@playfast/reform 0.0.5 → 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 (47) hide show
  1. package/package.json +31 -10
  2. package/src/boundary/boundary.test.ts +301 -0
  3. package/src/calc/asyncCalc.test.ts +556 -0
  4. package/src/calc/asyncData.ts +9 -1
  5. package/src/calc/calc.test.ts +287 -0
  6. package/src/calc/calcFamily.test.ts +206 -0
  7. package/src/calc/compose.test.ts +68 -0
  8. package/src/channel/channel.ts +9 -5
  9. package/src/compose/host.ts +4 -1
  10. package/src/compose/props.ts +5 -1
  11. package/src/compose/ui.test.ts +62 -0
  12. package/src/compose/ui.ts +173 -44
  13. package/src/compose/ui.typecheck.ts +56 -0
  14. package/src/definition/definition.ts +2 -0
  15. package/src/event/event.test.ts +23 -0
  16. package/src/feature/feature.mount.test.ts +82 -0
  17. package/src/feature/feature.test.ts +60 -0
  18. package/src/feature/feature.typecheck.ts +108 -0
  19. package/src/index.ts +38 -2
  20. package/src/internal/capture.ts +4 -4
  21. package/src/internal/errors.test.ts +33 -0
  22. package/src/internal/errors.ts +92 -16
  23. package/src/internal/inspect.test.ts +28 -0
  24. package/src/internal/queryDriver.ts +1 -1
  25. package/src/internal/reuse.test.ts +116 -0
  26. package/src/internal/scheduler.ts +3 -1
  27. package/src/internal/sources.ts +2 -2
  28. package/src/internal/stateRegistry.ts +32 -0
  29. package/src/internal/store.test.ts +80 -0
  30. package/src/internal/track.ts +3 -1
  31. package/src/remote/remoteState.test.ts +695 -0
  32. package/src/remote/remoteState.typecheck.ts +195 -0
  33. package/src/runtime/bus.ts +6 -2
  34. package/src/runtime/hardening.test.ts +69 -0
  35. package/src/runtime/loop.test.ts +178 -0
  36. package/src/runtime/loop.ts +4 -2
  37. package/src/scene/seedScene.test.ts +169 -0
  38. package/src/state/state.ts +4 -1
  39. package/src/state/stateFamily.test.ts +138 -0
  40. package/src/state/stateFamily.ts +4 -1
  41. package/src/state/stateGroup.ts +31 -4
  42. package/src/state/token.ts +5 -4
  43. package/src/synced/syncedStore.ts +99 -0
  44. package/src/wire/tree.test.ts +81 -0
  45. package/src/wire/tree.ts +129 -0
  46. package/src/wire/triggers.test.ts +76 -0
  47. package/src/wire/triggers.ts +98 -0
package/src/compose/ui.ts CHANGED
@@ -1,10 +1,11 @@
1
- import { Context, Effect, Option } from 'effect'
1
+ import type { FunctionComponent } from 'react'
2
+ import { Context, Effect, Option, type Schema } from 'effect'
2
3
  import { type Manifest, yieldableClass } from '../definition/definition'
3
4
  import { CaptureSink } from '../internal/capture'
4
5
  import { SlotRenderingUnavailable } from '../internal/errors'
5
6
  import type { Trigger } from '../ui/trigger'
6
7
  import { CurrentSlots } from './host'
7
- import { type Node, type SlotInstance, type SlotProps } from './slot'
8
+ import { type Node, type SlotClass, type SlotInstance, type SlotProps } from './slot'
8
9
 
9
10
  export interface UiContract {
10
11
  props: unknown
@@ -14,8 +15,30 @@ export interface UiContract {
14
15
 
15
16
  type PropsOf<C extends UiContract> = C['props']
16
17
  type EventsOf<C extends UiContract> = C extends { events: infer E } ? E : Record<never, never>
18
+ // A slot is a React COMPONENT whose props are OPTIONAL (a `Partial`): a parent that
19
+ // drives a child supplies them (`<slots.Item id=… />` / `createElement(slots.Item, {…})`),
20
+ // but a placeholder render (the remote client, where the per-child props were captured
21
+ // server-side and the framework expands the children) omits them (`<slots.Item />`).
22
+ // One `Ui.make` view thus serves both renderers. The child still reads its own
23
+ // props/state — these are only the external props the parent feeds, advisory at the
24
+ // slot boundary. Typing it as `FunctionComponent` makes both JSX and `createElement` work.
25
+ //
26
+ // `slotKey` is the universal KEYED-SLOT selector (see `WireNode.key`): for a LIST slot
27
+ // invoked once per item (`<slots.Row slotKey={id} />`), the remote client renders only the
28
+ // one wire child whose React `key` matches, instead of every child of that slot at every
29
+ // call site (which duplicates the whole list under each call). It is framework-handled, not
30
+ // forwarded to the child, so it is allowed on EVERY slot and never collides with a child's
31
+ // own props. Omit it for singleton slots (`<slots.Create />`) — they render all children.
17
32
  type SlotsOf<C extends UiContract> = C extends { slots: infer S }
18
- ? { readonly [K in keyof S]: (props: SlotProps<S[K]>) => Node }
33
+ ? {
34
+ // `slotKey` goes INSIDE the `Partial<…>` (not intersected outside) so that when a slot's
35
+ // child props are `any` the whole thing still collapses to `any` (`any & X = any`), keeping
36
+ // the component assignable to a bare `(props: unknown) => Node` slot-renderer shape. An
37
+ // outer intersection would leave a required-shape object that `unknown` can't satisfy.
38
+ readonly [K in keyof S]: FunctionComponent<
39
+ Partial<SlotProps<S[K]> & { readonly slotKey?: string }>
40
+ >
41
+ }
19
42
  : Record<never, never>
20
43
 
21
44
  /** What the composition logic calls: props + handlers in, a node out. Slots are bound by the renderer. */
@@ -32,66 +55,172 @@ export type ViewImpl<C extends UiContract> = (
32
55
  export const UiTypeId: unique symbol = Symbol.for('reform/Ui')
33
56
  export type UiTypeId = typeof UiTypeId
34
57
 
58
+ /**
59
+ * The reflectable descriptor a contract carries. The wire `props` / `events`
60
+ * schemas are present *only* on the schema (wired) form — the type-only form
61
+ * carries neither, so a local contract has no schema cost and no schema surface.
62
+ */
63
+ export interface UiManifest extends Manifest {
64
+ readonly kind: 'Ui'
65
+ // `any` in the encoded/context slots is required by Schema's variance for
66
+ // branded/Class schemas; only the decoded type is ever read off these.
67
+ readonly props?: Schema.Schema<any, any>
68
+ readonly events?: Readonly<Record<string, Schema.Schema<any, any>>>
69
+ }
70
+
71
+ /** A `UiManifest` whose wire schema is present — the runtime brand of a remote-capable contract. */
72
+ export interface WiredUiManifest extends UiManifest {
73
+ readonly props: Schema.Schema<any, any>
74
+ }
75
+
35
76
  export interface UiClass<C extends UiContract>
36
77
  extends Effect.Effect<LogicView<C>, never, ViewImpl<C>> {
37
78
  new (): {}
38
79
  readonly [UiTypeId]: UiTypeId
39
- readonly manifest: Manifest & { readonly kind: 'Ui' }
80
+ readonly manifest: UiManifest
40
81
  /** Internal DI tag the `Ui.make` presentation is provided under. */
41
82
  readonly impl: Context.Tag<ViewImpl<C>, ViewImpl<C>>
42
83
  }
43
84
 
85
+ /**
86
+ * Recover a contract's `UiContract` type from its `Ui` class — `Ui.Contract<typeof
87
+ * SomeUi>`. Lets a consumer (a proof, a reflection tool) name the contract derived
88
+ * from a wired `ui('X', {…})` without re-declaring it.
89
+ */
90
+ export type Contract<U> = U extends UiClass<infer C> ? C : never
91
+
92
+ /**
93
+ * A contract authored with wire schemas. Structurally a `UiClass<C>` whose
94
+ * manifest *carries* the schemas (`WiredUiManifest`), so it is the subtype the
95
+ * remote seam (`provideRemote`, the wire registry) demands while plain `provide`
96
+ * / `scene` / `Composition.make` keep accepting any `UiClass<C>`.
97
+ */
98
+ export type WiredUi<C extends UiContract> = UiClass<C> & { readonly manifest: WiredUiManifest }
99
+
100
+ /** The wire schemas a contract is authored from: props, a payload schema per event, and
101
+ * (type-only) the slots the view fills. Slots carry no wire schema — the children that
102
+ * fill them are their own contracts — but declaring them here threads typed slots into
103
+ * the derived contract, so a WIRED contract can also have slots (e.g. a parent whose
104
+ * props the client reads AND that renders slot children). */
105
+ export interface WireSchemas {
106
+ readonly props: Schema.Schema<any, any>
107
+ readonly events?: Readonly<Record<string, Schema.Schema<any, any>>>
108
+ // Slots are declared with their slot CLASSES (`slot('X')<typeof Child>()`), the
109
+ // same values `Composition.make({ slots })` takes — NOT `SlotInstance`s. The
110
+ // contract's slot facade is derived from them below.
111
+ readonly slots?: Readonly<Record<string, SlotClass>>
112
+ }
113
+
114
+ type DerivedEvents<Sch extends WireSchemas> = Sch extends {
115
+ readonly events: infer E extends Record<string, Schema.Schema<any, any>>
116
+ }
117
+ ? { readonly [K in keyof E]: Trigger<Schema.Schema.Type<E[K]>> }
118
+ : Record<never, never>
119
+
120
+ type DerivedSlots<Sch extends WireSchemas> = Sch extends {
121
+ readonly slots: infer S extends Record<string, SlotClass>
122
+ }
123
+ ? { readonly [K in keyof S]: InstanceType<S[K]> }
124
+ : Record<never, never>
125
+
126
+ /**
127
+ * The `UiContract` a set of wire schemas denotes — props and event-payload
128
+ * *types* derived from the schemas via `Schema.Type`, plus any declared slots. The
129
+ * schema is the single source of truth; the contract type is inferred, never written
130
+ * a second time.
131
+ */
132
+ export type DerivedContract<Sch extends WireSchemas> = {
133
+ readonly props: Schema.Schema.Type<Sch['props']>
134
+ readonly slots: DerivedSlots<Sch>
135
+ readonly events: DerivedEvents<Sch>
136
+ }
137
+
44
138
  /** Whether a value is a UI contract — discriminates a `provide` target by brand. */
45
139
  export const isUi = (u: unknown): u is UiClass<UiContract> =>
46
140
  (typeof u === 'function' || typeof u === 'object') && u !== null && UiTypeId in u
47
141
 
142
+ const buildUi = <C extends UiContract, M extends UiManifest>(
143
+ name: string,
144
+ manifest: M,
145
+ ): UiClass<C> & { readonly manifest: M } => {
146
+ const impl = Context.GenericTag<ViewImpl<C>, ViewImpl<C>>(`reform/ui/${name}`)
147
+ const read = Effect.gen(function* () {
148
+ const render = yield* impl
149
+ // Slots are bound by the host (`@reform/react`) per composition instance.
150
+ // Core has no renderer, so without a host every slot access throws.
151
+ const host = yield* Effect.serviceOption(CurrentSlots)
152
+ const slots = new Proxy({} as SlotsOf<C>, {
153
+ get(_t, key) {
154
+ if (Option.isNone(host)) {
155
+ throw new SlotRenderingUnavailable({ slot: String(key) })
156
+ }
157
+ return host.value.slot(String(key))
158
+ },
159
+ })
160
+ // A capturing host (proofs, the dev tool) reports each render's observable
161
+ // surface without replacing the presentation. Absent in production.
162
+ const sink = yield* Effect.serviceOption(CaptureSink)
163
+ return (props: PropsOf<C>, events?: EventsOf<C>) => {
164
+ if (Option.isSome(sink)) {
165
+ sink.value.record({
166
+ name,
167
+ props,
168
+ events: (events ?? {}) as Record<string, Trigger<unknown>>,
169
+ })
170
+ }
171
+ return render(props, slots, (events ?? {}) as EventsOf<C>)
172
+ }
173
+ })
174
+ return yieldableClass(read, {
175
+ [UiTypeId]: UiTypeId,
176
+ manifest,
177
+ impl,
178
+ })
179
+ }
180
+
48
181
  /**
49
182
  * A renderer-neutral UI contract. The logic resolves it (`yield* TodoAppUi`) to
50
183
  * a `(props, events) => node` view with slots already bound; `.make` authors the
51
184
  * presentation. Core defines the contract; `@reform/react` does the rendering.
185
+ *
186
+ * Two authoring forms, one source of truth each:
187
+ *
188
+ * - **Type-only (local):** `ui('Counter')<{ props: { count: number } }>()` — no
189
+ * schema, no ceremony, exactly as before.
190
+ * - **Schema (wired):** `ui('Counter', { props: S.Struct({ count: S.Number }) })`
191
+ * — the schema *is* the definition; the contract type is derived via
192
+ * `Schema.Type` (never re-written), and the result is a `WiredUi` the remote
193
+ * seam accepts. Make a local contract remote by rewriting this one line.
52
194
  */
53
- export const ui =
54
- (name: string) =>
55
- <C extends UiContract>(): UiClass<C> => {
56
- const impl = Context.GenericTag<ViewImpl<C>, ViewImpl<C>>(`reform/ui/${name}`)
57
- const read = Effect.gen(function* () {
58
- const render = yield* impl
59
- // Slots are bound by the host (`@reform/react`) per composition instance.
60
- // Core has no renderer, so without a host every slot access throws.
61
- const host = yield* Effect.serviceOption(CurrentSlots)
62
- const slots = new Proxy({} as SlotsOf<C>, {
63
- get(_t, key) {
64
- if (Option.isNone(host)) {
65
- throw new SlotRenderingUnavailable({ slot: String(key) })
66
- }
67
- return host.value.slot(String(key))
68
- },
69
- })
70
- // A capturing host (proofs, the dev tool) reports each render's observable
71
- // surface without replacing the presentation. Absent in production.
72
- const sink = yield* Effect.serviceOption(CaptureSink)
73
- return (props: PropsOf<C>, events?: EventsOf<C>) => {
74
- if (Option.isSome(sink)) {
75
- sink.value.record({
76
- name,
77
- props,
78
- events: (events ?? {}) as Record<string, Trigger<unknown>>,
79
- })
80
- }
81
- return render(props, slots, (events ?? {}) as EventsOf<C>)
82
- }
83
- })
84
- return yieldableClass(read, {
85
- [UiTypeId]: UiTypeId,
86
- manifest: { kind: 'Ui' as const, name },
87
- impl,
88
- })
195
+ export function ui(name: string): <C extends UiContract>() => UiClass<C>
196
+ export function ui<const Sch extends WireSchemas>(name: string, schemas: Sch): WiredUi<DerivedContract<Sch>>
197
+ export function ui(name: string, schemas?: WireSchemas): unknown {
198
+ if (schemas === undefined) {
199
+ return <C extends UiContract>(): UiClass<C> => buildUi<C, UiManifest>(name, { kind: 'Ui', name })
89
200
  }
201
+ const eventFields = schemas.events === undefined ? {} : { events: schemas.events }
202
+ const manifest: WiredUiManifest = { kind: 'Ui', name, props: schemas.props, ...eventFields }
203
+ return buildUi<DerivedContract<WireSchemas>, WiredUiManifest>(name, manifest)
204
+ }
205
+
206
+ /** Brand under which a `Ui.make` view carries its own contract. */
207
+ export const UiViewContract: unique symbol = Symbol.for('reform/ui/view-contract')
208
+ export type UiViewContract = typeof UiViewContract
209
+
210
+ /**
211
+ * A `Ui.make` view that carries its contract, so a consumer can recover the
212
+ * contract (its wire name + props schema) straight from the view — no separate
213
+ * registration call. This is what makes the remote client view-set
214
+ * (`remoteViews<AppContract>({ Some: SomeView, … })`) work with the very same
215
+ * `Ui.make` views the local renderer uses.
216
+ */
217
+ export type MadeView<C extends UiContract> = ViewImpl<C> & { readonly [UiViewContract]: UiClass<C> }
90
218
 
91
219
  /**
92
220
  * Author the pure presentation for a contract — `Ui.make(TodoAppUi, (props,
93
- * slots, events) => node)`. The contract argument fixes the view's types; wire
94
- * the result with `provide(contract, view)`.
221
+ * slots, events) => node)`. The contract argument fixes the view's types AND is
222
+ * carried on the returned view (`MadeView`), so the same view is reusable as a
223
+ * remote client presentation. Wire the result with `provide(contract, view)`.
95
224
  */
96
- export const make = <C extends UiContract>(_contract: UiClass<C>, view: ViewImpl<C>): ViewImpl<C> =>
97
- view
225
+ export const make = <C extends UiContract>(contract: UiClass<C>, view: ViewImpl<C>): MadeView<C> =>
226
+ Object.assign(view, { [UiViewContract]: contract })
@@ -0,0 +1,56 @@
1
+ // Type-level proofs enforced by `tsc --noEmit` over `src` (not a vitest file).
2
+ // These guard the schema-first seam: the wired form is the single source of
3
+ // truth (props/event types derived, never re-written), a wired contract is a
4
+ // plain `UiClass` (so `provide` / `scene` / `Composition.make` accept it), and
5
+ // the remote seam (`WiredUi`) rejects a type-only contract. If a guarantee
6
+ // regresses, a `@ts-expect-error` goes unused or an assignment fails, and `tsc`
7
+ // breaks.
8
+
9
+ import { Schema as S } from 'effect'
10
+ import {
11
+ type Contract,
12
+ type DerivedContract,
13
+ type MadeView,
14
+ make,
15
+ ui,
16
+ type UiClass,
17
+ type UiContract,
18
+ type WiredUi,
19
+ } from './ui'
20
+
21
+ declare function acceptsAny<C extends UiContract>(contract: UiClass<C>): void
22
+ declare function acceptsWired<C extends UiContract>(contract: WiredUi<C>): void
23
+
24
+ class LocalUi extends ui('Local')<{ props: { n: number } }>() {}
25
+ const wiredSchemas: {
26
+ readonly props: S.Struct<{ n: typeof S.Number }>
27
+ readonly events: { readonly bump: S.Struct<{ by: typeof S.Number }> }
28
+ } = {
29
+ props: S.Struct({ n: S.Number }),
30
+ events: { bump: S.Struct({ by: S.Number }) },
31
+ }
32
+ const WiredUiClassBase: WiredUi<DerivedContract<typeof wiredSchemas>> = ui('Wired', wiredSchemas)
33
+ class WiredUiClass extends WiredUiClassBase {}
34
+
35
+ // POSITIVE: both forms are a `UiClass` — plain wiring (provide/scene/Composition) accepts either.
36
+ acceptsAny(LocalUi)
37
+ acceptsAny(WiredUiClass)
38
+
39
+ // POSITIVE: the schema form is a `WiredUi` — the remote seam accepts it.
40
+ acceptsWired(WiredUiClass)
41
+
42
+ // NEGATIVE: a type-only contract has no wire schema, so the remote seam rejects it.
43
+ // @ts-expect-error -- LocalUi is `UiClass`, not `WiredUi`
44
+ acceptsWired(LocalUi)
45
+
46
+ // POSITIVE: props/event types are DERIVED from the schemas — authoring a presentation
47
+ // against the wired contract sees `n: number` and `bump: Trigger<{ by: number }>`,
48
+ // none of it written a second time.
49
+ export const derivedView: MadeView<Contract<typeof WiredUiClass>> = make(
50
+ WiredUiClass,
51
+ ({ n }, _slots, { bump }) => {
52
+ const _n: number = n
53
+ bump({ by: _n })
54
+ return `${_n}`
55
+ },
56
+ )
@@ -18,7 +18,9 @@ export type Kind =
18
18
  | 'Calc'
19
19
  | 'CalcFamily'
20
20
  | 'AsyncCalc'
21
+ | 'Resource'
21
22
  | 'RemoteState'
23
+ | 'SyncedStore'
22
24
  | 'Boundary'
23
25
  | 'Procedure'
24
26
  | 'Channel'
@@ -0,0 +1,23 @@
1
+ import { expect, test } from 'vitest'
2
+ import { Schema as S } from 'effect'
3
+ import { Event } from '../index'
4
+
5
+ // An event is a pure data fact: `Event.construct` builds the tagged value the
6
+ // bus carries, and the class carries the reflectable `manifest` + `tag`.
7
+
8
+ test('Event.construct builds the tagged value `{ _tag, ...payload }`', () => {
9
+ class Added extends Event.make('Added', S.Struct({ id: S.String })) {}
10
+ expect(Event.construct(Added, { id: 'x' })).toEqual({ _tag: 'Added', id: 'x' })
11
+ })
12
+
13
+ test('an event carries its reflectable manifest and tag', () => {
14
+ class Added extends Event.make('Added', S.Struct({ id: S.String })) {}
15
+ expect(Added.tag).toBe('Added')
16
+ expect(Added.manifest.kind).toBe('Event')
17
+ expect(Added.manifest.name).toBe('Added')
18
+ })
19
+
20
+ test('empty-payload events construct to just their tag', () => {
21
+ class Pinged extends Event.make('Pinged', S.Struct({})) {}
22
+ expect(Event.construct(Pinged, {})).toEqual({ _tag: 'Pinged' })
23
+ })
@@ -0,0 +1,82 @@
1
+ import { type Cause, Duration, Effect, Exit, Layer, ManagedRuntime, Scope } from 'effect'
2
+ import { Schema as S } from 'effect'
3
+ import { expect, test } from 'vitest'
4
+ import * as Composition from '../compose/composition'
5
+ import { ui } from '../compose/ui'
6
+ import * as Event from '../event/event'
7
+ import * as Reducer from '../reducer/reducer'
8
+ import * as State from '../state/state'
9
+ import { publish } from '../runtime/bus'
10
+ import { Engine, Reducers } from '../runtime/loop'
11
+ import * as Feature from './feature'
12
+ import { type EngineServices, featureModule, mountFeature } from './feature'
13
+
14
+ // A self-contained feature: a Count state + a reducer that folds Tick. The base
15
+ // seeds Count; the logic provides the reducer over it and leaves the engine
16
+ // (Reducers registry) OPEN, so `mountFeature` builds it against the live engine.
17
+ class Tick extends Event.make('Tick', S.Struct({})) {}
18
+ class Count extends State.make('count', S.Number) {}
19
+ class CountReducer extends Reducer.make('CountReducer', { states: [Count], events: [Tick] }) {}
20
+
21
+ const mod = featureModule(
22
+ [],
23
+ Reducer.live(CountReducer, (n) => n + 1).pipe(Layer.provideMerge(State.live(Count, 0))),
24
+ )
25
+
26
+ // A trivial composition to hang the feature off (definitions only).
27
+ class CtrUi extends ui('CtrUi')<{ props: {}; events: {} }>() {}
28
+ class CtrComp extends Composition.make('CtrComp', { title: 'Counter', ui: CtrUi }) {}
29
+
30
+ class CounterFeature extends Feature.make('counter', {
31
+ composition: CtrComp,
32
+ module: mod,
33
+ boot: [Event.construct(Tick, {})],
34
+ }) {}
35
+
36
+ // Poll a read until it satisfies a predicate (the loop drains on a forked fiber).
37
+ const waitUntil = <A, R>(
38
+ read: Effect.Effect<A, never, R>,
39
+ pred: (a: A) => boolean,
40
+ ): Effect.Effect<A, Cause.TimeoutException, R> =>
41
+ Effect.flatMap(read, (a) =>
42
+ pred(a)
43
+ ? Effect.succeed(a)
44
+ : Effect.flatMap(Effect.sleep(Duration.millis(1)), () => waitUntil(read, pred)),
45
+ ).pipe(Effect.timeout(Duration.seconds(2)))
46
+
47
+ test('a mounted feature registers on the shared loop, boots, and folds dispatched events', async () => {
48
+ const runtime = ManagedRuntime.make(Engine)
49
+ try {
50
+ await runtime.runPromise(
51
+ Effect.gen(function* () {
52
+ const engineContext = yield* Effect.context<EngineServices>()
53
+ const reducers = yield* Reducers
54
+ const baseline = reducers.entries.length
55
+
56
+ const scope = yield* Scope.make()
57
+ const ctx = yield* mountFeature(CounterFeature.binding, engineContext).pipe(
58
+ Effect.provideService(Scope.Scope, scope),
59
+ )
60
+ // Registered into the SHARED registry.
61
+ expect(reducers.entries.length).toBe(baseline + 1)
62
+
63
+ // boot dispatched Tick → Count folds to 1 on the shared loop.
64
+ const booted = yield* waitUntil(Count.pipe(Effect.provide(ctx)), (n) => n === 1)
65
+ expect(booted).toBe(1)
66
+
67
+ // A further dispatch on the shared bus folds again → 2.
68
+ yield* publish('High', Event.construct(Tick, {}))
69
+ const folded = yield* waitUntil(Count.pipe(Effect.provide(ctx)), (n) => n === 2)
70
+ expect(folded).toBe(2)
71
+
72
+ // Unmount: closing the feature scope unregisters its reducer — the entry is
73
+ // reclaimed, not left folding onto an orphaned store.
74
+ yield* Scope.close(scope, Exit.succeed(undefined))
75
+ expect(reducers.entries.length).toBe(baseline)
76
+ expect(reducers.byTag.get('Tick')).toBeUndefined()
77
+ }),
78
+ )
79
+ } finally {
80
+ await runtime.dispose()
81
+ }
82
+ })
@@ -0,0 +1,60 @@
1
+ import { Effect, Layer } from 'effect'
2
+ import { expect, test } from 'vitest'
3
+ import * as Composition from '../compose/composition'
4
+ import { ui } from '../compose/ui'
5
+ import * as Feature from './feature'
6
+ import { featureModule, isFeature, isFeatureBinding, lazyImport } from './feature'
7
+
8
+ // Minimal composition surface to hang features off — definitions only, no logic.
9
+ class TestUi extends ui('TestUi')<{ props: {}; events: {} }>() {}
10
+ class TestComp extends Composition.make('TestComp', { title: 'Test', ui: TestUi }) {}
11
+ class FailComp extends Composition.make('FailComp', { title: 'Fail', ui: TestUi }) {}
12
+
13
+ // A trivial loaded module: empty layer, no shared requirements.
14
+ const mod = featureModule([], Layer.empty)
15
+
16
+ class LazyFeature extends Feature.make('lazyFeature', {
17
+ loadingStrategy: 'lazy',
18
+ composition: TestComp,
19
+ load: lazyImport(() => Promise.resolve({ default: mod })),
20
+ placeholder: { loading: TestComp, failed: FailComp },
21
+ }) {}
22
+
23
+ class EagerFeature extends Feature.make('eagerFeature', {
24
+ composition: TestComp,
25
+ module: mod,
26
+ }) {}
27
+
28
+ test('a lazy feature reflects as a Feature manifest with placeholders, no chunk loaded', () => {
29
+ expect(LazyFeature.manifest.kind).toBe('Feature')
30
+ expect(LazyFeature.manifest.name).toBe('lazyFeature')
31
+ expect(LazyFeature.manifest.strategy).toBe('lazy')
32
+ expect(LazyFeature.manifest.composition.name).toBe('TestComp')
33
+ expect(LazyFeature.manifest.placeholder?.loading.name).toBe('TestComp')
34
+ expect(LazyFeature.manifest.placeholder?.failed.name).toBe('FailComp')
35
+ expect(LazyFeature.eagerModule).toBeUndefined()
36
+ })
37
+
38
+ test('an eager feature reflects as default strategy with its module available', () => {
39
+ expect(EagerFeature.manifest.strategy).toBe('default')
40
+ expect(EagerFeature.manifest.placeholder).toBeUndefined()
41
+ expect(EagerFeature.eagerModule).toBe(mod)
42
+ })
43
+
44
+ test('isFeature / isFeatureBinding discriminate', () => {
45
+ expect(isFeature(LazyFeature)).toBe(true)
46
+ expect(isFeature(TestComp)).toBe(false)
47
+ expect(isFeature(null)).toBe(false)
48
+ expect(isFeatureBinding(LazyFeature.binding)).toBe(true)
49
+ expect(isFeatureBinding(TestComp)).toBe(false)
50
+ })
51
+
52
+ test('load is an Effect (not a thenable) that yields the module and its requires', async () => {
53
+ // No `.then` on `load` — it is an Effect, run on the Effect runtime.
54
+ expect(typeof (LazyFeature.load as { then?: unknown }).then).toBe('undefined')
55
+ const loaded = await Effect.runPromise(LazyFeature.load)
56
+ expect(loaded.requires).toEqual([])
57
+ expect(loaded).toBe(mod)
58
+ // default strategy resolves immediately to its module.
59
+ expect(await Effect.runPromise(EagerFeature.load)).toBe(mod)
60
+ })
@@ -0,0 +1,108 @@
1
+ // Type-level proofs enforced by `tsc --noEmit` over `src` (not a vitest file).
2
+ // These guard the cast-free seam: if a guarantee regresses, a `@ts-expect-error`
3
+ // goes unused or an assignment fails, and `tsc` breaks.
4
+
5
+ import { Layer, Schema as S } from 'effect'
6
+ import type { Store } from '../internal/store'
7
+ import * as Composition from '../compose/composition'
8
+ import { provide } from '../compose/provide'
9
+ import { type SlotChild, type SlotClass, slot } from '../compose/slot'
10
+ import { type Contract, type UiClass, ui } from '../compose/ui'
11
+ import * as State from '../state/state'
12
+ import * as StateGroup from '../state/stateGroup'
13
+ import { type EngineServices, type FeatureModule, featureModule, lazyImport } from './feature'
14
+ import * as Feature from './feature'
15
+
16
+ const FeedStateBase: State.StateClass<'feed', string> = State.make('feed', S.String)
17
+ class FeedState extends FeedStateBase {}
18
+ const FilterStateBase: State.StateClass<'filter', string> = State.make('filter', S.String)
19
+ class FilterState extends FilterStateBase {}
20
+ const TodosStatesBase: StateGroup.StateGroupClass<readonly [typeof FeedState, typeof FilterState]> =
21
+ StateGroup.make(FeedState, FilterState)
22
+ class TodosStates extends TodosStatesBase {}
23
+
24
+ // --- featureModule: the covariant-RIn bound (cast-free requirement honesty) ---
25
+
26
+ // A feature layer that reads FeedState's store and the shared engine — nothing else.
27
+ declare const readsFeed: Layer.Layer<{ readonly _out: true }, never, Store<string> | EngineServices>
28
+
29
+ // POSITIVE: declaring the State it reads in `requires` covers the read — compiles.
30
+ export const okState: FeatureModule<{ readonly _out: true }, readonly [typeof FeedState]> =
31
+ featureModule([FeedState], readsFeed)
32
+
33
+ // POSITIVE: a StateGroup contributes its members' stores via `ProvidedBy` — compiles.
34
+ export const okGroup: FeatureModule<{ readonly _out: true }, readonly [typeof TodosStates]> =
35
+ featureModule([TodosStates], readsFeed)
36
+
37
+ // NEGATIVE: empty `requires` provides only the engine, not Store<string>; covariant
38
+ // `RIn` makes the layer unassignable to the declared bound.
39
+ export const badEmpty: FeatureModule<{ readonly _out: true }, readonly []> =
40
+ // @ts-expect-error feature layer reads a store it does not declare in `requires`
41
+ featureModule([], readsFeed)
42
+
43
+ // --- provide(slot, Feature): RIn surfacing + composition match ---
44
+
45
+ const AppUiBase: UiClass<{ props: { readonly a: string }; events: {} }> = ui('AppUi')<{
46
+ props: { readonly a: string }
47
+ events: {}
48
+ }>()
49
+ class AppUi extends AppUiBase {}
50
+ const AppCompBase: Composition.CompositionClass<{ readonly a: string }, Contract<typeof AppUi>> =
51
+ Composition.make('AppComp', {
52
+ title: 'App',
53
+ props: S.Struct({ a: S.String }),
54
+ ui: AppUi,
55
+ })
56
+ class AppComp extends AppCompBase {}
57
+ const AppSlotBase: SlotClass<typeof AppComp> = slot('App')<typeof AppComp>()
58
+ class AppSlot extends AppSlotBase {}
59
+
60
+ const AppFeatureBase: Feature.FeatureClass<
61
+ { readonly a: string },
62
+ Contract<typeof AppUi>,
63
+ never,
64
+ readonly []
65
+ > = Feature.make('appFeature', {
66
+ loadingStrategy: 'lazy',
67
+ composition: AppComp,
68
+ load: lazyImport(() => Promise.resolve({ default: featureModule([], Layer.empty) })),
69
+ placeholder: { loading: AppComp, failed: AppComp },
70
+ })
71
+ class AppFeature extends AppFeatureBase {}
72
+
73
+ // POSITIVE: the wired layer's open `RIn` is exactly `EngineServices` (requires=[]),
74
+ // so a scene must provide `Core` — surfaced cast-free by the overload.
75
+ export const wired: Layer.Layer<SlotChild, never, EngineServices> = provide(AppSlot, AppFeature)
76
+
77
+ // A feature over a DIFFERENT contract must not fill `AppSlot`.
78
+ const OtherUiBase: UiClass<{ props: { readonly n: number }; events: {} }> = ui('OtherUi')<{
79
+ props: { readonly n: number }
80
+ events: {}
81
+ }>()
82
+ class OtherUi extends OtherUiBase {}
83
+ const OtherCompBase: Composition.CompositionClass<{ readonly n: number }, Contract<typeof OtherUi>> =
84
+ Composition.make('OtherComp', {
85
+ title: 'Other',
86
+ props: S.Struct({ n: S.Number }),
87
+ ui: OtherUi,
88
+ })
89
+ class OtherComp extends OtherCompBase {}
90
+ const OtherFeatureBase: Feature.FeatureClass<
91
+ { readonly n: number },
92
+ Contract<typeof OtherUi>,
93
+ never,
94
+ readonly []
95
+ > = Feature.make('otherFeature', {
96
+ loadingStrategy: 'lazy',
97
+ composition: OtherComp,
98
+ load: lazyImport(() => Promise.resolve({ default: featureModule([], Layer.empty) })),
99
+ placeholder: { loading: OtherComp, failed: OtherComp },
100
+ })
101
+ class OtherFeature extends OtherFeatureBase {}
102
+
103
+ // NEGATIVE: OtherFeature's composition props don't match AppSlot's child composition.
104
+ // @ts-expect-error feature composition does not match the slot's child type
105
+ export const mismatched: Layer.Layer<SlotChild, never, EngineServices> = provide(
106
+ AppSlot,
107
+ OtherFeature,
108
+ )