stunk 2.3.0 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{core/core.d.ts → core-C7jFiHdO.d.ts} +5 -9
- package/dist/index.cjs +2 -1
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +171 -0
- package/dist/index.d.ts +171 -7
- package/dist/index.js +2 -6
- package/dist/index.js.map +1 -0
- package/dist/middleware/index.d.ts +45 -4
- package/dist/middleware/index.js +2 -6
- package/dist/middleware/index.js.map +1 -0
- package/dist/use-react/index.d.ts +82 -7
- package/dist/use-react/index.js +2 -7
- package/dist/use-react/index.js.map +1 -0
- package/package.json +25 -21
- package/dist/core/asyncChunk.d.ts +0 -28
- package/dist/core/asyncChunk.js +0 -50
- package/dist/core/computed.d.ts +0 -15
- package/dist/core/computed.js +0 -58
- package/dist/core/core.js +0 -102
- package/dist/core/selector.d.ts +0 -17
- package/dist/core/selector.js +0 -45
- package/dist/core/types.d.ts +0 -16
- package/dist/core/types.js +0 -1
- package/dist/middleware/history.d.ts +0 -30
- package/dist/middleware/history.js +0 -68
- package/dist/middleware/logger.d.ts +0 -2
- package/dist/middleware/logger.js +0 -4
- package/dist/middleware/persistence.d.ts +0 -8
- package/dist/middleware/persistence.js +0 -25
- package/dist/middleware/validator.d.ts +0 -2
- package/dist/middleware/validator.js +0 -6
- package/dist/use-react/hooks/useAsyncChunk.d.ts +0 -14
- package/dist/use-react/hooks/useAsyncChunk.js +0 -27
- package/dist/use-react/hooks/useChunk.d.ts +0 -6
- package/dist/use-react/hooks/useChunk.js +0 -26
- package/dist/use-react/hooks/useChunkProperty.d.ts +0 -6
- package/dist/use-react/hooks/useChunkProperty.js +0 -10
- package/dist/use-react/hooks/useChunkValue.d.ts +0 -6
- package/dist/use-react/hooks/useChunkValue.js +0 -9
- package/dist/use-react/hooks/useChunkValues.d.ts +0 -8
- package/dist/use-react/hooks/useChunkValues.js +0 -25
- package/dist/use-react/hooks/useComputed.d.ts +0 -7
- package/dist/use-react/hooks/useComputed.js +0 -22
- package/dist/use-react/hooks/useDerive.d.ts +0 -6
- package/dist/use-react/hooks/useDerive.js +0 -17
- package/dist/utils.d.ts +0 -15
- package/dist/utils.js +0 -113
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
type Subscriber<T> = (newValue: T) => void;
|
|
2
|
+
type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
|
|
3
|
+
interface Chunk<T> {
|
|
4
4
|
/** Get the current value of the chunk. */
|
|
5
5
|
get: () => T;
|
|
6
6
|
/** Set a new value for the chunk & Update existing value efficiently. */
|
|
@@ -14,9 +14,5 @@ export interface Chunk<T> {
|
|
|
14
14
|
/** Destroy the chunk and all its subscribers. */
|
|
15
15
|
destroy: () => void;
|
|
16
16
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
* Useful for updating multiple chunks at once without causing multiple re-renders.
|
|
20
|
-
*/
|
|
21
|
-
export declare function batch(callback: () => void): void;
|
|
22
|
-
export declare function chunk<T>(initialValue: T, middleware?: Middleware<T>[]): Chunk<T>;
|
|
17
|
+
|
|
18
|
+
export type { Chunk as C, Middleware as M };
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1,2 @@
|
|
|
1
|
-
|
|
1
|
+
'use strict';var N=Object.defineProperty;var z=(e,n)=>{for(var r in n)N(e,r,{get:n[r],enumerable:true});};function B(e){return e!=null}function W(e){if(!e||typeof e!="object")return false;let n=e;return ["get","set","update","subscribe","derive","reset","destroy"].every(t=>typeof n[t]=="function")}function J(e){let n=false,r;return ()=>(n||(r=e(),n=true),r)}function U(e){let n=Object.keys(e).reduce((c,s)=>(c[s]=null,c),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:n},t=p(r);Object.values(e);return Object.entries(e).forEach(([c,s])=>{s.subscribe(a=>{let f=t.get(),i=false,u=null,T={};Object.entries(e).forEach(([b,h])=>{let l=h.get();l.loading&&(i=true),l.error&&(u||(u=l.error),T[b]=l.error);}),t.set({loading:i,error:u,errors:T,data:{...f.data,[c]:a.data}});});}),t}function M(e,n){if(e==null)throw new Error("Value cannot be null or undefined.");let r=e,t=0;for(;t<n.length;){let o=n[t],c=typeof o=="function"?o:o.fn,s=typeof o=="function"?`index ${t}`:o.name||`index ${t}`,a=false,f=null;try{c(r,i=>{a=!0,f=i;});}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`Middleware "${s}" threw an error: ${u}`)}if(!a)break;if(f==null)throw new Error(`Middleware at index ${t} returned null or undefined value.`);r=f,t++;}return r}function E(e,n){if(e===n)return true;if(!e||!n||typeof e!=typeof n)return false;if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==n[r])return false;return true}if(typeof e=="object"&&typeof n=="object"){let r=Object.keys(e),t=Object.keys(n);if(r.length!==t.length)return false;for(let o of r)if(!Object.prototype.hasOwnProperty.call(n,o)||e[o]!==n[o])return false;return true}return false}function v(e,n,r=""){if(typeof e=="object"&&e!==null&&typeof n=="object"&&n!==null){if(Array.isArray(e)&&Array.isArray(n)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<n.length;t++)v(e[0],n[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(n)){let t=Object.keys(e),o=Object.keys(n),c=o.filter(s=>!t.includes(s));c.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${c.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",o));for(let s of t)v(e[s],n[s],r?`${r}.${s}`:s);}}}var S=false,P=new Set,V=new Map,L=0;function G(e){let n=S;S=true;try{e();}finally{if(!n){S=false;let r=Array.from(P);P.clear(),r.forEach(t=>{let o=V.get(t);o&&o.notify();});}}}function p(e,n=[]){if(e==null)throw new Error("Initial value cannot be undefined or null.");let r=e,t=new Set,o=L++,c=()=>{t.forEach(h=>h(r));};V.set(o,{notify:c});let s=()=>{t.size!==0&&(S?P.add(o):c());},a=()=>r,f=h=>{let l;typeof h=="function"?l=h(r):l=h,v(r,l);let y=M(l,n);y!==r&&(r=y,s());},i=h=>{if(typeof h!="function")throw new Error("Callback must be a function.");return t.add(h),h(r),()=>t.delete(h)};return {get:a,set:f,subscribe:i,derive:h=>{if(typeof h!="function")throw new Error("Derive function must be a function.");let l=h(r),y=p(l),m=i(()=>{let D=h(r);y.set(D);}),g=y.destroy;return y.destroy=()=>{m(),g();},y},reset:()=>{r=e,s();},destroy:()=>{t.clear(),r=e,P.delete(o),V.delete(o);}}}function Q(e,n={}){let {initialData:r=null,onError:t,retryCount:o=0,retryDelay:c=1e3,refresh:s={},enabled:a=true}=n,{staleTime:f=0,cacheTime:i=5*60*1e3,refetchInterval:u}=s,T=e.length>0,b={loading:a&&!T,error:null,data:r,lastFetched:void 0},h=d=>T?d===void 0?false:Array.isArray(d)?d.every(x=>x!=null):true:true,l=p(b),y,m=null,g=null,D=()=>{let d=l.get();return d.lastFetched?Date.now()-d.lastFetched>f:true},q=()=>{l.set({...l.get(),data:r,lastFetched:void 0});},K=()=>{g&&clearTimeout(g),i>0&&(g=setTimeout(q,i));},k=async(d,x=o,w=false)=>{if(a){if(d!==void 0&&(y=d),!h(y)){l.set({...l.get(),loading:false});return}if(!(!w&&!D()&&l.get().data!==null&&f>0)){l.set({...l.get(),loading:true,error:null});try{let C=T?await e(...y):await e(),A=Date.now();l.set({loading:!1,error:null,data:C,lastFetched:A}),K();}catch(C){if(x>0)return await new Promise(A=>setTimeout(A,c)),k(d,x-1,w);l.set({loading:false,error:C,data:l.get().data,lastFetched:l.get().lastFetched}),t&&t(C);}}}};u&&u>0&&a&&(m=setInterval(()=>{a&&k(y,0,false);},u)),a&&!T&&k();let j=()=>{m&&(clearInterval(m),m=null),g&&(clearTimeout(g),g=null);};return {...l,reload:async(...d)=>{await k(d.length>0?d:void 0,o,true);},refresh:async(...d)=>{await k(d.length>0?d:void 0,o,false);},mutate:d=>{let x=l.get(),w=d(x.data);l.set({...x,data:w});},reset:()=>{j(),l.set({...b,loading:a}),a&&(k(),u&&u>0&&(m=setInterval(()=>{a&&k(y,0,false);},u)));},cleanup:j,setParams:(...d)=>{y=d,a&&h(d)&&k(d);}}}function X(e,n){let r=e.map(i=>i.get()),t=n(...r),o=p(t),c=o.set,s=false,a=()=>{let i=false;for(let u=0;u<e.length;u++){let T=e[u].get();T!==r[u]&&(r[u]=T,i=true);}if(i){let u=n(...r);u!==t&&(typeof u!="object"||typeof t!="object"||!E(u,t))&&(t=u,c(u)),s=false;}},f=e.map(i=>i.subscribe(()=>{s=true,a();}));return {...o,get:()=>(s&&a(),t),recompute:a,isDirty:()=>s,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(i=>{typeof i.reset=="function"&&i.reset();}),s=true,a(),t),destroy:()=>{f.forEach(i=>i()),o.destroy?.();}}}function O(e,n,r={}){let{useShallowEqual:t=false}=r,o=e.get(),c=n(o),s=p(c),a=()=>{let i=e.get(),u=n(i);o=i,(t?!E(u,c):u!==c)&&(c=u,s.set(u));},f=e.subscribe(a);return {get:()=>s.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:s.subscribe,derive:i=>O(s,i,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{f(),s.destroy();}}}var $={};z($,{logger:()=>R,nonNegativeValidator:()=>I,withHistory:()=>F,withPersistence:()=>H});var R=(e,n)=>{console.log("Setting value:",e),n(e);};var I=(e,n)=>{if(e<0)throw new Error("Value must be non-negative!");n(e);};function F(e,n={}){let{maxHistory:r=100}=n,t=[e.get()],o=0,c=false,s={...e,set:a=>{if(c){e.set(a);return}let f;if(typeof a=="function"){let i=e.get();f=a(i);}else f=a;if(t.splice(o+1),t.push(f),t.length>r){console.warn("History limit reached. Removing oldest entries.");let i=t.length-r;t.splice(0,i),o=Math.max(0,o-i);}o=t.length-1,e.set(f);},undo:()=>{s.canUndo()&&(c=true,o--,s.set(t[o]),c=false);},redo:()=>{s.canRedo()&&(c=true,o++,s.set(t[o]),c=false);},canUndo:()=>o>0,canRedo:()=>o<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let a=e.get();t.length=0,t.push(a),o=0;},destroy:()=>{t.length=0,e.destroy();}};return s}function H(e,n){let{key:r,storage:t=localStorage,serialize:o=JSON.stringify,deserialize:c=JSON.parse}=n;try{let s=t.getItem(r);if(s){let a=c(s);e.set(a);}}catch(s){console.error("Failed to load persisted state:",s);}return e.subscribe(s=>{try{let a=o(s);t.setItem(r,a);}catch(a){console.log("Failed to persist chunk",a);}}),e}exports.asyncChunk=Q;exports.batch=G;exports.chunk=p;exports.combineAsyncChunks=U;exports.computed=X;exports.isChunk=W;exports.isValidChunkValue=B;exports.middleware=$;exports.once=J;exports.select=O;//# sourceMappingURL=index.cjs.map
|
|
2
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils.ts","../src/core/core.ts","../src/core/asyncChunk.ts","../src/core/computed.ts","../src/core/selector.ts","../src/middleware/index.ts","../src/middleware/logger.ts","../src/middleware/validator.ts","../src/middleware/history.ts","../src/middleware/persistence.ts"],"names":["isValidChunkValue","value","isChunk","chunk","method","once","fn","called","result","combineAsyncChunks","chunks","initialData","acc","key","initialState","combined","asyncChunk","state","currentState","hasLoading","firstError","allErrors","chunkKey","chunkState","processMiddleware","initialValue","middleware","currentValue","index","current","middlewareFn","middlewareName","nextCalled","nextValue","val","error","errorMessage","shallowEqual","a","b","i","keysA","keysB","validateObjectShape","original","updated","path","originalKeys","updatedKeys","extraKeys","isBatching","dirtyChunks","chunkRegistry","chunkIdCounter","batch","callback","wasBatchingBefore","id","subscribers","chunkId","notify","subscriber","notifySubscribers","get","set","newValueOrUpdater","newValue","processedValue","subscribe","initialDerivedValue","derivedChunk","unsubscribe","newDerivedValue","originalDestroy","fetcher","options","onError","retryCount","retryDelay","refreshConfig","enabled","staleTime","cacheTime","refetchInterval","expectsParams","hasValidParams","params","p","baseChunk","currentParams","intervalId","cacheTimeoutId","isStale","clearCache","setCacheTimeout","fetchData","retries","force","data","now","resolve","cleanup","mutator","newData","computed","dependencies","computeFn","dependencyValues","dep","cachedValue","computedChunk","originalSet","isDirty","recompute","hasChanges","unsubs","unsub","select","sourceChunk","selector","useShallowEqual","prevSourceValue","currentResult","update","newSourceValue","newResult","middleware_exports","__export","logger","nonNegativeValidator","withHistory","withPersistence","next","maxHistory","history","currentIndex","isHistoryAction","historyChunk","removeCount","storage","serialize","deserialize","savedChunk","parsed","serialized"],"mappings":"0GAKO,SAASA,CAAAA,CAAkBC,CAAyB,CAAA,CACzD,OAAOA,CAAAA,EAAU,IACnB,CAoBO,SAASC,CAAWD,CAAAA,CAAAA,CAAmC,CAC5D,GAAI,CAACA,CAAS,EAAA,OAAOA,CAAU,EAAA,QAAA,CAC7B,OAAO,MAAA,CAGT,IAAME,CAAQF,CAAAA,CAAAA,CAWd,OAVwB,CACtB,KACA,CAAA,KAAA,CACA,SACA,WACA,CAAA,QAAA,CACA,OACA,CAAA,SACF,CAEuB,CAAA,KAAA,CAAMG,GAC3B,OAAOD,CAAAA,CAAMC,CAAM,CAAA,EAAM,UAC3B,CACF,CAEO,SAASC,CAAAA,CAAQC,CAAsB,CAAA,CAC5C,IAAIC,CAAAA,CAAS,KACTC,CAAAA,CAAAA,CACJ,OAAO,KACAD,CACHC,GAAAA,CAAAA,CAASF,CAAG,EAAA,CACZC,EAAS,IAEJC,CAAAA,CAAAA,CAAAA,CAEX,CAEO,SAASC,CACdC,CAAAA,CAAAA,CACyB,CACnBC,IAAAA,CAAAA,CAAc,MAAO,CAAA,IAAA,CAAKD,CAAM,CAAA,CAAE,OAAO,CAACE,CAAAA,CAAKC,CACnDD,IAAAA,CAAAA,CAAIC,CAAc,CAAA,CAAI,KACfD,CACN,CAAA,CAAA,EAAqB,CAAA,CAElBE,CAA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U,KAC/B8C,CAAAA,CAAAA,CAAQ,MAAS,CAAA,CAAA,CACjBA,CAAQ,CAAA,IAAA,CAAK3G,CAAY,CACzB4G,CAAAA,CAAAA,CAAe,EACjB,CAAA,CAGA,OAAS,CAAA,IAAM,CACbD,CAAQ,CAAA,MAAA,CAAS,CACjB9C,CAAAA,CAAAA,CAAU,OAAQ,GACpB,CACF,CAEA,CAAA,OAAOiD,CAET,CCvGO,SAASN,CAAAA,CACd3C,EACAb,CACU,CAAA,CACV,GAAM,CACJ,GAAA9D,CAAAA,CAAAA,CACA,QAAA8H,CAAU,CAAA,YAAA,CACV,SAAAC,CAAAA,CAAAA,CAAY,IAAK,CAAA,SAAA,CACjB,WAAAC,CAAAA,CAAAA,CAAc,IAAK,CAAA,KACrB,CAAIlE,CAAAA,CAAAA,CAGJ,GAAI,CACF,IAAMmE,CAAaH,CAAAA,CAAAA,CAAQ,OAAQ9H,CAAAA,CAAG,CACtC,CAAA,GAAIiI,EAAY,CACd,IAAMC,CAASF,CAAAA,CAAAA,CAAYC,CAAU,CAAA,CACrCtD,EAAU,GAAIuD,CAAAA,CAAM,EACtB,CACF,CAAS5G,MAAAA,CAAAA,CAAO,CACd,OAAA,CAAQ,KAAM,CAAA,iCAAA,CAAmCA,CAAK,EACxD,CAGA,OAAAqD,EAAU,SAAWtB,CAAAA,CAAAA,EAAa,CAChC,GAAI,CACF,IAAM8E,EAAaJ,CAAU1E,CAAAA,CAAQ,CACrCyE,CAAAA,CAAAA,CAAQ,OAAQ9H,CAAAA,CAAAA,CAAKmI,CAAU,EAEjC,CAAA,MAAS7G,CAAO,CAAA,CACd,OAAQ,CAAA,GAAA,CAAI,yBAA2BA,CAAAA,CAAK,EAC9C,CACF,CAAC,CAAA,CAEMqD,CAET","file":"index.cjs","sourcesContent":["import { chunk, Chunk, Middleware } from \"./core/core\";\n\nimport { AsyncChunk } from \"./core/asyncChunk\";\nimport { CombinedData, CombinedState } from \"./core/types\";\n\nexport function isValidChunkValue(value: unknown): boolean {\n return value !== null && value !== undefined;\n}\n\nexport function isValidChunk<T>(value: unknown, validateBehavior = false): value is Chunk<T> {\n if (!isChunk(value)) {\n return false;\n }\n\n if (!validateBehavior) {\n return true;\n }\n\n try {\n const currentValue = value.get();\n value.set(currentValue);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function isChunk<T>(value: unknown): value is Chunk<T> {\n if (!value || typeof value !== 'object') {\n return false;\n }\n\n const chunk = value as Record<string, unknown>;\n const requiredMethods = [\n 'get',\n 'set',\n 'update',\n 'subscribe',\n 'derive',\n 'reset',\n 'destroy'\n ] as const;\n\n return requiredMethods.every(method =>\n typeof chunk[method] === 'function'\n );\n}\n\nexport function once<T>(fn: () => T): () => T {\n let called = false;\n let result: T;\n return () => {\n if (!called) {\n result = fn();\n called = true;\n }\n return result;\n };\n};\n\nexport function combineAsyncChunks<T extends Record<string, AsyncChunk<any>>>(\n chunks: T\n): Chunk<CombinedState<T>> {\n const initialData = Object.keys(chunks).reduce((acc, key) => {\n acc[key as keyof T] = null;\n return acc;\n }, {} as CombinedData<T>);\n\n const initialState: CombinedState<T> = {\n loading: Object.keys(chunks).length > 0,\n error: null,\n errors: {},\n data: initialData\n };\n\n const combined = chunk(initialState);\n\n const chunkValues = Object.values(chunks);\n\n Object.entries(chunks).forEach(([key, asyncChunk]) => {\n asyncChunk.subscribe((state) => {\n const currentState = combined.get();\n\n let hasLoading = false;\n let firstError: Error | null = null;\n const allErrors: Partial<{ [K in keyof T]: Error }> = {};\n\n Object.entries(chunks).forEach(([chunkKey, chunk]) => {\n const chunkState = chunk.get();\n if (chunkState.loading) hasLoading = true;\n if (chunkState.error) {\n if (!firstError) firstError = chunkState.error;\n allErrors[chunkKey as keyof T] = chunkState.error;\n }\n });\n\n combined.set({\n loading: hasLoading,\n error: firstError,\n errors: allErrors,\n data: {\n ...currentState.data,\n [key]: state.data\n },\n });\n });\n });\n\n return combined;\n}\n\nexport type NamedMiddleware<T> = {\n name?: string;\n fn: Middleware<T>;\n};\n\nexport function processMiddleware<T>(initialValue: T, middleware: (Middleware<T> | NamedMiddleware<T>)[]): T {\n if (initialValue === null || initialValue === undefined) {\n throw new Error(\"Value cannot be null or undefined.\");\n }\n\n let currentValue = initialValue;\n let index = 0;\n\n while (index < middleware.length) {\n const current = middleware[index];\n\n const middlewareFn = typeof current === 'function' ? current : current.fn;\n const middlewareName = typeof current === 'function' ? `index ${index}` : (current.name || `index ${index}`);\n let nextCalled = false;\n let nextValue: T | null = null;\n\n try {\n middlewareFn(currentValue, (val) => {\n nextCalled = true;\n nextValue = val;\n });\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n throw new Error(`Middleware \"${middlewareName}\" threw an error: ${errorMessage}`);\n }\n\n if (!nextCalled) break;\n\n if (nextValue === null || nextValue === undefined) {\n throw new Error(`Middleware at index ${index} returned null or undefined value.`);\n }\n\n currentValue = nextValue;\n index++;\n }\n\n return currentValue;\n}\n\nexport function shallowEqual<T>(a: T, b: T): boolean {\n if (a === b) {\n return true;\n }\n\n if (!a || !b || typeof a !== typeof b) {\n return false;\n }\n\n if (Array.isArray(a) && Array.isArray(b)) {\n if (a.length !== b.length) {\n return false;\n }\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n }\n\n if (typeof a === 'object' && typeof b === 'object') {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n\n if (keysA.length !== keysB.length) {\n return false;\n }\n\n for (const key of keysA) {\n if (!Object.prototype.hasOwnProperty.call(b, key) || (a as any)[key] !== (b as any)[key]) {\n return false;\n }\n }\n return true;\n }\n\n // For primitive types, return false. Strict equality already handled by initial check\n return false;\n}\n\nexport function validateObjectShape<T>(original: T, updated: T, path = ''): void {\n if (typeof original === 'object' && original !== null && typeof updated === 'object' && updated !== null) {\n if (Array.isArray(original) && Array.isArray(updated)) {\n if (original.length > 0 && typeof original[0] === 'object') {\n for (let i = 0; i < updated.length; i++) {\n validateObjectShape(original[0], updated[i], `${path}[${i}]`);\n }\n }\n } else if (!Array.isArray(original) && !Array.isArray(updated)) {\n const originalKeys = Object.keys(original as object);\n const updatedKeys = Object.keys(updated as object);\n const extraKeys = updatedKeys.filter(key => !originalKeys.includes(key));\n\n if (extraKeys.length > 0) {\n const fullPath = path || 'root';\n console.error(`🚨 Stunk: Unknown properties detected at '${fullPath}': ${extraKeys.join(', ')}. This might cause bugs.`);\n console.error('Expected keys:', originalKeys);\n console.error('Received keys:', updatedKeys);\n }\n\n // Recurse into common keys\n for (const key of originalKeys) {\n validateObjectShape((original as any)[key], (updated as any)[key], path ? `${path}.${key}` : key);\n }\n }\n }\n}\n","import { processMiddleware, validateObjectShape } from \"../utils\";\n\nexport type Subscriber<T> = (newValue: T) => void;\nexport type Middleware<T> = (value: T, next: (newValue: T) => void) => void;\n\n\nexport interface Chunk<T> {\n /** Get the current value of the chunk. */\n get: () => T;\n /** Set a new value for the chunk & Update existing value efficiently. */\n set: (newValueOrUpdater: T | ((currentValue: T) => T)) => void;\n /** Subscribe to changes in the chunk. Returns an unsubscribe function. */\n subscribe: (callback: Subscriber<T>) => () => void;\n /** Create a derived chunk based on this chunk's value. */\n derive: <D>(fn: (value: T) => D) => Chunk<D>;\n /** Reset the chunk to its initial value. */\n reset: () => void;\n /** Destroy the chunk and all its subscribers. */\n destroy: () => void;\n}\n\nlet isBatching = false;\nconst dirtyChunks = new Set<number>();\nconst chunkRegistry = new Map<number, { notify: () => void }>();\nlet chunkIdCounter = 0;\n\n/**\n * Batch multiple chunk updates into a single re-render.\n * Useful for updating multiple chunks at once without causing multiple re-renders.\n */\nexport function batch(callback: () => void) {\n const wasBatchingBefore = isBatching;\n isBatching = true;\n try {\n callback();\n } finally {\n if (!wasBatchingBefore) {\n isBatching = false;\n const chunks = Array.from(dirtyChunks); // Snapshot to avoid mutation issues\n dirtyChunks.clear(); // Clear early to prevent re-adds\n chunks.forEach(id => {\n const chunk = chunkRegistry.get(id);\n if (chunk) chunk.notify();\n });\n }\n }\n}\n\nexport function chunk<T>(initialValue: T, middleware: Middleware<T>[] = []): Chunk<T> {\n if (initialValue === undefined || initialValue === null) {\n throw new Error(\"Initial value cannot be undefined or null.\");\n }\n\n let value = initialValue;\n const subscribers = new Set<Subscriber<T>>();\n const chunkId = chunkIdCounter++;\n\n const notify = () => {\n subscribers.forEach(subscriber => subscriber(value));\n };\n\n chunkRegistry.set(chunkId, { notify });\n\n const notifySubscribers = () => {\n if (subscribers.size === 0) return; // Skip if no subscribers\n if (isBatching) {\n dirtyChunks.add(chunkId);\n } else {\n notify();\n }\n };\n\n const get = () => value;\n\n const set = (newValueOrUpdater: T | ((currentValue: T) => T)) => {\n let newValue: T;\n\n if (typeof newValueOrUpdater === 'function') {\n const updaterFn = newValueOrUpdater as (currentValue: T) => T;\n newValue = updaterFn(value);\n } else {\n newValue = newValueOrUpdater;\n }\n\n validateObjectShape(value, newValue);\n\n const processedValue = processMiddleware(newValue, middleware);\n\n if (processedValue !== value) {\n value = processedValue as T & {};\n notifySubscribers();\n }\n };\n\n const subscribe = (callback: Subscriber<T>) => {\n if (typeof callback !== \"function\") {\n throw new Error(\"Callback must be a function.\");\n }\n subscribers.add(callback);\n callback(value);\n return () => subscribers.delete(callback);\n };\n\n const reset = () => {\n value = initialValue;\n notifySubscribers();\n };\n\n const destroy = () => {\n subscribers.clear();\n value = initialValue;\n dirtyChunks.delete(chunkId);\n chunkRegistry.delete(chunkId);\n };\n\n const derive = <D>(fn: (value: T) => D) => {\n if (typeof fn !== \"function\") {\n throw new Error(\"Derive function must be a function.\");\n }\n\n const initialDerivedValue = fn(value);\n const derivedChunk = chunk(initialDerivedValue);\n\n const unsubscribe = subscribe(() => {\n const newDerivedValue = fn(value);\n derivedChunk.set(newDerivedValue);\n });\n\n // Add a cleanup method to the derived chunk\n const originalDestroy = derivedChunk.destroy;\n derivedChunk.destroy = () => {\n unsubscribe();\n originalDestroy();\n };\n\n return derivedChunk;\n };\n\n return { get, set, subscribe, derive, reset, destroy };\n}\n","import { chunk, Chunk } from \"./core\";\nimport { AsyncChunkOpt } from \"./types\";\n\nexport interface AsyncState<T, E extends Error> {\n loading: boolean;\n error: E | null;\n data: T | null;\n lastFetched?: number;\n}\n\nexport interface RefreshConfig {\n /** Time in milliseconds after which data becomes stale */\n staleTime?: number;\n /** Time in milliseconds to cache data before considering it expired */\n cacheTime?: number;\n /** Auto-refresh interval in milliseconds */\n refetchInterval?: number;\n}\n\n// Extend existing options without breaking changes\nexport interface AsyncChunkOptExtended<T, E extends Error> extends AsyncChunkOpt<T, E> {\n refresh?: RefreshConfig;\n /** Enable/disable the fetcher - useful for conditional fetching */\n enabled?: boolean;\n}\n\nexport interface AsyncChunk<T, E extends Error = Error> extends Chunk<AsyncState<T, E>> {\n /** Reload the data from the source. */\n reload: () => Promise<void>;\n\n /** Smart refresh - respects stale time */\n refresh: () => Promise<void>;\n\n /** Mutate the data directly. */\n mutate: (mutator: (currentData: T | null) => T) => void;\n\n /** Reset the state to the initial value. */\n reset: () => void;\n\n /** Clean up intervals and timeouts */\n cleanup: () => void;\n}\n\n// Overloaded function signatures for backward compatibility\nexport function asyncChunk<T, E extends Error = Error>(\n fetcher: () => Promise<T>,\n options?: AsyncChunkOptExtended<T, E>\n): AsyncChunk<T, E>;\n\nexport function asyncChunk<T, E extends Error = Error, P extends any[] = []>(\n fetcher: (...params: P) => Promise<T>,\n options?: AsyncChunkOptExtended<T, E>\n): AsyncChunk<T, E> & {\n /** Reload with new parameters */\n reload: (...params: P) => Promise<void>;\n /** Smart refresh with parameters */\n refresh: (...params: P) => Promise<void>;\n /** Set parameters for future calls */\n setParams: (...params: P) => void;\n};\n\nexport function asyncChunk<T, E extends Error = Error, P extends any[] = []>(\n fetcher: (...params: P) => Promise<T>,\n options: AsyncChunkOptExtended<T, E> = {}\n) {\n const {\n initialData = null,\n onError,\n retryCount = 0,\n retryDelay = 1000,\n refresh: refreshConfig = {},\n enabled = true,\n } = options;\n\n const { staleTime = 0, cacheTime = 5 * 60 * 1000, refetchInterval } = refreshConfig;\n\n // let's expect params\n const expectsParams = fetcher.length > 0;\n\n const initialState: AsyncState<T, E> = {\n loading: enabled && !expectsParams,\n error: null,\n data: initialData,\n lastFetched: undefined,\n };\n\n const hasValidParams = (params?: P): boolean => {\n if (!expectsParams) return true;\n\n if (params === undefined) return false;\n if (Array.isArray(params)) {\n return params.every(p => p !== undefined && p !== null);\n }\n return true;\n };\n\n const baseChunk = chunk(initialState);\n let currentParams: P | undefined;\n let intervalId: number | null = null;\n let cacheTimeoutId: number | null = null;\n\n const isStale = () => {\n const state = baseChunk.get();\n if (!state.lastFetched) return true;\n return Date.now() - state.lastFetched > staleTime;\n };\n\n const isCacheExpired = () => {\n const state = baseChunk.get();\n if (!state.lastFetched) return true;\n return Date.now() - state.lastFetched > cacheTime;\n };\n\n const clearCache = () => {\n baseChunk.set({\n ...baseChunk.get(),\n data: initialData,\n lastFetched: undefined,\n });\n };\n\n const setCacheTimeout = () => {\n if (cacheTimeoutId) {\n clearTimeout(cacheTimeoutId);\n }\n if (cacheTime > 0) {\n cacheTimeoutId = setTimeout(clearCache, cacheTime);\n }\n };\n\n const fetchData = async (params?: P, retries = retryCount, force = false): Promise<void> => {\n if (!enabled) return;\n\n // Store params for reuse\n if (params !== undefined) {\n currentParams = params;\n }\n\n // Don't fetch if we don't have valid parameters (only matters if params expected)\n if (!hasValidParams(currentParams)) {\n baseChunk.set({ ...baseChunk.get(), loading: false });\n return;\n }\n\n // Don't fetch if data is fresh and not forcing\n if (!force && !isStale() && baseChunk.get().data !== null && staleTime > 0) {\n return;\n }\n\n baseChunk.set({ ...baseChunk.get(), loading: true, error: null });\n\n try {\n const data = expectsParams\n ? await fetcher(...currentParams!)\n : await fetcher(...([] as unknown as P));\n const now = Date.now();\n\n baseChunk.set({\n loading: false,\n error: null,\n data,\n lastFetched: now\n });\n\n setCacheTimeout();\n } catch (error) {\n if (retries > 0) {\n await new Promise(resolve => setTimeout(resolve, retryDelay));\n return fetchData(params, retries - 1, force);\n }\n\n baseChunk.set({\n loading: false,\n error: error as E,\n data: baseChunk.get().data,\n lastFetched: baseChunk.get().lastFetched\n });\n\n if (onError) {\n onError(error as E);\n }\n }\n };\n\n // Setup auto-refresh\n if (refetchInterval && refetchInterval > 0 && enabled) {\n intervalId = setInterval(() => {\n if (enabled) {\n fetchData(currentParams, 0, false);\n }\n }, refetchInterval);\n }\n\n // Initial fetch\n if (enabled && !expectsParams) {\n fetchData();\n }\n\n const cleanup = () => {\n if (intervalId) {\n clearInterval(intervalId);\n intervalId = null;\n }\n if (cacheTimeoutId) {\n clearTimeout(cacheTimeoutId);\n cacheTimeoutId = null;\n }\n };\n\n const asyncChunkInstance = {\n ...baseChunk,\n\n reload: async (...params: P) => {\n await fetchData(params.length > 0 ? params : undefined, retryCount, true);\n },\n\n refresh: async (...params: P) => {\n await fetchData(params.length > 0 ? params : undefined, retryCount, false);\n },\n\n mutate: (mutator: (currentData: T | null) => T) => {\n const currentState = baseChunk.get();\n const newData = mutator(currentState.data);\n baseChunk.set({ ...currentState, data: newData });\n },\n\n reset: () => {\n cleanup();\n baseChunk.set({\n ...initialState,\n loading: enabled\n });\n if (enabled) {\n fetchData();\n\n if (refetchInterval && refetchInterval > 0) {\n intervalId = setInterval(() => {\n if (enabled) {\n fetchData(currentParams, 0, false);\n }\n }, refetchInterval);\n }\n }\n },\n\n cleanup,\n\n // Only add setParams if parameters were used\n setParams: (...params: P) => {\n currentParams = params;\n if (enabled && hasValidParams(params)) {\n fetchData(params);\n }\n },\n\n };\n\n return asyncChunkInstance;\n}\n","import { Chunk, chunk } from \"./core\";\n\nimport { shallowEqual } from \"../utils\";\n\n// Helper type to extract the value type from a Chunk\nexport type ChunkValue<T> = T extends Chunk<infer U> ? U : never;\n\n// Helper type to transform an array of Chunks into an array of their value types\nexport type DependencyValues<T extends Chunk<any>[]> = {\n [K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;\n};\n\nexport interface Computed<T> extends Chunk<T> {\n /**\n * Checks if the computed value needs to be recalculated due to dependency changes.\n * @returns True if the computed value is dirty, false otherwise.\n */\n isDirty: () => boolean;\n /** Manually forces recalculation of the computed value from its dependencies. */\n recompute: () => void;\n}\n\nexport function computed<TDeps extends Chunk<any>[], TResult>(\n dependencies: [...TDeps],\n computeFn: (...args: DependencyValues<TDeps>) => TResult\n): Computed<TResult> {\n const dependencyValues = dependencies.map(dep => dep.get());\n let cachedValue = computeFn(...dependencyValues as DependencyValues<TDeps>);\n\n const computedChunk = chunk(cachedValue);\n const originalSet = computedChunk.set;\n\n let isDirty = false;\n\n // Direct synchronous recomputation\n const recompute = () => {\n let hasChanges = false;\n\n for (let i = 0; i < dependencies.length; i++) {\n const newValue = dependencies[i].get();\n if (newValue !== dependencyValues[i]) {\n dependencyValues[i] = newValue;\n hasChanges = true;\n }\n }\n\n if (hasChanges) {\n const newValue = computeFn(...dependencyValues as DependencyValues<TDeps>);\n // Fast path for primitives only. Avoids shallowEqual for performance.\n if (newValue !== cachedValue) {\n // Only use shallowEqual for objects when needed\n if (typeof newValue !== 'object' || typeof cachedValue !== 'object' || !shallowEqual(newValue, cachedValue)) {\n cachedValue = newValue;\n originalSet(newValue);\n }\n }\n isDirty = false;\n }\n };\n\n const unsubs = dependencies.map(dep =>\n dep.subscribe(() => {\n isDirty = true;\n recompute();\n })\n );\n\n return {\n ...computedChunk,\n get: () => {\n if (isDirty) recompute();\n return cachedValue;\n },\n recompute,\n isDirty: () => isDirty,\n set: () => { throw new Error('Cannot set values directly on computed. Modify the source chunk instead.'); },\n reset: () => {\n dependencies.forEach(dep => {\n if (typeof dep.reset === 'function') {\n dep.reset();\n }\n });\n isDirty = true;\n recompute();\n return cachedValue;\n },\n destroy: () => { unsubs.forEach(unsub => unsub()); computedChunk.destroy?.(); }\n };\n}\n","import { shallowEqual } from \"../utils\";\nimport { Chunk, chunk } from \"./core\";\n\nexport interface SelectOptions {\n /**\n * Configuration options for selector functions.\n * @property {boolean} [useShallowEqual] - When true, performs a shallow equality check\n * on the derived selector results to prevent unnecessary updates.\n */\n useShallowEqual?: boolean;\n}\n\n/**\n * Creates a derived read-only chunk based on a selector function.\n * @param sourceChunk The source chunk to derive from.\n * @param selector A function that extracts part of the source value.\n * @param options Optional settings for shallow equality comparison.\n * @returns A read-only derived chunk.\n */\n\nexport function select<T, S>(\n sourceChunk: Chunk<T>,\n selector: (value: T) => S,\n options: SelectOptions = {}\n): Chunk<S> {\n const { useShallowEqual = false } = options;\n\n let prevSourceValue = sourceChunk.get();\n let currentResult = selector(prevSourceValue);\n\n const derivedChunk = chunk(currentResult);\n\n const update = () => {\n const newSourceValue = sourceChunk.get();\n const newResult = selector(newSourceValue);\n\n // Always update the reference to source value\n prevSourceValue = newSourceValue;\n\n // Check if the result has changed\n const resultChanged = useShallowEqual\n ? !shallowEqual(newResult, currentResult)\n : newResult !== currentResult;\n\n if (resultChanged) {\n currentResult = newResult;\n derivedChunk.set(newResult);\n }\n };\n\n const unsubscribe = sourceChunk.subscribe(update);\n\n return {\n get: () => derivedChunk.get(),\n set: () => {\n throw new Error('Cannot set values directly on a selector. Modify the source chunk instead.');\n },\n subscribe: derivedChunk.subscribe,\n derive: <D>(fn: (value: S) => D) => select(derivedChunk, fn, options), // Pass options to nested selectors\n reset: () => {\n throw new Error('Cannot reset a selector chunk. Reset the source chunk instead.');\n },\n destroy: () => {\n unsubscribe();\n derivedChunk.destroy();\n }\n };\n}\n","// Middleware passed to chunks\nexport { logger } from \"./logger\";\nexport { nonNegativeValidator } from \"./validator\";\n\n// Middleware used with chunks\nexport { withHistory } from \"./history\";\nexport { withPersistence } from './persistence';\n","import { Middleware } from \"../core/core\";\n\nexport const logger: Middleware<any> = (value, next) => {\n console.log(\"Setting value:\", value);\n next(value);\n};\n","import { chunk, Middleware } from \"../core/core\";\n\nexport const nonNegativeValidator: Middleware<number> = (value, next) => {\n if (value < 0) {\n throw new Error(\"Value must be non-negative!\");\n }\n next(value); // If validation passes, proceed with the update\n};\n","import { Chunk } from \"../core/core\";\n\nexport interface ChunkWithHistory<T> extends Chunk<T> {\n /**\n * Reverts to the previous state (if available).\n */\n undo: () => void;\n /**\n * Moves to the next state (if available).\n */\n redo: () => void;\n /**\n * Returns true if there is a previous state to revert to.\n */\n canUndo: () => boolean;\n /**\n * Returns true if there is a next state to move to.\n */\n canRedo: () => boolean;\n /**\n * Returns an array of all the values in the history.\n */\n getHistory: () => T[];\n /**\n * Clears the history, keeping only the current value.\n */\n clearHistory: () => void;\n}\n\nexport function withHistory<T>(\n baseChunk: Chunk<T>,\n options: { maxHistory?: number } = {}\n): ChunkWithHistory<T> {\n const { maxHistory = 100 } = options;\n const history: T[] = [baseChunk.get()];\n let currentIndex = 0;\n let isHistoryAction = false;\n\n const historyChunk: ChunkWithHistory<T> = {\n ...baseChunk,\n\n set: (newValueOrUpdater: T | ((currentValue: T) => T)) => {\n if (isHistoryAction) {\n baseChunk.set(newValueOrUpdater);\n return;\n }\n\n // Process the value or updater function\n let newValue: T;\n if (typeof newValueOrUpdater === 'function') {\n // Get current value and apply the updater function\n const currentValue = baseChunk.get();\n newValue = (newValueOrUpdater as ((currentValue: T) => T))(currentValue);\n } else {\n // Use directly as the new value\n newValue = newValueOrUpdater;\n }\n history.splice(currentIndex + 1);\n history.push(newValue);\n\n // Limit history size\n if (history.length > maxHistory) {\n console.warn(\"History limit reached. Removing oldest entries.\");\n const removeCount = history.length - maxHistory;\n history.splice(0, removeCount);\n currentIndex = Math.max(0, currentIndex - removeCount);\n }\n\n currentIndex = history.length - 1;\n baseChunk.set(newValue);\n },\n\n undo: () => {\n if (!historyChunk.canUndo()) return;\n\n isHistoryAction = true;\n currentIndex--;\n historyChunk.set(history[currentIndex]);\n isHistoryAction = false;\n },\n\n redo: () => {\n if (!historyChunk.canRedo()) return;\n\n isHistoryAction = true;\n currentIndex++;\n historyChunk.set(history[currentIndex]);\n isHistoryAction = false;\n },\n\n canUndo: () => currentIndex > 0,\n\n canRedo: () => currentIndex < history.length - 1,\n\n getHistory: () => [...history],\n\n clearHistory: () => {\n const currentValue = baseChunk.get();\n history.length = 0;\n history.push(currentValue);\n currentIndex = 0;\n },\n\n // Override destroy to clean up history\n destroy: () => {\n history.length = 0;\n baseChunk.destroy();\n }\n }\n\n return historyChunk;\n\n}\n","import { Chunk } from \"../core/core\";\n\nexport interface PersistOptions<T> {\n key: string;\n storage?: Storage;\n serialize?: (value: T) => string;\n deserialize?: (value: string) => T;\n}\n\nexport function withPersistence<T>(\n baseChunk: Chunk<T>,\n options: PersistOptions<T>\n): Chunk<T> {\n const {\n key,\n storage = localStorage,\n serialize = JSON.stringify,\n deserialize = JSON.parse,\n } = options;\n\n // Try to load initial state from storage\n try {\n const savedChunk = storage.getItem(key);\n if (savedChunk) {\n const parsed = deserialize(savedChunk);\n baseChunk.set(parsed)\n }\n } catch (error) {\n console.error('Failed to load persisted state:', error);\n }\n\n // Save to storage\n baseChunk.subscribe((newValue) => {\n try {\n const serialized = serialize(newValue);\n storage.setItem(key, serialized);\n\n } catch (error) {\n console.log('Failed to persist chunk', error)\n }\n })\n\n return baseChunk\n\n}\n"]}
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
type Subscriber<T> = (newValue: T) => void;
|
|
2
|
+
type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
|
|
3
|
+
interface Chunk<T> {
|
|
4
|
+
/** Get the current value of the chunk. */
|
|
5
|
+
get: () => T;
|
|
6
|
+
/** Set a new value for the chunk & Update existing value efficiently. */
|
|
7
|
+
set: (newValueOrUpdater: T | ((currentValue: T) => T)) => void;
|
|
8
|
+
/** Subscribe to changes in the chunk. Returns an unsubscribe function. */
|
|
9
|
+
subscribe: (callback: Subscriber<T>) => () => void;
|
|
10
|
+
/** Create a derived chunk based on this chunk's value. */
|
|
11
|
+
derive: <D>(fn: (value: T) => D) => Chunk<D>;
|
|
12
|
+
/** Reset the chunk to its initial value. */
|
|
13
|
+
reset: () => void;
|
|
14
|
+
/** Destroy the chunk and all its subscribers. */
|
|
15
|
+
destroy: () => void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Batch multiple chunk updates into a single re-render.
|
|
19
|
+
* Useful for updating multiple chunks at once without causing multiple re-renders.
|
|
20
|
+
*/
|
|
21
|
+
declare function batch(callback: () => void): void;
|
|
22
|
+
declare function chunk<T>(initialValue: T, middleware?: Middleware<T>[]): Chunk<T>;
|
|
23
|
+
|
|
24
|
+
type AsyncChunkOpt<T, E extends Error> = {
|
|
25
|
+
initialData?: T | null;
|
|
26
|
+
onError?: (error: E) => void;
|
|
27
|
+
retryCount?: number;
|
|
28
|
+
retryDelay?: number;
|
|
29
|
+
};
|
|
30
|
+
type InferAsyncData<T> = T extends AsyncChunk<infer U, Error> ? U : never;
|
|
31
|
+
type CombinedData<T extends Record<string, AsyncChunk<any>>> = {
|
|
32
|
+
[K in keyof T]: InferAsyncData<T[K]> | null;
|
|
33
|
+
};
|
|
34
|
+
type CombinedState<T extends Record<string, AsyncChunk<any>>> = {
|
|
35
|
+
loading: boolean;
|
|
36
|
+
error: Error | null;
|
|
37
|
+
errors: Partial<{
|
|
38
|
+
[K in keyof T]: Error;
|
|
39
|
+
}>;
|
|
40
|
+
data: CombinedData<T>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
interface AsyncState<T, E extends Error> {
|
|
44
|
+
loading: boolean;
|
|
45
|
+
error: E | null;
|
|
46
|
+
data: T | null;
|
|
47
|
+
lastFetched?: number;
|
|
48
|
+
}
|
|
49
|
+
interface RefreshConfig {
|
|
50
|
+
/** Time in milliseconds after which data becomes stale */
|
|
51
|
+
staleTime?: number;
|
|
52
|
+
/** Time in milliseconds to cache data before considering it expired */
|
|
53
|
+
cacheTime?: number;
|
|
54
|
+
/** Auto-refresh interval in milliseconds */
|
|
55
|
+
refetchInterval?: number;
|
|
56
|
+
}
|
|
57
|
+
interface AsyncChunkOptExtended<T, E extends Error> extends AsyncChunkOpt<T, E> {
|
|
58
|
+
refresh?: RefreshConfig;
|
|
59
|
+
/** Enable/disable the fetcher - useful for conditional fetching */
|
|
60
|
+
enabled?: boolean;
|
|
61
|
+
}
|
|
62
|
+
interface AsyncChunk<T, E extends Error = Error> extends Chunk<AsyncState<T, E>> {
|
|
63
|
+
/** Reload the data from the source. */
|
|
64
|
+
reload: () => Promise<void>;
|
|
65
|
+
/** Smart refresh - respects stale time */
|
|
66
|
+
refresh: () => Promise<void>;
|
|
67
|
+
/** Mutate the data directly. */
|
|
68
|
+
mutate: (mutator: (currentData: T | null) => T) => void;
|
|
69
|
+
/** Reset the state to the initial value. */
|
|
70
|
+
reset: () => void;
|
|
71
|
+
/** Clean up intervals and timeouts */
|
|
72
|
+
cleanup: () => void;
|
|
73
|
+
}
|
|
74
|
+
declare function asyncChunk<T, E extends Error = Error>(fetcher: () => Promise<T>, options?: AsyncChunkOptExtended<T, E>): AsyncChunk<T, E>;
|
|
75
|
+
declare function asyncChunk<T, E extends Error = Error, P extends any[] = []>(fetcher: (...params: P) => Promise<T>, options?: AsyncChunkOptExtended<T, E>): AsyncChunk<T, E> & {
|
|
76
|
+
/** Reload with new parameters */
|
|
77
|
+
reload: (...params: P) => Promise<void>;
|
|
78
|
+
/** Smart refresh with parameters */
|
|
79
|
+
refresh: (...params: P) => Promise<void>;
|
|
80
|
+
/** Set parameters for future calls */
|
|
81
|
+
setParams: (...params: P) => void;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
|
|
85
|
+
type DependencyValues<T extends Chunk<any>[]> = {
|
|
86
|
+
[K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
|
|
87
|
+
};
|
|
88
|
+
interface Computed<T> extends Chunk<T> {
|
|
89
|
+
/**
|
|
90
|
+
* Checks if the computed value needs to be recalculated due to dependency changes.
|
|
91
|
+
* @returns True if the computed value is dirty, false otherwise.
|
|
92
|
+
*/
|
|
93
|
+
isDirty: () => boolean;
|
|
94
|
+
/** Manually forces recalculation of the computed value from its dependencies. */
|
|
95
|
+
recompute: () => void;
|
|
96
|
+
}
|
|
97
|
+
declare function computed<TDeps extends Chunk<any>[], TResult>(dependencies: [...TDeps], computeFn: (...args: DependencyValues<TDeps>) => TResult): Computed<TResult>;
|
|
98
|
+
|
|
99
|
+
interface SelectOptions {
|
|
100
|
+
/**
|
|
101
|
+
* Configuration options for selector functions.
|
|
102
|
+
* @property {boolean} [useShallowEqual] - When true, performs a shallow equality check
|
|
103
|
+
* on the derived selector results to prevent unnecessary updates.
|
|
104
|
+
*/
|
|
105
|
+
useShallowEqual?: boolean;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Creates a derived read-only chunk based on a selector function.
|
|
109
|
+
* @param sourceChunk The source chunk to derive from.
|
|
110
|
+
* @param selector A function that extracts part of the source value.
|
|
111
|
+
* @param options Optional settings for shallow equality comparison.
|
|
112
|
+
* @returns A read-only derived chunk.
|
|
113
|
+
*/
|
|
114
|
+
declare function select<T, S>(sourceChunk: Chunk<T>, selector: (value: T) => S, options?: SelectOptions): Chunk<S>;
|
|
115
|
+
|
|
116
|
+
declare function isValidChunkValue(value: unknown): boolean;
|
|
117
|
+
declare function isChunk<T>(value: unknown): value is Chunk<T>;
|
|
118
|
+
declare function once<T>(fn: () => T): () => T;
|
|
119
|
+
declare function combineAsyncChunks<T extends Record<string, AsyncChunk<any>>>(chunks: T): Chunk<CombinedState<T>>;
|
|
120
|
+
|
|
121
|
+
declare const logger: Middleware<any>;
|
|
122
|
+
|
|
123
|
+
declare const nonNegativeValidator: Middleware<number>;
|
|
124
|
+
|
|
125
|
+
interface ChunkWithHistory<T> extends Chunk<T> {
|
|
126
|
+
/**
|
|
127
|
+
* Reverts to the previous state (if available).
|
|
128
|
+
*/
|
|
129
|
+
undo: () => void;
|
|
130
|
+
/**
|
|
131
|
+
* Moves to the next state (if available).
|
|
132
|
+
*/
|
|
133
|
+
redo: () => void;
|
|
134
|
+
/**
|
|
135
|
+
* Returns true if there is a previous state to revert to.
|
|
136
|
+
*/
|
|
137
|
+
canUndo: () => boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Returns true if there is a next state to move to.
|
|
140
|
+
*/
|
|
141
|
+
canRedo: () => boolean;
|
|
142
|
+
/**
|
|
143
|
+
* Returns an array of all the values in the history.
|
|
144
|
+
*/
|
|
145
|
+
getHistory: () => T[];
|
|
146
|
+
/**
|
|
147
|
+
* Clears the history, keeping only the current value.
|
|
148
|
+
*/
|
|
149
|
+
clearHistory: () => void;
|
|
150
|
+
}
|
|
151
|
+
declare function withHistory<T>(baseChunk: Chunk<T>, options?: {
|
|
152
|
+
maxHistory?: number;
|
|
153
|
+
}): ChunkWithHistory<T>;
|
|
154
|
+
|
|
155
|
+
interface PersistOptions<T> {
|
|
156
|
+
key: string;
|
|
157
|
+
storage?: Storage;
|
|
158
|
+
serialize?: (value: T) => string;
|
|
159
|
+
deserialize?: (value: string) => T;
|
|
160
|
+
}
|
|
161
|
+
declare function withPersistence<T>(baseChunk: Chunk<T>, options: PersistOptions<T>): Chunk<T>;
|
|
162
|
+
|
|
163
|
+
declare const index_logger: typeof logger;
|
|
164
|
+
declare const index_nonNegativeValidator: typeof nonNegativeValidator;
|
|
165
|
+
declare const index_withHistory: typeof withHistory;
|
|
166
|
+
declare const index_withPersistence: typeof withPersistence;
|
|
167
|
+
declare namespace index {
|
|
168
|
+
export { index_logger as logger, index_nonNegativeValidator as nonNegativeValidator, index_withHistory as withHistory, index_withPersistence as withPersistence };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export { type Chunk, type Middleware, asyncChunk, batch, chunk, combineAsyncChunks, computed, isChunk, isValidChunkValue, index as middleware, once, select };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,171 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
1
|
+
type Subscriber<T> = (newValue: T) => void;
|
|
2
|
+
type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
|
|
3
|
+
interface Chunk<T> {
|
|
4
|
+
/** Get the current value of the chunk. */
|
|
5
|
+
get: () => T;
|
|
6
|
+
/** Set a new value for the chunk & Update existing value efficiently. */
|
|
7
|
+
set: (newValueOrUpdater: T | ((currentValue: T) => T)) => void;
|
|
8
|
+
/** Subscribe to changes in the chunk. Returns an unsubscribe function. */
|
|
9
|
+
subscribe: (callback: Subscriber<T>) => () => void;
|
|
10
|
+
/** Create a derived chunk based on this chunk's value. */
|
|
11
|
+
derive: <D>(fn: (value: T) => D) => Chunk<D>;
|
|
12
|
+
/** Reset the chunk to its initial value. */
|
|
13
|
+
reset: () => void;
|
|
14
|
+
/** Destroy the chunk and all its subscribers. */
|
|
15
|
+
destroy: () => void;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Batch multiple chunk updates into a single re-render.
|
|
19
|
+
* Useful for updating multiple chunks at once without causing multiple re-renders.
|
|
20
|
+
*/
|
|
21
|
+
declare function batch(callback: () => void): void;
|
|
22
|
+
declare function chunk<T>(initialValue: T, middleware?: Middleware<T>[]): Chunk<T>;
|
|
23
|
+
|
|
24
|
+
type AsyncChunkOpt<T, E extends Error> = {
|
|
25
|
+
initialData?: T | null;
|
|
26
|
+
onError?: (error: E) => void;
|
|
27
|
+
retryCount?: number;
|
|
28
|
+
retryDelay?: number;
|
|
29
|
+
};
|
|
30
|
+
type InferAsyncData<T> = T extends AsyncChunk<infer U, Error> ? U : never;
|
|
31
|
+
type CombinedData<T extends Record<string, AsyncChunk<any>>> = {
|
|
32
|
+
[K in keyof T]: InferAsyncData<T[K]> | null;
|
|
33
|
+
};
|
|
34
|
+
type CombinedState<T extends Record<string, AsyncChunk<any>>> = {
|
|
35
|
+
loading: boolean;
|
|
36
|
+
error: Error | null;
|
|
37
|
+
errors: Partial<{
|
|
38
|
+
[K in keyof T]: Error;
|
|
39
|
+
}>;
|
|
40
|
+
data: CombinedData<T>;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
interface AsyncState<T, E extends Error> {
|
|
44
|
+
loading: boolean;
|
|
45
|
+
error: E | null;
|
|
46
|
+
data: T | null;
|
|
47
|
+
lastFetched?: number;
|
|
48
|
+
}
|
|
49
|
+
interface RefreshConfig {
|
|
50
|
+
/** Time in milliseconds after which data becomes stale */
|
|
51
|
+
staleTime?: number;
|
|
52
|
+
/** Time in milliseconds to cache data before considering it expired */
|
|
53
|
+
cacheTime?: number;
|
|
54
|
+
/** Auto-refresh interval in milliseconds */
|
|
55
|
+
refetchInterval?: number;
|
|
56
|
+
}
|
|
57
|
+
interface AsyncChunkOptExtended<T, E extends Error> extends AsyncChunkOpt<T, E> {
|
|
58
|
+
refresh?: RefreshConfig;
|
|
59
|
+
/** Enable/disable the fetcher - useful for conditional fetching */
|
|
60
|
+
enabled?: boolean;
|
|
61
|
+
}
|
|
62
|
+
interface AsyncChunk<T, E extends Error = Error> extends Chunk<AsyncState<T, E>> {
|
|
63
|
+
/** Reload the data from the source. */
|
|
64
|
+
reload: () => Promise<void>;
|
|
65
|
+
/** Smart refresh - respects stale time */
|
|
66
|
+
refresh: () => Promise<void>;
|
|
67
|
+
/** Mutate the data directly. */
|
|
68
|
+
mutate: (mutator: (currentData: T | null) => T) => void;
|
|
69
|
+
/** Reset the state to the initial value. */
|
|
70
|
+
reset: () => void;
|
|
71
|
+
/** Clean up intervals and timeouts */
|
|
72
|
+
cleanup: () => void;
|
|
73
|
+
}
|
|
74
|
+
declare function asyncChunk<T, E extends Error = Error>(fetcher: () => Promise<T>, options?: AsyncChunkOptExtended<T, E>): AsyncChunk<T, E>;
|
|
75
|
+
declare function asyncChunk<T, E extends Error = Error, P extends any[] = []>(fetcher: (...params: P) => Promise<T>, options?: AsyncChunkOptExtended<T, E>): AsyncChunk<T, E> & {
|
|
76
|
+
/** Reload with new parameters */
|
|
77
|
+
reload: (...params: P) => Promise<void>;
|
|
78
|
+
/** Smart refresh with parameters */
|
|
79
|
+
refresh: (...params: P) => Promise<void>;
|
|
80
|
+
/** Set parameters for future calls */
|
|
81
|
+
setParams: (...params: P) => void;
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
|
|
85
|
+
type DependencyValues<T extends Chunk<any>[]> = {
|
|
86
|
+
[K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
|
|
87
|
+
};
|
|
88
|
+
interface Computed<T> extends Chunk<T> {
|
|
89
|
+
/**
|
|
90
|
+
* Checks if the computed value needs to be recalculated due to dependency changes.
|
|
91
|
+
* @returns True if the computed value is dirty, false otherwise.
|
|
92
|
+
*/
|
|
93
|
+
isDirty: () => boolean;
|
|
94
|
+
/** Manually forces recalculation of the computed value from its dependencies. */
|
|
95
|
+
recompute: () => void;
|
|
96
|
+
}
|
|
97
|
+
declare function computed<TDeps extends Chunk<any>[], TResult>(dependencies: [...TDeps], computeFn: (...args: DependencyValues<TDeps>) => TResult): Computed<TResult>;
|
|
98
|
+
|
|
99
|
+
interface SelectOptions {
|
|
100
|
+
/**
|
|
101
|
+
* Configuration options for selector functions.
|
|
102
|
+
* @property {boolean} [useShallowEqual] - When true, performs a shallow equality check
|
|
103
|
+
* on the derived selector results to prevent unnecessary updates.
|
|
104
|
+
*/
|
|
105
|
+
useShallowEqual?: boolean;
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Creates a derived read-only chunk based on a selector function.
|
|
109
|
+
* @param sourceChunk The source chunk to derive from.
|
|
110
|
+
* @param selector A function that extracts part of the source value.
|
|
111
|
+
* @param options Optional settings for shallow equality comparison.
|
|
112
|
+
* @returns A read-only derived chunk.
|
|
113
|
+
*/
|
|
114
|
+
declare function select<T, S>(sourceChunk: Chunk<T>, selector: (value: T) => S, options?: SelectOptions): Chunk<S>;
|
|
115
|
+
|
|
116
|
+
declare function isValidChunkValue(value: unknown): boolean;
|
|
117
|
+
declare function isChunk<T>(value: unknown): value is Chunk<T>;
|
|
118
|
+
declare function once<T>(fn: () => T): () => T;
|
|
119
|
+
declare function combineAsyncChunks<T extends Record<string, AsyncChunk<any>>>(chunks: T): Chunk<CombinedState<T>>;
|
|
120
|
+
|
|
121
|
+
declare const logger: Middleware<any>;
|
|
122
|
+
|
|
123
|
+
declare const nonNegativeValidator: Middleware<number>;
|
|
124
|
+
|
|
125
|
+
interface ChunkWithHistory<T> extends Chunk<T> {
|
|
126
|
+
/**
|
|
127
|
+
* Reverts to the previous state (if available).
|
|
128
|
+
*/
|
|
129
|
+
undo: () => void;
|
|
130
|
+
/**
|
|
131
|
+
* Moves to the next state (if available).
|
|
132
|
+
*/
|
|
133
|
+
redo: () => void;
|
|
134
|
+
/**
|
|
135
|
+
* Returns true if there is a previous state to revert to.
|
|
136
|
+
*/
|
|
137
|
+
canUndo: () => boolean;
|
|
138
|
+
/**
|
|
139
|
+
* Returns true if there is a next state to move to.
|
|
140
|
+
*/
|
|
141
|
+
canRedo: () => boolean;
|
|
142
|
+
/**
|
|
143
|
+
* Returns an array of all the values in the history.
|
|
144
|
+
*/
|
|
145
|
+
getHistory: () => T[];
|
|
146
|
+
/**
|
|
147
|
+
* Clears the history, keeping only the current value.
|
|
148
|
+
*/
|
|
149
|
+
clearHistory: () => void;
|
|
150
|
+
}
|
|
151
|
+
declare function withHistory<T>(baseChunk: Chunk<T>, options?: {
|
|
152
|
+
maxHistory?: number;
|
|
153
|
+
}): ChunkWithHistory<T>;
|
|
154
|
+
|
|
155
|
+
interface PersistOptions<T> {
|
|
156
|
+
key: string;
|
|
157
|
+
storage?: Storage;
|
|
158
|
+
serialize?: (value: T) => string;
|
|
159
|
+
deserialize?: (value: string) => T;
|
|
160
|
+
}
|
|
161
|
+
declare function withPersistence<T>(baseChunk: Chunk<T>, options: PersistOptions<T>): Chunk<T>;
|
|
162
|
+
|
|
163
|
+
declare const index_logger: typeof logger;
|
|
164
|
+
declare const index_nonNegativeValidator: typeof nonNegativeValidator;
|
|
165
|
+
declare const index_withHistory: typeof withHistory;
|
|
166
|
+
declare const index_withPersistence: typeof withPersistence;
|
|
167
|
+
declare namespace index {
|
|
168
|
+
export { index_logger as logger, index_nonNegativeValidator as nonNegativeValidator, index_withHistory as withHistory, index_withPersistence as withPersistence };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export { type Chunk, type Middleware, asyncChunk, batch, chunk, combineAsyncChunks, computed, isChunk, isValidChunkValue, index as middleware, once, select };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
export { computed } from './core/computed';
|
|
4
|
-
export { select } from './core/selector';
|
|
5
|
-
export { combineAsyncChunks, once, isChunk, isValidChunkValue } from './utils';
|
|
6
|
-
export * as middleware from "./middleware";
|
|
1
|
+
var N=Object.defineProperty;var z=(e,n)=>{for(var r in n)N(e,r,{get:n[r],enumerable:true});};function B(e){return e!=null}function W(e){if(!e||typeof e!="object")return false;let n=e;return ["get","set","update","subscribe","derive","reset","destroy"].every(t=>typeof n[t]=="function")}function J(e){let n=false,r;return ()=>(n||(r=e(),n=true),r)}function U(e){let n=Object.keys(e).reduce((c,s)=>(c[s]=null,c),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:n},t=p(r);Object.values(e);return Object.entries(e).forEach(([c,s])=>{s.subscribe(a=>{let f=t.get(),i=false,u=null,T={};Object.entries(e).forEach(([b,h])=>{let l=h.get();l.loading&&(i=true),l.error&&(u||(u=l.error),T[b]=l.error);}),t.set({loading:i,error:u,errors:T,data:{...f.data,[c]:a.data}});});}),t}function M(e,n){if(e==null)throw new Error("Value cannot be null or undefined.");let r=e,t=0;for(;t<n.length;){let o=n[t],c=typeof o=="function"?o:o.fn,s=typeof o=="function"?`index ${t}`:o.name||`index ${t}`,a=false,f=null;try{c(r,i=>{a=!0,f=i;});}catch(i){let u=i instanceof Error?i.message:String(i);throw new Error(`Middleware "${s}" threw an error: ${u}`)}if(!a)break;if(f==null)throw new Error(`Middleware at index ${t} returned null or undefined value.`);r=f,t++;}return r}function E(e,n){if(e===n)return true;if(!e||!n||typeof e!=typeof n)return false;if(Array.isArray(e)&&Array.isArray(n)){if(e.length!==n.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==n[r])return false;return true}if(typeof e=="object"&&typeof n=="object"){let r=Object.keys(e),t=Object.keys(n);if(r.length!==t.length)return false;for(let o of r)if(!Object.prototype.hasOwnProperty.call(n,o)||e[o]!==n[o])return false;return true}return false}function v(e,n,r=""){if(typeof e=="object"&&e!==null&&typeof n=="object"&&n!==null){if(Array.isArray(e)&&Array.isArray(n)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<n.length;t++)v(e[0],n[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(n)){let t=Object.keys(e),o=Object.keys(n),c=o.filter(s=>!t.includes(s));c.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${c.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",o));for(let s of t)v(e[s],n[s],r?`${r}.${s}`:s);}}}var S=false,P=new Set,V=new Map,L=0;function G(e){let n=S;S=true;try{e();}finally{if(!n){S=false;let r=Array.from(P);P.clear(),r.forEach(t=>{let o=V.get(t);o&&o.notify();});}}}function p(e,n=[]){if(e==null)throw new Error("Initial value cannot be undefined or null.");let r=e,t=new Set,o=L++,c=()=>{t.forEach(h=>h(r));};V.set(o,{notify:c});let s=()=>{t.size!==0&&(S?P.add(o):c());},a=()=>r,f=h=>{let l;typeof h=="function"?l=h(r):l=h,v(r,l);let y=M(l,n);y!==r&&(r=y,s());},i=h=>{if(typeof h!="function")throw new Error("Callback must be a function.");return t.add(h),h(r),()=>t.delete(h)};return {get:a,set:f,subscribe:i,derive:h=>{if(typeof h!="function")throw new Error("Derive function must be a function.");let l=h(r),y=p(l),m=i(()=>{let D=h(r);y.set(D);}),g=y.destroy;return y.destroy=()=>{m(),g();},y},reset:()=>{r=e,s();},destroy:()=>{t.clear(),r=e,P.delete(o),V.delete(o);}}}function Q(e,n={}){let {initialData:r=null,onError:t,retryCount:o=0,retryDelay:c=1e3,refresh:s={},enabled:a=true}=n,{staleTime:f=0,cacheTime:i=5*60*1e3,refetchInterval:u}=s,T=e.length>0,b={loading:a&&!T,error:null,data:r,lastFetched:void 0},h=d=>T?d===void 0?false:Array.isArray(d)?d.every(x=>x!=null):true:true,l=p(b),y,m=null,g=null,D=()=>{let d=l.get();return d.lastFetched?Date.now()-d.lastFetched>f:true},q=()=>{l.set({...l.get(),data:r,lastFetched:void 0});},K=()=>{g&&clearTimeout(g),i>0&&(g=setTimeout(q,i));},k=async(d,x=o,w=false)=>{if(a){if(d!==void 0&&(y=d),!h(y)){l.set({...l.get(),loading:false});return}if(!(!w&&!D()&&l.get().data!==null&&f>0)){l.set({...l.get(),loading:true,error:null});try{let C=T?await e(...y):await e(),A=Date.now();l.set({loading:!1,error:null,data:C,lastFetched:A}),K();}catch(C){if(x>0)return await new Promise(A=>setTimeout(A,c)),k(d,x-1,w);l.set({loading:false,error:C,data:l.get().data,lastFetched:l.get().lastFetched}),t&&t(C);}}}};u&&u>0&&a&&(m=setInterval(()=>{a&&k(y,0,false);},u)),a&&!T&&k();let j=()=>{m&&(clearInterval(m),m=null),g&&(clearTimeout(g),g=null);};return {...l,reload:async(...d)=>{await k(d.length>0?d:void 0,o,true);},refresh:async(...d)=>{await k(d.length>0?d:void 0,o,false);},mutate:d=>{let x=l.get(),w=d(x.data);l.set({...x,data:w});},reset:()=>{j(),l.set({...b,loading:a}),a&&(k(),u&&u>0&&(m=setInterval(()=>{a&&k(y,0,false);},u)));},cleanup:j,setParams:(...d)=>{y=d,a&&h(d)&&k(d);}}}function X(e,n){let r=e.map(i=>i.get()),t=n(...r),o=p(t),c=o.set,s=false,a=()=>{let i=false;for(let u=0;u<e.length;u++){let T=e[u].get();T!==r[u]&&(r[u]=T,i=true);}if(i){let u=n(...r);u!==t&&(typeof u!="object"||typeof t!="object"||!E(u,t))&&(t=u,c(u)),s=false;}},f=e.map(i=>i.subscribe(()=>{s=true,a();}));return {...o,get:()=>(s&&a(),t),recompute:a,isDirty:()=>s,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(i=>{typeof i.reset=="function"&&i.reset();}),s=true,a(),t),destroy:()=>{f.forEach(i=>i()),o.destroy?.();}}}function O(e,n,r={}){let{useShallowEqual:t=false}=r,o=e.get(),c=n(o),s=p(c),a=()=>{let i=e.get(),u=n(i);o=i,(t?!E(u,c):u!==c)&&(c=u,s.set(u));},f=e.subscribe(a);return {get:()=>s.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:s.subscribe,derive:i=>O(s,i,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{f(),s.destroy();}}}var $={};z($,{logger:()=>R,nonNegativeValidator:()=>I,withHistory:()=>F,withPersistence:()=>H});var R=(e,n)=>{console.log("Setting value:",e),n(e);};var I=(e,n)=>{if(e<0)throw new Error("Value must be non-negative!");n(e);};function F(e,n={}){let{maxHistory:r=100}=n,t=[e.get()],o=0,c=false,s={...e,set:a=>{if(c){e.set(a);return}let f;if(typeof a=="function"){let i=e.get();f=a(i);}else f=a;if(t.splice(o+1),t.push(f),t.length>r){console.warn("History limit reached. Removing oldest entries.");let i=t.length-r;t.splice(0,i),o=Math.max(0,o-i);}o=t.length-1,e.set(f);},undo:()=>{s.canUndo()&&(c=true,o--,s.set(t[o]),c=false);},redo:()=>{s.canRedo()&&(c=true,o++,s.set(t[o]),c=false);},canUndo:()=>o>0,canRedo:()=>o<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let a=e.get();t.length=0,t.push(a),o=0;},destroy:()=>{t.length=0,e.destroy();}};return s}function H(e,n){let{key:r,storage:t=localStorage,serialize:o=JSON.stringify,deserialize:c=JSON.parse}=n;try{let s=t.getItem(r);if(s){let a=c(s);e.set(a);}}catch(s){console.error("Failed to load persisted state:",s);}return e.subscribe(s=>{try{let a=o(s);t.setItem(r,a);}catch(a){console.log("Failed to persist chunk",a);}}),e}export{Q as asyncChunk,G as batch,p as chunk,U as combineAsyncChunks,X as computed,W as isChunk,B as isValidChunkValue,$ as middleware,J as once,O as select};//# sourceMappingURL=index.js.map
|
|
2
|
+
//# sourceMappingURL=index.js.map
|