@playfast/reform-proof 1.2.1 → 1.4.0

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 (77) hide show
  1. package/dist/assert.d.ts +15 -0
  2. package/dist/assert.d.ts.map +1 -0
  3. package/dist/assert.js +39 -0
  4. package/dist/assert.js.map +1 -0
  5. package/dist/engine.d.ts +16 -0
  6. package/dist/engine.d.ts.map +1 -0
  7. package/dist/engine.js +123 -0
  8. package/dist/engine.js.map +1 -0
  9. package/dist/engineMounted.d.ts +18 -0
  10. package/dist/engineMounted.d.ts.map +1 -0
  11. package/dist/engineMounted.js +96 -0
  12. package/dist/engineMounted.js.map +1 -0
  13. package/dist/engineMounts.d.ts +13 -0
  14. package/dist/engineMounts.d.ts.map +1 -0
  15. package/dist/engineMounts.js +116 -0
  16. package/dist/engineMounts.js.map +1 -0
  17. package/dist/engineRender.d.ts +10 -0
  18. package/dist/engineRender.d.ts.map +1 -0
  19. package/dist/engineRender.js +64 -0
  20. package/dist/engineRender.js.map +1 -0
  21. package/dist/engineSink.d.ts +71 -0
  22. package/dist/engineSink.d.ts.map +1 -0
  23. package/dist/engineSink.js +73 -0
  24. package/dist/engineSink.js.map +1 -0
  25. package/dist/engineTree.d.ts +63 -0
  26. package/dist/engineTree.d.ts.map +1 -0
  27. package/dist/engineTree.js +137 -0
  28. package/dist/engineTree.js.map +1 -0
  29. package/dist/engineTreeDriver.d.ts +5 -0
  30. package/dist/engineTreeDriver.d.ts.map +1 -0
  31. package/dist/engineTreeDriver.js +187 -0
  32. package/dist/engineTreeDriver.js.map +1 -0
  33. package/dist/engineTreeFacade.d.ts +5 -0
  34. package/dist/engineTreeFacade.d.ts.map +1 -0
  35. package/dist/engineTreeFacade.js +124 -0
  36. package/dist/engineTreeFacade.js.map +1 -0
  37. package/dist/engineTreeTypes.d.ts +80 -0
  38. package/dist/engineTreeTypes.d.ts.map +1 -0
  39. package/dist/engineTreeTypes.js +11 -0
  40. package/dist/engineTreeTypes.js.map +1 -0
  41. package/dist/errors.d.ts +39 -0
  42. package/dist/errors.d.ts.map +1 -0
  43. package/dist/errors.js +30 -0
  44. package/dist/errors.js.map +1 -0
  45. package/dist/facade.d.ts +54 -0
  46. package/dist/facade.d.ts.map +1 -0
  47. package/dist/facade.js +2 -0
  48. package/dist/facade.js.map +1 -0
  49. package/dist/fingerprint.d.ts +2 -0
  50. package/dist/fingerprint.d.ts.map +1 -0
  51. package/dist/fingerprint.js +78 -0
  52. package/dist/fingerprint.js.map +1 -0
  53. package/dist/index.d.ts +88 -0
  54. package/dist/index.d.ts.map +1 -0
  55. package/dist/index.js +73 -0
  56. package/dist/index.js.map +1 -0
  57. package/dist/product.d.ts +56 -0
  58. package/dist/product.d.ts.map +1 -0
  59. package/dist/product.js +35 -0
  60. package/dist/product.js.map +1 -0
  61. package/dist/proofCase.d.ts +24 -0
  62. package/dist/proofCase.d.ts.map +1 -0
  63. package/dist/proofCase.js +2 -0
  64. package/dist/proofCase.js.map +1 -0
  65. package/dist/runner.d.ts +15 -0
  66. package/dist/runner.d.ts.map +1 -0
  67. package/dist/runner.js +13 -0
  68. package/dist/runner.js.map +1 -0
  69. package/package.json +17 -5
  70. package/src/engine.ts +17 -13
  71. package/src/engineMounted.ts +10 -12
  72. package/src/engineSink.ts +15 -1
  73. package/src/engineTreeFacade.ts +48 -13
  74. package/src/fingerprint.ts +45 -10
  75. package/src/index.ts +1 -1
  76. package/src/proof-attribution.test.ts +210 -0
  77. package/src/test-clock.test.ts +16 -6
@@ -1,4 +1,6 @@
1
+ import * as Arr from 'effect/Array'
1
2
  import * as Option from 'effect/Option'
3
+ import * as Order from 'effect/Order'
2
4
 
3
5
  const readPropertyOption = Option.liftThrowable((target: object, key: PropertyKey): unknown =>
4
6
  Reflect.get(target, key),
@@ -14,7 +16,15 @@ const propertyKeyFingerprint = (key: PropertyKey): string =>
14
16
  ? `number-key:${String(key)}`
15
17
  : `key:${key.length}:${key}`
16
18
 
17
- const valueFingerprint = (candidate: unknown, seen: WeakSet<object>): string => {
19
+ interface Walk {
20
+ readonly seen: WeakSet<object>
21
+ // Printed sub-fingerprints, so a shared reference is walked once. Unwinding `seen`
22
+ // made the walk follow every *path* rather than every node, which on a DAG that
23
+ // shares a child two ways doubles the work per level — a deep one hangs.
24
+ readonly memo: WeakMap<object, string>
25
+ }
26
+
27
+ const valueFingerprint = (candidate: unknown, walk: Walk): string => {
18
28
  if (typeof candidate === 'bigint') {
19
29
  return `bigint:${String(candidate)}`
20
30
  }
@@ -39,12 +49,32 @@ const valueFingerprint = (candidate: unknown, seen: WeakSet<object>): string =>
39
49
  if (candidate === null) {
40
50
  return 'null'
41
51
  }
42
- if (seen.has(candidate)) {
52
+ if (walk.seen.has(candidate)) {
43
53
  return '[Circular]'
44
54
  }
45
- seen.add(candidate)
55
+ const remembered = walk.memo.get(candidate)
56
+ if (remembered !== undefined) {
57
+ return remembered
58
+ }
59
+ // `seen` marks the path currently being walked, not everything ever visited: it
60
+ // is unwound below. Without that, a value that merely repeats a reference — the
61
+ // same config object under two keys, a DAG rather than a cycle — reads as
62
+ // `[Circular]` on its second appearance, so two equal values fingerprint
63
+ // differently and `toEqual` fails on them.
64
+ walk.seen.add(candidate)
65
+ const printed = structuralFingerprint(candidate, walk)
66
+ walk.seen.delete(candidate)
67
+ // Only a print that did not depend on where the walk had been is reusable: one
68
+ // containing `[Circular]` describes this path, not this value.
69
+ if (!printed.includes('[Circular]')) {
70
+ walk.memo.set(candidate, printed)
71
+ }
72
+ return printed
73
+ }
74
+
75
+ const structuralFingerprint = (candidate: object, walk: Walk): string => {
46
76
  if (Array.isArray(candidate)) {
47
- return `[${candidate.map((arrayEntry) => valueFingerprint(arrayEntry, seen)).join(',')}]`
77
+ return `[${candidate.map((arrayEntry) => valueFingerprint(arrayEntry, walk)).join(',')}]`
48
78
  }
49
79
  if (candidate instanceof Date) {
50
80
  return `date:${String(candidate.getTime())}`
@@ -53,21 +83,26 @@ const valueFingerprint = (candidate: unknown, seen: WeakSet<object>): string =>
53
83
  return `map:[${Array.from(
54
84
  candidate,
55
85
  ([mapKey, mapEntry]) =>
56
- `${valueFingerprint(mapKey, seen)}=>${valueFingerprint(mapEntry, seen)}`,
86
+ `${valueFingerprint(mapKey, walk)}=>${valueFingerprint(mapEntry, walk)}`,
57
87
  ).join(',')}]`
58
88
  }
59
89
  if (candidate instanceof Set) {
60
- return `set:[${Array.from(candidate, (setEntry) => valueFingerprint(setEntry, seen)).join(
90
+ return `set:[${Array.from(candidate, (setEntry) => valueFingerprint(setEntry, walk)).join(
61
91
  ',',
62
92
  )}]`
63
93
  }
64
- return `{${Reflect.ownKeys(candidate)
94
+ // Sorted by key: an object is the same value however its keys were inserted, so
95
+ // reordering fields in a composition's source must not break a passing proof.
96
+ return `{${Arr.sortWith(
97
+ Reflect.ownKeys(candidate).map((key) => ({ key, printed: propertyKeyFingerprint(key) })),
98
+ (entry) => entry.printed,
99
+ Order.string,
100
+ )
65
101
  .map(
66
- (key) =>
67
- `${propertyKeyFingerprint(key)}:${valueFingerprint(readProperty(candidate, key), seen)}`,
102
+ (entry) => `${entry.printed}:${valueFingerprint(readProperty(candidate, entry.key), walk)}`,
68
103
  )
69
104
  .join(',')}}`
70
105
  }
71
106
 
72
107
  export const formatFingerprint = (fingerprintInput: unknown): string =>
73
- valueFingerprint(fingerprintInput, new WeakSet())
108
+ valueFingerprint(fingerprintInput, { seen: new WeakSet(), memo: new WeakMap() })
package/src/index.ts CHANGED
@@ -29,6 +29,7 @@ export {
29
29
  proofLayer,
30
30
  } from './engine'
31
31
  export type {
32
+ DispatchedAction,
32
33
  MountedFacade,
33
34
  MountedSlotFacade,
34
35
  MountedSlotFacadesOf,
@@ -230,4 +231,3 @@ export const Proof: {
230
231
  readonly driver: typeof driver
231
232
  readonly withTestClock: typeof withTestClock
232
233
  } = { implement, implementVia, suite, run, runEffect, driver, withTestClock }
233
-
@@ -0,0 +1,210 @@
1
+ import { expect, it } from '@effect/vitest'
2
+ import { Effect, Layer, Ref, Schema as S } from 'effect'
3
+ import {
4
+ Composition,
5
+ each,
6
+ Engine,
7
+ Event,
8
+ mount,
9
+ provide,
10
+ Reducer,
11
+ scene,
12
+ slot,
13
+ State,
14
+ StateGroup,
15
+ type Trigger,
16
+ Ui,
17
+ ui,
18
+ } from '@playfast/reform'
19
+ import { Product, Proof, ProductRequirement, expect as proofExpect } from './index'
20
+ import type { Proof as ProofValue } from './index'
21
+
22
+ // A list of keyed children, each able to remove itself, over a root that owns its
23
+ // own `bump`. The child contract deliberately exposes an event with the SAME name
24
+ // (`bump`) backed by a DIFFERENT domain event, so "which node was this credited
25
+ // to?" is observable rather than a matter of taste.
26
+
27
+ const Todo = S.Struct({ id: S.String, label: S.String })
28
+
29
+ class HuntTodos extends State.make('huntTodos', S.Array(Todo)) {}
30
+ class HuntBumps extends State.make('huntBumps', S.Number) {}
31
+ class HuntStates extends StateGroup.make(HuntTodos, HuntBumps) {}
32
+
33
+ class HuntRemoved extends Event.make('HuntRemoved', S.Struct({ id: S.String })) {}
34
+ class HuntItemBumped extends Event.make('HuntItemBumped', S.Struct({ id: S.String })) {}
35
+ class HuntRootBumped extends Event.make('HuntRootBumped', S.Struct({})) {}
36
+
37
+ class HuntRemoveReducer extends Reducer.make('HuntRemoveReducer', {
38
+ states: [HuntTodos],
39
+ events: [HuntRemoved],
40
+ }) {}
41
+ const HuntRemoveReducerLive = Reducer.live(HuntRemoveReducer, (todos, event) =>
42
+ todos.filter((todo) => todo.id !== event.id),
43
+ )
44
+
45
+ class HuntRootBumpReducer extends Reducer.make('HuntRootBumpReducer', {
46
+ states: [HuntBumps],
47
+ events: [HuntRootBumped],
48
+ }) {}
49
+ const HuntRootBumpReducerLive = Reducer.live(HuntRootBumpReducer, (bumps) => bumps + 1)
50
+
51
+ class HuntItemUi extends ui('HuntItem')<{
52
+ props: { id: string; label: string }
53
+ events: { remove: Trigger<{ id: string }>; bump: Trigger<{ id: string }> }
54
+ }>() {}
55
+ class HuntItem extends Composition.make('HuntItem', {
56
+ title: 'HuntItem',
57
+ props: S.Struct({ id: S.String, label: S.String }),
58
+ events: [HuntRemoved, HuntItemBumped],
59
+ ui: HuntItemUi,
60
+ })<HuntItem>() {}
61
+ const HuntItemLive = Composition.live(HuntItem, function* () {
62
+ const props = yield* HuntItem.props
63
+ const remove = yield* Event.trigger(HuntRemoved)
64
+ const bump = yield* Event.trigger(HuntItemBumped)
65
+ return mount({ props, slots: {}, events: { remove, bump } })
66
+ })
67
+ class HuntItemSlot extends slot('HuntItem')<HuntItemSlot, typeof HuntItem>() {}
68
+
69
+ class HuntListUi extends ui('HuntList')<{
70
+ props: { total: number; bumps: number }
71
+ slots: { Item: HuntItemSlot }
72
+ events: { bump: Trigger<Record<string, never>> }
73
+ }>() {}
74
+ class HuntList extends Composition.make('HuntList', {
75
+ title: 'HuntList',
76
+ states: [HuntStates],
77
+ events: [HuntRootBumped],
78
+ slots: { Item: HuntItemSlot },
79
+ ui: HuntListUi,
80
+ })<HuntList>() {}
81
+ const HuntListLive = Composition.live(HuntList, function* () {
82
+ const todos = yield* StateGroup.select(HuntStates, 'huntTodos')
83
+ const bumps = yield* StateGroup.select(HuntStates, 'huntBumps')
84
+ const bump = yield* Event.trigger(HuntRootBumped)
85
+ return mount({
86
+ props: { total: todos.length, bumps },
87
+ slots: {
88
+ Item: each(todos, {
89
+ key: (todo) => todo.id,
90
+ props: (todo) => ({ id: todo.id, label: todo.label }),
91
+ }),
92
+ },
93
+ events: { bump },
94
+ })
95
+ })
96
+
97
+ const presentations = Layer.mergeAll(
98
+ provide(
99
+ HuntListUi,
100
+ Ui.make(HuntListUi, () => null),
101
+ ),
102
+ provide(
103
+ HuntItemUi,
104
+ Ui.make(HuntItemUi, () => null),
105
+ ),
106
+ )
107
+ const Views = Layer.mergeAll(HuntListLive, HuntItemLive, provide(HuntItemSlot, HuntItem)).pipe(
108
+ Layer.provideMerge(presentations),
109
+ )
110
+ const Logic = Layer.mergeAll(HuntRemoveReducerLive, HuntRootBumpReducerLive).pipe(
111
+ Layer.provideMerge(
112
+ Layer.mergeAll(
113
+ Engine,
114
+ StateGroup.live(HuntStates, {
115
+ huntTodos: [
116
+ { id: 'a', label: 'alpha' },
117
+ { id: 'b', label: 'beta' },
118
+ { id: 'c', label: 'gamma' },
119
+ ],
120
+ huntBumps: 0,
121
+ }),
122
+ ),
123
+ ),
124
+ )
125
+ const HuntScene = scene(HuntList, { provide: [Views.pipe(Layer.provideMerge(Logic))] })
126
+
127
+ class CoversListBump extends ProductRequirement.make(HuntList, 'bumps the list itself', {
128
+ events: ['bump'],
129
+ }) {}
130
+ class HuntProduct extends Product.make(HuntList, { requirements: [CoversListBump] }) {}
131
+
132
+ const runProof = (proof: ProofValue) =>
133
+ Effect.promise(() => Proof.run(Proof.suite(HuntProduct, { proofs: [proof] })))
134
+
135
+ // BUG 1 — engine.ts `missingCoverage` matches a requirement's declared events
136
+ // against a flat Set of event NAMES dispatched anywhere in the tree, so a
137
+ // same-named action on a child composition (a different domain Event entirely)
138
+ // silently satisfies coverage declared on the requirement's own composition.
139
+ it.live('requirement event coverage is not credited to the requirement’s composition', () =>
140
+ Effect.gen(function* () {
141
+ // Control A — a genuine dispatch of the list's own `bump` is covered.
142
+ const rootDispatch = Proof.implement(CoversListBump, HuntScene, function* (app) {
143
+ const after = yield* app.actions.bump({})
144
+ yield* proofExpect(after.bumps).toBe(1)
145
+ })
146
+ const rootResult = yield* runProof(rootDispatch)
147
+ expect(rootResult.results[0]?.error).toBeUndefined()
148
+ expect(rootResult.ok).toBe(true)
149
+
150
+ // Control B — dispatching nothing is reported as uncovered.
151
+ const noDispatch = Proof.implement(CoversListBump, HuntScene, function* (app) {
152
+ yield* app.expectProps({ bumps: 0 })
153
+ })
154
+ const noneResult = yield* runProof(noDispatch)
155
+ expect(noneResult.ok).toBe(false)
156
+ expect(noneResult.results[0]?.error).toContain('never dispatched')
157
+
158
+ // The defect — only the CHILD's `bump` (HuntItemBumped) is dispatched. The
159
+ // proof body itself proves the list's `bump` (HuntRootBumped) never fired,
160
+ // yet the run is reported green with its coverage requirement satisfied.
161
+ const childOnly = Proof.implement(CoversListBump, HuntScene, function* (app) {
162
+ const item = yield* app.slots.Item.first
163
+ yield* item.actions.bump({ id: 'a' })
164
+ yield* app.expectProps({ bumps: 0 })
165
+ })
166
+ const childResult = yield* runProof(childOnly)
167
+ expect(childResult.ok).toBe(false)
168
+ expect(childResult.results[0]?.error).toContain('never dispatched')
169
+ }),
170
+ )
171
+
172
+ // BUG 2 — engineTreeFacade.ts resolves a slot child's "did this node survive the
173
+ // action?" peek by INDEX, so an action that removes a non-last child reports the
174
+ // successor that slid into that index as if those were the acting node's props.
175
+ it.live('an action on a slot child resolves to that child’s own props', () =>
176
+ Effect.gen(function* () {
177
+ const observed = yield* Ref.make<ReadonlyArray<string>>([])
178
+ const removals = Proof.implement(CoversListBump, HuntScene, function* (app) {
179
+ yield* app.actions.bump({})
180
+
181
+ // [a, b, c] — remove the HEAD via its index locator.
182
+ const head = yield* app.slots.Item.at(0)
183
+ const afterHead = yield* head.actions.remove({ id: 'a' })
184
+ yield* Ref.update(observed, (seen) => [...seen, afterHead.id])
185
+
186
+ // [b, c] — remove the TAIL via its index locator (index runs past the end).
187
+ const tail = yield* app.slots.Item.at(1)
188
+ const afterTail = yield* tail.actions.remove({ id: 'c' })
189
+ yield* Ref.update(observed, (seen) => [...seen, afterTail.id])
190
+
191
+ // [b] — remove via the key locator.
192
+ const keyed = yield* app.slots.Item.byKey('b')
193
+ const afterKeyed = yield* keyed.actions.remove({ id: 'b' })
194
+ yield* Ref.update(observed, (seen) => [...seen, afterKeyed.id])
195
+ })
196
+ const result = yield* runProof(removals)
197
+ expect(result.results[0]?.error).toBeUndefined()
198
+
199
+ const seen = yield* Ref.get(observed)
200
+ expect(seen.length).toBe(3)
201
+ // Control A — removing the LAST child leaves nothing at that index, so the
202
+ // harness correctly reports the acting node's last props.
203
+ expect(seen[1]).toBe('c')
204
+ // Control B — the key locator misses after removal, likewise correct.
205
+ expect(seen[2]).toBe('b')
206
+ // The defect — removing a NON-last child still finds "something" at index 0,
207
+ // so the action resolves to sibling `b`'s props instead of `a`'s.
208
+ expect(seen[0]).toBe('a')
209
+ }),
210
+ )
@@ -66,7 +66,10 @@ const FlashLive = Composition.live(Flash, function* () {
66
66
  return mount({ props: { flash }, slots: {}, events: { submit } })
67
67
  })
68
68
 
69
- const presentations = provide(FlashUi, Ui.make(FlashUi, () => null))
69
+ const presentations = provide(
70
+ FlashUi,
71
+ Ui.make(FlashUi, () => null),
72
+ )
70
73
  const Views = FlashLive.pipe(Layer.provideMerge(presentations))
71
74
  const Logic = Layer.mergeAll(EndFlashLive, FlashTimerLive, Channel.live(FlashLane)).pipe(
72
75
  Layer.provideMerge(Layer.mergeAll(Engine, StateGroup.live(FlashStates, { flash: true }))),
@@ -83,13 +86,20 @@ class FlashProduct extends Product.make(Flash, { requirements: [ClearsFlash] })
83
86
 
84
87
  describe('Proof.withTestClock', () => {
85
88
  test('app.advance elapses a product timer without spending real time', async () => {
89
+ // An hour of product time, not the 1500ms window. The ratio is what keeps this an
90
+ // assertion about the clock rather than about the runner: virtual time costs the
91
+ // same whether it is a second or an hour, so the budget below sits ~15x above what
92
+ // this harness really spends (measured 370-710ms) and ~360x below what the real
93
+ // clock would charge. The 750ms budget it replaces sat inside that measured range,
94
+ // which is why it failed on a loaded runner.
95
+ const LONG = Duration.hours(1)
86
96
  const proof = Proof.implement(ClearsFlash, VirtualScene, function* (app) {
87
97
  yield* proofExpect((yield* app.props).flash).toBe(true)
88
98
  yield* app.actions.submit({})
89
99
  // The timer is armed but no virtual time has passed, so the flash still shows.
90
100
  // On the real clock this frame is a race; here it is a fact.
91
101
  yield* proofExpect((yield* app.props).flash).toBe(true)
92
- yield* app.advance(FLASH)
102
+ yield* app.advance(LONG)
93
103
  yield* proofExpect((yield* app.props).flash).toBe(false)
94
104
  })
95
105
 
@@ -99,10 +109,10 @@ describe('Proof.withTestClock', () => {
99
109
 
100
110
  expect(result.results.map((entry) => entry.error)).toEqual([undefined])
101
111
  expect(result.ok).toBe(true)
102
- // The assertion that matters: 1500ms of product time cost a fraction of it in
103
- // real time. Generous enough not to flake on a loaded runner, tight enough that
104
- // a regression to the real clock (>= 1500ms) fails here.
105
- expect(elapsed).toBeLessThan(750)
112
+ // The assertion that matters: an hour of product time cost well under a second of
113
+ // real time. A regression to the real clock cannot squeeze past this — it would
114
+ // have to finish an hour of sleeping in ten.
115
+ expect(elapsed).toBeLessThan(10_000)
106
116
  })
107
117
 
108
118
  test('the timer does not fire on its own — only advancing moves it', async () => {