@playfast/reform 0.0.7 → 0.0.8

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 (237) hide show
  1. package/package.json +2 -2
  2. package/src/boundary/boundary.test.ts +301 -0
  3. package/src/boundary/boundary.ts +192 -0
  4. package/src/calc/asyncCalc.test.ts +556 -0
  5. package/src/calc/asyncCalc.ts +267 -0
  6. package/src/calc/asyncData.ts +96 -0
  7. package/src/calc/calc.test.ts +287 -0
  8. package/src/calc/calc.ts +120 -0
  9. package/src/calc/calcFamily.test.ts +206 -0
  10. package/src/calc/calcFamily.ts +194 -0
  11. package/src/calc/compose.test.ts +68 -0
  12. package/src/calc/compose.ts +69 -0
  13. package/src/channel/channel.ts +269 -0
  14. package/src/compose/composition.ts +112 -0
  15. package/{dist/compose/host.d.ts → src/compose/host.ts} +9 -8
  16. package/{dist/compose/props.js → src/compose/props.ts} +7 -5
  17. package/src/compose/provide.ts +70 -0
  18. package/{dist/compose/slot.d.ts → src/compose/slot.ts} +36 -19
  19. package/src/compose/ui.test.ts +62 -0
  20. package/src/compose/ui.ts +226 -0
  21. package/src/compose/ui.typecheck.ts +56 -0
  22. package/src/definition/definition.ts +76 -0
  23. package/src/event/event.test.ts +23 -0
  24. package/src/event/event.ts +65 -0
  25. package/src/event/eventGroup.ts +14 -0
  26. package/src/feature/feature.mount.test.ts +82 -0
  27. package/src/feature/feature.test.ts +60 -0
  28. package/{dist/feature/feature.d.ts → src/feature/feature.ts} +178 -92
  29. package/src/feature/feature.typecheck.ts +108 -0
  30. package/src/index.ts +176 -0
  31. package/{dist/internal/capture.d.ts → src/internal/capture.ts} +13 -11
  32. package/{dist/internal/ctx.d.ts → src/internal/ctx.ts} +8 -4
  33. package/src/internal/errors.test.ts +33 -0
  34. package/src/internal/errors.ts +145 -0
  35. package/src/internal/inspect.test.ts +28 -0
  36. package/src/internal/inspect.ts +34 -0
  37. package/src/internal/queryDriver.ts +247 -0
  38. package/src/internal/reuse.test.ts +116 -0
  39. package/src/internal/reuse.ts +73 -0
  40. package/src/internal/scheduler.ts +93 -0
  41. package/{dist/internal/seeds.d.ts → src/internal/seeds.ts} +6 -3
  42. package/src/internal/sources.ts +104 -0
  43. package/{dist/internal/stateRegistry.js → src/internal/stateRegistry.ts} +18 -14
  44. package/src/internal/store.test.ts +80 -0
  45. package/src/internal/store.ts +105 -0
  46. package/{dist/internal/track.d.ts → src/internal/track.ts} +17 -11
  47. package/src/procedure/procedure.ts +89 -0
  48. package/src/reducer/reducer.ts +137 -0
  49. package/src/remote/remoteState.test.ts +695 -0
  50. package/src/remote/remoteState.ts +571 -0
  51. package/src/remote/remoteState.typecheck.ts +195 -0
  52. package/src/runtime/bus.ts +40 -0
  53. package/src/runtime/hardening.test.ts +69 -0
  54. package/src/runtime/loop.test.ts +178 -0
  55. package/src/runtime/loop.ts +171 -0
  56. package/src/scene/scene.ts +76 -0
  57. package/src/scene/seedScene.test.ts +169 -0
  58. package/src/state/state.ts +94 -0
  59. package/src/state/stateFamily.test.ts +138 -0
  60. package/src/state/stateFamily.ts +174 -0
  61. package/src/state/stateGroup.ts +105 -0
  62. package/{dist/state/token.d.ts → src/state/token.ts} +22 -13
  63. package/src/synced/syncedStore.ts +99 -0
  64. package/{dist/ui/node.d.ts → src/ui/node.ts} +3 -3
  65. package/{dist/ui/trigger.d.ts → src/ui/trigger.ts} +1 -2
  66. package/src/wire/tree.test.ts +81 -0
  67. package/src/wire/tree.ts +129 -0
  68. package/src/wire/triggers.test.ts +76 -0
  69. package/src/wire/triggers.ts +98 -0
  70. package/dist/boundary/boundary.d.ts +0 -72
  71. package/dist/boundary/boundary.d.ts.map +0 -1
  72. package/dist/boundary/boundary.js +0 -83
  73. package/dist/boundary/boundary.js.map +0 -1
  74. package/dist/calc/asyncCalc.d.ts +0 -91
  75. package/dist/calc/asyncCalc.d.ts.map +0 -1
  76. package/dist/calc/asyncCalc.js +0 -95
  77. package/dist/calc/asyncCalc.js.map +0 -1
  78. package/dist/calc/asyncData.d.ts +0 -57
  79. package/dist/calc/asyncData.d.ts.map +0 -1
  80. package/dist/calc/asyncData.js +0 -34
  81. package/dist/calc/asyncData.js.map +0 -1
  82. package/dist/calc/calc.d.ts +0 -57
  83. package/dist/calc/calc.d.ts.map +0 -1
  84. package/dist/calc/calc.js +0 -58
  85. package/dist/calc/calc.js.map +0 -1
  86. package/dist/calc/calcFamily.d.ts +0 -57
  87. package/dist/calc/calcFamily.d.ts.map +0 -1
  88. package/dist/calc/calcFamily.js +0 -124
  89. package/dist/calc/calcFamily.js.map +0 -1
  90. package/dist/calc/compose.d.ts +0 -16
  91. package/dist/calc/compose.d.ts.map +0 -1
  92. package/dist/calc/compose.js +0 -7
  93. package/dist/calc/compose.js.map +0 -1
  94. package/dist/channel/channel.d.ts +0 -115
  95. package/dist/channel/channel.d.ts.map +0 -1
  96. package/dist/channel/channel.js +0 -138
  97. package/dist/channel/channel.js.map +0 -1
  98. package/dist/compose/composition.d.ts +0 -72
  99. package/dist/compose/composition.d.ts.map +0 -1
  100. package/dist/compose/composition.js +0 -46
  101. package/dist/compose/composition.js.map +0 -1
  102. package/dist/compose/host.d.ts.map +0 -1
  103. package/dist/compose/host.js +0 -6
  104. package/dist/compose/host.js.map +0 -1
  105. package/dist/compose/props.d.ts +0 -13
  106. package/dist/compose/props.d.ts.map +0 -1
  107. package/dist/compose/props.js.map +0 -1
  108. package/dist/compose/provide.d.ts +0 -22
  109. package/dist/compose/provide.d.ts.map +0 -1
  110. package/dist/compose/provide.js +0 -28
  111. package/dist/compose/provide.js.map +0 -1
  112. package/dist/compose/slot.d.ts.map +0 -1
  113. package/dist/compose/slot.js +0 -23
  114. package/dist/compose/slot.js.map +0 -1
  115. package/dist/compose/ui.d.ts +0 -135
  116. package/dist/compose/ui.d.ts.map +0 -1
  117. package/dist/compose/ui.js +0 -63
  118. package/dist/compose/ui.js.map +0 -1
  119. package/dist/definition/definition.d.ts +0 -33
  120. package/dist/definition/definition.d.ts.map +0 -1
  121. package/dist/definition/definition.js +0 -42
  122. package/dist/definition/definition.js.map +0 -1
  123. package/dist/event/event.d.ts +0 -33
  124. package/dist/event/event.d.ts.map +0 -1
  125. package/dist/event/event.js +0 -30
  126. package/dist/event/event.js.map +0 -1
  127. package/dist/event/eventGroup.d.ts +0 -9
  128. package/dist/event/eventGroup.d.ts.map +0 -1
  129. package/dist/event/eventGroup.js +0 -4
  130. package/dist/event/eventGroup.js.map +0 -1
  131. package/dist/feature/feature.d.ts.map +0 -1
  132. package/dist/feature/feature.js +0 -98
  133. package/dist/feature/feature.js.map +0 -1
  134. package/dist/index.d.ts +0 -53
  135. package/dist/index.d.ts.map +0 -1
  136. package/dist/index.js +0 -62
  137. package/dist/index.js.map +0 -1
  138. package/dist/internal/capture.d.ts.map +0 -1
  139. package/dist/internal/capture.js +0 -12
  140. package/dist/internal/capture.js.map +0 -1
  141. package/dist/internal/ctx.d.ts.map +0 -1
  142. package/dist/internal/ctx.js +0 -2
  143. package/dist/internal/ctx.js.map +0 -1
  144. package/dist/internal/errors.d.ts +0 -89
  145. package/dist/internal/errors.d.ts.map +0 -1
  146. package/dist/internal/errors.js +0 -102
  147. package/dist/internal/errors.js.map +0 -1
  148. package/dist/internal/inspect.d.ts +0 -17
  149. package/dist/internal/inspect.d.ts.map +0 -1
  150. package/dist/internal/inspect.js +0 -32
  151. package/dist/internal/inspect.js.map +0 -1
  152. package/dist/internal/queryDriver.d.ts +0 -65
  153. package/dist/internal/queryDriver.d.ts.map +0 -1
  154. package/dist/internal/queryDriver.js +0 -134
  155. package/dist/internal/queryDriver.js.map +0 -1
  156. package/dist/internal/reuse.d.ts +0 -10
  157. package/dist/internal/reuse.d.ts.map +0 -1
  158. package/dist/internal/reuse.js +0 -68
  159. package/dist/internal/reuse.js.map +0 -1
  160. package/dist/internal/scheduler.d.ts +0 -47
  161. package/dist/internal/scheduler.d.ts.map +0 -1
  162. package/dist/internal/scheduler.js +0 -70
  163. package/dist/internal/scheduler.js.map +0 -1
  164. package/dist/internal/seeds.d.ts.map +0 -1
  165. package/dist/internal/seeds.js +0 -17
  166. package/dist/internal/seeds.js.map +0 -1
  167. package/dist/internal/sources.d.ts +0 -39
  168. package/dist/internal/sources.d.ts.map +0 -1
  169. package/dist/internal/sources.js +0 -59
  170. package/dist/internal/sources.js.map +0 -1
  171. package/dist/internal/stateRegistry.d.ts +0 -2
  172. package/dist/internal/stateRegistry.d.ts.map +0 -1
  173. package/dist/internal/stateRegistry.js.map +0 -1
  174. package/dist/internal/store.d.ts +0 -47
  175. package/dist/internal/store.d.ts.map +0 -1
  176. package/dist/internal/store.js +0 -73
  177. package/dist/internal/store.js.map +0 -1
  178. package/dist/internal/track.d.ts.map +0 -1
  179. package/dist/internal/track.js +0 -19
  180. package/dist/internal/track.js.map +0 -1
  181. package/dist/procedure/procedure.d.ts +0 -40
  182. package/dist/procedure/procedure.d.ts.map +0 -1
  183. package/dist/procedure/procedure.js +0 -50
  184. package/dist/procedure/procedure.js.map +0 -1
  185. package/dist/reducer/reducer.d.ts +0 -44
  186. package/dist/reducer/reducer.d.ts.map +0 -1
  187. package/dist/reducer/reducer.js +0 -63
  188. package/dist/reducer/reducer.js.map +0 -1
  189. package/dist/remote/remoteState.d.ts +0 -119
  190. package/dist/remote/remoteState.d.ts.map +0 -1
  191. package/dist/remote/remoteState.js +0 -270
  192. package/dist/remote/remoteState.js.map +0 -1
  193. package/dist/runtime/bus.d.ts +0 -27
  194. package/dist/runtime/bus.d.ts.map +0 -1
  195. package/dist/runtime/bus.js +0 -21
  196. package/dist/runtime/bus.js.map +0 -1
  197. package/dist/runtime/loop.d.ts +0 -45
  198. package/dist/runtime/loop.d.ts.map +0 -1
  199. package/dist/runtime/loop.js +0 -117
  200. package/dist/runtime/loop.js.map +0 -1
  201. package/dist/scene/scene.d.ts +0 -44
  202. package/dist/scene/scene.d.ts.map +0 -1
  203. package/dist/scene/scene.js +0 -31
  204. package/dist/scene/scene.js.map +0 -1
  205. package/dist/state/state.d.ts +0 -37
  206. package/dist/state/state.d.ts.map +0 -1
  207. package/dist/state/state.js +0 -46
  208. package/dist/state/state.js.map +0 -1
  209. package/dist/state/stateFamily.d.ts +0 -79
  210. package/dist/state/stateFamily.d.ts.map +0 -1
  211. package/dist/state/stateFamily.js +0 -99
  212. package/dist/state/stateFamily.js.map +0 -1
  213. package/dist/state/stateGroup.d.ts +0 -50
  214. package/dist/state/stateGroup.d.ts.map +0 -1
  215. package/dist/state/stateGroup.js +0 -54
  216. package/dist/state/stateGroup.js.map +0 -1
  217. package/dist/state/token.d.ts.map +0 -1
  218. package/dist/state/token.js +0 -20
  219. package/dist/state/token.js.map +0 -1
  220. package/dist/synced/syncedStore.d.ts +0 -51
  221. package/dist/synced/syncedStore.d.ts.map +0 -1
  222. package/dist/synced/syncedStore.js +0 -43
  223. package/dist/synced/syncedStore.js.map +0 -1
  224. package/dist/ui/node.d.ts.map +0 -1
  225. package/dist/ui/node.js +0 -2
  226. package/dist/ui/node.js.map +0 -1
  227. package/dist/ui/trigger.d.ts.map +0 -1
  228. package/dist/ui/trigger.js +0 -2
  229. package/dist/ui/trigger.js.map +0 -1
  230. package/dist/wire/tree.d.ts +0 -66
  231. package/dist/wire/tree.d.ts.map +0 -1
  232. package/dist/wire/tree.js +0 -60
  233. package/dist/wire/tree.js.map +0 -1
  234. package/dist/wire/triggers.d.ts +0 -44
  235. package/dist/wire/triggers.d.ts.map +0 -1
  236. package/dist/wire/triggers.js +0 -31
  237. package/dist/wire/triggers.js.map +0 -1
@@ -0,0 +1,269 @@
1
+ import { Chunk, Context, type Duration, Effect, Layer, Match, Queue, Stream } from 'effect'
2
+ import { type Manifest, definitionClass } from '../definition/definition'
3
+ import { DuplicateRegistration } from '../internal/errors'
4
+ import type { Tagged } from '../runtime/bus'
5
+
6
+ /**
7
+ * How a channel schedules the procedure work routed to it. Channels generalize
8
+ * the old per-procedure `concurrency`: a named lane with one policy, shared by
9
+ * every procedure that declares it.
10
+ *
11
+ * - `merge` run every routed event concurrently (the default).
12
+ * - `latest` a new event cancels the in-flight run (switch).
13
+ * - `debounce` collapse a burst, run only after `duration` of quiet.
14
+ * - `throttle` rate-limit to `units` per `duration` (shape or enforce).
15
+ * - `exclusive` one run at a time across the whole channel (mutual exclusion).
16
+ */
17
+ export type ChannelPolicy =
18
+ | { readonly _tag: 'merge' }
19
+ | { readonly _tag: 'latest' }
20
+ | { readonly _tag: 'debounce'; readonly duration: Duration.DurationInput }
21
+ | {
22
+ readonly _tag: 'throttle'
23
+ readonly units: number
24
+ readonly duration: Duration.DurationInput
25
+ readonly cost?: number
26
+ readonly burst?: number
27
+ readonly strategy?: 'enforce' | 'shape'
28
+ }
29
+ | { readonly _tag: 'exclusive' }
30
+
31
+ /** The reflectable descriptor a channel carries. */
32
+ export interface ChannelManifest extends Manifest {
33
+ readonly kind: 'Channel'
34
+ }
35
+
36
+ export interface ChannelClass {
37
+ new (): {}
38
+ readonly manifest: ChannelManifest
39
+ readonly policy: ChannelPolicy
40
+ }
41
+
42
+ export interface ChannelConfig {
43
+ readonly policy: ChannelPolicy
44
+ }
45
+
46
+ /**
47
+ * A registered procedure body, with its trigger events and the channel it runs
48
+ * on. `run`'s context (RPC clients, etc.) is already provided at registration
49
+ * (see `Procedure.live`), so the channel fiber can run it with no R.
50
+ */
51
+ export interface ProcedureEntry {
52
+ /** The procedure's name — used only to warn on duplicate registration. */
53
+ readonly name: string
54
+ readonly channelName: string
55
+ readonly handles: ReadonlySet<string>
56
+ readonly run: (event: Tagged) => Effect.Effect<unknown, unknown, never>
57
+ }
58
+
59
+ /**
60
+ * Mutable collector procedures register into; channels read it to find their
61
+ * bodies. `byTag` indexes entries by trigger tag, so a channel routes an event
62
+ * to O(procedures handling it) rather than scanning every registered procedure.
63
+ */
64
+ export interface ProcedureRegistry {
65
+ readonly entries: Array<ProcedureEntry>
66
+ readonly byTag: Map<string, Array<ProcedureEntry>>
67
+ /**
68
+ * Distinct channel names per event tag. The drain loop routes through this so
69
+ * it offers each event to each channel exactly once — not once per matching
70
+ * procedure, which would re-run every procedure on a shared channel per offer.
71
+ */
72
+ readonly channelsByTag: Map<string, Array<string>>
73
+ /**
74
+ * Procedures keyed by (channel, tag), so a channel's `runMatching` is a direct
75
+ * lookup instead of scanning `byTag` and re-filtering by channel per event.
76
+ */
77
+ readonly byChannelTag: Map<string, Map<string, Array<ProcedureEntry>>>
78
+ readonly register: (entry: ProcedureEntry) => void
79
+ /**
80
+ * Remove a previously-registered entry — the inverse of `register`, used when a
81
+ * lazy feature unmounts (scope close) so its procedures stop running and their
82
+ * index entries are reclaimed. Eager procedures (root scope) never call it.
83
+ */
84
+ readonly unregister: (entry: ProcedureEntry) => void
85
+ }
86
+
87
+ const ProceduresBase: Context.TagClass<Procedures, 'reform/Procedures', ProcedureRegistry> =
88
+ Context.Tag('reform/Procedures')<Procedures, ProcedureRegistry>()
89
+ export class Procedures extends ProceduresBase {}
90
+
91
+ /** Get a map entry, creating and inserting it on first access (avoids `let`). */
92
+ const getOrCreate = <K, V>(map: Map<K, V>, key: K, make: () => V): V => {
93
+ const existing = map.get(key)
94
+ if (existing !== undefined) return existing
95
+ const created = make()
96
+ map.set(key, created)
97
+ return created
98
+ }
99
+
100
+ /** Drop an item from a `Map<K, Array>` bucket, pruning the key when it empties. */
101
+ const dropFrom = <K, T>(map: Map<K, Array<T>>, key: K, item: T): void => {
102
+ const bucket = map.get(key)
103
+ if (bucket === undefined) return
104
+ const next = bucket.filter((value) => value !== item)
105
+ if (next.length === 0) map.delete(key)
106
+ else map.set(key, next)
107
+ }
108
+
109
+ const makeProcedureRegistry = (): ProcedureRegistry => {
110
+ const entries: Array<ProcedureEntry> = []
111
+ const byTag = new Map<string, Array<ProcedureEntry>>()
112
+ const channelsByTag = new Map<string, Array<string>>()
113
+ const byChannelTag = new Map<string, Map<string, Array<ProcedureEntry>>>()
114
+ return {
115
+ entries,
116
+ byTag,
117
+ channelsByTag,
118
+ byChannelTag,
119
+ register: (entry) => {
120
+ entries.push(entry)
121
+ for (const tag of entry.handles) {
122
+ getOrCreate(byTag, tag, () => []).push(entry)
123
+ const channels = getOrCreate(channelsByTag, tag, () => [])
124
+ if (!channels.includes(entry.channelName)) channels.push(entry.channelName)
125
+ getOrCreate(getOrCreate(byChannelTag, entry.channelName, () => new Map()), tag, () => []).push(
126
+ entry,
127
+ )
128
+ }
129
+ },
130
+ unregister: (entry) => {
131
+ const index = entries.indexOf(entry)
132
+ if (index >= 0) entries.splice(index, 1)
133
+ for (const tag of entry.handles) {
134
+ dropFrom(byTag, tag, entry)
135
+ const channelMap = byChannelTag.get(entry.channelName)
136
+ if (channelMap !== undefined) {
137
+ dropFrom(channelMap, tag, entry)
138
+ // If no procedure on this channel still handles the tag, drop the
139
+ // channel from `channelsByTag[tag]` so the loop stops offering to it.
140
+ if (channelMap.get(tag) === undefined) dropFrom(channelsByTag, tag, entry.channelName)
141
+ if (channelMap.size === 0) byChannelTag.delete(entry.channelName)
142
+ }
143
+ }
144
+ },
145
+ }
146
+ }
147
+
148
+ export const proceduresLayer: Layer.Layer<Procedures> = Layer.sync(Procedures, makeProcedureRegistry)
149
+
150
+ /** A live channel: the single loop offers events here; the channel drives them. */
151
+ export interface ChannelRuntime {
152
+ readonly name: string
153
+ /** The policy this channel was built with — used to reject a name clash. */
154
+ readonly policy: ChannelPolicy
155
+ readonly offer: (event: Tagged) => void
156
+ }
157
+
158
+ /** Registry of live channels, keyed by name. The single loop routes through it. */
159
+ const ChannelsBase: Context.TagClass<
160
+ Channels,
161
+ 'reform/Channels',
162
+ { readonly byName: Map<string, ChannelRuntime> }
163
+ > = Context.Tag('reform/Channels')<Channels, { readonly byName: Map<string, ChannelRuntime> }>()
164
+ export class Channels extends ChannelsBase {}
165
+
166
+ export const channelsLayer: Layer.Layer<Channels> = Layer.sync(Channels, () => ({ byName: new Map() }))
167
+
168
+ /**
169
+ * A scheduling lane for procedures. The *definition* (`Channel.make`) is a
170
+ * reflectable name + policy; the *implementation* (`Channel.live`) builds the
171
+ * queue + fiber that applies the policy. Procedures reference a channel by value
172
+ * and register into it; `Channel.live` is merged into the app once per channel.
173
+ */
174
+ export const make = (name: string, config: ChannelConfig): ChannelClass =>
175
+ definitionClass<ChannelClass>({
176
+ manifest: { kind: 'Channel' as const, name } satisfies ChannelManifest,
177
+ policy: config.policy,
178
+ })
179
+
180
+ /**
181
+ * Build and register the live machinery for a channel. Idempotent by name, so
182
+ * procedures sharing an `exclusive`/`latest` channel share one queue + fiber +
183
+ * semaphore (and therefore truly serialize / cancel across each other).
184
+ */
185
+ export const live = (channel: ChannelClass): Layer.Layer<never, never, Channels | Procedures> =>
186
+ Layer.scopedDiscard(
187
+ Effect.gen(function* () {
188
+ const name = channel.manifest.name
189
+ const channels = yield* Channels
190
+ const existing = channels.byName.get(name)
191
+ if (existing !== undefined) {
192
+ // Idempotent for the *same* channel `.live`'d through several sub-layers
193
+ // (shared `exclusive`/`latest` lane). A *different* channel reusing the
194
+ // name is a silent footgun — the second policy would be dropped — so
195
+ // reject it loudly instead.
196
+ if (existing.policy !== channel.policy) {
197
+ throw new DuplicateRegistration({ kind: 'Channel', name })
198
+ }
199
+ return
200
+ }
201
+ const procedures = yield* Procedures
202
+ const queue = yield* Queue.unbounded<Tagged>()
203
+
204
+ // Run every procedure on THIS channel that handles the event. Read the live
205
+ // index each time so procedures registered later are still seen.
206
+ // A procedure is expected to model expected failures as events; a leaked
207
+ // defect (a bug in the body) is logged before being isolated, so one
208
+ // procedure's crash never tears down the channel fiber — but is observable.
209
+ const runMatching = (event: Tagged): Effect.Effect<void> =>
210
+ Effect.forEach(
211
+ procedures.byChannelTag.get(name)?.get(event._tag) ?? [],
212
+ (e) =>
213
+ e.run(event).pipe(
214
+ Effect.tapErrorCause((cause) =>
215
+ Effect.logError(`reform: procedure on channel '${name}' failed`, cause),
216
+ ),
217
+ Effect.catchAllCause(() => Effect.void),
218
+ ),
219
+ { discard: true, concurrency: 'unbounded' },
220
+ )
221
+
222
+ // Map the policy to its scheduling stream. `Match.exhaustive` makes a new
223
+ // policy variant a compile error, and each arm is a self-contained const.
224
+ const events = Stream.fromQueue(queue)
225
+ const driven: Stream.Stream<unknown> = Match.value(channel.policy).pipe(
226
+ Match.tag('merge', () => Stream.mapEffect(events, runMatching, { concurrency: 'unbounded' })),
227
+ Match.tag('latest', () =>
228
+ Stream.flatMap(events, (e) => Stream.fromEffect(runMatching(e)), { switch: true }),
229
+ ),
230
+ Match.tag('debounce', (policy) =>
231
+ events.pipe(
232
+ Stream.debounce(policy.duration),
233
+ Stream.mapEffect(runMatching, { concurrency: 'unbounded' }),
234
+ ),
235
+ ),
236
+ Match.tag('throttle', (policy) =>
237
+ events.pipe(
238
+ Stream.throttle({
239
+ cost: (chunk) => Chunk.size(chunk) * (policy.cost ?? 1),
240
+ units: policy.units,
241
+ duration: policy.duration,
242
+ ...(policy.burst !== undefined ? { burst: policy.burst } : {}),
243
+ strategy: policy.strategy ?? 'shape',
244
+ }),
245
+ Stream.mapEffect(runMatching, { concurrency: 'unbounded' }),
246
+ ),
247
+ ),
248
+ // `concurrency: 1` runs one event at a time AND in offer order — a true
249
+ // serialized lane. (An unbounded fork racing for a single semaphore permit
250
+ // would serialize but could reorder under contention.)
251
+ Match.tag('exclusive', () => Stream.mapEffect(events, runMatching, { concurrency: 1 })),
252
+ Match.exhaustive,
253
+ )
254
+
255
+ yield* Effect.forkScoped(Stream.runDrain(driven))
256
+ channels.byName.set(name, {
257
+ name,
258
+ policy: channel.policy,
259
+ offer: (event) => {
260
+ Queue.unsafeOffer(queue, event)
261
+ },
262
+ })
263
+ // On scope close (a lazy feature unmounting) remove the live channel so the
264
+ // loop stops routing to it; the drain fiber is already torn down by
265
+ // `forkScoped`. Eager channels live on the root scope, so this is a no-op
266
+ // until app dispose.
267
+ yield* Effect.addFinalizer(() => Effect.sync(() => channels.byName.delete(name)))
268
+ }),
269
+ )
@@ -0,0 +1,112 @@
1
+ import { Context, Effect, Layer, type Schema } from 'effect'
2
+ import type { YieldWrap } from 'effect/Utils'
3
+ import { type Manifest, definitionClass } from '../definition/definition'
4
+ import { type Ctx } from '../internal/ctx'
5
+ import type { Tracker } from '../internal/track'
6
+ import { CurrentTracker } from '../internal/track'
7
+ import { CurrentSlots, type SlotHost } from './host'
8
+ import type { Node, SlotClass } from './slot'
9
+ import type { UiClass, UiContract } from './ui'
10
+ import { Props } from './props'
11
+
12
+ /** Everything the host injects per render: the instance props, the dependency tracker, and slot bindings. */
13
+ export interface RenderEnv {
14
+ readonly props: unknown
15
+ readonly tracker: Tracker
16
+ readonly slots: SlotHost
17
+ }
18
+
19
+ /** A mounted composition: given a render environment, produces the current frame's node. */
20
+ export interface CompositionService {
21
+ readonly render: (env: RenderEnv) => Effect.Effect<Node, never, never>
22
+ }
23
+
24
+ export interface CompositionConfig {
25
+ readonly title: string
26
+ readonly description?: string
27
+ // `any` in the encoded/context slots is required by Schema's variance for
28
+ // branded/Class schemas (e.g. `Todo`); only the decoded type `P` is used.
29
+ readonly props?: Schema.Schema<any, any>
30
+ readonly states?: ReadonlyArray<unknown>
31
+ readonly calcs?: ReadonlyArray<unknown>
32
+ readonly events?: ReadonlyArray<unknown>
33
+ readonly slots?: Record<string, SlotClass>
34
+ // The UI contract this composition resolves. Typed as a manifest carrier (not
35
+ // the full `UiClass`, whose invariant `impl` tag would force the contract type
36
+ // to leak here) so reflection — the dev tool, proofs — can read `ui.manifest`.
37
+ readonly ui: { readonly manifest: Manifest & { readonly kind: 'Ui' } }
38
+ }
39
+
40
+ type PropsOf<Config> = Config extends { props: Schema.Schema<infer P, any> } ? P : unknown
41
+
42
+ export interface CompositionClass<out P, out C extends UiContract = UiContract> {
43
+ new (): {}
44
+ readonly manifest: Manifest & { readonly kind: 'Composition' } & CompositionConfig
45
+ /** Phantom carrying the props type for `provide(slot, composition)` checks. */
46
+ readonly Props: P
47
+ /**
48
+ * Phantom carrying the resolved UI contract (props + events + slots). It lets
49
+ * reflection consumers — proofs, the dev tool — recover the full contract from
50
+ * a composition value and stay fully typed. Covariant (output only); the
51
+ * invariant `impl` tag is never stored here, so no variance regression.
52
+ */
53
+ readonly Contract: C
54
+ readonly tag: Context.Tag<CompositionService, CompositionService>
55
+ }
56
+
57
+ /**
58
+ * A component's logic. The *definition* (`Composition.make`) is a reflectable
59
+ * manifest that doubles as a requirement/tag; the *implementation*
60
+ * (`Composition.live`) is the synchronous body, provided separately and
61
+ * checked against it.
62
+ */
63
+ export const make = <const Config extends CompositionConfig, C extends UiContract>(
64
+ name: string,
65
+ // Constrain `ui` to the full `UiClass<C>` so `C` is inferred here; the stored
66
+ // manifest still sees only the erased `{ manifest }` carrier (CompositionConfig),
67
+ // so the manifest type — and its variance — is unchanged.
68
+ config: Config & { readonly ui: UiClass<C> },
69
+ ): CompositionClass<PropsOf<Config>, C> => {
70
+ const tag = Context.GenericTag<CompositionService, CompositionService>(
71
+ `reform/composition/${name}`,
72
+ )
73
+ const manifest = { kind: 'Composition' as const, name, ...config }
74
+ return definitionClass<CompositionClass<PropsOf<Config>, C>>({ manifest, tag })
75
+ }
76
+
77
+ /**
78
+ * Wire a composition's synchronous logic (D2): read state, acquire triggers,
79
+ * resolve the UI, return the view. Its requirements (minus `Props`, which the
80
+ * host injects per render) surface as the Layer's `RIn`; the runtime runs the
81
+ * body per render within the captured context.
82
+ */
83
+ export const live = <P, Eff extends YieldWrap<Effect.Effect<unknown, never, unknown>>>(
84
+ // `live` doesn't use the contract type; accept any composition.
85
+ composition: CompositionClass<P, any>,
86
+ body: () => Generator<Eff, Node, never>,
87
+ ): Layer.Layer<CompositionService, never, Exclude<Ctx<Eff>, Props>> => {
88
+ const logic = Effect.gen(body)
89
+ return Layer.effect(
90
+ composition.tag,
91
+ Effect.gen(function* () {
92
+ // Capture the build-time context (state stores, calc, ui, bus). `Props`,
93
+ // the tracker, and slots are injected per render below.
94
+ const context = yield* Effect.context<Exclude<Ctx<Eff>, Props>>()
95
+ const render = (env: RenderEnv): Effect.Effect<Node, never, never> =>
96
+ // Total once fully provided: the body is synchronous, reads can't fail,
97
+ // and every requirement is now satisfied (D2). `Effect.gen` widens the
98
+ // error channel to `unknown` for a generic body, so we restate it.
99
+ logic.pipe(
100
+ Effect.provideService(Props, env.props),
101
+ Effect.provideService(CurrentTracker, env.tracker),
102
+ Effect.provideService(CurrentSlots, env.slots),
103
+ Effect.provide(context),
104
+ ) as Effect.Effect<Node, never, never>
105
+ return { render }
106
+ }),
107
+ )
108
+ }
109
+
110
+ /** Run a mounted composition for one frame, producing its node. */
111
+ export const render = (service: CompositionService, env: RenderEnv): Effect.Effect<Node, never, never> =>
112
+ service.render(env)
@@ -1,5 +1,6 @@
1
- import { Context } from 'effect';
2
- import type { Node } from './slot';
1
+ import { Context } from 'effect'
2
+ import type { Node } from './slot'
3
+
3
4
  /**
4
5
  * Binds a parent's slots to concrete child renderers. The host package
5
6
  * (`@reform/react`) builds one per composition instance from the manifest's
@@ -7,11 +8,11 @@ import type { Node } from './slot';
7
8
  * child. Core stays renderer-neutral — it only defines this hole.
8
9
  */
9
10
  export interface SlotHost {
10
- slot(name: string): (props: unknown) => Node;
11
+ slot(name: string): (props: unknown) => Node
11
12
  }
12
- declare const CurrentSlotsBase: Context.TagClass<CurrentSlots, 'reform/Slots', SlotHost>;
13
+
14
+ const CurrentSlotsBase: Context.TagClass<CurrentSlots, 'reform/Slots', SlotHost> =
15
+ Context.Tag('reform/Slots')<CurrentSlots, SlotHost>()
16
+
13
17
  /** The active composition's slot bindings, provided per render by the host. */
14
- export declare class CurrentSlots extends CurrentSlotsBase {
15
- }
16
- export {};
17
- //# sourceMappingURL=host.d.ts.map
18
+ export class CurrentSlots extends CurrentSlotsBase {}
@@ -1,4 +1,5 @@
1
- import { Context } from 'effect';
1
+ import { Context } from 'effect'
2
+
2
3
  /**
3
4
  * The current composition instance's props. Bound per render by the runtime; a
4
5
  * composition body reads them with `const { todo } = yield* Props`.
@@ -6,7 +7,8 @@ import { Context } from 'effect';
6
7
  * (Per-instance typing of Props is DESIGN #26 — for now the value is opaque and
7
8
  * narrowed at the use site against the composition's declared props schema.)
8
9
  */
9
- const PropsBase = Context.Tag('reform/Props')();
10
- export class Props extends PropsBase {
11
- }
12
- //# sourceMappingURL=props.js.map
10
+ const PropsBase: Context.TagClass<Props, 'reform/Props', any> = Context.Tag('reform/Props')<
11
+ Props,
12
+ any
13
+ >()
14
+ export class Props extends PropsBase {}
@@ -0,0 +1,70 @@
1
+ import { type Context, Layer } from 'effect'
2
+ import { InvalidProvideTarget } from '../internal/errors'
3
+ import type { CompositionClass } from './composition'
4
+ import {
5
+ type EngineServices,
6
+ type FeatureClass,
7
+ isFeature,
8
+ type ProvidedBy,
9
+ type RequireCarrier,
10
+ } from '../feature/feature'
11
+ import { isSlot, type SlotChild, type SlotClass } from './slot'
12
+ import { isUi, type UiClass, type UiContract, type ViewImpl } from './ui'
13
+
14
+ /**
15
+ * Wire an implementation to a contract. Provides a `.make` presentation to a UI
16
+ * contract, a child composition into a parent's slot, or a `Feature` into a slot.
17
+ * The compose code never imports its implementations — they meet here.
18
+ */
19
+ export function provide<C extends UiContract>(
20
+ contract: UiClass<C>,
21
+ view: ViewImpl<C>,
22
+ ): Layer.Layer<ViewImpl<C>>
23
+ export function provide<Comp extends CompositionClass<any, any>>(
24
+ hole: SlotClass<Comp>,
25
+ composition: Comp,
26
+ ): Layer.Layer<CompositionClass<unknown>>
27
+ /**
28
+ * Fill a slot with a feature. The slot's child composition type
29
+ * (`CompositionClass<P, C>`) must match the feature's mounted composition, so the
30
+ * facade/contract stays typed. The returned layer surfaces the feature's shared
31
+ * requirement (`EngineServices | ProvidedBy<Requires>`) as an open `RIn`, so the
32
+ * scene that wires it won't compile unless it provides the matching `Core` — even
33
+ * for a lazy feature whose own `.live` layer isn't built until mount.
34
+ */
35
+ export function provide<
36
+ Comp extends CompositionClass<any, any>,
37
+ ROut,
38
+ Requires extends ReadonlyArray<RequireCarrier>,
39
+ >(
40
+ hole: SlotClass<Comp>,
41
+ feature: FeatureClass<
42
+ Comp extends CompositionClass<infer P, any> ? P : never,
43
+ Comp extends CompositionClass<any, infer C> ? C : never,
44
+ ROut,
45
+ Requires
46
+ >,
47
+ ): Layer.Layer<SlotChild, never, EngineServices | ProvidedBy<Requires>>
48
+ export function provide(target: unknown, impl: unknown): Layer.Layer<never, never, unknown> {
49
+ // Discriminate the target by its nominal brand, not by which DI-hole property
50
+ // happens to exist: a UI contract provides under its `impl` tag, a slot under
51
+ // its `tag`. Anything else is a wiring mistake. The overloads above pair
52
+ // `impl` with the chosen tag; this implementation sees both erased, so view
53
+ // the tag loosely (the one documented cast) to provide the service under it.
54
+ const tag = (isUi(target) ? target.impl : isSlot(target) ? target.tag : undefined) as
55
+ | Context.Tag<unknown, unknown>
56
+ | undefined
57
+ if (tag === undefined) throw new InvalidProvideTarget()
58
+ if (isFeature(impl)) {
59
+ const eager = impl.eagerModule
60
+ // Lazy: bind the `FeatureBinding`; the host drives load → mount, painting the
61
+ // placeholders. Default: bind the composition (so the existing `Compose` path
62
+ // renders it, no host, no flash) and merge the eager `.live` layer, whose `RIn`
63
+ // surfaces to the scene. Either way the overload's return type carries the
64
+ // shared `RIn`, so the scene still type-demands `Core`.
65
+ return eager === undefined
66
+ ? Layer.succeed(tag, impl.binding)
67
+ : Layer.merge(Layer.succeed(tag, impl.binding.composition), eager.layer)
68
+ }
69
+ return Layer.succeed(tag, impl)
70
+ }
@@ -1,17 +1,22 @@
1
- import { Context } from 'effect';
2
- import type { CompositionClass } from './composition';
3
- import type { FeatureBinding } from '../feature/feature';
4
- import type { Node } from '../ui/node';
5
- export type { Node };
1
+ import { Context } from 'effect'
2
+ import { definitionClass } from '../definition/definition'
3
+ import type { CompositionClass } from './composition'
4
+ import type { FeatureBinding } from '../feature/feature'
5
+ import type { Node } from '../ui/node'
6
+
7
+ export type { Node }
8
+
6
9
  /** Any composition, used where only the slot's structural role matters. */
7
- type AnyComposition = CompositionClass<any, any>;
10
+ type AnyComposition = CompositionClass<any, any>
11
+
8
12
  /**
9
13
  * What a slot can be filled with: a plain child composition (the host renders it
10
14
  * directly), or a `FeatureBinding` from `provide(slot, Feature)` (the host drives
11
15
  * its lazy/eager mount lifecycle). The slot's DI tag holds one of these; the host
12
16
  * discriminates by the `FeatureBinding` brand.
13
17
  */
14
- export type SlotChild = CompositionClass<unknown> | FeatureBinding;
18
+ export type SlotChild = CompositionClass<unknown> | FeatureBinding
19
+
15
20
  /**
16
21
  * Phantom instance shape: `ItemSlot` used as a *type* denotes this. It carries
17
22
  * the child *composition* type `Comp`, so the slot knows both the external props
@@ -20,8 +25,9 @@ export type SlotChild = CompositionClass<unknown> | FeatureBinding;
20
25
  * proof facade, drive.
21
26
  */
22
27
  export interface SlotInstance<Comp extends AnyComposition> {
23
- readonly _slot: Comp;
28
+ readonly _slot: Comp
24
29
  }
30
+
25
31
  /**
26
32
  * A DI hole for a child composition. The parent declares
27
33
  * `slot('Item')<typeof TodoItem>()` and renders through it; the concrete child
@@ -32,18 +38,29 @@ export interface SlotInstance<Comp extends AnyComposition> {
32
38
  * by `provide`'s signature, not the (invariant) tag.
33
39
  */
34
40
  /** Nominal brand identifying a slot at runtime (Effect's `TypeId` idiom). */
35
- export declare const SlotTypeId: unique symbol;
36
- export type SlotTypeId = typeof SlotTypeId;
41
+ export const SlotTypeId: unique symbol = Symbol.for('reform/Slot')
42
+ export type SlotTypeId = typeof SlotTypeId
43
+
37
44
  export interface SlotClass<Comp extends AnyComposition = AnyComposition> {
38
- new (): SlotInstance<Comp>;
39
- readonly [SlotTypeId]: SlotTypeId;
40
- readonly kind: 'Slot';
41
- /** Internal DI tag the filling child (composition or feature binding) is provided under. */
42
- readonly tag: Context.Tag<SlotChild, SlotChild>;
45
+ new (): SlotInstance<Comp>
46
+ readonly [SlotTypeId]: SlotTypeId
47
+ readonly kind: 'Slot'
48
+ /** Internal DI tag the filling child (composition or feature binding) is provided under. */
49
+ readonly tag: Context.Tag<SlotChild, SlotChild>
43
50
  }
51
+
44
52
  /** Whether a value is a slot — discriminates a `provide` target by brand. */
45
- export declare const isSlot: (u: unknown) => u is SlotClass;
53
+ export const isSlot = (u: unknown): u is SlotClass =>
54
+ (typeof u === 'function' || typeof u === 'object') && u !== null && SlotTypeId in u
55
+
46
56
  /** The props a slot renders with — the child composition's external props. */
47
- export type SlotProps<S> = S extends SlotInstance<infer Comp> ? Comp['Props'] : never;
48
- export declare const slot: (name: string) => <Comp extends AnyComposition = AnyComposition>() => SlotClass<Comp>;
49
- //# sourceMappingURL=slot.d.ts.map
57
+ export type SlotProps<S> = S extends SlotInstance<infer Comp> ? Comp['Props'] : never
58
+
59
+ export const slot =
60
+ (name: string) =>
61
+ // Defaulted so a slot whose child carries no meaningful props/contract can be
62
+ // declared bare (`slot('Tree')()`); pass `typeof Child` to type the facade.
63
+ <Comp extends AnyComposition = AnyComposition>(): SlotClass<Comp> => {
64
+ const tag = Context.GenericTag<SlotChild, SlotChild>(`reform/slot/${name}`)
65
+ return definitionClass<SlotClass<Comp>>({ [SlotTypeId]: SlotTypeId, kind: 'Slot' as const, tag })
66
+ }
@@ -0,0 +1,62 @@
1
+ import { expect, test } from 'vitest'
2
+ import { Effect, Schema as S } from 'effect'
3
+ import { Ui, isUi, ui } from '../index'
4
+ import { CaptureSink, type UiCapture } from '../internal/capture'
5
+ import type { Trigger } from '../ui/trigger'
6
+
7
+ // `ui` has two authoring forms with one source of truth each: the type-only form
8
+ // (local, no schema) and the schema form (wired, the type is *derived*). Both are
9
+ // the same contract at runtime; only the wired form carries reflectable schemas.
10
+
11
+ test('type-only `ui` carries no wire schema', () => {
12
+ class CounterUi extends ui('Counter')<{ props: { count: number } }>() {}
13
+ expect(CounterUi.manifest.kind).toBe('Ui')
14
+ expect(CounterUi.manifest.name).toBe('Counter')
15
+ expect(CounterUi.manifest.props).toBeUndefined()
16
+ expect(CounterUi.manifest.events).toBeUndefined()
17
+ expect(isUi(CounterUi)).toBe(true)
18
+ })
19
+
20
+ test('schema `ui` carries props and per-event wire schemas', () => {
21
+ class CounterUi extends ui('Counter', {
22
+ props: S.Struct({ count: S.Number }),
23
+ events: { bump: S.Struct({ by: S.Number }) },
24
+ }) {}
25
+ expect(CounterUi.manifest.kind).toBe('Ui')
26
+ expect(CounterUi.manifest.name).toBe('Counter')
27
+ expect(S.isSchema(CounterUi.manifest.props)).toBe(true)
28
+ expect(S.isSchema(CounterUi.manifest.events?.['bump'])).toBe(true)
29
+ expect(isUi(CounterUi)).toBe(true)
30
+ })
31
+
32
+ test('schema `ui` with no events omits the events schema', () => {
33
+ class TitleUi extends ui('Title', { props: S.Struct({ text: S.String }) }) {}
34
+ expect(S.isSchema(TitleUi.manifest.props)).toBe(true)
35
+ expect(TitleUi.manifest.events).toBeUndefined()
36
+ })
37
+
38
+ test('a contract resolves its presentation and reports to a capturing sink', () => {
39
+ class CounterUi extends ui('Counter', {
40
+ props: S.Struct({ count: S.Number }),
41
+ events: { bump: S.Struct({ by: S.Number }) },
42
+ }) {}
43
+
44
+ const view = Ui.make(CounterUi, ({ count }) => `count:${count}`)
45
+ const records: UiCapture[] = []
46
+ const sink = { record: (capture: UiCapture): void => void records.push(capture) }
47
+
48
+ const logicView = Effect.runSync(
49
+ CounterUi.pipe(
50
+ Effect.provideService(CounterUi.impl, view),
51
+ Effect.provideService(CaptureSink, sink),
52
+ ),
53
+ )
54
+
55
+ const bump: Trigger<{ by: number }> = () => {}
56
+ const node = logicView({ count: 3 }, { bump })
57
+
58
+ expect(node).toBe('count:3')
59
+ expect(records).toHaveLength(1)
60
+ expect(records[0]?.name).toBe('Counter')
61
+ expect(records[0]?.props).toEqual({ count: 3 })
62
+ })