@choksheak/react-utils 0.2.7 → 0.2.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +50 -2
  2. package/sharedQuery.cjs +146 -191
  3. package/sharedQuery.d.mts +72 -12
  4. package/sharedQuery.d.ts +69 -10
  5. package/sharedQuery.min.cjs +1 -1
  6. package/sharedQuery.min.cjs.map +1 -1
  7. package/sharedQuery.min.mjs +1 -1
  8. package/sharedQuery.min.mjs.map +1 -1
  9. package/sharedQuery.mjs +151 -191
  10. package/sharedState.cjs +50 -103
  11. package/sharedState.d.mts +12 -7
  12. package/sharedState.d.ts +10 -6
  13. package/sharedState.min.cjs +1 -1
  14. package/sharedState.min.cjs.map +1 -1
  15. package/sharedState.min.mjs +1 -1
  16. package/sharedState.min.mjs.map +1 -1
  17. package/sharedState.mjs +48 -102
  18. package/storage.cjs +67 -0
  19. package/storage.d.mts +19 -0
  20. package/storage.d.ts +16 -0
  21. package/storage.min.cjs +2 -0
  22. package/storage.min.cjs.map +1 -0
  23. package/storage.min.mjs +2 -0
  24. package/storage.min.mjs.map +1 -0
  25. package/storage.mjs +42 -0
  26. package/{utils/stringify.cjs → stringify.cjs} +1 -1
  27. package/stringify.min.cjs.map +1 -0
  28. package/stringify.min.mjs.map +1 -0
  29. package/{utils/stringify.mjs → stringify.mjs} +1 -1
  30. package/{utils/useDeepMemo.cjs → useDeepMemo.cjs} +1 -1
  31. package/useDeepMemo.d.mts +7 -0
  32. package/useDeepMemo.d.ts +5 -0
  33. package/useDeepMemo.min.cjs.map +1 -0
  34. package/useDeepMemo.min.mjs.map +1 -0
  35. package/{utils/useDeepMemo.mjs → useDeepMemo.mjs} +1 -1
  36. package/utils/storage.cjs +0 -162
  37. package/utils/storage.d.mts +0 -46
  38. package/utils/storage.d.ts +0 -44
  39. package/utils/storage.min.cjs +0 -2
  40. package/utils/storage.min.cjs.map +0 -1
  41. package/utils/storage.min.mjs +0 -2
  42. package/utils/storage.min.mjs.map +0 -1
  43. package/utils/storage.mjs +0 -134
  44. package/utils/stringify.min.cjs.map +0 -1
  45. package/utils/stringify.min.mjs.map +0 -1
  46. package/utils/useDeepMemo.d.mts +0 -4
  47. package/utils/useDeepMemo.d.ts +0 -2
  48. package/utils/useDeepMemo.min.cjs.map +0 -1
  49. package/utils/useDeepMemo.min.mjs.map +0 -1
  50. /package/{utils/stringify.d.mts → stringify.d.mts} +0 -0
  51. /package/{utils/stringify.d.ts → stringify.d.ts} +0 -0
  52. /package/{utils/stringify.min.cjs → stringify.min.cjs} +0 -0
  53. /package/{utils/stringify.min.mjs → stringify.min.mjs} +0 -0
  54. /package/{utils/useDeepMemo.min.cjs → useDeepMemo.min.cjs} +0 -0
  55. /package/{utils/useDeepMemo.min.mjs → useDeepMemo.min.mjs} +0 -0
package/sharedState.mjs CHANGED
@@ -2,108 +2,48 @@
2
2
  import { MS_PER_DAY } from "@choksheak/ts-utils/timeConstants";
3
3
  import { useSyncExternalStore } from "react";
4
4
 
5
- // src/utils/storage.ts
5
+ // src/storage.ts
6
6
  import { kvStore } from "@choksheak/ts-utils/kvStore";
7
+ import { LocalStore } from "@choksheak/ts-utils/localStore";
7
8
  function getStorageAdapter(options, defaultStoreExpiryMs) {
8
- const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};
9
- if (store) {
10
- return store;
11
- }
12
- const expiryMs = storeExpiryMs || defaultStoreExpiryMs;
13
- if (localStorageKey) {
14
- return new LocalStorageAdapter(localStorageKey, expiryMs);
15
- }
16
- if (indexedDbKey) {
17
- return new IndexedDbAdapter(indexedDbKey, expiryMs);
18
- }
19
- return null;
20
- }
21
- var LocalStorageAdapter = class {
22
- constructor(keyPrefix, expiryMs) {
23
- this.keyPrefix = keyPrefix;
24
- this.expiryMs = expiryMs;
25
- }
26
- save(key, value) {
27
- if (typeof window === "undefined") return;
28
- const fullKey = this.keyPrefix + ":" + key;
29
- window.localStorage.setItem(
30
- fullKey,
31
- JSON.stringify({
32
- value,
33
- expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0
34
- })
35
- );
36
- }
37
- load(key) {
38
- if (typeof window === "undefined") return void 0;
39
- const fullKey = this.keyPrefix + ":" + key;
40
- const raw = window.localStorage.getItem(fullKey);
41
- if (!raw) return void 0;
42
- try {
43
- const box = JSON.parse(raw);
44
- if (!box || box.expiresAt && Date.now() >= box.expiresAt) {
45
- window.localStorage.removeItem(fullKey);
46
- return void 0;
47
- }
48
- return box.value;
49
- } catch {
50
- window.localStorage.removeItem(fullKey);
51
- return void 0;
52
- }
53
- }
54
- delete(key) {
55
- if (typeof window === "undefined") return;
56
- const fullKey = this.keyPrefix + ":" + key;
57
- window.localStorage.removeItem(fullKey);
58
- }
59
- clear() {
60
- if (typeof window === "undefined") return;
61
- for (const key of Object.keys(window.localStorage)) {
62
- if (key.startsWith(this.keyPrefix)) {
63
- window.localStorage.removeItem(key);
9
+ const { store } = options ?? {};
10
+ if (!store) {
11
+ return null;
12
+ }
13
+ if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
14
+ const expiryMs = store.expiryMs || defaultStoreExpiryMs;
15
+ switch (store.persistTo) {
16
+ case "localStorage":
17
+ return new LocalStore(store.key, {
18
+ defaultExpiryMs: expiryMs
19
+ }).asStorageAdapter();
20
+ case "indexedDb": {
21
+ const keyPrefix = store.key + ":";
22
+ return {
23
+ set: async (key, value) => {
24
+ await kvStore.set(keyPrefix + key, value, expiryMs);
25
+ },
26
+ get: async (key) => {
27
+ return await kvStore.get(keyPrefix + key);
28
+ },
29
+ delete: async (key) => {
30
+ await kvStore.delete(keyPrefix + key);
31
+ },
32
+ clear: async () => {
33
+ await kvStore.clear();
34
+ }
35
+ };
64
36
  }
37
+ default:
38
+ store.persistTo;
39
+ throw new Error(`Unknown store.adapter ${store.persistTo}`);
65
40
  }
66
41
  }
67
- };
68
- var IndexedDbAdapter = class {
69
- constructor(keyPrefix, expiryMs) {
70
- this.keyPrefix = keyPrefix;
71
- this.expiryMs = expiryMs;
72
- }
73
- async save(key, value) {
74
- if (typeof window === "undefined") return;
75
- const fullKey = this.keyPrefix + ":" + key;
76
- await kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);
77
- }
78
- async load(key) {
79
- if (typeof window === "undefined") return void 0;
80
- const fullKey = this.keyPrefix + ":" + key;
81
- const raw = await kvStore.get(fullKey);
82
- if (raw === void 0) return void 0;
83
- try {
84
- return JSON.parse(raw);
85
- } catch {
86
- await kvStore.delete(fullKey);
87
- return void 0;
88
- }
89
- }
90
- async delete(key) {
91
- if (typeof window === "undefined") return;
92
- const fullKey = this.keyPrefix + ":" + key;
93
- await kvStore.delete(fullKey);
94
- }
95
- async clear() {
96
- if (typeof window === "undefined") return;
97
- await kvStore.forEach(async (k) => {
98
- if (k.startsWith(this.keyPrefix)) {
99
- await kvStore.delete(k);
100
- }
101
- });
102
- }
103
- };
42
+ return store;
43
+ }
104
44
 
105
45
  // src/sharedState.ts
106
- var SharedStateDefaults = {
46
+ var SharedStateConfig = {
107
47
  /**
108
48
  * Default duration for storage expiration in milliseconds. Initial value
109
49
  * is 30 days, but can be changed to anything.
@@ -115,6 +55,9 @@ var SharedStateDefaults = {
115
55
  */
116
56
  lazyLoad: false
117
57
  };
58
+ function configureSharedState(config) {
59
+ Object.assign(SharedStateConfig, config);
60
+ }
118
61
  var PubSubStore = class {
119
62
  dataByKey = /* @__PURE__ */ new Map();
120
63
  subscribersByKey = /* @__PURE__ */ new Map();
@@ -170,12 +113,14 @@ var SharedState = class {
170
113
  this.pubSubKey = String(stateKey++);
171
114
  this.storageAdapter = getStorageAdapter(
172
115
  options,
173
- SharedStateDefaults.storeExpiryMs
116
+ SharedStateConfig.storeExpiryMs
174
117
  );
175
- this.setValueBounded = (arg) => this.setValue(arg);
118
+ this.setValueBounded = (next) => {
119
+ this.setValue(next);
120
+ };
176
121
  pubSubStore.setNoNotify(this.pubSubKey, defaultValue);
177
122
  const lazyLoad = options?.lazyLoad;
178
- const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateDefaults.lazyLoad;
123
+ const lazy = lazyLoad !== void 0 ? lazyLoad : SharedStateConfig.lazyLoad;
179
124
  if (!lazy) {
180
125
  void this.initDefaultValueOnce();
181
126
  }
@@ -200,19 +145,19 @@ var SharedState = class {
200
145
  next = next(prev);
201
146
  }
202
147
  pubSubStore.set(this.pubSubKey, next);
203
- void this.storageAdapter?.save(STORAGE_KEY, next);
148
+ void this.storageAdapter?.set(STORAGE_KEY, next);
204
149
  }
205
150
  // Remove the value of the shared state. Actually this just sets the value
206
151
  // back to the given default value.
207
152
  delete() {
208
153
  pubSubStore.set(this.pubSubKey, this.defaultValue);
209
- void this.storageAdapter?.save(STORAGE_KEY, this.defaultValue);
154
+ void this.storageAdapter?.set(STORAGE_KEY, this.defaultValue);
210
155
  }
211
156
  // Initial default handling
212
157
  async initDefaultValueOnce() {
213
158
  if (this.initDone) return;
214
159
  this.initDone = true;
215
- const v = await this.storageAdapter?.load(STORAGE_KEY);
160
+ const v = await this.storageAdapter?.get(STORAGE_KEY);
216
161
  pubSubStore.set(this.pubSubKey, v !== void 0 ? v : this.defaultValue);
217
162
  }
218
163
  };
@@ -237,7 +182,8 @@ function useSharedStateSetter(state) {
237
182
  }
238
183
  export {
239
184
  SharedState,
240
- SharedStateDefaults,
185
+ SharedStateConfig,
186
+ configureSharedState,
241
187
  sharedState,
242
188
  useSharedState,
243
189
  useSharedStateSetter,
package/storage.cjs ADDED
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/storage.ts
21
+ var storage_exports = {};
22
+ __export(storage_exports, {
23
+ getStorageAdapter: () => getStorageAdapter
24
+ });
25
+ module.exports = __toCommonJS(storage_exports);
26
+ var import_kvStore = require("@choksheak/ts-utils/kvStore");
27
+ var import_localStore = require("@choksheak/ts-utils/localStore");
28
+ function getStorageAdapter(options, defaultStoreExpiryMs) {
29
+ const { store } = options ?? {};
30
+ if (!store) {
31
+ return null;
32
+ }
33
+ if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
34
+ const expiryMs = store.expiryMs || defaultStoreExpiryMs;
35
+ switch (store.persistTo) {
36
+ case "localStorage":
37
+ return new import_localStore.LocalStore(store.key, {
38
+ defaultExpiryMs: expiryMs
39
+ }).asStorageAdapter();
40
+ case "indexedDb": {
41
+ const keyPrefix = store.key + ":";
42
+ return {
43
+ set: async (key, value) => {
44
+ await import_kvStore.kvStore.set(keyPrefix + key, value, expiryMs);
45
+ },
46
+ get: async (key) => {
47
+ return await import_kvStore.kvStore.get(keyPrefix + key);
48
+ },
49
+ delete: async (key) => {
50
+ await import_kvStore.kvStore.delete(keyPrefix + key);
51
+ },
52
+ clear: async () => {
53
+ await import_kvStore.kvStore.clear();
54
+ }
55
+ };
56
+ }
57
+ default:
58
+ store.persistTo;
59
+ throw new Error(`Unknown store.adapter ${store.persistTo}`);
60
+ }
61
+ }
62
+ return store;
63
+ }
64
+ // Annotate the CommonJS export names for ESM import in node:
65
+ 0 && (module.exports = {
66
+ getStorageAdapter
67
+ });
package/storage.d.mts ADDED
@@ -0,0 +1,19 @@
1
+ import { StorageAdapter } from '@choksheak/ts-utils/storageAdapter';
2
+
3
+ /** List of all available pre-built persistence options. */
4
+ type PersistTo = "localStorage" | "indexedDb";
5
+ type StoreOptions = {
6
+ persistTo: PersistTo;
7
+ key: string;
8
+ expiryMs?: number;
9
+ };
10
+ type StorageOptions<T> = {
11
+ /**
12
+ * You can either specify the storage adapter directly to use a custom
13
+ * store, or specify the properties to use the pre-built ones.
14
+ */
15
+ store?: StorageAdapter<T> | StoreOptions;
16
+ };
17
+ declare function getStorageAdapter<T>(options: StorageOptions<T> | undefined, defaultStoreExpiryMs: number): StorageAdapter<T> | null;
18
+
19
+ export { type PersistTo, type StorageOptions, type StoreOptions, getStorageAdapter };
package/storage.d.ts ADDED
@@ -0,0 +1,16 @@
1
+ import { StorageAdapter } from "@choksheak/ts-utils/storageAdapter";
2
+ /** List of all available pre-built persistence options. */
3
+ export type PersistTo = "localStorage" | "indexedDb";
4
+ export type StoreOptions = {
5
+ persistTo: PersistTo;
6
+ key: string;
7
+ expiryMs?: number;
8
+ };
9
+ export type StorageOptions<T> = {
10
+ /**
11
+ * You can either specify the storage adapter directly to use a custom
12
+ * store, or specify the properties to use the pre-built ones.
13
+ */
14
+ store?: StorageAdapter<T> | StoreOptions;
15
+ };
16
+ export declare function getStorageAdapter<T>(options: StorageOptions<T> | undefined, defaultStoreExpiryMs: number): StorageAdapter<T> | null;
@@ -0,0 +1,2 @@
1
+ "use strict";var n=Object.defineProperty;var g=Object.getOwnPropertyDescriptor;var y=Object.getOwnPropertyNames;var T=Object.prototype.hasOwnProperty;var c=(r,t)=>{for(var e in t)n(r,e,{get:t[e],enumerable:!0})},l=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of y(t))!T.call(r,o)&&o!==e&&n(r,o,{get:()=>t[o],enumerable:!(s=g(t,o))||s.enumerable});return r};var f=r=>l(n({},"__esModule",{value:!0}),r);var S={};c(S,{getStorageAdapter:()=>u});module.exports=f(S);var a=require("@choksheak/ts-utils/kvStore"),p=require("@choksheak/ts-utils/localStore");function u(r,t){let{store:e}=r??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let s=e.expiryMs||t;switch(e.persistTo){case"localStorage":return new p.LocalStore(e.key,{defaultExpiryMs:s}).asStorageAdapter();case"indexedDb":{let o=e.key+":";return{set:async(i,d)=>{await a.kvStore.set(o+i,d,s)},get:async i=>await a.kvStore.get(o+i),delete:async i=>{await a.kvStore.delete(o+i)},clear:async()=>{await a.kvStore.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}0&&(module.exports={getStorageAdapter});
2
+ //# sourceMappingURL=storage.min.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } 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\nexport type StoreOptions = {\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;\n};\n\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\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\n switch (store.persistTo) {\n case \"localStorage\":\n return new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n }).asStorageAdapter<T>();\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.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 // 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 return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n await kvStore.clear();\n },\n };\n }\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"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,uBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAwB,uCACxBC,EAA2B,0CAwBpB,SAASH,EACdI,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eACH,OAAO,IAAI,aAAWA,EAAM,IAAK,CAC/B,gBAAiBC,CACnB,CAAC,EAAE,iBAAoB,EAEzB,IAAK,YAAa,CAEhB,IAAMC,EAAYF,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAEnD,MAAM,UAAQ,IAAIF,EAAYC,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GACH,MAAM,UAAQ,IAAID,EAAYC,CAAG,EAE1C,OAAQ,MAAOA,GAA+B,CAC5C,MAAM,UAAQ,OAAOD,EAAYC,CAAG,CACtC,EACA,MAAO,SAA2B,CAChC,MAAM,UAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAH,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["storage_exports","__export","getStorageAdapter","__toCommonJS","import_kvStore","import_localStore","options","defaultStoreExpiryMs","store","expiryMs","keyPrefix","key","value"]}
@@ -0,0 +1,2 @@
1
+ import{kvStore as r}from"@choksheak/ts-utils/kvStore";import{LocalStore as p}from"@choksheak/ts-utils/localStore";function y(i,a){let{store:e}=i??{};if(!e)return null;if("persistTo"in e&&typeof e.persistTo=="string"&&"key"in e&&typeof e.key=="string"){let s=e.expiryMs||a;switch(e.persistTo){case"localStorage":return new p(e.key,{defaultExpiryMs:s}).asStorageAdapter();case"indexedDb":{let o=e.key+":";return{set:async(t,n)=>{await r.set(o+t,n,s)},get:async t=>await r.get(o+t),delete:async t=>{await r.delete(o+t)},clear:async()=>{await r.clear()}}}default:throw e.persistTo,new Error(`Unknown store.adapter ${e.persistTo}`)}}return e}export{y as getStorageAdapter};
2
+ //# sourceMappingURL=storage.min.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/storage.ts"],"sourcesContent":["import { kvStore } from \"@choksheak/ts-utils/kvStore\";\nimport { LocalStore } 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\nexport type StoreOptions = {\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;\n};\n\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\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\n switch (store.persistTo) {\n case \"localStorage\":\n return new LocalStore(store.key, {\n defaultExpiryMs: expiryMs,\n }).asStorageAdapter<T>();\n\n case \"indexedDb\": {\n // Use the key prefix as a unique namespace for this store.\n const keyPrefix = store.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 // 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 return await kvStore.get(keyPrefix + key);\n },\n delete: async (key: string): Promise<void> => {\n await kvStore.delete(keyPrefix + key);\n },\n clear: async (): Promise<void> => {\n await kvStore.clear();\n },\n };\n }\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"],"mappings":"AAAA,OAAS,WAAAA,MAAe,8BACxB,OAAS,cAAAC,MAAkB,iCAwBpB,SAASC,EACdC,EACAC,EAC0B,CAC1B,GAAM,CAAE,MAAAC,CAAM,EAAIF,GAAW,CAAC,EAE9B,GAAI,CAACE,EACH,OAAO,KAGT,GACE,cAAeA,GACf,OAAOA,EAAM,WAAc,UAC3B,QAASA,GACT,OAAOA,EAAM,KAAQ,SACrB,CACA,IAAMC,EAAWD,EAAM,UAAYD,EAEnC,OAAQC,EAAM,UAAW,CACvB,IAAK,eACH,OAAO,IAAIJ,EAAWI,EAAM,IAAK,CAC/B,gBAAiBC,CACnB,CAAC,EAAE,iBAAoB,EAEzB,IAAK,YAAa,CAEhB,IAAMC,EAAYF,EAAM,IAAM,IAK9B,MAAO,CACL,IAAK,MAAOG,EAAaC,IAA4B,CAEnD,MAAMT,EAAQ,IAAIO,EAAYC,EAAKC,EAAOH,CAAQ,CACpD,EACA,IAAK,MAAOE,GACH,MAAMR,EAAQ,IAAIO,EAAYC,CAAG,EAE1C,OAAQ,MAAOA,GAA+B,CAC5C,MAAMR,EAAQ,OAAOO,EAAYC,CAAG,CACtC,EACA,MAAO,SAA2B,CAChC,MAAMR,EAAQ,MAAM,CACtB,CACF,CACF,CAEA,QACE,MAAAK,EAAM,UACA,IAAI,MAAM,yBAAyBA,EAAM,SAAS,EAAE,CAC9D,CACF,CAEA,OAAOA,CACT","names":["kvStore","LocalStore","getStorageAdapter","options","defaultStoreExpiryMs","store","expiryMs","keyPrefix","key","value"]}
package/storage.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // src/storage.ts
2
+ import { kvStore } from "@choksheak/ts-utils/kvStore";
3
+ import { LocalStore } from "@choksheak/ts-utils/localStore";
4
+ function getStorageAdapter(options, defaultStoreExpiryMs) {
5
+ const { store } = options ?? {};
6
+ if (!store) {
7
+ return null;
8
+ }
9
+ if ("persistTo" in store && typeof store.persistTo === "string" && "key" in store && typeof store.key === "string") {
10
+ const expiryMs = store.expiryMs || defaultStoreExpiryMs;
11
+ switch (store.persistTo) {
12
+ case "localStorage":
13
+ return new LocalStore(store.key, {
14
+ defaultExpiryMs: expiryMs
15
+ }).asStorageAdapter();
16
+ case "indexedDb": {
17
+ const keyPrefix = store.key + ":";
18
+ return {
19
+ set: async (key, value) => {
20
+ await kvStore.set(keyPrefix + key, value, expiryMs);
21
+ },
22
+ get: async (key) => {
23
+ return await kvStore.get(keyPrefix + key);
24
+ },
25
+ delete: async (key) => {
26
+ await kvStore.delete(keyPrefix + key);
27
+ },
28
+ clear: async () => {
29
+ await kvStore.clear();
30
+ }
31
+ };
32
+ }
33
+ default:
34
+ store.persistTo;
35
+ throw new Error(`Unknown store.adapter ${store.persistTo}`);
36
+ }
37
+ }
38
+ return store;
39
+ }
40
+ export {
41
+ getStorageAdapter
42
+ };
@@ -17,7 +17,7 @@ var __copyProps = (to, from, except, desc) => {
17
17
  };
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
- // src/utils/stringify.ts
20
+ // src/stringify.ts
21
21
  var stringify_exports = {};
22
22
  __export(stringify_exports, {
23
23
  stringifyDeterministicForKeys: () => stringifyDeterministicForKeys
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stringify.ts"],"sourcesContent":["/**\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"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,mCAAAE,IAAA,eAAAC,EAAAH,GASO,SAASE,EAA8BE,EAAyB,CACrE,IAAMC,EAAQ,IAAI,IAElB,OAAO,KAAK,UAAUD,EAAQ,CAACE,EAAGC,IAAU,CAC1C,GAAI,OAAOA,GAAU,WACnB,MAAM,IAAI,MAAM,sDAAsD,EAGxE,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAC5D,OAAOA,EAGT,GAAIF,EAAM,IAAIE,CAAK,EAEjB,MAAO,aAOT,GAJAF,EAAM,IAAIE,CAAK,EAIXA,IAAUH,EACZ,GAAI,CACF,KAAK,UAAUG,CAAK,CACtB,MAAQ,CACN,MAAO,kBACT,CAGF,OAAO,OAAO,KAAKA,CAAK,EACrB,KAAK,EACL,OACC,CAACC,EAAiCC,KAChCD,EAAOC,CAAG,EAAIF,EAAME,CAAG,EAChBD,GAET,CAAC,CACH,CACJ,CAAC,CACH","names":["stringify_exports","__export","stringifyDeterministicForKeys","__toCommonJS","params","cache","_","value","result","key"]}
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/stringify.ts"],"sourcesContent":["/**\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"],"mappings":"AASO,SAASA,EAA8BC,EAAyB,CACrE,IAAMC,EAAQ,IAAI,IAElB,OAAO,KAAK,UAAUD,EAAQ,CAACE,EAAGC,IAAU,CAC1C,GAAI,OAAOA,GAAU,WACnB,MAAM,IAAI,MAAM,sDAAsD,EAGxE,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAC5D,OAAOA,EAGT,GAAIF,EAAM,IAAIE,CAAK,EAEjB,MAAO,aAOT,GAJAF,EAAM,IAAIE,CAAK,EAIXA,IAAUH,EACZ,GAAI,CACF,KAAK,UAAUG,CAAK,CACtB,MAAQ,CACN,MAAO,kBACT,CAGF,OAAO,OAAO,KAAKA,CAAK,EACrB,KAAK,EACL,OACC,CAACC,EAAiCC,KAChCD,EAAOC,CAAG,EAAIF,EAAME,CAAG,EAChBD,GAET,CAAC,CACH,CACJ,CAAC,CACH","names":["stringifyDeterministicForKeys","params","cache","_","value","result","key"]}
@@ -1,4 +1,4 @@
1
- // src/utils/stringify.ts
1
+ // src/stringify.ts
2
2
  function stringifyDeterministicForKeys(params) {
3
3
  const cache = /* @__PURE__ */ new Set();
4
4
  return JSON.stringify(params, (_, value) => {
@@ -27,7 +27,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
27
27
  ));
28
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
29
 
30
- // src/utils/useDeepMemo.ts
30
+ // src/useDeepMemo.ts
31
31
  var useDeepMemo_exports = {};
32
32
  __export(useDeepMemo_exports, {
33
33
  useDeepMemo: () => useDeepMemo
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Provides a stable value for T based on deep equality. The deep equality is
3
+ * determined by the `isEqual()` function in lodash.
4
+ */
5
+ declare function useDeepMemo<T>(value: T): T;
6
+
7
+ export { useDeepMemo };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Provides a stable value for T based on deep equality. The deep equality is
3
+ * determined by the `isEqual()` function in lodash.
4
+ */
5
+ export declare function useDeepMemo<T>(value: T): T;
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/useDeepMemo.ts"],"sourcesContent":["import isEqual from \"lodash/isEqual\";\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 (state === value || 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"],"mappings":"0jBAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,iBAAAE,IAAA,eAAAC,EAAAH,GAAA,IAAAI,EAAoB,6BACpBC,EAAkC,iBAM3B,SAASH,EAAeI,EAAa,CAC1C,GAAM,CAACC,EAAOC,CAAQ,KAAI,YAAYF,CAAK,EAE3C,SAAO,WAAQ,IACTC,IAAUD,MAAS,EAAAG,SAAQF,EAAOD,CAAK,EAClCC,GAKTC,EAASF,CAAK,EAEPA,GACN,CAACC,EAAOD,CAAK,CAAC,CACnB","names":["useDeepMemo_exports","__export","useDeepMemo","__toCommonJS","import_isEqual","import_react","value","state","setState","isEqual"]}
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/useDeepMemo.ts"],"sourcesContent":["import isEqual from \"lodash/isEqual\";\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 (state === value || 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"],"mappings":"AAAA,OAAOA,MAAa,iBACpB,OAAS,WAAAC,EAAS,YAAAC,MAAgB,QAM3B,SAASC,EAAeC,EAAa,CAC1C,GAAM,CAACC,EAAOC,CAAQ,EAAIJ,EAAYE,CAAK,EAE3C,OAAOH,EAAQ,IACTI,IAAUD,GAASJ,EAAQK,EAAOD,CAAK,EAClCC,GAKTC,EAASF,CAAK,EAEPA,GACN,CAACC,EAAOD,CAAK,CAAC,CACnB","names":["isEqual","useMemo","useState","useDeepMemo","value","state","setState"]}
@@ -1,4 +1,4 @@
1
- // src/utils/useDeepMemo.ts
1
+ // src/useDeepMemo.ts
2
2
  import isEqual from "lodash/isEqual";
3
3
  import { useMemo, useState } from "react";
4
4
  function useDeepMemo(value) {
package/utils/storage.cjs DELETED
@@ -1,162 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/utils/storage.ts
21
- var storage_exports = {};
22
- __export(storage_exports, {
23
- InMemoryStorageAdapter: () => InMemoryStorageAdapter,
24
- IndexedDbAdapter: () => IndexedDbAdapter,
25
- LocalStorageAdapter: () => LocalStorageAdapter,
26
- getStorageAdapter: () => getStorageAdapter
27
- });
28
- module.exports = __toCommonJS(storage_exports);
29
- var import_kvStore = require("@choksheak/ts-utils/kvStore");
30
- function getStorageAdapter(options, defaultStoreExpiryMs) {
31
- const { localStorageKey, indexedDbKey, storeExpiryMs, store } = options ?? {};
32
- if (store) {
33
- return store;
34
- }
35
- const expiryMs = storeExpiryMs || defaultStoreExpiryMs;
36
- if (localStorageKey) {
37
- return new LocalStorageAdapter(localStorageKey, expiryMs);
38
- }
39
- if (indexedDbKey) {
40
- return new IndexedDbAdapter(indexedDbKey, expiryMs);
41
- }
42
- return null;
43
- }
44
- var InMemoryStorageAdapter = class {
45
- constructor(keyPrefix, expiryMs) {
46
- this.keyPrefix = keyPrefix;
47
- this.expiryMs = expiryMs;
48
- }
49
- cache = /* @__PURE__ */ new Map();
50
- save(key, value) {
51
- const fullKey = this.keyPrefix + ":" + key;
52
- this.cache.set(fullKey, {
53
- value,
54
- expiresAt: Date.now() + this.expiryMs
55
- });
56
- }
57
- load(key) {
58
- const fullKey = this.keyPrefix + ":" + key;
59
- const cached = this.cache.get(fullKey);
60
- if (cached && Date.now() < cached.expiresAt) {
61
- return cached.value;
62
- }
63
- return void 0;
64
- }
65
- delete(key) {
66
- const fullKey = this.keyPrefix + ":" + key;
67
- this.cache.delete(fullKey);
68
- }
69
- clear() {
70
- this.cache.clear();
71
- }
72
- };
73
- var LocalStorageAdapter = class {
74
- constructor(keyPrefix, expiryMs) {
75
- this.keyPrefix = keyPrefix;
76
- this.expiryMs = expiryMs;
77
- }
78
- save(key, value) {
79
- if (typeof window === "undefined") return;
80
- const fullKey = this.keyPrefix + ":" + key;
81
- window.localStorage.setItem(
82
- fullKey,
83
- JSON.stringify({
84
- value,
85
- expiresAt: this.expiryMs ? Date.now() + this.expiryMs : 0
86
- })
87
- );
88
- }
89
- load(key) {
90
- if (typeof window === "undefined") return void 0;
91
- const fullKey = this.keyPrefix + ":" + key;
92
- const raw = window.localStorage.getItem(fullKey);
93
- if (!raw) return void 0;
94
- try {
95
- const box = JSON.parse(raw);
96
- if (!box || box.expiresAt && Date.now() >= box.expiresAt) {
97
- window.localStorage.removeItem(fullKey);
98
- return void 0;
99
- }
100
- return box.value;
101
- } catch {
102
- window.localStorage.removeItem(fullKey);
103
- return void 0;
104
- }
105
- }
106
- delete(key) {
107
- if (typeof window === "undefined") return;
108
- const fullKey = this.keyPrefix + ":" + key;
109
- window.localStorage.removeItem(fullKey);
110
- }
111
- clear() {
112
- if (typeof window === "undefined") return;
113
- for (const key of Object.keys(window.localStorage)) {
114
- if (key.startsWith(this.keyPrefix)) {
115
- window.localStorage.removeItem(key);
116
- }
117
- }
118
- }
119
- };
120
- var IndexedDbAdapter = class {
121
- constructor(keyPrefix, expiryMs) {
122
- this.keyPrefix = keyPrefix;
123
- this.expiryMs = expiryMs;
124
- }
125
- async save(key, value) {
126
- if (typeof window === "undefined") return;
127
- const fullKey = this.keyPrefix + ":" + key;
128
- await import_kvStore.kvStore.set(fullKey, JSON.stringify(value), this.expiryMs);
129
- }
130
- async load(key) {
131
- if (typeof window === "undefined") return void 0;
132
- const fullKey = this.keyPrefix + ":" + key;
133
- const raw = await import_kvStore.kvStore.get(fullKey);
134
- if (raw === void 0) return void 0;
135
- try {
136
- return JSON.parse(raw);
137
- } catch {
138
- await import_kvStore.kvStore.delete(fullKey);
139
- return void 0;
140
- }
141
- }
142
- async delete(key) {
143
- if (typeof window === "undefined") return;
144
- const fullKey = this.keyPrefix + ":" + key;
145
- await import_kvStore.kvStore.delete(fullKey);
146
- }
147
- async clear() {
148
- if (typeof window === "undefined") return;
149
- await import_kvStore.kvStore.forEach(async (k) => {
150
- if (k.startsWith(this.keyPrefix)) {
151
- await import_kvStore.kvStore.delete(k);
152
- }
153
- });
154
- }
155
- };
156
- // Annotate the CommonJS export names for ESM import in node:
157
- 0 && (module.exports = {
158
- InMemoryStorageAdapter,
159
- IndexedDbAdapter,
160
- LocalStorageAdapter,
161
- getStorageAdapter
162
- });