react-understate
Version:
A lightweight, reactive signals library for React 18+ with automatic dependency tracking and optimized performance
2 lines (1 loc) • 15.4 kB
JavaScript
var e,t;e=this,t=function(e,t){function n(e){return e.split("\n").slice(1).find(e=>!e.includes("core.ts")&&!e.includes("derived.ts")&&!e.includes("effects.ts")&&!e.includes("react.ts")&&!e.includes("node_modules")&&!e.includes("dist/react-understate")&&!e.includes(".js?t=")&&!e.includes("rollup")&&!e.includes("vite")&&!e.includes("ModuleJob.run")&&!e.includes("node:internal")&&""!==e.trim()&&e.includes(":"))}function o(e){const t=e.match(/at\s+(.+):(\d+):(\d+)/);if(t){const[,e,n,o]=t;if(e&&n&&o)return{file:e,line:n,col:o}}return null}function r(e,t,n){return`%c${e}:${t}:${n}`}function i(e,t){if(t.enabled&&t.logger){if(t.showFile){const i=Error().stack;if(i){const c=n(i);if(c){const n=o(c);return n?void t.logger(`${e} ${r(n.file,n.line,n.col)}`,"color: #0066cc; text-decoration: underline; cursor: pointer;"):void t.logger(`${e} at ${c.trim()}`)}}}t.logger(e)}}function c(e){if(e.includes("."))throw Error(`Invalid state name '${e}': Names cannot contain dots (.) as they break the code.`);if(!/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e))throw Error(`Invalid state name '${e}': Names must be valid JavaScript identifiers (start with letter, underscore, or $, followed by letters, numbers, underscores, or $).`);return e}function s(e){return void 0!==e&&(P={...P,...e}),{...P}}function u(){if(0===D.size)return;const e=Array.from(D);D.clear(),e.forEach(e=>e())}function a(e){const t=L;return L=e,t}function f(e){const t=C;return C=e,t}function l(e){L&&0!=C?.preventLoops&&L===x&&V.add(e)}function d(){V.clear()}function w(e){R.set(e,new Set(V))}function y(e){x=e}function v(e){const t=q;return q=e,t}function p(e,t){const n=t?c(t):void 0;if(n&&i(`batch: '${n}'`,P),q)e();else{v(1);try{e()}finally{v(0),u()}}}function $(){"undefined"==typeof window||B||(window.reactUnderstate={configureDebug:s,states:{},actions:{}},B=1)}function h(e,t,n){const o=t?c(t):void 0;let r,u=0,l=0,v=0,$=0;const h=[],b={preventLoops:1,preventOverlap:1,...n},O=(t=0)=>{if(u)return;if(b.once&&l)return;if(o&&t&&G.has(o)){const e=G.get(o);return e&&"object"==typeof e&&"abort"in e&&e.abort(),H.has(o)||H.set(o,[]),void H.get(o).push(()=>O(1))}if(b.preventOverlap&&v)return void($=1);if(0!=b.preventLoops){const e=Date.now();if(h.push(e),h.length>20&&h.shift(),h.length>=5){const t=h.filter(t=>1e3>e-t);if(t.length>10)return void 0!==console&&console.error&&t.length,void(u=1)}}if(v=1,o){const e=s();i(`effect: '${o}' running`,e)}if(r){try{r()}catch(m){}r=void 0}d(),y(O),function(e){M.set(e,new Set)}(O),d();const n=f(b),c=a(O);try{if(o){const e=G.get(o);e&&"object"==typeof e&&"abort"in e&&e.abort()}const t=new AbortController,u={signal:t.signal};let d;if(p(()=>{d=e(u)}),w(O),d instanceof Promise){if(o){const e={promise:d,abort:()=>t.abort()};G.set(o,e)}a(c),f(n),y(null),d.then(e=>{if(r=e,o){const e=s();i(`effect: '${o}' async resolved`,e)}}).catch(e=>{if(o){const t=s();i(`effect: '${o}' async rejected: ${e}`,t)}}).finally(()=>{if(v=0,l=1,o){G.delete(o);const e=H.get(o);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}}$&&($=0,0!=b.preventLoops&&O(1))})}else w(O),r=d,a(c),f(n),y(null),v=0,l=1,$&&($=0,0!=b.preventLoops&&O(1))}catch(S){a(c),f(n),y(null),v=0,l=1}};if(function(e,t){z.set(e,t)}(O,b),O(),o&&"undefined"!=typeof window){window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}});const e=window.reactUnderstate;if(e.states[o])throw Error(`Effect with name '${o}' already exists. State names must be unique.`);e.states[o]={value:"effect",dispose:()=>{u=1,r&&(r(),r=void 0)}}}return()=>{u=1,r&&(r(),r=void 0)}}function b(){function e(e){var t,n=e.getSnapshot;e=e.value;try{return t=n(),!o(e,t)}catch(r){return 1}}var n,o,r,i,c,s,u;return g||(g=1,o="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=(n=t).useState,i=n.useEffect,c=n.useLayoutEffect,s=n.useDebugValue,u="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,n){var o=n(),u=r({inst:{value:o,getSnapshot:n}}),a=u[0].inst,f=u[1];return c(function(){a.value=o,a.getSnapshot=n,e(a)&&f({inst:a})},[t,o,n]),i(function(){return e(a)&&f({inst:a}),t(function(){e(a)&&f({inst:a})})},[t]),s(o),o},_.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:u),_}function O(){return j||(j=1,"production"!==process.env.NODE_ENV&&function(){function e(e){var t,n=e.getSnapshot;e=e.value;try{return t=n(),!o(e,t)}catch(r){return 1}}"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var n=t,o="function"==typeof Object.is?Object.is:function(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t},r=n.useState,i=n.useEffect,c=n.useLayoutEffect,s=n.useDebugValue,u=0,a=0,f="undefined"==typeof window||void 0===window.document||void 0===window.document.createElement?function(e,t){return t()}:function(t,f){var l,d,w,y;return u||void 0===n.startTransition||(u=1),l=f(),a||(d=f(),o(l,d)||(a=1)),d=r({inst:{value:l,getSnapshot:f}}),w=d[0].inst,y=d[1],c(function(){w.value=l,w.getSnapshot=f,e(w)&&y({inst:w})},[t,l,f]),i(function(){return e(w)&&y({inst:w}),t(function(){e(w)&&y({inst:w})})},[t]),s(l),l};E.useSyncExternalStore=void 0!==n.useSyncExternalStore?n.useSyncExternalStore:f,"undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),E}function m(){return A||(A=1,"production"===process.env.NODE_ENV?S.exports=b():S.exports=O()),S.exports}var S,_,g,E,j,A,T;let L=null,q=0;const D=new Set,J=new Map,N=new Map;let C=null;const V=new Set;let x=null;const M=new WeakMap,R=new WeakMap,z=new WeakMap;let P={enabled:0,logger:(...e)=>console.log(...e)},B=0;const G=new Map,H=new Map;S={exports:{}},_={},E={},T=m(),e.action=function(e,t){const n=t?c(t):void 0;if(n&&"undefined"!=typeof window){$();const t=window.reactUnderstate;if(t.actions[n])throw Error(`Action with name '${n}' already exists. Action names must be unique.`);t.actions[n]=e}return(...t)=>{n&&i(`action: '${n}'`,P);const o=new AbortController,r={signal:o.signal};if(n&&J.has(n)){const o=J.get(n);return o&&"object"==typeof o&&"abort"in o&&o.abort(),N.has(n)||N.set(n,[]),new Promise((o,r)=>{N.get(n).push(()=>{try{const i=new AbortController,c={signal:i.signal},s=[...t];if(e.length>0){const e=s[s.length-1];"object"==typeof e&&null!==e&&"signal"in e?s[s.length-1]=c:s.push(c)}const u=e(...s);if(u instanceof Promise){const e=u;J.set(n,{promise:e,abort:()=>i.abort()}),e.then(o).catch(r).finally(()=>{J.delete(n);const e=N.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}})}else{o(u);const e=N.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}}}catch(i){r(i)}})})}let c;if(p(()=>{if(e.length>0){const e=t[t.length-1];"object"==typeof e&&null!==e&&"signal"in e?t[t.length-1]=r:t.push(r)}c=e(...t)}),n&&c&&"object"==typeof c&&"then"in c){const e=c,t={promise:e,abort:()=>o.abort()};J.set(n,t),e.finally(()=>{J.delete(n);const e=N.get(n);if(e&&e.length>0){const t=e.shift();setTimeout(()=>t(),0)}})}return c}},e.asyncDerived=function(e,t){const n=t?c(t):void 0;let o,r=1;const u=new Set,f=new Set,l=()=>{if(!r){if(r=1,n){const e=s();i(`asyncDerived: '${n}' marked dirty`,e)}u.forEach(e=>{e!==l&&e()})}},d=async()=>{if(r){r=0;const c=a(l);try{if(n){const e=s();i(`asyncDerived: '${n}' computing`,e)}o=e();const t=await o;if(n){const e=s();i(`asyncDerived: '${n}' async resolved: ${JSON.stringify(t,null,2)}`,e)}return t}catch(t){if(n){const e=s();i(`asyncDerived: '${n}' async rejected: ${t}`,e)}throw t}finally{a(c)}}return o};try{const t=a(l);try{o=e(),r=0,o.catch(e=>{if(n){const t=s();i(`asyncDerived: '${n}' async rejected: ${e}`,t)}})}finally{a(t)}}catch(y){if(o=Promise.reject(y),r=0,n){const e=s();i(`asyncDerived: '${n}' async rejected: ${y}`,e)}}const w={get rawValue(){return o},get value(){const e=a(null);return e&&f.add(e),r&&d().catch(e=>{}),o},async update(e){throw Error("Cannot update async derived values directly - they are computed from dependencies")},subscribe:e=>(u.add(e),()=>u.delete(e)),get requiredValue(){const e=a(null);return e&&f.add(e),r&&d().catch(e=>{}),o.then(e=>{if(null==e)throw Error(`Required async derived value${n?` '${n}'`:""} is ${null===e?"null":"undefined"}. Use .value to access the actual value or ensure the async derived value is properly computed.`);return e})},set requiredValue(e){throw Error(`Cannot set required value on async derived value${n?` '${n}'`:""} - they are computed from dependencies`)}};if(n&&"undefined"!=typeof window){if(window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}}),window.reactUnderstate.states[n])throw Error(`Async derived value with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=w}return w},e.batch=p,e.configureDebug=s,e.createFileLocation=r,e.derived=function(e,t){const n=t?c(t):void 0;let o,r=1,u=0;const f=new Set,l=new Set,d=()=>{r=1,f.forEach(e=>{e!==d&&e()}),l.forEach(e=>{e!==d&&e()})},w=()=>{if(r&&!u){u=1;const t=a(d);try{if(o=e(),n){const e=s();i(`derived: '${n}' ${JSON.stringify(o,null,2)}`,e)}}finally{a(t),u=0}r=0}const t=a(null);return t&&l.add(t),o};try{const t=a(d);try{o=e(),r=0}finally{a(t)}}catch{o=void 0,r=1}const y={rawValue:o,update:()=>{throw Error("Cannot update derived values directly")},subscribe:e=>(f.add(e),()=>f.delete(e)),get value(){const e=a(null);return e&&l.add(e),w()},set value(e){throw Error("Cannot update derived values directly")},get requiredValue(){const e=a(null);e&&l.add(e);const t=w();if(null==t)throw Error(`Required derived value${n?` '${n}'`:""} is ${null===t?"null":"undefined"}. Use .value to access the actual value or ensure the derived value is properly computed.`);return t},set requiredValue(e){throw Error(`Cannot set required value on derived value${n?` '${n}'`:""} - they are computed from dependencies`)}};if(n&&"undefined"!=typeof window){if(window.reactUnderstate||(window.reactUnderstate={configureDebug:()=>({}),states:{},actions:{}}),window.reactUnderstate.states[n])throw Error(`Derived value with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=y}return y},e.effect=h,e.findUserCodeLine=n,e.getFileLocationStyle=function(){return"color: #0066cc; text-decoration: underline; cursor: pointer;"},e.logDebug=i,e.parseStackLine=o,e.persistLocalStorage=function(e,t,n={}){if("undefined"==typeof window)return()=>{};const{loadInitial:o=1,syncAcrossTabs:r=1,serialize:i=JSON.stringify,deserialize:c=JSON.parse,onError:s=e=>{}}=n;if(o)try{const n=localStorage.getItem(t);if(null!==n){const t=c(n);e.value=t}}catch(f){s(f)}const u=h(()=>{try{const n=i(e.value);localStorage.setItem(t,n)}catch(f){s(f)}});let a;if(r){const n=n=>{if(n.key===t&&n.storageArea===localStorage)try{if(null!==n.newValue){const t=c(n.newValue);e.value=t}}catch(f){s(f)}};window.addEventListener("storage",n),a=()=>{window.removeEventListener("storage",n)}}return()=>{u(),a?.()}},e.persistSessionStorage=function(e,t,n={}){if("undefined"==typeof window)return()=>{};const{loadInitial:o=1,syncAcrossTabs:r=1,serialize:i=JSON.stringify,deserialize:c=JSON.parse,onError:s=e=>{}}=n;if(o)try{const n=sessionStorage.getItem(t);if(null!==n){const t=c(n);e.value=t}}catch(f){s(f)}const u=h(()=>{try{const n=i(e.value);sessionStorage.setItem(t,n)}catch(f){s(f)}});let a;if(r){const n=n=>{if(n.key===t&&n.storageArea===sessionStorage)try{if(null!==n.newValue){const t=c(n.newValue);e.value=t}}catch(f){s(f)}};window.addEventListener("storage",n),a=()=>{window.removeEventListener("storage",n)}}return()=>{u(),a?.()}},e.persistStates=function(e,t,n=("undefined"!=typeof window?sessionStorage:{})){const o=[];for(const[r,i]of Object.entries(e)){const e=`${t}.${r}`;try{const t=n.getItem(e);if(null!==t){const e=JSON.parse(t);i.value=e}}catch{}const c=h(()=>{try{const t=JSON.stringify(i.value);n.setItem(e,t)}catch{}});let s;if("undefined"!=typeof window&&(n===window.localStorage||n===window.sessionStorage)){const t=t=>{if(t.key===e&&t.storageArea===n)try{if(null!==t.newValue){const e=JSON.parse(t.newValue);i.value=e}}catch{}};window.addEventListener("storage",t),s=()=>{window.removeEventListener("storage",t)}}o.push(()=>{c(),s?.()})}return()=>o.forEach(e=>e())},e.setReact=function(e){},e.state=function(e,t){const n=t?c(t):void 0;let o=e;const r=new Set,a=new Set,f=()=>{r.forEach(e=>{e!==L&&e()}),a.forEach(e=>{if(0!=C?.preventLoops&&function(e){return V.has(e)}(w)&&(e===L||e===x))return;const t=function(e){return z.get(e)}(e);0!=t?.preventLoops&&function(e,t){const n=M.get(e);return!!n&&n.has(t)}(e,w)||e()})},d=async e=>{try{let r;const c=s();if("function"==typeof e){const s=e(o);if(s instanceof Promise)try{r=await s,n&&i(`state: '${n}' async resolved: ${JSON.stringify(r,null,2)}`,c)}catch(t){throw n&&i(`state: '${n}' async rejected: ${t}`,c),t}else r=s}else r=e;Object.is(o,r)||(n&&i(`state: '${n}' ${JSON.stringify(r,null,2)}`,c),o=r,function(e){if(!x)return;let t=M.get(x);t||(t=new Set,M.set(x,t)),t.add(e)}(w),D.add(f),q||u())}catch{}},w={get rawValue(){return o},update:async e=>{try{const r=e(o);if(r instanceof Promise)try{const e=await r;if(n){const t=s();i(`state: '${n}' update async resolved: ${JSON.stringify(e,null,2)}`,t)}d(e)}catch(t){if(n){const e=s();i(`state: '${n}' update async rejected: ${t}`,e)}throw t}else d(r)}catch{}},subscribe:e=>(r.add(e),()=>r.delete(e)),get value(){return L&&(l(w),a.add(L)),o},set value(e){if("function"==typeof e){const t=e(o);if(t instanceof Promise)return void t.then(e=>d(e));d(t)}else d(e)},get requiredValue(){if(L&&(l(w),a.add(L)),null==o)throw Error(`Required value${n?` '${n}'`:""} is ${null===o?"null":"undefined"}. Use .value to access the actual value or ensure the state is initialized.`);return o},set requiredValue(e){if(null==e)throw Error(`Cannot set required value${n?` '${n}'`:""} to ${null===e?"null":"undefined"}. Use .value to set null/undefined values.`);d(e)},toString:()=>o+""};if(n&&"undefined"!=typeof window){if($(),window.reactUnderstate.states[n])throw Error(`State with name '${n}' already exists. State names must be unique.`);window.reactUnderstate.states[n]=w}return w},e.useUnderstate=function(e,...t){if(e&&"object"==typeof e&&!("value"in e)&&!("subscribe"in e)){const t=e,n=function(e){const t=[];for(const n of Object.values(e))n&&"object"==typeof n&&"value"in n&&"subscribe"in n&&t.push(n);return t}(t);return T.useSyncExternalStore(e=>{const t=n.map(t=>t.subscribe(()=>{e()}));return()=>{t.forEach(e=>e())}},()=>JSON.stringify(n.map(e=>e.value))),function(e){const t={};for(const[n,o]of Object.entries(e))t[n]=o&&"object"==typeof o&&"value"in o&&"subscribe"in o?o.value:o;return t}(t)}{const n=[e,...t];return T.useSyncExternalStore(e=>{const t=n.map(t=>t.subscribe(()=>{e()}));return()=>{t.forEach(e=>e())}},()=>JSON.stringify(n.map(e=>e.value))),n.map(e=>e.value)}},Object.defineProperty(e,Symbol.toStringTag,{value:"Module"})},"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("react")):"function"==typeof define&&define.amd?define(["exports","react"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).ReactUnderstate={},e.React);//# sourceMappingURL=react-understate.umd.js.map