@shadow-js/core 0.1.0 → 1.0.1

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 (387) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/LICENSE +2 -2
  3. package/README.md +134 -331
  4. package/dist/dev/action.d.ts +34 -0
  5. package/dist/dev/action.js +89 -0
  6. package/dist/dev/action.js.map +1 -0
  7. package/dist/dev/cache.d.ts +33 -0
  8. package/dist/dev/cache.js +61 -0
  9. package/dist/dev/cache.js.map +1 -0
  10. package/dist/dev/context.d.ts +104 -0
  11. package/dist/dev/context.js +110 -0
  12. package/dist/dev/context.js.map +1 -0
  13. package/dist/dev/effect.d.ts +120 -0
  14. package/dist/dev/effect.js +110 -0
  15. package/dist/dev/effect.js.map +1 -0
  16. package/dist/dev/env.d.ts +27 -0
  17. package/dist/dev/env.js +30 -0
  18. package/dist/dev/env.js.map +1 -0
  19. package/dist/dev/events.d.ts +26 -0
  20. package/dist/dev/events.js +32 -0
  21. package/dist/dev/events.js.map +1 -0
  22. package/dist/dev/extend/index.d.ts +329 -0
  23. package/dist/dev/extend/index.js +316 -0
  24. package/dist/dev/extend/index.js.map +1 -0
  25. package/dist/dev/external-store.d.ts +58 -0
  26. package/dist/dev/external-store.js +59 -0
  27. package/dist/dev/external-store.js.map +1 -0
  28. package/dist/dev/index.d.ts +29 -0
  29. package/dist/dev/index.js +26 -0
  30. package/dist/dev/internal/concurrency.d.ts +211 -0
  31. package/dist/dev/internal/concurrency.js +631 -0
  32. package/dist/dev/internal/concurrency.js.map +1 -0
  33. package/dist/dev/internal/devtools.d.ts +69 -0
  34. package/dist/dev/internal/devtools.js +76 -0
  35. package/dist/dev/internal/devtools.js.map +1 -0
  36. package/dist/dev/internal/diagnostics.d.ts +88 -0
  37. package/dist/dev/internal/diagnostics.js +101 -0
  38. package/dist/dev/internal/diagnostics.js.map +1 -0
  39. package/dist/dev/internal/dispose.d.ts +26 -0
  40. package/dist/dev/internal/dispose.js +48 -0
  41. package/dist/dev/internal/dispose.js.map +1 -0
  42. package/dist/dev/internal/flags.js +10 -0
  43. package/dist/dev/internal/flags.js.map +1 -0
  44. package/dist/dev/internal/graph.d.ts +231 -0
  45. package/dist/dev/internal/graph.js +577 -0
  46. package/dist/dev/internal/graph.js.map +1 -0
  47. package/dist/dev/internal/hydration-flag.d.ts +31 -0
  48. package/dist/dev/internal/hydration-flag.js +45 -0
  49. package/dist/dev/internal/hydration-flag.js.map +1 -0
  50. package/dist/dev/internal/messages.d.ts +54 -0
  51. package/dist/dev/internal/messages.js +53 -0
  52. package/dist/dev/internal/messages.js.map +1 -0
  53. package/dist/dev/internal/owner.d.ts +140 -0
  54. package/dist/dev/internal/owner.js +289 -0
  55. package/dist/dev/internal/owner.js.map +1 -0
  56. package/dist/dev/internal/queue.js +45 -0
  57. package/dist/dev/internal/queue.js.map +1 -0
  58. package/dist/dev/internal/scheduler.d.ts +111 -0
  59. package/dist/dev/internal/scheduler.js +286 -0
  60. package/dist/dev/internal/scheduler.js.map +1 -0
  61. package/dist/dev/internal/state.d.ts +139 -0
  62. package/dist/dev/internal/state.js +27 -0
  63. package/dist/dev/internal/state.js.map +1 -0
  64. package/dist/dev/internal/suspension.d.ts +41 -0
  65. package/dist/dev/internal/suspension.js +44 -0
  66. package/dist/dev/internal/suspension.js.map +1 -0
  67. package/dist/dev/internal/types.d.ts +44 -0
  68. package/dist/dev/list.d.ts +91 -0
  69. package/dist/dev/list.js +281 -0
  70. package/dist/dev/list.js.map +1 -0
  71. package/dist/dev/memo.d.ts +58 -0
  72. package/dist/dev/memo.js +40 -0
  73. package/dist/dev/memo.js.map +1 -0
  74. package/dist/dev/optimistic.d.ts +24 -0
  75. package/dist/dev/optimistic.js +44 -0
  76. package/dist/dev/optimistic.js.map +1 -0
  77. package/dist/dev/ownership.d.ts +202 -0
  78. package/dist/dev/ownership.js +260 -0
  79. package/dist/dev/ownership.js.map +1 -0
  80. package/dist/dev/props.d.ts +132 -0
  81. package/dist/dev/props.js +281 -0
  82. package/dist/dev/props.js.map +1 -0
  83. package/dist/dev/reaction.d.ts +27 -0
  84. package/dist/dev/reaction.js +60 -0
  85. package/dist/dev/reaction.js.map +1 -0
  86. package/dist/dev/reducer.d.ts +39 -0
  87. package/dist/dev/reducer.js +38 -0
  88. package/dist/dev/reducer.js.map +1 -0
  89. package/dist/dev/refs.d.ts +50 -0
  90. package/dist/dev/refs.js +57 -0
  91. package/dist/dev/refs.js.map +1 -0
  92. package/dist/dev/resource.d.ts +133 -0
  93. package/dist/dev/resource.js +176 -0
  94. package/dist/dev/resource.js.map +1 -0
  95. package/dist/dev/selector.d.ts +32 -0
  96. package/dist/dev/selector.js +117 -0
  97. package/dist/dev/selector.js.map +1 -0
  98. package/dist/dev/signal.d.ts +40 -0
  99. package/dist/dev/signal.js +38 -0
  100. package/dist/dev/signal.js.map +1 -0
  101. package/dist/dev/store/index.d.ts +5 -0
  102. package/dist/dev/store/index.js +4 -0
  103. package/dist/dev/store/nodes.js +191 -0
  104. package/dist/dev/store/nodes.js.map +1 -0
  105. package/dist/dev/store/proxies.js +159 -0
  106. package/dist/dev/store/proxies.js.map +1 -0
  107. package/dist/dev/store/read.d.ts +37 -0
  108. package/dist/dev/store/read.js +71 -0
  109. package/dist/dev/store/read.js.map +1 -0
  110. package/dist/dev/store/reconcile.d.ts +71 -0
  111. package/dist/dev/store/reconcile.js +185 -0
  112. package/dist/dev/store/reconcile.js.map +1 -0
  113. package/dist/dev/store/types.d.ts +104 -0
  114. package/dist/dev/store/use-store.d.ts +58 -0
  115. package/dist/dev/store/use-store.js +167 -0
  116. package/dist/dev/store/use-store.js.map +1 -0
  117. package/dist/dev/suspense.d.ts +99 -0
  118. package/dist/dev/suspense.js +44 -0
  119. package/dist/dev/suspense.js.map +1 -0
  120. package/dist/dev/transitions.d.ts +75 -0
  121. package/dist/dev/transitions.js +100 -0
  122. package/dist/dev/transitions.js.map +1 -0
  123. package/dist/prod/action.js +2 -0
  124. package/dist/prod/action.js.map +1 -0
  125. package/dist/prod/cache.js +2 -0
  126. package/dist/prod/cache.js.map +1 -0
  127. package/dist/prod/context.js +2 -0
  128. package/dist/prod/context.js.map +1 -0
  129. package/dist/prod/effect.js +2 -0
  130. package/dist/prod/effect.js.map +1 -0
  131. package/dist/prod/env.js +2 -0
  132. package/dist/prod/env.js.map +1 -0
  133. package/dist/prod/events.js +2 -0
  134. package/dist/prod/events.js.map +1 -0
  135. package/dist/prod/extend/index.js +2 -0
  136. package/dist/prod/extend/index.js.map +1 -0
  137. package/dist/prod/external-store.js +2 -0
  138. package/dist/prod/external-store.js.map +1 -0
  139. package/dist/prod/index.js +1 -0
  140. package/dist/prod/internal/concurrency.js +2 -0
  141. package/dist/prod/internal/concurrency.js.map +1 -0
  142. package/dist/prod/internal/devtools.js +2 -0
  143. package/dist/prod/internal/devtools.js.map +1 -0
  144. package/dist/prod/internal/diagnostics.js +2 -0
  145. package/dist/prod/internal/diagnostics.js.map +1 -0
  146. package/dist/prod/internal/dispose.js +2 -0
  147. package/dist/prod/internal/dispose.js.map +1 -0
  148. package/dist/prod/internal/flags.js +2 -0
  149. package/dist/prod/internal/flags.js.map +1 -0
  150. package/dist/prod/internal/graph.js +2 -0
  151. package/dist/prod/internal/graph.js.map +1 -0
  152. package/dist/prod/internal/hydration-flag.js +2 -0
  153. package/dist/prod/internal/hydration-flag.js.map +1 -0
  154. package/dist/prod/internal/messages.js +2 -0
  155. package/dist/prod/internal/messages.js.map +1 -0
  156. package/dist/prod/internal/owner.js +2 -0
  157. package/dist/prod/internal/owner.js.map +1 -0
  158. package/dist/prod/internal/queue.js +2 -0
  159. package/dist/prod/internal/queue.js.map +1 -0
  160. package/dist/prod/internal/scheduler.js +2 -0
  161. package/dist/prod/internal/scheduler.js.map +1 -0
  162. package/dist/prod/internal/state.js +2 -0
  163. package/dist/prod/internal/state.js.map +1 -0
  164. package/dist/prod/internal/suspension.js +2 -0
  165. package/dist/prod/internal/suspension.js.map +1 -0
  166. package/dist/prod/list.js +2 -0
  167. package/dist/prod/list.js.map +1 -0
  168. package/dist/prod/memo.js +2 -0
  169. package/dist/prod/memo.js.map +1 -0
  170. package/dist/prod/optimistic.js +2 -0
  171. package/dist/prod/optimistic.js.map +1 -0
  172. package/dist/prod/ownership.js +2 -0
  173. package/dist/prod/ownership.js.map +1 -0
  174. package/dist/prod/props.js +2 -0
  175. package/dist/prod/props.js.map +1 -0
  176. package/dist/prod/reaction.js +2 -0
  177. package/dist/prod/reaction.js.map +1 -0
  178. package/dist/prod/reducer.js +2 -0
  179. package/dist/prod/reducer.js.map +1 -0
  180. package/dist/prod/refs.js +2 -0
  181. package/dist/prod/refs.js.map +1 -0
  182. package/dist/prod/resource.js +2 -0
  183. package/dist/prod/resource.js.map +1 -0
  184. package/dist/prod/selector.js +2 -0
  185. package/dist/prod/selector.js.map +1 -0
  186. package/dist/prod/signal.js +2 -0
  187. package/dist/prod/signal.js.map +1 -0
  188. package/dist/prod/store/index.js +1 -0
  189. package/dist/prod/store/nodes.js +2 -0
  190. package/dist/prod/store/nodes.js.map +1 -0
  191. package/dist/prod/store/proxies.js +2 -0
  192. package/dist/prod/store/proxies.js.map +1 -0
  193. package/dist/prod/store/read.js +2 -0
  194. package/dist/prod/store/read.js.map +1 -0
  195. package/dist/prod/store/reconcile.js +2 -0
  196. package/dist/prod/store/reconcile.js.map +1 -0
  197. package/dist/prod/store/use-store.js +2 -0
  198. package/dist/prod/store/use-store.js.map +1 -0
  199. package/dist/prod/suspense.js +2 -0
  200. package/dist/prod/suspense.js.map +1 -0
  201. package/dist/prod/transitions.js +2 -0
  202. package/dist/prod/transitions.js.map +1 -0
  203. package/dist/server/action.js +2 -0
  204. package/dist/server/action.js.map +1 -0
  205. package/dist/server/cache.js +2 -0
  206. package/dist/server/cache.js.map +1 -0
  207. package/dist/server/context.js +2 -0
  208. package/dist/server/context.js.map +1 -0
  209. package/dist/server/effect.js +2 -0
  210. package/dist/server/effect.js.map +1 -0
  211. package/dist/server/env.js +2 -0
  212. package/dist/server/env.js.map +1 -0
  213. package/dist/server/events.js +2 -0
  214. package/dist/server/events.js.map +1 -0
  215. package/dist/server/extend/index.js +2 -0
  216. package/dist/server/extend/index.js.map +1 -0
  217. package/dist/server/external-store.js +2 -0
  218. package/dist/server/external-store.js.map +1 -0
  219. package/dist/server/index.js +1 -0
  220. package/dist/server/internal/concurrency.js +2 -0
  221. package/dist/server/internal/concurrency.js.map +1 -0
  222. package/dist/server/internal/devtools.js +2 -0
  223. package/dist/server/internal/devtools.js.map +1 -0
  224. package/dist/server/internal/diagnostics.js +2 -0
  225. package/dist/server/internal/diagnostics.js.map +1 -0
  226. package/dist/server/internal/dispose.js +2 -0
  227. package/dist/server/internal/dispose.js.map +1 -0
  228. package/dist/server/internal/flags.js +2 -0
  229. package/dist/server/internal/flags.js.map +1 -0
  230. package/dist/server/internal/graph.js +2 -0
  231. package/dist/server/internal/graph.js.map +1 -0
  232. package/dist/server/internal/hydration-flag.js +2 -0
  233. package/dist/server/internal/hydration-flag.js.map +1 -0
  234. package/dist/server/internal/messages.js +2 -0
  235. package/dist/server/internal/messages.js.map +1 -0
  236. package/dist/server/internal/owner.js +2 -0
  237. package/dist/server/internal/owner.js.map +1 -0
  238. package/dist/server/internal/queue.js +2 -0
  239. package/dist/server/internal/queue.js.map +1 -0
  240. package/dist/server/internal/scheduler.js +2 -0
  241. package/dist/server/internal/scheduler.js.map +1 -0
  242. package/dist/server/internal/state.js +2 -0
  243. package/dist/server/internal/state.js.map +1 -0
  244. package/dist/server/internal/suspension.js +2 -0
  245. package/dist/server/internal/suspension.js.map +1 -0
  246. package/dist/server/list.js +2 -0
  247. package/dist/server/list.js.map +1 -0
  248. package/dist/server/memo.js +2 -0
  249. package/dist/server/memo.js.map +1 -0
  250. package/dist/server/optimistic.js +2 -0
  251. package/dist/server/optimistic.js.map +1 -0
  252. package/dist/server/ownership.js +2 -0
  253. package/dist/server/ownership.js.map +1 -0
  254. package/dist/server/props.js +2 -0
  255. package/dist/server/props.js.map +1 -0
  256. package/dist/server/reaction.js +2 -0
  257. package/dist/server/reaction.js.map +1 -0
  258. package/dist/server/reducer.js +2 -0
  259. package/dist/server/reducer.js.map +1 -0
  260. package/dist/server/refs.js +2 -0
  261. package/dist/server/refs.js.map +1 -0
  262. package/dist/server/resource.js +2 -0
  263. package/dist/server/resource.js.map +1 -0
  264. package/dist/server/selector.js +2 -0
  265. package/dist/server/selector.js.map +1 -0
  266. package/dist/server/signal.js +2 -0
  267. package/dist/server/signal.js.map +1 -0
  268. package/dist/server/store/index.js +1 -0
  269. package/dist/server/store/nodes.js +2 -0
  270. package/dist/server/store/nodes.js.map +1 -0
  271. package/dist/server/store/proxies.js +2 -0
  272. package/dist/server/store/proxies.js.map +1 -0
  273. package/dist/server/store/read.js +2 -0
  274. package/dist/server/store/read.js.map +1 -0
  275. package/dist/server/store/reconcile.js +2 -0
  276. package/dist/server/store/reconcile.js.map +1 -0
  277. package/dist/server/store/use-store.js +2 -0
  278. package/dist/server/store/use-store.js.map +1 -0
  279. package/dist/server/suspense.js +2 -0
  280. package/dist/server/suspense.js.map +1 -0
  281. package/dist/server/transitions.js +2 -0
  282. package/dist/server/transitions.js.map +1 -0
  283. package/dist/server-dev/action.js +89 -0
  284. package/dist/server-dev/action.js.map +1 -0
  285. package/dist/server-dev/cache.js +61 -0
  286. package/dist/server-dev/cache.js.map +1 -0
  287. package/dist/server-dev/context.js +107 -0
  288. package/dist/server-dev/context.js.map +1 -0
  289. package/dist/server-dev/effect.js +55 -0
  290. package/dist/server-dev/effect.js.map +1 -0
  291. package/dist/server-dev/env.js +30 -0
  292. package/dist/server-dev/env.js.map +1 -0
  293. package/dist/server-dev/events.js +32 -0
  294. package/dist/server-dev/events.js.map +1 -0
  295. package/dist/server-dev/extend/index.js +316 -0
  296. package/dist/server-dev/extend/index.js.map +1 -0
  297. package/dist/server-dev/external-store.js +45 -0
  298. package/dist/server-dev/external-store.js.map +1 -0
  299. package/dist/server-dev/index.js +26 -0
  300. package/dist/server-dev/internal/concurrency.js +632 -0
  301. package/dist/server-dev/internal/concurrency.js.map +1 -0
  302. package/dist/server-dev/internal/devtools.js +76 -0
  303. package/dist/server-dev/internal/devtools.js.map +1 -0
  304. package/dist/server-dev/internal/diagnostics.js +101 -0
  305. package/dist/server-dev/internal/diagnostics.js.map +1 -0
  306. package/dist/server-dev/internal/dispose.js +48 -0
  307. package/dist/server-dev/internal/dispose.js.map +1 -0
  308. package/dist/server-dev/internal/flags.js +10 -0
  309. package/dist/server-dev/internal/flags.js.map +1 -0
  310. package/dist/server-dev/internal/graph.js +577 -0
  311. package/dist/server-dev/internal/graph.js.map +1 -0
  312. package/dist/server-dev/internal/hydration-flag.js +45 -0
  313. package/dist/server-dev/internal/hydration-flag.js.map +1 -0
  314. package/dist/server-dev/internal/messages.js +53 -0
  315. package/dist/server-dev/internal/messages.js.map +1 -0
  316. package/dist/server-dev/internal/owner.js +289 -0
  317. package/dist/server-dev/internal/owner.js.map +1 -0
  318. package/dist/server-dev/internal/queue.js +45 -0
  319. package/dist/server-dev/internal/queue.js.map +1 -0
  320. package/dist/server-dev/internal/scheduler.js +286 -0
  321. package/dist/server-dev/internal/scheduler.js.map +1 -0
  322. package/dist/server-dev/internal/state.js +27 -0
  323. package/dist/server-dev/internal/state.js.map +1 -0
  324. package/dist/server-dev/internal/suspension.js +44 -0
  325. package/dist/server-dev/internal/suspension.js.map +1 -0
  326. package/dist/server-dev/list.js +281 -0
  327. package/dist/server-dev/list.js.map +1 -0
  328. package/dist/server-dev/memo.js +40 -0
  329. package/dist/server-dev/memo.js.map +1 -0
  330. package/dist/server-dev/optimistic.js +44 -0
  331. package/dist/server-dev/optimistic.js.map +1 -0
  332. package/dist/server-dev/ownership.js +260 -0
  333. package/dist/server-dev/ownership.js.map +1 -0
  334. package/dist/server-dev/props.js +281 -0
  335. package/dist/server-dev/props.js.map +1 -0
  336. package/dist/server-dev/reaction.js +60 -0
  337. package/dist/server-dev/reaction.js.map +1 -0
  338. package/dist/server-dev/reducer.js +38 -0
  339. package/dist/server-dev/reducer.js.map +1 -0
  340. package/dist/server-dev/refs.js +57 -0
  341. package/dist/server-dev/refs.js.map +1 -0
  342. package/dist/server-dev/resource.js +175 -0
  343. package/dist/server-dev/resource.js.map +1 -0
  344. package/dist/server-dev/selector.js +81 -0
  345. package/dist/server-dev/selector.js.map +1 -0
  346. package/dist/server-dev/signal.js +38 -0
  347. package/dist/server-dev/signal.js.map +1 -0
  348. package/dist/server-dev/store/index.js +4 -0
  349. package/dist/server-dev/store/nodes.js +191 -0
  350. package/dist/server-dev/store/nodes.js.map +1 -0
  351. package/dist/server-dev/store/proxies.js +159 -0
  352. package/dist/server-dev/store/proxies.js.map +1 -0
  353. package/dist/server-dev/store/read.js +71 -0
  354. package/dist/server-dev/store/read.js.map +1 -0
  355. package/dist/server-dev/store/reconcile.js +185 -0
  356. package/dist/server-dev/store/reconcile.js.map +1 -0
  357. package/dist/server-dev/store/use-store.js +167 -0
  358. package/dist/server-dev/store/use-store.js.map +1 -0
  359. package/dist/server-dev/suspense.js +44 -0
  360. package/dist/server-dev/suspense.js.map +1 -0
  361. package/dist/server-dev/transitions.js +85 -0
  362. package/dist/server-dev/transitions.js.map +1 -0
  363. package/package.json +111 -50
  364. package/dist/chunk-6Y3CCWOY.js +0 -887
  365. package/dist/chunk-6Y3CCWOY.js.map +0 -1
  366. package/dist/chunk-B5FTYDUG.js +0 -3
  367. package/dist/chunk-B5FTYDUG.js.map +0 -1
  368. package/dist/index.cjs +0 -2000
  369. package/dist/index.cjs.map +0 -1
  370. package/dist/index.d.cts +0 -609
  371. package/dist/index.d.ts +0 -609
  372. package/dist/index.js +0 -1094
  373. package/dist/index.js.map +0 -1
  374. package/dist/jsx-Bugil6CJ.d.cts +0 -151
  375. package/dist/jsx-Bugil6CJ.d.ts +0 -151
  376. package/dist/jsx-dev-runtime.cjs +0 -742
  377. package/dist/jsx-dev-runtime.cjs.map +0 -1
  378. package/dist/jsx-dev-runtime.d.cts +0 -2
  379. package/dist/jsx-dev-runtime.d.ts +0 -2
  380. package/dist/jsx-dev-runtime.js +0 -4
  381. package/dist/jsx-dev-runtime.js.map +0 -1
  382. package/dist/jsx-runtime.cjs +0 -742
  383. package/dist/jsx-runtime.cjs.map +0 -1
  384. package/dist/jsx-runtime.d.cts +0 -36
  385. package/dist/jsx-runtime.d.ts +0 -36
  386. package/dist/jsx-runtime.js +0 -4
  387. package/dist/jsx-runtime.js.map +0 -1
@@ -0,0 +1,24 @@
1
+ import { Accessor } from "./internal/types.js";
2
+ /**
3
+ * Optimistic state: shows `reducer` applied over the real value for every action whose
4
+ * `settled` promise is still pending. When the promise settles (either way) the action is
5
+ * dropped and the view falls back to the real source, which is where the confirmed result lives.
6
+ *
7
+ * @param source The authoritative value, tracked.
8
+ * @param reducer Pure function combining the current state with one pending action. It runs for
9
+ * every pending action, in the order they were applied, each time the state recomputes.
10
+ * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once
11
+ * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.
12
+ * @example
13
+ * import { useOptimistic, useSignal } from "@shadow-js/core";
14
+ *
15
+ * const [todos, setTodos] = useSignal<string[]>([]);
16
+ * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);
17
+ * const save = (text: string) =>
18
+ * fetch("/api/todos", { method: "POST", body: text }).then(() => setTodos((l) => [...l, text]));
19
+ * addTodo("milk", save("milk")); // shown() includes "milk" at once
20
+ * @see useAction
21
+ * @since 1.0.0
22
+ */
23
+ export declare function useOptimistic<T, A>(source: Accessor<T>, reducer: (state: T, action: A) => T): [Accessor<T>, (action: A, settled: Promise<unknown>) => void];
24
+ //# sourceMappingURL=optimistic.d.ts.map
@@ -0,0 +1,44 @@
1
+ import { useSignal } from "./signal.js";
2
+ import { useMemo } from "./memo.js";
3
+ // src/optimistic.ts
4
+ /**
5
+ * Optimistic state: shows `reducer` applied over the real value for every action whose
6
+ * `settled` promise is still pending. When the promise settles (either way) the action is
7
+ * dropped and the view falls back to the real source, which is where the confirmed result lives.
8
+ *
9
+ * @param source The authoritative value, tracked.
10
+ * @param reducer Pure function combining the current state with one pending action. It runs for
11
+ * every pending action, in the order they were applied, each time the state recomputes.
12
+ * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once
13
+ * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.
14
+ * @example
15
+ * import { useOptimistic, useSignal } from "@shadow-js/core";
16
+ *
17
+ * const [todos, setTodos] = useSignal<string[]>([]);
18
+ * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);
19
+ * const save = (text: string) =>
20
+ * fetch("/api/todos", { method: "POST", body: text }).then(() => setTodos((l) => [...l, text]));
21
+ * addTodo("milk", save("milk")); // shown() includes "milk" at once
22
+ * @see useAction
23
+ * @since 1.0.0
24
+ */
25
+ function useOptimistic(source, reducer) {
26
+ const [pending, setPending] = useSignal([]);
27
+ const state = useMemo(() => {
28
+ let current = source();
29
+ for (const entry of pending()) current = reducer(current, entry.action);
30
+ return current;
31
+ });
32
+ const apply = (action, settled) => {
33
+ const entry = { action };
34
+ setPending((list) => [...list, entry]);
35
+ const drop = () => {
36
+ setPending((list) => list.filter((item) => item !== entry));
37
+ };
38
+ settled.then(drop, drop);
39
+ };
40
+ return [state, apply];
41
+ }
42
+ export { useOptimistic };
43
+
44
+ //# sourceMappingURL=optimistic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"optimistic.js","names":[],"sources":["../../src/optimistic.ts"],"sourcesContent":["import type { Accessor } from \"./extend\";\nimport { useMemo } from \"./memo\";\nimport { useSignal } from \"./signal\";\n\n/**\n * Optimistic state: shows `reducer` applied over the real value for every action whose\n * `settled` promise is still pending. When the promise settles (either way) the action is\n * dropped and the view falls back to the real source, which is where the confirmed result lives.\n *\n * @param source The authoritative value, tracked.\n * @param reducer Pure function combining the current state with one pending action. It runs for\n * every pending action, in the order they were applied, each time the state recomputes.\n * @returns `[state, apply]`. `state` is a memo; `apply(action, settled)` adds the action at once\n * and drops it when `settled` resolves or rejects. Pass the mutation's promise as `settled`.\n * @example\n * import { useOptimistic, useSignal } from \"@shadow-js/core\";\n *\n * const [todos, setTodos] = useSignal<string[]>([]);\n * const [shown, addTodo] = useOptimistic(todos, (list, text: string) => [...list, text]);\n * const save = (text: string) =>\n * fetch(\"/api/todos\", { method: \"POST\", body: text }).then(() => setTodos((l) => [...l, text]));\n * addTodo(\"milk\", save(\"milk\")); // shown() includes \"milk\" at once\n * @see useAction\n * @since 1.0.0\n */\nexport function useOptimistic<T, A>(\n source: Accessor<T>,\n reducer: (state: T, action: A) => T,\n): [Accessor<T>, (action: A, settled: Promise<unknown>) => void] {\n const [pending, setPending] = useSignal<ReadonlyArray<{ action: A }>>([]);\n const state = useMemo(() => {\n let current = source();\n for (const entry of pending()) current = reducer(current, entry.action);\n return current;\n });\n const apply = (action: A, settled: Promise<unknown>): void => {\n const entry = { action };\n setPending((list) => [...list, entry]);\n const drop = (): void => {\n setPending((list) => list.filter((item) => item !== entry));\n };\n settled.then(drop, drop);\n };\n return [state, apply];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,cACd,QACA,SAC+D;CAC/D,MAAM,CAAC,SAAS,cAAc,UAAwC,CAAC,CAAC;CACxE,MAAM,QAAQ,cAAc;EAC1B,IAAI,UAAU,OAAO;EACrB,KAAK,MAAM,SAAS,QAAQ,GAAG,UAAU,QAAQ,SAAS,MAAM,MAAM;EACtE,OAAO;CACT,CAAC;CACD,MAAM,SAAS,QAAW,YAAoC;EAC5D,MAAM,QAAQ,EAAE,OAAO;EACvB,YAAY,SAAS,CAAC,GAAG,MAAM,KAAK,CAAC;EACrC,MAAM,aAAmB;GACvB,YAAY,SAAS,KAAK,QAAQ,SAAS,SAAS,KAAK,CAAC;EAC5D;EACA,QAAQ,KAAK,MAAM,IAAI;CACzB;CACA,OAAO,CAAC,OAAO,KAAK;AACtB"}
@@ -0,0 +1,202 @@
1
+ import { Cleanup, ErrorHandler } from "./internal/types.js";
2
+ import { Owner } from "./internal/owner.js";
3
+ /**
4
+ * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an
5
+ * effect or a memo to read a value without re-running when that value changes. The current owner
6
+ * is kept, so effects and cleanups created inside `fn` are still owned.
7
+ *
8
+ * @param fn The function to run untracked.
9
+ * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.
10
+ * @example
11
+ * import { untrack, useEffect, useSignal } from "@shadow-js/core";
12
+ *
13
+ * const [count, setCount] = useSignal(0);
14
+ * const [unit] = useSignal("clicks");
15
+ * useEffect(() => {
16
+ * // Re-runs when `count` changes, never when `unit` changes.
17
+ * console.log(`${count()} ${untrack(unit)}`);
18
+ * });
19
+ * setCount(1);
20
+ * @see useEvent
21
+ * @since 1.0.0
22
+ */
23
+ export declare function untrack<T>(fn: () => T): T;
24
+ /**
25
+ * Options of {@link createRoot}.
26
+ * @since 1.0.0
27
+ */
28
+ export interface RootOptions {
29
+ /**
30
+ * When true, the root is not attached to the current owner: it outlives that owner and is
31
+ * disposed only through the `dispose` function passed to the body. It still sees the context
32
+ * values provided above the current owner.
33
+ * @default false (the root is a child of the current owner and is disposed with it)
34
+ */
35
+ detached?: boolean;
36
+ }
37
+ /**
38
+ * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
39
+ * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use
40
+ * it for code that runs outside a component, such as an app entry point, a test or a module that
41
+ * owns long-lived effects.
42
+ *
43
+ * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.
44
+ * @param options `detached` keeps the root out of the current owner. Undefined uses the default
45
+ * (attached).
46
+ * @returns Whatever `fn` returns.
47
+ * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are
48
+ * disposed.
49
+ * @example
50
+ * import { createRoot, useEffect, useSignal } from "@shadow-js/core";
51
+ *
52
+ * const [count, setCount] = useSignal(0);
53
+ * const dispose = createRoot((dispose) => {
54
+ * useEffect(() => console.log(count()));
55
+ * return dispose;
56
+ * });
57
+ * setCount(1);
58
+ * dispose(); // the effect stops and its cleanups run
59
+ * @see getOwner
60
+ * @since 1.0.0
61
+ */
62
+ export declare function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T;
63
+ /**
64
+ * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a
65
+ * component or root runs, then hand it to {@link runWithOwner} from code that runs later.
66
+ *
67
+ * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that
68
+ * runs after an `await` or a timer).
69
+ * @example
70
+ * import { getOwner, onCleanup, runWithOwner } from "@shadow-js/core";
71
+ *
72
+ * function Poller() {
73
+ * const owner = getOwner();
74
+ * setTimeout(() => {
75
+ * runWithOwner(owner, () => onCleanup(() => console.log("poller disposed")));
76
+ * }, 1000);
77
+ * return null;
78
+ * }
79
+ * @see runWithOwner
80
+ * @since 1.0.0
81
+ */
82
+ export declare function getOwner(): Owner | null;
83
+ /**
84
+ * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an
85
+ * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and
86
+ * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs
87
+ * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.
88
+ *
89
+ * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`
90
+ * without an owner.
91
+ * @param fn The function to run.
92
+ * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.
93
+ * @example
94
+ * import { createContext, getOwner, runWithOwner, useContext } from "@shadow-js/core";
95
+ *
96
+ * const Locale = createContext("en");
97
+ *
98
+ * function Clock() {
99
+ * const owner = getOwner();
100
+ * queueMicrotask(() => {
101
+ * const locale = runWithOwner(owner, () => useContext(Locale));
102
+ * console.log(new Date().toLocaleTimeString(locale));
103
+ * });
104
+ * return null;
105
+ * }
106
+ * @see getOwner
107
+ * @since 1.0.0
108
+ */
109
+ export declare function runWithOwner<T>(owner: Owner | null, fn: () => T): T;
110
+ /**
111
+ * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it
112
+ * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and
113
+ * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because
114
+ * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.
115
+ *
116
+ * @param fn The cleanup to register.
117
+ * @example
118
+ * import { onCleanup } from "@shadow-js/core";
119
+ *
120
+ * function Ticker() {
121
+ * const timer = setInterval(() => console.log("tick"), 1000);
122
+ * onCleanup(() => clearInterval(timer));
123
+ * return null;
124
+ * }
125
+ * @see onMount
126
+ * @since 1.0.0
127
+ */
128
+ export declare function onCleanup(fn: Cleanup): void;
129
+ /**
130
+ * Registers an error handler on the current owner. It receives errors thrown in this owner's scope
131
+ * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same
132
+ * owner are tried newest first; a handler that throws passes its own error to the next handler up.
133
+ * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.
134
+ *
135
+ * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.
136
+ * @example
137
+ * import { onError, useEffect } from "@shadow-js/core";
138
+ *
139
+ * function Dashboard() {
140
+ * onError((error) => console.error("dashboard failed:", error));
141
+ * useEffect(() => {
142
+ * throw new Error("widget crashed"); // reaches the handler above
143
+ * });
144
+ * return null;
145
+ * }
146
+ * @see catchError
147
+ * @since 1.0.0
148
+ */
149
+ export declare function onError(handler: ErrorHandler): void;
150
+ /**
151
+ * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by
152
+ * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with
153
+ * the current owner. Use it to contain the failures of one part of a component tree.
154
+ *
155
+ * @param fn The function to run; it runs untracked, with the new scope as owner.
156
+ * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.
157
+ * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.
158
+ * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).
159
+ * @example
160
+ * import { catchError, useEffect } from "@shadow-js/core";
161
+ *
162
+ * function Widget() {
163
+ * return catchError(
164
+ * () => {
165
+ * useEffect(() => {
166
+ * throw new Error("network down");
167
+ * });
168
+ * return "ready";
169
+ * },
170
+ * (error) => console.error("widget failed:", error),
171
+ * );
172
+ * }
173
+ * @see onError
174
+ * @since 1.0.0
175
+ */
176
+ export declare function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined;
177
+ /**
178
+ * Returns an id that is identical on server and client for the same position in the owner tree.
179
+ * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references
180
+ * and in `querySelector("#" + id)` without escaping. Use it to link a label to its input, or an
181
+ * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.
182
+ *
183
+ * @returns A new id, unique within the root; each call on the same owner returns the next one.
184
+ * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists
185
+ * there.
186
+ * @example
187
+ * import { useId } from "@shadow-js/core";
188
+ *
189
+ * function EmailField() {
190
+ * const id = useId();
191
+ * return (
192
+ * <>
193
+ * <label for={id}>Email</label>
194
+ * <input id={id} type="email" />
195
+ * </>
196
+ * );
197
+ * }
198
+ * @since 1.0.0
199
+ */
200
+ export declare function useId(): string;
201
+ export type { Owner };
202
+ //# sourceMappingURL=ownership.d.ts.map
@@ -0,0 +1,260 @@
1
+ import { ShadowError, warn } from "./internal/diagnostics.js";
2
+ import { Owner, addCleanup, handleError } from "./internal/owner.js";
3
+ import { disposeTree } from "./internal/dispose.js";
4
+ import { currentOwner, runInScope } from "./extend/index.js";
5
+ // src/ownership.ts
6
+ /**
7
+ * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an
8
+ * effect or a memo to read a value without re-running when that value changes. The current owner
9
+ * is kept, so effects and cleanups created inside `fn` are still owned.
10
+ *
11
+ * @param fn The function to run untracked.
12
+ * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.
13
+ * @example
14
+ * import { untrack, useEffect, useSignal } from "@shadow-js/core";
15
+ *
16
+ * const [count, setCount] = useSignal(0);
17
+ * const [unit] = useSignal("clicks");
18
+ * useEffect(() => {
19
+ * // Re-runs when `count` changes, never when `unit` changes.
20
+ * console.log(`${count()} ${untrack(unit)}`);
21
+ * });
22
+ * setCount(1);
23
+ * @see useEvent
24
+ * @since 1.0.0
25
+ */
26
+ function untrack(fn) {
27
+ return runInScope({ listener: null }, fn);
28
+ }
29
+ /**
30
+ * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is
31
+ * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use
32
+ * it for code that runs outside a component, such as an app entry point, a test or a module that
33
+ * owns long-lived effects.
34
+ *
35
+ * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.
36
+ * @param options `detached` keeps the root out of the current owner. Undefined uses the default
37
+ * (attached).
38
+ * @returns Whatever `fn` returns.
39
+ * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are
40
+ * disposed.
41
+ * @example
42
+ * import { createRoot, useEffect, useSignal } from "@shadow-js/core";
43
+ *
44
+ * const [count, setCount] = useSignal(0);
45
+ * const dispose = createRoot((dispose) => {
46
+ * useEffect(() => console.log(count()));
47
+ * return dispose;
48
+ * });
49
+ * setCount(1);
50
+ * dispose(); // the effect stops and its cleanups run
51
+ * @see getOwner
52
+ * @since 1.0.0
53
+ */
54
+ function createRoot(fn, options) {
55
+ const detached = options?.detached === true;
56
+ const current = currentOwner();
57
+ const root = new Owner(detached ? null : current);
58
+ if (detached) root.context = current === null ? null : current.context;
59
+ try {
60
+ return runInScope({
61
+ owner: root,
62
+ listener: null
63
+ }, () => fn(() => disposeTree(root)));
64
+ } catch (error) {
65
+ disposeTree(root);
66
+ throw error;
67
+ }
68
+ }
69
+ /**
70
+ * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a
71
+ * component or root runs, then hand it to {@link runWithOwner} from code that runs later.
72
+ *
73
+ * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that
74
+ * runs after an `await` or a timer).
75
+ * @example
76
+ * import { getOwner, onCleanup, runWithOwner } from "@shadow-js/core";
77
+ *
78
+ * function Poller() {
79
+ * const owner = getOwner();
80
+ * setTimeout(() => {
81
+ * runWithOwner(owner, () => onCleanup(() => console.log("poller disposed")));
82
+ * }, 1000);
83
+ * return null;
84
+ * }
85
+ * @see runWithOwner
86
+ * @since 1.0.0
87
+ */
88
+ function getOwner() {
89
+ return currentOwner();
90
+ }
91
+ /**
92
+ * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an
93
+ * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and
94
+ * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs
95
+ * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.
96
+ *
97
+ * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`
98
+ * without an owner.
99
+ * @param fn The function to run.
100
+ * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.
101
+ * @example
102
+ * import { createContext, getOwner, runWithOwner, useContext } from "@shadow-js/core";
103
+ *
104
+ * const Locale = createContext("en");
105
+ *
106
+ * function Clock() {
107
+ * const owner = getOwner();
108
+ * queueMicrotask(() => {
109
+ * const locale = runWithOwner(owner, () => useContext(Locale));
110
+ * console.log(new Date().toLocaleTimeString(locale));
111
+ * });
112
+ * return null;
113
+ * }
114
+ * @see getOwner
115
+ * @since 1.0.0
116
+ */
117
+ function runWithOwner(owner, fn) {
118
+ let target = owner;
119
+ if (target?.disposed) {
120
+ warn("RUN_WITH_DISPOSED_OWNER");
121
+ target = null;
122
+ }
123
+ return runInScope({
124
+ owner: target,
125
+ listener: null
126
+ }, fn);
127
+ }
128
+ /**
129
+ * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it
130
+ * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and
131
+ * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because
132
+ * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.
133
+ *
134
+ * @param fn The cleanup to register.
135
+ * @example
136
+ * import { onCleanup } from "@shadow-js/core";
137
+ *
138
+ * function Ticker() {
139
+ * const timer = setInterval(() => console.log("tick"), 1000);
140
+ * onCleanup(() => clearInterval(timer));
141
+ * return null;
142
+ * }
143
+ * @see onMount
144
+ * @since 1.0.0
145
+ */
146
+ function onCleanup(fn) {
147
+ const owner = currentOwner();
148
+ if (owner === null) {
149
+ warn("NO_OWNER_CLEANUP");
150
+ return;
151
+ }
152
+ addCleanup(owner, fn);
153
+ }
154
+ /**
155
+ * Registers an error handler on the current owner. It receives errors thrown in this owner's scope
156
+ * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same
157
+ * owner are tried newest first; a handler that throws passes its own error to the next handler up.
158
+ * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.
159
+ *
160
+ * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.
161
+ * @example
162
+ * import { onError, useEffect } from "@shadow-js/core";
163
+ *
164
+ * function Dashboard() {
165
+ * onError((error) => console.error("dashboard failed:", error));
166
+ * useEffect(() => {
167
+ * throw new Error("widget crashed"); // reaches the handler above
168
+ * });
169
+ * return null;
170
+ * }
171
+ * @see catchError
172
+ * @since 1.0.0
173
+ */
174
+ function onError(handler) {
175
+ const owner = currentOwner();
176
+ if (owner === null) {
177
+ warn("NO_OWNER_ERROR");
178
+ return;
179
+ }
180
+ if (owner.errorHandlers === null) owner.errorHandlers = [handler];
181
+ else owner.errorHandlers.push(handler);
182
+ }
183
+ /**
184
+ * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by
185
+ * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with
186
+ * the current owner. Use it to contain the failures of one part of a component tree.
187
+ *
188
+ * @param fn The function to run; it runs untracked, with the new scope as owner.
189
+ * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.
190
+ * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.
191
+ * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).
192
+ * @example
193
+ * import { catchError, useEffect } from "@shadow-js/core";
194
+ *
195
+ * function Widget() {
196
+ * return catchError(
197
+ * () => {
198
+ * useEffect(() => {
199
+ * throw new Error("network down");
200
+ * });
201
+ * return "ready";
202
+ * },
203
+ * (error) => console.error("widget failed:", error),
204
+ * );
205
+ * }
206
+ * @see onError
207
+ * @since 1.0.0
208
+ */
209
+ function catchError(fn, handler) {
210
+ const scope = new Owner(currentOwner());
211
+ scope.errorHandlers = [handler];
212
+ try {
213
+ return runWithOwner(scope, fn);
214
+ } catch (error) {
215
+ handleError(error, scope);
216
+ return;
217
+ }
218
+ }
219
+ /**
220
+ * Returns an id that is identical on server and client for the same position in the owner tree.
221
+ * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references
222
+ * and in `querySelector("#" + id)` without escaping. Use it to link a label to its input, or an
223
+ * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.
224
+ *
225
+ * @returns A new id, unique within the root; each call on the same owner returns the next one.
226
+ * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists
227
+ * there.
228
+ * @example
229
+ * import { useId } from "@shadow-js/core";
230
+ *
231
+ * function EmailField() {
232
+ * const id = useId();
233
+ * return (
234
+ * <>
235
+ * <label for={id}>Email</label>
236
+ * <input id={id} type="email" />
237
+ * </>
238
+ * );
239
+ * }
240
+ * @since 1.0.0
241
+ */
242
+ function useId() {
243
+ const owner = currentOwner();
244
+ if (owner === null) throw new ShadowError("NO_OWNER_ID");
245
+ for (let host = owner; host !== null; host = host.parent) {
246
+ if (host.idPrefix === void 0) continue;
247
+ const hosted = host.idCount;
248
+ host.idCount += 1;
249
+ return `s${host.idPrefix}${hosted}`;
250
+ }
251
+ const path = [];
252
+ for (let node = owner; node !== null; node = node.parent) path.push(node.index);
253
+ path.reverse();
254
+ const sequence = owner.idCount;
255
+ owner.idCount += 1;
256
+ return `s${path.join("-")}_${sequence}`;
257
+ }
258
+ export { catchError, createRoot, getOwner, onCleanup, onError, runWithOwner, untrack, useId };
259
+
260
+ //# sourceMappingURL=ownership.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ownership.js","names":["disposeOwner"],"sources":["../../src/ownership.ts"],"sourcesContent":["import {\n addCleanup,\n type Cleanup,\n currentOwner,\n disposeOwner,\n type ErrorHandler,\n handleError,\n Owner,\n runInScope,\n ShadowError,\n warn,\n} from \"./extend\";\n\nexport type { Owner };\n\n/**\n * Runs `fn` without subscribing the running computation to anything `fn` reads. Use it inside an\n * effect or a memo to read a value without re-running when that value changes. The current owner\n * is kept, so effects and cleanups created inside `fn` are still owned.\n *\n * @param fn The function to run untracked.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { untrack, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const [unit] = useSignal(\"clicks\");\n * useEffect(() => {\n * // Re-runs when `count` changes, never when `unit` changes.\n * console.log(`${count()} ${untrack(unit)}`);\n * });\n * setCount(1);\n * @see useEvent\n * @since 1.0.0\n */\nexport function untrack<T>(fn: () => T): T {\n return runInScope({ listener: null }, fn);\n}\n\n/**\n * Options of {@link createRoot}.\n * @since 1.0.0\n */\nexport interface RootOptions {\n /**\n * When true, the root is not attached to the current owner: it outlives that owner and is\n * disposed only through the `dispose` function passed to the body. It still sees the context\n * values provided above the current owner.\n * @default false (the root is a child of the current owner and is disposed with it)\n */\n detached?: boolean;\n}\n\n/**\n * Creates an ownership scope. Everything created inside (effects, memos, cleanups, children) is\n * disposed together when `dispose` is called or, for attached roots, when the parent disposes. Use\n * it for code that runs outside a component, such as an app entry point, a test or a module that\n * owns long-lived effects.\n *\n * @param fn Body; receives the `dispose` function. Runs untracked, with the new root as owner.\n * @param options `detached` keeps the root out of the current owner. Undefined uses the default\n * (attached).\n * @returns Whatever `fn` returns.\n * @throws Rethrows any error thrown by `fn`, after the root and everything created in it are\n * disposed.\n * @example\n * import { createRoot, useEffect, useSignal } from \"@shadow-js/core\";\n *\n * const [count, setCount] = useSignal(0);\n * const dispose = createRoot((dispose) => {\n * useEffect(() => console.log(count()));\n * return dispose;\n * });\n * setCount(1);\n * dispose(); // the effect stops and its cleanups run\n * @see getOwner\n * @since 1.0.0\n */\nexport function createRoot<T>(fn: (dispose: () => void) => T, options?: RootOptions): T {\n const detached = options?.detached === true;\n const current = currentOwner();\n const root = new Owner(detached ? null : current);\n if (detached) root.context = current === null ? null : current.context;\n try {\n return runInScope({ owner: root, listener: null }, () => fn(() => disposeOwner(root)));\n } catch (error) {\n disposeOwner(root);\n throw error;\n }\n}\n\n/**\n * Returns the owner that currently adopts new effects, memos and cleanups. Capture it while a\n * component or root runs, then hand it to {@link runWithOwner} from code that runs later.\n *\n * @returns The current owner, or `null` outside any owner (at module scope, or in a callback that\n * runs after an `await` or a timer).\n * @example\n * import { getOwner, onCleanup, runWithOwner } from \"@shadow-js/core\";\n *\n * function Poller() {\n * const owner = getOwner();\n * setTimeout(() => {\n * runWithOwner(owner, () => onCleanup(() => console.log(\"poller disposed\")));\n * }, 1000);\n * return null;\n * }\n * @see runWithOwner\n * @since 1.0.0\n */\nexport function getOwner(): Owner | null {\n return currentOwner();\n}\n\n/**\n * Runs `fn` with `owner` as the current owner, untracked. Use it to restore ownership after an\n * `await` or inside callbacks that outlive the synchronous run, so that effects, cleanups and\n * context reads inside `fn` attach to that owner. A disposed owner is ignored: `fn` then runs\n * without an owner, and development builds warn `RUN_WITH_DISPOSED_OWNER`.\n *\n * @param owner The owner to make current, usually captured with {@link getOwner}. `null` runs `fn`\n * without an owner.\n * @param fn The function to run.\n * @returns Whatever `fn` returns. An error thrown by `fn` propagates unchanged.\n * @example\n * import { createContext, getOwner, runWithOwner, useContext } from \"@shadow-js/core\";\n *\n * const Locale = createContext(\"en\");\n *\n * function Clock() {\n * const owner = getOwner();\n * queueMicrotask(() => {\n * const locale = runWithOwner(owner, () => useContext(Locale));\n * console.log(new Date().toLocaleTimeString(locale));\n * });\n * return null;\n * }\n * @see getOwner\n * @since 1.0.0\n */\nexport function runWithOwner<T>(owner: Owner | null, fn: () => T): T {\n let target = owner;\n if (target?.disposed) {\n warn(\"RUN_WITH_DISPOSED_OWNER\");\n target = null;\n }\n return runInScope({ owner: target, listener: null }, fn);\n}\n\n/**\n * Registers `fn` to run when the current owner is disposed or, for an effect or memo, before it\n * re-runs. Cleanups run newest first and untracked; one that throws does not stop the others, and\n * its error goes to the nearest error handler ({@link onError}, {@link catchError}). Outside any owner the call does nothing, because\n * nothing would ever run the cleanup; development builds warn `NO_OWNER_CLEANUP`.\n *\n * @param fn The cleanup to register.\n * @example\n * import { onCleanup } from \"@shadow-js/core\";\n *\n * function Ticker() {\n * const timer = setInterval(() => console.log(\"tick\"), 1000);\n * onCleanup(() => clearInterval(timer));\n * return null;\n * }\n * @see onMount\n * @since 1.0.0\n */\nexport function onCleanup(fn: Cleanup): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_CLEANUP\");\n return;\n }\n addCleanup(owner, fn);\n}\n\n/**\n * Registers an error handler on the current owner. It receives errors thrown in this owner's scope\n * (its effects, memos, cleanups and child owners) that no closer handler took. Handlers on the same\n * owner are tried newest first; a handler that throws passes its own error to the next handler up.\n * Outside any owner the call does nothing; development builds warn `NO_OWNER_ERROR`.\n *\n * @param handler Receives the error, untracked. Throw from it to pass an error on to the next handler.\n * @example\n * import { onError, useEffect } from \"@shadow-js/core\";\n *\n * function Dashboard() {\n * onError((error) => console.error(\"dashboard failed:\", error));\n * useEffect(() => {\n * throw new Error(\"widget crashed\"); // reaches the handler above\n * });\n * return null;\n * }\n * @see catchError\n * @since 1.0.0\n */\nexport function onError(handler: ErrorHandler): void {\n const owner = currentOwner();\n if (owner === null) {\n warn(\"NO_OWNER_ERROR\");\n return;\n }\n if (owner.errorHandlers === null) owner.errorHandlers = [handler];\n else owner.errorHandlers.push(handler);\n}\n\n/**\n * Runs `fn` inside a new child scope whose errors go to `handler`: errors thrown synchronously by\n * `fn`, and later errors of the effects, memos and cleanups it created. The scope is disposed with\n * the current owner. Use it to contain the failures of one part of a component tree.\n *\n * @param fn The function to run; it runs untracked, with the new scope as owner.\n * @param handler Receives each error, untracked. Throw from it to pass the error on to the next handler up.\n * @returns Whatever `fn` returns, or `undefined` when `fn` threw and `handler` took the error.\n * @throws Rethrows the error `handler` throws when no handler above takes it (outside a flush).\n * @example\n * import { catchError, useEffect } from \"@shadow-js/core\";\n *\n * function Widget() {\n * return catchError(\n * () => {\n * useEffect(() => {\n * throw new Error(\"network down\");\n * });\n * return \"ready\";\n * },\n * (error) => console.error(\"widget failed:\", error),\n * );\n * }\n * @see onError\n * @since 1.0.0\n */\nexport function catchError<T>(fn: () => T, handler: ErrorHandler): T | undefined {\n const scope = new Owner(currentOwner());\n scope.errorHandlers = [handler];\n try {\n return runWithOwner(scope, fn);\n } catch (error) {\n return void handleError(error, scope);\n }\n}\n\n/**\n * Returns an id that is identical on server and client for the same position in the owner tree.\n * The id uses only letters, digits, `-` and `_`, so it is valid in `id`, `for`, `aria-*` references\n * and in `querySelector(\"#\" + id)` without escaping. Use it to link a label to its input, or an\n * element to its `aria-describedby` target, in markup that is rendered on the server and hydrated.\n *\n * @returns A new id, unique within the root; each call on the same owner returns the next one.\n * @throws ShadowError `NO_OWNER_ID` when called outside any owner, because no stable id exists\n * there.\n * @example\n * import { useId } from \"@shadow-js/core\";\n *\n * function EmailField() {\n * const id = useId();\n * return (\n * <>\n * <label for={id}>Email</label>\n * <input id={id} type=\"email\" />\n * </>\n * );\n * }\n * @since 1.0.0\n */\nexport function useId(): string {\n const owner = currentOwner();\n if (owner === null) throw new ShadowError(\"NO_OWNER_ID\");\n // An owner with an id prefix (a component the renderer put in a hydration scope) hosts the ids of\n // everything below it: the prefix already encodes where the component is, and the owners between\n // here and there (effects exist in the browser, not on the server) must not leak into the id.\n for (let host: Owner | null = owner; host !== null; host = host.parent) {\n if (host.idPrefix === undefined) continue;\n const hosted = host.idCount;\n host.idCount += 1;\n return `s${host.idPrefix}${hosted}`;\n }\n const path: number[] = [];\n for (let node: Owner | null = owner; node !== null; node = node.parent) path.push(node.index);\n path.reverse();\n const sequence = owner.idCount;\n owner.idCount += 1;\n return `s${path.join(\"-\")}_${sequence}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAmCA,SAAgB,QAAW,IAAgB;CACzC,OAAO,WAAW,EAAE,UAAU,KAAK,GAAG,EAAE;AAC1C;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAgB,WAAc,IAAgC,SAA0B;CACtF,MAAM,WAAW,SAAS,aAAa;CACvC,MAAM,UAAU,aAAa;CAC7B,MAAM,OAAO,IAAI,MAAM,WAAW,OAAO,OAAO;CAChD,IAAI,UAAU,KAAK,UAAU,YAAY,OAAO,OAAO,QAAQ;CAC/D,IAAI;EACF,OAAO,WAAW;GAAE,OAAO;GAAM,UAAU;EAAK,SAAS,SAASA,YAAa,IAAI,CAAC,CAAC;CACvF,SAAS,OAAO;EACd,YAAa,IAAI;EACjB,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;;;;AAqBA,SAAgB,WAAyB;CACvC,OAAO,aAAa;AACtB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,aAAgB,OAAqB,IAAgB;CACnE,IAAI,SAAS;CACb,IAAI,QAAQ,UAAU;EACpB,KAAK,yBAAyB;EAC9B,SAAS;CACX;CACA,OAAO,WAAW;EAAE,OAAO;EAAQ,UAAU;CAAK,GAAG,EAAE;AACzD;;;;;;;;;;;;;;;;;;;AAoBA,SAAgB,UAAU,IAAmB;CAC3C,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM;EAClB,KAAK,kBAAkB;EACvB;CACF;CACA,WAAW,OAAO,EAAE;AACtB;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,QAAQ,SAA6B;CACnD,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM;EAClB,KAAK,gBAAgB;EACrB;CACF;CACA,IAAI,MAAM,kBAAkB,MAAM,MAAM,gBAAgB,CAAC,OAAO;MAC3D,MAAM,cAAc,KAAK,OAAO;AACvC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BA,SAAgB,WAAc,IAAa,SAAsC;CAC/E,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;CACtC,MAAM,gBAAgB,CAAC,OAAO;CAC9B,IAAI;EACF,OAAO,aAAa,OAAO,EAAE;CAC/B,SAAS,OAAO;EACP,YAAiB,OAAO,KAAK;EAApC;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,QAAgB;CAC9B,MAAM,QAAQ,aAAa;CAC3B,IAAI,UAAU,MAAM,MAAM,IAAI,YAAY,aAAa;CAIvD,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ;EACtE,IAAI,KAAK,aAAa,KAAA,GAAW;EACjC,MAAM,SAAS,KAAK;EACpB,KAAK,WAAW;EAChB,OAAO,IAAI,KAAK,WAAW;CAC7B;CACA,MAAM,OAAiB,CAAC;CACxB,KAAK,IAAI,OAAqB,OAAO,SAAS,MAAM,OAAO,KAAK,QAAQ,KAAK,KAAK,KAAK,KAAK;CAC5F,KAAK,QAAQ;CACb,MAAM,WAAW,MAAM;CACvB,MAAM,WAAW;CACjB,OAAO,IAAI,KAAK,KAAK,GAAG,EAAE,GAAG;AAC/B"}