@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,89 @@
1
+ import { handleError } from "./internal/owner.js";
2
+ import { batch } from "./internal/scheduler.js";
3
+ import { untrack } from "./ownership.js";
4
+ import { useSignal } from "./signal.js";
5
+ import { currentOwner } from "./extend/index.js";
6
+ // src/action.ts
7
+ function isPromiseLike(value) {
8
+ return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
9
+ }
10
+ /**
11
+ * A state machine for a form-style action: `dispatch(...args)` runs `action(previous, ...args)`,
12
+ * tracks whether it is pending, and commits its result. The ShadowJS form of React's
13
+ * `useActionState` (state, dispatch, pending). `previous` is the last committed state.
14
+ *
15
+ * Only the latest dispatch commits: when two actions overlap, a slower result that settles after a
16
+ * newer dispatch is discarded, so the screen never goes back to an older answer. A failure does not
17
+ * change the state; it clears `pending` and is sent to the owner's error handler (`onError`), so an
18
+ * error boundary can show it. Without an owner the returned promise rejects instead.
19
+ *
20
+ * @param action `(previous, ...args) => next`, synchronous or async. It runs untracked.
21
+ * @param initialState The state before the first dispatch.
22
+ * @returns `[state, dispatch, pending]`. A synchronous result commits at once; `pending` is true
23
+ * only while a returned promise is unsettled. `dispatch` returns a promise that settles when this
24
+ * call has finished, whether it committed or not.
25
+ * @throws Nothing synchronously. Without an owner, the promise returned by `dispatch` rejects with
26
+ * the action's error. With an owner, the error goes to its error handler, or is reported as an
27
+ * uncaught error (`reportError`) when no handler is registered above it.
28
+ * @example
29
+ * import { useAction } from "@shadow-js/core";
30
+ *
31
+ * const [message, send, sending] = useAction(async (_prev: string, text: string) => {
32
+ * await fetch("/api/messages", { method: "POST", body: text });
33
+ * return `sent: ${text}`;
34
+ * }, "");
35
+ * void send("hello");
36
+ * console.log(sending(), message());
37
+ * @see useOptimistic
38
+ * @see useTransition
39
+ * @since 1.0.0
40
+ */
41
+ function useAction(action, initialState) {
42
+ const owner = currentOwner();
43
+ const [state, setState] = useSignal(initialState);
44
+ const [pending, setPending] = useSignal(false);
45
+ let latest = 0;
46
+ const dispatch = (...args) => {
47
+ latest += 1;
48
+ const id = latest;
49
+ const previous = untrack(state);
50
+ const commit = (value) => {
51
+ if (id !== latest) return;
52
+ batch(() => {
53
+ setState(() => value);
54
+ setPending(false);
55
+ });
56
+ };
57
+ const fail = (error) => {
58
+ if (id !== latest) return;
59
+ setPending(false);
60
+ if (owner === null) throw error;
61
+ handleError(error, owner);
62
+ };
63
+ let result;
64
+ try {
65
+ result = untrack(() => action(previous, ...args));
66
+ } catch (error) {
67
+ if (owner === null) {
68
+ if (id === latest) setPending(false);
69
+ return Promise.reject(error);
70
+ }
71
+ fail(error);
72
+ return Promise.resolve();
73
+ }
74
+ if (!isPromiseLike(result)) {
75
+ commit(result);
76
+ return Promise.resolve();
77
+ }
78
+ setPending(true);
79
+ return Promise.resolve(result).then(commit, fail);
80
+ };
81
+ return [
82
+ state,
83
+ dispatch,
84
+ pending
85
+ ];
86
+ }
87
+ export { useAction };
88
+
89
+ //# sourceMappingURL=action.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action.js","names":[],"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":";;;;;;AAIA,SAAS,cAAiB,OAAyC;CACjE,OACE,UAAU,SACT,OAAO,UAAU,YAAY,OAAO,UAAU,eAC/C,OAAQ,MAA6B,SAAS;AAElD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,UACd,QACA,cAC2F;CAC3F,MAAM,QAAQ,aAAa;CAC3B,MAAM,CAAC,OAAO,YAAY,UAAa,YAAY;CACnD,MAAM,CAAC,SAAS,cAAc,UAAU,KAAK;CAC7C,IAAI,SAAS;CAEb,MAAM,YAAY,GAAG,SAA2B;EAC9C,UAAU;EACV,MAAM,KAAK;EACX,MAAM,WAAW,QAAQ,KAAK;EAC9B,MAAM,UAAU,UAAmB;GACjC,IAAI,OAAO,QAAQ;GACnB,YAAY;IACV,eAAe,KAAK;IACpB,WAAW,KAAK;GAClB,CAAC;EACH;EACA,MAAM,QAAQ,UAAyB;GACrC,IAAI,OAAO,QAAQ;GACnB,WAAW,KAAK;GAChB,IAAI,UAAU,MAAM,MAAM;GAC1B,YAAY,OAAO,KAAK;EAC1B;EACA,IAAI;EACJ,IAAI;GACF,SAAS,cAAc,OAAO,UAAU,GAAG,IAAI,CAAC;EAClD,SAAS,OAAO;GACd,IAAI,UAAU,MAAM;IAElB,IAAI,OAAO,QAAQ,WAAW,KAAK;IACnC,OAAO,QAAQ,OAAO,KAAK;GAC7B;GACA,KAAK,KAAK;GACV,OAAO,QAAQ,QAAQ;EACzB;EACA,IAAI,CAAC,cAAiB,MAAM,GAAG;GAC7B,OAAO,MAAM;GACb,OAAO,QAAQ,QAAQ;EACzB;EACA,WAAW,IAAI;EACf,OAAO,QAAQ,QAAQ,MAAM,CAAC,CAAC,KAAK,QAAQ,IAAI;CAClD;CACA,OAAO;EAAC;EAAO;EAAU;CAAO;AAClC"}
@@ -0,0 +1,33 @@
1
+ /** Options of {@link cache}. @since 1.0.0 */
2
+ export interface CacheOptions {
3
+ /**
4
+ * Most results kept per scope (one root); the oldest is dropped first. A positive integer.
5
+ * @default 100
6
+ */
7
+ limit?: number;
8
+ }
9
+ /**
10
+ * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
11
+ * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
12
+ * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
13
+ * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.
14
+ *
15
+ * Use it to share one data fetch between components rendered in the same request.
16
+ *
17
+ * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
18
+ * @param options Per-scope limit. Undefined uses the default.
19
+ * @returns A function with the same signature.
20
+ * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in
21
+ * production builds). The returned function rethrows what `fn` throws.
22
+ * @example
23
+ * import { cache } from "@shadow-js/core";
24
+ *
25
+ * const loadUser = cache((id: string) =>
26
+ * fetch(`/api/users/${id}`).then((response) => response.json()),
27
+ * );
28
+ * // Two components calling loadUser("u1") in the same render fetch once.
29
+ * @see useResource
30
+ * @since 1.0.0
31
+ */
32
+ export declare function cache<A extends unknown[], R>(fn: (...args: A) => R, options?: CacheOptions): (...args: A) => R;
33
+ //# sourceMappingURL=cache.d.ts.map
@@ -0,0 +1,61 @@
1
+ import { currentOwner } from "./extend/index.js";
2
+ // src/cache.ts
3
+ function sameArgs(a, b) {
4
+ if (a.length !== b.length) return false;
5
+ for (let i = 0; i < a.length; i += 1) if (!Object.is(a[i], b[i])) return false;
6
+ return true;
7
+ }
8
+ /** The outermost owner: the root of the render (a request on the server, the app on the client). */
9
+ function rootOf(owner) {
10
+ let root = owner;
11
+ while (root !== null && root.parent !== null) root = root.parent;
12
+ return root;
13
+ }
14
+ /**
15
+ * Memoizes `fn` per request: within one root (a server render, or the app on the client) the same
16
+ * arguments return the same result without calling `fn` again. Arguments compare with `Object.is`,
17
+ * position by position. Results are kept in a list bounded by `limit`; the oldest is dropped first.
18
+ * A call that throws is not kept. Outside any owner nothing is scoped, so `fn` runs every time.
19
+ *
20
+ * Use it to share one data fetch between components rendered in the same request.
21
+ *
22
+ * @param fn The function to memoize. Its result is kept as is, so a promise is shared, not awaited.
23
+ * @param options Per-scope limit. Undefined uses the default.
24
+ * @returns A function with the same signature.
25
+ * @throws RangeError when `limit` is not a positive integer (message code `SHADOW_CACHE_LIMIT` in
26
+ * production builds). The returned function rethrows what `fn` throws.
27
+ * @example
28
+ * import { cache } from "@shadow-js/core";
29
+ *
30
+ * const loadUser = cache((id: string) =>
31
+ * fetch(`/api/users/${id}`).then((response) => response.json()),
32
+ * );
33
+ * // Two components calling loadUser("u1") in the same render fetch once.
34
+ * @see useResource
35
+ * @since 1.0.0
36
+ */
37
+ function cache(fn, options) {
38
+ const limit = options?.limit ?? 100;
39
+ if (!Number.isInteger(limit) || limit < 1) throw new RangeError("cache: limit must be a positive integer");
40
+ const scopes = /* @__PURE__ */ new WeakMap();
41
+ return (...args) => {
42
+ const root = rootOf(currentOwner());
43
+ if (root === null) return fn(...args);
44
+ let entries = scopes.get(root);
45
+ if (entries === void 0) {
46
+ entries = [];
47
+ scopes.set(root, entries);
48
+ }
49
+ for (const entry of entries) if (sameArgs(entry.args, args)) return entry.value;
50
+ const value = fn(...args);
51
+ entries.push({
52
+ args,
53
+ value
54
+ });
55
+ if (entries.length > limit) entries.shift();
56
+ return value;
57
+ };
58
+ }
59
+ export { cache };
60
+
61
+ //# sourceMappingURL=cache.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cache.js","names":[],"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":";;AAgBA,SAAS,SAAS,GAAuB,GAAgC;CACvE,IAAI,EAAE,WAAW,EAAE,QAAQ,OAAO;CAClC,KAAK,IAAI,IAAI,GAAG,IAAI,EAAE,QAAQ,KAAK,GACjC,IAAI,CAAC,OAAO,GAAG,EAAE,IAAI,EAAE,EAAE,GAAG,OAAO;CAErC,OAAO;AACT;;AAGA,SAAS,OAAO,OAAmC;CACjD,IAAI,OAAO;CACX,OAAO,SAAS,QAAQ,KAAK,WAAW,MAAM,OAAO,KAAK;CAC1D,OAAO;AACT;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,SAAgB,MACd,IACA,SACmB;CACnB,MAAM,QAAQ,SAAS,SAAS;CAChC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,GACtC,MAAM,IAAI,WACE,yCACZ;CAEF,MAAM,yBAAS,IAAI,QAAwB;CAC3C,QAAQ,GAAG,SAAe;EACxB,MAAM,OAAO,OAAO,aAAa,CAAC;EAClC,IAAI,SAAS,MAAM,OAAO,GAAG,GAAG,IAAI;EACpC,IAAI,UAAU,OAAO,IAAI,IAAI;EAC7B,IAAI,YAAY,KAAA,GAAW;GACzB,UAAU,CAAC;GACX,OAAO,IAAI,MAAM,OAAO;EAC1B;EACA,KAAK,MAAM,SAAS,SAClB,IAAI,SAAS,MAAM,MAAM,IAAI,GAAG,OAAO,MAAM;EAE/C,MAAM,QAAQ,GAAG,GAAG,IAAI;EACxB,QAAQ,KAAK;GAAE;GAAM;EAAM,CAAC;EAC5B,IAAI,QAAQ,SAAS,OAAO,QAAQ,MAAM;EAC1C,OAAO;CACT;AACF"}
@@ -0,0 +1,104 @@
1
+ /**
2
+ * A context made by {@link createContext}: a value that a subtree receives from the nearest provider
3
+ * above it. The context is itself the provider component; `Provider` is the same function.
4
+ * @since 1.0.0
5
+ */
6
+ export interface Context<T> {
7
+ /**
8
+ * Renders `children` with `value` provided. The value is read once, when the provider is created;
9
+ * provide an accessor or a store for a value that changes. Returns an accessor of the children.
10
+ */
11
+ (props: {
12
+ value: T;
13
+ children?: unknown;
14
+ }): unknown;
15
+ /** The unique key the provided value is stored under, described by the context's `name`. */
16
+ readonly id: symbol;
17
+ /** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */
18
+ readonly defaultValue: T | undefined;
19
+ /** The same component, for code written as `<Ctx.Provider value={...}>`. */
20
+ readonly Provider: (props: {
21
+ value: T;
22
+ children?: unknown;
23
+ }) => unknown;
24
+ }
25
+ /**
26
+ * Options of {@link createContext}.
27
+ * @since 1.0.0
28
+ */
29
+ export interface ContextOptions {
30
+ /**
31
+ * Label shown in diagnostics and used as the description of the context's `id` symbol.
32
+ * @default "context"
33
+ */
34
+ name?: string;
35
+ }
36
+ /**
37
+ * Creates a context: a value that components read with {@link useContext} without passing it
38
+ * through props. Render the returned component around a subtree to provide a value. The value is
39
+ * read once; pass a signal accessor or a store to provide something reactive. On the server the
40
+ * provider builds its subtree once.
41
+ *
42
+ * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
43
+ * (or omitted) means the context has no default, so reading it without a provider throws.
44
+ * @param options A diagnostics name. Undefined uses the default.
45
+ * @returns The context, which is also its provider component.
46
+ * @example
47
+ * import { createContext, useContext } from "@shadow-js/core";
48
+ *
49
+ * const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
50
+ *
51
+ * function Label() {
52
+ * return <p>Theme: {useContext(Theme)}</p>;
53
+ * }
54
+ *
55
+ * const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
56
+ * @see useContext
57
+ * @since 1.0.0
58
+ */
59
+ export declare function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T>;
60
+ /**
61
+ * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
62
+ * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
63
+ * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
64
+ * child owner of the current owner that is disposed with it.
65
+ *
66
+ * @param context The context to provide.
67
+ * @param value The value `useContext(context)` returns inside `fn`.
68
+ * @param fn Runs once, synchronously.
69
+ * @returns What `fn` returns.
70
+ * @example
71
+ * import { createContext, useContext } from "@shadow-js/core";
72
+ * import { runWithContext } from "@shadow-js/core/extend";
73
+ *
74
+ * const Theme = createContext("light");
75
+ * const theme = runWithContext(Theme, "dark", () => useContext(Theme));
76
+ * console.log(theme); // "dark"
77
+ * @see createContext
78
+ * @since 1.0.0
79
+ */
80
+ export declare function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R;
81
+ /**
82
+ * Reads the nearest provided value of `context`. Falls back to its default; throws when there is
83
+ * neither a provider nor a default, because no correct value exists. The lookup follows the current
84
+ * owner, so call it while a component runs (or in an effect or memo it creates), not after an
85
+ * `await` or in an event handler. The read is not tracked.
86
+ *
87
+ * @param context A context made by {@link createContext}.
88
+ * @returns The value of the nearest provider above the current owner, else the default value.
89
+ * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
90
+ * context's default is `undefined`.
91
+ * @example
92
+ * import { createContext, useContext } from "@shadow-js/core";
93
+ *
94
+ * const User = createContext<{ name: string }>();
95
+ *
96
+ * function Greeting() {
97
+ * const user = useContext(User); // throws CONTEXT_MISSING without a provider
98
+ * return <p>Hello, {user.name}</p>;
99
+ * }
100
+ * @see createContext
101
+ * @since 1.0.0
102
+ */
103
+ export declare function useContext<T>(context: Context<T>): T;
104
+ //# sourceMappingURL=context.d.ts.map
@@ -0,0 +1,110 @@
1
+ import { ShadowError } from "./internal/diagnostics.js";
2
+ import { Owner } from "./internal/owner.js";
3
+ import { runWithOwner } from "./ownership.js";
4
+ import { useRenderEffect } from "./effect.js";
5
+ import { useSignal } from "./signal.js";
6
+ import { currentOwner } from "./extend/index.js";
7
+ // src/context.ts
8
+ /**
9
+ * Creates a context: a value that components read with {@link useContext} without passing it
10
+ * through props. Render the returned component around a subtree to provide a value. The value is
11
+ * read once; pass a signal accessor or a store to provide something reactive. On the server the
12
+ * provider builds its subtree once.
13
+ *
14
+ * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined
15
+ * (or omitted) means the context has no default, so reading it without a provider throws.
16
+ * @param options A diagnostics name. Undefined uses the default.
17
+ * @returns The context, which is also its provider component.
18
+ * @example
19
+ * import { createContext, useContext } from "@shadow-js/core";
20
+ *
21
+ * const Theme = createContext<"light" | "dark">("light", { name: "Theme" });
22
+ *
23
+ * function Label() {
24
+ * return <p>Theme: {useContext(Theme)}</p>;
25
+ * }
26
+ *
27
+ * const app = <Theme.Provider value="dark"><Label /></Theme.Provider>;
28
+ * @see useContext
29
+ * @since 1.0.0
30
+ */
31
+ function createContext(defaultValue, options) {
32
+ const id = Symbol(options?.name ?? "context");
33
+ const provider = (props) => {
34
+ const scope = new Owner(currentOwner());
35
+ const inherited = scope.context;
36
+ const next = Object.create(inherited);
37
+ next[id] = props.value;
38
+ scope.context = next;
39
+ return runWithOwner(scope, () => {
40
+ const [children, setChildren] = useSignal(void 0, { equals: false });
41
+ useRenderEffect(() => props.children, (value) => {
42
+ setChildren(() => value);
43
+ });
44
+ return children;
45
+ });
46
+ };
47
+ return Object.assign(provider, {
48
+ id,
49
+ defaultValue,
50
+ Provider: provider
51
+ });
52
+ }
53
+ /**
54
+ * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the
55
+ * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer
56
+ * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new
57
+ * child owner of the current owner that is disposed with it.
58
+ *
59
+ * @param context The context to provide.
60
+ * @param value The value `useContext(context)` returns inside `fn`.
61
+ * @param fn Runs once, synchronously.
62
+ * @returns What `fn` returns.
63
+ * @example
64
+ * import { createContext, useContext } from "@shadow-js/core";
65
+ * import { runWithContext } from "@shadow-js/core/extend";
66
+ *
67
+ * const Theme = createContext("light");
68
+ * const theme = runWithContext(Theme, "dark", () => useContext(Theme));
69
+ * console.log(theme); // "dark"
70
+ * @see createContext
71
+ * @since 1.0.0
72
+ */
73
+ function runWithContext(context, value, fn) {
74
+ const scope = new Owner(currentOwner());
75
+ const next = Object.create(scope.context);
76
+ next[context.id] = value;
77
+ scope.context = next;
78
+ return runWithOwner(scope, fn);
79
+ }
80
+ /**
81
+ * Reads the nearest provided value of `context`. Falls back to its default; throws when there is
82
+ * neither a provider nor a default, because no correct value exists. The lookup follows the current
83
+ * owner, so call it while a component runs (or in an effect or memo it creates), not after an
84
+ * `await` or in an event handler. The read is not tracked.
85
+ *
86
+ * @param context A context made by {@link createContext}.
87
+ * @returns The value of the nearest provider above the current owner, else the default value.
88
+ * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the
89
+ * context's default is `undefined`.
90
+ * @example
91
+ * import { createContext, useContext } from "@shadow-js/core";
92
+ *
93
+ * const User = createContext<{ name: string }>();
94
+ *
95
+ * function Greeting() {
96
+ * const user = useContext(User); // throws CONTEXT_MISSING without a provider
97
+ * return <p>Hello, {user.name}</p>;
98
+ * }
99
+ * @see createContext
100
+ * @since 1.0.0
101
+ */
102
+ function useContext(context) {
103
+ const map = currentOwner()?.context;
104
+ if (map !== null && map !== void 0 && context.id in map) return map[context.id];
105
+ if (context.defaultValue === void 0) throw new ShadowError("CONTEXT_MISSING");
106
+ return context.defaultValue;
107
+ }
108
+ export { createContext, runWithContext, useContext };
109
+
110
+ //# sourceMappingURL=context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"context.js","names":[],"sources":["../../src/context.ts"],"sourcesContent":["import { useRenderEffect } from \"./effect\";\nimport { currentOwner, Owner, ShadowError } from \"./extend\";\nimport { runWithOwner } from \"./ownership\";\nimport { useSignal } from \"./signal\";\n\n/**\n * A context made by {@link createContext}: a value that a subtree receives from the nearest provider\n * above it. The context is itself the provider component; `Provider` is the same function.\n * @since 1.0.0\n */\nexport interface Context<T> {\n /**\n * Renders `children` with `value` provided. The value is read once, when the provider is created;\n * provide an accessor or a store for a value that changes. Returns an accessor of the children.\n */\n (props: { value: T; children?: unknown }): unknown;\n /** The unique key the provided value is stored under, described by the context's `name`. */\n readonly id: symbol;\n /** The value {@link useContext} returns without a provider. `undefined` means none: it throws. */\n readonly defaultValue: T | undefined;\n /** The same component, for code written as `<Ctx.Provider value={...}>`. */\n readonly Provider: (props: { value: T; children?: unknown }) => unknown;\n}\n\n/**\n * Options of {@link createContext}.\n * @since 1.0.0\n */\nexport interface ContextOptions {\n /**\n * Label shown in diagnostics and used as the description of the context's `id` symbol.\n * @default \"context\"\n */\n name?: string;\n}\n\n/**\n * Creates a context: a value that components read with {@link useContext} without passing it\n * through props. Render the returned component around a subtree to provide a value. The value is\n * read once; pass a signal accessor or a store to provide something reactive. On the server the\n * provider builds its subtree once.\n *\n * @param defaultValue Returned by `useContext` when no provider is above the reader. Undefined\n * (or omitted) means the context has no default, so reading it without a provider throws.\n * @param options A diagnostics name. Undefined uses the default.\n * @returns The context, which is also its provider component.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const Theme = createContext<\"light\" | \"dark\">(\"light\", { name: \"Theme\" });\n *\n * function Label() {\n * return <p>Theme: {useContext(Theme)}</p>;\n * }\n *\n * const app = <Theme.Provider value=\"dark\"><Label /></Theme.Provider>;\n * @see useContext\n * @since 1.0.0\n */\nexport function createContext<T>(defaultValue?: T, options?: ContextOptions): Context<T> {\n const id = Symbol(options?.name ?? \"context\");\n const provider = (props: { value: T; children?: unknown }): unknown => {\n const scope = new Owner(currentOwner());\n const inherited = scope.context;\n const next = Object.create(inherited) as Record<symbol, unknown>;\n next[id] = props.value;\n scope.context = next;\n // A render effect, so a children expression that reads signals stays reactive and still sees\n // the provided value. An effect (not a memo) because component setup may legitimately write\n // signals, and errors thrown while building the subtree must reach the error boundaries.\n return runWithOwner(scope, () => {\n if (__SERVER__) {\n // Nothing is reactive on the server: build the subtree once.\n const built = props.children;\n return () => built;\n }\n const [children, setChildren] = useSignal<unknown>(undefined, { equals: false });\n useRenderEffect(\n () => props.children,\n (value) => {\n setChildren(() => value);\n },\n );\n return children;\n });\n };\n return Object.assign(provider, { id, defaultValue, Provider: provider }) as Context<T>;\n}\n\n/**\n * Runs `fn` with `value` provided for `context` (as a Provider does), without a render effect: the\n * value is set for the duration of `fn` only, and what `fn` creates sees it. Used where a renderer\n * builds a subtree that must not be re-run by a Provider's effect. `fn` runs untracked, in a new\n * child owner of the current owner that is disposed with it.\n *\n * @param context The context to provide.\n * @param value The value `useContext(context)` returns inside `fn`.\n * @param fn Runs once, synchronously.\n * @returns What `fn` returns.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n * import { runWithContext } from \"@shadow-js/core/extend\";\n *\n * const Theme = createContext(\"light\");\n * const theme = runWithContext(Theme, \"dark\", () => useContext(Theme));\n * console.log(theme); // \"dark\"\n * @see createContext\n * @since 1.0.0\n */\nexport function runWithContext<T, R>(context: Context<T>, value: T, fn: () => R): R {\n const scope = new Owner(currentOwner());\n const next = Object.create(scope.context) as Record<symbol, unknown>;\n next[context.id] = value;\n scope.context = next;\n return runWithOwner(scope, fn);\n}\n\n/**\n * Reads the nearest provided value of `context`. Falls back to its default; throws when there is\n * neither a provider nor a default, because no correct value exists. The lookup follows the current\n * owner, so call it while a component runs (or in an effect or memo it creates), not after an\n * `await` or in an event handler. The read is not tracked.\n *\n * @param context A context made by {@link createContext}.\n * @returns The value of the nearest provider above the current owner, else the default value.\n * @throws ShadowError `CONTEXT_MISSING` when no provider is above the current owner and the\n * context's default is `undefined`.\n * @example\n * import { createContext, useContext } from \"@shadow-js/core\";\n *\n * const User = createContext<{ name: string }>();\n *\n * function Greeting() {\n * const user = useContext(User); // throws CONTEXT_MISSING without a provider\n * return <p>Hello, {user.name}</p>;\n * }\n * @see createContext\n * @since 1.0.0\n */\nexport function useContext<T>(context: Context<T>): T {\n const map = currentOwner()?.context;\n if (map !== null && map !== undefined && context.id in map) return map[context.id] as T;\n if (context.defaultValue === undefined) throw new ShadowError(\"CONTEXT_MISSING\");\n return context.defaultValue;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2DA,SAAgB,cAAiB,cAAkB,SAAsC;CACvF,MAAM,KAAK,OAAO,SAAS,QAAQ,SAAS;CAC5C,MAAM,YAAY,UAAqD;EACrE,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;EACtC,MAAM,YAAY,MAAM;EACxB,MAAM,OAAO,OAAO,OAAO,SAAS;EACpC,KAAK,MAAM,MAAM;EACjB,MAAM,UAAU;EAIhB,OAAO,aAAa,aAAa;GAM/B,MAAM,CAAC,UAAU,eAAe,UAAmB,KAAA,GAAW,EAAE,QAAQ,MAAM,CAAC;GAC/E,sBACQ,MAAM,WACX,UAAU;IACT,kBAAkB,KAAK;GACzB,CACF;GACA,OAAO;EACT,CAAC;CACH;CACA,OAAO,OAAO,OAAO,UAAU;EAAE;EAAI;EAAc,UAAU;CAAS,CAAC;AACzE;;;;;;;;;;;;;;;;;;;;;AAsBA,SAAgB,eAAqB,SAAqB,OAAU,IAAgB;CAClF,MAAM,QAAQ,IAAI,MAAM,aAAa,CAAC;CACtC,MAAM,OAAO,OAAO,OAAO,MAAM,OAAO;CACxC,KAAK,QAAQ,MAAM;CACnB,MAAM,UAAU;CAChB,OAAO,aAAa,OAAO,EAAE;AAC/B;;;;;;;;;;;;;;;;;;;;;;;AAwBA,SAAgB,WAAc,SAAwB;CACpD,MAAM,MAAM,aAAa,CAAC,EAAE;CAC5B,IAAI,QAAQ,QAAQ,QAAQ,KAAA,KAAa,QAAQ,MAAM,KAAK,OAAO,IAAI,QAAQ;CAC/E,IAAI,QAAQ,iBAAiB,KAAA,GAAW,MAAM,IAAI,YAAY,iBAAiB;CAC/E,OAAO,QAAQ;AACjB"}
@@ -0,0 +1,120 @@
1
+ import { Cleanup } from "./internal/types.js";
2
+ /**
3
+ * Options of {@link useEffect} in its tracking form `useEffect(fn, options)`.
4
+ * @since 1.0.0
5
+ */
6
+ export interface EffectOptions {
7
+ /**
8
+ * Label shown by devtools and diagnostics.
9
+ * @default undefined (the effect is unnamed)
10
+ */
11
+ name?: string;
12
+ }
13
+ /**
14
+ * Options of {@link useEffect} in its explicit-dependency form `useEffect(deps, fn, options)`.
15
+ * @since 1.0.0
16
+ */
17
+ export interface DeferredEffectOptions extends EffectOptions {
18
+ /**
19
+ * Skip the first call of `fn`: `deps` is still read (and tracked) on the first run, but `fn` only
20
+ * runs for later changes of it.
21
+ * @default false
22
+ */
23
+ defer?: boolean;
24
+ }
25
+ /**
26
+ * Runs a side effect after rendering and again whenever a tracked signal changes. The first run
27
+ * is deferred to the next flush. Effects never run on the server. Inside a `<Suspense>` boundary
28
+ * that is still showing its fallback, the first run waits until the boundary first shows its content.
29
+ *
30
+ * Two forms: `useEffect(fn)` tracks everything `fn` reads; `useEffect(deps, fn)` tracks only
31
+ * `deps` and runs `fn` untracked. Return a function to clean up before the next run or disposal.
32
+ * An error thrown by the effect goes to the owner's error handler (`onError`, an error boundary).
33
+ * In development, an effect created outside any owner warns `NO_OWNER_EFFECT`: it still runs, but
34
+ * nothing can dispose it.
35
+ *
36
+ * @param fn The effect. Every signal it reads is tracked. It may return a cleanup function.
37
+ * @param options A devtools name. Undefined uses the default.
38
+ * @example
39
+ * import { useEffect, useSignal } from "@shadow-js/core";
40
+ *
41
+ * function PageTitle(props: { unread: number }) {
42
+ * const [title] = useSignal("Inbox");
43
+ * useEffect(() => {
44
+ * document.title = `${title()} (${props.unread})`; // re-runs when either changes
45
+ * });
46
+ * return null;
47
+ * }
48
+ * @see useRenderEffect
49
+ * @see onMount
50
+ * @since 1.0.0
51
+ */
52
+ export declare function useEffect(fn: () => void | Cleanup, options?: EffectOptions): void;
53
+ /**
54
+ * Explicit-dependency form of {@link useEffect}: tracks only what `deps` reads, and calls `fn`
55
+ * untracked with the new and the previous value of `deps`. Use it when the effect body reads
56
+ * signals that must not re-run it.
57
+ *
58
+ * @param deps Tracked; its result is passed to `fn`.
59
+ * @param fn Untracked; receives the value of `deps` and its previous value (`undefined` when there
60
+ * is none yet). It may return a cleanup function, which runs before the next call or on disposal.
61
+ * @param options `defer` skips the first call; a devtools name. Undefined uses the defaults.
62
+ * @example
63
+ * import { useEffect } from "@shadow-js/core";
64
+ *
65
+ * function Profile(props: { userId: string }) {
66
+ * useEffect(
67
+ * () => props.userId,
68
+ * (next, previous) => console.log(`switched from ${previous} to ${next}`),
69
+ * { defer: true }, // not called for the first id
70
+ * );
71
+ * return null;
72
+ * }
73
+ * @see useEffect
74
+ * @since 1.0.0
75
+ */
76
+ export declare function useEffect<T>(deps: () => T, fn: (value: T, previous: T | undefined) => void | Cleanup, options?: DeferredEffectOptions): void;
77
+ /**
78
+ * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
79
+ * before user effects on every flush. Used for DOM bindings; application code rarely needs it.
80
+ * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
81
+ * development, one created outside any owner warns `NO_OWNER_EFFECT`.
82
+ *
83
+ * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
84
+ * and may return a cleanup function.
85
+ * @param apply Untracked; receives the value and the previous value (`undefined` on the first
86
+ * run), and may return a cleanup function. Undefined: only `compute` runs.
87
+ * @example
88
+ * import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
89
+ *
90
+ * const button = document.createElement("button");
91
+ * createRoot(() => {
92
+ * const [label] = useSignal("Save");
93
+ * useRenderEffect(label, (text) => {
94
+ * button.textContent = text; // runs now, and again when label changes
95
+ * });
96
+ * });
97
+ * @see useEffect
98
+ * @since 1.0.0
99
+ */
100
+ export declare function useRenderEffect<T>(compute: () => T, apply?: (value: T, previous: T | undefined) => void | Cleanup): void;
101
+ /**
102
+ * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
103
+ * run it again. Its return value, if a function, is the cleanup, which runs when the owner is
104
+ * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
105
+ * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
106
+ *
107
+ * @param fn Runs once, untracked. It may return a cleanup function.
108
+ * @example
109
+ * import { onMount } from "@shadow-js/core";
110
+ *
111
+ * function SearchBox() {
112
+ * let input: HTMLInputElement | undefined;
113
+ * onMount(() => input?.focus());
114
+ * return <input ref={(el: HTMLInputElement) => (input = el)} />;
115
+ * }
116
+ * @see useEffect
117
+ * @since 1.0.0
118
+ */
119
+ export declare function onMount(fn: () => void | Cleanup): void;
120
+ //# sourceMappingURL=effect.d.ts.map
@@ -0,0 +1,110 @@
1
+ import { warn } from "./internal/diagnostics.js";
2
+ import { untrack } from "./ownership.js";
3
+ import { createComputation, currentOwner } from "./extend/index.js";
4
+ // src/effect.ts
5
+ /** What a held effect computes while its gate is closed: nothing for `apply` to act on. */
6
+ const HELD = Symbol("held");
7
+ /** The nearest gate above the current owner (see `Owner.gate`), or null. */
8
+ function nearestGate() {
9
+ for (let owner = currentOwner(); owner !== null; owner = owner.parent) if (owner.gate !== null) return owner.gate;
10
+ return null;
11
+ }
12
+ function createEffect(fnIn, applyIn, render, deferIn, name) {
13
+ if (currentOwner() === null) warn("NO_OWNER_EFFECT");
14
+ let fn = fnIn;
15
+ let apply = applyIn;
16
+ let defer = deferIn;
17
+ const gate = render ? null : nearestGate();
18
+ if (gate !== null) {
19
+ let opened = false;
20
+ const held = () => {
21
+ if (opened) return false;
22
+ if (gate()) return true;
23
+ opened = true;
24
+ return false;
25
+ };
26
+ if (apply === null) {
27
+ const inner = fn;
28
+ fn = (previous) => held() ? void 0 : inner(previous);
29
+ } else {
30
+ const innerFn = fn;
31
+ const innerApply = apply;
32
+ let skipFirst = defer;
33
+ defer = false;
34
+ fn = (previous) => held() ? HELD : innerFn(previous);
35
+ apply = (value, previous) => {
36
+ if (value === HELD) return void 0;
37
+ if (skipFirst) {
38
+ skipFirst = false;
39
+ return;
40
+ }
41
+ return innerApply(value, previous === HELD ? void 0 : previous);
42
+ };
43
+ }
44
+ }
45
+ createComputation({
46
+ kind: "effect",
47
+ fn,
48
+ render,
49
+ defer,
50
+ ...apply === null ? {} : { apply },
51
+ ...name === void 0 ? {} : { name }
52
+ });
53
+ }
54
+ function useEffect(first, second, third) {
55
+ if (typeof second === "function") createEffect(first, second, false, third?.defer === true, third?.name);
56
+ else {
57
+ if (Array.isArray(second)) warn("EFFECT_DEPS_IGNORED");
58
+ createEffect(first, null, false, false, second?.name);
59
+ }
60
+ }
61
+ /**
62
+ * Like {@link useEffect} but belongs to the render phase: it runs synchronously when created and
63
+ * before user effects on every flush. Used for DOM bindings; application code rarely needs it.
64
+ * It is not held by a pending `<Suspense>` boundary, and it never runs on the server. In
65
+ * development, one created outside any owner warns `NO_OWNER_EFFECT`.
66
+ *
67
+ * @param compute Tracked; its result is passed to `apply`. Without `apply`, it is the effect itself
68
+ * and may return a cleanup function.
69
+ * @param apply Untracked; receives the value and the previous value (`undefined` on the first
70
+ * run), and may return a cleanup function. Undefined: only `compute` runs.
71
+ * @example
72
+ * import { createRoot, useRenderEffect, useSignal } from "@shadow-js/core";
73
+ *
74
+ * const button = document.createElement("button");
75
+ * createRoot(() => {
76
+ * const [label] = useSignal("Save");
77
+ * useRenderEffect(label, (text) => {
78
+ * button.textContent = text; // runs now, and again when label changes
79
+ * });
80
+ * });
81
+ * @see useEffect
82
+ * @since 1.0.0
83
+ */
84
+ function useRenderEffect(compute, apply) {
85
+ createEffect(compute, apply ?? null, true, false, void 0);
86
+ }
87
+ /**
88
+ * Runs `fn` once after the owner has been created and flushed, untracked, so signal changes never
89
+ * run it again. Its return value, if a function, is the cleanup, which runs when the owner is
90
+ * disposed. Never runs on the server. Like {@link useEffect}, it waits for a pending `<Suspense>`
91
+ * boundary to show its content, and warns `NO_OWNER_EFFECT` in development outside any owner.
92
+ *
93
+ * @param fn Runs once, untracked. It may return a cleanup function.
94
+ * @example
95
+ * import { onMount } from "@shadow-js/core";
96
+ *
97
+ * function SearchBox() {
98
+ * let input: HTMLInputElement | undefined;
99
+ * onMount(() => input?.focus());
100
+ * return <input ref={(el: HTMLInputElement) => (input = el)} />;
101
+ * }
102
+ * @see useEffect
103
+ * @since 1.0.0
104
+ */
105
+ function onMount(fn) {
106
+ createEffect(() => untrack(fn), null, false, false, "onMount");
107
+ }
108
+ export { onMount, useEffect, useRenderEffect };
109
+
110
+ //# sourceMappingURL=effect.js.map