@mmstack/mesh 21.9.1 → 21.10.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmstack/mesh",
3
- "version": "21.9.1",
3
+ "version": "21.10.1",
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": ">=21 <22",
23
- "@mmstack/primitives": ">=21.15 <22",
24
- "@mmstack/mesh-protocol": ">=0.9 <1"
23
+ "@mmstack/primitives": ">=21.16 <22",
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, ClientSignalMsg } 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`. */
@@ -98,17 +274,20 @@ type MeshSyncOptions = {
98
274
  */
99
275
  readonly whenReady?: () => PromiseLike<void> | void;
100
276
  /**
101
- * Persist the unacknowledged local outbox (and this client's stable origin) so offline writes
277
+ * Persist the unacknowledged local outbox (and the writing boot's origin) so offline writes
102
278
  * survive a REBOOT, not just a live reconnect: on boot they are restored and rebased onto the room
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,133 +496,6 @@ 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
- /** One data channel on a peer link. `ordered: false` + `maxRetransmits: 0` makes it lossy. */
318
- type PeerChannelSpec = {
319
- readonly label: string;
320
- readonly ordered?: boolean;
321
- readonly maxRetransmits?: number;
322
- };
323
- /** The single reliable channel every link carries when no channels are asked for. */
324
- declare const defaultPeerChannels: readonly PeerChannelSpec[];
325
- /**
326
- * Creates one peer link. `polite` assigns the perfect-negotiation role (derived
327
- * deterministically from origin ordering); `sendSignal` routes offer/answer/ICE payloads
328
- * through the relay; `signal` delivers the remote side's payloads. Object payloads gain a
329
- * `link` field on the way out (the sending link's instance id) and, once the remote instance
330
- * is known, a `to` field; both are stripped before `signal` sees the payload.
331
- *
332
- * `channels` lists the labelled channels the link carries; `channel` is the first of them and
333
- * `channels` (by label) all of them. A connector that returns only `channel` supports a single
334
- * channel. Signal payloads carry no channel field: one link per remote carries every channel,
335
- * so nothing needs routing. The field name `ch` is kept free for a future where it does.
336
- */
337
- type PeerConnector = (opt: {
338
- readonly remote: string;
339
- readonly polite: boolean;
340
- readonly sendSignal: (data: unknown) => void;
341
- readonly channels: readonly PeerChannelSpec[];
342
- }) => {
343
- readonly channel: DataChannelLike;
344
- readonly channels?: Readonly<Record<string, DataChannelLike>>;
345
- signal(data: unknown): void;
346
- close(): void;
347
- };
348
- /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
349
- declare function rtcPeerConnector(config?: RTCConfiguration): PeerConnector;
350
- /**
351
- * A relay connection someone else owns (a live session, say). Peer links ride on it without
352
- * saying hello, so the links share that connection's origin and room membership.
353
- */
354
- type SignalingPort = {
355
- /** Current relay membership for this room, or undefined until welcomed. Read after subscribing. */
356
- members(): readonly string[] | undefined;
357
- send(msg: ClientSignalMsg): void;
358
- onMessage(cb: (msg: ServerMsg) => void): () => void;
359
- };
360
- type PeerLinksOptions = {
361
- readonly room: string;
362
- /** This side's origin; also decides the perfect-negotiation role against each remote. */
363
- readonly origin: string;
364
- /**
365
- * A transport factory means the links own their relay connection (hello, reconnect); a
366
- * {@link SignalingPort} means they ride on one that is already joined.
367
- */
368
- readonly signaling: MeshTransportFactory | SignalingPort;
369
- /** Peer link factory; defaults to {@link rtcPeerConnector}. Injectable for tests. */
370
- readonly connector?: PeerConnector;
371
- /**
372
- * The channels every link carries, first one the default for `send` and `broadcast`.
373
- * Defaults to {@link defaultPeerChannels}. Both sides must ask for the same labels.
374
- */
375
- readonly channels?: readonly PeerChannelSpec[];
376
- /** Sent in the hello when the links own their connection. */
377
- readonly policyVersion?: number;
378
- /**
379
- * `false` defers signaling until {@link PeerLinks.connect}, so a consumer can subscribe
380
- * before the first link opens. Defaults to `true`.
381
- */
382
- readonly autoConnect?: boolean;
383
- readonly injector?: Injector;
384
- };
385
- type PeerLinks = {
386
- /**
387
- * `live` once the relay has welcomed this side (or, over a port, once it has seen a
388
- * welcome); back to `connecting` while an owned relay connection is being re-established.
389
- * Peer links outlive that: they are torn down only by their own close or a relay `gone`.
390
- */
391
- readonly status: Signal<'connecting' | 'live'>;
392
- /** Origins whose link has every channel open. */
393
- readonly peers: Signal<readonly string[]>;
394
- /**
395
- * Other origins in the room as the relay reports them (welcome, then join and leave). The
396
- * relay is the authority on who is present; a link can outlive a dead socket for a while.
397
- */
398
- readonly members: Signal<readonly string[]>;
399
- /** Replays current membership synchronously, then reports every change without coalescing. */
400
- onMembers(cb: (members: readonly string[]) => void): () => void;
401
- /** The labels every link carries, in the order they were asked for. */
402
- readonly channels: readonly string[];
403
- /** Fires when one channel of a link opens; replays channels that are already open. */
404
- onOpen(cb: (origin: string, channel: string) => void): () => void;
405
- onMessage(cb: (origin: string, frame: string, channel: string) => void): () => void;
406
- /** Fires when a link goes away: a channel closed or the relay reported the origin gone. */
407
- onClose(cb: (origin: string) => void): () => void;
408
- /** Fires once when the links shut down: `close()`, or the relay rejected the hello. */
409
- onEnd(cb: () => void): () => void;
410
- /** Sends on one open channel; a frame for a channel that is not open is dropped. */
411
- send(origin: string, frame: string, channel?: string): void;
412
- /** Sends on the channel of every link where it is open. */
413
- broadcast(frame: string, channel?: string): void;
414
- /** Starts signaling when created with `autoConnect: false`; a no-op otherwise. */
415
- connect(): void;
416
- close(): void;
417
- };
418
- /**
419
- * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
420
- * room, set up from relay membership and negotiated over relay `signal` frames. Each link
421
- * carries the same labelled channels; frames are opaque strings, what they mean is the
422
- * consumer's business.
423
- *
424
- * An origin is one seat: the relay hands a second connection with the same origin the seat
425
- * and reports it to the room as a plain join. Links tell seats apart by instance, not by
426
- * order: every link announces a random instance id in its signals and, once it knows the
427
- * instance across, addresses its signals to it. A signal addressed to an instance this side
428
- * no longer has is dropped. An unaddressed signal from an instance other than the one linked
429
- * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
430
- * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
431
- * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
432
- * still take the seat from each other on every reconnect; give each tab its own origin.
433
- */
434
- declare function peerLinks(opt: PeerLinksOptions): PeerLinks;
435
-
436
499
  type WebRtcMeshOptions = {
437
500
  readonly room: string;
438
501
  readonly writer: string;