@playfast/reform-proof 0.1.0 → 1.1.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.
@@ -0,0 +1,34 @@
1
+ import { Effect } from 'effect'
2
+ import { SETTLE_MAX_RENDERS, SETTLE_STEP, settleDrain } from './sink'
3
+ import type { SettleProgress } from './treeBindings'
4
+ import type { TreeRenderState } from './runtimeTreeTypes'
5
+
6
+ export const makeTreeSettle: (
7
+ render: () => TreeRenderState,
8
+ ) => Effect.Effect<void, never, never> = Effect.fn('makeTreeSettle')(function* (
9
+ render: () => TreeRenderState,
10
+ ): Effect.fn.Return<void, never, never> {
11
+ yield* settleDrain
12
+ const first = render()
13
+ yield* Effect.iterate(
14
+ {
15
+ previous: first.fingerprint,
16
+ remaining: SETTLE_MAX_RENDERS,
17
+ stable: false,
18
+ },
19
+ {
20
+ while: (progress: SettleProgress) => !progress.stable && progress.remaining > 0,
21
+ body: (progress) =>
22
+ Effect.gen(function* () {
23
+ yield* settleDrain
24
+ yield* Effect.sleep(SETTLE_STEP)
25
+ const current = render()
26
+ return {
27
+ previous: current.fingerprint,
28
+ remaining: progress.remaining - 1,
29
+ stable: current.fingerprint === progress.previous,
30
+ }
31
+ }),
32
+ },
33
+ )
34
+ })
@@ -0,0 +1,99 @@
1
+ import { Effect, Match, Option, Record as Rec } from 'effect'
2
+ import {
3
+ type CompositionClass,
4
+ type FeatureBinding,
5
+ type RuntimeHandle,
6
+ type SlotFill,
7
+ type Trigger,
8
+ } from '@playfast/reform'
9
+ import type { MountedFacade } from './runtimeFacade'
10
+ import { uiNameOf } from './sink'
11
+
12
+ export type FeatureMountState =
13
+ | { readonly _tag: 'Loading' }
14
+ | { readonly _tag: 'Live'; readonly runtime: RuntimeHandle }
15
+ | { readonly _tag: 'Failed'; readonly error: unknown }
16
+
17
+ export interface TreeFeatureMount {
18
+ readonly id: string
19
+ readonly binding: FeatureBinding
20
+ readonly parent: RuntimeHandle
21
+ readonly depth: number
22
+ readonly props: unknown
23
+ attempt: number
24
+ state: FeatureMountState
25
+ dispose: () => void
26
+ }
27
+
28
+ export interface TreeNode {
29
+ readonly path: string
30
+ readonly depth: number
31
+ readonly key: Option.Option<string>
32
+ readonly comp: CompositionClass<unknown>
33
+ readonly props: unknown
34
+ readonly events: Record<string, Trigger<unknown>>
35
+ readonly slots: Readonly<Record<string, ReadonlyArray<TreeNode>>>
36
+ }
37
+
38
+ export interface TreeRenderState {
39
+ readonly root: TreeNode
40
+ readonly fingerprint: string
41
+ }
42
+
43
+ export interface RuntimeTreeFacade {
44
+ readonly facade: MountedFacade
45
+ readonly settle: Effect.Effect<void, never, never>
46
+ dispose(): void
47
+ }
48
+
49
+ export interface TreeDriver {
50
+ readonly render: () => TreeRenderState
51
+ readonly settle: Effect.Effect<void, never, never>
52
+ readonly dispose: () => void
53
+ }
54
+
55
+ export interface MountIdentityInput {
56
+ readonly parent: RuntimeHandle
57
+ readonly parentPath: string
58
+ readonly slotName: string
59
+ readonly key: string
60
+ readonly binding: FeatureBinding
61
+ }
62
+
63
+ export interface FeatureRecordInput {
64
+ readonly id: string
65
+ readonly parent: RuntimeHandle
66
+ readonly binding: FeatureBinding
67
+ readonly depth: number
68
+ readonly props: unknown
69
+ }
70
+
71
+ export interface RenderCompositionInput {
72
+ readonly runtime: RuntimeHandle
73
+ readonly comp: CompositionClass<unknown>
74
+ readonly props: unknown
75
+ readonly key: Option.Option<string>
76
+ readonly path: string
77
+ readonly depth: number
78
+ readonly seen: Set<string>
79
+ }
80
+
81
+ export const encodeIdentityPart = (part: string): string => `${part.length}:${part}`
82
+
83
+ export const fillEntries = (
84
+ slotName: string,
85
+ fill: SlotFill<unknown>,
86
+ ): ReadonlyArray<{ readonly key: string; readonly props: unknown }> =>
87
+ Match.value(fill).pipe(
88
+ Match.when({ _tag: 'Each' }, (each) => each.items),
89
+ Match.when({ _tag: 'One' }, (oneFill) => [{ key: `${slotName}.0`, props: oneFill.props }]),
90
+ Match.when({ _tag: 'Absent' }, () => []),
91
+ Match.exhaustive,
92
+ )
93
+
94
+ export const treeFingerprint = (node: TreeNode): unknown => [
95
+ uiNameOf(node.comp),
96
+ node.key,
97
+ node.props,
98
+ Rec.map(node.slots, (children) => children.map(treeFingerprint)),
99
+ ]
package/src/sink.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { Effect, Layer, MutableRef } from 'effect'
2
+ import {
3
+ Bus,
4
+ CaptureSink,
5
+ type CaptureSinkApi,
6
+ type CompositionClass,
7
+ type CompositionService,
8
+ type Instrumentation,
9
+ noopInstrumentation,
10
+ type Scene,
11
+ type SlotChild,
12
+ type Structure,
13
+ type Trigger,
14
+ type UiCapture,
15
+ type UiContract,
16
+ } from '@playfast/reform'
17
+
18
+ const SETTLE_DRAIN = 30
19
+ export const SETTLE_STEP = '1 milli'
20
+ export const SETTLE_MAX_RENDERS = 100
21
+
22
+ export const settleDrain: Effect.Effect<void> = Effect.yieldNow().pipe(Effect.repeatN(SETTLE_DRAIN))
23
+
24
+ export const keyed = <V>(get: (key: string) => V): Record<string, V> => {
25
+ const target: Record<string, V> = Object.create(null)
26
+ return new Proxy(target, { get: (_target, key) => get(String(key)) })
27
+ }
28
+
29
+ export const messageOf = (error: unknown): string =>
30
+ error instanceof Error ? error.message : String(error)
31
+
32
+ export const uiNameOf = (comp: CompositionClass<unknown>): string => comp.manifest.ui.manifest.name
33
+
34
+ export const eventsOf = (structure: Structure<UiContract>): Record<string, Trigger<unknown>> => ({
35
+ ...structure.events,
36
+ })
37
+
38
+ export interface Sink {
39
+ readonly api: CaptureSinkApi
40
+ readonly captures: ReadonlyArray<UiCapture>
41
+ readonly instrumentation: Instrumentation
42
+ reset(): void
43
+ }
44
+
45
+ export const makeSink = (instrumentation: Instrumentation = noopInstrumentation): Sink => {
46
+ const captures = MutableRef.make<UiCapture[]>([])
47
+ return {
48
+ api: {
49
+ record: (capture) => {
50
+ MutableRef.update(captures, (current) => [...current, capture])
51
+ },
52
+ },
53
+ get captures() {
54
+ return MutableRef.get(captures)
55
+ },
56
+ instrumentation,
57
+ reset: () => {
58
+ MutableRef.set(captures, [])
59
+ },
60
+ }
61
+ }
62
+
63
+ export type RuntimeServices = CompositionService | SlotChild | Bus
64
+
65
+ export const proofLayer = (scene: Scene, sink: Sink): Layer.Layer<RuntimeServices, never, never> => {
66
+ // oxlint-disable-next-line reform-rules/no-type-assertion -- the one erasure boundary: the scene's host-read `MountedServices` layer widens to the broader `RuntimeServices` a proof resolves
67
+ const sceneLayer = scene.provide.reduce((merged, layer) => Layer.merge(merged, layer)) as unknown as Layer.Layer<
68
+ RuntimeServices,
69
+ never,
70
+ never
71
+ >
72
+ return Layer.provideMerge(sceneLayer, Layer.succeed(CaptureSink, sink.api))
73
+ }
@@ -16,15 +16,6 @@ import {
16
16
  import { describe, expect, test } from 'vitest'
17
17
  import { Product, Proof, ProductRequirement, expect as proofExpect } from './index'
18
18
 
19
- // Plan 03b — events ride ON the structure. A composition whose `live` body returns
20
- // `mount({ props, events })` never calls its view, so the event triggers it acquires
21
- // (`yield* Event.trigger(Bumped)`) are NOT captured by a view's CaptureSink — they
22
- // travel with the frame on `structure.events`. The proof engine's `driveStructure`
23
- // records them into the same capture the view path uses, so `app.actions.bump()`
24
- // resolves and settles identically for a Structure frame. This file is the only
25
- // runtime exercise of the structure EVENT path; the view path stays covered by
26
- // typed-seams.test.ts.
27
-
28
19
  class CountState extends State.make('scount', S.Number) {}
29
20
  class MiniStates extends StateGroup.make(CountState) {}
30
21
  class Bumped extends Event.make('SBumped', S.Struct({})) {}
@@ -41,8 +32,6 @@ class Counter extends Composition.make('SCounter', {
41
32
  events: [Bumped],
42
33
  ui: CounterUi,
43
34
  }) {}
44
- // Body returns a STRUCTURE carrying the bump trigger on `events` — the view is never
45
- // called, so the trigger must ride on the frame for the proof to resolve it.
46
35
  const CounterLive = Composition.live(Counter, function* () {
47
36
  const count = yield* StateGroup.select(MiniStates, 'scount')
48
37
  const bump = yield* Event.trigger(Bumped)
@@ -16,15 +16,6 @@ import {
16
16
  import { describe, expect, test } from 'vitest'
17
17
  import { type Facade, Product, Proof, ProductRequirement, expect as proofExpect } from './index'
18
18
 
19
- // Plan 06 — typed recursive proof navigation. A list parent returns a STRUCTURE
20
- // whose `Item` slot is filled with `each`, so each child rides a stable `key` (the
21
- // SINGLE source of the wire key + family key). The proof facade selects a child by
22
- // that key (`byKey`), filters by computed props (`where`), and reads the fill length
23
- // (`count`) — all against the structure tree, no view evaluated. `byKey` returns a
24
- // facade still typed by the child contract, so `.expectProps` checks the CHILD's
25
- // props and `.slots` would keep descending type-safely.
26
-
27
- // A list of todos lives in state; the parent computes its props + the `each` fill.
28
19
  class TodosState extends State.make(
29
20
  'locTodos',
30
21
  S.Array(S.Struct({ id: S.String, done: S.Boolean })),
@@ -50,8 +41,6 @@ class List extends Composition.make('LocList', {
50
41
  ui: ListUi,
51
42
  }) {}
52
43
 
53
- // The parent body returns pure data: its own props, and the `Item` slot filled with
54
- // one keyed child per todo. No `.map`, no JSX — `each` owns multiplicity + key.
55
44
  const ListLive = Composition.live(List, function* () {
56
45
  const todos = yield* StateGroup.select(TodoStates, 'locTodos')
57
46
  return mount({
@@ -61,9 +50,6 @@ const ListLive = Composition.live(List, function* () {
61
50
  },
62
51
  })
63
52
  })
64
- // A leaf child in structure-as-data echoes the props its parent's `each` fed it
65
- // (read via the `Props` service), so the recorded capture carries the per-item
66
- // props `byKey`/`where`/`expectProps` assert against. No view, hook-free.
67
53
  const ItemLive = Composition.live(Item, function* () {
68
54
  const props: { id: string; done: boolean } = yield* Props
69
55
  return mount({ props, slots: {} })
@@ -94,18 +80,12 @@ class ListProduct extends Product.make(List, { requirements: [Locates] }) {}
94
80
  describe('typed recursive proof navigation (plan 06)', () => {
95
81
  test('byKey / where / count resolve children from the structure tree', async () => {
96
82
  const proof = Proof.implement(Locates, ListScene, function* (app) {
97
- // The parent's computed props.
98
83
  yield* proofExpect((yield* app.props).total).toBe(3)
99
- // count = the fill length.
100
84
  yield* proofExpect(yield* app.slots.Item.count).toBe(3)
101
- // byKey selects the one child mounted under that `each` key; the facade is
102
- // typed by the CHILD contract, so `expectProps` checks the child's props.
103
85
  const second = yield* app.slots.Item.byKey('todo-2')
104
86
  yield* second.expectProps({ id: 'todo-2', done: true })
105
87
  const first = yield* app.slots.Item.byKey('todo-1')
106
88
  yield* first.expectProps({ id: 'todo-1', done: false })
107
- // where filters children by their computed props (predicate typed by the
108
- // CHILD contract — `p.done` is known).
109
89
  const doneItems = yield* app.slots.Item.where((p) => p.done)
110
90
  yield* proofExpect(doneItems.length).toBe(1)
111
91
  yield* doneItems[0]!.expectProps({ id: 'todo-2' })
@@ -123,9 +103,6 @@ describe('typed recursive proof navigation (plan 06)', () => {
123
103
  })
124
104
  })
125
105
 
126
- // Type-only: the `byKey`-selected facade is typed by the Item CHILD contract
127
- // (`{ id, done }`) — recursive typed selection. A wrong prop key in `expectProps`
128
- // is a compile error. Non-exported, never called; exists only to be typechecked.
129
106
  const _negativeTypeCheck = (app: Facade<Ui.Contract<typeof ListUi>>): void => {
130
107
  Proof.implement(Locates, ListScene, function* () {
131
108
  const child = yield* app.slots.Item.byKey('todo-1')
@@ -0,0 +1,121 @@
1
+ import { Effect, Match, Option, Record as Rec } from 'effect'
2
+ import {
3
+ type CompositionClass,
4
+ isFeatureBinding,
5
+ type SlotChild,
6
+ type SlotClass,
7
+ type SlotFill,
8
+ type Structure,
9
+ type UiContract,
10
+ } from '@playfast/reform'
11
+ import { eventsOf, type Sink, uiNameOf } from './sink'
12
+
13
+ export interface Mounted {
14
+ readonly comp: CompositionClass<unknown>
15
+ readonly props: unknown
16
+ readonly key: Option.Option<string>
17
+ }
18
+
19
+ export interface NodeRef {
20
+ readonly name: string
21
+ readonly index: number
22
+ }
23
+
24
+ export interface SettleProgress {
25
+ readonly previous: string
26
+ readonly remaining: number
27
+ readonly stable: boolean
28
+ }
29
+
30
+ export interface PumpStep {
31
+ readonly input: unknown
32
+ readonly index: number
33
+ }
34
+
35
+ export const childComposition = (child: SlotChild): CompositionClass<unknown> =>
36
+ isFeatureBinding(child) ? child.composition : child
37
+
38
+ export const slotsOf = (comp: CompositionClass<unknown>): Record<string, SlotClass> =>
39
+ Option.getOrElse(Option.fromNullable(comp.manifest.slots), () => ({}))
40
+
41
+ const isSlotFill = (candidate: unknown): candidate is SlotFill<unknown> =>
42
+ typeof candidate === 'object' &&
43
+ candidate !== null &&
44
+ '_tag' in candidate &&
45
+ (candidate._tag === 'Each' || candidate._tag === 'One' || candidate._tag === 'Absent')
46
+
47
+ export const structureFills = (
48
+ structure: Structure<UiContract>,
49
+ ): Record<string, SlotFill<unknown>> =>
50
+ Rec.fromEntries(
51
+ Rec.toEntries(structure.slots).flatMap(([slotName, fillValue]) =>
52
+ isSlotFill(fillValue) ? [[slotName, fillValue] as const] : [],
53
+ ),
54
+ )
55
+
56
+ export const collectBindings: (
57
+ root: CompositionClass<unknown>,
58
+ ) => Effect.Effect<Map<SlotClass, CompositionClass<unknown>>, never, SlotChild> = Effect.fn(
59
+ 'collectBindings',
60
+ )(function* (
61
+ root: CompositionClass<unknown>,
62
+ ): Effect.fn.Return<Map<SlotClass, CompositionClass<unknown>>, never, SlotChild> {
63
+ const bindings = new Map<SlotClass, CompositionClass<unknown>>()
64
+ const walk: (comp: CompositionClass<unknown>) => Effect.Effect<void, never, SlotChild> = Effect.fn(
65
+ 'collectBindings.walk',
66
+ )(function* (comp: CompositionClass<unknown>): Effect.fn.Return<void, never, SlotChild> {
67
+ yield* Effect.forEach(Rec.values(slotsOf(comp)), (slotClass) =>
68
+ Effect.gen(function* () {
69
+ if (bindings.has(slotClass)) {
70
+ return
71
+ }
72
+ const child = childComposition(yield* slotClass.tag)
73
+ bindings.set(slotClass, child)
74
+ yield* walk(child)
75
+ }),
76
+ )
77
+ })
78
+ yield* walk(root)
79
+ return bindings
80
+ })
81
+
82
+ const enqueueFill = (
83
+ slotName: string,
84
+ fill: SlotFill<unknown>,
85
+ child: CompositionClass<unknown>,
86
+ ): ReadonlyArray<Mounted> =>
87
+ Match.value(fill).pipe(
88
+ Match.when({ _tag: 'Each' }, (each) =>
89
+ each.items.map((entry) => ({
90
+ comp: child,
91
+ props: entry.props,
92
+ key: Option.some(entry.key),
93
+ })),
94
+ ),
95
+ Match.when({ _tag: 'One' }, (oneFill) => [
96
+ { comp: child, props: oneFill.props, key: Option.some(`${slotName}.0`) },
97
+ ]),
98
+ Match.when({ _tag: 'Absent' }, () => []),
99
+ Match.exhaustive,
100
+ )
101
+
102
+ export const driveStructure = (
103
+ comp: CompositionClass<unknown>,
104
+ structure: Structure<UiContract>,
105
+ key: Option.Option<string>,
106
+ sink: Sink,
107
+ bindings: ReadonlyMap<SlotClass, CompositionClass<unknown>>,
108
+ ): ReadonlyArray<Mounted> => {
109
+ sink.api.record({
110
+ name: uiNameOf(comp),
111
+ props: structure.props,
112
+ events: eventsOf(structure),
113
+ ...(Option.isSome(key) ? { key: key.value } : {}),
114
+ })
115
+ const fills = structureFills(structure)
116
+ return Rec.toEntries(slotsOf(comp)).flatMap(([slotName, slotClass]) => {
117
+ const child = bindings.get(slotClass)
118
+ const fill = fills[slotName]
119
+ return child === undefined || fill === undefined ? [] : enqueueFill(slotName, fill, child)
120
+ })
121
+ }
@@ -18,23 +18,12 @@ import {
18
18
  import { describe, expect, test } from 'vitest'
19
19
  import { Product, Proof, ProductRequirement, expect as proofExpect } from './index'
20
20
 
21
- // Exercises the four type-safety seams closed in this change, each against a
22
- // self-contained mini Counter (the same fixture shape as the stepper test):
23
- // #1 typed seeds — seedScene is keyed/valued by the state tuple
24
- // #2 action results — an action resolves to the settled next props
25
- // #4 typed assertions — app.expectProps is a contract-typed subset match
26
- // #5 event coverage — a requirement's declared events must be dispatched
27
- // Negative cases are compile-time (`@ts-expect-error`) — the whole point is that
28
- // the bad input never reaches runtime.
29
-
30
21
  class CountState extends State.make('count', S.Number) {}
31
22
  class MiniStates extends StateGroup.make(CountState) {}
32
23
  class Bumped extends Event.make('Bumped', S.Struct({})) {}
33
24
  class BumpReducer extends Reducer.make('BumpReducer', { states: [CountState], events: [Bumped] }) {}
34
25
  const BumpReducerLive = Reducer.live(BumpReducer, (n) => n + 1)
35
26
 
36
- // A trivial slot child: a proof runtime resolves slot-bound compositions, so the
37
- // app needs at least one slot for the suite's provide layer to type-close.
38
27
  class LabelUi extends ui('Label')<{ props: { text: string } }>() {}
39
28
  class Label extends Composition.make('Label', { title: 'Label', ui: LabelUi }) {}
40
29
  const LabelLive = Composition.live(Label, function* () {