stunk 2.6.0 → 2.8.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.
@@ -1,5 +1,5 @@
1
1
  type Subscriber<T> = (newValue: T) => void;
2
- type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
2
+ type Middleware<T> = (value: T) => T | undefined;
3
3
  interface Chunk<T> {
4
4
  /** Get the current value of the chunk. */
5
5
  get: () => T;
@@ -0,0 +1,18 @@
1
+ type Subscriber<T> = (newValue: T) => void;
2
+ type Middleware<T> = (value: T) => T | undefined;
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
+ export type { Chunk as C, Middleware as M };
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- 'use strict';var X=Object.defineProperty;var Y=(e,o)=>{for(var n in o)X(e,n,{get:o[n],enumerable:true});};function Z(e){return e!==null}function _(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function ee(e){let o=false,n;return ()=>(o||(n=e(),o=true),n)}function te(e){let o=Object.keys(e).reduce((r,u)=>(r[u]=null,r),{}),n={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(n);return Object.entries(e).forEach(([r,u])=>{u.subscribe(a=>{let c=t.get(),l=false,s=null,d={};Object.entries(e).forEach(([h,w])=>{let p=w.get();p.loading&&(l=true),p.error&&(s||(s=p.error),d[h]=p.error);}),t.set({loading:l,error:s,errors:d,data:{...c.data,[r]:a.data}});});}),t}function $(e,o){if(e===null)throw new Error("Value cannot be null.");let n=e,t=0;for(;t<o.length;){let r=o[t],u=typeof r=="function"?r:r.fn,a=typeof r=="function"?`index ${t}`:r.name||`index ${t}`,c=false,l=null;try{u(n,s=>{c=!0,l=s;});}catch(s){let d=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${d}`)}if(!c)break;if(l===null)throw new Error(`Middleware at index ${t} returned null value.`);n=l,t++;}return n}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==o[n])return false;return true}if(typeof e=="object"&&typeof o=="object"){let n=Object.keys(e),t=Object.keys(o);if(n.length!==t.length)return false;for(let r of n)if(!Object.prototype.hasOwnProperty.call(o,r)||e[r]!==o[r])return false;return true}return false}function D(e,o,n=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${n}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),r=Object.keys(o),u=r.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${n||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",r));for(let a of t)D(e[a],o[a],n?`${n}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function re(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let n=Array.from(R);R.clear(),n.forEach(t=>{let r=O.get(t);r&&r.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let n=e,t=new Set,r=ne++,u=()=>{t.forEach(p=>p(n));};O.set(r,{notify:u});let a=()=>{t.size!==0&&(V?R.add(r):u());},c=()=>n,l=p=>{let y;typeof p=="function"?y=p(n):y=p,D(n,y);let b=$(y,o);b!==n&&(n=b,a());},s=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(n),()=>t.delete(p)};return {get:c,set:l,subscribe:s,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(n),b=k(y),f=s(()=>{let E=p(n);b.set(E);}),g=b.destroy;return b.destroy=()=>{f(),g();},b},reset:()=>{n=e,a();},destroy:()=>{t.clear(),n=e,R.delete(r),O.delete(r);}}}function oe(e,o={}){let{initialData:n=null,onError:t,retryCount:r=0,retryDelay:u=1e3,refresh:a={},pagination:c,enabled:l=true}=o,{staleTime:s=0,cacheTime:d=300*1e3,refetchInterval:h}=a,w=!!c,p=c?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:n,lastFetched:void 0,pagination:w?{page:c.initialPage||1,pageSize:c.pageSize||10}:void 0},f=k(b),g={},E=null,v=null,U=()=>{let i=f.get();return !i.lastFetched||s===0?true:Date.now()-i.lastFetched>s},L=()=>{f.set({...f.get(),data:n,lastFetched:void 0});},G=()=>{v&&clearTimeout(v),d>0&&(v=setTimeout(L,d));},T=async(i,m=r,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!U()&&f.get().data!==null))return;let C=f.get();f.set({...C,loading:true,error:null});try{let S={...g};w&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let x=y?await e(S):await e(),P,I,H;if(x&&typeof x=="object"&&"data"in x){let j=x;P=j.data,I=j.total,H=j.hasMore;}else P=x;w&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(P)&&(P=[...C.data,...P]);let Q=Date.now();f.set({loading:!1,error:null,data:P,lastFetched:Q,pagination:w?{...C.pagination,total:I,hasMore:H}:void 0}),G();}catch(S){if(m>0)return await new Promise(P=>setTimeout(P,u)),T(i,m-1,A);let x=f.get();f.set({loading:false,error:S,data:x.data,lastFetched:x.lastFetched,pagination:x.pagination}),t&&t(S);}};h&&h>0&&l&&(E=setInterval(()=>{l&&T(void 0,0,false);},h)),l&&!y&&T();let F=()=>{E&&(clearInterval(E),E=null),v&&(clearTimeout(v),v=null);},z={...f,reload:async i=>{await T(i,r,true);},refresh:async i=>{await T(i,r,false);},mutate:i=>{let m=f.get(),A=i(m.data);f.set({...m,data:A});},reset:()=>{F(),g={},f.set({...b,loading:l&&!y}),l&&!y&&(T(),h&&h>0&&(E=setInterval(()=>{l&&T(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&T(i,r,true);}};return w?{...z,nextPage:async()=>{let i=f.get();i.pagination&&i.pagination.hasMore!==false&&(f.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await T(g,r,true));},prevPage:async()=>{let i=f.get();!i.pagination||i.pagination.page<=1||(f.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await T(g,r,true));},goToPage:async i=>{let m=f.get();!m.pagination||i<1||(f.set({...m,pagination:{...m.pagination,page:i}}),await T(g,r,true));},resetPagination:async()=>{let i=f.get();if(!i.pagination)return;let m=c?.initialPage||1;f.set({...i,data:p==="accumulate"?n:i.data,pagination:{...i.pagination,page:m}}),await T(g,r,true);}}:z}function ae(e,o){let n=e.map(s=>s.get()),t=o(...n),r=k(t),u=r.set,a=false,c=()=>{let s=false;for(let d=0;d<e.length;d++){let h=e[d].get();h!==n[d]&&(n[d]=h,s=true);}if(s){let d=o(...n);d!==t&&(typeof d!="object"||typeof t!="object"||!M(d,t))&&(t=d,u(d)),a=false;}},l=e.map(s=>s.subscribe(()=>{a=true,c();}));return {...r,get:()=>(a&&c(),t),recompute:c,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(s=>{typeof s.reset=="function"&&s.reset();}),a=true,c(),t),destroy:()=>{l.forEach(s=>s()),r.destroy?.();}}}function N(e,o,n={}){let{useShallowEqual:t=false}=n,r=e.get(),u=o(r),a=k(u),c=()=>{let s=e.get(),d=o(s);r=s,(t?!M(d,u):d!==u)&&(u=d,a.set(d));},l=e.subscribe(c);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:s=>N(a,s,n),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var J={};Y(J,{logger:()=>q,nonNegativeValidator:()=>K,withHistory:()=>W,withPersistence:()=>B});var q=(e,o)=>{console.log("Setting value:",e),o(e);};var K=(e,o)=>{if(e<0)throw new Error("Value must be non-negative!");o(e);};function W(e,o={}){let{maxHistory:n=100}=o,t=[e.get()],r=0,u=false,a={...e,set:c=>{if(u){e.set(c);return}let l;if(typeof c=="function"){let s=e.get();l=c(s);}else l=c;if(t.splice(r+1),t.push(l),t.length>n){console.warn("History limit reached. Removing oldest entries.");let s=t.length-n;t.splice(0,s),r=Math.max(0,r-s);}r=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,r--,a.set(t[r]),u=false);},redo:()=>{a.canRedo()&&(u=true,r++,a.set(t[r]),u=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let c=e.get();t.length=0,t.push(c),r=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function B(e,o){let{key:n,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(n);if(a){let c=u(a);e.set(c);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let c=r(a);t.setItem(n,c);}catch(c){console.log("Failed to persist chunk",c);}}),e}exports.asyncChunk=oe;exports.batch=re;exports.chunk=k;exports.combineAsyncChunks=te;exports.computed=ae;exports.isChunk=_;exports.isValidChunkValue=Z;exports.middleware=J;exports.once=ee;exports.select=N;
1
+ 'use strict';var Y=Object.defineProperty;var Z=(e,o)=>{for(var r in o)Y(e,r,{get:o[r],enumerable:true});};function _(e){return e!==null}function ee(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function te(e){let o=false,r;return ()=>(o||(r=e(),o=true),r)}function re(e){let o=Object.keys(e).reduce((n,u)=>(n[u]=null,n),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(r);return Object.entries(e).forEach(([n,u])=>{u.subscribe(a=>{let s=t.get(),l=false,c=null,f={};Object.entries(e).forEach(([h,x])=>{let p=x.get();p.loading&&(l=true),p.error&&(c||(c=p.error),f[h]=p.error);}),t.set({loading:l,error:c,errors:f,data:{...s.data,[n]:a.data}});});}),t}function N(e,o){if(e===null)throw new Error("Value cannot be null.");let r=e;for(let t=0;t<o.length;t++){let n=o[t],u=typeof n=="function"?n:n.fn,a=typeof n=="function"?`index ${t}`:n.name||`index ${t}`;try{let s=u(r);if(s===void 0)break;if(s===null)throw new Error(`Middleware "${a}" returned null value.`);r=s;}catch(s){let l=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${l}`)}}return r}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==o[r])return false;return true}if(typeof e=="object"&&typeof o=="object"){let r=Object.keys(e),t=Object.keys(o);if(r.length!==t.length)return false;for(let n of r)if(!Object.prototype.hasOwnProperty.call(o,n)||e[n]!==o[n])return false;return true}return false}function D(e,o,r=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),n=Object.keys(o),u=n.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",n));for(let a of t)D(e[a],o[a],r?`${r}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function oe(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let r=Array.from(R);R.clear(),r.forEach(t=>{let n=O.get(t);n&&n.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let r=e,t=new Set,n=ne++,u=()=>{t.forEach(p=>p(r));};O.set(n,{notify:u});let a=()=>{t.size!==0&&(V?R.add(n):u());},s=()=>r,l=p=>{let y;typeof p=="function"?y=p(r):y=p,D(r,y);let b=N(y,o);b!==r&&(r=b,a());},c=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(r),()=>t.delete(p)};return {get:s,set:l,subscribe:c,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(r),b=k(y),d=c(()=>{let w=p(r);b.set(w);}),g=b.destroy;return b.destroy=()=>{d(),g();},b},reset:()=>{r=e,a();},destroy:()=>{t.clear(),r=e,R.delete(n),O.delete(n);}}}function z(e,o={}){let{initialData:r=null,onError:t,retryCount:n=0,retryDelay:u=1e3,refresh:a={},pagination:s,enabled:l=true}=o,{staleTime:c=0,cacheTime:f=300*1e3,refetchInterval:h}=a,x=!!s,p=s?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:r,lastFetched:void 0,pagination:x?{page:s.initialPage||1,pageSize:s.pageSize||10}:void 0},d=k(b),g={},w=null,v=null,L=()=>{let i=d.get();return !i.lastFetched||c===0?true:Date.now()-i.lastFetched>c},G=()=>{d.set({...d.get(),data:r,lastFetched:void 0});},Q=()=>{v&&clearTimeout(v),f>0&&(v=setTimeout(G,f));},m=async(i,T=n,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!L()&&d.get().data!==null))return;let C=d.get();d.set({...C,loading:true,error:null});try{let S={...g};x&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let P=y?await e(S):await e(),E,H,$;if(P&&typeof P=="object"&&"data"in P){let j=P;E=j.data,H=j.total,$=j.hasMore;}else E=P;x&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(E)&&(E=[...C.data,...E]);let X=Date.now();d.set({loading:!1,error:null,data:E,lastFetched:X,pagination:x?{...C.pagination,total:H,hasMore:$}:void 0}),Q();}catch(S){if(T>0)return await new Promise(E=>setTimeout(E,u)),m(i,T-1,A);let P=d.get();d.set({loading:false,error:S,data:P.data,lastFetched:P.lastFetched,pagination:P.pagination}),t&&t(S);}};h&&h>0&&l&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)),l&&!y&&m();let F=()=>{w&&(clearInterval(w),w=null),v&&(clearTimeout(v),v=null);},I={...d,reload:async i=>{await m(i,n,true);},refresh:async i=>{await m(i,n,false);},mutate:i=>{let T=d.get(),A=i(T.data);d.set({...T,data:A});},reset:()=>{F(),g={},d.set({...b,loading:l&&!y}),l&&!y&&(m(),h&&h>0&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&m(i,n,true);}};return x?{...I,nextPage:async()=>{let i=d.get();i.pagination&&i.pagination.hasMore!==false&&(d.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await m(g,n,true));},prevPage:async()=>{let i=d.get();!i.pagination||i.pagination.page<=1||(d.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await m(g,n,true));},goToPage:async i=>{let T=d.get();!T.pagination||i<1||(d.set({...T,pagination:{...T.pagination,page:i}}),await m(g,n,true));},resetPagination:async()=>{let i=d.get();if(!i.pagination)return;let T=s?.initialPage||1;d.set({...i,data:p==="accumulate"?r:i.data,pagination:{...i.pagination,page:T}}),await m(g,n,true);}}:I}function ae(e,o={}){let{pageSize:r=10,staleTime:t,cacheTime:n,retryCount:u,retryDelay:a,onError:s}=o;return z(e,{pagination:{pageSize:r,mode:"accumulate",initialPage:1},refresh:{staleTime:t,cacheTime:n},retryCount:u,retryDelay:a,onError:s})}function se(e,o){let r=e.map(c=>c.get()),t=o(...r),n=k(t),u=n.set,a=false,s=()=>{let c=false;for(let f=0;f<e.length;f++){let h=e[f].get();h!==r[f]&&(r[f]=h,c=true);}if(c){let f=o(...r);f!==t&&(typeof f!="object"||typeof t!="object"||!M(f,t))&&(t=f,u(f)),a=false;}},l=e.map(c=>c.subscribe(()=>{a=true,s();}));return {...n,get:()=>(a&&s(),t),recompute:s,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(c=>{typeof c.reset=="function"&&c.reset();}),a=true,s(),t),destroy:()=>{l.forEach(c=>c()),n.destroy?.();}}}function q(e,o,r={}){let{useShallowEqual:t=false}=r,n=e.get(),u=o(n),a=k(u),s=()=>{let c=e.get(),f=o(c);n=c,(t?!M(f,u):f!==u)&&(u=f,a.set(f));},l=e.subscribe(s);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:c=>q(a,c,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var U={};Z(U,{logger:()=>K,nonNegativeValidator:()=>W,withHistory:()=>B,withPersistence:()=>J});var K=e=>(console.log("Setting value:",e),e);var W=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function B(e,o={}){let{maxHistory:r=100}=o,t=[e.get()],n=0,u=false,a={...e,set:s=>{if(u){e.set(s);return}let l;if(typeof s=="function"){let c=e.get();l=s(c);}else l=s;if(t.splice(n+1),t.push(l),t.length>r){console.warn("History limit reached. Removing oldest entries.");let c=t.length-r;t.splice(0,c),n=Math.max(0,n-c);}n=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,n--,a.set(t[n]),u=false);},redo:()=>{a.canRedo()&&(u=true,n++,a.set(t[n]),u=false);},canUndo:()=>n>0,canRedo:()=>n<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let s=e.get();t.length=0,t.push(s),n=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function J(e,o){let{key:r,storage:t=localStorage,serialize:n=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(r);if(a){let s=u(a);e.set(s);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let s=n(a);t.setItem(r,s);}catch(s){console.log("Failed to persist chunk",s);}}),e}exports.asyncChunk=z;exports.batch=oe;exports.chunk=k;exports.combineAsyncChunks=re;exports.computed=se;exports.infiniteAsyncChunk=ae;exports.isChunk=ee;exports.isValidChunkValue=_;exports.middleware=U;exports.once=te;exports.select=q;
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  type Subscriber<T> = (newValue: T) => void;
2
- type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
2
+ type Middleware<T> = (value: T) => T | undefined;
3
3
  type NamedMiddleware<T> = {
4
4
  name?: string;
5
5
  fn: Middleware<T>;
@@ -118,6 +118,37 @@ declare function asyncChunk<T, E extends Error = Error, P extends Record<string,
118
118
  refresh: (params?: Partial<P>) => Promise<void>;
119
119
  };
120
120
 
121
+ interface InfiniteAsyncChunkOptions<T, E extends Error> {
122
+ /** Initial page size (default: 10) */
123
+ pageSize?: number;
124
+ /** Time in ms after which data becomes stale */
125
+ staleTime?: number;
126
+ /** Time in ms to cache data */
127
+ cacheTime?: number;
128
+ /** Retry count on error */
129
+ retryCount?: number;
130
+ /** Delay between retries in ms */
131
+ retryDelay?: number;
132
+ /** Error callback */
133
+ onError?: (error: E) => void;
134
+ }
135
+ /**
136
+ * Create an infinite scroll async chunk with accumulate mode.
137
+ * Automatically handles pagination in accumulate mode for infinite scrolling.
138
+ */
139
+ declare function infiniteAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(fetcher: (params: P & {
140
+ page: number;
141
+ pageSize: number;
142
+ }) => Promise<{
143
+ data: T[];
144
+ hasMore?: boolean;
145
+ total?: number;
146
+ }>, options?: InfiniteAsyncChunkOptions<T, E>): PaginatedAsyncChunk<T[], E> & {
147
+ setParams: (params: Partial<P>) => void;
148
+ reload: (params?: Partial<P>) => Promise<void>;
149
+ refresh: (params?: Partial<P>) => Promise<void>;
150
+ };
151
+
121
152
  type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
122
153
  type DependencyValues<T extends Chunk<any>[]> = {
123
154
  [K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
@@ -209,4 +240,4 @@ declare namespace index {
209
240
  export { index_logger as logger, index_nonNegativeValidator as nonNegativeValidator, index_withHistory as withHistory, index_withPersistence as withPersistence };
210
241
  }
211
242
 
212
- export { type Chunk, type Middleware, asyncChunk, batch, chunk, combineAsyncChunks, computed, isChunk, isValidChunkValue, index as middleware, once, select };
243
+ export { type AsyncChunk, type AsyncState, type AsyncStateWithPagination, type Chunk, type Middleware, type PaginatedAsyncChunk, asyncChunk, batch, chunk, combineAsyncChunks, computed, infiniteAsyncChunk, isChunk, isValidChunkValue, index as middleware, once, select };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  type Subscriber<T> = (newValue: T) => void;
2
- type Middleware<T> = (value: T, next: (newValue: T) => void) => void;
2
+ type Middleware<T> = (value: T) => T | undefined;
3
3
  type NamedMiddleware<T> = {
4
4
  name?: string;
5
5
  fn: Middleware<T>;
@@ -118,6 +118,37 @@ declare function asyncChunk<T, E extends Error = Error, P extends Record<string,
118
118
  refresh: (params?: Partial<P>) => Promise<void>;
119
119
  };
120
120
 
121
+ interface InfiniteAsyncChunkOptions<T, E extends Error> {
122
+ /** Initial page size (default: 10) */
123
+ pageSize?: number;
124
+ /** Time in ms after which data becomes stale */
125
+ staleTime?: number;
126
+ /** Time in ms to cache data */
127
+ cacheTime?: number;
128
+ /** Retry count on error */
129
+ retryCount?: number;
130
+ /** Delay between retries in ms */
131
+ retryDelay?: number;
132
+ /** Error callback */
133
+ onError?: (error: E) => void;
134
+ }
135
+ /**
136
+ * Create an infinite scroll async chunk with accumulate mode.
137
+ * Automatically handles pagination in accumulate mode for infinite scrolling.
138
+ */
139
+ declare function infiniteAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(fetcher: (params: P & {
140
+ page: number;
141
+ pageSize: number;
142
+ }) => Promise<{
143
+ data: T[];
144
+ hasMore?: boolean;
145
+ total?: number;
146
+ }>, options?: InfiniteAsyncChunkOptions<T, E>): PaginatedAsyncChunk<T[], E> & {
147
+ setParams: (params: Partial<P>) => void;
148
+ reload: (params?: Partial<P>) => Promise<void>;
149
+ refresh: (params?: Partial<P>) => Promise<void>;
150
+ };
151
+
121
152
  type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
122
153
  type DependencyValues<T extends Chunk<any>[]> = {
123
154
  [K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
@@ -209,4 +240,4 @@ declare namespace index {
209
240
  export { index_logger as logger, index_nonNegativeValidator as nonNegativeValidator, index_withHistory as withHistory, index_withPersistence as withPersistence };
210
241
  }
211
242
 
212
- export { type Chunk, type Middleware, asyncChunk, batch, chunk, combineAsyncChunks, computed, isChunk, isValidChunkValue, index as middleware, once, select };
243
+ export { type AsyncChunk, type AsyncState, type AsyncStateWithPagination, type Chunk, type Middleware, type PaginatedAsyncChunk, asyncChunk, batch, chunk, combineAsyncChunks, computed, infiniteAsyncChunk, isChunk, isValidChunkValue, index as middleware, once, select };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var X=Object.defineProperty;var Y=(e,o)=>{for(var n in o)X(e,n,{get:o[n],enumerable:true});};function Z(e){return e!==null}function _(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function ee(e){let o=false,n;return ()=>(o||(n=e(),o=true),n)}function te(e){let o=Object.keys(e).reduce((r,u)=>(r[u]=null,r),{}),n={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(n);return Object.entries(e).forEach(([r,u])=>{u.subscribe(a=>{let c=t.get(),l=false,s=null,d={};Object.entries(e).forEach(([h,w])=>{let p=w.get();p.loading&&(l=true),p.error&&(s||(s=p.error),d[h]=p.error);}),t.set({loading:l,error:s,errors:d,data:{...c.data,[r]:a.data}});});}),t}function $(e,o){if(e===null)throw new Error("Value cannot be null.");let n=e,t=0;for(;t<o.length;){let r=o[t],u=typeof r=="function"?r:r.fn,a=typeof r=="function"?`index ${t}`:r.name||`index ${t}`,c=false,l=null;try{u(n,s=>{c=!0,l=s;});}catch(s){let d=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${d}`)}if(!c)break;if(l===null)throw new Error(`Middleware at index ${t} returned null value.`);n=l,t++;}return n}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let n=0;n<e.length;n++)if(e[n]!==o[n])return false;return true}if(typeof e=="object"&&typeof o=="object"){let n=Object.keys(e),t=Object.keys(o);if(n.length!==t.length)return false;for(let r of n)if(!Object.prototype.hasOwnProperty.call(o,r)||e[r]!==o[r])return false;return true}return false}function D(e,o,n=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${n}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),r=Object.keys(o),u=r.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${n||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",r));for(let a of t)D(e[a],o[a],n?`${n}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function re(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let n=Array.from(R);R.clear(),n.forEach(t=>{let r=O.get(t);r&&r.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let n=e,t=new Set,r=ne++,u=()=>{t.forEach(p=>p(n));};O.set(r,{notify:u});let a=()=>{t.size!==0&&(V?R.add(r):u());},c=()=>n,l=p=>{let y;typeof p=="function"?y=p(n):y=p,D(n,y);let b=$(y,o);b!==n&&(n=b,a());},s=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(n),()=>t.delete(p)};return {get:c,set:l,subscribe:s,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(n),b=k(y),f=s(()=>{let E=p(n);b.set(E);}),g=b.destroy;return b.destroy=()=>{f(),g();},b},reset:()=>{n=e,a();},destroy:()=>{t.clear(),n=e,R.delete(r),O.delete(r);}}}function oe(e,o={}){let{initialData:n=null,onError:t,retryCount:r=0,retryDelay:u=1e3,refresh:a={},pagination:c,enabled:l=true}=o,{staleTime:s=0,cacheTime:d=300*1e3,refetchInterval:h}=a,w=!!c,p=c?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:n,lastFetched:void 0,pagination:w?{page:c.initialPage||1,pageSize:c.pageSize||10}:void 0},f=k(b),g={},E=null,v=null,U=()=>{let i=f.get();return !i.lastFetched||s===0?true:Date.now()-i.lastFetched>s},L=()=>{f.set({...f.get(),data:n,lastFetched:void 0});},G=()=>{v&&clearTimeout(v),d>0&&(v=setTimeout(L,d));},T=async(i,m=r,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!U()&&f.get().data!==null))return;let C=f.get();f.set({...C,loading:true,error:null});try{let S={...g};w&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let x=y?await e(S):await e(),P,I,H;if(x&&typeof x=="object"&&"data"in x){let j=x;P=j.data,I=j.total,H=j.hasMore;}else P=x;w&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(P)&&(P=[...C.data,...P]);let Q=Date.now();f.set({loading:!1,error:null,data:P,lastFetched:Q,pagination:w?{...C.pagination,total:I,hasMore:H}:void 0}),G();}catch(S){if(m>0)return await new Promise(P=>setTimeout(P,u)),T(i,m-1,A);let x=f.get();f.set({loading:false,error:S,data:x.data,lastFetched:x.lastFetched,pagination:x.pagination}),t&&t(S);}};h&&h>0&&l&&(E=setInterval(()=>{l&&T(void 0,0,false);},h)),l&&!y&&T();let F=()=>{E&&(clearInterval(E),E=null),v&&(clearTimeout(v),v=null);},z={...f,reload:async i=>{await T(i,r,true);},refresh:async i=>{await T(i,r,false);},mutate:i=>{let m=f.get(),A=i(m.data);f.set({...m,data:A});},reset:()=>{F(),g={},f.set({...b,loading:l&&!y}),l&&!y&&(T(),h&&h>0&&(E=setInterval(()=>{l&&T(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&T(i,r,true);}};return w?{...z,nextPage:async()=>{let i=f.get();i.pagination&&i.pagination.hasMore!==false&&(f.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await T(g,r,true));},prevPage:async()=>{let i=f.get();!i.pagination||i.pagination.page<=1||(f.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await T(g,r,true));},goToPage:async i=>{let m=f.get();!m.pagination||i<1||(f.set({...m,pagination:{...m.pagination,page:i}}),await T(g,r,true));},resetPagination:async()=>{let i=f.get();if(!i.pagination)return;let m=c?.initialPage||1;f.set({...i,data:p==="accumulate"?n:i.data,pagination:{...i.pagination,page:m}}),await T(g,r,true);}}:z}function ae(e,o){let n=e.map(s=>s.get()),t=o(...n),r=k(t),u=r.set,a=false,c=()=>{let s=false;for(let d=0;d<e.length;d++){let h=e[d].get();h!==n[d]&&(n[d]=h,s=true);}if(s){let d=o(...n);d!==t&&(typeof d!="object"||typeof t!="object"||!M(d,t))&&(t=d,u(d)),a=false;}},l=e.map(s=>s.subscribe(()=>{a=true,c();}));return {...r,get:()=>(a&&c(),t),recompute:c,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(s=>{typeof s.reset=="function"&&s.reset();}),a=true,c(),t),destroy:()=>{l.forEach(s=>s()),r.destroy?.();}}}function N(e,o,n={}){let{useShallowEqual:t=false}=n,r=e.get(),u=o(r),a=k(u),c=()=>{let s=e.get(),d=o(s);r=s,(t?!M(d,u):d!==u)&&(u=d,a.set(d));},l=e.subscribe(c);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:s=>N(a,s,n),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var J={};Y(J,{logger:()=>q,nonNegativeValidator:()=>K,withHistory:()=>W,withPersistence:()=>B});var q=(e,o)=>{console.log("Setting value:",e),o(e);};var K=(e,o)=>{if(e<0)throw new Error("Value must be non-negative!");o(e);};function W(e,o={}){let{maxHistory:n=100}=o,t=[e.get()],r=0,u=false,a={...e,set:c=>{if(u){e.set(c);return}let l;if(typeof c=="function"){let s=e.get();l=c(s);}else l=c;if(t.splice(r+1),t.push(l),t.length>n){console.warn("History limit reached. Removing oldest entries.");let s=t.length-n;t.splice(0,s),r=Math.max(0,r-s);}r=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,r--,a.set(t[r]),u=false);},redo:()=>{a.canRedo()&&(u=true,r++,a.set(t[r]),u=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let c=e.get();t.length=0,t.push(c),r=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function B(e,o){let{key:n,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(n);if(a){let c=u(a);e.set(c);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let c=r(a);t.setItem(n,c);}catch(c){console.log("Failed to persist chunk",c);}}),e}export{oe as asyncChunk,re as batch,k as chunk,te as combineAsyncChunks,ae as computed,_ as isChunk,Z as isValidChunkValue,J as middleware,ee as once,N as select};
1
+ var Y=Object.defineProperty;var Z=(e,o)=>{for(var r in o)Y(e,r,{get:o[r],enumerable:true});};function _(e){return e!==null}function ee(e){if(!e||typeof e!="object")return false;let o=e;return ["get","set","subscribe","derive","reset","destroy"].every(t=>typeof o[t]=="function")}function te(e){let o=false,r;return ()=>(o||(r=e(),o=true),r)}function re(e){let o=Object.keys(e).reduce((n,u)=>(n[u]=null,n),{}),r={loading:Object.keys(e).length>0,error:null,errors:{},data:o},t=k(r);return Object.entries(e).forEach(([n,u])=>{u.subscribe(a=>{let s=t.get(),l=false,c=null,f={};Object.entries(e).forEach(([h,x])=>{let p=x.get();p.loading&&(l=true),p.error&&(c||(c=p.error),f[h]=p.error);}),t.set({loading:l,error:c,errors:f,data:{...s.data,[n]:a.data}});});}),t}function N(e,o){if(e===null)throw new Error("Value cannot be null.");let r=e;for(let t=0;t<o.length;t++){let n=o[t],u=typeof n=="function"?n:n.fn,a=typeof n=="function"?`index ${t}`:n.name||`index ${t}`;try{let s=u(r);if(s===void 0)break;if(s===null)throw new Error(`Middleware "${a}" returned null value.`);r=s;}catch(s){let l=s instanceof Error?s.message:String(s);throw new Error(`Middleware "${a}" threw an error: ${l}`)}}return r}function M(e,o){if(e===o)return true;if(!e||!o||typeof e!=typeof o)return false;if(Array.isArray(e)&&Array.isArray(o)){if(e.length!==o.length)return false;for(let r=0;r<e.length;r++)if(e[r]!==o[r])return false;return true}if(typeof e=="object"&&typeof o=="object"){let r=Object.keys(e),t=Object.keys(o);if(r.length!==t.length)return false;for(let n of r)if(!Object.prototype.hasOwnProperty.call(o,n)||e[n]!==o[n])return false;return true}return false}function D(e,o,r=""){if(typeof e=="object"&&e!==null&&typeof o=="object"&&o!==null){if(Array.isArray(e)&&Array.isArray(o)){if(e.length>0&&typeof e[0]=="object")for(let t=0;t<o.length;t++)D(e[0],o[t],`${r}[${t}]`);}else if(!Array.isArray(e)&&!Array.isArray(o)){let t=Object.keys(e),n=Object.keys(o),u=n.filter(a=>!t.includes(a));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${r||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",t),console.error("Received keys:",n));for(let a of t)D(e[a],o[a],r?`${r}.${a}`:a);}}}var V=false,R=new Set,O=new Map,ne=0;function oe(e){let o=V;V=true;try{e();}finally{if(!o){V=false;let r=Array.from(R);R.clear(),r.forEach(t=>{let n=O.get(t);n&&n.notify();});}}}function k(e,o=[]){if(e===null)throw new Error("Initial value cannot be null.");let r=e,t=new Set,n=ne++,u=()=>{t.forEach(p=>p(r));};O.set(n,{notify:u});let a=()=>{t.size!==0&&(V?R.add(n):u());},s=()=>r,l=p=>{let y;typeof p=="function"?y=p(r):y=p,D(r,y);let b=N(y,o);b!==r&&(r=b,a());},c=p=>{if(typeof p!="function")throw new Error("Callback must be a function.");return t.add(p),p(r),()=>t.delete(p)};return {get:s,set:l,subscribe:c,derive:p=>{if(typeof p!="function")throw new Error("Derive function must be a function.");let y=p(r),b=k(y),d=c(()=>{let w=p(r);b.set(w);}),g=b.destroy;return b.destroy=()=>{d(),g();},b},reset:()=>{r=e,a();},destroy:()=>{t.clear(),r=e,R.delete(n),O.delete(n);}}}function z(e,o={}){let{initialData:r=null,onError:t,retryCount:n=0,retryDelay:u=1e3,refresh:a={},pagination:s,enabled:l=true}=o,{staleTime:c=0,cacheTime:f=300*1e3,refetchInterval:h}=a,x=!!s,p=s?.mode||"replace",y=e.length>0,b={loading:l&&!y,error:null,data:r,lastFetched:void 0,pagination:x?{page:s.initialPage||1,pageSize:s.pageSize||10}:void 0},d=k(b),g={},w=null,v=null,L=()=>{let i=d.get();return !i.lastFetched||c===0?true:Date.now()-i.lastFetched>c},G=()=>{d.set({...d.get(),data:r,lastFetched:void 0});},Q=()=>{v&&clearTimeout(v),f>0&&(v=setTimeout(G,f));},m=async(i,T=n,A=false)=>{if(!l||(i!==void 0&&(g={...g,...i}),!A&&!L()&&d.get().data!==null))return;let C=d.get();d.set({...C,loading:true,error:null});try{let S={...g};x&&C.pagination&&(S.page=C.pagination.page,S.pageSize=C.pagination.pageSize);let P=y?await e(S):await e(),E,H,$;if(P&&typeof P=="object"&&"data"in P){let j=P;E=j.data,H=j.total,$=j.hasMore;}else E=P;x&&p==="accumulate"&&C.data&&Array.isArray(C.data)&&Array.isArray(E)&&(E=[...C.data,...E]);let X=Date.now();d.set({loading:!1,error:null,data:E,lastFetched:X,pagination:x?{...C.pagination,total:H,hasMore:$}:void 0}),Q();}catch(S){if(T>0)return await new Promise(E=>setTimeout(E,u)),m(i,T-1,A);let P=d.get();d.set({loading:false,error:S,data:P.data,lastFetched:P.lastFetched,pagination:P.pagination}),t&&t(S);}};h&&h>0&&l&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)),l&&!y&&m();let F=()=>{w&&(clearInterval(w),w=null),v&&(clearTimeout(v),v=null);},I={...d,reload:async i=>{await m(i,n,true);},refresh:async i=>{await m(i,n,false);},mutate:i=>{let T=d.get(),A=i(T.data);d.set({...T,data:A});},reset:()=>{F(),g={},d.set({...b,loading:l&&!y}),l&&!y&&(m(),h&&h>0&&(w=setInterval(()=>{l&&m(void 0,0,false);},h)));},cleanup:F,setParams:i=>{g={...g,...i},l&&m(i,n,true);}};return x?{...I,nextPage:async()=>{let i=d.get();i.pagination&&i.pagination.hasMore!==false&&(d.set({...i,pagination:{...i.pagination,page:i.pagination.page+1}}),await m(g,n,true));},prevPage:async()=>{let i=d.get();!i.pagination||i.pagination.page<=1||(d.set({...i,pagination:{...i.pagination,page:i.pagination.page-1}}),await m(g,n,true));},goToPage:async i=>{let T=d.get();!T.pagination||i<1||(d.set({...T,pagination:{...T.pagination,page:i}}),await m(g,n,true));},resetPagination:async()=>{let i=d.get();if(!i.pagination)return;let T=s?.initialPage||1;d.set({...i,data:p==="accumulate"?r:i.data,pagination:{...i.pagination,page:T}}),await m(g,n,true);}}:I}function ae(e,o={}){let{pageSize:r=10,staleTime:t,cacheTime:n,retryCount:u,retryDelay:a,onError:s}=o;return z(e,{pagination:{pageSize:r,mode:"accumulate",initialPage:1},refresh:{staleTime:t,cacheTime:n},retryCount:u,retryDelay:a,onError:s})}function se(e,o){let r=e.map(c=>c.get()),t=o(...r),n=k(t),u=n.set,a=false,s=()=>{let c=false;for(let f=0;f<e.length;f++){let h=e[f].get();h!==r[f]&&(r[f]=h,c=true);}if(c){let f=o(...r);f!==t&&(typeof f!="object"||typeof t!="object"||!M(f,t))&&(t=f,u(f)),a=false;}},l=e.map(c=>c.subscribe(()=>{a=true,s();}));return {...n,get:()=>(a&&s(),t),recompute:s,isDirty:()=>a,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(c=>{typeof c.reset=="function"&&c.reset();}),a=true,s(),t),destroy:()=>{l.forEach(c=>c()),n.destroy?.();}}}function q(e,o,r={}){let{useShallowEqual:t=false}=r,n=e.get(),u=o(n),a=k(u),s=()=>{let c=e.get(),f=o(c);n=c,(t?!M(f,u):f!==u)&&(u=f,a.set(f));},l=e.subscribe(s);return {get:()=>a.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:a.subscribe,derive:c=>q(a,c,r),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),a.destroy();}}}var U={};Z(U,{logger:()=>K,nonNegativeValidator:()=>W,withHistory:()=>B,withPersistence:()=>J});var K=e=>(console.log("Setting value:",e),e);var W=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function B(e,o={}){let{maxHistory:r=100}=o,t=[e.get()],n=0,u=false,a={...e,set:s=>{if(u){e.set(s);return}let l;if(typeof s=="function"){let c=e.get();l=s(c);}else l=s;if(t.splice(n+1),t.push(l),t.length>r){console.warn("History limit reached. Removing oldest entries.");let c=t.length-r;t.splice(0,c),n=Math.max(0,n-c);}n=t.length-1,e.set(l);},undo:()=>{a.canUndo()&&(u=true,n--,a.set(t[n]),u=false);},redo:()=>{a.canRedo()&&(u=true,n++,a.set(t[n]),u=false);},canUndo:()=>n>0,canRedo:()=>n<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let s=e.get();t.length=0,t.push(s),n=0;},destroy:()=>{t.length=0,e.destroy();}};return a}function J(e,o){let{key:r,storage:t=localStorage,serialize:n=JSON.stringify,deserialize:u=JSON.parse}=o;try{let a=t.getItem(r);if(a){let s=u(a);e.set(s);}}catch(a){console.error("Failed to load persisted state:",a);}return e.subscribe(a=>{try{let s=n(a);t.setItem(r,s);}catch(s){console.log("Failed to persist chunk",s);}}),e}export{z as asyncChunk,oe as batch,k as chunk,re as combineAsyncChunks,se as computed,ae as infiniteAsyncChunk,ee as isChunk,_ as isValidChunkValue,U as middleware,te as once,q as select};
@@ -0,0 +1 @@
1
+ 'use strict';var d=e=>(console.log("Setting value:",e),e);var u=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function g(e,a={}){let{maxHistory:s=100}=a,t=[e.get()],r=0,n=false,o={...e,set:i=>{if(n){e.set(i);return}let l;if(typeof i=="function"){let c=e.get();l=i(c);}else l=i;if(t.splice(r+1),t.push(l),t.length>s){console.warn("History limit reached. Removing oldest entries.");let c=t.length-s;t.splice(0,c),r=Math.max(0,r-c);}r=t.length-1,e.set(l);},undo:()=>{o.canUndo()&&(n=true,r--,o.set(t[r]),n=false);},redo:()=>{o.canRedo()&&(n=true,r++,o.set(t[r]),n=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let i=e.get();t.length=0,t.push(i),r=0;},destroy:()=>{t.length=0,e.destroy();}};return o}function h(e,a){let{key:s,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:n=JSON.parse}=a;try{let o=t.getItem(s);if(o){let i=n(o);e.set(i);}}catch(o){console.error("Failed to load persisted state:",o);}return e.subscribe(o=>{try{let i=r(o);t.setItem(s,i);}catch(i){console.log("Failed to persist chunk",i);}}),e}exports.logger=d;exports.nonNegativeValidator=u;exports.withHistory=g;exports.withPersistence=h;
@@ -0,0 +1,45 @@
1
+ import { M as Middleware, C as Chunk } from '../core-DMY69lzg.cjs';
2
+
3
+ declare const logger: Middleware<any>;
4
+
5
+ declare const nonNegativeValidator: Middleware<number>;
6
+
7
+ interface ChunkWithHistory<T> extends Chunk<T> {
8
+ /**
9
+ * Reverts to the previous state (if available).
10
+ */
11
+ undo: () => void;
12
+ /**
13
+ * Moves to the next state (if available).
14
+ */
15
+ redo: () => void;
16
+ /**
17
+ * Returns true if there is a previous state to revert to.
18
+ */
19
+ canUndo: () => boolean;
20
+ /**
21
+ * Returns true if there is a next state to move to.
22
+ */
23
+ canRedo: () => boolean;
24
+ /**
25
+ * Returns an array of all the values in the history.
26
+ */
27
+ getHistory: () => T[];
28
+ /**
29
+ * Clears the history, keeping only the current value.
30
+ */
31
+ clearHistory: () => void;
32
+ }
33
+ declare function withHistory<T>(baseChunk: Chunk<T>, options?: {
34
+ maxHistory?: number;
35
+ }): ChunkWithHistory<T>;
36
+
37
+ interface PersistOptions<T> {
38
+ key: string;
39
+ storage?: Storage;
40
+ serialize?: (value: T) => string;
41
+ deserialize?: (value: string) => T;
42
+ }
43
+ declare function withPersistence<T>(baseChunk: Chunk<T>, options: PersistOptions<T>): Chunk<T>;
44
+
45
+ export { logger, nonNegativeValidator, withHistory, withPersistence };
@@ -1,4 +1,4 @@
1
- import { M as Middleware, C as Chunk } from '../core-C7jFiHdO.js';
1
+ import { M as Middleware, C as Chunk } from '../core-DMY69lzg.js';
2
2
 
3
3
  declare const logger: Middleware<any>;
4
4
 
@@ -1 +1 @@
1
- var d=(e,n)=>{console.log("Setting value:",e),n(e);};var u=(e,n)=>{if(e<0)throw new Error("Value must be non-negative!");n(e);};function g(e,n={}){let{maxHistory:l=100}=n,t=[e.get()],r=0,s=false,o={...e,set:i=>{if(s){e.set(i);return}let c;if(typeof i=="function"){let a=e.get();c=i(a);}else c=i;if(t.splice(r+1),t.push(c),t.length>l){console.warn("History limit reached. Removing oldest entries.");let a=t.length-l;t.splice(0,a),r=Math.max(0,r-a);}r=t.length-1,e.set(c);},undo:()=>{o.canUndo()&&(s=true,r--,o.set(t[r]),s=false);},redo:()=>{o.canRedo()&&(s=true,r++,o.set(t[r]),s=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let i=e.get();t.length=0,t.push(i),r=0;},destroy:()=>{t.length=0,e.destroy();}};return o}function h(e,n){let{key:l,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:s=JSON.parse}=n;try{let o=t.getItem(l);if(o){let i=s(o);e.set(i);}}catch(o){console.error("Failed to load persisted state:",o);}return e.subscribe(o=>{try{let i=r(o);t.setItem(l,i);}catch(i){console.log("Failed to persist chunk",i);}}),e}export{d as logger,u as nonNegativeValidator,g as withHistory,h as withPersistence};
1
+ var d=e=>(console.log("Setting value:",e),e);var u=e=>{if(e<0)throw new Error("Value must be non-negative!");return e};function g(e,a={}){let{maxHistory:s=100}=a,t=[e.get()],r=0,n=false,o={...e,set:i=>{if(n){e.set(i);return}let l;if(typeof i=="function"){let c=e.get();l=i(c);}else l=i;if(t.splice(r+1),t.push(l),t.length>s){console.warn("History limit reached. Removing oldest entries.");let c=t.length-s;t.splice(0,c),r=Math.max(0,r-c);}r=t.length-1,e.set(l);},undo:()=>{o.canUndo()&&(n=true,r--,o.set(t[r]),n=false);},redo:()=>{o.canRedo()&&(n=true,r++,o.set(t[r]),n=false);},canUndo:()=>r>0,canRedo:()=>r<t.length-1,getHistory:()=>[...t],clearHistory:()=>{let i=e.get();t.length=0,t.push(i),r=0;},destroy:()=>{t.length=0,e.destroy();}};return o}function h(e,a){let{key:s,storage:t=localStorage,serialize:r=JSON.stringify,deserialize:n=JSON.parse}=a;try{let o=t.getItem(s);if(o){let i=n(o);e.set(i);}}catch(o){console.error("Failed to load persisted state:",o);}return e.subscribe(o=>{try{let i=r(o);t.setItem(s,i);}catch(i){console.log("Failed to persist chunk",i);}}),e}export{d as logger,u as nonNegativeValidator,g as withHistory,h as withPersistence};
@@ -0,0 +1 @@
1
+ 'use strict';var react=require('react');var S=new Set,D=new Map,j=0;function P(e,r=[]){if(e===null)throw new Error("Initial value cannot be null.");let t=e,n=new Set,s=j++,i=()=>{n.forEach(f=>f(t));};D.set(s,{notify:i});let o=()=>{n.size!==0&&(i());},u=()=>t,l=f=>{let h;typeof f=="function"?h=f(t):h=f,b(t,h);let p=M(h,r);p!==t&&(t=p,o());},a=f=>{if(typeof f!="function")throw new Error("Callback must be a function.");return n.add(f),f(t),()=>n.delete(f)};return {get:u,set:l,subscribe:a,derive:f=>{if(typeof f!="function")throw new Error("Derive function must be a function.");let h=f(t),p=P(h),m=a(()=>{let k=f(t);p.set(k);}),d=p.destroy;return p.destroy=()=>{m(),d();},p},reset:()=>{t=e,o();},destroy:()=>{n.clear(),t=e,S.delete(s),D.delete(s);}}}function M(e,r){if(e===null)throw new Error("Value cannot be null.");let t=e;for(let n=0;n<r.length;n++){let s=r[n],i=typeof s=="function"?s:s.fn,o=typeof s=="function"?`index ${n}`:s.name||`index ${n}`;try{let u=i(t);if(u===void 0)break;if(u===null)throw new Error(`Middleware "${o}" returned null value.`);t=u;}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Middleware "${o}" threw an error: ${l}`)}}return t}function E(e,r){if(e===r)return true;if(!e||!r||typeof e!=typeof r)return false;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return false;for(let t=0;t<e.length;t++)if(e[t]!==r[t])return false;return true}if(typeof e=="object"&&typeof r=="object"){let t=Object.keys(e),n=Object.keys(r);if(t.length!==n.length)return false;for(let s of t)if(!Object.prototype.hasOwnProperty.call(r,s)||e[s]!==r[s])return false;return true}return false}function b(e,r,t=""){if(typeof e=="object"&&e!==null&&typeof r=="object"&&r!==null){if(Array.isArray(e)&&Array.isArray(r)){if(e.length>0&&typeof e[0]=="object")for(let n=0;n<r.length;n++)b(e[0],r[n],`${t}[${n}]`);}else if(!Array.isArray(e)&&!Array.isArray(r)){let n=Object.keys(e),s=Object.keys(r),i=s.filter(o=>!n.includes(o));i.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${t||"root"}': ${i.join(", ")}. This might cause bugs.`),console.error("Expected keys:",n),console.error("Received keys:",s));for(let o of n)b(e[o],r[o],t?`${t}.${o}`:o);}}}function x(e,r,t={}){let{useShallowEqual:n=false}=t,s=e.get(),i=r(s),o=P(i),u=()=>{let a=e.get(),c=r(a);s=a,(n?!E(c,i):c!==i)&&(i=c,o.set(c));},l=e.subscribe(u);return {get:()=>o.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:o.subscribe,derive:a=>x(o,a,t),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),o.destroy();}}}function C(e,r){let t=r?x(e,r):e,[n,s]=react.useState(()=>t.get());react.useEffect(()=>{let l=t.subscribe(a=>{s(()=>a);});return ()=>l()},[t]);let i=react.useCallback(l=>{e.set(l);},[e]),o=react.useCallback(()=>{e.reset();},[e]),u=react.useCallback(()=>{e.destroy();},[e]);return [n,i,o,u]}function F(e,r){let t=react.useRef(r);react.useEffect(()=>{t.current=r;},[r]);let n=react.useMemo(()=>e.derive(i=>t.current(i)),[e]),[s]=C(n);return s}function O(e,r){let t=e.map(a=>a.get()),n=r(...t),s=P(n),i=s.set,o=false,u=()=>{let a=false;for(let c=0;c<e.length;c++){let T=e[c].get();T!==t[c]&&(t[c]=T,a=true);}if(a){let c=r(...t);c!==n&&(typeof c!="object"||typeof n!="object"||!E(c,n))&&(n=c,i(c)),o=false;}},l=e.map(a=>a.subscribe(()=>{o=true,u();}));return {...s,get:()=>(o&&u(),n),recompute:u,isDirty:()=>o,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(a=>{typeof a.reset=="function"&&a.reset();}),o=true,u(),n),destroy:()=>{l.forEach(a=>a()),s.destroy?.();}}}function L(e,r){let t=react.useMemo(()=>O(e,r),[...e]),[n,s]=react.useState(()=>t.get());return react.useEffect(()=>{let i=t.subscribe(o=>{s(o);});return ()=>{i();}},[t]),n}function v(e,r){let[t]=C(e,r);return t}function G(e,r){let t=react.useMemo(()=>n=>n[r],[r]);return v(e,t)}function X(e){let[r,t]=react.useState(()=>e.map(n=>n.get()));return react.useEffect(()=>{let n=e.map((s,i)=>s.subscribe(o=>{t(u=>{let l=[...u];return l[i]=o,l});}));return ()=>{n.forEach(s=>s());}},[e]),r}function Z(e){return "nextPage"in e}function U(e){return "setParams"in e}function R(e,r){let{initialParams:t,fetchOnMount:n}=typeof r=="object"&&("initialParams"in r||"fetchOnMount"in r)?r:{initialParams:r,fetchOnMount:false},[s,i]=react.useState(()=>e.get());react.useEffect(()=>e.subscribe(k=>{i(k);}),[e]),react.useEffect(()=>{t&&U(e)?e.setParams(t):n&&!t&&e.reload();},[e]),react.useEffect(()=>()=>{e.cleanup();},[e]);let o=react.useCallback(d=>e.reload(d),[e]),u=react.useCallback(d=>e.refresh(d),[e]),l=react.useCallback(d=>e.mutate(d),[e]),a=react.useCallback(()=>e.reset(),[e]),c=react.useCallback(d=>{"setParams"in e&&e.setParams(d);},[e]),{data:T,loading:g,error:f,lastFetched:h,pagination:p}=s,m={data:T,loading:g,error:f,lastFetched:h,reload:o,refresh:u,mutate:l,reset:a};if(U(e)&&(m.setParams=c),Z(e)){let d=m;d.pagination=p,d.nextPage=react.useCallback(()=>e.nextPage(),[e]),d.prevPage=react.useCallback(()=>e.prevPage(),[e]),d.goToPage=react.useCallback(k=>e.goToPage(k),[e]),d.resetPagination=react.useCallback(()=>e.resetPagination(),[e]);}return m}function re(e,r={}){let{initialParams:t,autoLoad:n=true,threshold:s=1,...i}=r,o=react.useRef(null),u=R(e,{initialParams:{...t,page:1,pageSize:e.get().pagination?.pageSize||10},...i}),{loading:l,pagination:a,nextPage:c}=u;react.useEffect(()=>{if(!n)return;let g=new IntersectionObserver(h=>{h[0].isIntersecting&&!l&&a?.hasMore&&c();},{threshold:s}),f=o.current;return f&&g.observe(f),()=>{f&&g.unobserve(f);}},[l,a?.hasMore,c,n,s]);let T=react.useCallback(()=>{!l&&a?.hasMore&&c();},[l,a?.hasMore,c]);return {...u,loadMore:T,observerTarget:o,hasMore:a?.hasMore??false,isFetchingMore:l&&(u.data?.length??0)>0}}exports.useAsyncChunk=R;exports.useChunk=C;exports.useChunkProperty=G;exports.useChunkValue=v;exports.useChunkValues=X;exports.useComputed=L;exports.useDerive=F;exports.useInfiniteAsyncChunk=re;
@@ -0,0 +1,141 @@
1
+ import { C as Chunk } from '../core-DMY69lzg.cjs';
2
+
3
+ /**
4
+ * A lightweight hook that subscribes to a chunk and returns its current value, along with setters, selector, reset and destroy.
5
+ * Ensures reactivity and prevents unnecessary re-renders.
6
+ */
7
+ declare function useChunk<T, S = T>(chunk: Chunk<T>, selector?: (value: T) => S): readonly [S, (valueOrUpdater: T | ((currentValue: T) => T)) => void, () => void, () => void];
8
+
9
+ /**
10
+ * A hook for creating a read-only derived value from a chunk.
11
+ * Ensures reactivity and updates when the source chunk changes.
12
+ */
13
+ declare function useDerive<T, D>(chunk: Chunk<T>, fn: (value: T) => D): D;
14
+
15
+ type ChunkValue<T> = T extends Chunk<infer U> ? U : never;
16
+ type DependencyValues<T extends Chunk<any>[]> = {
17
+ [K in keyof T]: T[K] extends Chunk<any> ? ChunkValue<T[K]> : never;
18
+ };
19
+
20
+ /**
21
+ * A hook that computes a value based on multiple chunks.
22
+ * Automatically re-computes when any dependency changes.
23
+ */
24
+ declare function useComputed<TDeps extends Chunk<any>[], TResult>(dependencies: [...TDeps], computeFn: (...args: DependencyValues<TDeps>) => TResult): TResult;
25
+
26
+ /**
27
+ * A lightweight hook that subscribes to a chunk and returns only its current value.
28
+ * Useful for read-only components that don't need to update the chunk.
29
+ */
30
+ declare function useChunkValue<T, S = T>(chunk: Chunk<T>, selector?: (value: T) => S): S;
31
+
32
+ /**
33
+ * A hook that subscribes to a specific property of a chunk.
34
+ * This optimizes renders by only updating when the selected property changes.
35
+ */
36
+ declare function useChunkProperty<T, K extends keyof T>(chunk: Chunk<T>, property: K): T[K];
37
+
38
+ /**
39
+ * Hook to read values from multiple chunks at once.
40
+ * Only re-renders when any of the chunk values change.
41
+ */
42
+ declare function useChunkValues<T extends Chunk<any>[]>(chunks: [...T]): {
43
+ [K in keyof T]: T[K] extends Chunk<infer U> ? U : never;
44
+ };
45
+
46
+ interface AsyncState<T, E extends Error> {
47
+ loading: boolean;
48
+ error: E | null;
49
+ data: T | null;
50
+ lastFetched?: number;
51
+ }
52
+ interface PaginationState {
53
+ page: number;
54
+ pageSize: number;
55
+ total?: number;
56
+ hasMore?: boolean;
57
+ }
58
+ interface AsyncStateWithPagination<T, E extends Error> extends AsyncState<T, E> {
59
+ pagination?: PaginationState;
60
+ }
61
+ interface AsyncChunk<T, E extends Error = Error> extends Chunk<AsyncStateWithPagination<T, E>> {
62
+ /** Force reload data */
63
+ reload: (params?: any) => Promise<void>;
64
+ /** Smart refresh - respects stale time */
65
+ refresh: (params?: any) => Promise<void>;
66
+ /** Mutate data directly */
67
+ mutate: (mutator: (currentData: T | null) => T) => void;
68
+ /** Reset to initial state */
69
+ reset: () => void;
70
+ /** Clean up intervals */
71
+ cleanup: () => void;
72
+ }
73
+ interface PaginatedAsyncChunk<T, E extends Error = Error> extends AsyncChunk<T, E> {
74
+ /** Load next page */
75
+ nextPage: () => Promise<void>;
76
+ /** Load previous page */
77
+ prevPage: () => Promise<void>;
78
+ /** Go to specific page */
79
+ goToPage: (page: number) => Promise<void>;
80
+ /** Reset pagination to first page */
81
+ resetPagination: () => Promise<void>;
82
+ }
83
+
84
+ interface UseAsyncChunkResult<T, E extends Error, P extends Record<string, any>> {
85
+ data: T | null;
86
+ loading: boolean;
87
+ error: E | null;
88
+ lastFetched?: number;
89
+ reload: (params?: Partial<P>) => Promise<void>;
90
+ refresh: (params?: Partial<P>) => Promise<void>;
91
+ mutate: (mutator: (currentData: T | null) => T) => void;
92
+ reset: () => void;
93
+ }
94
+ interface UseAsyncChunkResultWithParams<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResult<T, E, P> {
95
+ setParams: (params: Partial<P>) => void;
96
+ }
97
+ interface UseAsyncChunkResultWithPagination<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResult<T, E, P> {
98
+ pagination?: PaginationState;
99
+ nextPage: () => Promise<void>;
100
+ prevPage: () => Promise<void>;
101
+ goToPage: (page: number) => Promise<void>;
102
+ resetPagination: () => Promise<void>;
103
+ }
104
+ interface UseAsyncChunkResultWithParamsAndPagination<T, E extends Error, P extends Record<string, any>> extends UseAsyncChunkResultWithParams<T, E, P>, Omit<UseAsyncChunkResultWithPagination<T, E, P>, keyof UseAsyncChunkResult<T, E, P>> {
105
+ }
106
+ /**
107
+ * A hook that handles asynchronous state with built-in reactivity.
108
+ * Provides loading, error, and data states with full asyncChunk functionality.
109
+ */
110
+ interface UseAsyncChunkOptions<P extends Record<string, any> = {}> {
111
+ /** Initial parameters to pass to the fetcher */
112
+ initialParams?: Partial<P>;
113
+ /** Force fetch on mount, even without params (default: false) */
114
+ fetchOnMount?: boolean;
115
+ }
116
+ declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T, E> & {
117
+ setParams: (params: Partial<P>) => void;
118
+ }, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithParamsAndPagination<T, E, P>;
119
+ declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T, E>, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithPagination<T, E, P>;
120
+ declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: AsyncChunk<T, E> & {
121
+ setParams: (params: Partial<P>) => void;
122
+ }, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithParams<T, E, P>;
123
+ declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: AsyncChunk<T, E>, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResult<T, E, P>;
124
+
125
+ interface UseInfiniteAsyncChunkOptions<P extends Record<string, any>> extends Omit<UseAsyncChunkOptions<P>, 'initialParams'> {
126
+ /** Initial parameters (page and pageSize added automatically) */
127
+ initialParams?: Omit<Partial<P>, 'page' | 'pageSize'>;
128
+ /** Enable auto-loading on scroll (default: true) */
129
+ autoLoad?: boolean;
130
+ /** Intersection observer threshold (default: 1.0) */
131
+ threshold?: number;
132
+ }
133
+ /**
134
+ * Hook for infinite scroll functionality.
135
+ * Automatically loads more data when scrolling to the bottom.
136
+ */
137
+ declare function useInfiniteAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T[], E> & {
138
+ setParams: (params: Partial<P>) => void;
139
+ }, options?: UseInfiniteAsyncChunkOptions<P>): any;
140
+
141
+ export { useAsyncChunk, useChunk, useChunkProperty, useChunkValue, useChunkValues, useComputed, useDerive, useInfiniteAsyncChunk };
@@ -1,4 +1,4 @@
1
- import { C as Chunk } from '../core-C7jFiHdO.js';
1
+ import { C as Chunk } from '../core-DMY69lzg.js';
2
2
 
3
3
  /**
4
4
  * A lightweight hook that subscribes to a chunk and returns its current value, along with setters, selector, reset and destroy.
@@ -122,4 +122,20 @@ declare function useAsyncChunk<T, E extends Error = Error, P extends Record<stri
122
122
  }, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResultWithParams<T, E, P>;
123
123
  declare function useAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: AsyncChunk<T, E>, options?: UseAsyncChunkOptions<P> | Partial<P>): UseAsyncChunkResult<T, E, P>;
124
124
 
125
- export { useAsyncChunk, useChunk, useChunkProperty, useChunkValue, useChunkValues, useComputed, useDerive };
125
+ interface UseInfiniteAsyncChunkOptions<P extends Record<string, any>> extends Omit<UseAsyncChunkOptions<P>, 'initialParams'> {
126
+ /** Initial parameters (page and pageSize added automatically) */
127
+ initialParams?: Omit<Partial<P>, 'page' | 'pageSize'>;
128
+ /** Enable auto-loading on scroll (default: true) */
129
+ autoLoad?: boolean;
130
+ /** Intersection observer threshold (default: 1.0) */
131
+ threshold?: number;
132
+ }
133
+ /**
134
+ * Hook for infinite scroll functionality.
135
+ * Automatically loads more data when scrolling to the bottom.
136
+ */
137
+ declare function useInfiniteAsyncChunk<T, E extends Error = Error, P extends Record<string, any> = {}>(asyncChunk: PaginatedAsyncChunk<T[], E> & {
138
+ setParams: (params: Partial<P>) => void;
139
+ }, options?: UseInfiniteAsyncChunkOptions<P>): any;
140
+
141
+ export { useAsyncChunk, useChunk, useChunkProperty, useChunkValue, useChunkValues, useComputed, useDerive, useInfiniteAsyncChunk };
@@ -1 +1 @@
1
- import {useState,useEffect,useCallback,useRef,useMemo}from'react';var R=new Set,S=new Map,O=0;function P(e,r=[]){if(e===null)throw new Error("Initial value cannot be null.");let t=e,n=new Set,s=O++,u=()=>{n.forEach(f=>f(t));};S.set(s,{notify:u});let o=()=>{n.size!==0&&(u());},l=()=>t,c=f=>{let h;typeof f=="function"?h=f(t):h=f,C(t,h);let T=D(h,r);T!==t&&(t=T,o());},a=f=>{if(typeof f!="function")throw new Error("Callback must be a function.");return n.add(f),f(t),()=>n.delete(f)};return {get:l,set:c,subscribe:a,derive:f=>{if(typeof f!="function")throw new Error("Derive function must be a function.");let h=f(t),T=P(h),m=a(()=>{let k=f(t);T.set(k);}),d=T.destroy;return T.destroy=()=>{m(),d();},T},reset:()=>{t=e,o();},destroy:()=>{n.clear(),t=e,R.delete(s),S.delete(s);}}}function D(e,r){if(e===null)throw new Error("Value cannot be null.");let t=e,n=0;for(;n<r.length;){let s=r[n],u=typeof s=="function"?s:s.fn,o=typeof s=="function"?`index ${n}`:s.name||`index ${n}`,l=false,c=null;try{u(t,a=>{l=!0,c=a;});}catch(a){let i=a instanceof Error?a.message:String(a);throw new Error(`Middleware "${o}" threw an error: ${i}`)}if(!l)break;if(c===null)throw new Error(`Middleware at index ${n} returned null value.`);t=c,n++;}return t}function b(e,r){if(e===r)return true;if(!e||!r||typeof e!=typeof r)return false;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return false;for(let t=0;t<e.length;t++)if(e[t]!==r[t])return false;return true}if(typeof e=="object"&&typeof r=="object"){let t=Object.keys(e),n=Object.keys(r);if(t.length!==n.length)return false;for(let s of t)if(!Object.prototype.hasOwnProperty.call(r,s)||e[s]!==r[s])return false;return true}return false}function C(e,r,t=""){if(typeof e=="object"&&e!==null&&typeof r=="object"&&r!==null){if(Array.isArray(e)&&Array.isArray(r)){if(e.length>0&&typeof e[0]=="object")for(let n=0;n<r.length;n++)C(e[0],r[n],`${t}[${n}]`);}else if(!Array.isArray(e)&&!Array.isArray(r)){let n=Object.keys(e),s=Object.keys(r),u=s.filter(o=>!n.includes(o));u.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${t||"root"}': ${u.join(", ")}. This might cause bugs.`),console.error("Expected keys:",n),console.error("Received keys:",s));for(let o of n)C(e[o],r[o],t?`${t}.${o}`:o);}}}function x(e,r,t={}){let{useShallowEqual:n=false}=t,s=e.get(),u=r(s),o=P(u),l=()=>{let a=e.get(),i=r(a);s=a,(n?!b(i,u):i!==u)&&(u=i,o.set(i));},c=e.subscribe(l);return {get:()=>o.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:o.subscribe,derive:a=>x(o,a,t),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{c(),o.destroy();}}}function g(e,r){let t=r?x(e,r):e,[n,s]=useState(()=>t.get());useEffect(()=>{let c=t.subscribe(a=>{s(()=>a);});return ()=>c()},[t]);let u=useCallback(c=>{e.set(c);},[e]),o=useCallback(()=>{e.reset();},[e]),l=useCallback(()=>{e.destroy();},[e]);return [n,u,o,l]}function N(e,r){let t=useRef(r);useEffect(()=>{t.current=r;},[r]);let n=useMemo(()=>e.derive(u=>t.current(u)),[e]),[s]=g(n);return s}function V(e,r){let t=e.map(a=>a.get()),n=r(...t),s=P(n),u=s.set,o=false,l=()=>{let a=false;for(let i=0;i<e.length;i++){let p=e[i].get();p!==t[i]&&(t[i]=p,a=true);}if(a){let i=r(...t);i!==n&&(typeof i!="object"||typeof n!="object"||!b(i,n))&&(n=i,u(i)),o=false;}},c=e.map(a=>a.subscribe(()=>{o=true,l();}));return {...s,get:()=>(o&&l(),n),recompute:l,isDirty:()=>o,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(a=>{typeof a.reset=="function"&&a.reset();}),o=true,l(),n),destroy:()=>{c.forEach(a=>a()),s.destroy?.();}}}function z(e,r){let t=useMemo(()=>V(e,r),[...e]),[n,s]=useState(()=>t.get());return useEffect(()=>{let u=t.subscribe(o=>{s(o);});return ()=>{u();}},[t]),n}function A(e,r){let[t]=g(e,r);return t}function G(e,r){let t=useMemo(()=>n=>n[r],[r]);return A(e,t)}function Q(e){let[r,t]=useState(()=>e.map(n=>n.get()));return useEffect(()=>{let n=e.map((s,u)=>s.subscribe(o=>{t(l=>{let c=[...l];return c[u]=o,c});}));return ()=>{n.forEach(s=>s());}},[e]),r}function Y(e){return "nextPage"in e}function U(e){return "setParams"in e}function Z(e,r){let{initialParams:t,fetchOnMount:n}=typeof r=="object"&&("initialParams"in r||"fetchOnMount"in r)?r:{initialParams:r,fetchOnMount:false},[s,u]=useState(()=>e.get());useEffect(()=>e.subscribe(k=>{u(k);}),[e]),useEffect(()=>{t&&U(e)?e.setParams(t):n&&!t&&e.reload();},[e]),useEffect(()=>()=>{e.cleanup();},[e]);let o=useCallback(d=>e.reload(d),[e]),l=useCallback(d=>e.refresh(d),[e]),c=useCallback(d=>e.mutate(d),[e]),a=useCallback(()=>e.reset(),[e]),i=useCallback(d=>{"setParams"in e&&e.setParams(d);},[e]),{data:p,loading:w,error:f,lastFetched:h,pagination:T}=s,m={data:p,loading:w,error:f,lastFetched:h,reload:o,refresh:l,mutate:c,reset:a};if(U(e)&&(m.setParams=i),Y(e)){let d=m;d.pagination=T,d.nextPage=useCallback(()=>e.nextPage(),[e]),d.prevPage=useCallback(()=>e.prevPage(),[e]),d.goToPage=useCallback(k=>e.goToPage(k),[e]),d.resetPagination=useCallback(()=>e.resetPagination(),[e]);}return m}export{Z as useAsyncChunk,g as useChunk,G as useChunkProperty,A as useChunkValue,Q as useChunkValues,z as useComputed,N as useDerive};
1
+ import {useState,useEffect,useCallback,useRef,useMemo}from'react';var S=new Set,D=new Map,j=0;function P(e,r=[]){if(e===null)throw new Error("Initial value cannot be null.");let t=e,n=new Set,s=j++,i=()=>{n.forEach(f=>f(t));};D.set(s,{notify:i});let o=()=>{n.size!==0&&(i());},u=()=>t,l=f=>{let h;typeof f=="function"?h=f(t):h=f,b(t,h);let p=M(h,r);p!==t&&(t=p,o());},a=f=>{if(typeof f!="function")throw new Error("Callback must be a function.");return n.add(f),f(t),()=>n.delete(f)};return {get:u,set:l,subscribe:a,derive:f=>{if(typeof f!="function")throw new Error("Derive function must be a function.");let h=f(t),p=P(h),m=a(()=>{let k=f(t);p.set(k);}),d=p.destroy;return p.destroy=()=>{m(),d();},p},reset:()=>{t=e,o();},destroy:()=>{n.clear(),t=e,S.delete(s),D.delete(s);}}}function M(e,r){if(e===null)throw new Error("Value cannot be null.");let t=e;for(let n=0;n<r.length;n++){let s=r[n],i=typeof s=="function"?s:s.fn,o=typeof s=="function"?`index ${n}`:s.name||`index ${n}`;try{let u=i(t);if(u===void 0)break;if(u===null)throw new Error(`Middleware "${o}" returned null value.`);t=u;}catch(u){let l=u instanceof Error?u.message:String(u);throw new Error(`Middleware "${o}" threw an error: ${l}`)}}return t}function E(e,r){if(e===r)return true;if(!e||!r||typeof e!=typeof r)return false;if(Array.isArray(e)&&Array.isArray(r)){if(e.length!==r.length)return false;for(let t=0;t<e.length;t++)if(e[t]!==r[t])return false;return true}if(typeof e=="object"&&typeof r=="object"){let t=Object.keys(e),n=Object.keys(r);if(t.length!==n.length)return false;for(let s of t)if(!Object.prototype.hasOwnProperty.call(r,s)||e[s]!==r[s])return false;return true}return false}function b(e,r,t=""){if(typeof e=="object"&&e!==null&&typeof r=="object"&&r!==null){if(Array.isArray(e)&&Array.isArray(r)){if(e.length>0&&typeof e[0]=="object")for(let n=0;n<r.length;n++)b(e[0],r[n],`${t}[${n}]`);}else if(!Array.isArray(e)&&!Array.isArray(r)){let n=Object.keys(e),s=Object.keys(r),i=s.filter(o=>!n.includes(o));i.length>0&&(console.error(`\u{1F6A8} Stunk: Unknown properties detected at '${t||"root"}': ${i.join(", ")}. This might cause bugs.`),console.error("Expected keys:",n),console.error("Received keys:",s));for(let o of n)b(e[o],r[o],t?`${t}.${o}`:o);}}}function x(e,r,t={}){let{useShallowEqual:n=false}=t,s=e.get(),i=r(s),o=P(i),u=()=>{let a=e.get(),c=r(a);s=a,(n?!E(c,i):c!==i)&&(i=c,o.set(c));},l=e.subscribe(u);return {get:()=>o.get(),set:()=>{throw new Error("Cannot set values directly on a selector. Modify the source chunk instead.")},subscribe:o.subscribe,derive:a=>x(o,a,t),reset:()=>{throw new Error("Cannot reset a selector chunk. Reset the source chunk instead.")},destroy:()=>{l(),o.destroy();}}}function C(e,r){let t=r?x(e,r):e,[n,s]=useState(()=>t.get());useEffect(()=>{let l=t.subscribe(a=>{s(()=>a);});return ()=>l()},[t]);let i=useCallback(l=>{e.set(l);},[e]),o=useCallback(()=>{e.reset();},[e]),u=useCallback(()=>{e.destroy();},[e]);return [n,i,o,u]}function F(e,r){let t=useRef(r);useEffect(()=>{t.current=r;},[r]);let n=useMemo(()=>e.derive(i=>t.current(i)),[e]),[s]=C(n);return s}function O(e,r){let t=e.map(a=>a.get()),n=r(...t),s=P(n),i=s.set,o=false,u=()=>{let a=false;for(let c=0;c<e.length;c++){let T=e[c].get();T!==t[c]&&(t[c]=T,a=true);}if(a){let c=r(...t);c!==n&&(typeof c!="object"||typeof n!="object"||!E(c,n))&&(n=c,i(c)),o=false;}},l=e.map(a=>a.subscribe(()=>{o=true,u();}));return {...s,get:()=>(o&&u(),n),recompute:u,isDirty:()=>o,set:()=>{throw new Error("Cannot set values directly on computed. Modify the source chunk instead.")},reset:()=>(e.forEach(a=>{typeof a.reset=="function"&&a.reset();}),o=true,u(),n),destroy:()=>{l.forEach(a=>a()),s.destroy?.();}}}function L(e,r){let t=useMemo(()=>O(e,r),[...e]),[n,s]=useState(()=>t.get());return useEffect(()=>{let i=t.subscribe(o=>{s(o);});return ()=>{i();}},[t]),n}function v(e,r){let[t]=C(e,r);return t}function G(e,r){let t=useMemo(()=>n=>n[r],[r]);return v(e,t)}function X(e){let[r,t]=useState(()=>e.map(n=>n.get()));return useEffect(()=>{let n=e.map((s,i)=>s.subscribe(o=>{t(u=>{let l=[...u];return l[i]=o,l});}));return ()=>{n.forEach(s=>s());}},[e]),r}function Z(e){return "nextPage"in e}function U(e){return "setParams"in e}function R(e,r){let{initialParams:t,fetchOnMount:n}=typeof r=="object"&&("initialParams"in r||"fetchOnMount"in r)?r:{initialParams:r,fetchOnMount:false},[s,i]=useState(()=>e.get());useEffect(()=>e.subscribe(k=>{i(k);}),[e]),useEffect(()=>{t&&U(e)?e.setParams(t):n&&!t&&e.reload();},[e]),useEffect(()=>()=>{e.cleanup();},[e]);let o=useCallback(d=>e.reload(d),[e]),u=useCallback(d=>e.refresh(d),[e]),l=useCallback(d=>e.mutate(d),[e]),a=useCallback(()=>e.reset(),[e]),c=useCallback(d=>{"setParams"in e&&e.setParams(d);},[e]),{data:T,loading:g,error:f,lastFetched:h,pagination:p}=s,m={data:T,loading:g,error:f,lastFetched:h,reload:o,refresh:u,mutate:l,reset:a};if(U(e)&&(m.setParams=c),Z(e)){let d=m;d.pagination=p,d.nextPage=useCallback(()=>e.nextPage(),[e]),d.prevPage=useCallback(()=>e.prevPage(),[e]),d.goToPage=useCallback(k=>e.goToPage(k),[e]),d.resetPagination=useCallback(()=>e.resetPagination(),[e]);}return m}function re(e,r={}){let{initialParams:t,autoLoad:n=true,threshold:s=1,...i}=r,o=useRef(null),u=R(e,{initialParams:{...t,page:1,pageSize:e.get().pagination?.pageSize||10},...i}),{loading:l,pagination:a,nextPage:c}=u;useEffect(()=>{if(!n)return;let g=new IntersectionObserver(h=>{h[0].isIntersecting&&!l&&a?.hasMore&&c();},{threshold:s}),f=o.current;return f&&g.observe(f),()=>{f&&g.unobserve(f);}},[l,a?.hasMore,c,n,s]);let T=useCallback(()=>{!l&&a?.hasMore&&c();},[l,a?.hasMore,c]);return {...u,loadMore:T,observerTarget:o,hasMore:a?.hasMore??false,isFetchingMore:l&&(u.data?.length??0)>0}}export{R as useAsyncChunk,C as useChunk,G as useChunkProperty,v as useChunkValue,X as useChunkValues,L as useComputed,F as useDerive,re as useInfiniteAsyncChunk};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "stunk",
3
- "version": "2.6.0",
4
- "description": "Stunk is a lightweight, framework-agnostic state management library for JavaScript and TypeScript. It uses chunk-based state units for efficient updates, reactivity, and performance optimization in React, Vue, Svelte, and Vanilla JS/TS applications.",
3
+ "version": "2.8.0",
4
+ "description": "Stunk is a lightweight, framework-agnostic state management library for JavaScript and TypeScript. It uses chunk-based state units for efficient updates, reactivity, and performance optimization in React, Vue(WIP), Svelte(Coming soon), and Vanilla JS/TS applications.",
5
5
  "type": "module",
6
6
  "repository": {
7
7
  "type": "git",
@@ -67,8 +67,12 @@
67
67
  "url": "https://github.com/I-am-abdulazeez"
68
68
  },
69
69
  {
70
- "name": "AbdulAzeez",
71
- "url": "https://github.com/I-am-abdulazeez"
70
+ "name": "Chiboy",
71
+ "url": "https://github.com/chibx"
72
+ },
73
+ {
74
+ "name": "Idris",
75
+ "url": "https://github.com/Dreezy305"
72
76
  }
73
77
  ],
74
78
  "license": "MIT",