@livestore/webmesh 0.3.1 → 0.3.2-dev.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
@@ -20,6 +20,58 @@ ProxyChannels and DirectChannels have the following properties (similar to TCP):
20
20
  - `WebSocket`
21
21
  - `window.postMessage`
22
22
 
23
+ ## Example
24
+
25
+ Scenario: For topology `A <> B <> C`, we want to create direct channel between `A` and `C`
26
+
27
+ ```ts
28
+ import { makeMeshNode, Packet, WebChannel } from '@livestore/webmesh'
29
+
30
+ const ChannelSchema = Schema.Struct({ message: Schema.String })
31
+
32
+ // Creating shared message channels between nodes to simplify the example.
33
+ // In a real-world application, you would use e.g. a shared worker or similar to exchange the message channels between nodes.
34
+ const mcA_B = new MessageChannel()
35
+ const mcB_C = new MessageChannel()
36
+
37
+ // e.g. running in tab A of a browser
38
+ const codeOnNodeA = Effect.gen(function* () {
39
+ const nodeA = yield* makeMeshNode('A')
40
+
41
+ // create edge to node B using a MessageChannel
42
+ const edgeChannelB = yield* WebChannel.messagePortChannel({ port: mcA_B.port1, schema: Packet })
43
+ yield* nodeA.addEdge({ target: 'B', edgeChannel: edgeChannelB })
44
+
45
+ const channelToC = yield* nodeA.makeChannel({ target: 'C', schema: ChannelSchema })
46
+
47
+ yield* channelToC.send('Hello from A')
48
+ })
49
+
50
+ // e.g. running in tab B of a browser
51
+ const codeOnNodeB = Effect.gen(function* () {
52
+ const nodeB = yield* makeMeshNode('B')
53
+
54
+ const edgeChannelA = yield* WebChannel.messagePortChannel({ port: mcA_B.port2, schema: Packet })
55
+ yield* nodeB.addEdge({ target: 'A', edgeChannel: edgeChannelA })
56
+
57
+ const edgeChannelC = yield* WebChannel.messagePortChannel({ port: mcB_C.port2, schema: Packet })
58
+ yield* nodeB.addEdge({ target: 'C', edgeChannel: edgeChannelC })
59
+ })
60
+
61
+ // e.g. running in tab C of a browser
62
+ const codeOnNodeC = Effect.gen(function* () {
63
+ const nodeC = yield* makeMeshNode('C')
64
+
65
+ const edgeChannelB = yield* WebChannel.messagePortChannel({ port: mcB_C.port1, schema: Packet })
66
+ yield* nodeC.addEdge({ target: 'B', edgeChannel: edgeChannelB })
67
+
68
+ const channelToA = yield* nodeC.makeChannel({ target: 'A', schema: ChannelSchema })
69
+
70
+ const message = yield* channelToA.listen.pipe(Stream.take(1), Stream.runCollect)
71
+ console.log('message', message) // => 'Hello from A'
72
+ })
73
+ ```
74
+
23
75
  ## Important notes
24
76
 
25
77
  - Each node name needs to be unique in the network.