foldkit-surface 0.13.0 → 0.15.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.
package/README.md CHANGED
@@ -17,11 +17,12 @@ of its own.
17
17
 
18
18
  ## The mental model
19
19
 
20
- ```text
21
- Model Schema → typed field references → Projection → named Surface
22
- application Model ────────────────────────read────────→ feature input
23
- feature Message → application update → next Model
24
- ```
20
+ A Surface is derived in three steps from the application's Model Schema: the
21
+ Schema gives typed field references, a Projection picks the fields a feature
22
+ reads, and a named Surface pairs that Projection with the Messages the feature
23
+ may send. At run time the application's Model is read through the Projection to
24
+ give the feature its input, and the feature's Message goes to the application's
25
+ `update`, which produces the next Model.
25
26
 
26
27
  Declaring or reading a Surface does not dispatch a Message, fetch data, or
27
28
  create a state owner. Its Message list constrains consumers; the application's
@@ -137,11 +138,15 @@ facts other packages attach and interpret, such as the server data a
137
138
  `foldkit-remote` selection needs. Reading never performs I/O.
138
139
 
139
140
  ```ts
140
- Projection.struct({ todos: model.todos, selectedTodoId: model.selectedTodoId })
141
- Projection.of(Model)({ todos: true, selectedTodoId: true }) // from the Schema
142
- Projection.array(projection) // Projection<ReadonlyArray<Root>, ReadonlyArray<Value>>
143
- Projection.option(projection) // Projection<Option<Root>, Option<Value>>
144
- Projection.fromReader(codec, read) // escape hatch for a non-ModelRef value
141
+ const Summary = Projection.struct({
142
+ todos: App.model.todos,
143
+ selectedTodoId: App.model.selectedTodoId,
144
+ })
145
+ const Titles = Projection.of(Todo)({ title: true }) // from the Schema
146
+ Projection.array(Titles) // Projection<ReadonlyArray<Root>, ReadonlyArray<Value>>
147
+ Projection.option(Titles) // Projection<Option<Root>, Option<Value>>
148
+ // Escape hatch for a value that is no ModelRef:
149
+ Projection.fromReader(Schema.Number, (model: typeof Model.Type) => model.todos.length)
145
150
  ```
146
151
 
147
152
  `Projection.struct` accepts `ModelRef`s and nested `Projection`s, so a Surface can
@@ -163,7 +168,11 @@ Open.read(model) // the same array while `model.todos` is
163
168
  ```
164
169
 
165
170
  `on` takes field references and Projections, whose `dependencies` it reads;
166
- `derive` must read nothing else, or it shows what it read last. A Remote read
171
+ `derive` must read nothing else, or it shows what it read last. In
172
+ development, `Projection.derive(on, derive, { verify: import.meta.env?.DEV ===
173
+ true })` checks that: where the memo would hand back its last value, it works
174
+ the value out again, and throws, naming `on`'s paths, when the two differ by
175
+ `Equal.equals`. It doubles the work, so leave it off in production. A Remote read
167
176
  declares no path (its data is named by its metadata), and a `struct` holding
168
177
  one declares only its other entries' paths, so while `on` holds such a read
169
178
  the value is worked out on every read. Name the store's field,
@@ -175,19 +184,40 @@ was last given, and an empty `on` throws, since nothing could tell it to work
175
184
  the value out again. What it returns is `{ dependencies, read }`, which
176
185
  `foldkit-mixins`' `SlotView.region` takes, and a region uses the same rule.
177
186
 
187
+ A Derived can be an entry of `Projection.struct` when it names the Schema of its
188
+ value, `Projection.derive(on, derive, { Model: Schema.Number })`. The struct then
189
+ reads the memoized value, declares the Derived's paths and checks the value
190
+ against `Model` like any entry, so a Surface can show it:
191
+
192
+ ```ts
193
+ const Count = Projection.derive([App.model.todos], model => model.todos.length, {
194
+ Model: Schema.Number,
195
+ })
196
+ const Board = Projection.struct({ count: Count, selected: App.model.selectedTodoId })
197
+ ```
198
+
199
+ A Derived carries no metadata, so the struct plans no requirements for it,
200
+ whatever `on` holds: a Remote read it works from is planned by the Remote read
201
+ itself, not by the struct that shows the value. A Derived without `Model` is a
202
+ type error in a `struct`, and throws if the type is bypassed.
203
+
178
204
  ### Metadata
179
205
 
180
206
  `Metadata` is [`foldkit-metadata`](../metadata/README.md), re-exported so an
181
207
  application needs one import. A package declares its own slot once and reads back only its own entries:
182
208
 
183
209
  ```ts
210
+ import { Metadata } from 'foldkit-surface'
211
+
184
212
  const Flags = Metadata.key<string>('flags', {
185
- merge: flags => [...new Set(flags)],
186
- summarize: flag => flag,
213
+ merge: (flags: ReadonlyArray<string>) => [...new Set(flags)],
214
+ summarize: (flag: string) => flag,
187
215
  })
188
216
 
189
- const beta = Projection.fromReader(Schema.Boolean, readBeta, { metadata: Flags.of('beta') })
190
- Flags.get(Projection.struct({ beta, todos: model.todos }).metadata) // ['beta']
217
+ const beta = Projection.fromReader(Schema.Boolean, (_model: typeof Model.Type) => false, {
218
+ metadata: Flags.of('beta'),
219
+ })
220
+ Flags.get(Projection.struct({ beta, todos: App.model.todos }).metadata) // ['beta']
191
221
  ```
192
222
 
193
223
  Entries are combined per key with that key's `merge` as projections compose, and
@@ -198,6 +228,92 @@ opaque and its entries frozen; only a key's `of` and composition make one.
198
228
  Surface never interprets them; `Surface.inspect` and `Module` show them through
199
229
  `summarize`.
200
230
 
231
+ ### Closure
232
+
233
+ A projection is **closed** when its value after a Message depends only on the
234
+ projection before it and the Message. Sync replays a durable Message over the
235
+ shared slice alone, so the slice has to be closed for it. `Closure.reads` is
236
+ the check: it runs `update` on the Model, and again with every top-level field
237
+ the projection does not depend on reset to `initial`, compares the two
238
+ projections with the projection's codec, and names the fields whose reset
239
+ changed the answer. It returns `[]` for a closed step. Nothing else runs:
240
+ Commands `update` returns are ignored, and nothing is written.
241
+
242
+ ```ts standalone
243
+ import { Schema } from 'effect'
244
+ import { defineMessageUnion } from 'foldkit/message'
245
+ import { Closure, Projection, Surface } from 'foldkit-surface'
246
+
247
+ const Model = Schema.Struct({
248
+ todos: Schema.Array(Schema.Struct({ id: Schema.String, title: Schema.String })),
249
+ filter: Schema.String,
250
+ })
251
+ type Model = typeof Model.Type
252
+ const Message = defineMessageUnion({ ClearedShown: {} })
253
+ const initial: Model = { todos: [], filter: '' }
254
+ const update = (model: Model, _message: typeof Message.Type) => ({
255
+ // Removes the todos whose title is the local `filter`.
256
+ model: { ...model, todos: model.todos.filter(todo => todo.title !== model.filter) },
257
+ })
258
+
259
+ const App = Surface.application({ Model, Message })
260
+ const shown: Model = { todos: [{ id: 'a', title: 'x' }], filter: 'x' }
261
+
262
+ Closure.reads({ initial, update }, Projection.pick(App.model.todos), shown, Message.ClearedShown())
263
+ // ['filter']: the slice after ClearedShown depends on it
264
+ ```
265
+
266
+ It takes a read-only `Projection` as well as a `WritableProjection`, and a
267
+ field that holds any path of the projection is never named. `Sync.mount` runs it
268
+ on every durable dispatch; see the
269
+ [Sync README](https://github.com/doeixd/foldkit-plus/blob/main/packages/sync/README.md#what-makes-a-message-durable).
270
+
271
+ ### A closed Surface
272
+
273
+ `closed: true` on a Surface declares the same property of the whole Surface: for
274
+ a Message in its `messages`, the projection after depends only on the projection
275
+ before and the Message, and no other Message changes it. Declaring it enforces
276
+ nothing at run time; it is a law of the application, tested in a walk.
277
+ `Closure.violations(app, surfaces)` returns a step check,
278
+ `(before, message, after) => violations`, to call at every step of a walk. It
279
+ tests only the Surfaces declared closed, and refuses a closed Surface with
280
+ params, which has no one projection.
281
+
282
+ ```ts standalone
283
+ import { Schema } from 'effect'
284
+ import { defineMessageUnion } from 'foldkit/message'
285
+ import { Closure, Surface } from 'foldkit-surface'
286
+
287
+ const Model = Schema.Struct({ todos: Schema.Array(Schema.String), tally: Schema.Number })
288
+ type Model = typeof Model.Type
289
+ const Message = defineMessageUnion({ Emptied: {}, Counted: {} })
290
+ const initial: Model = { todos: ['a'], tally: 0 }
291
+ const update = (model: Model, message: typeof Message.Type) => ({
292
+ model: Message.match(message, {
293
+ Emptied: () => ({ ...model, todos: [] }),
294
+ Counted: () => ({ ...model, tally: model.tally + 1 }),
295
+ }),
296
+ })
297
+
298
+ const App = Surface.application({ Model, Message, initial, update })
299
+ const Shown = App.surface('Shown', {
300
+ model: ({ model }) => ({ todos: model.todos }),
301
+ messages: [Message.Emptied],
302
+ closed: true,
303
+ })
304
+
305
+ const check = Closure.violations(App, [Shown])
306
+ const counted = Message.Counted()
307
+ check(initial, counted, update(initial, counted).model)
308
+ // []: Counted is outside the Surface and leaves its projection alone
309
+ ```
310
+
311
+ A violation is a `ClosureViolation`: `Reads({ surface, fields })` for a Message
312
+ in the set that reads fields outside the Surface (the fields are named), or
313
+ `Outside({ surface })` for a Message outside the set that changed the
314
+ projection. Read one through `ClosureViolation.$match`.
315
+ `Surface.contract` carries `closed: true` for such a Surface.
316
+
201
317
  ## Applications
202
318
 
203
319
  `Surface.application({ Model, Message })` returns an `Application`: the schemas
@@ -217,6 +333,29 @@ returns a `RunnableApplication` with the same references and the same owner.
217
333
  A second `Surface.application` for the update would be another application,
218
334
  whose references `Projection.pick` refuses to mix with the first's:
219
335
 
336
+ <!-- docs-check standalone define todoApp
337
+ import { Option, Schema } from 'effect'
338
+ import { defineMessageUnion } from 'foldkit/message'
339
+ import { ModelRef, Projection, Surface } from 'foldkit-surface'
340
+
341
+ const Todo = Schema.Struct({ id: Schema.String, title: Schema.String, done: Schema.Boolean })
342
+ const Model = Schema.Struct({
343
+ todos: Schema.Array(Todo),
344
+ todosById: Schema.Record(Schema.String, Todo),
345
+ selectedTodoId: Schema.Option(Schema.String),
346
+ })
347
+ const Message = defineMessageUnion({
348
+ CreatedTodo: { id: Schema.String, title: Schema.String },
349
+ ToggledTodo: { id: Schema.String },
350
+ SelectedTodo: { id: Schema.String },
351
+ })
352
+ const initial: typeof Model.Type = { todos: [], todosById: {}, selectedTodoId: Option.none() }
353
+ const update = (model: typeof Model.Type, _message: typeof Message.Type) => ({ model })
354
+ declare const model: typeof Model.Type
355
+ declare const root: typeof Model.Type
356
+ declare const restoredTodos: typeof Model.Type['todos']
357
+ -->
358
+
220
359
  ```ts
221
360
  const Made = Surface.application({ Model, Message })
222
361
  // …what the update needs, built over Made.model…
@@ -252,19 +391,19 @@ so `update` stays the only place a Message has effects:
252
391
  ```ts
253
392
  import { Action } from 'foldkit-surface'
254
393
 
255
- const AddToCart = Action.define({
256
- name: 'addToCart',
257
- description: 'Add a product to the cart',
258
- input: Schema.Struct({ productId: ProductId }),
259
- toMessage: input => Message.AddedToCart(input),
394
+ const SelectTodo = Action.define({
395
+ name: 'selectTodo',
396
+ description: 'Select a todo',
397
+ input: Schema.Struct({ id: Schema.String }),
398
+ toMessage: input => Message.SelectedTodo(input),
260
399
  })
261
400
 
262
- Action.run(AddToCart, { productId: 'p1' }) // Result: the Message, or why the input was refused
401
+ Action.run(SelectTodo, { id: 't1' }) // Result: the Message, or why the input was refused
263
402
  ```
264
403
 
265
404
  `Action.run` decodes the data as the Action's input before `toMessage` sees it,
266
405
  so data from a Document or a tool call never executes. The Action is declared
267
- once: `Agent.action(AddToCart)` exposes it to an agent, and a page's Catalog
406
+ once: `Agent.action(SelectTodo)` exposes it to an agent, and a page's Catalog
268
407
  lists it for Blocks to reference by name.
269
408
 
270
409
  ## Surfaces
@@ -289,7 +428,7 @@ const ById = App.surface('ById', {
289
428
 
290
429
  Surface.read(TodoDetail, root) // project purely
291
430
  Surface.read(ById, root, { id: 't1' })
292
- Surface.view(TodoDetail, render) // bind a renderer
431
+ const render = Surface.view(TodoDetail, (todos, h) => h.div([], [`${todos.todos.length} todos`]))
293
432
  Surface.rootView(TodoDetail, undefined, render) // bound to the app root
294
433
  ```
295
434
 
@@ -332,7 +471,7 @@ described in place (`Surface.contract(surface, params)` for a parameterized one)
332
471
  ```ts
333
472
  import { Module } from 'foldkit-surface'
334
473
 
335
- const Project = Module.make(App, [BoardSurface, ProjectSync, ProjectRemote, ProjectAgent])
474
+ const Project = Module.make(App, [TodoDetail]) // and any Sync, Remote or Agent contracts
336
475
 
337
476
  Module.validate(Project) // [] or findings
338
477
  Module.manifest(Project) // fields, Messages, who owns each Model path, contracts
@@ -354,6 +493,90 @@ recorded by two replication contracts, and a path or Message the application
354
493
  does not declare. `Module.add(module, ...more)` returns a new Module, so feature
355
494
  modules can contribute their contracts independently.
356
495
 
496
+ ### Laws in the graph
497
+
498
+ A contract may also say which laws it holds and which transitions can break
499
+ them. `Contract.laws` holds the declarations themselves, and `Graph.of`
500
+ derives their nodes and edges only when it is asked. `Graph` is apart from
501
+ `Module`: a page that reads only `Module` (to draw who owns what) carries
502
+ none of the graph's code. `laws.entities` lists transitions over
503
+ Entities as `Laws.check` takes them: Remote declares each declared write, which
504
+ becomes `write:Sell` beside a law per invariant of its Entity
505
+ (`Product.reservedWithinStock`). `laws.model` names laws over the contract's
506
+ Model slice: Sync declares its document's, each `sync:<name>.<id>` reading the
507
+ whole slice, and each of its Messages is `durable:<tag>` writing it. A closed
508
+ Surface is a level with a `closure:<name>` law over its paths.
509
+ `Graph.of(module, { evidence })` joins them.
510
+
511
+ ```text
512
+ transition --writes--> path <--reads-- law
513
+ transition ----------keeps(evidence)--> law
514
+ ```
515
+
516
+ A transition that writes a path a law reads could break it. The graph does not
517
+ decide whether it does; evidence says so: `Laws.check`'s `Enumerated` records,
518
+ what a walk or a scenario returns, or `Evidence.runtimeOnly` for a pair only
519
+ the writer or the journal refuses. `Graph.validate(module, { evidence })` asks
520
+ the one question of the graph; with no `evidence`, every pair a transition can
521
+ break is unwitnessed. `Module.validate` asks none of these rules, and
522
+ `Graph.validate` none of `Module`'s, so a test that wants both asks both.
523
+
524
+ ```ts standalone
525
+ import { Schema } from 'effect'
526
+ import { defineMessageUnion } from 'foldkit/message'
527
+ import { Evidence, Graph, Module, Surface } from 'foldkit-surface'
528
+
529
+ const App = Surface.application({
530
+ Model: Schema.Struct({ todos: Schema.Array(Schema.String) }),
531
+ Message: defineMessageUnion({ Added: { title: Schema.String } }),
532
+ })
533
+
534
+ // What `Sync.forApplication(App).make` declares for a document with one law.
535
+ const todos = {
536
+ kind: 'sync',
537
+ name: 'todos',
538
+ owner: App.owner,
539
+ owns: [['todos']],
540
+ observes: [['todos']],
541
+ messages: ['Added'],
542
+ metadata: [],
543
+ laws: { model: ['capped'] },
544
+ }
545
+ const Todos = Module.make(App, [todos])
546
+
547
+ Module.validate(Todos) // []: one owner per path, every name declared
548
+ Graph.validate(Todos)
549
+ // [{ rule: 'law-unwitnessed', message: 'durable:Added writes todos, which sync:todos.capped reads, …' }]
550
+
551
+ const judged = Evidence.runtimeOnly({
552
+ transition: 'durable:Added',
553
+ law: 'sync:todos.capped',
554
+ why: 'the journal judges every append, and refuses one past the cap',
555
+ })
556
+ Graph.validate(Todos, { evidence: [judged] }) // []
557
+ Graph.breakersOf(Graph.of(Todos, { evidence: [judged] }), 'sync:todos.capped')
558
+ // [{ transition: 'durable:Added', paths: [['todos']], evidence: [judged] }]
559
+ ```
560
+
561
+ The rules over the graph:
562
+
563
+ | Rule | Reported when |
564
+ | --- | --- |
565
+ | `law-unwitnessed` | A transition writes a path a law reads (one within the other), and no evidence joins them. A pair sharing no path is never reported, but a law over a row's change (one reading `before`) reads the whole row, since a write leaving its members alone can still break it. |
566
+ | `evidence-unmatched` | A record was issued by no producer (typed by hand, or a copy of one), or names a transition or law no contract declares, or a pair the graph does not join: a write and a law of two Entities, or a Message and a law over Model paths that do not overlap (two documents'). |
567
+ | `level-declared-twice` | Two closed Surfaces observe the same paths and list the same Messages. |
568
+ | `transition-declared-twice` | Two contracts declare a write of one name (`write:Sell` in two Remote domains): the graph and evidence name a write by its name, so neither can tell them apart. |
569
+
570
+ So a durable Message added to a document, or a write added to a domain, is
571
+ reported until a walk or a scenario draws it, or a line says why only
572
+ production refuses it. `Graph.toMarkdown` takes the same options and writes a
573
+ Laws section, to set beside `Module.toMarkdown`'s: each law, each transition
574
+ that can break it, its evidence, then `Graph.validate`'s findings.
575
+ `Graph.toMermaid` draws the same as a flowchart of its own. The graph holds no transition for a local Message: what
576
+ `modifyFields` writes is known only at run time, so a law over the local Model
577
+ has no `law-unwitnessed` yet, though a walk over it still runs.
578
+ `examples/writes` keeps its table in `LAWS.md`.
579
+
357
580
  ## Diagnostics
358
581
 
359
582
  `Diagnostics` is the one channel every Foldkit Plus package reports into what
@@ -432,18 +655,24 @@ Surface = observation + capability contract
432
655
  Submodel = state-machine ownership boundary
433
656
  ```
434
657
 
435
- They compose; none replaces the others. This schematic example assumes an
436
- application with a `filter` field and an already-decoded `restoredFilter`:
658
+ They compose; none replaces the others. Each line below changes
659
+ or reads the same field, `todos` (`restoredTodos` is an already-decoded value):
660
+
661
+ <!-- docs-check standalone use todoApp
662
+ const App = Surface.application({ Model, Message }).runnable({ initial, update })
663
+ -->
437
664
 
438
665
  ```ts
666
+ import { modifyFields } from 'foldkit/struct'
667
+
439
668
  // application transition
440
- modifyFields(model, { filter: () => 'active' })
669
+ modifyFields(model, { todos: () => [] })
441
670
 
442
671
  // structural addressing
443
- ModelRef.focus(App.model.filter).get(model)
672
+ ModelRef.focus(App.model.todos).get(model)
444
673
 
445
674
  // infrastructure installation
446
- ModelRef.focus(App.model.filter).set(model, restoredFilter)
675
+ ModelRef.focus(App.model.todos).set(model, restoredTodos)
447
676
  ```
448
677
 
449
678
  ### Surface builds on Optics rather than replacing them
@@ -522,6 +751,17 @@ the route, a theme owned by `Settings`, and the signed-in user owned by
522
751
  `Session` does not need to become a third state machine just to assemble those
523
752
  values:
524
753
 
754
+ <!-- docs-check standalone
755
+ import { Schema } from 'effect'
756
+ import { defineMessageUnion } from 'foldkit/message'
757
+ import { Surface } from 'foldkit-surface'
758
+
759
+ const Route = Schema.Literals(['Home', 'Account'])
760
+ const Settings = { Model: Schema.Struct({ theme: Schema.String }) }
761
+ const Session = { Model: Schema.Struct({ user: Schema.NullOr(Schema.String) }) }
762
+ const Message = defineMessageUnion({ ChangedTheme: { theme: Schema.String } })
763
+ -->
764
+
525
765
  ```ts
526
766
  const Model = Schema.Struct({
527
767
  route: Route,
@@ -529,7 +769,7 @@ const Model = Schema.Struct({
529
769
  session: Session.Model,
530
770
  })
531
771
 
532
- const App = Surface.application({ Model, Message, initial, update })
772
+ const App = Surface.application({ Model, Message })
533
773
 
534
774
  const AccountPage = App.surface('AccountPage', {
535
775
  model: ({ model }) => ({
@@ -603,6 +843,13 @@ that may observe across those runtime boundaries without creating another one.
603
843
  interpreter metadata (`Metadata.key`).
604
844
  - Application scopes (`Surface.application`) and their identity token.
605
845
  - Typed Message subsets (`MessageSet.make`, `MessageSet.union`).
846
+ - `Closure.reads`: whether a projection after a Message depends on the rest of the Model.
847
+ - `Closure.violations`: the closed Surfaces a step broke, as `ClosureViolation`s; `Surface.make`'s and `App.surface`'s `closed`.
848
+ - The law half of the contract graph: `Contract.laws`, and `Graph`: `Graph.of`,
849
+ `Graph.validate` (`law-unwitnessed`, `evidence-unmatched`,
850
+ `level-declared-twice`, `transition-declared-twice`), `Graph.breakersOf`,
851
+ `Graph.toMarkdown` and `Graph.toMermaid`. It owns the question, not the answers: each contract
852
+ owns its declared laws, and the producers of `Evidence` own its records.
606
853
  - Actions (`Action.define`, `Action.run`): a named capability ending in a Message.
607
854
  - Named Surfaces and their renderer binding.
608
855
  - The `Diagnostics` channel and its default reporter; each package owns its own
@@ -0,0 +1,75 @@
1
+ import { Data, Schema } from "effect";
2
+ import { DependencyTree, Projection } from "./index.js";
3
+ /** A read-only `Projection` or a `WritableProjection`: `Closure` needs only the codec, the paths and the read. */
4
+ export type ClosureProjection<Root, Value> = {
5
+ readonly Model: Schema.Schema<Value>;
6
+ readonly dependencies: DependencyTree;
7
+ readonly read: (root: Root) => Value;
8
+ } | {
9
+ readonly schema: Schema.Schema<Value>;
10
+ readonly dependencies: DependencyTree;
11
+ readonly get: (root: Root) => Value;
12
+ };
13
+ /**
14
+ * The top-level Model fields outside `projection` that its value after `message` depends on;
15
+ * empty when the projection is closed for this step. `update` runs on `model` and on `model`
16
+ * with those fields reset to `app.initial`, and the two projections are compared with the
17
+ * projection's codec. Only a field that differs from `initial` can be named, and a field that
18
+ * holds the projection's own paths (even in part) is never one.
19
+ *
20
+ * It runs `update` again and so does what `update` does: no Command it returns is run.
21
+ */
22
+ declare const reads: <Root, Value, Message>(app: {
23
+ readonly initial: Root;
24
+ readonly update: (model: Root, message: Message) => {
25
+ readonly model: Root;
26
+ };
27
+ }, projection: ClosureProjection<Root, Value>, model: Root, message: Message) => ReadonlyArray<string>;
28
+ /**
29
+ * A closed Surface a step broke: `Reads` names the fields outside it that a Message in its
30
+ * set read, `Outside` says a Message outside its set moved it.
31
+ */
32
+ export type ClosureViolation = Data.TaggedEnum<{
33
+ Reads: {
34
+ readonly surface: string;
35
+ readonly fields: ReadonlyArray<string>;
36
+ };
37
+ Outside: {
38
+ readonly surface: string;
39
+ };
40
+ }>;
41
+ export declare const ClosureViolation: Data.TaggedEnum.Constructor<{
42
+ readonly _tag: "Outside";
43
+ readonly surface: string;
44
+ } | {
45
+ readonly _tag: "Reads";
46
+ readonly surface: string;
47
+ readonly fields: ReadonlyArray<string>;
48
+ }>;
49
+ /**
50
+ * A step check over the Surfaces declared `closed: true`, for a walk. For a Message in a
51
+ * Surface's `messages`, `Closure.reads` must be empty; for any other Message the projection
52
+ * must not change from `before` to `after`. A Surface not declared closed is never tested.
53
+ * A Surface with params is refused here: it has no one projection to test.
54
+ */
55
+ declare const violations: <Root, Message>(app: {
56
+ readonly initial: Root;
57
+ readonly update: (model: Root, message: Message) => {
58
+ readonly model: Root;
59
+ };
60
+ }, surfaces: ReadonlyArray<{
61
+ readonly name: string;
62
+ readonly closed: boolean;
63
+ readonly messages: readonly unknown[];
64
+ /** Read only to refuse a Surface with params. */
65
+ readonly Params: unknown;
66
+ /** `never`: whatever params a Surface takes, it is only ever called with none. */
67
+ readonly projection: (params: never) => Projection<Root, unknown>;
68
+ }>) => ((before: Root, message: Message, after: Root) => ReadonlyArray<ClosureViolation>);
69
+ /** Checks that a projection is closed under `update`: `Closure.reads` names what it still depends on. */
70
+ export declare const Closure: {
71
+ reads: typeof reads;
72
+ violations: typeof violations;
73
+ };
74
+ export {};
75
+ //# sourceMappingURL=closure.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"closure.d.ts","names":[],"sources":["../src/closure.ts"],"mappings":";;;YAKY,kBAAkB,MAAM;WAErB,OAAO,OAAO,OAAO;WACrB,cAAc;WACd,OAAO,MAAM,SAAS;;WAGtB,QAAQ,OAAO,OAAO;WACtB,cAAc;WACd,MAAM,MAAM,SAAS;;;;;;;;;;;cAwC9B,QAAS,MAAM,OAAO,SAAO;WAEtB,SAAS;WACT,SAAS,OAAO,MAAM,SAAS;aAAuB,OAAO;;GACvE,YACW,kBAAkB,MAAM,QAAM,OACnC,MAAI,SACF,YACR;;;;;YA8BS,mBAAmB,KAAK;EAClC;aAAkB;aAA0B,QAAQ;;EACpD;aAAoB;;;qBAET,kBAAgB,KAAA,WAAA;;WAFE;;;WADF;WAAyB,QAAA;;;;;;;;cAWhD,aAAc,MAAM,SAAO;WAEpB,SAAS;WACT,SAAS,OAAO,MAAM,SAAS;aAAuB,OAAO;;GACvE,UACS;WACC;WACA;WACA;;WAEA;;WAEA,aAAa,kBAAkB,WAAW;SAElD,QAAQ,MAAM,SAAS,SAAS,OAAO,SAAS,cAAc;;qBA2BtD"}
@@ -0,0 +1,95 @@
1
+ import { Data, Schema } from "effect";
2
+ import { hasTagIn, messageTags } from "./messageTags.js";
3
+ // src/closure.ts
4
+ const ownedBy = /* @__PURE__ */ new WeakMap();
5
+ const equivalenceOf = /* @__PURE__ */ new WeakMap();
6
+ const owned = (dependencies) => {
7
+ let fields = ownedBy.get(dependencies);
8
+ if (fields === void 0) {
9
+ fields = new Set(dependencies.map((path) => path[0]).filter((key) => key !== void 0));
10
+ ownedBy.set(dependencies, fields);
11
+ }
12
+ return fields;
13
+ };
14
+ const partsOf = (projection) => "schema" in projection ? {
15
+ codec: projection.schema,
16
+ read: projection.get
17
+ } : {
18
+ codec: projection.Model,
19
+ read: projection.read
20
+ };
21
+ const equivalence = (codec) => {
22
+ let equal = equivalenceOf.get(codec);
23
+ if (equal === void 0) {
24
+ equal = Schema.toEquivalence(codec);
25
+ equivalenceOf.set(codec, equal);
26
+ }
27
+ return equal;
28
+ };
29
+ /**
30
+ * The top-level Model fields outside `projection` that its value after `message` depends on;
31
+ * empty when the projection is closed for this step. `update` runs on `model` and on `model`
32
+ * with those fields reset to `app.initial`, and the two projections are compared with the
33
+ * projection's codec. Only a field that differs from `initial` can be named, and a field that
34
+ * holds the projection's own paths (even in part) is never one.
35
+ *
36
+ * It runs `update` again and so does what `update` does: no Command it returns is run.
37
+ */
38
+ const reads = (app, projection, model, message) => {
39
+ const live = model;
40
+ const baseline = app.initial;
41
+ const own = owned(projection.dependencies);
42
+ const outside = Object.keys(live).filter((key) => !own.has(key) && !Object.is(live[key], baseline[key]));
43
+ if (outside.length === 0) return [];
44
+ const { codec, read } = partsOf(projection);
45
+ const equal = equivalence(codec);
46
+ const after = read(app.update(model, message).model);
47
+ const differs = (fields) => {
48
+ const reset = { ...live };
49
+ for (const key of fields) reset[key] = baseline[key];
50
+ const other = read(app.update(reset, message).model);
51
+ return !Object.is(after, other) && !equal(after, other);
52
+ };
53
+ if (!differs(outside)) return [];
54
+ if (outside.length === 1) return outside;
55
+ const named = outside.filter((key) => differs([key]));
56
+ return named.length === 0 ? outside : named;
57
+ };
58
+ const ClosureViolation = Data.taggedEnum();
59
+ /**
60
+ * A step check over the Surfaces declared `closed: true`, for a walk. For a Message in a
61
+ * Surface's `messages`, `Closure.reads` must be empty; for any other Message the projection
62
+ * must not change from `before` to `after`. A Surface not declared closed is never tested.
63
+ * A Surface with params is refused here: it has no one projection to test.
64
+ */
65
+ const violations = (app, surfaces) => {
66
+ const closed = surfaces.filter((surface) => surface.closed).map((surface) => {
67
+ if (surface.Params !== void 0) throw new Error(`Closure.violations: Surface "${surface.name}" declares params`);
68
+ const projection = surface.projection(void 0);
69
+ return {
70
+ name: surface.name,
71
+ projection,
72
+ tags: new Set(messageTags(surface))
73
+ };
74
+ });
75
+ return (before, message, after) => closed.flatMap(({ name, projection, tags }) => {
76
+ if (hasTagIn(tags, message)) {
77
+ const fields = reads(app, projection, before, message);
78
+ return fields.length === 0 ? [] : [ClosureViolation.Reads({
79
+ surface: name,
80
+ fields
81
+ })];
82
+ }
83
+ const { codec, read } = partsOf(projection);
84
+ const [was, now] = [read(before), read(after)];
85
+ return Object.is(was, now) || equivalence(codec)(was, now) ? [] : [ClosureViolation.Outside({ surface: name })];
86
+ });
87
+ };
88
+ /** Checks that a projection is closed under `update`: `Closure.reads` names what it still depends on. */
89
+ const Closure = {
90
+ reads,
91
+ violations
92
+ };
93
+ export { Closure, ClosureViolation };
94
+
95
+ //# sourceMappingURL=closure.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"closure.js","names":[],"sources":["../src/closure.ts"],"sourcesContent":["import { Data, Schema } from 'effect'\nimport type { DependencyTree, Projection } from './index.js'\nimport { hasTagIn, messageTags } from './messageTags.js'\n\n/** A read-only `Projection` or a `WritableProjection`: `Closure` needs only the codec, the paths and the read. */\nexport type ClosureProjection<Root, Value> =\n | {\n readonly Model: Schema.Schema<Value>\n readonly dependencies: DependencyTree\n readonly read: (root: Root) => Value\n }\n | {\n readonly schema: Schema.Schema<Value>\n readonly dependencies: DependencyTree\n readonly get: (root: Root) => Value\n }\n\nconst ownedBy = new WeakMap<DependencyTree, ReadonlySet<string>>()\nconst equivalenceOf = new WeakMap<object, (a: never, b: never) => boolean>()\n\nconst owned = (dependencies: DependencyTree): ReadonlySet<string> => {\n let fields = ownedBy.get(dependencies)\n if (fields === undefined) {\n fields = new Set(dependencies.map(path => path[0]).filter(key => key !== undefined))\n ownedBy.set(dependencies, fields)\n }\n return fields\n}\n\nconst partsOf = <Root, Value>(\n projection: ClosureProjection<Root, Value>,\n): { readonly codec: Schema.Schema<Value>; readonly read: (root: Root) => Value } =>\n 'schema' in projection\n ? { codec: projection.schema, read: projection.get }\n : { codec: projection.Model, read: projection.read }\n\nconst equivalence = <Value>(codec: Schema.Schema<Value>): ((a: Value, b: Value) => boolean) => {\n let equal = equivalenceOf.get(codec)\n if (equal === undefined) {\n equal = Schema.toEquivalence(codec) as never\n equivalenceOf.set(codec, equal)\n }\n return equal as (a: Value, b: Value) => boolean\n}\n\n/**\n * The top-level Model fields outside `projection` that its value after `message` depends on;\n * empty when the projection is closed for this step. `update` runs on `model` and on `model`\n * with those fields reset to `app.initial`, and the two projections are compared with the\n * projection's codec. Only a field that differs from `initial` can be named, and a field that\n * holds the projection's own paths (even in part) is never one.\n *\n * It runs `update` again and so does what `update` does: no Command it returns is run.\n */\nconst reads = <Root, Value, Message>(\n app: {\n readonly initial: Root\n readonly update: (model: Root, message: Message) => { readonly model: Root }\n },\n projection: ClosureProjection<Root, Value>,\n model: Root,\n message: Message,\n): ReadonlyArray<string> => {\n const live = model as Readonly<Record<string, unknown>>\n const baseline = app.initial as Readonly<Record<string, unknown>>\n const own = owned(projection.dependencies)\n const outside = Object.keys(live).filter(\n key => !own.has(key) && !Object.is(live[key], baseline[key]),\n )\n if (outside.length === 0) return []\n\n const { codec, read } = partsOf(projection)\n const equal = equivalence(codec)\n const after = read(app.update(model, message).model)\n const differs = (fields: ReadonlyArray<string>): boolean => {\n const reset = { ...live }\n for (const key of fields) reset[key] = baseline[key]\n const other = read(app.update(reset as Root, message).model)\n return !Object.is(after, other) && !equal(after, other)\n }\n\n if (!differs(outside)) return []\n if (outside.length === 1) return outside\n const named = outside.filter(key => differs([key]))\n // When each of several fields is enough alone, resetting one changes nothing: all are named.\n return named.length === 0 ? outside : named\n}\n\n/**\n * A closed Surface a step broke: `Reads` names the fields outside it that a Message in its\n * set read, `Outside` says a Message outside its set moved it.\n */\nexport type ClosureViolation = Data.TaggedEnum<{\n Reads: { readonly surface: string; readonly fields: ReadonlyArray<string> }\n Outside: { readonly surface: string }\n}>\nexport const ClosureViolation = Data.taggedEnum<ClosureViolation>()\n\n/**\n * A step check over the Surfaces declared `closed: true`, for a walk. For a Message in a\n * Surface's `messages`, `Closure.reads` must be empty; for any other Message the projection\n * must not change from `before` to `after`. A Surface not declared closed is never tested.\n * A Surface with params is refused here: it has no one projection to test.\n */\nconst violations = <Root, Message>(\n app: {\n readonly initial: Root\n readonly update: (model: Root, message: Message) => { readonly model: Root }\n },\n surfaces: ReadonlyArray<{\n readonly name: string\n readonly closed: boolean\n readonly messages: readonly unknown[]\n /** Read only to refuse a Surface with params. */\n readonly Params: unknown\n /** `never`: whatever params a Surface takes, it is only ever called with none. */\n readonly projection: (params: never) => Projection<Root, unknown>\n }>,\n): ((before: Root, message: Message, after: Root) => ReadonlyArray<ClosureViolation>) => {\n const closed = surfaces\n .filter(surface => surface.closed)\n .map(surface => {\n if (surface.Params !== undefined) {\n throw new Error(`Closure.violations: Surface \"${surface.name}\" declares params`)\n }\n // No params schema, checked above: the Surface takes none.\n const projection: ClosureProjection<Root, unknown> = surface.projection(undefined as never)\n return { name: surface.name, projection, tags: new Set(messageTags(surface)) }\n })\n return (before, message, after) =>\n closed.flatMap(({ name, projection, tags }): ReadonlyArray<ClosureViolation> => {\n // tag-check: open, `Message` is the application's own, which this cannot name\n if (hasTagIn(tags, message)) {\n const fields = reads(app, projection, before, message)\n return fields.length === 0 ? [] : [ClosureViolation.Reads({ surface: name, fields })]\n }\n const { codec, read } = partsOf(projection)\n const [was, now] = [read(before), read(after)]\n return Object.is(was, now) || equivalence(codec)(was, now)\n ? []\n : [ClosureViolation.Outside({ surface: name })]\n })\n}\n\n/** Checks that a projection is closed under `update`: `Closure.reads` names what it still depends on. */\nexport const Closure = { reads, violations }\n"],"mappings":"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"}