@shadow-js/core 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (191) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/dev/action.js +11 -7
  3. package/dist/dev/action.js.map +1 -1
  4. package/dist/dev/cache.d.ts +2 -1
  5. package/dist/dev/cache.js +5 -3
  6. package/dist/dev/cache.js.map +1 -1
  7. package/dist/dev/effect.js +17 -33
  8. package/dist/dev/effect.js.map +1 -1
  9. package/dist/dev/extend/index.d.ts +7 -6
  10. package/dist/dev/extend/index.js +7 -7
  11. package/dist/dev/extend/index.js.map +1 -1
  12. package/dist/dev/external-store.js +8 -3
  13. package/dist/dev/external-store.js.map +1 -1
  14. package/dist/dev/internal/concurrency.js +56 -30
  15. package/dist/dev/internal/concurrency.js.map +1 -1
  16. package/dist/dev/internal/diagnostics.js +0 -2
  17. package/dist/dev/internal/diagnostics.js.map +1 -1
  18. package/dist/dev/internal/dispose.js +1 -1
  19. package/dist/dev/internal/dispose.js.map +1 -1
  20. package/dist/dev/internal/flags.js +1 -3
  21. package/dist/dev/internal/flags.js.map +1 -1
  22. package/dist/dev/internal/graph.d.ts +1 -2
  23. package/dist/dev/internal/graph.js +47 -69
  24. package/dist/dev/internal/graph.js.map +1 -1
  25. package/dist/dev/internal/owner.d.ts +9 -6
  26. package/dist/dev/internal/owner.js +22 -30
  27. package/dist/dev/internal/owner.js.map +1 -1
  28. package/dist/dev/internal/scheduler.js +44 -73
  29. package/dist/dev/internal/scheduler.js.map +1 -1
  30. package/dist/dev/list.js +4 -12
  31. package/dist/dev/list.js.map +1 -1
  32. package/dist/dev/memo.d.ts +2 -1
  33. package/dist/dev/memo.js +4 -4
  34. package/dist/dev/memo.js.map +1 -1
  35. package/dist/dev/ownership.d.ts +4 -2
  36. package/dist/dev/ownership.js +59 -3
  37. package/dist/dev/ownership.js.map +1 -1
  38. package/dist/dev/props.js +18 -11
  39. package/dist/dev/props.js.map +1 -1
  40. package/dist/dev/reaction.d.ts +1 -1
  41. package/dist/dev/reaction.js +5 -1
  42. package/dist/dev/reaction.js.map +1 -1
  43. package/dist/dev/reducer.js +1 -1
  44. package/dist/dev/reducer.js.map +1 -1
  45. package/dist/dev/resource.js +24 -15
  46. package/dist/dev/resource.js.map +1 -1
  47. package/dist/dev/selector.js +1 -5
  48. package/dist/dev/selector.js.map +1 -1
  49. package/dist/dev/signal.d.ts +3 -2
  50. package/dist/dev/signal.js +3 -3
  51. package/dist/dev/signal.js.map +1 -1
  52. package/dist/dev/store/nodes.js +10 -4
  53. package/dist/dev/store/nodes.js.map +1 -1
  54. package/dist/dev/store/use-store.d.ts +5 -0
  55. package/dist/dev/store/use-store.js.map +1 -1
  56. package/dist/dev/transitions.js +1 -1
  57. package/dist/dev/transitions.js.map +1 -1
  58. package/dist/prod/action.js +1 -1
  59. package/dist/prod/action.js.map +1 -1
  60. package/dist/prod/cache.js +1 -1
  61. package/dist/prod/cache.js.map +1 -1
  62. package/dist/prod/effect.js +1 -1
  63. package/dist/prod/effect.js.map +1 -1
  64. package/dist/prod/extend/index.js +1 -1
  65. package/dist/prod/extend/index.js.map +1 -1
  66. package/dist/prod/external-store.js +1 -1
  67. package/dist/prod/external-store.js.map +1 -1
  68. package/dist/prod/internal/concurrency.js +1 -1
  69. package/dist/prod/internal/concurrency.js.map +1 -1
  70. package/dist/prod/internal/diagnostics.js +1 -1
  71. package/dist/prod/internal/diagnostics.js.map +1 -1
  72. package/dist/prod/internal/dispose.js +1 -1
  73. package/dist/prod/internal/dispose.js.map +1 -1
  74. package/dist/prod/internal/flags.js +1 -1
  75. package/dist/prod/internal/flags.js.map +1 -1
  76. package/dist/prod/internal/graph.js +1 -1
  77. package/dist/prod/internal/graph.js.map +1 -1
  78. package/dist/prod/internal/owner.js +1 -1
  79. package/dist/prod/internal/owner.js.map +1 -1
  80. package/dist/prod/internal/scheduler.js +1 -1
  81. package/dist/prod/internal/scheduler.js.map +1 -1
  82. package/dist/prod/list.js +1 -1
  83. package/dist/prod/list.js.map +1 -1
  84. package/dist/prod/memo.js +1 -1
  85. package/dist/prod/memo.js.map +1 -1
  86. package/dist/prod/ownership.js +1 -1
  87. package/dist/prod/ownership.js.map +1 -1
  88. package/dist/prod/props.js.map +1 -1
  89. package/dist/prod/reaction.js +1 -1
  90. package/dist/prod/reaction.js.map +1 -1
  91. package/dist/prod/reducer.js +1 -1
  92. package/dist/prod/reducer.js.map +1 -1
  93. package/dist/prod/resource.js +1 -1
  94. package/dist/prod/resource.js.map +1 -1
  95. package/dist/prod/selector.js +1 -1
  96. package/dist/prod/selector.js.map +1 -1
  97. package/dist/prod/signal.js +1 -1
  98. package/dist/prod/signal.js.map +1 -1
  99. package/dist/prod/store/nodes.js +1 -1
  100. package/dist/prod/store/nodes.js.map +1 -1
  101. package/dist/prod/store/use-store.js.map +1 -1
  102. package/dist/prod/transitions.js +1 -1
  103. package/dist/prod/transitions.js.map +1 -1
  104. package/dist/server/action.js +1 -1
  105. package/dist/server/action.js.map +1 -1
  106. package/dist/server/cache.js +1 -1
  107. package/dist/server/cache.js.map +1 -1
  108. package/dist/server/effect.js.map +1 -1
  109. package/dist/server/extend/index.js +1 -1
  110. package/dist/server/extend/index.js.map +1 -1
  111. package/dist/server/external-store.js.map +1 -1
  112. package/dist/server/internal/concurrency.js +1 -1
  113. package/dist/server/internal/concurrency.js.map +1 -1
  114. package/dist/server/internal/diagnostics.js +1 -1
  115. package/dist/server/internal/diagnostics.js.map +1 -1
  116. package/dist/server/internal/dispose.js +1 -1
  117. package/dist/server/internal/dispose.js.map +1 -1
  118. package/dist/server/internal/flags.js +1 -1
  119. package/dist/server/internal/flags.js.map +1 -1
  120. package/dist/server/internal/graph.js +1 -1
  121. package/dist/server/internal/graph.js.map +1 -1
  122. package/dist/server/internal/owner.js +1 -1
  123. package/dist/server/internal/owner.js.map +1 -1
  124. package/dist/server/internal/scheduler.js +1 -1
  125. package/dist/server/internal/scheduler.js.map +1 -1
  126. package/dist/server/list.js +1 -1
  127. package/dist/server/list.js.map +1 -1
  128. package/dist/server/memo.js +1 -1
  129. package/dist/server/memo.js.map +1 -1
  130. package/dist/server/ownership.js +1 -1
  131. package/dist/server/ownership.js.map +1 -1
  132. package/dist/server/props.js.map +1 -1
  133. package/dist/server/reaction.js +1 -1
  134. package/dist/server/reaction.js.map +1 -1
  135. package/dist/server/reducer.js +1 -1
  136. package/dist/server/reducer.js.map +1 -1
  137. package/dist/server/resource.js +1 -1
  138. package/dist/server/resource.js.map +1 -1
  139. package/dist/server/selector.js +1 -1
  140. package/dist/server/selector.js.map +1 -1
  141. package/dist/server/signal.js +1 -1
  142. package/dist/server/signal.js.map +1 -1
  143. package/dist/server/store/nodes.js +1 -1
  144. package/dist/server/store/nodes.js.map +1 -1
  145. package/dist/server/store/use-store.js.map +1 -1
  146. package/dist/server/transitions.js.map +1 -1
  147. package/dist/server-dev/action.js +11 -7
  148. package/dist/server-dev/action.js.map +1 -1
  149. package/dist/server-dev/cache.js +5 -3
  150. package/dist/server-dev/cache.js.map +1 -1
  151. package/dist/server-dev/effect.js.map +1 -1
  152. package/dist/server-dev/extend/index.js +7 -7
  153. package/dist/server-dev/extend/index.js.map +1 -1
  154. package/dist/server-dev/external-store.js.map +1 -1
  155. package/dist/server-dev/internal/concurrency.js +56 -30
  156. package/dist/server-dev/internal/concurrency.js.map +1 -1
  157. package/dist/server-dev/internal/diagnostics.js +0 -2
  158. package/dist/server-dev/internal/diagnostics.js.map +1 -1
  159. package/dist/server-dev/internal/dispose.js +1 -1
  160. package/dist/server-dev/internal/dispose.js.map +1 -1
  161. package/dist/server-dev/internal/flags.js +1 -3
  162. package/dist/server-dev/internal/flags.js.map +1 -1
  163. package/dist/server-dev/internal/graph.js +47 -69
  164. package/dist/server-dev/internal/graph.js.map +1 -1
  165. package/dist/server-dev/internal/owner.js +22 -30
  166. package/dist/server-dev/internal/owner.js.map +1 -1
  167. package/dist/server-dev/internal/scheduler.js +44 -73
  168. package/dist/server-dev/internal/scheduler.js.map +1 -1
  169. package/dist/server-dev/list.js +4 -12
  170. package/dist/server-dev/list.js.map +1 -1
  171. package/dist/server-dev/memo.js +4 -4
  172. package/dist/server-dev/memo.js.map +1 -1
  173. package/dist/server-dev/ownership.js +59 -3
  174. package/dist/server-dev/ownership.js.map +1 -1
  175. package/dist/server-dev/props.js +18 -11
  176. package/dist/server-dev/props.js.map +1 -1
  177. package/dist/server-dev/reaction.js +5 -1
  178. package/dist/server-dev/reaction.js.map +1 -1
  179. package/dist/server-dev/reducer.js +1 -1
  180. package/dist/server-dev/reducer.js.map +1 -1
  181. package/dist/server-dev/resource.js +24 -15
  182. package/dist/server-dev/resource.js.map +1 -1
  183. package/dist/server-dev/selector.js +1 -5
  184. package/dist/server-dev/selector.js.map +1 -1
  185. package/dist/server-dev/signal.js +3 -3
  186. package/dist/server-dev/signal.js.map +1 -1
  187. package/dist/server-dev/store/nodes.js +10 -4
  188. package/dist/server-dev/store/nodes.js.map +1 -1
  189. package/dist/server-dev/store/use-store.js.map +1 -1
  190. package/dist/server-dev/transitions.js.map +1 -1
  191. package/package.json +2 -1
@@ -1 +1 @@
1
- {"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":"A,wCAwCA,SAAgBA,EACd,EACA,EACA,EACoC,CACpC,GAAM,CAACC,EAAOC,GAAYC,EAAaC,EAAc,CACnD,OAASC,GAAS,QAAU,OAAO,GACnC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EAID,MAAO,CAACJ,EAHU,GAAoB,CACpCC,EAAU,GAAaI,EAAQC,EAAUC,CAAM,CAAC,CAClD,CACuB,CACzB,C"}
1
+ {"version":3,"file":"reducer.js","names":["useReducer","state","setState","useSignal","initialState","options","reducer","previous","action"],"sources":["../../src/reducer.ts"],"sourcesContent":["import type { Accessor, Equals } from \"./extend\";\nimport { useSignal } from \"./signal\";\n\n/** Options of {@link useReducer}. @since 1.0.0 */\nexport interface ReducerOptions {\n /**\n * Decides whether a new state is a change: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<unknown>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the state is unnamed)\n */\n name?: string;\n}\n\n/**\n * A state cell whose writes go through a reducer: `dispatch(action)` stores\n * `reducer(state, action)`. Equivalent to `useSignal` with the transition written in one place,\n * which keeps every state change of a complex value (a form, a queue) in one function. Reads are\n * fresh immediately after `dispatch`, like every write.\n *\n * @param reducer Pure function `(state, action) => next`.\n * @param initialState Starting state, stored as is.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns `[state, dispatch]`; `state()` tracks, `dispatch(action)` returns nothing. The reducer\n * runs untracked, once per dispatch.\n * @throws ShadowError `WRITE_IN_MEMO` from `dispatch`, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `dispatch` also rethrows what the reducer throws.\n * @example\n * import { useReducer } from \"@shadow-js/core\";\n *\n * type Action = \"inc\" | \"dec\";\n * const [count, dispatch] = useReducer((n: number, a: Action) => (a === \"inc\" ? n + 1 : n - 1), 0);\n * dispatch(\"inc\");\n * console.log(count()); // 1\n * @see useSignal\n * @since 1.0.0\n */\nexport function useReducer<S, A>(\n reducer: (state: S, action: A) => S,\n initialState: S,\n options?: ReducerOptions,\n): [Accessor<S>, (action: A) => void] {\n const [state, setState] = useSignal<S>(initialState, {\n equals: (options?.equals ?? Object.is) as Equals<S>,\n name: options?.name,\n });\n const dispatch = (action: A): void => {\n setState((previous) => reducer(previous, action));\n };\n return [state, dispatch];\n}\n"],"mappings":"A,wCAwCA,SAAgBA,EACd,EACA,EACA,EACoC,CACpC,GAAM,CAACC,EAAOC,GAAYC,EAAaC,EAAc,CACnD,OAASC,GAAS,QAAU,OAAO,GACnC,KAAMA,GAAS,IACjB,CAAC,EAID,MAAO,CAACJ,EAHU,GAAoB,CACpCC,EAAU,GAAaI,EAAQC,EAAUC,CAAM,CAAC,CAClD,CACuB,CACzB,C"}
@@ -1,2 +1,2 @@
1
- import{readSignal as e}from"./internal/graph.js";import{batch as t}from"./internal/scheduler.js";import{onCleanup as n,untrack as r}from"./ownership.js";import{useRenderEffect as i}from"./effect.js";import{useContext as a}from"./context.js";import{ResourceCacheContext as o,SuspenseContext as s}from"./suspense.js";import{holdReader as c,inTransition as l}from"./internal/concurrency.js";import{createSignalNode as u,currentListener as d,writeSignal as f}from"./extend/index.js";function p(t,n){let r=u(t,n?Object.is:!1);return[()=>e(r),e=>{f(r,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,u,f){let h=typeof u==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?u:(e,t)=>_(t),y=(h?f:u)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=a(o),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,n)=>P||e!==M?!1:(t(n),L(),!0),z=(e,n)=>{if(A!==void 0&&!j&&!n)return j=!0,F=!0,t(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let i=new AbortController;N=i,M+=1;let a=M;t(()=>{T(F?`refreshing`:`pending`),D(void 0)});let o;try{let t=n||O===null||k===void 0?void 0:O.pending?.(k);o=t===void 0?r(()=>v(e,{signal:i.signal,refetching:n,value:r(x)})):t}catch(e){return R(a,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(o))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(o),{deferStream:y.deferStream}),Promise.resolve(o).then(e=>R(a,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(a,()=>{D(e),T(`errored`)})});let s=o,c=R(a,()=>{F=!0,S(s),T(`ready`)});return Promise.resolve(c?s:void 0)},B=e=>{e===!1||e==null?(N?.abort(),M+=1,L(),T(F?`ready`:`unresolved`)):z(e,F)},V=(()=>{let e=C();if(e===`errored`)throw E();if(e===`pending`){let e=a(s);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&d()!==null&&l()&&c(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{let e=r(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let n;return t(()=>{n=typeof e==`function`?e(r(x)):e,N?.abort(),M+=1,F=!0,S(n),D(void 0),T(`ready`)}),L(),n}}}),i(g,B),n(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
1
+ import{Signal as e,readSignal as t}from"./internal/graph.js";import{batch as n}from"./internal/scheduler.js";import{onCleanup as r,untrack as i}from"./ownership.js";import{useRenderEffect as a}from"./effect.js";import{useContext as o}from"./context.js";import{ResourceCacheContext as s,SuspenseContext as c}from"./suspense.js";import{holdReader as l,inTransition as u}from"./internal/concurrency.js";import{currentListener as d,writeSignal as f}from"./extend/index.js";function p(n,r){let i=new e(n,r?Object.is:!1);return[()=>t(i),e=>{f(i,e,{allowInMemo:!0})}]}function m(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function h(e,t,f){let h=typeof t==`function`,g=h?typeof e==`function`?e:()=>e:()=>!0,_=e,v=h?t:(e,t)=>_(t),y=(h?f:t)??{},b=`initialValue`in y,[x,S]=p(y.initialValue,!1),[C,w]=p(b?`ready`:`unresolved`,!0),T=e=>{w(e)},[E,D]=p(void 0,!1),O=o(s),k=O===null?void 0:O.key(y.key),A=O!==null&&k!==void 0?O.read(k):void 0,j=!1,M=0,N,P=!1,F=b,I=/* @__PURE__ */ new Set,L=()=>{if(I.size===0)return;let e=[...I];I.clear();for(let t of e)t.decrement()},R=(e,t)=>{if(P||e!==M)return!1;try{n(t)}finally{L()}return!0},z=(e,t)=>{if(A!==void 0&&!j&&!t)return j=!0,F=!0,n(()=>{S(A.value),T(`ready`)}),Promise.resolve(A.value);N?.abort();let r=new AbortController;N=r,M+=1;let a=M;n(()=>{T(F?`refreshing`:`pending`),D(void 0)});let o;try{let n=t||O===null||k===void 0?void 0:O.pending?.(k);o=n===void 0?i(()=>v(e,{signal:r.signal,refetching:t,value:i(x)})):n}catch(e){return R(a,()=>{D(e),T(`errored`)}),Promise.resolve(void 0)}if(m(o))return O!==null&&k!==void 0&&O.track(k,Promise.resolve(o),{deferStream:y.deferStream}),Promise.resolve(o).then(e=>R(a,()=>{F=!0,S(e),T(`ready`)})?e:void 0,e=>{R(a,()=>{D(e),T(`errored`)})});let s=o,c=R(a,()=>{F=!0,S(s),T(`ready`)});return Promise.resolve(c?s:void 0)},B=e=>{e===!1||e==null?(N?.abort(),M+=1,L(),T(F?`ready`:`unresolved`)):z(e,F)},V=(()=>{let e=C();if(e===`errored`)throw E();if(e===`pending`){let e=o(c);e!==null&&!I.has(e)&&(I.add(e),e.increment()),e!==null&&d()!==null&&u()&&l(e)}return x()});return Object.defineProperties(V,{state:{get:C},loading:{get:()=>C()===`pending`||C()===`refreshing`},error:{get:E},latest:{get:x},refetch:{value:()=>{if(P)return Promise.resolve(void 0);let e=i(g);return e===!1||e==null?Promise.resolve(void 0):z(e,F)}},mutate:{value:e=>{let t,r=!1;try{n(()=>{t=typeof e==`function`?i(()=>e(x())):e,r=!0,N?.abort(),M+=1,F=!0,S(t),D(void 0),T(`ready`)})}finally{r&&L()}return t}}}),a(g,B),r(()=>{P=!0,N?.abort(),L()}),V}export{h as useResource};
2
2
  //# sourceMappingURL=resource.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"resource.js","names":["cell","node","createSignalNode","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","useRenderEffect","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n createSignalNode,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = createSignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n batch(apply);\n release();\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? (next as (previous: T | undefined) => T)(untrack(value))\n : next;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n release();\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,+dAkGA,SAASA,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAOC,EAAoBC,EAASC,EAAW,OAAO,GAAK,EAAK,EACtE,MAAO,KACCC,EAAWJ,CAAI,EACpB,GAAS,CACRK,EAAYL,EAAMM,EAAM,CAAE,YAAa,EAAK,CAAC,CAC/C,CACF,CACF,CAEA,SAASC,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiFA,SAAgBC,EACd,EACA,EACA,EACa,CACb,IAAMC,EAAY,OAAOC,GAAW,WAE9BC,EACJF,EAAa,OAAOG,GAAU,WAAaA,MAAcA,MAAe,GAEpEC,EAAUD,EACVE,EAAWL,EAAYC,GAAU,EAAW,IAA0BG,EAAQE,CAAI,EAIlFC,GAAWP,EAAYQ,EAASP,IAA8C,CAAC,EAE/EQ,EAAa,iBAAkBF,EAG/B,CAACT,EAAOY,GAAYrB,EAAoBkB,EAAQ,aAAc,EAAK,EACnE,CAACI,EAAOC,GAAcvB,EAAoBoB,EAAa,QAAU,aAAc,EAAI,EAGnFI,EAAY,GAA8B,CAC9CD,EAAWhB,CAAI,CAIjB,EACM,CAACkB,EAASC,GAAc1B,EAAc,IAAA,GAAW,EAAK,EACtD2B,EAAQC,EAAWC,CAAoB,EACvCC,EAAWH,IAAU,KAAO,IAAA,GAAYA,EAAM,IAAIT,EAAQ,GAAG,EAC7Da,EAASJ,IAAU,MAAQG,IAAa,IAAA,GAAYH,EAAM,KAAKG,CAAQ,EAAI,IAAA,GAC7EE,EAAY,GAEZC,EAAU,EACVC,EACAC,EAAW,GAEXC,EAAWhB,EAGTi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CAC7B,CACF,EACA,OAAQ,CACN,MAAQ,GAAkD,CACxD,IAAI0B,EAcJ,OAbAnB,MAAY,CACV,EACE,OAAOpC,GAAS,WACXA,EAAwC2C,EAAQzC,CAAK,CAAC,EACvDF,EACN2B,GAAY,MAAM,EAClB,GAAW,EACX,EAAW,GACXb,EAASyC,CAAa,EACtBpC,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,EACDc,EAAQ,EACDwB,CACT,CACF,CACF,CAAC,EAOIC,EAAgBlD,EAAQ2C,CAAQ,EACrCQ,MAAgB,CACd,EAAW,GACX9B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
1
+ {"version":3,"file":"resource.js","names":["SignalNode","cell","node","Signal","initial","distinct","readSignal","writeSignal","next","isPromiseLike","value","useResource","hasSource","second","source","first","oneShot","fetcher","info","options","third","hasInitial","setValue","state","writeState","setState","failure","setFailure","cache","useContext","ResourceCacheContext","cacheKey","cached","usedCache","version","controller","disposed","hasValue","holders","release","held","tracker","settle","id","batch","apply","load","refetching","current","output","joined","untrack","input","error","result","immediate","applied","onSource","read","SuspenseContext","currentListener","inTransition","holdReader","resolved","changed","useRenderEffect","onCleanup"],"sources":["../../src/resource.ts"],"sourcesContent":["import { useContext } from \"./context\";\nimport { useRenderEffect } from \"./effect\";\nimport {\n type Accessor,\n batch,\n currentListener,\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n holdReader,\n inTransition,\n readSignal,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\nimport { ResourceCacheContext, SuspenseContext, type SuspenseTracker } from \"./suspense\";\n\n/**\n * Where a {@link Resource} is in its life: `\"unresolved\"` (no value and no fetch, for example while\n * the source is falsy), `\"pending\"` (the first fetch is in flight), `\"ready\"` (a value is shown and\n * nothing is in flight), `\"refreshing\"` (a value is shown while a newer fetch runs) or `\"errored\"`\n * (the last fetch failed; reading the resource throws).\n * @since 1.0.0\n */\nexport type ResourceState = \"unresolved\" | \"pending\" | \"ready\" | \"refreshing\" | \"errored\";\n\n/** Passed to every fetcher call. @since 1.0.0 */\nexport interface ResourceInfo<T = unknown> {\n /** Aborted when a newer fetch starts or the owner is disposed. */\n signal: AbortSignal;\n /** True when this call was started by `refetch()` or a source change after a value existed. */\n refetching: boolean;\n /** The last value, if any. */\n value: T | undefined;\n}\n\n/**\n * Options of {@link useResource}.\n * @since 1.0.0\n */\nexport interface ResourceOptions<T> {\n /**\n * Value shown before the first fetch settles. With it the resource never reads as `\"pending\"`: the\n * first fetch still runs, as a refresh (`\"refreshing\"`, `info.refetching` true), and never\n * suspends. A key that is present with the value `undefined` counts as given.\n * @default No initial value: the first fetch reads as `\"pending\"` and suspends its readers.\n */\n initialValue?: T;\n /**\n * The key that matches the value a server render recorded with the resource that hydrates it.\n * Give one when the creation order may differ between server and client.\n * @default undefined (a key is generated from the resource's position in the render)\n */\n key?: string;\n /**\n * On the server, the streamed response holds its first flush until this resource settles, so its value\n * is in the shell (the first chunk) and not in a later chunk behind a fallback. A resource that\n * rejects does not hold the stream: its fallback stays. Only resources created while the shell renders\n * hold it; a resource created later, by a streamed boundary, streams as usual. Other renderers\n * (`renderToString`, `renderToStringAsync`) already wait for every resource, so the option has no\n * effect there. Matches Solid's option of the same name.\n * @default false\n */\n deferStream?: boolean;\n /**\n * Label shown by devtools next to the resource's state changes. It has no effect on caching or on\n * the server key (use `key` for that) and costs nothing in production builds, where devtools reporting\n * is removed.\n * @default undefined (the resource is unnamed)\n */\n name?: string;\n}\n\n/** Reactive handle to an asynchronous value. @since 1.0.0 */\nexport interface Resource<T> extends Accessor<T | undefined> {\n /** The current {@link ResourceState}. Tracked when read in an effect or memo. */\n readonly state: ResourceState;\n /** True while a fetch is in flight (`\"pending\"` or `\"refreshing\"`). Tracked. */\n readonly loading: boolean;\n /** The error of the last fetch, or `undefined` when it did not fail. Tracked; never throws. */\n readonly error: unknown;\n /** The last successfully loaded value; unlike the call form it never throws or suspends. */\n readonly latest: T | undefined;\n /**\n * Fetches again (keeping the previous value visible). The promise resolves with the new value,\n * or with `undefined` when the fetch failed (see `error`) or a newer one replaced it; it never\n * rejects, so a call you do not await is safe.\n */\n refetch(): Promise<T | undefined>;\n /** Replaces the value without fetching, cancels a fetch in flight, and returns the new value. */\n mutate(value: T | ((previous: T | undefined) => T)): T;\n}\n\n/**\n * A signal cell whose writes are allowed everywhere (see {@link createSignalNode}). `distinct`\n * false notifies on every write, true only when the value changes.\n */\nfunction cell<T>(initial: T, distinct: boolean): [Accessor<T>, (next: T) => void] {\n const node = new SignalNode<T>(initial, distinct ? Object.is : false);\n return [\n () => readSignal(node),\n (next) => {\n writeSignal(node, next, { allowInMemo: true });\n },\n ];\n}\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * Loads data asynchronously and exposes it reactively. Reading it while the first load is pending\n * holds the nearest `<Suspense>` boundary around the reader (not the creator) in its fallback;\n * reading it after a failure throws the error to the nearest error boundary. Refetching keeps the previous\n * value visible (`state === \"refreshing\"`) and never re-suspends.\n *\n * Two forms: `useResource(fetcher)` fetches once; `useResource(source, fetcher)` refetches whenever\n * `source()` changes and stays `unresolved` while it is `false`, `null` or `undefined`.\n *\n * `T` is inferred from what the fetcher returns. `info.value` is typed `unknown` unless the\n * parameter is annotated: `(info: ResourceInfo<User>) => ...`.\n *\n * @param fetcher Called untracked, once at creation (skipped when a server render already provided\n * the value) and again for every `refetch()`. It receives an abort signal, the `refetching` flag\n * and the last value; it returns the value or a promise.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource: call it to read the value; `state`, `loading`, `error`, `latest`,\n * `refetch` and `mutate` are on the same function.\n * @throws Nothing itself: a fetcher that throws or rejects makes the resource `\"errored\"`. Reading\n * the resource then rethrows that error, so the nearest error boundary receives it.\n * @example\n * import { useResource } from \"@shadow-js/core\";\n *\n * function Clock() {\n * const time = useResource(({ signal }) => fetch(\"/api/time\", { signal }).then((r) => r.text()));\n * return <p>{time.loading ? \"Loading...\" : time()}</p>;\n * }\n * @see ResourceOptions\n * @see cache\n * @since 1.0.0\n */\nexport function useResource<T>(\n fetcher: (info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n/**\n * Source form of {@link useResource}: fetches for each value of `source`, and refetches whenever it\n * changes. While `source()` is `false`, `null` or `undefined` nothing is fetched and the resource\n * stays `\"unresolved\"` (or keeps its value, `\"ready\"`). A newer fetch aborts the previous one, whose\n * late result is ignored.\n *\n * @param source Tracked; its value is passed to `fetcher`. A plain value fetches once.\n * @param fetcher Called untracked with the source value and the fetch info.\n * @param options Initial value, server key and a devtools name. Undefined uses the defaults.\n * @returns The resource (see {@link Resource}).\n * @throws Nothing itself. Reading the resource rethrows the error of a failed fetch.\n * @example\n * import { useResource, useSignal } from \"@shadow-js/core\";\n *\n * function UserCard() {\n * const [id] = useSignal(1);\n * const user = useResource(id, (id, { signal }) =>\n * fetch(`/api/users/${id}`, { signal }).then((r) => r.json() as Promise<{ name: string }>),\n * );\n * return <p>{user()?.name}</p>;\n * }\n * @since 1.0.0\n */\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// A source that is a plain value fetches once for that value.\nexport function useResource<S extends string | number | boolean | bigint | object, T>(\n source: S,\n fetcher: (source: S, info: ResourceInfo) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\n// Annotating the info parameter (`(info: ResourceInfo<User>) => ...`) types `info.value`.\nexport function useResource<T>(\n fetcher: (info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n source: Accessor<S | false | null | undefined>,\n fetcher: (source: S, info: ResourceInfo<T>) => T | Promise<T>,\n options?: ResourceOptions<T>,\n): Resource<T>;\nexport function useResource<S, T>(\n first: unknown,\n second?: unknown,\n third?: ResourceOptions<T>,\n): Resource<T> {\n const hasSource = typeof second === \"function\";\n // The source is an accessor, or a plain value that never changes (a function is always an accessor).\n const source = (\n hasSource ? (typeof first === \"function\" ? first : () => first) : () => true\n ) as Accessor<S | false | null | undefined>;\n const oneShot = first as (info: ResourceInfo<T>) => T | Promise<T>;\n const fetcher = (hasSource ? second : (_input: S, info: ResourceInfo<T>) => oneShot(info)) as (\n source: S,\n info: ResourceInfo<T>,\n ) => T | Promise<T>;\n const options = (hasSource ? third : (second as ResourceOptions<T> | undefined)) ?? {};\n\n const hasInitial = \"initialValue\" in options;\n // Extension-API cells: a resource may be created (and so start loading) while a memo computes,\n // for example when a router renders a route inside one. Its own state is not a derived value.\n const [value, setValue] = cell<T | undefined>(options.initialValue, false);\n const [state, writeState] = cell<ResourceState>(hasInitial ? \"ready\" : \"unresolved\", true);\n // Filled below with the accessor users hold, so devtools can name the resource that changed.\n let handle: unknown;\n const setState = (next: ResourceState): void => {\n writeState(next);\n if (__DEV__) {\n devtoolsReport(DEVTOOLS_EVENT.RESOURCE_STATE, handle, next, options.name, currentOwner());\n }\n };\n const [failure, setFailure] = cell<unknown>(undefined, false);\n const cache = useContext(ResourceCacheContext);\n const cacheKey = cache === null ? undefined : cache.key(options.key);\n const cached = cache !== null && cacheKey !== undefined ? cache.read(cacheKey) : undefined;\n let usedCache = false;\n\n let version = 0;\n let controller: AbortController | undefined;\n let disposed = false;\n let lastSource: S | undefined;\n let hasValue = hasInitial;\n // Boundaries held by readers: whoever reads this resource while it is pending, inside a\n // <Suspense>, keeps that boundary showing its fallback until the first load settles.\n const holders = new Set<SuspenseTracker>();\n\n const release = (): void => {\n if (holders.size === 0) return;\n const held = [...holders];\n holders.clear();\n for (const tracker of held) tracker.decrement();\n };\n\n /** Applies a result unless a newer load or a dispose made it stale; says whether it applied. */\n const settle = (id: number, apply: () => void): boolean => {\n if (disposed || id !== version) return false;\n // The flush that ends the batch throws what no handler took (a reader that failed): the boundary\n // must be released regardless, or it would show its fallback forever.\n try {\n batch(apply);\n } finally {\n release();\n }\n return true;\n };\n\n /** Starts a load. The promise resolves with the value, or undefined when it failed or went stale. */\n const load = (input: S, refetching: boolean): Promise<T | undefined> => {\n if (cached !== undefined && !usedCache && !refetching) {\n // Server data (hydration) or a previous server pass: no fetch needed for the first load.\n usedCache = true;\n hasValue = true;\n batch(() => {\n setValue(cached.value as T);\n setState(\"ready\");\n });\n return Promise.resolve(cached.value as T);\n }\n controller?.abort();\n const current = new AbortController();\n controller = current;\n version += 1;\n const id = version;\n batch(() => {\n setState(hasValue ? \"refreshing\" : \"pending\");\n setFailure(undefined);\n });\n let output: T | Promise<T>;\n try {\n // A fetch an earlier pass of the same render still runs is joined, not repeated (a refetch never joins).\n const joined =\n refetching || cache === null || cacheKey === undefined\n ? undefined\n : cache.pending?.(cacheKey);\n output =\n joined !== undefined\n ? (joined as Promise<T>)\n : untrack(() =>\n fetcher(input, { signal: current.signal, refetching, value: untrack(value) }),\n );\n } catch (error) {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return Promise.resolve(undefined);\n }\n if (isPromiseLike<T>(output)) {\n if (cache !== null && cacheKey !== undefined)\n cache.track(cacheKey, Promise.resolve(output), {\n deferStream: options.deferStream,\n });\n return Promise.resolve(output).then(\n (result) =>\n settle(id, () => {\n hasValue = true;\n setValue(result);\n setState(\"ready\");\n })\n ? result\n : undefined,\n (error: unknown) => {\n settle(id, () => {\n setFailure(error);\n setState(\"errored\");\n });\n return undefined;\n },\n );\n }\n const immediate = output;\n const applied = settle(id, () => {\n hasValue = true;\n setValue(immediate);\n setState(\"ready\");\n });\n return Promise.resolve(applied ? immediate : undefined);\n };\n\n const onSource = (input: S | false | null | undefined): void => {\n if (input === false || input === null || input === undefined) {\n controller?.abort();\n version += 1;\n release();\n setState(hasValue ? \"ready\" : \"unresolved\");\n return;\n }\n lastSource = input;\n load(input, hasValue);\n };\n const read = (() => {\n const current = state();\n if (current === \"errored\") throw failure();\n if (current === \"pending\") {\n const tracker = useContext(SuspenseContext);\n if (tracker !== null && !holders.has(tracker)) {\n holders.add(tracker);\n tracker.increment();\n }\n // A transition reading pending data inside a boundary that shows content: the reader keeps its\n // previous value instead of showing this loading state (React's \"keep content while suspended\").\n if (tracker !== null && currentListener() !== null && inTransition()) holdReader(tracker);\n }\n return value();\n }) as Resource<T>;\n\n Object.defineProperties(read, {\n state: { get: state },\n loading: { get: () => state() === \"pending\" || state() === \"refreshing\" },\n error: { get: failure },\n latest: { get: value },\n refetch: {\n value: (): Promise<T | undefined> => {\n // A disposed resource has aborted its fetch and owns no controller any more: a new fetch would\n // run unabortable and its result would be thrown away.\n if (disposed) return Promise.resolve(undefined);\n const input = untrack(source);\n if (input === false || input === null || input === undefined)\n return Promise.resolve(undefined);\n lastSource = input;\n return load(input, hasValue);\n },\n },\n mutate: {\n value: (next: T | ((previous: T | undefined) => T)): T => {\n let resolved: T | undefined;\n // A throwing updater changes nothing, so the boundaries it holds stay held.\n let changed = false;\n try {\n batch(() => {\n resolved =\n typeof next === \"function\"\n ? untrack(() => (next as (previous: T | undefined) => T)(value()))\n : next;\n changed = true;\n controller?.abort();\n version += 1;\n hasValue = true;\n setValue(resolved as T);\n setFailure(undefined);\n setState(\"ready\");\n });\n } finally {\n if (changed) release();\n }\n return resolved as T;\n },\n },\n });\n void lastSource;\n // The accessor must exist before the first load starts: its first state report (pending) names it\n // to devtools, and a report about a handle that is still unassigned would be dropped.\n handle = read;\n // On the server nothing is reactive: read the source once and start the fetch.\n if (__SERVER__) onSource(untrack(source));\n else useRenderEffect(source, onSource);\n onCleanup(() => {\n disposed = true;\n controller?.abort();\n release();\n });\n return read;\n}\n"],"mappings":"A,qdAkGA,SAASC,EAAQ,EAAY,EAAqD,CAChF,IAAMC,EAAO,IAAIF,EAAcI,EAASC,EAAW,OAAO,GAAK,EAAK,EACpE,MAA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AU,GACV2B,GAAY,MAAM,EAClB,GAAW,EACX,EAAW,GACXb,EAASyC,CAAa,EACtBpC,EAAW,IAAA,EAAS,EACpBF,EAAS,OAAO,CAClB,CAAC,CACH,QAAU,CACJuC,GAASzB,EAAQ,CACvB,CACA,OAAOwB,CACT,CACF,CACF,CAAC,EAOIE,EAAgBnD,EAAQ2C,CAAQ,EACrCS,MAAgB,CACd,EAAW,GACX/B,GAAY,MAAM,EAClBI,EAAQ,CACV,CAAC,EACMmB,CACT,C"}
@@ -1,2 +1,2 @@
1
- import{track as e}from"./internal/graph.js";import{onCleanup as t,untrack as n}from"./ownership.js";import{useRenderEffect as r}from"./effect.js";import{isTracking as i,notify as a}from"./extend/index.js";var o=class{kind=0;observers=null;stamp=0;subscribers=0;key;value;constructor(e,t){this.key=e,this.value=t}};function s(e,t){e.value!==t&&(e.value=t,a(e))}function c(a,c){let l=/* @__PURE__ */ new Map,u=null,d=(e,t)=>c===void 0?e===t:c(e,t),f=()=>u===null?n(a):u.value,p=e=>{--e.subscribers,e.subscribers===0&&l.get(e.key)===e&&l.delete(e.key)},m=e=>{let t=new o(e,d(e,f()));return l.set(e,t),t};return r(()=>a(),e=>{let t=u;if(u={value:e},t!==null&&c===void 0){if(t.value===e)return;let n=l.get(t.value);n!==void 0&&s(n,n.key===e);let r=l.get(e);r!==void 0&&s(r,r.key===e);return}let n=!1,r;for(let t of l.values()){let i;try{i=d(t.key,e)}catch(e){n||(n=!0,r=e);continue}s(t,i)}if(n)throw r}),n=>{if(!i())return d(n,a());let r=l.get(n)??m(n);return r.subscribers+=1,t(()=>p(r)),e(r),r.value}}export{c as useSelector};
1
+ import{track as e}from"./internal/graph.js";import{onCleanup as t,untrack as n}from"./ownership.js";import{useRenderEffect as r}from"./effect.js";import{isTracking as i,notify as a}from"./extend/index.js";var o=class{kind=0;observers=null;stamp=0;subscribers=0;constructor(e,t){this.key=e,this.value=t}};function s(e,t){e.value!==t&&(e.value=t,a(e))}function c(a,c){let l=/* @__PURE__ */ new Map,u=null,d=(e,t)=>c===void 0?e===t:c(e,t),f=()=>u===null?n(a):u.value,p=e=>{--e.subscribers,e.subscribers===0&&l.get(e.key)===e&&l.delete(e.key)},m=e=>{let t=new o(e,n(()=>d(e,f())));return l.set(e,t),t};return r(()=>a(),e=>{let t=u;if(u={value:e},t!==null&&c===void 0){if(t.value===e)return;let n=l.get(t.value);n!==void 0&&s(n,n.key===e);let r=l.get(e);r!==void 0&&s(r,r.key===e);return}let n=!1,r;for(let t of l.values()){let i;try{i=d(t.key,e)}catch(e){n||(n=!0,r=e);continue}s(t,i)}if(n)throw r}),n=>{if(!i())return d(n,a());let r=l.get(n)??m(n);return r.subscribers+=1,t(()=>p(r)),e(r),r.value}}export{c as useSelector};
2
2
  //# sourceMappingURL=selector.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"selector.js","names":["Entry","key","value","setEntry","entry","selected","notify","useSelector","entries","last","matches","equals","currentValue","untrack","source","release","create","useRenderEffect","previous","next","before","after","failed","failure","error","isTracking","onCleanup","track"],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n readonly key: unknown;\n /** Whether the key matches the selected value. */\n value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n const entry = new Entry(key, matches(key, currentValue()));\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":"A,6MAQA,IAAMA,EAAN,KAAkC,CAEhC,KAAgB,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAGd,IAEA,MAEA,YAAY,EAAc,EAAgB,CACxC,KAAK,IAAMC,EACX,KAAK,MAAQC,CACf,CACF,EAGA,SAASC,EAAS,EAAc,EAAyB,CACnDC,EAAM,QAAUC,IACpB,EAAM,MAAQA,EACdC,EAAOF,CAAK,EACd,CAgCA,SAAgBG,EACd,EACA,EACqB,CACrB,IAAMC,kBAAU,IAAI,IAEhBC,EAAqC,KAEnCC,GAAW,EAAQ,IACvBC,IAAW,IAAA,GAAaV,IAAoBC,EAAQS,EAAOV,EAAKC,CAAK,EAEjEU,MAAyBH,IAAS,KAAOI,EAAQC,CAAM,EAAIL,EAAK,MAEhEM,EAAW,GAAuB,CACtC,IAAM,YACFX,EAAM,cAAgB,GAAKI,EAAQ,IAAIJ,EAAM,GAAG,IAAMA,GAAOI,EAAQ,OAAOJ,EAAM,GAAG,CAC3F,EAEMY,EAAU,GAAkB,CAChC,IAAMZ,EAAQ,IAAIJ,EAAMC,EAAKS,EAAQT,EAAKW,EAAa,CAAC,CAAC,EAEzD,OADAJ,EAAQ,IAAIP,EAAKG,CAAK,EACfA,CACT,EA8CA,OAnCAa,MACQH,EAAO,EACZ,GAAS,CACR,IAAMI,EAAWT,EAEjB,GADA,EAAO,CAAE,MAAOU,CAAK,EACjBD,IAAa,MAAQP,IAAW,IAAA,GAAW,CAE7C,GAAIO,EAAS,QAAUC,EAAM,OAC7B,IAAMC,EAASZ,EAAQ,IAAIU,EAAS,KAAK,EACrCE,IAAW,IAAA,IAAWjB,EAASiB,EAAQA,EAAO,MAAQD,CAAI,EAC9D,IAAME,EAAQb,EAAQ,IAAIW,CAAI,EAC1BE,IAAU,IAAA,IAAWlB,EAASkB,EAAOA,EAAM,MAAQF,CAAI,EAC3D,MACF,CAGA,IAAIG,EAAS,GACTC,EACJ,IAAK,IAAMnB,KAASI,EAAQ,OAAO,EAAG,CACpC,IAAIH,EACJ,GAAI,CACF,EAAWK,EAAQN,EAAM,IAAUe,CAAI,CACzC,OAASK,EAAO,CACTF,IACH,EAAS,GACT,EAAUE,GAEZ,QACF,CACArB,EAASC,EAAOC,CAAQ,CAC1B,CACA,GAAIiB,EAAQ,MAAMC,CACpB,CACF,EA1CoB,GAAoB,CACtC,GAAI,CAACE,EAAW,EAAG,OAAOf,EAAQT,EAAKa,EAAO,CAAC,EAC/C,IAAMV,EAAQI,EAAQ,IAAIP,CAAG,GAAKe,EAAOf,CAAG,EAI5C,MAHA,GAAM,aAAe,EACrByB,MAAgBX,EAAQX,CAAK,CAAC,EAC9BuB,EAAMvB,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
1
+ {"version":3,"file":"selector.js","names":["Entry","key","value","setEntry","entry","selected","notify","useSelector","entries","last","matches","equals","currentValue","untrack","source","release","create","useRenderEffect","previous","next","before","after","failed","failure","error","isTracking","onCleanup","track"],"sources":["../../src/selector.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { isTracking, notify, type SourceNode, track } from \"./extend\";\nimport { onCleanup, untrack } from \"./ownership\";\n\n/**\n * The boolean for one key, shared by every reader that asked about that key. It is a reactive source itself (the\n * shape `track` and `notify` take), so a key costs one object where a separate signal would cost two.\n */\nclass Entry implements SourceNode {\n /** A source with no sources of its own, like a signal. */\n readonly kind = 0;\n observers: SourceNode[\"observers\"] = null;\n stamp = 0;\n /** Tracked reads whose cleanup has not run yet. The entry is dropped when this reaches 0. */\n subscribers = 0;\n\n /** The key this entry answers for. */\n declare readonly key: unknown;\n /** Whether the key matches the selected value. */\n declare value: boolean;\n\n constructor(key: unknown, value: boolean) {\n this.key = key;\n this.value = value;\n }\n}\n\n/** Writes a key's boolean and notifies its readers only when it actually changed. */\nfunction setEntry(entry: Entry, selected: boolean): void {\n if (entry.value === selected) return;\n entry.value = selected;\n notify(entry);\n}\n\n/**\n * Creates a selection set over `source`. `isSelected(key)` answers whether `key` matches the\n * current source value. Reading it inside an effect or memo subscribes only to that key's boolean,\n * so when the source changes from `a` to `b` only the readers of `a` and `b` re-run, with the\n * default equality. A custom `equals` costs one call per registered key per change.\n *\n * The source is tracked by a render-phase effect in the current owner. Create the selector before\n * its consumers, so that each consumer runs once per change. Calling `isSelected` outside a tracked\n * context reads the source directly and creates no subscription. The default equality is `===`,\n * so `NaN` never matches.\n *\n * @param source The value that selects keys. Tracked.\n * @param equals Optional `(key, value) => boolean`. Undefined uses `key === value`.\n * @returns `isSelected(key)`.\n * @throws Nothing itself. When a custom `equals` throws during a change, the other keys are still\n * updated and the error goes to the owner's error handler. In development, a selector created\n * outside any owner warns `NO_OWNER_EFFECT`.\n * @example\n * import { mapArray, useSelector, useSignal } from \"@shadow-js/core\";\n *\n * function Rows(props: { ids: number[] }) {\n * const [selectedId, setSelectedId] = useSignal(1);\n * const isSelected = useSelector(selectedId);\n * return mapArray(() => props.ids, (id) => (\n * <li classList={{ active: isSelected(id) }} onClick={() => setSelectedId(id)}>{id}</li>\n * ));\n * }\n * @see mapArray\n * @since 1.0.0\n */\nexport function useSelector<T, K = T>(\n source: () => T,\n equals?: (key: K, value: T) => boolean,\n): (key: K) => boolean {\n const entries = new Map<unknown, Entry>();\n /** The value the entries were last reconciled against; `null` until the first successful apply. */\n let last: { readonly value: T } | null = null;\n\n const matches = (key: K, value: T): boolean =>\n equals === undefined ? (key as unknown) === value : equals(key, value);\n\n const currentValue = (): T => (last === null ? untrack(source) : last.value);\n\n const release = (entry: Entry): void => {\n entry.subscribers -= 1;\n if (entry.subscribers === 0 && entries.get(entry.key) === entry) entries.delete(entry.key);\n };\n\n const create = (key: K): Entry => {\n // `equals` is a user callback: it must not subscribe the reader that happens to register the key.\n const entry = new Entry(\n key,\n untrack(() => matches(key, currentValue())),\n );\n entries.set(key, entry);\n return entry;\n };\n\n const isSelected = (key: K): boolean => {\n if (!isTracking()) return matches(key, source());\n const entry = entries.get(key) ?? create(key);\n entry.subscribers += 1;\n onCleanup(() => release(entry));\n track(entry);\n return entry.value;\n };\n\n useRenderEffect(\n () => source(),\n (next) => {\n const previous = last;\n last = { value: next };\n if (previous !== null && equals === undefined) {\n // Default equality: only the entries for the previous and the next key can change.\n if (previous.value === next) return;\n const before = entries.get(previous.value);\n if (before !== undefined) setEntry(before, before.key === next);\n const after = entries.get(next);\n if (after !== undefined) setEntry(after, after.key === next);\n return;\n }\n // Custom equality, or the first successful value: every registered key is checked. A\n // failing equals does not stop the others; its error is rethrown once they are all updated.\n let failed = false;\n let failure: unknown;\n for (const entry of entries.values()) {\n let selected: boolean;\n try {\n selected = matches(entry.key as K, next);\n } catch (error) {\n if (!failed) {\n failed = true;\n failure = error;\n }\n continue;\n }\n setEntry(entry, selected);\n }\n if (failed) throw failure;\n },\n );\n\n return isSelected;\n}\n"],"mappings":"A,6MAQA,IAAMA,EAAN,KAAkC,CAEhC,KAAgB,EAChB,UAAqC,KACrC,MAAQ,EAER,YAAc,EAOd,YAAY,EAAc,EAAgB,CACxC,KAAK,IAAMC,EACX,KAAK,MAAQC,CACf,CACF,EAGA,SAASC,EAAS,EAAc,EAAyB,CACnDC,EAAM,QAAUC,IACpB,EAAM,MAAQA,EACdC,EAAOF,CAAK,E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AAQT,EAAKa,EAAO,CAAC,EAC/C,IAAMV,EAAQI,EAAQ,IAAIP,CAAG,GAAKe,EAAOf,CAAG,EAI5C,MAHA,GAAM,aAAe,EACrByB,MAAgBX,EAAQX,CAAK,CAAC,EAC9BuB,EAAMvB,CAAK,EACJA,EAAM,KACf,CAsCF,C"}
@@ -1,2 +1,2 @@
1
- import{readSignal as e}from"./internal/graph.js";import{untrack as t}from"./ownership.js";import{createSignalNode as n,writeSignal as r}from"./extend/index.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=n(i,o,a?.name);return[()=>e(s),(e=>{let n=typeof e==`function`?t(()=>e(s.value)):e;return r(s,n),n})]}export{i as useSignal};
1
+ import{Signal as e,readSignal as t}from"./internal/graph.js";import{untrack as n}from"./ownership.js";import{writeSignal as r}from"./extend/index.js";function i(i,a){let o=a?.equals===void 0?Object.is:a.equals,s=new e(i,o,a?.name);return[()=>t(s),(e=>{let t=typeof e==`function`?n(()=>e(s.value)):e;return r(s,t),t})]}export{i as useSignal};
2
2
  //# sourceMappingURL=signal.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"signal.js","names":["useSignal","equals","options","signal","createSignalNode","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n createSignalNode,\n type Equals,\n readSignal,\n type Setter,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = createSignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,gKAgDA,SAAgBA,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAASC,EAAoBC,EAAOJ,EAAQC,GAAS,IAAI,EAS/D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
1
+ {"version":3,"file":"signal.js","names":["SignalNode","useSignal","equals","options","signal","Signal","value","readSignal","resolved","next","untrack","writeSignal"],"sources":["../../src/signal.ts"],"sourcesContent":["import {\n type Accessor,\n type Equals,\n readSignal,\n type Setter,\n SignalNode,\n writeSignal,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useSignal}.\n * @since 1.0.0\n */\nexport interface SignalOptions<T> {\n /**\n * Decides whether a write is a change: readers are notified only when it returns `false`.\n * `false` notifies on every write, even of the same value. It runs untracked: a signal it reads\n * is not a dependency of the computation that writes.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the signal is unnamed)\n */\n name?: string | undefined;\n}\n\n/**\n * Creates a reactive cell holding one value: the low-level primitive `useStore` builds on. Reads\n * inside effects and memos subscribe them; writes notify them. Works at module scope.\n *\n * @param value Initial value.\n * @param options Equality override and a devtools name. Undefined uses the defaults.\n * @returns A `[read, write]` pair. The writer also accepts an updater `(prev) => next`, which runs\n * untracked, and returns the value it stored.\n * @throws ShadowError `WRITE_IN_MEMO` from the writer, in development builds only, when it is\n * called while a {@link useMemo} computation runs (unless that memo sets `allowWrites`).\n * @example\n * import { useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * setCount((n) => n + 1);\n * console.log(count()); // 1\n * @see useStore\n * @see useMemo\n * @since 1.0.0\n */\nexport function useSignal<T>(value: T, options?: SignalOptions<T>): [Accessor<T>, Setter<T>] {\n const equals: Equals<T> = options?.equals === undefined ? Object.is : options.equals;\n const signal = new SignalNode<T>(value, equals, options?.name);\n const read: Accessor<T> = () => readSignal(signal);\n const write = ((next: unknown) => {\n const resolved = (\n typeof next === \"function\" ? untrack(() => (next as (prev: T) => T)(signal.value)) : next\n ) as T;\n writeSignal(signal, resolved);\n return resolved;\n }) as Setter<T>;\n return [read, write];\n}\n"],"mappings":"A,sJAiDA,SAAgBC,EAAa,EAAU,EAAsD,CAC3F,IAAMC,EAAoBC,GAAS,SAAW,IAAA,GAAY,OAAO,GAAKA,EAAQ,OACxEC,EAAS,IAAIJ,EAAcM,EAAOJ,EAAQC,GAAS,IAAI,EAS7D,MAAO,KARyBI,EAAWH,CAAM,GACjC,GAAkB,CAChC,IAAMI,EACJ,OAAOC,GAAS,WAAaC,MAAeD,EAAwBL,EAAO,KAAK,CAAC,EAAIK,EAGvF,OADAE,EAAYP,EAAQI,CAAQ,EACrBA,CACT,EACmB,CACrB,C"}
@@ -1,2 +1,2 @@
1
- import{track as e}from"../internal/graph.js";import{createSignalNode as t,isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(e,n){let r=e.signals;r===null&&(r=/* @__PURE__ */ new Map,e.signals=r);let i=r.get(n);return i===void 0&&(i=t(0,!1),r.set(n,i)),i}function h(t,r){n()&&e(m(t,r))}function g(r){n()&&(r.keys===null&&(r.keys=t(0,!1)),e(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let n=a.get(e);return n===void 0||(_(n.signals?.get(t)),_(n.keys)),!0}export{a as NODES,o as RAW,x as deleteRaw,s as isReservedKey,c as isWrappable,p as nodeOf,f as readRaw,g as trackKeys,h as trackProperty,d as unwrapDeep,l as unwrapValue,b as writeRaw};
1
+ import{Signal as e,track as t}from"../internal/graph.js";import{isTracking as n,notify as r}from"../extend/index.js";const i=/* @__PURE__ */ new Set([`__proto__`,`constructor`,`prototype`]),a=/* @__PURE__ */ new WeakMap,o=/* @__PURE__ */ new WeakMap;function s(e){return i.has(e)}function c(e){if(typeof e!=`object`||!e)return!1;if(Array.isArray(e))return!0;if(e===Object.prototype)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function l(e){return typeof e!=`object`||!e?e:o.get(e)??e}function u(e){let t=/* @__PURE__ */ new Set([e]),n=[e];for(;n.length>0;){let e=n.pop();for(let r of Object.keys(e)){let i=Reflect.get(e,r);if(typeof i==`object`&&i){if(o.has(i))return!0;c(i)&&!t.has(i)&&(t.add(i),n.push(i))}}}return!1}function d(e){let t=l(e);if(t!==e||!c(t)||!u(t))return t;let n=/* @__PURE__ */ new Map,r=e=>{let t=n.get(e);if(t!==void 0)return t;let r=Array.isArray(e)?[]:Object.create(Object.getPrototypeOf(e));return n.set(e,r),r},i=r(t),a=[t];for(let e=0;e<a.length;e+=1){let t=a[e],i=n.get(t);for(let e of Object.keys(t)){let s=Reflect.get(t,e);if(typeof s==`object`&&s){let i=o.get(s);if(i!==void 0)s=i;else if(c(s)){let i=n.has(s);s=r(s),i||a.push(Reflect.get(t,e))}}Object.defineProperty(i,e,{value:s,enumerable:!0,writable:!0,configurable:!0})}}return i}function f(e,t){return Reflect.get(e,t)}function p(e){let t=a.get(e);return t===void 0&&(t={signals:null,keys:null,proxy:null},a.set(e,t)),t}function m(t,n){let r=t.signals;r===null&&(r=/* @__PURE__ */ new Map,t.signals=r);let i=r.get(n);if(i===void 0){let t=r.size;if(t>=256&&!(t&t-1))for(let[e,t]of r)(t.observers?.length??0)===0&&r.delete(e);i=new e(0,!1),r.set(n,i)}return i}function h(e,r){n()&&t(m(e,r))}function g(r){n()&&(r.keys===null&&(r.keys=new e(0,!1)),t(r.keys))}function _(e){e!=null&&r(e)}function v(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===e}function y(e,t){let n=e.signals;if(n!==null)for(let[e,r]of n)v(e)&&Number(e)>=t&&_(r)}function b(e,t,n){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_KEY`);n=d(n);let r=Array.isArray(e),i=Object.hasOwn(e,t);if(i&&Object.is(f(e,t),n))return!1;let o=r?e.length:0;if(!Reflect.set(e,t,n))throw TypeError(`SHADOW_STORE_PROP_READ_ONLY`);let c=a.get(e);if(c===void 0)return!0;if(_(c.signals?.get(t)),i||_(c.keys),r){let t=e.length;t!==o&&(_(c.signals?.get(`length`)),_(c.keys),t<o&&y(c,t))}return!0}function x(e,t){if(s(t))throw TypeError(`SHADOW_STORE_RESERVED_DELETE`);if(!Object.hasOwn(e,t))return!0;if(!Reflect.deleteProperty(e,t))throw TypeError(`SHADOW_STORE_DELETE`);let n=a.get(e);return n===void 0||(_(n.signals?.get(t)),_(n.keys)),!0}export{a as NODES,o as RAW,x as deleteRaw,s as isReservedKey,c as isWrappable,p as nodeOf,f as readRaw,g as trackKeys,h as trackProperty,d as unwrapDeep,l as unwrapValue,b as writeRaw};
2
2
  //# sourceMappingURL=nodes.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"nodes.js","names":["notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","createSignalNode","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import {\n createSignalNode,\n isTracking,\n notify as notifySource,\n type SignalNode,\n track,\n} from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /** One signal per property read in a tracked context, keyed by property name. */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n signal = createSignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = createSignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,+HASA,MAAMC,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAgB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAY,EAAiC,CAC3D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MA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AQD,GAAQL,EAAkBZ,EAAMkB,CAAK,EAErD,CACA,MAAO,EACT,CAGA,SAAgBC,EAAU,EAAgB,EAAsB,CAC9D,GAAI9C,EAAcC,CAAG,EACnB,MAAU,UAGJ,8BACN,EAEF,GAAI,CAAC,OAAO,OAAOqB,EAAQrB,CAAG,EAAG,MAAO,GACxC,GAAI,CAAC,QAAQ,eAAeqB,EAAQrB,CAAG,EACrC,MAAU,UACuD,qBACjE,EAEF,IAAM0B,EAAO7B,EAAM,IAAIwB,CAAM,EAI7B,OAHIK,IAAS,IAAA,KACbS,EAAOT,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BmC,EAAOT,EAAK,IAAI,GACT,EACT,C"}
1
+ {"version":3,"file":"nodes.js","names":["SignalNode","notify$1","RESERVED_KEYS","NODES","RAW","isReservedKey","key","isWrappable","value","prototype","unwrapValue","containsProxy","seen","root","stack","container","member","unwrapDeep","first","copies","copyOf","existing","source","made","rootCopy","queue","head","target","raw","known","readRaw","nodeOf","node","signalFor","signals","signal","size","other","Signal","trackProperty","isTracking","track","trackKeys","notify","isIndexKey","index","notifyIndicesFrom","from","writeRaw","array","had","before","after","deleteRaw"],"sources":["../../../src/store/nodes.ts"],"sourcesContent":["import { isTracking, notify as notifySource, SignalNode, track } from \"../extend\";\n\n/** Keys that could reach `Object.prototype` if written; they are never stored as own properties. */\nconst RESERVED_KEYS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\n/**\n * Tracking state of one plain object or array. Signals are created lazily, on the first read made\n * inside a tracked computation, so untracked data costs one small record per object.\n */\nexport interface NodeState {\n /**\n * One signal per property read in a tracked context, keyed by property name. A signal is only a\n * notifier (it holds no value), so one that nothing observes any more is dropped by a sweep (see\n * `signalFor`) and a later read simply makes a new one.\n */\n signals: Map<string, SignalNode<number>> | null;\n /** Notified when a property is added or removed, or an array changes length. */\n keys: SignalNode<number> | null;\n /** The read-only proxy for this object, created on first read. */\n proxy: object | null;\n}\n\n/** Raw object -> its tracking state. Keys are the raw data, so nothing is stamped on user objects. */\nexport const NODES: WeakMap<object, NodeState> = new WeakMap();\n\n/** Any store proxy (read-only or draft) -> the raw object it wraps. */\nexport const RAW: WeakMap<object, object> = new WeakMap();\n\n/** True for the keys that must never be written as own properties. */\nexport function isReservedKey(key: string): boolean {\n return RESERVED_KEYS.has(key);\n}\n\n/** True for the values the store wraps: plain objects (null or Object.prototype) and arrays. */\nexport function isWrappable(value: unknown): value is object {\n if (typeof value !== \"object\" || value === null) return false;\n if (Array.isArray(value)) return true;\n if (value === Object.prototype) return false;\n const prototype: unknown = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\n/** Replaces a store proxy by the raw object it wraps; any other value is returned as is. */\nexport function unwrapValue(value: unknown): unknown {\n if (typeof value !== \"object\" || value === null) return value;\n return RAW.get(value) ?? value;\n}\n\n/** True when a store proxy (draft or read-only view) sits anywhere inside the plain data `root`. */\nfunction containsProxy(root: object): boolean {\n const seen = new Set<object>([root]);\n const stack: object[] = [root];\n while (stack.length > 0) {\n const container = stack.pop() as object;\n for (const key of Object.keys(container)) {\n const member: unknown = Reflect.get(container, key);\n if (typeof member !== \"object\" || member === null) continue;\n if (RAW.has(member)) return true;\n if (isWrappable(member) && !seen.has(member)) {\n seen.add(member);\n stack.push(member);\n }\n }\n }\n return false;\n}\n\n/**\n * Like {@link unwrapValue}, and also for proxies hidden inside plain data: `draft.todos =\n * draft.todos.filter(...)` assigns an array whose members are drafts, and a draft stored in the\n * data would throw on its next use. Data without proxies is returned as is; otherwise a copy with\n * every proxy replaced by its raw object. Iterative, so nesting depth is not limited by the stack.\n */\nexport function unwrapDeep(value: unknown): unknown {\n const first = unwrapValue(value);\n if (first !== value || !isWrappable(first) || !containsProxy(first)) return first;\n const copies = new Map<object, object>();\n const copyOf = (source: object): object => {\n const existing = copies.get(source);\n if (existing !== undefined) return existing;\n const made: object = Array.isArray(source) ? [] : Object.create(Object.getPrototypeOf(source));\n copies.set(source, made);\n return made;\n };\n const rootCopy = copyOf(first);\n const queue: object[] = [first];\n for (let head = 0; head < queue.length; head += 1) {\n const source = queue[head] as object;\n const target = copies.get(source) as object;\n for (const key of Object.keys(source)) {\n let member: unknown = Reflect.get(source, key);\n if (typeof member === \"object\" && member !== null) {\n const raw = RAW.get(member);\n if (raw !== undefined) member = raw;\n else if (isWrappable(member)) {\n const known = copies.has(member);\n member = copyOf(member);\n if (!known) queue.push(Reflect.get(source, key) as object);\n }\n }\n Object.defineProperty(target, key, {\n value: member,\n enumerable: true,\n writable: true,\n configurable: true,\n });\n }\n }\n return rootCopy;\n}\n\n/** Reads an own or inherited property without tracking and without invoking proxies. */\nexport function readRaw(target: object, key: string): unknown {\n return Reflect.get(target, key);\n}\n\n/** Returns the tracking state of `raw`, creating an empty one on first use. */\nexport function nodeOf(raw: object): NodeState {\n let node = NODES.get(raw);\n if (node === undefined) {\n node = { signals: null, keys: null, proxy: null };\n NODES.set(raw, node);\n }\n return node;\n}\n\n/** The map size at which the first sweep of unobserved key signals runs. */\nconst SWEEP_AT = 256;\n\nfunction signalFor(node: NodeState, key: string): SignalNode<number> {\n let signals = node.signals;\n if (signals === null) {\n signals = new Map();\n node.signals = signals;\n }\n let signal = signals.get(key);\n if (signal === undefined) {\n // Reading many transient keys (`store.byId[id]` with churning ids) would keep one signal per key\n // for the life of the store. The sweep runs when the map reaches a power of two from SWEEP_AT on,\n // so its cost is amortized O(1) per new key, and the map stays within about twice the number of\n // keys that are observed at that moment (plus SWEEP_AT).\n const size = signals.size;\n if (size >= SWEEP_AT && (size & (size - 1)) === 0) {\n // Safe at any time: a signal carries no value, and the next read of its key makes a fresh one.\n for (const [other, node] of signals) {\n if ((node.observers?.length ?? 0) === 0) signals.delete(other);\n }\n }\n signal = new SignalNode(0, false);\n signals.set(key, signal);\n }\n return signal;\n}\n\n/** Subscribes the running computation (if any) to one property of the object. */\nexport function trackProperty(node: NodeState, key: string): void {\n if (!isTracking()) return;\n track(signalFor(node, key));\n}\n\n/** Subscribes the running computation (if any) to the key set of the object. */\nexport function trackKeys(node: NodeState): void {\n if (!isTracking()) return;\n if (node.keys === null) node.keys = new SignalNode(0, false);\n track(node.keys);\n}\n\n/**\n * Notifies the observers of one signal. The same engine steps as a signal write: mark the\n * observers dirty, then request a flush (which the surrounding batch defers).\n */\nfunction notify(signal: SignalNode<number> | null | undefined): void {\n if (signal === undefined || signal === null) return;\n notifySource(signal);\n}\n\nfunction isIndexKey(key: string): boolean {\n const index = Number(key);\n return Number.isInteger(index) && index >= 0 && String(index) === key;\n}\n\n/** Notifies the index signals of an array at or beyond `from` (used when the array shrinks). */\nfunction notifyIndicesFrom(node: NodeState, from: number): void {\n const signals = node.signals;\n if (signals === null) return;\n for (const [key, signal] of signals) {\n if (isIndexKey(key) && Number(key) >= from) notify(signal);\n }\n}\n\n/**\n * Writes one property of a raw object and notifies exactly what changed: the property's signal,\n * the key set when a property appears, and the length when an array's length moves. An equal\n * value (Object.is) writes nothing. Returns whether anything changed.\n */\nexport function writeRaw(target: object, key: string, value: unknown): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be written; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_KEY\",\n );\n }\n value = unwrapDeep(value);\n const array = Array.isArray(target);\n const had = Object.hasOwn(target, key);\n if (had && Object.is(readRaw(target, key), value)) return false;\n const before = array ? (target as unknown[]).length : 0;\n if (!Reflect.set(target, key, value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: property \"${key}\" is read-only and cannot be written`\n : \"SHADOW_STORE_PROP_READ_ONLY\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n if (!had) notify(node.keys);\n if (array) {\n const after = (target as unknown[]).length;\n if (after !== before) {\n notify(node.signals?.get(\"length\"));\n notify(node.keys);\n if (after < before) notifyIndicesFrom(node, after);\n }\n }\n return true;\n}\n\n/** Deletes one own property of a raw object and notifies its signal and the key set. */\nexport function deleteRaw(target: object, key: string): boolean {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore: \"${key}\" cannot be deleted; it is a reserved key`\n : \"SHADOW_STORE_RESERVED_DELETE\",\n );\n }\n if (!Object.hasOwn(target, key)) return true;\n if (!Reflect.deleteProperty(target, key)) {\n throw new TypeError(\n __DEV__ ? `ShadowStore: property \"${key}\" cannot be deleted` : \"SHADOW_STORE_DELETE\",\n );\n }\n const node = NODES.get(target);\n if (node === undefined) return true;\n notify(node.signals?.get(key));\n notify(node.keys);\n return true;\n}\n"],"mappings":"A,qHAGA,MAAME,kBAAqC,IAAI,IAAI,CAAC,YAAa,cAAe,WAAW,CAAC,EAoB/EC,kBAAoC,IAAI,QAGxCC,kBAA+B,IAAI,QAGhD,SAAgBC,EAAc,EAAsB,CAClD,OAAOH,EAAc,IAAII,CAAG,CAC9B,CAGA,SAAgBC,EAAY,EAAiC,CAC3D,GAAI,OAAOC,GAAU,WAAYA,EAAgB,MAAO,GACxD,GAAI,MAAM,QAAQA,CAAK,EAAG,MAAO,GACjC,GAAIA,IAAU,OAAO,UAAW,MAAO,GACvC,IAAMC,EAAqB,OAAO,eAAeD,CAAK,EACtD,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAGA,SAAgBC,EAAY,EAAyB,CAEnD,OADI,OAAOF,GAAU,WAAYA,EAAuBA,EACjDJ,EAAI,IAAII,CAAK,GAAKA,CAC3B,CAGA,SAASG,EAAc,EAAuB,CAC5C,IAAMC,kBAAO,IAAI,IAAY,CAACC,CAAI,CAAC,EAC7BC,EAAkB,CAACD,CAAI,EAC7B,KAAOC,EAAM,OAAS,GAAG,CACvB,IAAMC,EAAYD,EAAM,IAAI,EAC5B,IAAK,IAAMR,KAAO,OAAO,KAAKS,CAAS,EAAG,CACxC,IAAMC,EAAkB,QAAQ,IAAID,EAAWT,CAAG,EAClD,GAAI,OAAOU,GAAW,UAAYA,EAClC,IAAIZ,EAAI,IAAIY,CAAM,E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AI7B,OAHIK,IAAS,IAAA,KACbW,EAAOX,EAAK,SAAS,IAAI1B,CAAG,CAAC,EAC7BqC,EAAOX,EAAK,IAAI,GACT,EACT,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":"A,qWA4BA,SAASC,EAAc,EAAkD,CACvE,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAY,OAAO,eAAeD,CAAK,EAC7C,OAAOC,IAAc,OAAO,WAAaA,IAAc,IACzD,CAEA,SAASC,EAAU,EAAoD,EAA0B,CAC/F,IAAMC,EAAOC,EAAM,MAAQ,EACrBC,EAAKD,EAAM,IAAME,EAAS,EAC1BC,EAAKH,EAAM,IAAM,EACvB,GAAI,CAAC,OAAO,SAASG,CAAE,GAAKA,IAAO,EACjC,MAAU,UACiD,oBAC3D,EACF,IAAMC,EAAiB,CAAC,EACxB,IAAK,IAAIC,EAAIN,GAAMI,EAAK,EAAIE,GAAKJ,EAAKI,GAAKJ,KACzCG,EAAK,KAAKC,CAAC,EACP,IAAK,OAASH,EAAS,IAFkB,GAAKC,GAIpD,OAAOC,CACT,CAGA,SAASE,EAAS,EAAgB,EAAe,EAAuC,CACtF,IAAMF,EAA+B,CAAC,EACtC,GAAI,MAAM,QAAQG,CAAM,EAAG,CACzB,GAAI,OAAOC,GAAS,SAAUJ,EAAK,KAAKI,CAAI,OACvC,GAAI,OAAOA,GAAS,WAAY,CACnC,IAAMC,EAASD,EACf,IAAK,IAAIH,EAAI,EAAGA,EAAIE,EAAO,OAAQ,GAAK,EAAOE,EAAOF,EAAOF,GAAIA,CAAC,GAAGD,EAAK,KAAKC,CAAC,CAClF,MAAO,GAAI,MAAM,QAAQG,CAAI,EAAGJ,EAAK,KAAK,GA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C,EAAOqB,EAAU9C,CAAK,CAAC,EAChCwB,IAAS,IAAA,IAAWG,EAAeK,EAAMR,EAAMH,CAAK,EACxD,MACF,CACA,GAAI,CAACtB,EAAcC,CAAK,EACtB,MAAU,UAGJ,8BACN,EAEF,IAAMyC,EAAK,IAAIC,EAAYrB,CAAK,EAChC,GAAI,CACFS,EAAUa,EAAQX,EAAMS,CAAE,EAA8BzC,EAAOqB,CAAK,CACtE,QAAU,CACR,EAAG,KAAO,EACZ,CACF,CA+CA,SAAgB0B,EAAS,EAAkB,EAAiC,CAC1E,IAAM1B,EAAQ2B,GAAS,OAAS,IAAA,GAAY,GAAK,KAAKA,EAAQ,KAAK,GAC7DhB,EAAOJ,EAAYO,CAAO,EAChC,GAAIT,EAAYM,CAAI,EAAG,OAAOE,EAAgBF,EAAMX,CAAK,EAGzD,GAAM,CAAC4B,EAAMC,GAASC,EACpBC,EAASjB,CAAO,EAChBa,GAAS,OAAS,IAAA,GAAY,IAAA,GAAY,CAAE,KAAMA,EAAQ,IAAK,CACjE,EAOA,MAAO,CAACC,EANK,GACXC,EACE,OAAOrB,GAAS,WACX,GAAsBuB,EAAUvB,EAAwCN,CAAQ,CAAC,EAClF6B,EAASvB,CAAI,CACnB,CACe,CACnB,CAGA,SAASuB,EAAS,EAAyB,CACzC,IAAMC,EAAMzB,EAAY5B,CAAK,EAC7B,OAAO0B,EAAY2B,CAAG,EAAIjB,EAAYiB,CAAG,EAAIrD,CAC/C,C"}
1
+ {"version":3,"file":"use-store.js","names":["setStore","isPlainObject","value","prototype","rangeKeys","from","range","to","length","by","keys","i","stepKeys","target","step","filter","key","isReservedKey","applyPath","path","steps","walk","depth","label","holder","previous","spec","specOf","isWrappable","applyReconcile","unwrapValue","next","mergeInto","child","root","source","createDeepStore","initial","readProxyOf","args","first","group","untrack","tx","Transaction","draftOf","result","replaceWith","reconcile","useStore","options","read","write","useSignal","wrapCell","raw"],"sources":["../../../src/store/use-store.ts"],"sourcesContent":["import {\n currentOwner,\n DEVTOOLS_EVENT,\n devtoolsReport,\n group,\n isComputingMemo,\n ShadowError,\n} from \"../extend\";\nimport { untrack } from \"../ownership\";\nimport { useSignal } from \"../signal\";\nimport { isReservedKey, isWrappable, unwrapValue } from \"./nodes\";\nimport { draftOf, readProxyOf, Transaction } from \"./proxies\";\nimport { snapshot } from \"./read\";\nimport { applyReconcile, reconcile, specOf } from \"./reconcile\";\nimport type { MixedInitial, NotMixed, SetStore, Store, StoreResult } from \"./types\";\n\n/**\n * Options of {@link useStore}.\n * @since 1.0.0\n */\nexport interface StoreOptions {\n /**\n * Label shown in error messages and by devtools.\n * @default undefined (the store is unnamed)\n */\n name?: string;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction rangeKeys(range: { from?: number; to?: number; by?: number }, length: number): number[] {\n const from = range.from ?? 0;\n const to = range.to ?? length - 1;\n const by = range.by ?? 1;\n if (!Number.isFinite(by) || by === 0)\n throw new TypeError(\n __DEV__ ? \"ShadowStore: a range needs a non-zero `by`\" : \"SHADOW_STORE_RANGE\",\n );\n const keys: number[] = [];\n for (let i = from; by > 0 ? i <= to : i >= to; i += by) {\n keys.push(i);\n if (keys.length > length + 1) break;\n }\n return keys;\n}\n\n/** The keys one path step addresses on `target` (a draft). */\nfunction stepKeys(target: object, step: unknown, label: string): Array<string | number> {\n const keys: Array<string | number> = [];\n if (Array.isArray(target)) {\n if (typeof step === \"number\") keys.push(step);\n else if (typeof step === \"function\") {\n const filter = step as (item: unknown, index: number) => boolean;\n for (let i = 0; i < target.length; i += 1) if (filter(target[i], i)) keys.push(i);\n } else if (Array.isArray(step)) keys.push(...(step as number[]));\n else if (typeof step === \"object\" && step !== null)\n keys.push(...rangeKeys(step, target.length));\n else\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an array` : \"SHADOW_STORE_PATH_ARRAY\",\n );\n } else if (typeof step === \"string\" || typeof step === \"number\") {\n keys.push(step);\n } else if (Array.isArray(step)) {\n keys.push(...(step as Array<string | number>));\n } else {\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: bad path step for an object` : \"SHADOW_STORE_PATH_OBJECT\",\n );\n }\n for (const key of keys) {\n if (typeof key === \"string\" && isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be used in a path`\n : \"SHADOW_STORE_PATH_KEY\",\n );\n }\n }\n return keys;\n}\n\n/** Writes `value` (or the updater's result) at the end of a path, merging plain objects. */\nfunction applyPath(root: object, path: unknown[], label: string): void {\n const value = path[path.length - 1];\n const steps = path.slice(0, -1);\n const walk = (target: object, depth: number): void => {\n for (const key of stepKeys(target, steps[depth], label)) {\n const holder = target as Record<string | number, unknown>;\n if (depth === steps.length - 1) {\n const previous = holder[key];\n const spec = typeof value === \"function\" ? specOf(value) : undefined;\n if (spec !== undefined) {\n // reconcile(...) at a path diffs only that sub-tree.\n if (isWrappable(previous)) applyReconcile(unwrapValue(previous) as object, spec, label);\n else holder[key] = spec.next;\n continue;\n }\n const next =\n typeof value === \"function\" ? (value as (p: unknown) => unknown)(previous) : value;\n if (isPlainObject(next) && isWrappable(previous) && !Array.isArray(previous)) {\n mergeInto(previous as Record<string, unknown>, next, label);\n } else {\n holder[key] = next;\n }\n } else {\n const child = holder[key];\n if (!isWrappable(child)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the path goes through a value that is not an object`\n : \"SHADOW_STORE_PATH_VALUE\",\n );\n }\n walk(child, depth + 1);\n }\n }\n };\n walk(root, 0);\n}\n\nfunction mergeInto(\n target: Record<string, unknown>,\n source: Record<string, unknown>,\n label: string,\n): void {\n for (const key of Object.keys(source)) {\n if (isReservedKey(key)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: the key \"${key}\" cannot be assigned`\n : \"SHADOW_STORE_ASSIGN_KEY\",\n );\n }\n target[key] = source[key];\n }\n}\n\n/**\n * Devtools handles of the stores, by store root. Dev builds only: the WeakMap is unused (and dropped)\n * in production, where `__DEV__` is false.\n */\nconst storeHandles = /* @__PURE__ */ new WeakMap<object, Array<{ readonly name: string }>>();\n\nfunction createDeepStore<T extends object>(initial: T, label: string): [Store<T>, SetStore<T>] {\n const root = unwrapValue(initial) as object;\n const store = readProxyOf(root) as Store<T>;\n\n // One untyped entry point for every form of update. It is assignable to SetStore<T> because its\n // parameters accept anything: the typed overloads are the public contract, and the devtools\n // path setter below calls this function directly with a path it built at run time.\n const apply = (...args: unknown[]): void => {\n if (__DEV__ && isComputingMemo()) throw new ShadowError(\"WRITE_IN_MEMO\");\n if (args.length === 0)\n throw new TypeError(\n __DEV__ ? `ShadowStore${label}: setStore() needs an argument` : \"SHADOW_STORE_NO_ARGUMENT\",\n );\n const first = args[0];\n group(() =>\n untrack(() => {\n if (args.length > 1) {\n const tx = new Transaction(label);\n try {\n applyPath(draftOf(root, tx), args, label);\n } finally {\n tx.open = false;\n }\n return;\n }\n if (typeof first === \"function\") {\n const spec = specOf(first);\n if (spec !== undefined) {\n applyReconcile(root, spec, label);\n return;\n }\n const tx = new Transaction(label);\n let result: unknown;\n try {\n result = (first as (draft: unknown) => unknown)(draftOf(root, tx));\n } finally {\n tx.open = false;\n }\n if (result !== undefined) replaceWith(root, result, label);\n return;\n }\n replaceWith(root, first, label);\n }),\n );\n };\n const setStore: SetStore<T> = apply;\n if (__DEV__) {\n const handle = {\n name: label === \"\" ? \"store\" : label.replace(/^ \\((.*)\\)$/, \"$1\"),\n snapshot: () => snapshot(store),\n set: (path: readonly (string | number)[], value: unknown) => {\n apply(...path, value);\n },\n };\n // Devtools hold the handle weakly, so the handle must stay reachable exactly as long as the store.\n // The store's proxy and its setter both reach `root`, and a WeakMap value lives as long as its key.\n // A root shared by two stores keeps both handles.\n const anchored = storeHandles.get(root);\n if (anchored === undefined) storeHandles.set(root, [handle]);\n else anchored.push(handle);\n devtoolsReport(DEVTOOLS_EVENT.STORE_CREATED, handle, currentOwner());\n }\n return [store, setStore];\n}\n\n/** `setStore(value)`: an array replaces (diffed in place), a plain object merges its keys. */\nfunction replaceWith(root: object, value: unknown, label: string): void {\n if (Array.isArray(root)) {\n if (!Array.isArray(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: an array store is updated with an array or a function`\n : \"SHADOW_STORE_ARRAY_UPDATE\",\n );\n }\n const spec = specOf(reconcile(value));\n if (spec !== undefined) applyReconcile(root, spec, label);\n return;\n }\n if (!isPlainObject(value)) {\n throw new TypeError(\n __DEV__\n ? `ShadowStore${label}: setStore() expects an object, a function or a reconcile() result`\n : \"SHADOW_STORE_UPDATE_ARGUMENT\",\n );\n }\n const tx = new Transaction(label);\n try {\n mergeInto(draftOf(root, tx) as Record<string, unknown>, value, label);\n } finally {\n tx.open = false;\n }\n}\n\n/**\n * The state hook. Pass a single value for a reactive cell, or plain data for a deep store:\n *\n * ```ts\n * const [count, setCount] = useStore(0); // count() / setCount(n => n + 1)\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * todos.items[0]?.done; // tracks exactly this property\n * setTodos((draft) => { draft.items.push(todo); }); // notifies only what changed\n * setTodos(\"items\", (t) => t.id === 3, \"done\", true); // path form\n * ```\n *\n * Reads inside effects, memos and JSX subscribe to the exact value or property read; writes notify\n * exactly the readers of what changed, in one batch. A store wraps plain objects and arrays in\n * place; class instances, `Date`, `Map`, `Set` and functions are single values. A value that may\n * be `null` or another type (`Todo[] | null`) is a single value too: it is replaced as a whole, and\n * plain data assigned to it is read through the same fine-grained proxies a store uses.\n *\n * A property read in a tracked context gets a small notifier. Reading many transient keys\n * (`store.byId[id]` with churning ids) does not grow it for the life of the store: once an object\n * has collected a few hundred notifiers, the ones nothing observes any more are dropped, and a key\n * read again gets a fresh one that reflects the current value.\n *\n * @param initial Initial value or plain data. Plain objects and arrays are wrapped in place, not\n * copied.\n * @param options `name` labels the store in messages. Undefined uses the default (unnamed).\n * @returns `[read, write]` for a single value, `[store, setStore]` for plain data.\n * @throws ShadowError `WRITE_IN_MEMO` from the setter, in development builds only, when it is called\n * while a {@link useMemo} computation runs. `setStore` throws TypeError (production messages\n * `SHADOW_STORE_*`) for an update it cannot apply: no argument, a bad path step, a path through a\n * value that is not an object, a reserved key such as `__proto__`, or a non-array value for an\n * array store. Writing to the store view itself throws TypeError (`SHADOW_STORE_READ_ONLY`).\n * @example\n * import { useStore } from \"@shadow-js/core\";\n *\n * interface Todo { id: number; title: string; done: boolean }\n *\n * const [count, setCount] = useStore(0);\n * const [todos, setTodos] = useStore({ items: [] as Todo[] });\n * setCount((n) => n + 1);\n * setTodos((draft) => {\n * draft.items.push({ id: 1, title: \"Write docs\", done: false });\n * });\n * setTodos(\"items\", (todo) => todo.id === 1, \"done\", true);\n * console.log(count(), todos.items[0]?.done); // 1 true\n * @see useSignal\n * @see reconcile\n * @since 1.0.0\n */\nexport function useStore<T extends NotMixed<T>>(initial: T, options?: StoreOptions): StoreResult<T>;\nexport function useStore<T>(initial: MixedInitial<T>, options?: StoreOptions): StoreResult<T>;\nexport function useStore(initial: unknown, options?: StoreOptions): unknown {\n const label = options?.name === undefined ? \"\" : ` (${options.name})`;\n const root = unwrapValue(initial);\n if (isWrappable(root)) return createDeepStore(root, label);\n // A single value, which may be plain data later (`Todo[] | null`): objects and arrays that are\n // assigned are wrapped in read proxies, so `todos()?.[0]?.done` tracks exactly what it reads.\n const [read, write] = useSignal<unknown>(\n wrapCell(initial),\n options?.name === undefined ? undefined : { name: options.name },\n );\n const set = (next: unknown): unknown =>\n write(\n typeof next === \"function\"\n ? (previous: unknown) => wrapCell((next as (previous: unknown) => unknown)(previous))\n : wrapCell(next),\n );\n return [read, set];\n}\n\n/** The value a single-value cell holds: plain data becomes its (stable) read proxy. */\nfunction wrapCell(value: unknown): unknown {\n const raw = unwrapValue(value);\n return isWrappable(raw) ? readProxyOf(raw) : value;\n}\n"],"mappings":"A,qWA4BA,SAASC,EAAc,EAAk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AoDA,SAAgB0B,EAAS,EAAkB,EAAiC,CAC1E,IAAM1B,EAAQ2B,GAAS,OAAS,IAAA,GAAY,GAAK,KAAKA,EAAQ,KAAK,GAC7DhB,EAAOJ,EAAYO,CAAO,EAChC,GAAIT,EAAYM,CAAI,EAAG,OAAOE,EAAgBF,EAAMX,CAAK,EAGzD,GAAM,CAAC4B,EAAMC,GAASC,EACpBC,EAASjB,CAAO,EAChBa,GAAS,OAAS,IAAA,GAAY,IAAA,GAAY,CAAE,KAAMA,EAAQ,IAAK,CACjE,EAOA,MAAO,CAACC,EANK,GACXC,EACE,OAAOrB,GAAS,WACX,GAAsBuB,EAAUvB,EAAwCN,CAAQ,CAAC,EAClF6B,EAASvB,CAAI,CACnB,CACe,CACnB,CAGA,SAASuB,EAAS,EAAyB,CACzC,IAAMC,EAAMzB,EAAY5B,CAAK,EAC7B,OAAO0B,EAAY2B,CAAG,EAAIjB,EAAYiB,CAAG,EAAIrD,CAC/C,C"}
@@ -1,2 +1,2 @@
1
- import{untrack as e}from"./ownership.js";import{useSignal as t}from"./signal.js";import{registerTransitionLane as n,startTransition as r}from"./internal/concurrency.js";import{createComputation as i}from"./extend/index.js";function a(){let[n,i]=t(!1),a=0;return[n,t=>{a+=1,e(()=>i(!0));let n;try{n=r(t)}catch(t){throw--a,a===0&&e(()=>i(!1)),t}return n.then(()=>{--a,a===0&&e(()=>i(!1))})}]}function o(r,a){n();let[o,s]=t(e(r),{equals:a?.equals??Object.is,...a?.name===void 0?{}:{name:a.name}});return i({kind:`effect`,fn:()=>r(),apply:e=>{s(()=>e)},lane:!0,name:a?.name??`useDeferredValue`}),o}export{o as useDeferredValue,a as useTransition};
1
+ import{untrack as e}from"./ownership.js";import{useSignal as t}from"./signal.js";import{registerTransitionLane as n,startTransition as r}from"./internal/concurrency.js";import{createComputation as i}from"./extend/index.js";function a(){let[n,i]=t(!1),a=0;return[n,t=>{a+=1,e(()=>i(!0));let n;try{n=r(t)}catch(t){throw--a,a===0&&e(()=>i(!1)),t}return n.then(()=>{--a,a===0&&e(()=>i(!1))})}]}function o(r,a){n();let[o,s]=t(e(r),{equals:a?.equals??Object.is,name:a?.name});return i({kind:`effect`,fn:()=>r(),apply:e=>{s(()=>e)},lane:!0,name:a?.name??`useDeferredValue`}),o}export{o as useDeferredValue,a as useTransition};
2
2
  //# sourceMappingURL=transitions.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","registerTransitionLane","value","setValue","source","options","createComputation","next"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n ...(options?.name === undefined ? {} : { name: options.name }),\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,+NAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CAEbC,EAAuB,EACvB,GAAM,CAACC,EAAOC,GAAYV,EAAaE,EAAQS,CAAM,EAAG,CACtD,OAAQC,GAAS,QAAU,OAAO,GAClC,GAAIA,GAAS,OAAS,IAAA,GAAY,CAAC,EAAI,CAAE,KAAMA,EAAQ,IAAK,CAC9D,CAAC,EAYD,OATAC,EAAkB,CAChB,KAAM,SACN,OAAUF,EAAO,EACjB,MAAQ,GAAY,CAClBD,MAAeI,CAAI,CACrB,EACA,KAAM,GACN,KAAMF,GAAS,MAAQ,kBACzB,CAAC,EACMH,CACT,C"}
1
+ {"version":3,"file":"transitions.js","names":["useTransition","pending","setPending","useSignal","running","untrack","applied","startTransition","fn","error","useDeferredValue","registerTransitionLane","value","setValue","source","options","createComputation","next"],"sources":["../../src/transitions.ts"],"sourcesContent":["import {\n type Accessor,\n createComputation,\n type Equals,\n inTransition,\n registerTransitionLane,\n startTransition,\n} from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Options of {@link useDeferredValue}.\n * @since 1.0.0\n */\nexport interface DeferredValueOptions<T> {\n /**\n * Decides whether the deferred value changed: readers are notified only when it returns `false`.\n * @default Object.is\n */\n equals?: Equals<T>;\n /**\n * Label shown by devtools and diagnostics.\n * @default \"useDeferredValue\" for the watcher; the value itself is unnamed\n */\n name?: string;\n}\n\n/**\n * Runs `fn` as a transition and reports whether it is pending. Returns `[isPending, start]`:\n * `isPending` is true from `start(fn)` until the transition has been applied (including any Suspense\n * boundary it waits on); `start(fn)` is {@link startTransition} that also updates `isPending`.\n *\n * Use it for updates that may be slow to show (navigating to a page that loads data): the previous\n * screen stays until the new one is ready, and the input stays responsive meanwhile.\n *\n * @returns `[isPending, start]`. `isPending` is an accessor; `start` returns a promise that\n * resolves when the transition has been applied. On the server `start` runs `fn` at once.\n * @throws Nothing itself. `start` rethrows synchronously what `fn` throws, after clearing\n * `isPending` when no other transition of this hook is running.\n * @example\n * import { useSignal, useTransition } from \"@shadow-js/core\";\n *\n * function Tabs() {\n * const [page, setPage] = useSignal(\"home\");\n * const [pending, start] = useTransition();\n * return (\n * <button disabled={pending()} onClick={() => start(() => setPage(\"reports\"))}>\n * {page() === \"reports\" ? \"Reports\" : \"Open reports\"}\n * </button>\n * );\n * }\n * @see startTransition\n * @see useDeferredValue\n * @since 1.0.0\n */\nexport function useTransition(): [Accessor<boolean>, (fn: () => void) => Promise<void>] {\n const [pending, setPending] = useSignal(false);\n let running = 0;\n const start = (fn: () => void): Promise<void> => {\n running += 1;\n // Urgent: the pending state must show before the transition's own work.\n untrack(() => setPending(true));\n let applied: Promise<void>;\n try {\n applied = startTransition(fn);\n } catch (error) {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n throw error;\n }\n return applied.then(() => {\n running -= 1;\n if (running === 0) untrack(() => setPending(false));\n });\n };\n return [pending, start];\n}\n\n/**\n * Returns a value that follows `source` in the transition lane: it keeps the previous value while\n * urgent updates run, and takes the new value when the lane applies it. Reads of the source are\n * unaffected. On the server it returns the source itself (there is no lane).\n *\n * @param source The value to follow. Tracked by a watcher that runs in the transition lane.\n * @param options Equality and a devtools name. Undefined uses the defaults.\n * @returns An accessor of the deferred value. It starts as the source's current value.\n * @example\n * import { useDeferredValue, useMemo, useSignal } from \"@shadow-js/core\";\n *\n * const names = [\"Ada\", \"Grace\", \"Linus\"];\n * function Search() {\n * const [query, setQuery] = useSignal(\"\");\n * const deferredQuery = useDeferredValue(query);\n * const results = useMemo(() => names.filter((name) => name.includes(deferredQuery())));\n * return (\n * <label>\n * <input value={query()} onInput={(e) => setQuery(e.currentTarget.value)} />\n * {results().join(\", \")}\n * </label>\n * );\n * }\n * @see useTransition\n * @since 1.0.0\n */\nexport function useDeferredValue<T>(\n source: Accessor<T>,\n options?: DeferredValueOptions<T>,\n): Accessor<T> {\n if (__SERVER__) return source;\n registerTransitionLane();\n const [value, setValue] = useSignal<T>(untrack(source), {\n equals: options?.equals ?? Object.is,\n name: options?.name,\n });\n // The watcher runs in the lane. Its first run (queued at creation) finds the value equal, so it\n // writes nothing; a later run writes the source's value, and an equal value notifies nobody.\n createComputation({\n kind: \"effect\",\n fn: () => source(),\n apply: (next: T) => {\n setValue(() => next);\n },\n lane: true,\n name: options?.name ?? \"useDeferredValue\",\n });\n return value;\n}\n\nexport { inTransition };\n"],"mappings":"A,+NAwDA,SAAgBA,GAAwE,CACtF,GAAM,CAACC,EAASC,GAAcC,EAAU,EAAK,EACzCC,EAAU,EAkBd,MAAO,CAACH,EAjBO,GAAkC,CAC/C,GAAW,EAEXI,MAAcH,EAAW,EAAI,CAAC,EAC9B,IAAII,EACJ,GAAI,CACF,EAAUC,EAAgBC,CAAE,CAC9B,OAASC,EAAO,CAGd,KAFA,IACIL,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,EAC5CO,CACR,CACA,OAAOH,EAAQ,SAAW,CACxB,IACIF,IAAY,GAAGC,MAAcH,EAAW,EAAK,CAAC,CACpD,CAAC,CACH,CACsB,CACxB,CA4BA,SAAgBQ,EACd,EACA,EACa,CAEbC,EAAuB,EACvB,GAAM,CAACC,EAAOC,GAAYV,EAAaE,EAAQS,CAAM,EAAG,CACtD,OAAQC,GAAS,QAAU,OAAO,GAClC,KAAMA,GAAS,IACjB,CAAC,EAYD,OATAC,EAAkB,CAChB,KAAM,SACN,OAAUF,EAAO,EACjB,MAAQ,GAAY,CAClBD,MAAeI,CAAI,CACrB,EACA,KAAM,GACN,KAAMF,GAAS,MAAQ,kBACzB,CAAC,EACMH,CACT,C"}
@@ -1,2 +1,2 @@
1
- import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p){if(f(!1),c===null)throw t;e(t,c)}},h;try{h=n(()=>o(s,...r))}catch(e){return c===null?(i===p&&f(!1),Promise.reject(e)):(m(e),Promise.resolve())}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
1
+ import{handleError as e}from"./internal/owner.js";import{batch as t}from"./internal/scheduler.js";import{untrack as n}from"./ownership.js";import{useSignal as r}from"./signal.js";import{currentOwner as i}from"./extend/index.js";function a(e){return e!==null&&(typeof e==`object`||typeof e==`function`)&&typeof e.then==`function`}function o(o,s){let c=i(),[l,u]=r(s),[d,f]=r(!1),p=0;return[l,(...r)=>{p+=1;let i=p,s=n(l),d=e=>{i===p&&t(()=>{u(()=>e),f(!1)})},m=t=>{if(i===p&&f(!1),c===null)throw t;try{e(t,c)}catch(e){typeof reportError==`function`?reportError(e):queueMicrotask(()=>Promise.reject(e))}},h;try{h=n(()=>o(s,...r))}catch(e){try{m(e)}catch(e){return Promise.reject(e)}return Promise.resolve()}return a(h)?(f(!0),Promise.resolve(h).then(d,m)):(d(h),Promise.resolve())},d]}export{o as useAction};
2
2
  //# sourceMappingURL=action.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","result","action"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n if (id !== latest) return;\n setPending(false);\n if (owner === null) throw error;\n handleError(error, owner);\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n if (owner === null) {\n // `fail` would rethrow synchronously; without an owner the promise carries the error.\n if (id === latest) setPending(false);\n return Promise.reject(error);\n }\n fail(error);\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":"A,oOAIA,SAASA,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiCA,SAAgBC,EACd,EACA,EAC2F,CAC3F,IAAMC,EAAQC,EAAa,EACrB,CAACC,EAAOC,GAAYC,EAAaC,CAAY,EAC7C,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAS,EAsCb,MAAO,CAACN,GApCU,GAAGO,IAA2B,CAC9C,GAAU,EACV,IAAMC,EAAKF,EACLG,EAAWC,EAAQV,CAAK,EACxBW,EAAU,GAAmB,CAC7BH,IAAOF,GACXM,MAAY,CACVX,MAAeL,CAAK,EACpBS,EAAW,EAAK,CAClB,CAAC,CACH,EACMQ,EAAQ,GAAyB,CACrC,GAAIL,IAAOF,EACX,CACA,GADAD,EAAW,EAAK,EACZP,IAAU,KAAM,MAAMgB,EAC1BC,EAAYD,EAAOhB,CAAK,CAFR,CAGlB,EACIkB,EACJ,GAAI,CACF,EAASN,MAAcO,EAAOR,EAAU,GAAGF,CAAI,CAAC,CAClD,OAASO,EAAO,CAOd,OANIhB,IAAU,MAERU,IAAOF,GAAQD,EAAW,EAAK,EAC5B,QAAQ,OAAOS,CAAK,IAE7BD,EAAKC,CAAK,EACH,QAAQ,QAAQ,EACzB,CAMA,OALKnB,EAAiBqB,CAAM,GAI5BX,EAAW,EAAI,EACR,QAAQ,QAAQW,CAAM,CAAC,CAAC,KAAKL,EAAQE,CAAI,IAJ9CF,EAAOK,CAAM,EACN,QAAQ,QAAQ,EAI3B,EACyBZ,CAAO,CAClC,C"}
1
+ {"version":3,"file":"action.js","names":["isPromiseLike","value","useAction","owner","currentOwner","state","setState","useSignal","initialState","pending","setPending","latest","args","id","previous","untrack","commit","batch","fail","error","handleError","uncaught","result","action","thrown"],"sources":["../../src/action.ts"],"sourcesContent":["import { type Accessor, batch, currentOwner, handleError } from \"./extend\";\nimport { untrack } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\nfunction isPromiseLike<T>(value: unknown): value is PromiseLike<T> {\n return (\n value !== null &&\n (typeof value === \"object\" || typeof value === \"function\") &&\n typeof (value as { then?: unknown }).then === \"function\"\n );\n}\n\n/**\n * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,\n * tracks whether it is pending, and commits its result. The ShadowJS form of React's\n * `useActionState` (state, dispatch, pending). `previous` is the last committed state.\n *\n * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a\n * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not\n * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an\n * error boundary can show it. Without an owner the returned promise rejects instead.\n *\n * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.\n * @param initialState The state before the first dispatch.\n * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true\n * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this\n * call has finished, whether it committed or not.\n * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with\n * the action's error. With an owner, the error goes to its error handler, or is reported as an\n * uncaught error (`reportError`) when no handler is registered above it.\n * @example\n * import { useAction } from \"@shadow-js/core\";\n *\n * const [message, send, sending] = useAction(async (_prev: string, text: string) => {\n * await fetch(\"/api/messages\", { method: \"POST\", body: text });\n * return `sent: ${text}`;\n * }, \"\");\n * void send(\"hello\");\n * console.log(sending(), message());\n * @see useOptimistic\n * @see useTransition\n * @since 1.0.0\n */\nexport function useAction<S, A extends unknown[]>(\n action: (previous: S, ...args: A) => S | PromiseLike<S>,\n initialState: S,\n): [state: Accessor<S>, dispatch: (...args: A) => Promise<void>, pending: Accessor<boolean>] {\n const owner = currentOwner();\n const [state, setState] = useSignal<S>(initialState);\n const [pending, setPending] = useSignal(false);\n let latest = 0;\n\n const dispatch = (...args: A): Promise<void> => {\n latest += 1;\n const id = latest;\n const previous = untrack(state);\n const commit = (value: S): void => {\n if (id !== latest) return;\n batch(() => {\n setState(() => value);\n setPending(false);\n });\n };\n const fail = (error: unknown): void => {\n // A stale dispatch changes no state, but its error is still the owner's to hear.\n if (id === latest) setPending(false);\n if (owner === null) throw error;\n try {\n handleError(error, owner);\n } catch (uncaught) {\n // No handler took it: report it, as documented, instead of throwing out of dispatch.\n if (typeof reportError === \"function\") reportError(uncaught);\n else queueMicrotask(() => Promise.reject(uncaught));\n }\n };\n let result: S | PromiseLike<S>;\n try {\n result = untrack(() => action(previous, ...args));\n } catch (error) {\n try {\n fail(error);\n } catch (thrown) {\n // Without an owner the returned promise carries the error.\n return Promise.reject(thrown);\n }\n return Promise.resolve();\n }\n if (!isPromiseLike<S>(result)) {\n commit(result);\n return Promise.resolve();\n }\n setPending(true);\n return Promise.resolve(result).then(commit, fail);\n };\n return [state, dispatch, pending];\n}\n"],"mappings":"A,oOAIA,SAASA,EAAiB,EAAyC,CACjE,OACEC,IAAU,OACT,OAAOA,GAAU,UAAY,OAAOA,GAAU,aAC/C,OAAQA,EAA6B,MAAS,UAElD,CAiCA,SAAgBC,EACd,EACA,EAC2F,CAC3F,IAAMC,EAAQC,EAAa,EACrB,CAACC,EAAOC,GAAYC,EAAaC,CAAY,EAC7C,CAACC,EAASC,GAAcH,EAAU,EAAK,EACzCI,EAAS,EA4Cb,MAAO,CAACN,GA1CU,GAAGO,IAA2B,CAC9C,GAAU,EACV,IAAMC,EAAKF,EACLG,EAAWC,EAAQV,CAAK,EACxBW,EAAU,GAAmB,CAC7BH,IAAOF,GACXM,MAAY,CACVX,MAAeL,CAAK,EACpBS,EAAW,EAAK,CAClB,CAAC,CACH,EACMQ,EAAQ,GAAyB,CAGrC,GADIL,IAAOF,GAAQD,EAAW,EAAK,EAC/BP,IAAU,KAAM,MAAMgB,EAC1B,GAAI,CACFC,EAAYD,EAAOhB,CAAK,CAC1B,OAASkB,EAAU,CAEb,OAAO,aAAgB,WAAY,YAAYA,CAAQ,EACtD,mBAAqB,QAAQ,OAAOA,CAAQ,CAAC,CACpD,CACF,EACIC,EACJ,GAAI,CACF,EAASP,MAAcQ,EAAOT,EAAU,GAAGF,CAAI,CAAC,CAClD,OAASO,EAAO,CACd,GAAI,CACFD,EAAKC,CAAK,CACZ,OAASK,EAAQ,CAEf,OAAO,QAAQ,OAAOA,CAAM,CAC9B,CACA,OAAO,QAAQ,QAAQ,CACzB,CAMA,OALKxB,EAAiBsB,CAAM,GAI5BZ,EAAW,EAAI,EACR,QAAQ,QAAQY,CAAM,CAAC,CAAC,KAAKN,EAAQE,CAAI,IAJ9CF,EAAOM,CAAM,EACN,QAAQ,QAAQ,EAI3B,EACyBb,CAAO,CAClC,C"}
@@ -1,2 +1,2 @@
1
- import{currentOwner as e}from"./extend/index.js";function t(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0}function n(e){let t=e;for(;t!==null&&t.parent!==null;)t=t.parent;return t}function r(r,i){let a=i?.limit??100;if(!Number.isInteger(a)||a<1)throw RangeError(`SHADOW_CACHE_LIMIT`);let o=/* @__PURE__ */ new WeakMap;return(...i)=>{let s=n(e());if(s===null)return r(...i);let c=o.get(s);c===void 0&&(c=[],o.set(s,c));for(let e of c)if(t(e.args,i))return e.value;let l=r(...i);return c.push({args:i,value:l}),c.length>a&&c.shift(),l}}export{r as cache};
1
+ import{untrack as e}from"./ownership.js";import{currentOwner as t}from"./extend/index.js";function n(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(!Object.is(e[n],t[n]))return!1;return!0}function r(e){let t=e;for(;t!==null&&t.parent!==null;)t=t.parent;return t}function i(i,a){let o=a?.limit??100;if(!Number.isInteger(o)||o<1)throw RangeError(`SHADOW_CACHE_LIMIT`);let s=/* @__PURE__ */ new WeakMap;return(...a)=>{let c=r(t());if(c===null)return e(()=>i(...a));let l=s.get(c);l===void 0&&(l=[],s.set(c,l));for(let e of l)if(n(e.args,a))return e.value;let u=e(()=>i(...a));return l.push({args:a,value:u}),l.length>o&&l.shift(),u}}export{i as cache};
2
2
  //# sourceMappingURL=cache.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cache.js","names":["sameArgs","a","b","i","rootOf","root","owner","cache","limit","options","scopes","args","currentOwner","fn","entries","entry","value"],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return fn(...args);\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = fn(...args);\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":"A,iDAgBA,SAASA,EAAS,EAAuB,EAAgC,CACvE,GAAIC,EAAE,SAAWC,EAAE,OAAQ,MAAO,GAClC,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAE,OAAQ,GAAK,EACjC,GAAI,CAAC,OAAO,GAAGA,EAAEE,GAAID,EAAEC,EAAE,EAAG,MAAO,GAErC,MAAO,EACT,CAGA,SAASC,EAAO,EAAmC,CACjD,IAAIC,EAAOC,EACX,KAAOD,IAAS,MAAQA,EAAK,SAAW,MAAM,EAAOA,EAAK,OAC1D,OAAOA,CACT,CAyBA,SAAgBE,EACd,EACA,EACmB,CACnB,IAAMC,EAAQC,GAAS,OAAS,IAChC,GAAI,CAAC,OAAO,UAAUD,CAAK,GAAKA,EAAQ,EACtC,MAAU,WAC8C,oBACxD,EAEF,IAAME,kBAAS,IAAI,QACnB,OAAQ,GAAGC,IAAe,CACxB,IAAMN,EAAOD,EAAOQ,EAAa,CAAC,EAClC,GAAIP,IAAS,KAAM,OAAOQ,EAAG,GAAGF,CAAI,EACpC,IAAIG,EAAUJ,EAAO,IAAIL,CAAI,EACzBS,IAAY,IAAA,KACd,EAAU,CAAC,EACXJ,EAAO,IAAIL,EAAMS,CAAO,GAE1B,IAAK,IAAMC,KAASD,EAClB,GAAId,EAASe,EAAM,KAAMJ,CAAI,EAAG,OAAOI,EAAM,MAE/C,IAAMC,EAAQH,EAAG,GAAGF,CAAI,EAGxB,OAFAG,EAAQ,KAAK,CAAE,OAAM,OAAM,CAAC,EACxBA,EAAQ,OAASN,GAAOM,EAAQ,MAAM,EACnCE,CACT,CACF,C"}
1
+ {"version":3,"file":"cache.js","names":["sameArgs","a","b","i","rootOf","root","owner","cache","limit","options","scopes","args","currentOwner","untrack","fn","entries","entry","value"],"sources":["../../src/cache.ts"],"sourcesContent":["import { currentOwner, type Owner } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/** Options of {@link cache}. @since 1.0.0 */\nexport interface CacheOptions {\n /**\n * Most results kept per scope (one root); the oldest is dropped first. A positive integer.\n * @default 100\n */\n limit?: number;\n}\n\ninterface Entry {\n readonly args: readonly unknown[];\n readonly value: unknown;\n}\n\nfunction sameArgs(a: readonly unknown[], b: readonly unknown[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n\n/** The outermost owner: the root of the render (a request on the server, the app on the client). */\nfunction rootOf(owner: Owner | null): Owner | null {\n let root = owner;\n while (root !== null && root.parent !== null) root = root.parent;\n return root;\n}\n\n/**\n * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same\n * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,\n * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.\n * A call that throws is not kept. `fn` runs untracked, so the first caller does not alone subscribe to what\n * it reads. Outside any owner nothing is scoped, so `fn` runs every time.\n *\n * Use it to share one data fetch between components rendered in the same request.\n *\n * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.\n * @param options Per-scope limit. Undefined uses the default.\n * @returns A function with the same signature.\n * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in\n * production builds). The returned function rethrows what `fn` throws.\n * @example\n * import { cache } from \"@shadow-js/core\";\n *\n * const loadUser = cache((id: string) =>\n * fetch(`/api/users/${id}`).then((response) => response.json()),\n * );\n * // Two components calling loadUser(\"u1\") in the same render fetch once.\n * @see useResource\n * @since 1.0.0\n */\nexport function cache<A extends unknown[], R>(\n fn: (...args: A) => R,\n options?: CacheOptions,\n): (...args: A) => R {\n const limit = options?.limit ?? 100;\n if (!Number.isInteger(limit) || limit < 1) {\n throw new RangeError(\n __DEV__ ? \"cache: limit must be a positive integer\" : \"SHADOW_CACHE_LIMIT\",\n );\n }\n const scopes = new WeakMap<Owner, Entry[]>();\n return (...args: A): R => {\n const root = rootOf(currentOwner());\n if (root === null) return untrack(() => fn(...args));\n let entries = scopes.get(root);\n if (entries === undefined) {\n entries = [];\n scopes.set(root, entries);\n }\n for (const entry of entries) {\n if (sameArgs(entry.args, args)) return entry.value as R;\n }\n const value = untrack(() => fn(...args));\n entries.push({ args, value });\n if (entries.length > limit) entries.shift();\n return value;\n };\n}\n"],"mappings":"A,0FAiBA,SAASA,EAAS,EAAuB,EAAgC,CACvE,GAAIC,EAAE,SAAWC,EAAE,OAAQ,MAAO,GAClC,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAAE,OAAQ,GAAK,EACjC,GAAI,CAAC,OAAO,GAAGA,EAAEE,GAAID,EAAEC,EAAE,EAAG,MAAO,GAErC,MAAO,EACT,CAGA,SAASC,EAAO,EAAmC,CACjD,IAAIC,EAAOC,EACX,KAAOD,IAAS,MAAQA,EAAK,SAAW,MAAM,EAAOA,EAAK,OAC1D,OAAOA,CACT,CA0BA,SAAgBE,EACd,EACA,EACmB,CACnB,IAAMC,EAAQC,GAAS,OAAS,IAChC,GAAI,CAAC,OAAO,UAAUD,CAAK,GAAKA,EAAQ,EACtC,MAAU,WAC8C,oBACxD,EAEF,IAAME,kBAAS,IAAI,QACnB,OAAQ,GAAGC,IAAe,CACxB,IAAMN,EAAOD,EAAOQ,EAAa,CAAC,EAClC,GAAIP,IAAS,KAAM,OAAOQ,MAAcC,EAAG,GAAGH,CAAI,CAAC,EACnD,IAAII,EAAUL,EAAO,IAAIL,CAAI,EACzBU,IAAY,IAAA,KACd,EAAU,CAAC,EACXL,EAAO,IAAIL,EAAMU,CAAO,GAE1B,IAAK,IAAMC,KAASD,EAClB,GAAIf,EAASgB,EAAM,KAAML,CAAI,EAAG,OAAOK,EAAM,MAE/C,IAAMC,EAAQJ,MAAcC,EAAG,GAAGH,CAAI,CAAC,EAGvC,OAFAI,EAAQ,KAAK,CAAE,OAAM,OAAM,CAAC,EACxBA,EAAQ,OAASP,GAAOO,EAAQ,MAAM,EACnCE,CACT,CACF,C"}
@@ -1 +1 @@
1
- {"version":3,"file":"effect.js","names":["useEffect","second","third","useRenderEffect","onMount"],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\n/** What a held effect computes while its gate is closed: nothing for `apply` to act on. */\nconst HELD: unique symbol = Symbol(\"held\");\n\n/** The nearest gate above the current owner (see `Owner.gate`), or null. */\nfunction nearestGate(): (() => boolean) | null {\n for (let owner = currentOwner(); owner !== null; owner = owner.parent) {\n if (owner.gate !== null) return owner.gate;\n }\n return null;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : nearestGate();\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect.\n let opened = false;\n const held = (): boolean => {\n if (opened) return false;\n if (gate()) return true;\n opened = true;\n return false;\n };\n if (apply === null) {\n const inner = fn;\n fn = (previous) => (held() ? undefined : inner(previous));\n } else {\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => (held() ? HELD : innerFn(previous));\n apply = (value, previous) => {\n if ((value as unknown) === HELD) return undefined;\n if (skipFirst) {\n skipFirst = false;\n return undefined;\n }\n return innerApply(value, ((previous as unknown) === HELD ? undefined : previous) as never);\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n ...(apply === null ? {} : { apply }),\n ...(name === undefined ? {} : { name }),\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":"A,kCAqJA,SAAgBA,EACd,EACA,EACA,EACM,CACF,OAAOC,GAAW,YACpBC,GAIS,MACPA,GAAO,MAITD,GAA+E,IAEnF,CAyBA,SAAgBE,EACd,EACA,EACM,CAQR,CAoBA,SAAgBC,EAAQ,EAAgC,CAExD,C"}
1
+ {"version":3,"file":"effect.js","names":["useEffect","second","third","useRenderEffect","onMount"],"sources":["../../src/effect.ts"],"sourcesContent":["import { type Cleanup, createComputation, currentOwner, warn } from \"./extend\";\nimport { untrack } from \"./ownership\";\n\n/**\n * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.\n * @since 1.0.0\n */\nexport interface EffectOptions {\n /**\n * Label shown by devtools and diagnostics.\n * @default undefined (the effect is unnamed)\n */\n name?: string;\n}\n\n/**\n * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.\n * @since 1.0.0\n */\nexport interface DeferredEffectOptions extends EffectOptions {\n /**\n * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only\n * runs for later changes of it.\n * @default false\n */\n defer?: boolean;\n}\n\nfunction createEffect(\n fnIn: (previous: never) => unknown,\n applyIn: ((value: never, previous: never) => unknown) | null,\n render: boolean,\n deferIn: boolean,\n name: string | undefined,\n): void {\n // Effects never run on the server (G-24): no node, no ownership slot, no cost.\n if (__SERVER__) return;\n if (__DEV__ && currentOwner() === null) warn(\"NO_OWNER_EFFECT\");\n let fn = fnIn;\n let apply = applyIn;\n let defer = deferIn;\n const gate = render ? null : (currentOwner()?.gate ?? null);\n if (gate !== null) {\n // Held until the gate first opens (a Suspense boundary resolving). The gate is only read until\n // then, so later changes of it never re-run the effect. `closed` is what the latest run of `fn`\n // found: `apply` runs right after it, and does nothing for a run that was held.\n let opened = false;\n let closed = false;\n const innerFn = fn;\n const innerApply = apply;\n // `defer` skips the first real run, not the held one, so it is handled here.\n let skipFirst = defer;\n defer = false;\n fn = (previous) => {\n closed = !opened && gate();\n opened ||= !closed;\n return closed ? undefined : innerFn(previous);\n };\n if (innerApply !== null) {\n apply = (value, previous) => {\n if (closed) return undefined;\n if (!skipFirst) return innerApply(value, previous);\n skipFirst = false;\n return undefined;\n };\n }\n }\n createComputation({\n kind: \"effect\",\n fn,\n render,\n defer,\n apply: apply ?? undefined,\n name,\n });\n}\n\n/**\n * Runs a side effect after rendering and again whenever a tracked signal changes. The first run\n * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary\n * that is still showing its fallback, the first run waits until the boundary first shows its content.\n *\n * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only\n * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.\n * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).\n * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but\n * nothing can dispose it.\n *\n * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.\n * @param options A devtools name. Undefined uses the default.\n * @example\n * import { useEffect, useSignal } from \"@shadow-js/core\";\n *\n * function PageTitle(props: { unread: number }) {\n * const [title] = useSignal(\"Inbox\");\n * useEffect(() => {\n * document.title = `${title()} (${props.unread})`; // re-runs when either changes\n * });\n * return null;\n * }\n * @see useRenderEffect\n * @see onMount\n * @since 1.0.0\n */\nexport function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;\n/**\n * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`\n * untracked with the new and the previous value of `deps`. Use it when the effect body reads\n * signals that must not re-run it.\n *\n * @param deps Tracked; its result is passed to `fn`.\n * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there\n * is none yet). It may return a cleanup function, which runs before the next call or on disposal.\n * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.\n * @example\n * import { useEffect } from \"@shadow-js/core\";\n *\n * function Profile(props: { userId: string }) {\n * useEffect(\n * () => props.userId,\n * (next, previous) => console.log(`switched from ${previous} to ${next}`),\n * { defer: true }, // not called for the first id\n * );\n * return null;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function useEffect<T>(\n deps: () => T,\n fn: (value: T, previous: T | undefined) => void | Cleanup,\n options?: DeferredEffectOptions,\n): void;\nexport function useEffect(\n first: () => unknown,\n second?: unknown,\n third?: DeferredEffectOptions,\n): void {\n if (typeof second === \"function\") {\n createEffect(\n first,\n second as (value: never, previous: never) => unknown,\n false,\n third?.defer === true,\n third?.name,\n );\n } else {\n if (Array.isArray(second)) warn(\"EFFECT_DEPS_IGNORED\");\n createEffect(first, null, false, false, (second as EffectOptions | undefined)?.name);\n }\n}\n\n/**\n * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and\n * before user effects on every flush. Used for DOM bindings; application code rarely needs it.\n * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In\n * development, one created outside any owner warns `NO_OWNER_EFFECT`.\n *\n * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself\n * and may return a cleanup function.\n * @param apply Untracked; receives the value and the previous value (`undefined` on the first\n * run), and may return a cleanup function. Undefined: only `compute` runs.\n * @example\n * import { createRoot, useRenderEffect, useSignal } from \"@shadow-js/core\";\n *\n * const button = document.createElement(\"button\");\n * createRoot(() => {\n * const [label] = useSignal(\"Save\");\n * useRenderEffect(label, (text) => {\n * button.textContent = text; // runs now, and again when label changes\n * });\n * });\n * @see useEffect\n * @since 1.0.0\n */\nexport function useRenderEffect<T>(\n compute: () => T,\n apply?: (value: T, previous: T | undefined) => void | Cleanup,\n): void {\n createEffect(\n compute,\n (apply ?? null) as ((value: never, previous: never) => unknown) | null,\n true,\n false,\n undefined,\n );\n}\n\n/**\n * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never\n * run it again. Its return value, if a function, is the cleanup, which runs when the owner is\n * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`\n * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.\n *\n * @param fn Runs once, untracked. It may return a cleanup function.\n * @example\n * import { onMount } from \"@shadow-js/core\";\n *\n * function SearchBox() {\n * let input: HTMLInputElement | undefined;\n * onMount(() => input?.focus());\n * return <input ref={(el: HTMLInputElement) => (input = el)} />;\n * }\n * @see useEffect\n * @since 1.0.0\n */\nexport function onMount(fn: () => void | Cleanup): void {\n createEffect(() => untrack(fn), null, false, false, \"onMount\");\n}\n"],"mappings":"A,kCAqIA,SAAgBA,EACd,EACA,EACA,EACM,CACF,OAAOC,GAAW,YACpBC,GAIS,MACPA,GAAO,MAITD,GAA+E,IAEnF,CAyBA,SAAgBE,EACd,EACA,EACM,CAQR,CAoBA,SAAgBC,EAAQ,EAAgC,CAExD,C"}