@mmstack/mesh 22.10.2 → 22.12.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.
@@ -1,2216 +1,1775 @@
1
- import { createWatch } from '@angular/core/primitives/signals';
2
- import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
3
- import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
4
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, untracked, effect } from '@angular/core';
5
-
1
+ import { createWatch } from "@angular/core/primitives/signals";
2
+ import { OP_PROTO_VERSION, createConvergingApply, createStoreContext, forkStore, isStoreReservedKey, opSync, registerResource, store, throttled } from "@mmstack/primitives/core";
3
+ import { MESH_PROTO_VERSION, checkEnvelope } from "@mmstack/mesh-protocol";
4
+ import { DestroyRef, Injector, computed, effect, inject, isDevMode, runInInjectionContext, signal, untracked } from "@angular/core";
6
5
  const RECONNECT_BASE_MS = 500;
7
6
  function meshSession(opt) {
8
- const { sync, hooks } = opt;
9
- const schedule = opt.schedule ?? {
10
- set: (fn, ms) => setTimeout(fn, ms),
11
- clear: (handle) => clearTimeout(handle),
12
- };
13
- let status = 'connecting';
14
- const ownOrigins = new Set([sync.origin]);
15
- const unacked = new Map();
16
- const acked = new Map();
17
- const unackedKey = (env) => `${env.origin} ${env.version}`;
18
- let lastSeq = 0;
19
- let instance = opt.instance;
20
- if (instance)
21
- sync.adopt(instance);
22
- // a refusal asks for a fresh snapshot; one hello per burst, cleared by the welcome it earns
23
- let rehydrating = false;
24
- let peers = new Map();
25
- let members;
26
- let presenceData;
27
- let hasPresence = false;
28
- let transport = null;
29
- let attempts = 0;
30
- let reconnectTimer;
31
- let unsubs = [];
32
- let closed = false;
33
- let ackFailure;
34
- const ackWaiters = [];
35
- const releaseAckWaiters = (failure) => {
36
- for (const waiter of ackWaiters.splice(0)) {
37
- if (failure)
38
- waiter.reject(failure);
39
- else
40
- waiter.resolve();
41
- }
42
- };
43
- const setStatus = (next, reason) => {
44
- status = next;
45
- hooks.onStatus(next, reason);
46
- };
47
- const terminal = (state, reason) => {
48
- if (closed)
49
- return;
50
- closed = true;
51
- if (reconnectTimer !== undefined) {
52
- schedule.clear(reconnectTimer);
53
- reconnectTimer = undefined;
54
- }
55
- for (const unsub of unsubs.splice(0))
56
- unsub();
57
- unsubLocal();
58
- hooks.onTerminal?.(state, reason); // unacked is still intact here — the persist window
59
- if (unacked.size > 0) {
60
- // these writes are not in the room and never will be on this session
61
- ackFailure = new Error(reason ?? state);
62
- releaseAckWaiters(ackFailure);
63
- }
64
- else {
65
- releaseAckWaiters();
66
- }
67
- unacked.clear();
68
- transport?.close();
69
- transport = null;
70
- peers = new Map();
71
- hooks.onPeers?.(peers);
72
- members = undefined;
73
- hooks.onMembers?.(members);
74
- setStatus(state, reason);
75
- };
76
- const sendEnv = (env) => {
77
- // an envelope minted before any generation was known adopts the one this session is in
78
- let out = env;
79
- if (env.instance === '' && instance) {
80
- out = { ...env, instance };
81
- unacked.set(unackedKey(env), out);
82
- }
83
- transport?.send({ t: 'env', room: opt.room, env: out });
84
- };
85
- const sendHello = () => {
86
- if (!transport)
87
- return;
88
- hooks.onOrigin?.(sync.origin);
89
- transport?.send({
90
- t: 'hello',
91
- room: opt.room,
92
- origin: sync.origin,
93
- proto: MESH_PROTO_VERSION,
94
- policyVersion: opt.policyVersion,
95
- seq: lastSeq > 0 ? lastSeq : undefined,
96
- schemaVersion: opt.schemaVersion,
97
- });
98
- };
99
- const ackOwn = (origin, version) => {
100
- if (!unacked.delete(unackedKey({ origin, version })))
101
- return;
102
- acked.set(origin, Math.max(acked.get(origin) ?? 0, version));
103
- hooks.onOutboxChange?.();
104
- if (unacked.size === 0)
105
- releaseAckWaiters();
106
- };
107
- const refuse = (env, reason) => {
108
- unacked.delete(unackedKey(env));
109
- hooks.onRefused?.(env, reason);
110
- hooks.onOutboxChange?.();
111
- // "every write was classified" is not "every write was stored": a waiter rejects
112
- releaseAckWaiters(new Error(`refused: ${reason}`));
113
- };
114
- const flushUnacked = () => {
115
- for (const env of unacked.values())
116
- sendEnv(env);
117
- };
118
- const applyRemote = (env) => {
119
- if (closed)
120
- return; // a delta welcome keeps iterating after an eject — nothing lands past it
121
- if (opt.schemaVersion !== undefined &&
122
- env.schemaVersion !== undefined &&
123
- env.schemaVersion > opt.schemaVersion) {
124
- terminal('ejected', 'schema');
125
- return;
126
- }
127
- lastSeq = Math.max(lastSeq, env.seq);
128
- hooks.onSynced?.();
129
- if (ownOrigins.has(env.origin)) {
130
- ackOwn(env.origin, env.version);
131
- return;
132
- }
133
- sync.receive(env);
134
- hooks.onRemote?.({ seq: env.seq, writer: env.writer, ops: env.ops });
135
- };
136
- const handle = (msg) => {
137
- if (msg.room !== opt.room)
138
- return;
139
- switch (msg.t) {
140
- case 'welcome': {
141
- const instanceChanged = instance !== undefined && msg.instance !== instance;
142
- const prevSeq = lastSeq;
143
- if (instanceChanged) {
144
- // the generation boundary on the client: the tail written in the old one is refused
145
- // loudly, its acknowledgements mean nothing here, and the new generation's snapshot
146
- // replaces the whole applied state below
147
- lastSeq = 0;
148
- acked.clear();
149
- for (const env of [...unacked.values()])
150
- refuse(env, 'generation');
151
- }
152
- instance = msg.instance;
153
- sync.adopt(msg.instance);
154
- rehydrating = false;
155
- peers = new Map(msg.peers.map((p) => [p.origin, p]));
156
- hooks.onPeers?.(peers);
157
- members = [
158
- ...new Set(msg.members.filter((origin) => origin !== sync.origin)),
159
- ];
160
- hooks.onMembers?.(members);
161
- const resync = msg.mode === 'snapshot' || instanceChanged;
162
- if (msg.mode === 'delta') {
163
- for (const env of msg.envs)
164
- applyRemote(env);
165
- }
166
- else if (msg.mode === 'snapshot') {
167
- const conv = createConvergingApply({ policies: opt.policies });
168
- conv.load(msg.registers);
169
- const ownWm = {};
170
- for (const o of ownOrigins)
171
- ownWm[o] = acked.get(o) ?? 0;
172
- sync.hydrate({
173
- root: conv.materialize(),
174
- registers: msg.registers,
175
- wm: { ...msg.wm, ...ownWm },
176
- }, [...unacked.values()]);
177
- lastSeq = msg.seq;
178
- }
179
- else if (msg.seq === 0 && lastSeq === 0) {
180
- sync.seed();
181
- }
182
- // every branch can end terminal (schema eject in a delta env, a seed or rebase
183
- // emission tripping the emit-side policy) — never revive to live
184
- if (closed) {
185
- if (instanceChanged && lastSeq === 0)
186
- lastSeq = prevSeq;
187
- return;
188
- }
189
- lastSeq = Math.max(lastSeq, msg.seq);
190
- attempts = 0;
191
- hooks.onSynced?.();
192
- if (resync)
193
- hooks.onResync?.(lastSeq);
194
- setStatus('live');
195
- flushUnacked();
196
- if (hasPresence)
197
- transport?.send({
198
- t: 'presence',
199
- room: opt.room,
200
- data: presenceData,
201
- });
202
- return;
203
- }
204
- case 'env':
205
- applyRemote(msg.env);
206
- return;
207
- case 'presence': {
208
- const next = new Map(peers);
209
- if (msg.gone)
210
- next.delete(msg.peer.origin);
211
- else
212
- next.set(msg.peer.origin, msg.peer);
213
- peers = next;
214
- hooks.onPeers?.(peers);
215
- return;
216
- }
217
- case 'member': {
218
- if (members === undefined || msg.origin === sync.origin)
219
- return;
220
- members = msg.gone
221
- ? members.filter((origin) => origin !== msg.origin)
222
- : members.includes(msg.origin)
223
- ? members
224
- : [...members, msg.origin];
225
- hooks.onMembers?.(members);
226
- return;
227
- }
228
- case 'eject':
229
- if (msg.writer === opt.writer)
230
- terminal('ejected', msg.reason);
231
- return;
232
- case 'reject':
233
- terminal('ejected', msg.reason);
234
- return;
235
- case 'settled':
236
- sync.settle(msg.settled);
237
- return;
238
- case 'drop': {
239
- const held = unacked.get(unackedKey(msg));
240
- if (!held)
241
- return; // already classified (a duplicate reply after the echo, or an old generation's)
242
- if (msg.reason === 'duplicate') {
243
- ackOwn(msg.origin, msg.version); // the room holds it: this is the acknowledgement
244
- return;
245
- }
246
- refuse(held, msg.reason);
247
- // the refused write is still applied locally: drop and rehydrate from a fresh snapshot
248
- if (!rehydrating) {
249
- rehydrating = true;
250
- lastSeq = 0;
251
- sendHello();
252
- }
253
- return;
254
- }
255
- }
256
- };
257
- const connect = () => {
258
- if (closed)
259
- return;
260
- for (const unsub of unsubs.splice(0))
261
- unsub();
262
- const t = opt.transport();
263
- transport = t;
264
- unsubs = [
265
- t.onMessage((msg) => {
266
- if (closed || transport !== t || msg.room !== opt.room)
267
- return;
268
- handle(msg);
269
- if (!closed || msg.t === 'reject' || msg.t === 'eject')
270
- hooks.onMessage?.(msg);
271
- }),
272
- t.onClose(() => {
273
- if (closed || transport !== t)
274
- return;
275
- transport = null;
276
- members = undefined;
277
- hooks.onMembers?.(members);
278
- setStatus('reconnecting');
279
- const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15_000, RECONNECT_BASE_MS * 2 ** attempts++);
280
- reconnectTimer = schedule.set(() => {
281
- reconnectTimer = undefined;
282
- connect();
283
- }, delay + Math.random() * 100);
284
- }),
285
- ];
286
- sendHello();
287
- };
288
- const unsubLocal = sync.subscribe((env) => {
289
- const violation = checkEnvelope(opt.policy, env, { ...opt.ctx, writer: opt.writer }, opt.room,
290
- // the last sequence this client observed; it can only lag the relay's, so a rule that
291
- // keys off an empty room is at worst more permissive here than it is at the relay
292
- { seq: lastSeq });
293
- if (violation) {
294
- // same outcome the relay's own check would produce one hop later — the emit-side
295
- // check is an optimization, never the enforcement
296
- hooks.onLocalReject?.(violation);
297
- terminal('ejected', violation.reason);
298
- return;
299
- }
300
- ownOrigins.add(env.origin); // the fresh mint, or a restored-tail origin resending verbatim
301
- unacked.set(unackedKey(env), env);
302
- hooks.onOutboxChange?.();
303
- if (status === 'live')
304
- sendEnv(env);
305
- });
306
- return {
307
- connect,
308
- status: () => status,
309
- lastSeq: () => lastSeq,
310
- hasUnacked: () => unacked.size > 0,
311
- whenAcked: () => ackFailure
312
- ? Promise.reject(ackFailure)
313
- : unacked.size === 0
314
- ? Promise.resolve()
315
- : new Promise((resolve, reject) => {
316
- ackWaiters.push({ resolve, reject });
317
- }),
318
- unackedEnvs: () => [...unacked.values()],
319
- instance: () => instance,
320
- peers: () => peers,
321
- sendSignal: (msg) => {
322
- if (!closed && msg.room === opt.room)
323
- transport?.send(msg);
324
- },
325
- setPresence: (data) => {
326
- presenceData = data;
327
- hasPresence = true;
328
- if (status === 'live') {
329
- transport?.send({ t: 'presence', room: opt.room, data });
330
- }
331
- },
332
- close: () => terminal('closed'),
333
- };
7
+ const { sync, hooks } = opt;
8
+ const schedule = opt.schedule ?? {
9
+ set: (fn, ms) => setTimeout(fn, ms),
10
+ clear: (handle) => clearTimeout(handle)
11
+ };
12
+ let status = "connecting";
13
+ const ownOrigins = /* @__PURE__ */ new Set([sync.origin]);
14
+ const unacked = /* @__PURE__ */ new Map();
15
+ const acked = /* @__PURE__ */ new Map();
16
+ const unackedKey = (env) => `${env.origin} ${env.version}`;
17
+ let lastSeq = 0;
18
+ let instance = opt.instance;
19
+ if (instance) sync.adopt(instance);
20
+ let rehydrating = false;
21
+ let peers = /* @__PURE__ */ new Map();
22
+ let members;
23
+ let presenceData;
24
+ let hasPresence = false;
25
+ let transport = null;
26
+ let attempts = 0;
27
+ let reconnectTimer;
28
+ let unsubs = [];
29
+ let closed = false;
30
+ let ackFailure;
31
+ const ackWaiters = [];
32
+ const releaseAckWaiters = (failure) => {
33
+ for (const waiter of ackWaiters.splice(0)) if (failure) waiter.reject(failure);
34
+ else waiter.resolve();
35
+ };
36
+ const setStatus = (next, reason) => {
37
+ status = next;
38
+ hooks.onStatus(next, reason);
39
+ };
40
+ const terminal = (state, reason) => {
41
+ if (closed) return;
42
+ closed = true;
43
+ if (reconnectTimer !== void 0) {
44
+ schedule.clear(reconnectTimer);
45
+ reconnectTimer = void 0;
46
+ }
47
+ for (const unsub of unsubs.splice(0)) unsub();
48
+ unsubLocal();
49
+ hooks.onTerminal?.(state, reason);
50
+ if (unacked.size > 0) {
51
+ ackFailure = new Error(reason ?? state);
52
+ releaseAckWaiters(ackFailure);
53
+ } else releaseAckWaiters();
54
+ unacked.clear();
55
+ transport?.close();
56
+ transport = null;
57
+ peers = /* @__PURE__ */ new Map();
58
+ hooks.onPeers?.(peers);
59
+ members = void 0;
60
+ hooks.onMembers?.(members);
61
+ setStatus(state, reason);
62
+ };
63
+ const sendEnv = (env) => {
64
+ let out = env;
65
+ if (env.instance === "" && instance) {
66
+ out = {
67
+ ...env,
68
+ instance
69
+ };
70
+ unacked.set(unackedKey(env), out);
71
+ }
72
+ transport?.send({
73
+ t: "env",
74
+ room: opt.room,
75
+ env: out
76
+ });
77
+ };
78
+ const sendHello = () => {
79
+ if (!transport) return;
80
+ hooks.onOrigin?.(sync.origin);
81
+ transport?.send({
82
+ t: "hello",
83
+ room: opt.room,
84
+ origin: sync.origin,
85
+ proto: MESH_PROTO_VERSION,
86
+ policyVersion: opt.policyVersion,
87
+ seq: lastSeq > 0 ? lastSeq : void 0,
88
+ schemaVersion: opt.schemaVersion
89
+ });
90
+ };
91
+ const ackOwn = (origin, version) => {
92
+ if (!unacked.delete(unackedKey({
93
+ origin,
94
+ version
95
+ }))) return;
96
+ acked.set(origin, Math.max(acked.get(origin) ?? 0, version));
97
+ hooks.onOutboxChange?.();
98
+ if (unacked.size === 0) releaseAckWaiters();
99
+ };
100
+ const refuse = (env, reason) => {
101
+ unacked.delete(unackedKey(env));
102
+ hooks.onRefused?.(env, reason);
103
+ hooks.onOutboxChange?.();
104
+ releaseAckWaiters(/* @__PURE__ */ new Error(`refused: ${reason}`));
105
+ };
106
+ const flushUnacked = () => {
107
+ for (const env of unacked.values()) sendEnv(env);
108
+ };
109
+ const applyRemote = (env) => {
110
+ if (closed) return;
111
+ if (opt.schemaVersion !== void 0 && env.schemaVersion !== void 0 && env.schemaVersion > opt.schemaVersion) {
112
+ terminal("ejected", "schema");
113
+ return;
114
+ }
115
+ lastSeq = Math.max(lastSeq, env.seq);
116
+ hooks.onSynced?.();
117
+ if (ownOrigins.has(env.origin)) {
118
+ ackOwn(env.origin, env.version);
119
+ return;
120
+ }
121
+ sync.receive(env);
122
+ hooks.onRemote?.({
123
+ seq: env.seq,
124
+ writer: env.writer,
125
+ ops: env.ops
126
+ });
127
+ };
128
+ const handle = (msg) => {
129
+ if (msg.room !== opt.room) return;
130
+ switch (msg.t) {
131
+ case "welcome": {
132
+ const instanceChanged = instance !== void 0 && msg.instance !== instance;
133
+ const prevSeq = lastSeq;
134
+ if (instanceChanged) {
135
+ lastSeq = 0;
136
+ acked.clear();
137
+ for (const env of [...unacked.values()]) refuse(env, "generation");
138
+ }
139
+ instance = msg.instance;
140
+ sync.adopt(msg.instance);
141
+ rehydrating = false;
142
+ peers = new Map(msg.peers.map((p) => [p.origin, p]));
143
+ hooks.onPeers?.(peers);
144
+ members = [...new Set(msg.members.filter((origin) => origin !== sync.origin))];
145
+ hooks.onMembers?.(members);
146
+ const resync = msg.mode === "snapshot" || instanceChanged;
147
+ if (msg.mode === "delta") for (const env of msg.envs) applyRemote(env);
148
+ else if (msg.mode === "snapshot") {
149
+ const conv = createConvergingApply({ policies: opt.policies });
150
+ conv.load(msg.registers);
151
+ const ownWm = {};
152
+ for (const o of ownOrigins) ownWm[o] = acked.get(o) ?? 0;
153
+ sync.hydrate({
154
+ root: conv.materialize(),
155
+ registers: msg.registers,
156
+ wm: {
157
+ ...msg.wm,
158
+ ...ownWm
159
+ }
160
+ }, [...unacked.values()]);
161
+ lastSeq = msg.seq;
162
+ } else if (msg.seq === 0 && lastSeq === 0) sync.seed();
163
+ if (closed) {
164
+ if (instanceChanged && lastSeq === 0) lastSeq = prevSeq;
165
+ return;
166
+ }
167
+ lastSeq = Math.max(lastSeq, msg.seq);
168
+ attempts = 0;
169
+ hooks.onSynced?.();
170
+ if (resync) hooks.onResync?.(lastSeq);
171
+ setStatus("live");
172
+ flushUnacked();
173
+ if (hasPresence) transport?.send({
174
+ t: "presence",
175
+ room: opt.room,
176
+ data: presenceData
177
+ });
178
+ return;
179
+ }
180
+ case "env":
181
+ applyRemote(msg.env);
182
+ return;
183
+ case "presence": {
184
+ const next = new Map(peers);
185
+ if (msg.gone) next.delete(msg.peer.origin);
186
+ else next.set(msg.peer.origin, msg.peer);
187
+ peers = next;
188
+ hooks.onPeers?.(peers);
189
+ return;
190
+ }
191
+ case "member":
192
+ if (members === void 0 || msg.origin === sync.origin) return;
193
+ members = msg.gone ? members.filter((origin) => origin !== msg.origin) : members.includes(msg.origin) ? members : [...members, msg.origin];
194
+ hooks.onMembers?.(members);
195
+ return;
196
+ case "eject":
197
+ if (msg.writer === opt.writer) terminal("ejected", msg.reason);
198
+ return;
199
+ case "reject":
200
+ terminal("ejected", msg.reason);
201
+ return;
202
+ case "settled":
203
+ sync.settle(msg.settled);
204
+ return;
205
+ case "drop": {
206
+ const held = unacked.get(unackedKey(msg));
207
+ if (!held) return;
208
+ if (msg.reason === "duplicate") {
209
+ ackOwn(msg.origin, msg.version);
210
+ return;
211
+ }
212
+ refuse(held, msg.reason);
213
+ if (!rehydrating) {
214
+ rehydrating = true;
215
+ lastSeq = 0;
216
+ sendHello();
217
+ }
218
+ return;
219
+ }
220
+ }
221
+ };
222
+ const connect = () => {
223
+ if (closed) return;
224
+ for (const unsub of unsubs.splice(0)) unsub();
225
+ const t = opt.transport();
226
+ transport = t;
227
+ unsubs = [t.onMessage((msg) => {
228
+ if (closed || transport !== t || msg.room !== opt.room) return;
229
+ handle(msg);
230
+ if (!closed || msg.t === "reject" || msg.t === "eject") hooks.onMessage?.(msg);
231
+ }), t.onClose(() => {
232
+ if (closed || transport !== t) return;
233
+ transport = null;
234
+ members = void 0;
235
+ hooks.onMembers?.(members);
236
+ setStatus("reconnecting");
237
+ const delay = Math.min(opt.reconnect?.maxDelayMs ?? 15e3, RECONNECT_BASE_MS * 2 ** attempts++);
238
+ reconnectTimer = schedule.set(() => {
239
+ reconnectTimer = void 0;
240
+ connect();
241
+ }, delay + Math.random() * 100);
242
+ })];
243
+ sendHello();
244
+ };
245
+ const unsubLocal = sync.subscribe((env) => {
246
+ const violation = checkEnvelope(opt.policy, env, {
247
+ ...opt.ctx,
248
+ writer: opt.writer
249
+ }, opt.room, { seq: lastSeq });
250
+ if (violation) {
251
+ hooks.onLocalReject?.(violation);
252
+ terminal("ejected", violation.reason);
253
+ return;
254
+ }
255
+ ownOrigins.add(env.origin);
256
+ unacked.set(unackedKey(env), env);
257
+ hooks.onOutboxChange?.();
258
+ if (status === "live") sendEnv(env);
259
+ });
260
+ return {
261
+ connect,
262
+ status: () => status,
263
+ lastSeq: () => lastSeq,
264
+ hasUnacked: () => unacked.size > 0,
265
+ whenAcked: () => ackFailure ? Promise.reject(ackFailure) : unacked.size === 0 ? Promise.resolve() : new Promise((resolve, reject) => {
266
+ ackWaiters.push({
267
+ resolve,
268
+ reject
269
+ });
270
+ }),
271
+ unackedEnvs: () => [...unacked.values()],
272
+ instance: () => instance,
273
+ peers: () => peers,
274
+ sendSignal: (msg) => {
275
+ if (!closed && msg.room === opt.room) transport?.send(msg);
276
+ },
277
+ setPresence: (data) => {
278
+ presenceData = data;
279
+ hasPresence = true;
280
+ if (status === "live") transport?.send({
281
+ t: "presence",
282
+ room: opt.room,
283
+ data
284
+ });
285
+ },
286
+ close: () => terminal("closed")
287
+ };
334
288
  }
335
-
336
289
  const microtaskDriver = () => (run) => {
337
- let scheduled = false;
338
- const watch = createWatch(() => run(), (w) => {
339
- if (scheduled)
340
- return;
341
- scheduled = true;
342
- queueMicrotask(() => {
343
- scheduled = false;
344
- w.run();
345
- });
346
- }, false);
347
- watch.notify();
348
- return { destroy: () => watch.destroy() };
290
+ let scheduled = false;
291
+ const watch = createWatch(() => run(), (w) => {
292
+ if (scheduled) return;
293
+ scheduled = true;
294
+ queueMicrotask(() => {
295
+ scheduled = false;
296
+ w.run();
297
+ });
298
+ }, false);
299
+ watch.notify();
300
+ return { destroy: () => watch.destroy() };
349
301
  };
350
- /**
351
- * A headless mesh peer: the same replica and wire contract `meshSync` implements in the
352
- * browser, without Angular's injector or any browser API — for agents, server-side bridges,
353
- * and device writers joining a room as first-class, attributed participants. Each call is
354
- * one identity with its own replica; run several seats in one process for several
355
- * collaborators. Governance is the room's: the relay's policy applies to a seat exactly as
356
- * to any human peer.
357
- */
358
302
  function agentSeat(initial, opt) {
359
- const context = opt.context ?? createStoreContext();
360
- const root = store(initial, context);
361
- const doc = root;
362
- const read = root;
363
- const policyVersion = opt.policyVersion ?? 0;
364
- // onReject fires synchronously inside receive(); the flag keeps a malformed envelope's
365
- // ops (which did NOT apply) out of the change stream.
366
- let rejected = false;
367
- const sync = opSync(root, {
368
- writer: opt.writer,
369
- policies: opt.policies,
370
- policyVersion,
371
- driver: microtaskDriver(),
372
- onReject: (_env, reason) => {
373
- rejected = true;
374
- console.warn(`[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`);
375
- },
376
- });
377
- const listeners = new Set();
378
- const emit = (event) => {
379
- for (const cb of [...listeners])
380
- cb(event);
381
- };
382
- let welcomed = false;
383
- let diverged = false;
384
- let terminated = false;
385
- let lostWrites = false;
386
- const session = meshSession({
387
- room: opt.room,
388
- writer: opt.writer,
389
- transport: opt.transport,
390
- sync,
391
- policies: opt.policies,
392
- policy: opt.policy,
393
- ctx: opt.ctx,
394
- policyVersion,
395
- schemaVersion: opt.schemaVersion,
396
- reconnect: opt.reconnect,
397
- hooks: {
398
- onStatus: (s, reason) => {
399
- if (s === 'live')
400
- welcomed = true;
401
- if (s === 'ejected' && reason !== undefined)
402
- opt.onEject?.(reason);
403
- },
404
- onRemote: (batch) => {
405
- if (rejected) {
406
- rejected = false;
407
- return;
408
- }
409
- emit({ kind: 'change', ...batch });
410
- },
411
- onResync: (seq) => emit({ kind: 'resync', seq }),
412
- onRefused: (env, reason) => {
413
- diverged = true; // the write stays applied until the rehydrate that follows lands
414
- opt.onRefused?.(env, reason);
415
- },
416
- onLocalReject: (violation) => {
417
- diverged = true; // the write stays in the replica but will never reach the room
418
- console.warn('[@mmstack/mesh] agent seat write violates the room policy — not sent', violation);
419
- },
420
- onTerminal: () => {
421
- if (session.hasUnacked()) {
422
- diverged = true;
423
- lostWrites = true; // latched: no echo can arrive for them now
424
- }
425
- terminated = true;
426
- },
427
- },
428
- });
429
- // a write after the terminal state is one the room will never sequence: the doc keeps it
430
- // (post-mortem), but the seat stops claiming provable folds — same latch as a refused write
431
- sync.subscribe(() => {
432
- if (terminated)
433
- diverged = true;
434
- });
435
- session.connect();
436
- return {
437
- doc,
438
- status: () => session.status(),
439
- peers: () => [...session.peers().values()],
440
- snapshot: () => read(),
441
- stableSnapshot: () => {
442
- sync.flush(); // a write made this tick must count as pending, not linger unstamped
443
- if (!welcomed || diverged || session.hasUnacked())
444
- return null;
445
- return { seq: session.lastSeq(), doc: read() };
446
- },
447
- write: (fn) => {
448
- fn();
449
- sync.flush();
450
- },
451
- setAtPath: (path, value) => {
452
- setAtPath(doc, path, value);
453
- sync.flush();
454
- },
455
- changes: (cb) => {
456
- listeners.add(cb);
457
- return () => listeners.delete(cb);
458
- },
459
- fork: (forkOpt) => {
460
- const f = forkStore(doc, forkOpt);
461
- let frontier = sync.captureFrontier();
462
- const recapture = () => {
463
- frontier = sync.captureFrontier();
464
- };
465
- return {
466
- store: f.store,
467
- ops: f.ops,
468
- commit: () => {
469
- sync.commitScope(frontier, () => f.commit());
470
- sync.flush();
471
- },
472
- discard: () => {
473
- f.discard();
474
- recapture();
475
- },
476
- rebase: recapture,
477
- };
478
- },
479
- acked: () => {
480
- sync.flush(); // a write made this tick counts as pending, not as unstamped
481
- return !lostWrites && !session.hasUnacked();
482
- },
483
- whenAcked: () => {
484
- sync.flush();
485
- return session.whenAcked();
486
- },
487
- setPresence: (data) => session.setPresence(data),
488
- sync: {
489
- override: (fn) => sync.override(fn),
490
- captureFrontier: () => sync.captureFrontier(),
491
- commitScope: (frontier, fn) => sync.commitScope(frontier, fn),
492
- liveUnder: (path) => sync.liveUnder(path),
493
- liveAt: (path) => sync.liveAt(path),
494
- appliedFrontier: () => sync.appliedFrontier(),
495
- },
496
- close: () => {
497
- diverged = true; // sync is destroyed below: later writes are unwatched, so no more proofs
498
- session.close();
499
- sync.destroy();
500
- },
501
- };
303
+ const context = opt.context ?? createStoreContext();
304
+ const root = store(initial, context);
305
+ const doc = root;
306
+ const read = root;
307
+ const policyVersion = opt.policyVersion ?? 0;
308
+ let rejected = false;
309
+ const sync = opSync(root, {
310
+ writer: opt.writer,
311
+ policies: opt.policies,
312
+ policyVersion,
313
+ driver: microtaskDriver(),
314
+ emit: opt.emit,
315
+ onReject: (_env, reason) => {
316
+ rejected = true;
317
+ console.warn(`[@mmstack/mesh] agent seat dropped a malformed envelope (${reason})`);
318
+ }
319
+ });
320
+ const listeners = /* @__PURE__ */ new Set();
321
+ const emit = (event) => {
322
+ for (const cb of [...listeners]) cb(event);
323
+ };
324
+ let welcomed = false;
325
+ let diverged = false;
326
+ let terminated = false;
327
+ let lostWrites = false;
328
+ const session = meshSession({
329
+ room: opt.room,
330
+ writer: opt.writer,
331
+ transport: opt.transport,
332
+ sync,
333
+ policies: opt.policies,
334
+ policy: opt.policy,
335
+ ctx: opt.ctx,
336
+ policyVersion,
337
+ schemaVersion: opt.schemaVersion,
338
+ reconnect: opt.reconnect,
339
+ hooks: {
340
+ onStatus: (s, reason) => {
341
+ if (s === "live") welcomed = true;
342
+ if (s === "ejected" && reason !== void 0) opt.onEject?.(reason);
343
+ },
344
+ onRemote: (batch) => {
345
+ if (rejected) {
346
+ rejected = false;
347
+ return;
348
+ }
349
+ emit({
350
+ kind: "change",
351
+ ...batch
352
+ });
353
+ },
354
+ onResync: (seq) => emit({
355
+ kind: "resync",
356
+ seq
357
+ }),
358
+ onRefused: (env, reason) => {
359
+ diverged = true;
360
+ opt.onRefused?.(env, reason);
361
+ },
362
+ onLocalReject: (violation) => {
363
+ diverged = true;
364
+ console.warn("[@mmstack/mesh] agent seat write violates the room policy — not sent", violation);
365
+ },
366
+ onTerminal: () => {
367
+ if (session.hasUnacked()) {
368
+ diverged = true;
369
+ lostWrites = true;
370
+ }
371
+ terminated = true;
372
+ }
373
+ }
374
+ });
375
+ sync.subscribe(() => {
376
+ if (terminated) diverged = true;
377
+ });
378
+ session.connect();
379
+ return {
380
+ doc,
381
+ status: () => session.status(),
382
+ peers: () => [...session.peers().values()],
383
+ snapshot: () => read(),
384
+ stableSnapshot: () => {
385
+ sync.flush();
386
+ if (!welcomed || diverged || session.hasUnacked()) return null;
387
+ return {
388
+ seq: session.lastSeq(),
389
+ doc: read()
390
+ };
391
+ },
392
+ write: (fn) => {
393
+ fn();
394
+ sync.flush();
395
+ },
396
+ setAtPath: (path, value) => {
397
+ setAtPath(doc, path, value);
398
+ sync.flush();
399
+ },
400
+ changes: (cb) => {
401
+ listeners.add(cb);
402
+ return () => listeners.delete(cb);
403
+ },
404
+ fork: (forkOpt) => {
405
+ const f = forkStore(doc, forkOpt);
406
+ let frontier = sync.captureFrontier();
407
+ const recapture = () => {
408
+ frontier = sync.captureFrontier();
409
+ };
410
+ return {
411
+ store: f.store,
412
+ ops: f.ops,
413
+ commit: () => {
414
+ sync.commitScope(frontier, () => f.commit());
415
+ sync.flush();
416
+ },
417
+ discard: () => {
418
+ f.discard();
419
+ recapture();
420
+ },
421
+ rebase: recapture
422
+ };
423
+ },
424
+ acked: () => {
425
+ sync.flush();
426
+ return !lostWrites && !session.hasUnacked();
427
+ },
428
+ whenAcked: () => {
429
+ sync.flush();
430
+ return session.whenAcked();
431
+ },
432
+ setPresence: (data) => session.setPresence(data),
433
+ sync: {
434
+ override: (fn) => sync.override(fn),
435
+ captureFrontier: () => sync.captureFrontier(),
436
+ commitScope: (frontier, fn) => sync.commitScope(frontier, fn),
437
+ liveUnder: (path) => sync.liveUnder(path),
438
+ liveAt: (path) => sync.liveAt(path),
439
+ appliedFrontier: () => sync.appliedFrontier()
440
+ },
441
+ close: () => {
442
+ diverged = true;
443
+ session.close();
444
+ sync.destroy();
445
+ }
446
+ };
502
447
  }
503
- const parsePath = (path) => typeof path === 'string' ? path.split('.').filter((s) => s !== '') : path;
504
- // resolve a string segment against an array ('0' → 0) so dot-paths address list items
505
- const resolveKey = (current, seg) => Array.isArray(current) && typeof seg === 'string' && /^\d+$/.test(seg)
506
- ? Number(seg)
507
- : seg;
448
+ const parsePath = (path) => typeof path === "string" ? path.split(".").filter((s) => s !== "") : path;
449
+ const resolveKey = (current, seg) => Array.isArray(current) && typeof seg === "string" && /^\d+$/.test(seg) ? Number(seg) : seg;
508
450
  function withPathSet(current, path, value) {
509
- if (path.length === 0)
510
- return value;
511
- const [head, ...rest] = path;
512
- if (Array.isArray(current)) {
513
- const idx = typeof head === 'number' ? head : Number(head);
514
- const copy = [...current];
515
- copy[idx] = withPathSet(current[idx], rest, value);
516
- return copy;
517
- }
518
- const base = current !== null && typeof current === 'object'
519
- ? current
520
- : {};
521
- return { ...base, [head]: withPathSet(base[head], rest, value) };
451
+ if (path.length === 0) return value;
452
+ const [head, ...rest] = path;
453
+ if (Array.isArray(current)) {
454
+ const idx = typeof head === "number" ? head : Number(head);
455
+ const copy = [...current];
456
+ copy[idx] = withPathSet(current[idx], rest, value);
457
+ return copy;
458
+ }
459
+ const base = current !== null && typeof current === "object" ? current : {};
460
+ return {
461
+ ...base,
462
+ [head]: withPathSet(base[head], rest, value)
463
+ };
522
464
  }
523
- /**
524
- * Applies `value` at a path on a signal-store node — the write shape a tool-calling model
525
- * naturally produces (`'plan.endDate'`, `'tasks.t1.done'`). Walks child signals as far as
526
- * the path exists in the current value and finishes with one immutable set on the deepest
527
- * real node, which also covers paths that do not exist yet (a fresh record key creates it).
528
- * Works on a seat's `doc` and on a fork's `store` alike; on a seat, prefer
529
- * `seat.setAtPath`, which also emits immediately.
530
- */
531
465
  function setAtPath(node, path, value) {
532
- const segs = parsePath(path);
533
- let cursor = node;
534
- let walked = 0;
535
- for (const seg of segs) {
536
- const current = cursor();
537
- if (current === null || typeof current !== 'object')
538
- break;
539
- const key = resolveKey(current, seg);
540
- // a key the node answers itself has no child node; the rest of the path is set on this value
541
- if (!Object.hasOwn(current, key) || isStoreReservedKey(key))
542
- break;
543
- const child = cursor[key];
544
- if (typeof child !== 'function')
545
- break;
546
- cursor = child;
547
- walked++;
548
- }
549
- const rest = segs.slice(walked);
550
- if (rest.length === 0) {
551
- cursor.set(value);
552
- return;
553
- }
554
- cursor.set(withPathSet(cursor(), rest, value));
466
+ const segs = parsePath(path);
467
+ let cursor = node;
468
+ let walked = 0;
469
+ for (const seg of segs) {
470
+ const current = cursor();
471
+ if (current === null || typeof current !== "object") break;
472
+ const key = resolveKey(current, seg);
473
+ if (!Object.hasOwn(current, key) || isStoreReservedKey(key)) break;
474
+ const child = cursor[key];
475
+ if (typeof child !== "function") break;
476
+ cursor = child;
477
+ walked++;
478
+ }
479
+ const rest = segs.slice(walked);
480
+ if (rest.length === 0) {
481
+ cursor.set(value);
482
+ return;
483
+ }
484
+ cursor.set(withPathSet(cursor(), rest, value));
555
485
  }
556
486
  const MAX_VALUE_CHARS = 120;
557
487
  const printable = (value) => {
558
- const json = JSON.stringify(value);
559
- if (json === undefined)
560
- return String(value);
561
- return json.length > MAX_VALUE_CHARS
562
- ? `${json.slice(0, MAX_VALUE_CHARS - 1)}…`
563
- : json;
488
+ const json = JSON.stringify(value);
489
+ if (json === void 0) return String(value);
490
+ return json.length > MAX_VALUE_CHARS ? `${json.slice(0, 119)}…` : json;
564
491
  };
565
- /**
566
- * One store op as a plain-English line ("mira set plan.endDate to \"2026-10-11\""), for
567
- * activity feeds and model context. Values render as truncated JSON. Pair with a seat's
568
- * `changes` stream: narrating each batch's ops yields an append-only account of the room.
569
- */
570
492
  function describeOp(op, writer) {
571
- const at = op.path.length === 0 ? 'the document root' : op.path.join('.');
572
- switch (op.kind) {
573
- case 'set':
574
- return `${writer} set ${at} to ${printable(op.next)}`;
575
- case 'delete':
576
- return `${writer} removed ${at}`;
577
- case 'clear':
578
- return `${writer} cleared ${at}`;
579
- }
493
+ const at = op.path.length === 0 ? "the document root" : op.path.join(".");
494
+ switch (op.kind) {
495
+ case "set": return `${writer} set ${at} to ${printable(op.next)}`;
496
+ case "delete": return `${writer} removed ${at}`;
497
+ case "clear": return `${writer} cleared ${at}`;
498
+ }
580
499
  }
581
-
582
- // a versioned reject means "your build is behind" → prompt an update, not a dead socket
583
- const OUTDATED_REASONS = new Set([
584
- 'proto',
585
- 'policy-version',
586
- 'schema',
500
+ const OUTDATED_REASONS = /* @__PURE__ */ new Set([
501
+ "proto",
502
+ "policy-version",
503
+ "schema"
587
504
  ]);
588
505
  const OUTBOX_DEBOUNCE_MS = 300;
589
- /**
590
- * Replicates a signal store across clients through a relay room: local writes emit stamped
591
- * envelopes, remote envelopes fold in convergently, reconnects resume via delta or snapshot
592
- * with unacknowledged local writes rebased on top, and presence rides an ephemeral channel.
593
- * A synced store reads exactly like a local one — connection state surfaces only through
594
- * `status` and the transition scope.
595
- */
596
506
  function meshSync(source, opt) {
597
- const injector = opt.injector ?? inject(Injector);
598
- const status = signal('connecting', /* @ts-ignore */
599
- ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
600
- const origin = signal(null, /* @ts-ignore */
601
- ...(ngDevMode ? [{ debugName: "origin" }] : /* istanbul ignore next */ []));
602
- const members = signal([], /* @ts-ignore */
603
- ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
604
- let membership;
605
- // the last roster the links on the port were given; a socket drop blanks the session's, not this
606
- let roster = [];
607
- const signalingListeners = new Set();
608
- let earlySignals = [];
609
- // the ICE servers of the last welcome, for peer links that attach after it
610
- let welcomeIce;
611
- const deliverSignal = (cb, msg) => {
612
- try {
613
- cb(msg);
614
- }
615
- catch {
616
- // A failed peer link must never interrupt the room's sync session or other listeners.
617
- }
618
- };
619
- const signalMessage = (msg) => {
620
- if (msg.t === 'welcome')
621
- welcomeIce = msg.ice;
622
- if (msg.t === 'welcome' && earlySignals !== null)
623
- earlySignals = [];
624
- if (msg.t === 'member' && msg.gone && earlySignals !== null) {
625
- earlySignals = earlySignals.filter((held) => held.t !== 'signal' || held.from !== msg.origin);
626
- }
627
- if (msg.t === 'signal' &&
628
- earlySignals !== null &&
629
- earlySignals.length < 256) {
630
- earlySignals.push(msg);
631
- }
632
- for (const cb of [...signalingListeners])
633
- deliverSignal(cb, msg);
634
- };
635
- const lastReason = signal(undefined, /* @ts-ignore */
636
- ...(ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []));
637
- const lastSyncedAt = signal(undefined, /* @ts-ignore */
638
- ...(ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []));
639
- const droppedOffline = signal(0, /* @ts-ignore */
640
- ...(ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []));
641
- const acked = signal(true, /* @ts-ignore */
642
- ...(ngDevMode ? [{ debugName: "acked" }] : /* istanbul ignore next */ [])); // nothing has been written yet
643
- const refused = signal(0, /* @ts-ignore */
644
- ...(ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []));
645
- const droppedInvalid = signal(0, /* @ts-ignore */
646
- ...(ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []));
647
- const peerMap = signal(new Map(), /* @ts-ignore */
648
- ...(ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []));
649
- const peers = computed(() => [...peerMap().values()], /* @ts-ignore */
650
- ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
651
- const policyVersion = opt.policyVersion ?? 0;
652
- const health = computed(() => {
653
- const at = lastSyncedAt();
654
- const dropped = droppedOffline();
655
- const invalid = droppedInvalid();
656
- const extra = {
657
- ...(dropped > 0 ? { droppedOfflineWrites: dropped } : undefined),
658
- ...(refused() > 0 ? { refusedWrites: refused() } : undefined),
659
- ...(invalid > 0 ? { droppedInvalidEnvelopes: invalid } : undefined),
660
- };
661
- switch (status()) {
662
- case 'live':
663
- return { status: 'live', lastSyncedAt: at, ...extra };
664
- case 'waiting':
665
- return { status: 'waiting', lastSyncedAt: at, ...extra };
666
- case 'ejected': {
667
- const reason = lastReason();
668
- return reason && OUTDATED_REASONS.has(reason)
669
- ? { status: 'outdated', reason, lastSyncedAt: at, ...extra }
670
- : { status: 'ejected', reason, lastSyncedAt: at, ...extra };
671
- }
672
- default: // connecting / reconnecting / closed — not reachable
673
- return { status: 'offline', lastSyncedAt: at, ...extra };
674
- }
675
- }, /* @ts-ignore */
676
- ...(ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []));
677
- // Created lazily: with a persisted outbox the slot lock and the restored tail come first, so the
678
- // engine never mints before it knows the generation it is in
679
- let sync;
680
- let session;
681
- let started = false;
682
- let closed = false;
683
- let pendingPresence;
684
- let persistTimer;
685
- let pendingPersist;
686
- let releaseLock;
687
- let cancelLock;
688
- // this tab owns the persisted slot ('off', no Web Locks, or a granted lock); an ephemeral boot never does
689
- let durable = false;
690
- // the slot's clock high-water as restored: persisted back until this boot mints its own stamp
691
- let restoredClock;
692
- // resolves when the store has the payload (a failed write resolves too: persistence is best-effort)
693
- const doPersist = () => {
694
- if (closed || !opt.outbox || !started || !session || !durable)
695
- return Promise.resolve(); // ephemeral: never writes
696
- const instance = session.instance();
697
- const clock = sync.lastStamp() ?? restoredClock;
698
- const payload = {
699
- origin: sync.origin,
700
- version: sync.watermark()[sync.origin] ?? 0,
701
- envs: session.unackedEnvs(),
702
- ...(instance ? { instance } : {}),
703
- floors: sync.floors(),
704
- ...(clock ? { clock } : {}),
705
- };
706
- const { store, key } = opt.outbox;
707
- // Capture before queueing: teardown clears the session's tail immediately after this call.
708
- const write = () => {
709
- try {
710
- return Promise.resolve(store.set(key, payload)).then(() => undefined, () => undefined);
711
- }
712
- catch {
713
- return Promise.resolve(); // a failed save must not block later saves or lock release
714
- }
715
- };
716
- // Keep the idle path synchronous, but never let an older save land after a newer one.
717
- const pending = pendingPersist ? pendingPersist.then(write) : write();
718
- pendingPersist = pending;
719
- void pending.then(() => {
720
- if (pendingPersist === pending)
721
- pendingPersist = undefined;
722
- });
723
- return pending;
724
- };
725
- // coalesce outbox writes; `immediate` bypasses the debounce, but waits for earlier saves
726
- const persistOutbox = (immediate = false) => {
727
- if (!opt.outbox)
728
- return Promise.resolve();
729
- if (immediate) {
730
- if (persistTimer !== undefined)
731
- clearTimeout(persistTimer);
732
- persistTimer = undefined;
733
- return doPersist();
734
- }
735
- if (persistTimer === undefined) {
736
- persistTimer = setTimeout(() => {
737
- persistTimer = undefined;
738
- void doPersist();
739
- }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
740
- }
741
- return Promise.resolve(); // the debounced path is not awaited
742
- };
743
- const dropLocks = () => {
744
- cancelLock?.(); // drop a still-queued lock request so we never steal it after teardown
745
- releaseLock?.(); // free a held lock for the next waiting tab
746
- cancelLock = releaseLock = undefined;
747
- };
748
- // Only a tail this boot could actually get admitted is worth resending: recorded under
749
- // this writer, on the current proto and policyVersion pins (the relay rejects a stale pin
750
- // per envelope, so restoring one would eject the boot, persist the tail intact, and brick
751
- // every boot after). Anything else drops loudly instead.
752
- const restorable = (env) => env.proto === OP_PROTO_VERSION &&
753
- env.writer === opt.writer &&
754
- env.policyVersion === policyVersion &&
755
- env.ops.every((op) => Array.isArray(op.cites) &&
756
- typeof op.epoch === 'number');
757
- const initCore = (restore) => {
758
- if (closed)
759
- return;
760
- restoredClock = restore?.clock;
761
- sync = opSync(source, {
762
- writer: opt.writer,
763
- instance: restore?.instance,
764
- policies: opt.policies,
765
- policyVersion,
766
- injector,
767
- onReject: (_env, reason) => {
768
- droppedInvalid.update((n) => n + 1);
769
- if (isDevMode()) {
770
- console.warn(`[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`);
771
- }
772
- },
773
- });
774
- started = true;
775
- // set once this session ends: only then are the links riding on its port retired
776
- let ended = false;
777
- session = meshSession({
778
- room: opt.room,
779
- writer: opt.writer,
780
- transport: opt.transport,
781
- sync,
782
- policies: opt.policies,
783
- policy: opt.policy,
784
- ctx: opt.ctx,
785
- policyVersion,
786
- schemaVersion: opt.schemaVersion,
787
- instance: restore?.instance,
788
- reconnect: opt.reconnect,
789
- hooks: {
790
- onOrigin: (value) => origin.set(value),
791
- onMembers: (value) => {
792
- membership = value;
793
- members.set(value ?? []);
794
- if (value !== undefined) {
795
- roster = value;
796
- return;
797
- }
798
- if (earlySignals !== null)
799
- earlySignals = [];
800
- // Peer links outlive a socket drop: the next welcome re-lists who is still there. A
801
- // borrowed port has no close of its own, so the session's end retires them here, from
802
- // the last roster the links saw (a drop before the close already blanked the session's).
803
- if (!ended)
804
- return;
805
- const retired = roster;
806
- roster = [];
807
- for (const origin of retired) {
808
- signalMessage({ t: 'member', room: opt.room, origin, gone: true });
809
- }
810
- },
811
- onMessage: signalMessage,
812
- onRefused: (env, reason) => {
813
- refused.update((n) => n + 1);
814
- opt.onRefused?.(env, reason);
815
- if (isDevMode()) {
816
- console.warn(`[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`);
817
- }
818
- },
819
- onStatus: (s, reason) => {
820
- if (s === 'ejected' || s === 'closed') {
821
- closed = true;
822
- lastReason.set(reason);
823
- }
824
- status.set(s);
825
- if ((s === 'ejected' || s === 'closed') && reason !== undefined) {
826
- opt.onEject?.(reason);
827
- }
828
- },
829
- onSynced: () => lastSyncedAt.set(Date.now()),
830
- onPeers: (map) => peerMap.set(map),
831
- onOutboxChange: () => {
832
- void persistOutbox();
833
- acked.set(!session?.hasUnacked());
834
- },
835
- onTerminal: () => {
836
- ended = true;
837
- // latched: the tail is about to be dropped from the session, but it was never
838
- // acknowledged, so the answer to "is everything I wrote in the room" stays no
839
- if (session?.hasUnacked())
840
- acked.set(false);
841
- // save the still-unacked tail for the next boot, and release the lock only once the store
842
- // has it: a successor granted earlier could restore the slot before this write lands
843
- let saved;
844
- try {
845
- saved = persistOutbox(true);
846
- }
847
- catch {
848
- saved = Promise.resolve(); // a failed capture must still hand the slot on
849
- }
850
- void saved.finally(dropLocks);
851
- },
852
- onLocalReject: (violation) => {
853
- if (isDevMode()) {
854
- console.warn('[@mmstack/mesh] local write violates the room policy — not sent', violation);
855
- }
856
- },
857
- },
858
- });
859
- if (restore &&
860
- (restore.envs.length > 0 ||
861
- restore.version > 0 ||
862
- (restore.floors?.length ?? 0) > 0 ||
863
- restore.clock !== undefined)) {
864
- const kept = restore.envs.filter(restorable);
865
- const dropped = restore.envs.length - kept.length;
866
- if (dropped > 0) {
867
- droppedOffline.set(dropped);
868
- if (isDevMode()) {
869
- console.warn(`[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`);
870
- }
871
- }
872
- sync.restore(kept, restore.version, restore.floors, restore.clock); // → the session's subscribe repopulates its unacked tail for resend
873
- }
874
- void persistOutbox(true); // pin the freshly minted origin immediately, so a crash before any write is safe
875
- if (pendingPresence) {
876
- session.setPresence(pendingPresence.data);
877
- pendingPresence = undefined;
878
- }
879
- session.connect();
880
- };
881
- if (opt.register) {
882
- const connection = {
883
- status: computed(() => {
884
- const s = status();
885
- return s === 'connecting' || s === 'waiting'
886
- ? 'loading'
887
- : s === 'reconnecting'
888
- ? 'reloading'
889
- : s === 'ejected'
890
- ? 'error'
891
- : 'resolved';
892
- }),
893
- isLoading: computed(() => status() === 'connecting' ||
894
- status() === 'waiting' ||
895
- status() === 'reconnecting'),
896
- hasValue: () => true,
897
- };
898
- runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === 'suspend' }));
899
- }
900
- const teardown = () => {
901
- if (session) {
902
- session.close(); // no-op if already terminal; onTerminal handled locks + persist
903
- }
904
- else if (!closed) {
905
- // closed before the (async) boot ever created the session
906
- closed = true;
907
- dropLocks();
908
- status.set('closed');
909
- }
910
- if (started)
911
- sync.destroy();
912
- };
913
- injector.get(DestroyRef).onDestroy(teardown);
914
- // Load the persisted outbox, then boot on a fresh origin. A fresh/unreadable slot boots clean.
915
- const bootFromDisk = async () => {
916
- durable = true; // every caller owns the slot
917
- if (closed || !opt.outbox)
918
- return;
919
- let saved;
920
- try {
921
- const raw = await opt.outbox.store.get(opt.outbox.key);
922
- saved =
923
- raw && typeof raw === 'object' && 'origin' in raw
924
- ? raw
925
- : undefined;
926
- }
927
- catch {
928
- saved = undefined; // an unreadable slot must not wedge the boot
929
- }
930
- initCore(saved);
931
- };
932
- const beginConnect = () => {
933
- if (closed)
934
- return;
935
- if (!opt.outbox) {
936
- initCore();
937
- }
938
- else if ((opt.outbox.crossTab ?? 'queue') === 'off') {
939
- void bootFromDisk(); // no single-writer lock — the app coordinates ownership
940
- }
941
- else {
942
- const locks = globalThis.navigator?.locks;
943
- const mode = opt.outbox.crossTab ?? 'queue';
944
- if (!locks) {
945
- if (isDevMode()) {
946
- console.warn(`[@mmstack/mesh] outbox crossTab:"${mode}" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock ('queue' and 'ephemeral' both own the slot). Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:"off" to silence this.`);
947
- }
948
- void bootFromDisk();
949
- return;
950
- }
951
- const name = `@mmstack/mesh:outbox:${opt.outbox.key}`;
952
- // hold a granted lock until teardown resolves this promise
953
- const hold = (queued = false) => {
954
- cancelLock = undefined; // granted — no longer abortable, only releasable
955
- if (closed)
956
- return Promise.resolve();
957
- if (queued)
958
- status.set('connecting'); // the wait ends with the grant
959
- return new Promise((release) => {
960
- releaseLock = release;
961
- void bootFromDisk();
962
- });
963
- };
964
- const queueUp = () => {
965
- status.set('waiting');
966
- const abort = new AbortController();
967
- cancelLock = () => abort.abort();
968
- void locks
969
- .request(name, { mode: 'exclusive', signal: abort.signal }, () => hold(true))
970
- .catch((e) => {
971
- // an aborted request is our own teardown; any other failure → degrade to no-lock
972
- if (!closed &&
973
- !started &&
974
- e?.name !== 'AbortError') {
975
- status.set('connecting'); // no longer waiting on anyone
976
- void bootFromDisk();
977
- }
978
- });
979
- };
980
- // Web Locks forbids `signal` together with `ifAvailable`, hence the probe first
981
- void locks
982
- .request(name, { mode: 'exclusive', ifAvailable: true }, (lock) => {
983
- if (lock === null) {
984
- // another tab owns the slot
985
- if (closed)
986
- return Promise.resolve();
987
- if (mode === 'ephemeral') {
988
- initCore(); // live at once on a fresh origin; never reads or writes the slot
989
- return Promise.resolve();
990
- }
991
- queueUp();
992
- return Promise.resolve();
993
- }
994
- return hold();
995
- })
996
- .catch(() => {
997
- if (!closed && !started)
998
- void bootFromDisk(); // a broken lock manager degrades to no-lock
999
- });
1000
- }
1001
- };
1002
- if (opt.whenReady) {
1003
- void Promise.resolve()
1004
- .then(() => opt.whenReady?.())
1005
- .then(() => beginConnect(), () => beginConnect());
1006
- }
1007
- else {
1008
- beginConnect();
1009
- }
1010
- return {
1011
- status: status.asReadonly(),
1012
- origin: origin.asReadonly(),
1013
- members: members.asReadonly(),
1014
- signaling: {
1015
- members: () => membership,
1016
- iceServers: () => welcomeIce,
1017
- send: (msg) => session?.sendSignal(msg),
1018
- onMessage: (cb) => {
1019
- signalingListeners.add(cb);
1020
- const held = earlySignals ?? [];
1021
- earlySignals = null;
1022
- for (const msg of held)
1023
- deliverSignal(cb, msg);
1024
- return () => signalingListeners.delete(cb);
1025
- },
1026
- },
1027
- health,
1028
- acked: acked.asReadonly(),
1029
- whenAcked: () => (session ? session.whenAcked() : Promise.resolve()), // nothing written yet
1030
- peers,
1031
- setPresence: (data) => {
1032
- if (session)
1033
- session.setPresence(data);
1034
- else
1035
- pendingPresence = { data };
1036
- },
1037
- fork: (forkOpt) => {
1038
- const f = forkStore(source, forkOpt);
1039
- let frontier = started ? sync.captureFrontier() : { seq: 0 };
1040
- const recapture = () => {
1041
- frontier = started ? sync.captureFrontier() : { seq: 0 };
1042
- };
1043
- return {
1044
- store: f.store,
1045
- ops: f.ops,
1046
- commit: () => started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),
1047
- discard: () => {
1048
- f.discard();
1049
- recapture();
1050
- },
1051
- rebase: recapture,
1052
- };
1053
- },
1054
- sync: {
1055
- override: (fn) => (started ? sync.override(fn) : fn()),
1056
- captureFrontier: () => (started ? sync.captureFrontier() : { seq: 0 }),
1057
- commitScope: (frontier, fn) => started ? sync.commitScope(frontier, fn) : fn(),
1058
- liveUnder: (path) => (started ? sync.liveUnder(path) : []),
1059
- liveAt: (path) => (started ? sync.liveAt(path) : []),
1060
- appliedFrontier: () => (started ? sync.appliedFrontier() : {}),
1061
- },
1062
- close: teardown,
1063
- };
507
+ const injector = opt.injector ?? inject(Injector);
508
+ const status = signal("connecting", ...ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []);
509
+ const origin = signal(null, ...ngDevMode ? [{ debugName: "origin" }] : /* istanbul ignore next */ []);
510
+ const members = signal([], ...ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []);
511
+ let membership;
512
+ let roster = [];
513
+ const signalingListeners = /* @__PURE__ */ new Set();
514
+ let earlySignals = [];
515
+ let welcomeIce;
516
+ const deliverSignal = (cb, msg) => {
517
+ try {
518
+ cb(msg);
519
+ } catch {}
520
+ };
521
+ const signalMessage = (msg) => {
522
+ if (msg.t === "welcome") welcomeIce = msg.ice;
523
+ if (msg.t === "welcome" && earlySignals !== null) earlySignals = [];
524
+ if (msg.t === "member" && msg.gone && earlySignals !== null) earlySignals = earlySignals.filter((held) => held.t !== "signal" || held.from !== msg.origin);
525
+ if (msg.t === "signal" && earlySignals !== null && earlySignals.length < 256) earlySignals.push(msg);
526
+ for (const cb of [...signalingListeners]) deliverSignal(cb, msg);
527
+ };
528
+ const lastReason = signal(void 0, ...ngDevMode ? [{ debugName: "lastReason" }] : /* istanbul ignore next */ []);
529
+ const lastSyncedAt = signal(void 0, ...ngDevMode ? [{ debugName: "lastSyncedAt" }] : /* istanbul ignore next */ []);
530
+ const droppedOffline = signal(0, ...ngDevMode ? [{ debugName: "droppedOffline" }] : /* istanbul ignore next */ []);
531
+ const acked = signal(true, ...ngDevMode ? [{ debugName: "acked" }] : /* istanbul ignore next */ []);
532
+ const refused = signal(0, ...ngDevMode ? [{ debugName: "refused" }] : /* istanbul ignore next */ []);
533
+ const droppedInvalid = signal(0, ...ngDevMode ? [{ debugName: "droppedInvalid" }] : /* istanbul ignore next */ []);
534
+ const peerMap = signal(/* @__PURE__ */ new Map(), ...ngDevMode ? [{ debugName: "peerMap" }] : /* istanbul ignore next */ []);
535
+ const peers = computed(() => [...peerMap().values()], ...ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []);
536
+ const policyVersion = opt.policyVersion ?? 0;
537
+ const health = computed(() => {
538
+ const at = lastSyncedAt();
539
+ const dropped = droppedOffline();
540
+ const invalid = droppedInvalid();
541
+ const extra = {
542
+ ...dropped > 0 ? { droppedOfflineWrites: dropped } : void 0,
543
+ ...refused() > 0 ? { refusedWrites: refused() } : void 0,
544
+ ...invalid > 0 ? { droppedInvalidEnvelopes: invalid } : void 0
545
+ };
546
+ switch (status()) {
547
+ case "live": return {
548
+ status: "live",
549
+ lastSyncedAt: at,
550
+ ...extra
551
+ };
552
+ case "waiting": return {
553
+ status: "waiting",
554
+ lastSyncedAt: at,
555
+ ...extra
556
+ };
557
+ case "ejected": {
558
+ const reason = lastReason();
559
+ return reason && OUTDATED_REASONS.has(reason) ? {
560
+ status: "outdated",
561
+ reason,
562
+ lastSyncedAt: at,
563
+ ...extra
564
+ } : {
565
+ status: "ejected",
566
+ reason,
567
+ lastSyncedAt: at,
568
+ ...extra
569
+ };
570
+ }
571
+ default: return {
572
+ status: "offline",
573
+ lastSyncedAt: at,
574
+ ...extra
575
+ };
576
+ }
577
+ }, ...ngDevMode ? [{ debugName: "health" }] : /* istanbul ignore next */ []);
578
+ let sync;
579
+ let session;
580
+ let started = false;
581
+ let closed = false;
582
+ let pendingPresence;
583
+ let persistTimer;
584
+ let pendingPersist;
585
+ let releaseLock;
586
+ let cancelLock;
587
+ let durable = false;
588
+ let restoredClock;
589
+ const doPersist = () => {
590
+ if (closed || !opt.outbox || !started || !session || !durable) return Promise.resolve();
591
+ const instance = session.instance();
592
+ const clock = sync.lastStamp() ?? restoredClock;
593
+ const payload = {
594
+ origin: sync.origin,
595
+ version: sync.watermark()[sync.origin] ?? 0,
596
+ envs: session.unackedEnvs(),
597
+ ...instance ? { instance } : {},
598
+ floors: sync.floors(),
599
+ ...clock ? { clock } : {}
600
+ };
601
+ const { store, key } = opt.outbox;
602
+ const write = () => {
603
+ try {
604
+ return Promise.resolve(store.set(key, payload)).then(() => void 0, () => void 0);
605
+ } catch {
606
+ return Promise.resolve();
607
+ }
608
+ };
609
+ const pending = pendingPersist ? pendingPersist.then(write) : write();
610
+ pendingPersist = pending;
611
+ pending.then(() => {
612
+ if (pendingPersist === pending) pendingPersist = void 0;
613
+ });
614
+ return pending;
615
+ };
616
+ const persistOutbox = (immediate = false) => {
617
+ if (!opt.outbox) return Promise.resolve();
618
+ if (immediate) {
619
+ if (persistTimer !== void 0) clearTimeout(persistTimer);
620
+ persistTimer = void 0;
621
+ return doPersist();
622
+ }
623
+ if (persistTimer === void 0) persistTimer = setTimeout(() => {
624
+ persistTimer = void 0;
625
+ doPersist();
626
+ }, opt.outbox.debounceMs ?? OUTBOX_DEBOUNCE_MS);
627
+ return Promise.resolve();
628
+ };
629
+ const dropLocks = () => {
630
+ cancelLock?.();
631
+ releaseLock?.();
632
+ cancelLock = releaseLock = void 0;
633
+ };
634
+ const restorable = (env) => env.proto === OP_PROTO_VERSION && env.writer === opt.writer && env.policyVersion === policyVersion && env.ops.every((op) => Array.isArray(op.cites) && typeof op.epoch === "number");
635
+ const initCore = (restore) => {
636
+ if (closed) return;
637
+ restoredClock = restore?.clock;
638
+ sync = opSync(source, {
639
+ writer: opt.writer,
640
+ instance: restore?.instance,
641
+ policies: opt.policies,
642
+ policyVersion,
643
+ injector,
644
+ emit: opt.emit,
645
+ onReject: (_env, reason) => {
646
+ droppedInvalid.update((n) => n + 1);
647
+ if (isDevMode()) console.warn(`[@mmstack/mesh] dropped malformed envelope from a peer (${reason})`);
648
+ }
649
+ });
650
+ started = true;
651
+ let ended = false;
652
+ session = meshSession({
653
+ room: opt.room,
654
+ writer: opt.writer,
655
+ transport: opt.transport,
656
+ sync,
657
+ policies: opt.policies,
658
+ policy: opt.policy,
659
+ ctx: opt.ctx,
660
+ policyVersion,
661
+ schemaVersion: opt.schemaVersion,
662
+ instance: restore?.instance,
663
+ reconnect: opt.reconnect,
664
+ hooks: {
665
+ onOrigin: (value) => origin.set(value),
666
+ onMembers: (value) => {
667
+ membership = value;
668
+ members.set(value ?? []);
669
+ if (value !== void 0) {
670
+ roster = value;
671
+ return;
672
+ }
673
+ if (earlySignals !== null) earlySignals = [];
674
+ if (!ended) return;
675
+ const retired = roster;
676
+ roster = [];
677
+ for (const origin of retired) signalMessage({
678
+ t: "member",
679
+ room: opt.room,
680
+ origin,
681
+ gone: true
682
+ });
683
+ },
684
+ onMessage: signalMessage,
685
+ onRefused: (env, reason) => {
686
+ refused.update((n) => n + 1);
687
+ opt.onRefused?.(env, reason);
688
+ if (isDevMode()) console.warn(`[@mmstack/mesh] the relay refused a write (${reason}); it is not in the room and the store was rehydrated`);
689
+ },
690
+ onStatus: (s, reason) => {
691
+ if (s === "ejected" || s === "closed") {
692
+ closed = true;
693
+ lastReason.set(reason);
694
+ }
695
+ status.set(s);
696
+ if ((s === "ejected" || s === "closed") && reason !== void 0) opt.onEject?.(reason);
697
+ },
698
+ onSynced: () => lastSyncedAt.set(Date.now()),
699
+ onPeers: (map) => peerMap.set(map),
700
+ onOutboxChange: () => {
701
+ persistOutbox();
702
+ acked.set(!session?.hasUnacked());
703
+ },
704
+ onTerminal: () => {
705
+ ended = true;
706
+ if (session?.hasUnacked()) acked.set(false);
707
+ let saved;
708
+ try {
709
+ saved = persistOutbox(true);
710
+ } catch {
711
+ saved = Promise.resolve();
712
+ }
713
+ saved.finally(dropLocks);
714
+ },
715
+ onLocalReject: (violation) => {
716
+ if (isDevMode()) console.warn("[@mmstack/mesh] local write violates the room policy — not sent", violation);
717
+ }
718
+ }
719
+ });
720
+ if (restore && (restore.envs.length > 0 || restore.version > 0 || (restore.floors?.length ?? 0) > 0 || restore.clock !== void 0)) {
721
+ const kept = restore.envs.filter(restorable);
722
+ const dropped = restore.envs.length - kept.length;
723
+ if (dropped > 0) {
724
+ droppedOffline.set(dropped);
725
+ if (isDevMode()) console.warn(`[@mmstack/mesh] dropped ${dropped} persisted offline write(s) that cannot be resent: recorded under a different writer, or from an older protocol version (citations are never fabricated)`);
726
+ }
727
+ sync.restore(kept, restore.version, restore.floors, restore.clock);
728
+ }
729
+ persistOutbox(true);
730
+ if (pendingPresence) {
731
+ session.setPresence(pendingPresence.data);
732
+ pendingPresence = void 0;
733
+ }
734
+ session.connect();
735
+ };
736
+ if (opt.register) {
737
+ const connection = {
738
+ status: computed(() => {
739
+ const s = status();
740
+ return s === "connecting" || s === "waiting" ? "loading" : s === "reconnecting" ? "reloading" : s === "ejected" ? "error" : "resolved";
741
+ }),
742
+ isLoading: computed(() => status() === "connecting" || status() === "waiting" || status() === "reconnecting"),
743
+ hasValue: () => true
744
+ };
745
+ runInInjectionContext(injector, () => registerResource(connection, { suspends: opt.register === "suspend" }));
746
+ }
747
+ const teardown = () => {
748
+ if (session) session.close();
749
+ else if (!closed) {
750
+ closed = true;
751
+ dropLocks();
752
+ status.set("closed");
753
+ }
754
+ if (started) sync.destroy();
755
+ };
756
+ injector.get(DestroyRef).onDestroy(teardown);
757
+ const bootFromDisk = async () => {
758
+ durable = true;
759
+ if (closed || !opt.outbox) return;
760
+ let saved;
761
+ try {
762
+ const raw = await opt.outbox.store.get(opt.outbox.key);
763
+ saved = raw && typeof raw === "object" && "origin" in raw ? raw : void 0;
764
+ } catch {
765
+ saved = void 0;
766
+ }
767
+ initCore(saved);
768
+ };
769
+ const beginConnect = () => {
770
+ if (closed) return;
771
+ if (!opt.outbox) initCore();
772
+ else if ((opt.outbox.crossTab ?? "queue") === "off") bootFromDisk();
773
+ else {
774
+ const locks = globalThis.navigator?.locks;
775
+ const mode = opt.outbox.crossTab ?? "queue";
776
+ if (!locks) {
777
+ if (isDevMode()) console.warn(`[@mmstack/mesh] outbox crossTab:"${mode}" needs the Web Locks API (navigator.locks), unavailable here — running WITHOUT a single-writer lock ('queue' and 'ephemeral' both own the slot). Two tabs sharing this key can diverge; coordinate ownership yourself, or set crossTab:"off" to silence this.`);
778
+ bootFromDisk();
779
+ return;
780
+ }
781
+ const name = `@mmstack/mesh:outbox:${opt.outbox.key}`;
782
+ const hold = (queued = false) => {
783
+ cancelLock = void 0;
784
+ if (closed) return Promise.resolve();
785
+ if (queued) status.set("connecting");
786
+ return new Promise((release) => {
787
+ releaseLock = release;
788
+ bootFromDisk();
789
+ });
790
+ };
791
+ const queueUp = () => {
792
+ status.set("waiting");
793
+ const abort = new AbortController();
794
+ cancelLock = () => abort.abort();
795
+ locks.request(name, {
796
+ mode: "exclusive",
797
+ signal: abort.signal
798
+ }, () => hold(true)).catch((e) => {
799
+ if (!closed && !started && e?.name !== "AbortError") {
800
+ status.set("connecting");
801
+ bootFromDisk();
802
+ }
803
+ });
804
+ };
805
+ locks.request(name, {
806
+ mode: "exclusive",
807
+ ifAvailable: true
808
+ }, (lock) => {
809
+ if (lock === null) {
810
+ if (closed) return Promise.resolve();
811
+ if (mode === "ephemeral") {
812
+ initCore();
813
+ return Promise.resolve();
814
+ }
815
+ queueUp();
816
+ return Promise.resolve();
817
+ }
818
+ return hold();
819
+ }).catch(() => {
820
+ if (!closed && !started) bootFromDisk();
821
+ });
822
+ }
823
+ };
824
+ if (opt.whenReady) Promise.resolve().then(() => opt.whenReady?.()).then(() => beginConnect(), () => beginConnect());
825
+ else beginConnect();
826
+ return {
827
+ status: status.asReadonly(),
828
+ origin: origin.asReadonly(),
829
+ members: members.asReadonly(),
830
+ signaling: {
831
+ members: () => membership,
832
+ iceServers: () => welcomeIce,
833
+ send: (msg) => session?.sendSignal(msg),
834
+ onMessage: (cb) => {
835
+ signalingListeners.add(cb);
836
+ const held = earlySignals ?? [];
837
+ earlySignals = null;
838
+ for (const msg of held) deliverSignal(cb, msg);
839
+ return () => signalingListeners.delete(cb);
840
+ }
841
+ },
842
+ health,
843
+ acked: acked.asReadonly(),
844
+ whenAcked: () => session ? session.whenAcked() : Promise.resolve(),
845
+ peers,
846
+ setPresence: (data) => {
847
+ if (session) session.setPresence(data);
848
+ else pendingPresence = { data };
849
+ },
850
+ fork: (forkOpt) => {
851
+ const f = forkStore(source, forkOpt);
852
+ let frontier = started ? sync.captureFrontier() : { seq: 0 };
853
+ const recapture = () => {
854
+ frontier = started ? sync.captureFrontier() : { seq: 0 };
855
+ };
856
+ return {
857
+ store: f.store,
858
+ ops: f.ops,
859
+ commit: () => started ? sync.commitScope(frontier, () => f.commit()) : f.commit(),
860
+ discard: () => {
861
+ f.discard();
862
+ recapture();
863
+ },
864
+ rebase: recapture
865
+ };
866
+ },
867
+ sync: {
868
+ override: (fn) => started ? sync.override(fn) : fn(),
869
+ captureFrontier: () => started ? sync.captureFrontier() : { seq: 0 },
870
+ commitScope: (frontier, fn) => started ? sync.commitScope(frontier, fn) : fn(),
871
+ liveUnder: (path) => started ? sync.liveUnder(path) : [],
872
+ liveAt: (path) => started ? sync.liveAt(path) : [],
873
+ appliedFrontier: () => started ? sync.appliedFrontier() : {}
874
+ },
875
+ close: teardown
876
+ };
1064
877
  }
1065
-
1066
- /**
1067
- * JSON-over-WebSocket transport. Messages sent before the socket opens are buffered and
1068
- * flushed on open; malformed inbound frames are dropped.
1069
- */
1070
878
  function webSocketTransport(url, protocols) {
1071
- return () => {
1072
- const ws = new WebSocket(url, protocols);
1073
- const messageCbs = new Set();
1074
- const closeCbs = new Set();
1075
- const pending = [];
1076
- ws.onopen = () => {
1077
- for (const frame of pending.splice(0))
1078
- ws.send(frame);
1079
- };
1080
- ws.onmessage = (event) => {
1081
- let msg;
1082
- try {
1083
- msg = JSON.parse(String(event.data));
1084
- }
1085
- catch {
1086
- if (isDevMode()) {
1087
- console.warn('[@mmstack/mesh] dropped unparseable frame (expected JSON text)');
1088
- }
1089
- return;
1090
- }
1091
- for (const cb of [...messageCbs])
1092
- cb(msg);
1093
- };
1094
- ws.onclose = () => {
1095
- for (const cb of [...closeCbs])
1096
- cb();
1097
- };
1098
- return {
1099
- send: (msg) => {
1100
- const frame = JSON.stringify(msg);
1101
- if (ws.readyState === WebSocket.OPEN)
1102
- ws.send(frame);
1103
- else if (ws.readyState === WebSocket.CONNECTING)
1104
- pending.push(frame);
1105
- },
1106
- onMessage: (cb) => {
1107
- messageCbs.add(cb);
1108
- return () => messageCbs.delete(cb);
1109
- },
1110
- onClose: (cb) => {
1111
- closeCbs.add(cb);
1112
- return () => closeCbs.delete(cb);
1113
- },
1114
- close: () => ws.close(),
1115
- };
1116
- };
879
+ return () => {
880
+ const ws = new WebSocket(url, protocols);
881
+ const messageCbs = /* @__PURE__ */ new Set();
882
+ const closeCbs = /* @__PURE__ */ new Set();
883
+ const pending = [];
884
+ ws.onopen = () => {
885
+ for (const frame of pending.splice(0)) ws.send(frame);
886
+ };
887
+ ws.onmessage = (event) => {
888
+ let msg;
889
+ try {
890
+ msg = JSON.parse(String(event.data));
891
+ } catch {
892
+ if (isDevMode()) console.warn("[@mmstack/mesh] dropped unparseable frame (expected JSON text)");
893
+ return;
894
+ }
895
+ for (const cb of [...messageCbs]) cb(msg);
896
+ };
897
+ ws.onclose = () => {
898
+ for (const cb of [...closeCbs]) cb();
899
+ };
900
+ return {
901
+ send: (msg) => {
902
+ const frame = JSON.stringify(msg);
903
+ if (ws.readyState === WebSocket.OPEN) ws.send(frame);
904
+ else if (ws.readyState === WebSocket.CONNECTING) pending.push(frame);
905
+ },
906
+ onMessage: (cb) => {
907
+ messageCbs.add(cb);
908
+ return () => messageCbs.delete(cb);
909
+ },
910
+ onClose: (cb) => {
911
+ closeCbs.add(cb);
912
+ return () => closeCbs.delete(cb);
913
+ },
914
+ close: () => ws.close()
915
+ };
916
+ };
1117
917
  }
1118
- /**
1119
- * Connects directly to an in-process `createRelay` — no network. The backbone of full-loop
1120
- * tests, and handy for single-process demos or an SSR-side room.
1121
- */
1122
918
  function directTransport(relay, ctx) {
1123
- return () => {
1124
- const messageCbs = new Set();
1125
- const closeCbs = new Set();
1126
- let open = true;
1127
- const connection = relay.connect({
1128
- send: (msg) => {
1129
- if (!open)
1130
- return;
1131
- for (const cb of [...messageCbs])
1132
- cb(msg);
1133
- },
1134
- close: () => {
1135
- if (!open)
1136
- return;
1137
- open = false;
1138
- connection.disconnect();
1139
- for (const cb of [...closeCbs])
1140
- cb();
1141
- },
1142
- }, ctx);
1143
- return {
1144
- send: (msg) => {
1145
- if (open)
1146
- connection.receive(msg);
1147
- },
1148
- onMessage: (cb) => {
1149
- messageCbs.add(cb);
1150
- return () => messageCbs.delete(cb);
1151
- },
1152
- onClose: (cb) => {
1153
- closeCbs.add(cb);
1154
- return () => closeCbs.delete(cb);
1155
- },
1156
- close: () => {
1157
- if (!open)
1158
- return;
1159
- open = false;
1160
- connection.disconnect();
1161
- for (const cb of [...closeCbs])
1162
- cb();
1163
- },
1164
- };
1165
- };
919
+ return () => {
920
+ const messageCbs = /* @__PURE__ */ new Set();
921
+ const closeCbs = /* @__PURE__ */ new Set();
922
+ let open = true;
923
+ const connection = relay.connect({
924
+ send: (msg) => {
925
+ if (!open) return;
926
+ for (const cb of [...messageCbs]) cb(msg);
927
+ },
928
+ close: () => {
929
+ if (!open) return;
930
+ open = false;
931
+ connection.disconnect();
932
+ for (const cb of [...closeCbs]) cb();
933
+ }
934
+ }, ctx);
935
+ return {
936
+ send: (msg) => {
937
+ if (open) connection.receive(msg);
938
+ },
939
+ onMessage: (cb) => {
940
+ messageCbs.add(cb);
941
+ return () => messageCbs.delete(cb);
942
+ },
943
+ onClose: (cb) => {
944
+ closeCbs.add(cb);
945
+ return () => closeCbs.delete(cb);
946
+ },
947
+ close: () => {
948
+ if (!open) return;
949
+ open = false;
950
+ connection.disconnect();
951
+ for (const cb of [...closeCbs]) cb();
952
+ }
953
+ };
954
+ };
1166
955
  }
1167
-
1168
- /** The starting value: nothing listed. */
1169
- const emptyLifecycle = new Map();
1170
- /** The value after `close`; `step` recognises it by identity and ignores every later event. */
1171
- const closedLifecycle = new Map();
1172
- const hasPeer = (e) => e?.state === 'linking' || e?.state === 'open';
1173
- const hasTimer = (e) => e?.state === 'linking' || e?.state === 'waiting';
1174
- /**
1175
- * Builds now for a listed origin with no peer; keeps an existing one. The open timeout is
1176
- * armed before the build so a link that opens while it is being built cancels it.
1177
- */
956
+ const emptyLifecycle = /* @__PURE__ */ new Map();
957
+ const closedLifecycle = /* @__PURE__ */ new Map();
958
+ const hasPeer = (e) => e?.state === "linking" || e?.state === "open";
959
+ const hasTimer = (e) => e?.state === "linking" || e?.state === "waiting";
1178
960
  const listOne = (s, origin, effects) => {
1179
- const cur = s.get(origin);
1180
- if (hasPeer(cur))
1181
- return;
1182
- if (cur)
1183
- effects.push({ t: 'disarm', origin });
1184
- effects.push({ t: 'armOpen', origin }, { t: 'build', origin });
1185
- s.set(origin, {
1186
- state: 'linking',
1187
- attempt: cur?.attempt ?? 0,
1188
- stalled: cur?.stalled ?? false,
1189
- });
961
+ const cur = s.get(origin);
962
+ if (hasPeer(cur)) return;
963
+ if (cur) effects.push({
964
+ t: "disarm",
965
+ origin
966
+ });
967
+ effects.push({
968
+ t: "armOpen",
969
+ origin
970
+ }, {
971
+ t: "build",
972
+ origin
973
+ });
974
+ s.set(origin, {
975
+ state: "linking",
976
+ attempt: cur?.attempt ?? 0,
977
+ stalled: cur?.stalled ?? false
978
+ });
1190
979
  };
1191
980
  const unlistOne = (s, origin, effects) => {
1192
- const cur = s.get(origin);
1193
- if (!cur)
1194
- return;
1195
- if (hasPeer(cur))
1196
- effects.push({ t: 'drop', origin });
1197
- effects.push({ t: 'disarm', origin });
1198
- s.delete(origin);
981
+ const cur = s.get(origin);
982
+ if (!cur) return;
983
+ if (hasPeer(cur)) effects.push({
984
+ t: "drop",
985
+ origin
986
+ });
987
+ effects.push({
988
+ t: "disarm",
989
+ origin
990
+ });
991
+ s.delete(origin);
1199
992
  };
1200
- const none$1 = (s) => ({ next: s, effects: [] });
1201
- /** One transition. Pure and total: an event that does not apply returns `s` and no effects. */
993
+ const none$1 = (s) => ({
994
+ next: s,
995
+ effects: []
996
+ });
1202
997
  function step(s, e) {
1203
- if (s === closedLifecycle)
1204
- return none$1(s);
1205
- const effects = [];
1206
- const next = new Map(s);
1207
- switch (e.t) {
1208
- case 'listed':
1209
- if (hasPeer(s.get(e.origin)))
1210
- return none$1(s);
1211
- listOne(next, e.origin, effects);
1212
- break;
1213
- case 'welcome': {
1214
- const listed = new Set(e.members);
1215
- for (const origin of s.keys())
1216
- if (!listed.has(origin))
1217
- unlistOne(next, origin, effects);
1218
- for (const origin of listed)
1219
- listOne(next, origin, effects);
1220
- break;
1221
- }
1222
- case 'gone':
1223
- if (!s.has(e.origin))
1224
- return none$1(s);
1225
- unlistOne(next, e.origin, effects);
1226
- break;
1227
- case 'opened': {
1228
- const cur = s.get(e.origin);
1229
- if (cur?.state !== 'linking')
1230
- return none$1(s);
1231
- next.set(e.origin, { state: 'open', attempt: 0, stalled: false });
1232
- effects.push({ t: 'disarm', origin: e.origin });
1233
- break;
1234
- }
1235
- case 'lost': {
1236
- const cur = s.get(e.origin);
1237
- if (!cur || !hasPeer(cur))
1238
- return none$1(s);
1239
- next.set(e.origin, {
1240
- state: 'waiting',
1241
- attempt: cur.attempt + 1,
1242
- stalled: true,
1243
- });
1244
- effects.push({ t: 'drop', origin: e.origin }, { t: 'armRetry', origin: e.origin, attempt: cur.attempt });
1245
- break;
1246
- }
1247
- case 'due': {
1248
- const cur = s.get(e.origin);
1249
- if (cur?.state !== 'waiting')
1250
- return none$1(s);
1251
- next.set(e.origin, { ...cur, state: 'linking' });
1252
- effects.push({ t: 'armOpen', origin: e.origin }, { t: 'build', origin: e.origin });
1253
- break;
1254
- }
1255
- case 'close':
1256
- for (const [origin, cur] of s) {
1257
- if (hasPeer(cur))
1258
- effects.push({ t: 'drop', origin });
1259
- if (hasTimer(cur))
1260
- effects.push({ t: 'disarm', origin });
1261
- }
1262
- return { next: closedLifecycle, effects };
1263
- }
1264
- return { next, effects };
998
+ if (s === closedLifecycle) return none$1(s);
999
+ const effects = [];
1000
+ const next = new Map(s);
1001
+ switch (e.t) {
1002
+ case "listed":
1003
+ if (hasPeer(s.get(e.origin))) return none$1(s);
1004
+ listOne(next, e.origin, effects);
1005
+ break;
1006
+ case "welcome": {
1007
+ const listed = new Set(e.members);
1008
+ for (const origin of s.keys()) if (!listed.has(origin)) unlistOne(next, origin, effects);
1009
+ for (const origin of listed) listOne(next, origin, effects);
1010
+ break;
1011
+ }
1012
+ case "gone":
1013
+ if (!s.has(e.origin)) return none$1(s);
1014
+ unlistOne(next, e.origin, effects);
1015
+ break;
1016
+ case "opened":
1017
+ if (s.get(e.origin)?.state !== "linking") return none$1(s);
1018
+ next.set(e.origin, {
1019
+ state: "open",
1020
+ attempt: 0,
1021
+ stalled: false
1022
+ });
1023
+ effects.push({
1024
+ t: "disarm",
1025
+ origin: e.origin
1026
+ });
1027
+ break;
1028
+ case "lost": {
1029
+ const cur = s.get(e.origin);
1030
+ if (!cur || !hasPeer(cur)) return none$1(s);
1031
+ next.set(e.origin, {
1032
+ state: "waiting",
1033
+ attempt: cur.attempt + 1,
1034
+ stalled: true
1035
+ });
1036
+ effects.push({
1037
+ t: "drop",
1038
+ origin: e.origin
1039
+ }, {
1040
+ t: "armRetry",
1041
+ origin: e.origin,
1042
+ attempt: cur.attempt
1043
+ });
1044
+ break;
1045
+ }
1046
+ case "due": {
1047
+ const cur = s.get(e.origin);
1048
+ if (cur?.state !== "waiting") return none$1(s);
1049
+ next.set(e.origin, {
1050
+ ...cur,
1051
+ state: "linking"
1052
+ });
1053
+ effects.push({
1054
+ t: "armOpen",
1055
+ origin: e.origin
1056
+ }, {
1057
+ t: "build",
1058
+ origin: e.origin
1059
+ });
1060
+ break;
1061
+ }
1062
+ case "close":
1063
+ for (const [origin, cur] of s) {
1064
+ if (hasPeer(cur)) effects.push({
1065
+ t: "drop",
1066
+ origin
1067
+ });
1068
+ if (hasTimer(cur)) effects.push({
1069
+ t: "disarm",
1070
+ origin
1071
+ });
1072
+ }
1073
+ return {
1074
+ next: closedLifecycle,
1075
+ effects
1076
+ };
1077
+ }
1078
+ return {
1079
+ next,
1080
+ effects
1081
+ };
1265
1082
  }
1266
- /**
1267
- * The wait before rebuild number `attempt` (0-based): equal jitter over a capped exponential,
1268
- * so every delay lies in `[base / 2, base)` with `base = min(minMs * 2^attempt, maxMs)`.
1269
- */
1270
1083
  function retryDelay(attempt, bounds, random) {
1271
- const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);
1272
- return base / 2 + random() * (base / 2);
1084
+ const base = Math.min(bounds.minMs * 2 ** attempt, bounds.maxMs);
1085
+ return base / 2 + random() * (base / 2);
1273
1086
  }
1274
-
1275
- /** How many signals are held for replay while a connection waits for its welcome. */
1276
1087
  const HELD_SIGNALS = 256;
1277
- /** The single reliable channel every link carries when no channels are asked for. */
1278
- const defaultPeerChannels = [
1279
- { label: 'mmstack-mesh' },
1280
- ];
1281
- /**
1282
- * WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only.
1283
- *
1284
- * `config` is the static configuration; ICE servers the relay issues replace its `iceServers`.
1285
- * Without any ICE servers browsers hide host addresses behind mDNS names, so links only form
1286
- * on one network segment. When ICE fails, or stays `disconnected` longer than
1287
- * `disconnectGraceMs` (default 5000), the connector restarts ICE once. A second failure before
1288
- * the link connects again, a closed connection, or a negotiation step the browser rejects
1289
- * reports the link gone through `onClose`.
1290
- */
1088
+ const defaultPeerChannels = [{ label: "mmstack-mesh" }];
1291
1089
  function rtcPeerConnector(config, opt) {
1292
- const graceMs = opt?.disconnectGraceMs ?? 5000;
1293
- return ({ polite, sendSignal, channels = defaultPeerChannels, iceServers, }) => {
1294
- const pc = new RTCPeerConnection(iceServers
1295
- ? {
1296
- ...config,
1297
- iceServers: iceServers.map((server) => ({
1298
- ...server,
1299
- urls: typeof server.urls === 'string'
1300
- ? server.urls
1301
- : [...server.urls],
1302
- })),
1303
- }
1304
- : config);
1305
- let makingOffer = false;
1306
- let ignoreOffer = false;
1307
- const goneCbs = new Set();
1308
- let finished = false;
1309
- let restartTried = false;
1310
- let grace;
1311
- const clearGrace = () => {
1312
- if (grace !== undefined)
1313
- clearTimeout(grace);
1314
- grace = undefined;
1315
- };
1316
- const reportGone = () => {
1317
- if (finished)
1318
- return;
1319
- finished = true;
1320
- clearGrace();
1321
- for (const cb of [...goneCbs])
1322
- cb();
1323
- };
1324
- // one ICE restart per connected period; a second failure is the end of the link
1325
- const failed = () => {
1326
- if (finished)
1327
- return;
1328
- if (restartTried)
1329
- return reportGone();
1330
- restartTried = true;
1331
- pc.restartIce();
1332
- };
1333
- const rejected = (step, err) => {
1334
- if (finished || pc.signalingState === 'closed')
1335
- return;
1336
- if (isDevMode()) {
1337
- console.warn(`[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`, err);
1338
- }
1339
- reportGone();
1340
- };
1341
- pc.oniceconnectionstatechange = () => {
1342
- const state = pc.iceConnectionState;
1343
- if (state === 'connected' || state === 'completed') {
1344
- clearGrace();
1345
- restartTried = false;
1346
- }
1347
- else if (state === 'failed') {
1348
- clearGrace();
1349
- failed();
1350
- }
1351
- else if (state === 'disconnected' && grace === undefined) {
1352
- grace = setTimeout(() => {
1353
- grace = undefined;
1354
- const now = pc.iceConnectionState;
1355
- if (now === 'disconnected' || now === 'failed')
1356
- failed();
1357
- }, graceMs);
1358
- }
1359
- };
1360
- pc.onconnectionstatechange = () => {
1361
- if (pc.connectionState === 'closed')
1362
- reportGone();
1363
- };
1364
- const makeChannel = () => {
1365
- const messageCbs = new Set();
1366
- const openCbs = new Set();
1367
- const closeCbs = new Set();
1368
- const pending = [];
1369
- let dc = null;
1370
- const attach = (channel) => {
1371
- dc = channel;
1372
- channel.onmessage = (e) => {
1373
- for (const cb of [...messageCbs])
1374
- cb(String(e.data));
1375
- };
1376
- channel.onopen = () => {
1377
- for (const frame of pending.splice(0))
1378
- channel.send(frame);
1379
- for (const cb of [...openCbs])
1380
- cb();
1381
- };
1382
- channel.onclose = () => {
1383
- for (const cb of [...closeCbs])
1384
- cb();
1385
- };
1386
- };
1387
- const like = {
1388
- send: (frame) => {
1389
- if (dc && dc.readyState === 'open')
1390
- dc.send(frame);
1391
- else
1392
- pending.push(frame);
1393
- },
1394
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1395
- onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1396
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1397
- close: () => dc?.close(),
1398
- };
1399
- return { attach, like };
1400
- };
1401
- const made = new Map(channels.map((c) => [c.label, makeChannel()]));
1402
- // the impolite side opens every channel; the polite side adopts them by label
1403
- if (!polite) {
1404
- for (const spec of channels) {
1405
- const init = {};
1406
- if (spec.ordered !== undefined)
1407
- init.ordered = spec.ordered;
1408
- if (spec.maxRetransmits !== undefined)
1409
- init.maxRetransmits = spec.maxRetransmits;
1410
- made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));
1411
- }
1412
- }
1413
- else {
1414
- pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);
1415
- }
1416
- pc.onicecandidate = (e) => {
1417
- if (e.candidate)
1418
- sendSignal({ ice: e.candidate.toJSON() });
1419
- };
1420
- pc.onnegotiationneeded = async () => {
1421
- try {
1422
- makingOffer = true;
1423
- await pc.setLocalDescription();
1424
- sendSignal({ description: pc.localDescription });
1425
- }
1426
- catch (err) {
1427
- rejected('make an offer', err);
1428
- }
1429
- finally {
1430
- makingOffer = false;
1431
- }
1432
- };
1433
- const byLabel = {};
1434
- for (const [label, ch] of made)
1435
- byLabel[label] = ch.like;
1436
- return {
1437
- channel: byLabel[channels[0].label],
1438
- channels: byLabel,
1439
- signal: async (data) => {
1440
- if (pc.signalingState === 'closed')
1441
- return;
1442
- const { description, ice } = (data ?? {});
1443
- if (description) {
1444
- const collision = description.type === 'offer' &&
1445
- (makingOffer || pc.signalingState !== 'stable');
1446
- ignoreOffer = !polite && collision;
1447
- if (ignoreOffer)
1448
- return;
1449
- try {
1450
- await pc.setRemoteDescription(description);
1451
- if (description.type === 'offer') {
1452
- await pc.setLocalDescription();
1453
- sendSignal({ description: pc.localDescription });
1454
- }
1455
- }
1456
- catch (err) {
1457
- rejected('apply the remote description', err);
1458
- }
1459
- }
1460
- else if (ice) {
1461
- try {
1462
- await pc.addIceCandidate(ice);
1463
- }
1464
- catch (err) {
1465
- if (!ignoreOffer)
1466
- throw err;
1467
- }
1468
- }
1469
- },
1470
- onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),
1471
- close: () => {
1472
- finished = true;
1473
- clearGrace();
1474
- for (const ch of made.values())
1475
- ch.like.close();
1476
- pc.close();
1477
- },
1478
- };
1479
- };
1090
+ const graceMs = opt?.disconnectGraceMs ?? 5e3;
1091
+ return ({ polite, sendSignal, channels = defaultPeerChannels, iceServers }) => {
1092
+ const pc = new RTCPeerConnection(iceServers ? {
1093
+ ...config,
1094
+ iceServers: iceServers.map((server) => ({
1095
+ ...server,
1096
+ urls: typeof server.urls === "string" ? server.urls : [...server.urls]
1097
+ }))
1098
+ } : config);
1099
+ let makingOffer = false;
1100
+ let ignoreOffer = false;
1101
+ const goneCbs = /* @__PURE__ */ new Set();
1102
+ let finished = false;
1103
+ let restartTried = false;
1104
+ let grace;
1105
+ const clearGrace = () => {
1106
+ if (grace !== void 0) clearTimeout(grace);
1107
+ grace = void 0;
1108
+ };
1109
+ const reportGone = () => {
1110
+ if (finished) return;
1111
+ finished = true;
1112
+ clearGrace();
1113
+ for (const cb of [...goneCbs]) cb();
1114
+ };
1115
+ const failed = () => {
1116
+ if (finished) return;
1117
+ if (restartTried) return reportGone();
1118
+ restartTried = true;
1119
+ pc.restartIce();
1120
+ };
1121
+ const rejected = (step, err) => {
1122
+ if (finished || pc.signalingState === "closed") return;
1123
+ if (isDevMode()) console.warn(`[@mmstack/mesh] a peer link could not ${step}; it will be rebuilt`, err);
1124
+ reportGone();
1125
+ };
1126
+ pc.oniceconnectionstatechange = () => {
1127
+ const state = pc.iceConnectionState;
1128
+ if (state === "connected" || state === "completed") {
1129
+ clearGrace();
1130
+ restartTried = false;
1131
+ } else if (state === "failed") {
1132
+ clearGrace();
1133
+ failed();
1134
+ } else if (state === "disconnected" && grace === void 0) grace = setTimeout(() => {
1135
+ grace = void 0;
1136
+ const now = pc.iceConnectionState;
1137
+ if (now === "disconnected" || now === "failed") failed();
1138
+ }, graceMs);
1139
+ };
1140
+ pc.onconnectionstatechange = () => {
1141
+ if (pc.connectionState === "closed") reportGone();
1142
+ };
1143
+ const makeChannel = () => {
1144
+ const messageCbs = /* @__PURE__ */ new Set();
1145
+ const openCbs = /* @__PURE__ */ new Set();
1146
+ const closeCbs = /* @__PURE__ */ new Set();
1147
+ const pending = [];
1148
+ let dc = null;
1149
+ const attach = (channel) => {
1150
+ dc = channel;
1151
+ channel.onmessage = (e) => {
1152
+ for (const cb of [...messageCbs]) cb(String(e.data));
1153
+ };
1154
+ channel.onopen = () => {
1155
+ for (const frame of pending.splice(0)) channel.send(frame);
1156
+ for (const cb of [...openCbs]) cb();
1157
+ };
1158
+ channel.onclose = () => {
1159
+ for (const cb of [...closeCbs]) cb();
1160
+ };
1161
+ };
1162
+ return {
1163
+ attach,
1164
+ like: {
1165
+ send: (frame) => {
1166
+ if (dc && dc.readyState === "open") dc.send(frame);
1167
+ else pending.push(frame);
1168
+ },
1169
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1170
+ onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1171
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1172
+ close: () => dc?.close()
1173
+ }
1174
+ };
1175
+ };
1176
+ const made = new Map(channels.map((c) => [c.label, makeChannel()]));
1177
+ if (!polite) for (const spec of channels) {
1178
+ const init = {};
1179
+ if (spec.ordered !== void 0) init.ordered = spec.ordered;
1180
+ if (spec.maxRetransmits !== void 0) init.maxRetransmits = spec.maxRetransmits;
1181
+ made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));
1182
+ }
1183
+ else pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);
1184
+ pc.onicecandidate = (e) => {
1185
+ if (e.candidate) sendSignal({ ice: e.candidate.toJSON() });
1186
+ };
1187
+ pc.onnegotiationneeded = async () => {
1188
+ try {
1189
+ makingOffer = true;
1190
+ await pc.setLocalDescription();
1191
+ sendSignal({ description: pc.localDescription });
1192
+ } catch (err) {
1193
+ rejected("make an offer", err);
1194
+ } finally {
1195
+ makingOffer = false;
1196
+ }
1197
+ };
1198
+ const byLabel = {};
1199
+ for (const [label, ch] of made) byLabel[label] = ch.like;
1200
+ return {
1201
+ channel: byLabel[channels[0].label],
1202
+ channels: byLabel,
1203
+ signal: async (data) => {
1204
+ if (pc.signalingState === "closed") return;
1205
+ const { description, ice } = data ?? {};
1206
+ if (description) {
1207
+ const collision = description.type === "offer" && (makingOffer || pc.signalingState !== "stable");
1208
+ ignoreOffer = !polite && collision;
1209
+ if (ignoreOffer) return;
1210
+ try {
1211
+ await pc.setRemoteDescription(description);
1212
+ if (description.type === "offer") {
1213
+ await pc.setLocalDescription();
1214
+ sendSignal({ description: pc.localDescription });
1215
+ }
1216
+ } catch (err) {
1217
+ rejected("apply the remote description", err);
1218
+ }
1219
+ } else if (ice) try {
1220
+ await pc.addIceCandidate(ice);
1221
+ } catch (err) {
1222
+ if (!ignoreOffer) throw err;
1223
+ }
1224
+ },
1225
+ onClose: (cb) => (goneCbs.add(cb), () => goneCbs.delete(cb)),
1226
+ close: () => {
1227
+ finished = true;
1228
+ clearGrace();
1229
+ for (const ch of made.values()) ch.like.close();
1230
+ pc.close();
1231
+ }
1232
+ };
1233
+ };
1480
1234
  }
1481
- /**
1482
- * A signal payload split into its addressing and the connector's part: `link` is the sending
1483
- * instance, `to` the receiving instance it was bound to when it sent (absent until it is).
1484
- */
1485
1235
  const unwrapSignal = (data) => {
1486
- if (typeof data !== 'object' || data === null)
1487
- return { payload: data };
1488
- const { link, to, ...rest } = data;
1489
- if (typeof link !== 'string')
1490
- return { payload: data };
1491
- return {
1492
- link,
1493
- to: typeof to === 'string' ? to : undefined,
1494
- payload: Object.keys(rest).length ? rest : undefined,
1495
- };
1236
+ if (typeof data !== "object" || data === null) return { payload: data };
1237
+ const { link, to, ...rest } = data;
1238
+ if (typeof link !== "string") return { payload: data };
1239
+ return {
1240
+ link,
1241
+ to: typeof to === "string" ? to : void 0,
1242
+ payload: Object.keys(rest).length ? rest : void 0
1243
+ };
1496
1244
  };
1497
- /**
1498
- * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
1499
- * room, set up from relay membership and negotiated over relay `signal` frames. Each link
1500
- * carries the same labelled channels; frames are opaque strings, what they mean is the
1501
- * consumer's business.
1502
- *
1503
- * An origin is one seat: the relay hands a second connection with the same origin the seat
1504
- * and reports it to the room as a plain join. Links tell seats apart by instance, not by
1505
- * order: every link announces a random instance id in its signals and, once it knows the
1506
- * instance across, addresses its signals to it. A signal addressed to an instance this side
1507
- * no longer has is dropped. An unaddressed signal from an instance other than the one linked
1508
- * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
1509
- * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1510
- * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
1511
- * still take the seat from each other on every reconnect; give each tab its own origin.
1512
- *
1513
- * A link that does not open every channel within `openTimeoutMs`, loses a channel, or is
1514
- * reported gone by its connector is dropped and rebuilt after a jittered, capped backoff, for
1515
- * as long as the relay lists its origin; a welcome or a join rebuilds at once. Either side may
1516
- * rebuild: its new instance announces itself unaddressed, which makes the other side rebuild
1517
- * its end addressed to it, as for a takeover. `stalled` lists the origins in that state.
1518
- *
1519
- * No link is built before the welcome of the connection it signals over: joins before it are
1520
- * superseded by the welcome's roster and signals are held and replayed after it, so every link
1521
- * is built with that welcome's ICE servers and never an earlier connection's.
1522
- */
1523
1245
  function peerLinks(opt) {
1524
- const injector = opt.injector ?? inject(Injector);
1525
- const connector = opt.connector ?? rtcPeerConnector();
1526
- const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;
1527
- const labels = specs.map((c) => c.label);
1528
- const primary = labels[0];
1529
- const status = signal('connecting', /* @ts-ignore */
1530
- ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1531
- const openPeers = signal(new Set(), /* @ts-ignore */
1532
- ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1533
- const members = signal(new Set(), /* @ts-ignore */
1534
- ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1535
- const peers = new Map();
1536
- const lifecycle = signal(emptyLifecycle, /* @ts-ignore */
1537
- ...(ngDevMode ? [{ debugName: "lifecycle" }] : /* istanbul ignore next */ []));
1538
- // one timer slot per origin: the open timeout or the rebuild timer, never both
1539
- const timers = new Map();
1540
- const openTimeoutMs = opt.openTimeoutMs ?? 15_000;
1541
- const bounds = {
1542
- minMs: opt.retry?.minMs ?? 1000,
1543
- maxMs: opt.retry?.maxMs ?? 30_000,
1544
- };
1545
- const random = opt.random ?? Math.random;
1546
- // the relay's ICE servers from the last welcome; undefined leaves the connector's own
1547
- let iceServers;
1548
- const openCbs = new Set();
1549
- const messageCbs = new Set();
1550
- const closeCbs = new Set();
1551
- const endCbs = new Set();
1552
- const memberCbs = new Set();
1553
- let signalingUnsubs = [];
1554
- let transport = null;
1555
- let reconnectTimer;
1556
- let connected = false;
1557
- let closed = false;
1558
- // no link is built before the welcome of the connection it signals over, so every link
1559
- // carries that welcome's ICE servers: joins are ignored and signals held until then
1560
- let welcomed = false;
1561
- let held = [];
1562
- let heldWarned = false;
1563
- // links are told apart by instance, never by order: a random tag plus a counter
1564
- const tag = Math.random().toString(36).slice(2, 10);
1565
- let linkSeq = 0;
1566
- const port = typeof opt.signaling === 'function' ? null : opt.signaling;
1567
- const sendSignal = (msg) => {
1568
- if (port)
1569
- port.send(msg);
1570
- else
1571
- transport?.send(msg);
1572
- };
1573
- const dropPeer = (origin) => {
1574
- const peer = peers.get(origin);
1575
- if (!peer)
1576
- return;
1577
- peers.delete(origin);
1578
- for (const unsub of peer.unsubs)
1579
- unsub();
1580
- peer.link.close();
1581
- openPeers.update((set) => {
1582
- const next = new Set(set);
1583
- next.delete(origin);
1584
- return next;
1585
- });
1586
- for (const cb of [...closeCbs])
1587
- cb(origin);
1588
- };
1589
- /**
1590
- * Builds the link to `origin`; `remote` is the instance on the other side when the link is
1591
- * built in answer to one of its signals, so everything this side sends is addressed to it.
1592
- */
1593
- const ensurePeer = (origin, remote) => {
1594
- const existing = peers.get(origin);
1595
- if (existing)
1596
- return existing;
1597
- const id = `${tag}.${++linkSeq}`;
1598
- // signals the connector sends while it is still being built wait until the peer is
1599
- // registered, so the remote's synchronous answer finds it instead of building another
1600
- let building = [];
1601
- let retired = false;
1602
- const signal = (data) => {
1603
- if (retired)
1604
- return;
1605
- if (building) {
1606
- building.push(data);
1607
- return;
1608
- }
1609
- const stamped = typeof data === 'object' && data !== null
1610
- ? {
1611
- ...data,
1612
- link: id,
1613
- ...(p.remote === undefined ? {} : { to: p.remote }),
1614
- }
1615
- : data;
1616
- sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });
1617
- };
1618
- const link = connector({
1619
- remote: origin,
1620
- polite: opt.origin > origin,
1621
- sendSignal: signal,
1622
- channels: specs,
1623
- ...(iceServers ? { iceServers } : {}),
1624
- });
1625
- const p = {
1626
- id,
1627
- remote,
1628
- link,
1629
- channels: new Map(),
1630
- unsubs: [() => (retired = true)],
1631
- };
1632
- peers.set(origin, p);
1633
- const lost = () => {
1634
- if (peers.get(origin) === p)
1635
- feed({ t: 'lost', origin });
1636
- };
1637
- if (link.onClose)
1638
- p.unsubs.push(link.onClose(lost));
1639
- const early = building;
1640
- building = null;
1641
- // announce the instance, so a side that still holds a link to an earlier seat of this
1642
- // origin (a takeover the relay reports as a plain join) replaces it
1643
- signal({});
1644
- for (const data of early)
1645
- signal(data);
1646
- for (const label of labels) {
1647
- const channel = link.channels?.[label] ??
1648
- (label === primary ? link.channel : undefined);
1649
- if (!channel) {
1650
- if (isDevMode()) {
1651
- console.warn(`[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`);
1652
- }
1653
- continue;
1654
- }
1655
- const state = { channel, open: false };
1656
- p.channels.set(label, state);
1657
- p.unsubs.push(channel.onOpen(() => {
1658
- state.open = true;
1659
- if (peers.get(origin) === p &&
1660
- labels.every((l) => p.channels.get(l)?.open)) {
1661
- openPeers.update((set) => new Set(set).add(origin));
1662
- feed({ t: 'opened', origin });
1663
- // a link rebuilt by a takeover opens while its origin is already open to the
1664
- // lifecycle, which then ignores the report: its open timeout ends here all the same
1665
- if (untracked(lifecycle).get(origin)?.state === 'open')
1666
- disarm(origin);
1667
- }
1668
- for (const cb of [...openCbs])
1669
- cb(origin, label);
1670
- }), channel.onMessage((frame) => {
1671
- for (const cb of [...messageCbs])
1672
- cb(origin, frame, label);
1673
- }), channel.onClose(lost));
1674
- }
1675
- return p;
1676
- };
1677
- const disarm = (origin) => {
1678
- const timer = timers.get(origin);
1679
- if (timer !== undefined)
1680
- clearTimeout(timer);
1681
- timers.delete(origin);
1682
- };
1683
- const arm = (origin, ms, fire) => {
1684
- disarm(origin);
1685
- const timer = setTimeout(() => {
1686
- if (timers.get(origin) !== timer)
1687
- return;
1688
- timers.delete(origin);
1689
- feed(fire);
1690
- }, ms);
1691
- timers.set(origin, timer);
1692
- };
1693
- const execute = (f, remote) => {
1694
- switch (f.t) {
1695
- case 'drop':
1696
- return dropPeer(f.origin);
1697
- case 'disarm':
1698
- return disarm(f.origin);
1699
- }
1700
- if (closed)
1701
- return;
1702
- switch (f.t) {
1703
- case 'build':
1704
- ensurePeer(f.origin, remote);
1705
- return;
1706
- case 'armOpen':
1707
- return arm(f.origin, openTimeoutMs, { t: 'lost', origin: f.origin });
1708
- case 'armRetry':
1709
- return arm(f.origin, retryDelay(f.attempt, bounds, random), {
1710
- t: 'due',
1711
- origin: f.origin,
1712
- });
1713
- }
1714
- };
1715
- /**
1716
- * Steps the lifecycle and runs its effects in order. The new state is stored first, so an
1717
- * event an effect causes on the spot (a link that opens while it is built) steps from it.
1718
- * `remote` addresses the build of a link made in answer to a signal.
1719
- */
1720
- function feed(e, remote) {
1721
- const { next, effects } = step(untracked(lifecycle), e);
1722
- if (next !== untracked(lifecycle))
1723
- lifecycle.set(next);
1724
- for (const f of effects)
1725
- execute(f, remote);
1726
- }
1727
- const setMembers = (origins) => {
1728
- const next = new Set(origins);
1729
- members.set(next);
1730
- for (const cb of [...memberCbs])
1731
- cb([...next]);
1732
- };
1733
- const welcomeMembers = (origins, ice) => {
1734
- setMembers(origins);
1735
- iceServers = ice;
1736
- welcomed = true;
1737
- status.set('live');
1738
- feed({ t: 'welcome', members: origins });
1739
- const replay = held;
1740
- held = [];
1741
- for (const msg of replay) {
1742
- if (closed)
1743
- return;
1744
- handleSignaling(msg);
1745
- }
1746
- };
1747
- const handleSignaling = (msg) => {
1748
- if (closed || msg.room !== opt.room)
1749
- return;
1750
- if (!welcomed && msg.t !== 'welcome' && msg.t !== 'reject') {
1751
- // the welcome's roster supersedes joins before it; a leave discards what the origin sent
1752
- if (msg.t === 'signal') {
1753
- if (held.length < HELD_SIGNALS)
1754
- held.push(msg);
1755
- else if (isDevMode() && !heldWarned) {
1756
- heldWarned = true;
1757
- console.warn(`[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`);
1758
- }
1759
- }
1760
- else if (msg.t === 'member' && msg.gone) {
1761
- held = held.filter((h) => h.from !== msg.origin);
1762
- }
1763
- return;
1764
- }
1765
- switch (msg.t) {
1766
- case 'welcome':
1767
- welcomeMembers(msg.members, msg.ice);
1768
- return;
1769
- case 'member':
1770
- setMembers(msg.gone
1771
- ? [...members()].filter((origin) => origin !== msg.origin)
1772
- : [...new Set([...members(), msg.origin])]);
1773
- feed({ t: msg.gone ? 'gone' : 'listed', origin: msg.origin });
1774
- return;
1775
- case 'signal': {
1776
- if (!members().has(msg.from)) {
1777
- // the relay routes signals among members only and reports a join before the
1778
- // joiner's first signal; anything else must not become a link that retries forever
1779
- if (isDevMode()) {
1780
- console.warn(`[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`);
1781
- }
1782
- return;
1783
- }
1784
- const { link, to, payload } = unwrapSignal(msg.data);
1785
- let peer = peers.get(msg.from);
1786
- if (link === undefined || (!peer && to === undefined)) {
1787
- // no link to this member (lost and waiting to rebuild): its announce is the reason
1788
- // to build now, addressed to its instance if stamped
1789
- if (!peer)
1790
- feed({ t: 'listed', origin: msg.from }, link);
1791
- peer = peers.get(msg.from);
1792
- if (!peer)
1793
- return;
1794
- }
1795
- else if (to !== undefined && to !== peer?.id) {
1796
- // addressed to an instance this side no longer has: a retired link's leftovers
1797
- return;
1798
- }
1799
- else if (!peer) {
1800
- return;
1801
- }
1802
- else if (peer.remote === undefined) {
1803
- peer.remote = link;
1804
- }
1805
- else if (peer.remote !== link) {
1806
- if (to === undefined) {
1807
- // a new instance over there that does not know this side yet: a new seat or a
1808
- // restarted link, so this side rebuilds, addressing it, which is what makes the
1809
- // rebuild final: the other side never rebuilds in answer to an addressed signal.
1810
- // It replaces the instance, not a lost link: the lifecycle state stays and only
1811
- // the open timeout moves to the new instance.
1812
- dropPeer(msg.from);
1813
- arm(msg.from, openTimeoutMs, { t: 'lost', origin: msg.from });
1814
- peer = ensurePeer(msg.from, link);
1815
- }
1816
- else {
1817
- // built for this very instance, so it is the newer end of this link: adopt it
1818
- peer.remote = link;
1819
- }
1820
- }
1821
- if (payload !== undefined)
1822
- peer.link.signal(payload);
1823
- return;
1824
- }
1825
- case 'reject':
1826
- close();
1827
- return;
1828
- }
1829
- };
1830
- const connectSignaling = () => {
1831
- if (closed)
1832
- return;
1833
- for (const unsub of signalingUnsubs.splice(0))
1834
- unsub();
1835
- if (port) {
1836
- const unsub = port.onMessage(handleSignaling);
1837
- if (closed) {
1838
- unsub();
1839
- return;
1840
- }
1841
- signalingUnsubs = [unsub];
1842
- const current = port.members();
1843
- if (current !== undefined)
1844
- welcomeMembers(current, port.iceServers?.());
1845
- return;
1846
- }
1847
- const t = opt.signaling();
1848
- transport = t;
1849
- signalingUnsubs = [
1850
- t.onMessage(handleSignaling),
1851
- t.onClose(() => {
1852
- if (closed || transport !== t)
1853
- return;
1854
- transport = null;
1855
- welcomed = false;
1856
- held = [];
1857
- status.set('connecting');
1858
- reconnectTimer = setTimeout(connectSignaling, 1000);
1859
- }),
1860
- ];
1861
- t.send({
1862
- t: 'hello',
1863
- room: opt.room,
1864
- origin: opt.origin,
1865
- proto: MESH_PROTO_VERSION,
1866
- policyVersion: opt.policyVersion ?? 0,
1867
- });
1868
- };
1869
- const connect = () => {
1870
- if (connected || closed)
1871
- return;
1872
- connected = true;
1873
- connectSignaling();
1874
- };
1875
- const close = () => {
1876
- if (closed)
1877
- return;
1878
- closed = true;
1879
- held = [];
1880
- if (reconnectTimer !== undefined)
1881
- clearTimeout(reconnectTimer);
1882
- feed({ t: 'close' });
1883
- // a takeover's open timeout on a link the lifecycle already counts open
1884
- for (const origin of [...timers.keys()])
1885
- disarm(origin);
1886
- for (const origin of [...peers.keys()])
1887
- dropPeer(origin);
1888
- for (const unsub of signalingUnsubs.splice(0))
1889
- unsub();
1890
- transport?.close();
1891
- transport = null;
1892
- setMembers([]);
1893
- memberCbs.clear();
1894
- status.set('connecting');
1895
- for (const cb of [...endCbs])
1896
- cb();
1897
- endCbs.clear();
1898
- };
1899
- const openChannel = (origin, label) => {
1900
- const state = peers.get(origin)?.channels.get(label);
1901
- return state?.open ? state.channel : null;
1902
- };
1903
- injector.get(DestroyRef).onDestroy(close);
1904
- if (opt.autoConnect !== false)
1905
- connect();
1906
- return {
1907
- status: status.asReadonly(),
1908
- peers: computed(() => [...openPeers()]),
1909
- stalled: computed(() => [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin)),
1910
- members: computed(() => [...members()]),
1911
- onMembers: (cb) => {
1912
- if (!closed)
1913
- memberCbs.add(cb);
1914
- cb([...members()]);
1915
- return () => memberCbs.delete(cb);
1916
- },
1917
- channels: labels,
1918
- onOpen: (cb) => {
1919
- openCbs.add(cb);
1920
- for (const [origin, peer] of peers) {
1921
- for (const [label, state] of peer.channels) {
1922
- if (state.open)
1923
- cb(origin, label);
1924
- }
1925
- }
1926
- return () => openCbs.delete(cb);
1927
- },
1928
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1929
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1930
- onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),
1931
- send: (origin, frame, channel = primary) => {
1932
- openChannel(origin, channel)?.send(frame);
1933
- },
1934
- broadcast: (frame, channel = primary) => {
1935
- for (const origin of peers.keys())
1936
- openChannel(origin, channel)?.send(frame);
1937
- },
1938
- connect,
1939
- close,
1940
- };
1246
+ const injector = opt.injector ?? inject(Injector);
1247
+ const connector = opt.connector ?? rtcPeerConnector();
1248
+ const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;
1249
+ const labels = specs.map((c) => c.label);
1250
+ const primary = labels[0];
1251
+ const status = signal("connecting", ...ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []);
1252
+ const openPeers = signal(/* @__PURE__ */ new Set(), ...ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []);
1253
+ const members = signal(/* @__PURE__ */ new Set(), ...ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []);
1254
+ const peers = /* @__PURE__ */ new Map();
1255
+ const lifecycle = signal(emptyLifecycle, ...ngDevMode ? [{ debugName: "lifecycle" }] : /* istanbul ignore next */ []);
1256
+ const timers = /* @__PURE__ */ new Map();
1257
+ const openTimeoutMs = opt.openTimeoutMs ?? 15e3;
1258
+ const bounds = {
1259
+ minMs: opt.retry?.minMs ?? 1e3,
1260
+ maxMs: opt.retry?.maxMs ?? 3e4
1261
+ };
1262
+ const random = opt.random ?? Math.random;
1263
+ let iceServers;
1264
+ const openCbs = /* @__PURE__ */ new Set();
1265
+ const messageCbs = /* @__PURE__ */ new Set();
1266
+ const closeCbs = /* @__PURE__ */ new Set();
1267
+ const endCbs = /* @__PURE__ */ new Set();
1268
+ const memberCbs = /* @__PURE__ */ new Set();
1269
+ let signalingUnsubs = [];
1270
+ let transport = null;
1271
+ let reconnectTimer;
1272
+ let connected = false;
1273
+ let closed = false;
1274
+ let welcomed = false;
1275
+ let held = [];
1276
+ let heldWarned = false;
1277
+ const tag = Math.random().toString(36).slice(2, 10);
1278
+ let linkSeq = 0;
1279
+ const port = typeof opt.signaling === "function" ? null : opt.signaling;
1280
+ const sendSignal = (msg) => {
1281
+ if (port) port.send(msg);
1282
+ else transport?.send(msg);
1283
+ };
1284
+ const dropPeer = (origin) => {
1285
+ const peer = peers.get(origin);
1286
+ if (!peer) return;
1287
+ peers.delete(origin);
1288
+ for (const unsub of peer.unsubs) unsub();
1289
+ peer.link.close();
1290
+ openPeers.update((set) => {
1291
+ const next = new Set(set);
1292
+ next.delete(origin);
1293
+ return next;
1294
+ });
1295
+ for (const cb of [...closeCbs]) cb(origin);
1296
+ };
1297
+ const ensurePeer = (origin, remote) => {
1298
+ const existing = peers.get(origin);
1299
+ if (existing) return existing;
1300
+ const id = `${tag}.${++linkSeq}`;
1301
+ let building = [];
1302
+ let retired = false;
1303
+ const signal = (data) => {
1304
+ if (retired) return;
1305
+ if (building) {
1306
+ building.push(data);
1307
+ return;
1308
+ }
1309
+ const stamped = typeof data === "object" && data !== null ? {
1310
+ ...data,
1311
+ link: id,
1312
+ ...p.remote === void 0 ? {} : { to: p.remote }
1313
+ } : data;
1314
+ sendSignal({
1315
+ t: "signal",
1316
+ room: opt.room,
1317
+ to: origin,
1318
+ data: stamped
1319
+ });
1320
+ };
1321
+ const link = connector({
1322
+ remote: origin,
1323
+ polite: opt.origin > origin,
1324
+ sendSignal: signal,
1325
+ channels: specs,
1326
+ ...iceServers ? { iceServers } : {}
1327
+ });
1328
+ const p = {
1329
+ id,
1330
+ remote,
1331
+ link,
1332
+ channels: /* @__PURE__ */ new Map(),
1333
+ unsubs: [() => retired = true]
1334
+ };
1335
+ peers.set(origin, p);
1336
+ const lost = () => {
1337
+ if (peers.get(origin) === p) feed({
1338
+ t: "lost",
1339
+ origin
1340
+ });
1341
+ };
1342
+ if (link.onClose) p.unsubs.push(link.onClose(lost));
1343
+ const early = building;
1344
+ building = null;
1345
+ signal({});
1346
+ for (const data of early) signal(data);
1347
+ for (const label of labels) {
1348
+ const channel = link.channels?.[label] ?? (label === primary ? link.channel : void 0);
1349
+ if (!channel) {
1350
+ if (isDevMode()) console.warn(`[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`);
1351
+ continue;
1352
+ }
1353
+ const state = {
1354
+ channel,
1355
+ open: false
1356
+ };
1357
+ p.channels.set(label, state);
1358
+ p.unsubs.push(channel.onOpen(() => {
1359
+ state.open = true;
1360
+ if (peers.get(origin) === p && labels.every((l) => p.channels.get(l)?.open)) {
1361
+ openPeers.update((set) => new Set(set).add(origin));
1362
+ feed({
1363
+ t: "opened",
1364
+ origin
1365
+ });
1366
+ if (untracked(lifecycle).get(origin)?.state === "open") disarm(origin);
1367
+ }
1368
+ for (const cb of [...openCbs]) cb(origin, label);
1369
+ }), channel.onMessage((frame) => {
1370
+ for (const cb of [...messageCbs]) cb(origin, frame, label);
1371
+ }), channel.onClose(lost));
1372
+ }
1373
+ return p;
1374
+ };
1375
+ const disarm = (origin) => {
1376
+ const timer = timers.get(origin);
1377
+ if (timer !== void 0) clearTimeout(timer);
1378
+ timers.delete(origin);
1379
+ };
1380
+ const arm = (origin, ms, fire) => {
1381
+ disarm(origin);
1382
+ const timer = setTimeout(() => {
1383
+ if (timers.get(origin) !== timer) return;
1384
+ timers.delete(origin);
1385
+ feed(fire);
1386
+ }, ms);
1387
+ timers.set(origin, timer);
1388
+ };
1389
+ const execute = (f, remote) => {
1390
+ switch (f.t) {
1391
+ case "drop": return dropPeer(f.origin);
1392
+ case "disarm": return disarm(f.origin);
1393
+ }
1394
+ if (closed) return;
1395
+ switch (f.t) {
1396
+ case "build":
1397
+ ensurePeer(f.origin, remote);
1398
+ return;
1399
+ case "armOpen": return arm(f.origin, openTimeoutMs, {
1400
+ t: "lost",
1401
+ origin: f.origin
1402
+ });
1403
+ case "armRetry": return arm(f.origin, retryDelay(f.attempt, bounds, random), {
1404
+ t: "due",
1405
+ origin: f.origin
1406
+ });
1407
+ }
1408
+ };
1409
+ function feed(e, remote) {
1410
+ const { next, effects } = step(untracked(lifecycle), e);
1411
+ if (next !== untracked(lifecycle)) lifecycle.set(next);
1412
+ for (const f of effects) execute(f, remote);
1413
+ }
1414
+ const setMembers = (origins) => {
1415
+ const next = new Set(origins);
1416
+ members.set(next);
1417
+ for (const cb of [...memberCbs]) cb([...next]);
1418
+ };
1419
+ const welcomeMembers = (origins, ice) => {
1420
+ setMembers(origins);
1421
+ iceServers = ice;
1422
+ welcomed = true;
1423
+ status.set("live");
1424
+ feed({
1425
+ t: "welcome",
1426
+ members: origins
1427
+ });
1428
+ const replay = held;
1429
+ held = [];
1430
+ for (const msg of replay) {
1431
+ if (closed) return;
1432
+ handleSignaling(msg);
1433
+ }
1434
+ };
1435
+ const handleSignaling = (msg) => {
1436
+ if (closed || msg.room !== opt.room) return;
1437
+ if (!welcomed && msg.t !== "welcome" && msg.t !== "reject") {
1438
+ if (msg.t === "signal") {
1439
+ if (held.length < HELD_SIGNALS) held.push(msg);
1440
+ else if (isDevMode() && !heldWarned) {
1441
+ heldWarned = true;
1442
+ console.warn(`[@mmstack/mesh] more than ${HELD_SIGNALS} signals arrived before the welcome; the rest are dropped`);
1443
+ }
1444
+ } else if (msg.t === "member" && msg.gone) held = held.filter((h) => h.from !== msg.origin);
1445
+ return;
1446
+ }
1447
+ switch (msg.t) {
1448
+ case "welcome":
1449
+ welcomeMembers(msg.members, msg.ice);
1450
+ return;
1451
+ case "member":
1452
+ setMembers(msg.gone ? [...members()].filter((origin) => origin !== msg.origin) : [.../* @__PURE__ */ new Set([...members(), msg.origin])]);
1453
+ feed({
1454
+ t: msg.gone ? "gone" : "listed",
1455
+ origin: msg.origin
1456
+ });
1457
+ return;
1458
+ case "signal": {
1459
+ if (!members().has(msg.from)) {
1460
+ if (isDevMode()) console.warn(`[@mmstack/mesh] dropped a signal from '${msg.from}', which the relay does not list`);
1461
+ return;
1462
+ }
1463
+ const { link, to, payload } = unwrapSignal(msg.data);
1464
+ let peer = peers.get(msg.from);
1465
+ if (link === void 0 || !peer && to === void 0) {
1466
+ if (!peer) feed({
1467
+ t: "listed",
1468
+ origin: msg.from
1469
+ }, link);
1470
+ peer = peers.get(msg.from);
1471
+ if (!peer) return;
1472
+ } else if (to !== void 0 && to !== peer?.id) return;
1473
+ else if (!peer) return;
1474
+ else if (peer.remote === void 0) peer.remote = link;
1475
+ else if (peer.remote !== link) {
1476
+ if (to === void 0) {
1477
+ dropPeer(msg.from);
1478
+ arm(msg.from, openTimeoutMs, {
1479
+ t: "lost",
1480
+ origin: msg.from
1481
+ });
1482
+ peer = ensurePeer(msg.from, link);
1483
+ } else peer.remote = link;
1484
+ }
1485
+ if (payload !== void 0) peer.link.signal(payload);
1486
+ return;
1487
+ }
1488
+ case "reject":
1489
+ close();
1490
+ return;
1491
+ }
1492
+ };
1493
+ const connectSignaling = () => {
1494
+ if (closed) return;
1495
+ for (const unsub of signalingUnsubs.splice(0)) unsub();
1496
+ if (port) {
1497
+ const unsub = port.onMessage(handleSignaling);
1498
+ if (closed) {
1499
+ unsub();
1500
+ return;
1501
+ }
1502
+ signalingUnsubs = [unsub];
1503
+ const current = port.members();
1504
+ if (current !== void 0) welcomeMembers(current, port.iceServers?.());
1505
+ return;
1506
+ }
1507
+ const t = opt.signaling();
1508
+ transport = t;
1509
+ signalingUnsubs = [t.onMessage(handleSignaling), t.onClose(() => {
1510
+ if (closed || transport !== t) return;
1511
+ transport = null;
1512
+ welcomed = false;
1513
+ held = [];
1514
+ status.set("connecting");
1515
+ reconnectTimer = setTimeout(connectSignaling, 1e3);
1516
+ })];
1517
+ t.send({
1518
+ t: "hello",
1519
+ room: opt.room,
1520
+ origin: opt.origin,
1521
+ proto: MESH_PROTO_VERSION,
1522
+ policyVersion: opt.policyVersion ?? 0
1523
+ });
1524
+ };
1525
+ const connect = () => {
1526
+ if (connected || closed) return;
1527
+ connected = true;
1528
+ connectSignaling();
1529
+ };
1530
+ const close = () => {
1531
+ if (closed) return;
1532
+ closed = true;
1533
+ held = [];
1534
+ if (reconnectTimer !== void 0) clearTimeout(reconnectTimer);
1535
+ feed({ t: "close" });
1536
+ for (const origin of [...timers.keys()]) disarm(origin);
1537
+ for (const origin of [...peers.keys()]) dropPeer(origin);
1538
+ for (const unsub of signalingUnsubs.splice(0)) unsub();
1539
+ transport?.close();
1540
+ transport = null;
1541
+ setMembers([]);
1542
+ memberCbs.clear();
1543
+ status.set("connecting");
1544
+ for (const cb of [...endCbs]) cb();
1545
+ endCbs.clear();
1546
+ };
1547
+ const openChannel = (origin, label) => {
1548
+ const state = peers.get(origin)?.channels.get(label);
1549
+ return state?.open ? state.channel : null;
1550
+ };
1551
+ injector.get(DestroyRef).onDestroy(close);
1552
+ if (opt.autoConnect !== false) connect();
1553
+ return {
1554
+ status: status.asReadonly(),
1555
+ peers: computed(() => [...openPeers()]),
1556
+ stalled: computed(() => [...lifecycle()].filter(([, e]) => e.stalled).map(([origin]) => origin)),
1557
+ members: computed(() => [...members()]),
1558
+ onMembers: (cb) => {
1559
+ if (!closed) memberCbs.add(cb);
1560
+ cb([...members()]);
1561
+ return () => memberCbs.delete(cb);
1562
+ },
1563
+ channels: labels,
1564
+ onOpen: (cb) => {
1565
+ openCbs.add(cb);
1566
+ for (const [origin, peer] of peers) for (const [label, state] of peer.channels) if (state.open) cb(origin, label);
1567
+ return () => openCbs.delete(cb);
1568
+ },
1569
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1570
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1571
+ onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),
1572
+ send: (origin, frame, channel = primary) => {
1573
+ openChannel(origin, channel)?.send(frame);
1574
+ },
1575
+ broadcast: (frame, channel = primary) => {
1576
+ for (const origin of peers.keys()) openChannel(origin, channel)?.send(frame);
1577
+ },
1578
+ connect,
1579
+ close
1580
+ };
1941
1581
  }
1942
-
1943
- /**
1944
- * Peer-to-peer mesh sync: the relay only signals
1945
- * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1946
- * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1947
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1948
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
1949
- * carry over intact: a late joiner is indistinguishable from a peer that saw every
1950
- * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1951
- * go-forward guarantees but do not exchange the missed envelopes retroactively.
1952
- *
1953
- * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1954
- * relay-backed session over the same document a peer channel may hand on only envelopes the
1955
- * relay has sequenced, never a peer's own unacknowledged writes.
1956
- */
1957
1582
  function webRtcMesh(source, opt) {
1958
- const injector = opt.injector ?? inject(Injector);
1959
- const meshChannel = defaultPeerChannels[0];
1960
- let closed = false;
1961
- const sync = opSync(source, {
1962
- writer: opt.writer,
1963
- origin: opt.origin,
1964
- policies: opt.policies,
1965
- policyVersion: opt.policyVersion,
1966
- injector,
1967
- });
1968
- // subscribe before signaling starts: a link can open, and its first frame arrive, while
1969
- // the hello is still being answered
1970
- const links = peerLinks({
1971
- room: opt.room,
1972
- origin: sync.origin,
1973
- signaling: opt.signaling,
1974
- connector: opt.connector,
1975
- channels: [
1976
- meshChannel,
1977
- ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),
1978
- ],
1979
- policyVersion: opt.policyVersion,
1980
- autoConnect: false,
1981
- injector,
1982
- });
1983
- const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1984
- const sendTo = (origin, msg) => {
1985
- links.send(origin, JSON.stringify(msg));
1986
- };
1987
- const handlePeerMsg = (origin, msg) => {
1988
- switch (msg.t) {
1989
- case 'hello': {
1990
- const snap = sync.snapshot();
1991
- if (covered(snap.wm, msg.wm))
1992
- sendTo(origin, { t: 'uptodate' });
1993
- else
1994
- sendTo(origin, { t: 'state', state: snap });
1995
- return;
1996
- }
1997
- case 'state': {
1998
- if (covered(sync.watermark(), msg.state.wm)) {
1999
- sync.hydrate(msg.state);
2000
- }
2001
- return;
2002
- }
2003
- case 'uptodate':
2004
- return;
2005
- case 'env':
2006
- sync.receive(msg.env);
2007
- return;
2008
- }
2009
- };
2010
- links.onOpen((origin, channel) => {
2011
- if (channel === meshChannel.label)
2012
- sendTo(origin, { t: 'hello', wm: sync.watermark() });
2013
- });
2014
- links.onMessage((origin, frame, channel) => {
2015
- if (channel !== meshChannel.label)
2016
- return;
2017
- let msg;
2018
- try {
2019
- msg = JSON.parse(frame);
2020
- }
2021
- catch {
2022
- return;
2023
- }
2024
- handlePeerMsg(origin, msg);
2025
- });
2026
- const unsubLocal = sync.subscribe((env) => links.broadcast(JSON.stringify({ t: 'env', env })));
2027
- const close = () => {
2028
- if (closed)
2029
- return;
2030
- closed = true;
2031
- unsubLocal();
2032
- links.close();
2033
- sync.destroy();
2034
- };
2035
- // a relay reject ends the links; the mesh ends with them
2036
- links.onEnd(close);
2037
- links.connect();
2038
- return {
2039
- origin: sync.origin,
2040
- status: links.status,
2041
- peers: links.peers,
2042
- links,
2043
- close,
2044
- };
1583
+ const injector = opt.injector ?? inject(Injector);
1584
+ const meshChannel = defaultPeerChannels[0];
1585
+ let closed = false;
1586
+ const sync = opSync(source, {
1587
+ writer: opt.writer,
1588
+ origin: opt.origin,
1589
+ policies: opt.policies,
1590
+ policyVersion: opt.policyVersion,
1591
+ injector,
1592
+ emit: opt.emit
1593
+ });
1594
+ const links = peerLinks({
1595
+ room: opt.room,
1596
+ origin: sync.origin,
1597
+ signaling: opt.signaling,
1598
+ connector: opt.connector,
1599
+ channels: [meshChannel, ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label)],
1600
+ policyVersion: opt.policyVersion,
1601
+ autoConnect: false,
1602
+ injector
1603
+ });
1604
+ const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1605
+ const sendTo = (origin, msg) => {
1606
+ links.send(origin, JSON.stringify(msg));
1607
+ };
1608
+ const handlePeerMsg = (origin, msg) => {
1609
+ switch (msg.t) {
1610
+ case "hello": {
1611
+ const snap = sync.snapshot();
1612
+ if (covered(snap.wm, msg.wm)) sendTo(origin, { t: "uptodate" });
1613
+ else sendTo(origin, {
1614
+ t: "state",
1615
+ state: snap
1616
+ });
1617
+ return;
1618
+ }
1619
+ case "state":
1620
+ if (covered(sync.watermark(), msg.state.wm)) sync.hydrate(msg.state);
1621
+ return;
1622
+ case "uptodate": return;
1623
+ case "env":
1624
+ sync.receive(msg.env);
1625
+ return;
1626
+ }
1627
+ };
1628
+ links.onOpen((origin, channel) => {
1629
+ if (channel === meshChannel.label) sendTo(origin, {
1630
+ t: "hello",
1631
+ wm: sync.watermark()
1632
+ });
1633
+ });
1634
+ links.onMessage((origin, frame, channel) => {
1635
+ if (channel !== meshChannel.label) return;
1636
+ let msg;
1637
+ try {
1638
+ msg = JSON.parse(frame);
1639
+ } catch {
1640
+ return;
1641
+ }
1642
+ handlePeerMsg(origin, msg);
1643
+ });
1644
+ const unsubLocal = sync.subscribe((env) => links.broadcast(JSON.stringify({
1645
+ t: "env",
1646
+ env
1647
+ })));
1648
+ const close = () => {
1649
+ if (closed) return;
1650
+ closed = true;
1651
+ unsubLocal();
1652
+ links.close();
1653
+ sync.destroy();
1654
+ };
1655
+ links.onEnd(close);
1656
+ links.connect();
1657
+ return {
1658
+ origin: sync.origin,
1659
+ status: links.status,
1660
+ peers: links.peers,
1661
+ links,
1662
+ close
1663
+ };
2045
1664
  }
2046
-
2047
- /**
2048
- * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
2049
- * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
2050
- * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
2051
- */
2052
1665
  const presenceChannel = {
2053
- label: 'mmstack-presence',
2054
- ordered: false,
2055
- maxRetransmits: 0,
1666
+ label: "mmstack-presence",
1667
+ ordered: false,
1668
+ maxRetransmits: 0
2056
1669
  };
2057
- const none = Symbol('none');
2058
- // one send counter per links object and channel, shared by every sender created on them
2059
- const counters = new WeakMap();
1670
+ const none = Symbol("none");
1671
+ const counters = /* @__PURE__ */ new WeakMap();
2060
1672
  const counterOf = (links, label) => {
2061
- let byLabel = counters.get(links);
2062
- if (!byLabel)
2063
- counters.set(links, (byLabel = new Map()));
2064
- let counter = byLabel.get(label);
2065
- if (!counter)
2066
- byLabel.set(label, (counter = { seq: 0 }));
2067
- return counter;
1673
+ let byLabel = counters.get(links);
1674
+ if (!byLabel) counters.set(links, byLabel = /* @__PURE__ */ new Map());
1675
+ let counter = byLabel.get(label);
1676
+ if (!counter) byLabel.set(label, counter = { seq: 0 });
1677
+ return counter;
2068
1678
  };
2069
- const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
2070
- /**
2071
- * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
2072
- * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
2073
- * sender's next `set`.
2074
- *
2075
- * Order comes from causality the receiver observes, never from clocks or from numbers chosen
2076
- * by different senders. A value is held only for an origin in the roster, and it is removed
2077
- * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
2078
- * below it is dropped: one counter stamps every frame sent on that link in send order, so a
2079
- * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
2080
- * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
2081
- * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
2082
- * and nobody reads `peers` between leave and rejoin.
2083
- *
2084
- * The counter belongs to the links and the channel, not to this sender, so a sender closed
2085
- * and recreated on the same links carries on where the last one stopped and is heard at
2086
- * once. A new tab or device is a new link, which every receiver already treats as fresh.
2087
- *
2088
- * Nothing is minted while no link carries the channel: a sender alone costs no frames, no
2089
- * numbers and no timers. The gate is the set of links whose presence channel is open, the very
2090
- * set `broadcast` delivers to, so no frame that anyone could receive is withheld.
2091
- *
2092
- * Values travel as JSON.
2093
- */
1679
+ const isNum = (x) => typeof x === "number" && Number.isFinite(x);
2094
1680
  function rtcPresence(links, opt) {
2095
- const injector = opt.injector ?? inject(Injector);
2096
- const label = opt.channel ?? presenceChannel.label;
2097
- if (!links.channels.includes(label)) {
2098
- throw new Error(`[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`);
2099
- }
2100
- const held = new Map();
2101
- const version = signal(0, /* @ts-ignore */
2102
- ...(ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []));
2103
- const counter = counterOf(links, label);
2104
- let closed = false;
2105
- let roster = new Set();
2106
- // origins whose link has this channel open: who a broadcast would reach
2107
- const open = new Set();
2108
- const forget = (origin) => {
2109
- if (held.delete(origin))
2110
- version.update((v) => v + 1);
2111
- };
2112
- const receive = (origin, frame) => {
2113
- if (closed)
2114
- return;
2115
- let msg;
2116
- try {
2117
- msg = JSON.parse(frame);
2118
- }
2119
- catch {
2120
- return;
2121
- }
2122
- if (typeof msg !== 'object' ||
2123
- msg === null ||
2124
- !isNum(msg.seq) ||
2125
- !('value' in msg)) {
2126
- return;
2127
- }
2128
- if (!roster.has(origin))
2129
- return;
2130
- const prev = held.get(origin);
2131
- if (prev && msg.seq <= prev.seq)
2132
- return;
2133
- held.set(origin, { seq: msg.seq, value: msg.value });
2134
- version.update((v) => v + 1);
2135
- };
2136
- const unsubs = [
2137
- opt.roster((members) => {
2138
- roster = new Set(members);
2139
- for (const origin of held.keys())
2140
- if (!roster.has(origin))
2141
- forget(origin);
2142
- }),
2143
- links.onMessage((origin, frame, channel) => {
2144
- if (channel === label)
2145
- receive(origin, frame);
2146
- }),
2147
- // the link is the epoch: a new or lost link starts the origin fresh
2148
- links.onOpen((origin, channel) => {
2149
- if (channel !== label)
2150
- return;
2151
- forget(origin);
2152
- open.add(origin);
2153
- }),
2154
- links.onClose((origin) => {
2155
- open.delete(origin);
2156
- forget(origin);
2157
- }),
2158
- links.onEnd(() => close()),
2159
- ];
2160
- const peers = computed(() => {
2161
- version();
2162
- if (closed)
2163
- return new Map();
2164
- const out = new Map();
2165
- for (const [origin, entry] of held) {
2166
- if (roster.has(origin))
2167
- out.set(origin, entry.value);
2168
- }
2169
- return out;
2170
- }, /* @ts-ignore */
2171
- ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
2172
- const destroyRef = injector.get(DestroyRef);
2173
- const outgoing = throttled(none, {
2174
- ms: opt.throttleMs ?? 33,
2175
- leading: true,
2176
- trailing: true,
2177
- destroyRef,
2178
- });
2179
- const publisher = effect(() => {
2180
- const value = outgoing();
2181
- // a link closed since the set: nothing to reach, so nothing is minted
2182
- if (value === none || closed || open.size === 0)
2183
- return;
2184
- untracked(() => links.broadcast(JSON.stringify({
2185
- seq: counter.seq++,
2186
- value,
2187
- }), label));
2188
- }, { ...(ngDevMode ? { debugName: "publisher" } : /* istanbul ignore next */ {}), injector });
2189
- const close = () => {
2190
- if (closed)
2191
- return;
2192
- closed = true;
2193
- publisher.destroy();
2194
- for (const unsub of unsubs.splice(0))
2195
- unsub();
2196
- held.clear();
2197
- open.clear();
2198
- version.update((v) => v + 1);
2199
- };
2200
- destroyRef.onDestroy(close);
2201
- return {
2202
- set: (value) => {
2203
- if (!closed && open.size > 0)
2204
- outgoing.set(value);
2205
- },
2206
- peers,
2207
- close,
2208
- };
1681
+ const injector = opt.injector ?? inject(Injector);
1682
+ const label = opt.channel ?? presenceChannel.label;
1683
+ if (!links.channels.includes(label)) throw new Error(`[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`);
1684
+ const held = /* @__PURE__ */ new Map();
1685
+ const version = signal(0, ...ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []);
1686
+ const counter = counterOf(links, label);
1687
+ let closed = false;
1688
+ let roster = /* @__PURE__ */ new Set();
1689
+ const open = /* @__PURE__ */ new Set();
1690
+ const forget = (origin) => {
1691
+ if (held.delete(origin)) version.update((v) => v + 1);
1692
+ };
1693
+ const receive = (origin, frame) => {
1694
+ if (closed) return;
1695
+ let msg;
1696
+ try {
1697
+ msg = JSON.parse(frame);
1698
+ } catch {
1699
+ return;
1700
+ }
1701
+ if (typeof msg !== "object" || msg === null || !isNum(msg.seq) || !("value" in msg)) return;
1702
+ if (!roster.has(origin)) return;
1703
+ const prev = held.get(origin);
1704
+ if (prev && msg.seq <= prev.seq) return;
1705
+ held.set(origin, {
1706
+ seq: msg.seq,
1707
+ value: msg.value
1708
+ });
1709
+ version.update((v) => v + 1);
1710
+ };
1711
+ const unsubs = [
1712
+ opt.roster((members) => {
1713
+ roster = new Set(members);
1714
+ for (const origin of held.keys()) if (!roster.has(origin)) forget(origin);
1715
+ }),
1716
+ links.onMessage((origin, frame, channel) => {
1717
+ if (channel === label) receive(origin, frame);
1718
+ }),
1719
+ links.onOpen((origin, channel) => {
1720
+ if (channel !== label) return;
1721
+ forget(origin);
1722
+ open.add(origin);
1723
+ }),
1724
+ links.onClose((origin) => {
1725
+ open.delete(origin);
1726
+ forget(origin);
1727
+ }),
1728
+ links.onEnd(() => close())
1729
+ ];
1730
+ const peers = computed(() => {
1731
+ version();
1732
+ if (closed) return /* @__PURE__ */ new Map();
1733
+ const out = /* @__PURE__ */ new Map();
1734
+ for (const [origin, entry] of held) if (roster.has(origin)) out.set(origin, entry.value);
1735
+ return out;
1736
+ }, ...ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []);
1737
+ const destroyRef = injector.get(DestroyRef);
1738
+ const outgoing = throttled(none, {
1739
+ ms: opt.throttleMs ?? 33,
1740
+ leading: true,
1741
+ trailing: true,
1742
+ destroyRef
1743
+ });
1744
+ const publisher = effect(() => {
1745
+ const value = outgoing();
1746
+ if (value === none || closed || open.size === 0) return;
1747
+ untracked(() => links.broadcast(JSON.stringify({
1748
+ seq: counter.seq++,
1749
+ value
1750
+ }), label));
1751
+ }, {
1752
+ ...ngDevMode ? { debugName: "publisher" } : /* istanbul ignore next */ {},
1753
+ injector
1754
+ });
1755
+ const close = () => {
1756
+ if (closed) return;
1757
+ closed = true;
1758
+ publisher.destroy();
1759
+ for (const unsub of unsubs.splice(0)) unsub();
1760
+ held.clear();
1761
+ open.clear();
1762
+ version.update((v) => v + 1);
1763
+ };
1764
+ destroyRef.onDestroy(close);
1765
+ return {
1766
+ set: (value) => {
1767
+ if (!closed && open.size > 0) outgoing.set(value);
1768
+ },
1769
+ peers,
1770
+ close
1771
+ };
2209
1772
  }
2210
-
2211
- /**
2212
- * Generated bundle index. Do not edit.
2213
- */
2214
-
2215
1773
  export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
2216
- //# sourceMappingURL=mmstack-mesh.mjs.map
1774
+
1775
+ //# sourceMappingURL=mmstack-mesh.mjs.map