@mmstack/mesh 22.9.0 → 22.10.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmstack/mesh",
3
- "version": "22.9.0",
3
+ "version": "22.10.0",
4
4
  "keywords": [
5
5
  "angular",
6
6
  "signals",
@@ -20,8 +20,8 @@
20
20
  "homepage": "https://github.com/mihajm/mmstack/blob/master/packages/mesh/client",
21
21
  "peerDependencies": {
22
22
  "@angular/core": ">=22 <23",
23
- "@mmstack/primitives": ">=22.15 <23",
24
- "@mmstack/mesh-protocol": ">=0.9 <1"
23
+ "@mmstack/primitives": ">=22.16 <23",
24
+ "@mmstack/mesh-protocol": ">=0.10 <1"
25
25
  },
26
26
  "sideEffects": false,
27
27
  "module": "fesm2022/mmstack-mesh.mjs",
@@ -1,6 +1,6 @@
1
- import { ClientMsg, ServerMsg, Relay, PrincipalCtx, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
1
+ import { ClientMsg, ServerMsg, Relay, PrincipalCtx, IceServer, ClientSignalMsg, PresenceState, OpPolicy } from '@mmstack/mesh-protocol';
2
2
  import { OpSync, MergePolicyEntry, OpEnvelope, AsyncStore, ForkStoreOptions, SyncedFork, WritableSignalStore, StoreOp, toStoreOptions } from '@mmstack/primitives/core';
3
- import { Injector, Signal, WritableSignal } from '@angular/core';
3
+ import { Signal, Injector, WritableSignal } from '@angular/core';
4
4
 
5
5
  /**
6
6
  * One live connection to a relay. `meshSync` calls the factory per (re)connect; a transport
@@ -24,14 +24,190 @@ declare function webSocketTransport(url: string, protocols?: string | string[]):
24
24
  */
25
25
  declare function directTransport(relay: Relay, ctx: PrincipalCtx): MeshTransportFactory;
26
26
 
27
- type MeshStatus = 'connecting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
27
+ type MeshStatus = 'connecting'
28
+ /** Queued behind another tab that owns this key's durable outbox (`crossTab: 'queue'`). */
29
+ | 'waiting' | 'live' | 'reconnecting' | 'ejected' | 'closed';
30
+
31
+ /** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */
32
+ type DataChannelLike = {
33
+ send(frame: string): void;
34
+ onMessage(cb: (frame: string) => void): () => void;
35
+ onOpen(cb: () => void): () => void;
36
+ onClose(cb: () => void): () => void;
37
+ close(): void;
38
+ };
39
+ /** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */
40
+ type PeerChannelSpec = {
41
+ readonly label: string;
42
+ readonly ordered?: boolean;
43
+ readonly maxRetransmits?: number;
44
+ };
45
+ /** The single reliable channel every link carries when no channels are asked for. */
46
+ declare const defaultPeerChannels: readonly PeerChannelSpec[];
47
+ /**
48
+ * Creates one peer link. `polite` assigns the perfect-negotiation role (derived
49
+ * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads
50
+ * through the relay; `signal` delivers the remote side's payloads. Object payloads gain a
51
+ * `link` field on the way out (the sending link's instance id) and, once the remote instance
52
+ * is known, a `to` field; both are stripped before `signal` sees the payload.
53
+ *
54
+ * `channels` lists the labelled channels the link carries; `channel` is the first of them and
55
+ * `channels` (by label) all of them. A connector that returns only `channel` supports a single
56
+ * channel. Signal payloads carry no channel field: one link per remote carries every channel,
57
+ * so nothing needs routing. The field name `ch` is kept free for a future where it does.
58
+ *
59
+ * `onClose`, when the connector has it, reports the link as a whole finished even if no channel
60
+ * said so; the links then rebuild it.
61
+ */
62
+ type PeerConnector = (opt: {
63
+ readonly remote: string;
64
+ readonly polite: boolean;
65
+ readonly sendSignal: (data: unknown) => void;
66
+ readonly channels: readonly PeerChannelSpec[];
67
+ /** ICE servers the relay issued in the last welcome, if any. */
68
+ readonly iceServers?: readonly IceServer[];
69
+ }) => {
70
+ readonly channel: DataChannelLike;
71
+ readonly channels?: Readonly<Record<string, DataChannelLike>>;
72
+ signal(data: unknown): void;
73
+ /** Fires once when the link as a whole is gone, whether or not its channels reported it. */
74
+ onClose?(cb: () => void): () => void;
75
+ close(): void;
76
+ };
77
+ /**
78
+ * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.
79
+ *
80
+ * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.
81
+ * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form
82
+ * on one network segment. When ICE fails, or stays `disconnected` longer than
83
+ * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before
84
+ * the link connects again, a closed connection, or a negotiation step the browser rejects
85
+ * reports the link gone through `onClose`.
86
+ */
87
+ declare function rtcPeerConnector(config?: RTCConfiguration, opt?: {
88
+ readonly disconnectGraceMs?: number;
89
+ }): PeerConnector;
90
+ /**
91
+ * A relay connection someone else owns (a live session, say). Peer links ride on it without
92
+ * saying hello, so the links share that connection's origin and room membership.
93
+ */
94
+ type SignalingPort = {
95
+ /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */
96
+ members(): readonly string[] | undefined;
97
+ /** ICE servers from the owner's last welcome, if it keeps them. Read after subscribing. */
98
+ iceServers?(): readonly IceServer[] | undefined;
99
+ send(msg: ClientSignalMsg): void;
100
+ onMessage(cb: (msg: ServerMsg) => void): () => void;
101
+ };
102
+ type PeerLinksOptions = {
103
+ readonly room: string;
104
+ /** This side's origin; also decides the perfect-negotiation role against each remote. */
105
+ readonly origin: string;
106
+ /**
107
+ * A transport factory means the links own their relay connection (hello, reconnect); a
108
+ * {@link SignalingPort} means they ride on one that is already joined.
109
+ */
110
+ readonly signaling: MeshTransportFactory | SignalingPort;
111
+ /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
112
+ readonly connector?: PeerConnector;
113
+ /**
114
+ * The channels every link carries, first one the default for `send` and `broadcast`.
115
+ * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.
116
+ */
117
+ readonly channels?: readonly PeerChannelSpec[];
118
+ /** Sent in the hello when the links own their connection. */
119
+ readonly policyVersion?: number;
120
+ /**
121
+ * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe
122
+ * before the first link opens. Defaults to `true`.
123
+ */
124
+ readonly autoConnect?: boolean;
125
+ /** How long a link may take to open every channel before it counts as lost. Default 15000. */
126
+ readonly openTimeoutMs?: number;
127
+ /** Backoff bounds for rebuilding a lost link. Defaults 1000 and 30000. */
128
+ readonly retry?: {
129
+ readonly minMs?: number;
130
+ readonly maxMs?: number;
131
+ };
132
+ /** Random source for the backoff jitter; tests pass a seeded one. Default Math.random. */
133
+ readonly random?: () => number;
134
+ readonly injector?: Injector;
135
+ };
136
+ type PeerLinks = {
137
+ /**
138
+ * `live` once the relay has welcomed this side (or, over a port, once it has seen a
139
+ * welcome); back to `connecting` while an owned relay connection is being re-established.
140
+ * Peer links outlive that: they are retired only by their own close or a relay `gone`. Over
141
+ * a port the same holds across the session's socket drops; when the session itself ends, the
142
+ * port reports `gone` for every member and the links are retired with it.
143
+ */
144
+ readonly status: Signal<'connecting' | 'live'>;
145
+ /** Origins whose link has every channel open. */
146
+ readonly peers: Signal<readonly string[]>;
147
+ /** Members whose link was lost at least once since it last opened: waiting to rebuild, or rebuilding. */
148
+ readonly stalled: Signal<readonly string[]>;
149
+ /**
150
+ * Other origins in the room as the relay reports them (welcome, then join and leave). The
151
+ * relay is the authority on who is present; a link can outlive a dead socket for a while.
152
+ */
153
+ readonly members: Signal<readonly string[]>;
154
+ /** Replays current membership synchronously, then reports every change without coalescing. */
155
+ onMembers(cb: (members: readonly string[]) => void): () => void;
156
+ /** The labels every link carries, in the order they were asked for. */
157
+ readonly channels: readonly string[];
158
+ /** Fires when one channel of a link opens; replays channels that are already open. */
159
+ onOpen(cb: (origin: string, channel: string) => void): () => void;
160
+ onMessage(cb: (origin: string, frame: string, channel: string) => void): () => void;
161
+ /**
162
+ * Fires when a link goes away: a channel closed, the connector reported it gone, it did not
163
+ * open in time, or the relay reported the origin gone. A lost link is rebuilt while the relay
164
+ * lists its origin.
165
+ */
166
+ onClose(cb: (origin: string) => void): () => void;
167
+ /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */
168
+ onEnd(cb: () => void): () => void;
169
+ /** Sends on one open channel; a frame for a channel that is not open is dropped. */
170
+ send(origin: string, frame: string, channel?: string): void;
171
+ /** Sends on the channel of every link where it is open. */
172
+ broadcast(frame: string, channel?: string): void;
173
+ /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */
174
+ connect(): void;
175
+ close(): void;
176
+ };
177
+ /**
178
+ * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
179
+ * room, set up from relay membership and negotiated over relay `signal` frames. Each link
180
+ * carries the same labelled channels; frames are opaque strings, what they mean is the
181
+ * consumer's business.
182
+ *
183
+ * An origin is one seat: the relay hands a second connection with the same origin the seat
184
+ * and reports it to the room as a plain join. Links tell seats apart by instance, not by
185
+ * order: every link announces a random instance id in its signals and, once it knows the
186
+ * instance across, addresses its signals to it. A signal addressed to an instance this side
187
+ * no longer has is dropped. An unaddressed signal from an instance other than the one linked
188
+ * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
189
+ * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
190
+ * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
191
+ * still take the seat from each other on every reconnect; give each tab its own origin.
192
+ *
193
+ * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is
194
+ * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for
195
+ * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may
196
+ * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild
197
+ * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.
198
+ *
199
+ * No link is built before the welcome of the connection it signals over: joins before it are
200
+ * superseded by the welcome's roster and signals are held and replayed after it, so every link
201
+ * is built with that welcome's ICE servers and never an earlier connection's.
202
+ */
203
+ declare function peerLinks(opt: PeerLinksOptions): PeerLinks;
28
204
 
29
205
  type MeshPeer = PresenceState;
30
206
  /**
31
207
  * A composed, user-facing health status for a synced store the surface that
32
208
  * turns a versioned reject from a dead socket into a speakable 'outdated' banner.
33
209
  */
34
- type SyncHealthStatus = 'live' | 'offline' | 'outdated' | 'ejected' | 'degraded';
210
+ type SyncHealthStatus = 'live' | 'waiting' | 'offline' | 'outdated' | 'ejected' | 'degraded';
35
211
  type SyncHealth = {
36
212
  readonly status: SyncHealthStatus;
37
213
  /** Why, when the status is `outdated`/`ejected`/`degraded`. */
@@ -103,12 +279,15 @@ type MeshSyncOptions = {
103
279
  * on the next welcome, instead of being lost with in-memory state. The payload is written to
104
280
  * `store` under `key`, debounced.
105
281
  *
106
- * By default (`crossTab: 'queue'`) a Web Lock on `key` makes this a single-writer-per-key resource:
107
- * a second tab sharing the key WAITS (stays `connecting`, surfaced via `status`/`health`) until the
108
- * first releases, rather than restoring the same origin and colliding on version mints. Set
109
- * `crossTab: 'off'` to skip the lock and coordinate ownership yourself (e.g. a per-tab key, or
110
- * leader election over `tabSync`). A debounced write means a hard crash within the debounce window
111
- * can drop the very last mint — a small, best-effort gap; tune it with `debounceMs`.
282
+ * The persisted outbox under `key` is a single-writer slot: every persist overwrites it whole, so
283
+ * two tabs writing one key would each drop the other's tail from disk. A Web Lock on `key` elects
284
+ * the one tab that restores from the slot and writes to it; origins are fresh on every boot either
285
+ * way, so the lock guards the slot, not the origin. `crossTab` sets what a tab that did not get the
286
+ * lock does: `'queue'` (default) waits (`status` reads `'waiting'`) and takes over when the owner
287
+ * closes; `'ephemeral'` runs live at once and never touches the slot. `'off'` skips the lock and
288
+ * leaves ownership to you (e.g. a per-tab key, or leader election over `tabSync`). A debounced
289
+ * write means a hard crash within the debounce window can drop the very last mint — a small,
290
+ * best-effort gap; tune it with `debounceMs`.
112
291
  */
113
292
  readonly outbox?: {
114
293
  readonly key: string;
@@ -116,11 +295,16 @@ type MeshSyncOptions = {
116
295
  /** Coalesce outbox writes by this many ms (default 300; `0` = write on every change). */
117
296
  readonly debounceMs?: number;
118
297
  /**
119
- * Cross-tab contention for the shared `key`. `'queue'` (default) holds a Web Lock so only one tab
120
- * owns the durable outbox at a time; others wait. `'off'` skips the lock (you coordinate).
121
- * (A future `'ephemeral'` — non-leaders run live with a throwaway origin — is planned.)
298
+ * Cross-tab contention for the shared `key`. The persisted outbox is a single-writer slot: the
299
+ * Web Lock elects the one tab that restores from it and writes to it.
300
+ * `'queue'` (default): a tab that did not get the lock WAITS (`status` reads `'waiting'`) and
301
+ * takes over when the owner closes. `'ephemeral'`: it runs live at once on its own fresh origin
302
+ * and never touches the slot — its unacknowledged writes live in memory only and are lost if that
303
+ * tab terminates before the room acknowledges them — online or offline, and it stays ephemeral
304
+ * for life, also after the owner leaves. When the lock is free both behave the same (take it,
305
+ * restore, persist). `'off'` skips the lock (you coordinate ownership).
122
306
  */
123
- readonly crossTab?: 'queue' | 'off';
307
+ readonly crossTab?: 'queue' | 'off' | 'ephemeral';
124
308
  };
125
309
  };
126
310
  /**
@@ -135,6 +319,12 @@ type MeshSyncOptions = {
135
319
  type SeatSync<T = unknown> = Pick<OpSync<T>, 'override' | 'captureFrontier' | 'commitScope' | 'liveUnder' | 'liveAt' | 'appliedFrontier'>;
136
320
  type MeshSyncRef<T extends object = Record<string, unknown>> = {
137
321
  readonly status: Signal<MeshStatus>;
322
+ /** Origin used by the current session's hello; null until hello, including while waiting on an outbox. */
323
+ readonly origin: Signal<string | null>;
324
+ /** Other relay members, including peers with no presence; empty before welcome and while disconnected. */
325
+ readonly members: Signal<readonly string[]>;
326
+ /** Peer signaling on this session's connection; buffers up to 256 early signals until the first listener. */
327
+ readonly signaling: SignalingPort;
138
328
  /** Composed sync-health for a user-facing surface. */
139
329
  readonly health: Signal<SyncHealth>;
140
330
  /**
@@ -306,45 +496,35 @@ declare function setAtPath(node: unknown, path: string | readonly PathSegment[],
306
496
  */
307
497
  declare function describeOp(op: StoreOp, writer: string): string;
308
498
 
309
- /** A data channel as the P2P engine needs it; opens later, buffers nothing itself. */
310
- type DataChannelLike = {
311
- send(frame: string): void;
312
- onMessage(cb: (frame: string) => void): () => void;
313
- onOpen(cb: () => void): () => void;
314
- onClose(cb: () => void): () => void;
315
- close(): void;
316
- };
317
- /**
318
- * Creates one peer link. `polite` assigns the perfect-negotiation role (derived
319
- * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads
320
- * through the relay; `signal` delivers the remote side's payloads.
321
- */
322
- type PeerConnector = (opt: {
323
- readonly remote: string;
324
- readonly polite: boolean;
325
- readonly sendSignal: (data: unknown) => void;
326
- }) => {
327
- readonly channel: DataChannelLike;
328
- signal(data: unknown): void;
329
- close(): void;
330
- };
331
- /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
332
- declare function rtcPeerConnector(config?: RTCConfiguration): PeerConnector;
333
499
  type WebRtcMeshOptions = {
334
500
  readonly room: string;
335
501
  readonly writer: string;
502
+ /**
503
+ * This replica's origin, its identity in the room; defaults to a random id per instance.
504
+ * One origin is one seat, so never share one between two live instances.
505
+ */
506
+ readonly origin?: string;
336
507
  /** Signaling path to the relay (ws or direct) — data flows peer-to-peer. */
337
508
  readonly signaling: MeshTransportFactory;
338
509
  /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
339
510
  readonly connector?: PeerConnector;
511
+ /**
512
+ * Further channels every link carries beside the mesh's own reliable one, for consumers
513
+ * that share the links (`rtcPresence`, say). Reach them through {@link WebRtcMeshRef.links}.
514
+ */
515
+ readonly channels?: readonly PeerChannelSpec[];
340
516
  readonly policies?: readonly MergePolicyEntry[];
341
517
  readonly policyVersion?: number;
342
518
  readonly injector?: Injector;
343
519
  };
344
520
  type WebRtcMeshRef = {
521
+ /** This replica's origin: what other peers see this side as, in `peers` and on the wire. */
522
+ readonly origin: string;
345
523
  readonly status: Signal<'connecting' | 'live'>;
346
524
  /** Origins with an OPEN data channel. */
347
525
  readonly peers: Signal<readonly string[]>;
526
+ /** The links the mesh runs on; other channels asked for in `channels` are sent on these. */
527
+ readonly links: PeerLinks;
348
528
  close(): void;
349
529
  };
350
530
  /**
@@ -363,5 +543,65 @@ type WebRtcMeshRef = {
363
543
  */
364
544
  declare function webRtcMesh<T extends object>(source: WritableSignal<T>, opt: WebRtcMeshOptions): WebRtcMeshRef;
365
545
 
366
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
367
- export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerConnector, SeatChange, SeatEvent, SeatResync, SeatSync, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };
546
+ /**
547
+ * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
548
+ * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
549
+ * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
550
+ */
551
+ declare const presenceChannel: PeerChannelSpec;
552
+ /**
553
+ * What goes over the wire. `seq` counts frames sent on one channel of one links object, in
554
+ * send order, and is shared by every sender created on those links; it never restarts while
555
+ * the links live. It orders frames of one link only, and is never compared across links.
556
+ */
557
+ type PresenceFrame<T> = {
558
+ readonly seq: number;
559
+ readonly value: T;
560
+ };
561
+ type RtcPresenceOptions = {
562
+ /** The channel label on the links; defaults to {@link presenceChannel}'s. */
563
+ readonly channel?: string;
564
+ /** Minimum gap between two published frames. Defaults to 33 ms (about 30 per second). */
565
+ readonly throttleMs?: number;
566
+ /**
567
+ * Who is in the room, from the relay. A value is held only for an origin in it: a peer link
568
+ * can outlive the relay membership on a dead socket, so the link is not proof of presence.
569
+ * Subscribe synchronously with the current roster, then report every transition, including
570
+ * a leave followed immediately by a rejoin. Use `links.onMembers` for the links' relay roster.
571
+ * A sampled signal or an effect cannot preserve these transitions.
572
+ */
573
+ readonly roster: (cb: (members: readonly string[]) => void) => () => void;
574
+ readonly injector?: Injector;
575
+ };
576
+ type RtcPresenceRef<T> = {
577
+ /** Publishes this side's value; throttled, and the last value of a burst always goes out. */
578
+ set(value: T): void;
579
+ /** The latest value per origin, only for origins in the roster. */
580
+ readonly peers: Signal<ReadonlyMap<string, T>>;
581
+ /** Stops publishing and forgets every held value. The links stay open. */
582
+ close(): void;
583
+ };
584
+ /**
585
+ * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
586
+ * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
587
+ * sender's next `set`.
588
+ *
589
+ * Order comes from causality the receiver observes, never from clocks or from numbers chosen
590
+ * by different senders. A value is held only for an origin in the roster, and it is removed
591
+ * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
592
+ * below it is dropped: one counter stamps every frame sent on that link in send order, so a
593
+ * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
594
+ * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
595
+ * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
596
+ * and nobody reads `peers` between leave and rejoin.
597
+ *
598
+ * The counter belongs to the links and the channel, not to this sender, so a sender closed
599
+ * and recreated on the same links carries on where the last one stopped and is heard at
600
+ * once. A new tab or device is a new link, which every receiver already treats as fresh.
601
+ *
602
+ * Values travel as JSON.
603
+ */
604
+ declare function rtcPresence<T>(links: PeerLinks, opt: RtcPresenceOptions): RtcPresenceRef<T>;
605
+
606
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
607
+ export type { AgentSeat, AgentSeatOptions, DataChannelLike, MeshPeer, MeshStatus, MeshSyncOptions, MeshSyncRef, MeshTransport, MeshTransportFactory, PeerChannelSpec, PeerConnector, PeerLinks, PeerLinksOptions, PresenceFrame, RtcPresenceOptions, RtcPresenceRef, SeatChange, SeatEvent, SeatResync, SeatSync, SignalingPort, StableSnapshot, SyncHealth, SyncHealthStatus, WebRtcMeshOptions, WebRtcMeshRef };