@mmstack/mesh 22.9.0 → 22.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  import { createWatch } from '@angular/core/primitives/signals';
2
- import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource } from '@mmstack/primitives/core';
2
+ import { createConvergingApply, createStoreContext, store, opSync, forkStore, isStoreReservedKey, OP_PROTO_VERSION, registerResource, throttled } from '@mmstack/primitives/core';
3
3
  import { MESH_PROTO_VERSION, checkEnvelope } from '@mmstack/mesh-protocol';
4
- import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef } from '@angular/core';
4
+ import { inject, Injector, signal, computed, isDevMode, runInInjectionContext, DestroyRef, effect, untracked } from '@angular/core';
5
5
 
6
6
  const RECONNECT_BASE_MS = 500;
7
7
  function meshSession(opt) {
@@ -985,38 +985,68 @@ function directTransport(relay, ctx) {
985
985
  };
986
986
  }
987
987
 
988
+ /** The single reliable channel every link carries when no channels are asked for. */
989
+ const defaultPeerChannels = [
990
+ { label: 'mmstack-mesh' },
991
+ ];
988
992
  /** WebRTC `PeerConnector` implementing the perfect-negotiation pattern. Browser-only. */
989
993
  function rtcPeerConnector(config) {
990
- return ({ polite, sendSignal }) => {
994
+ return ({ polite, sendSignal, channels = defaultPeerChannels }) => {
991
995
  const pc = new RTCPeerConnection(config);
992
- const messageCbs = new Set();
993
- const openCbs = new Set();
994
- const closeCbs = new Set();
995
- const pending = [];
996
- let dc = null;
997
996
  let makingOffer = false;
998
997
  let ignoreOffer = false;
999
- const attach = (channel) => {
1000
- dc = channel;
1001
- channel.onmessage = (e) => {
1002
- for (const cb of [...messageCbs])
1003
- cb(String(e.data));
998
+ const makeChannel = () => {
999
+ const messageCbs = new Set();
1000
+ const openCbs = new Set();
1001
+ const closeCbs = new Set();
1002
+ const pending = [];
1003
+ let dc = null;
1004
+ const attach = (channel) => {
1005
+ dc = channel;
1006
+ channel.onmessage = (e) => {
1007
+ for (const cb of [...messageCbs])
1008
+ cb(String(e.data));
1009
+ };
1010
+ channel.onopen = () => {
1011
+ for (const frame of pending.splice(0))
1012
+ channel.send(frame);
1013
+ for (const cb of [...openCbs])
1014
+ cb();
1015
+ };
1016
+ channel.onclose = () => {
1017
+ for (const cb of [...closeCbs])
1018
+ cb();
1019
+ };
1004
1020
  };
1005
- channel.onopen = () => {
1006
- for (const frame of pending.splice(0))
1007
- channel.send(frame);
1008
- for (const cb of [...openCbs])
1009
- cb();
1010
- };
1011
- channel.onclose = () => {
1012
- for (const cb of [...closeCbs])
1013
- cb();
1021
+ const like = {
1022
+ send: (frame) => {
1023
+ if (dc && dc.readyState === 'open')
1024
+ dc.send(frame);
1025
+ else
1026
+ pending.push(frame);
1027
+ },
1028
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1029
+ onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1030
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1031
+ close: () => dc?.close(),
1014
1032
  };
1033
+ return { attach, like };
1015
1034
  };
1016
- if (!polite)
1017
- attach(pc.createDataChannel('mmstack-mesh'));
1018
- else
1019
- pc.ondatachannel = (e) => attach(e.channel);
1035
+ const made = new Map(channels.map((c) => [c.label, makeChannel()]));
1036
+ // the impolite side opens every channel; the polite side adopts them by label
1037
+ if (!polite) {
1038
+ for (const spec of channels) {
1039
+ const init = {};
1040
+ if (spec.ordered !== undefined)
1041
+ init.ordered = spec.ordered;
1042
+ if (spec.maxRetransmits !== undefined)
1043
+ init.maxRetransmits = spec.maxRetransmits;
1044
+ made.get(spec.label)?.attach(pc.createDataChannel(spec.label, init));
1045
+ }
1046
+ }
1047
+ else {
1048
+ pc.ondatachannel = (e) => made.get(e.channel.label)?.attach(e.channel);
1049
+ }
1020
1050
  pc.onicecandidate = (e) => {
1021
1051
  if (e.candidate)
1022
1052
  sendSignal({ ice: e.candidate.toJSON() });
@@ -1031,19 +1061,12 @@ function rtcPeerConnector(config) {
1031
1061
  makingOffer = false;
1032
1062
  }
1033
1063
  };
1064
+ const byLabel = {};
1065
+ for (const [label, ch] of made)
1066
+ byLabel[label] = ch.like;
1034
1067
  return {
1035
- channel: {
1036
- send: (frame) => {
1037
- if (dc && dc.readyState === 'open')
1038
- dc.send(frame);
1039
- else
1040
- pending.push(frame);
1041
- },
1042
- onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1043
- onOpen: (cb) => (openCbs.add(cb), () => openCbs.delete(cb)),
1044
- onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1045
- close: () => dc?.close(),
1046
- },
1068
+ channel: byLabel[channels[0].label],
1069
+ channels: byLabel,
1047
1070
  signal: async (data) => {
1048
1071
  const { description, ice } = (data ?? {});
1049
1072
  if (description) {
@@ -1069,53 +1092,77 @@ function rtcPeerConnector(config) {
1069
1092
  }
1070
1093
  },
1071
1094
  close: () => {
1072
- dc?.close();
1095
+ for (const ch of made.values())
1096
+ ch.like.close();
1073
1097
  pc.close();
1074
1098
  },
1075
1099
  };
1076
1100
  };
1077
1101
  }
1078
1102
  /**
1079
- * Peer-to-peer mesh sync: the relay only signals
1080
- * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1081
- * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1082
- * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1083
- * checkpoint (root + per-path register state + watermark), so supersession and precedence
1084
- * carry over intact: a late joiner is indistinguishable from a peer that saw every
1085
- * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1086
- * go-forward guarantees but do not exchange the missed envelopes retroactively.
1103
+ * A signal payload split into its addressing and the connector's part: `link` is the sending
1104
+ * instance, `to` the receiving instance it was bound to when it sent (absent until it is).
1105
+ */
1106
+ const unwrapSignal = (data) => {
1107
+ if (typeof data !== 'object' || data === null)
1108
+ return { payload: data };
1109
+ const { link, to, ...rest } = data;
1110
+ if (typeof link !== 'string')
1111
+ return { payload: data };
1112
+ return {
1113
+ link,
1114
+ to: typeof to === 'string' ? to : undefined,
1115
+ payload: Object.keys(rest).length ? rest : undefined,
1116
+ };
1117
+ };
1118
+ /**
1119
+ * The link layer under peer-to-peer consumers: one peer connection per remote origin in the
1120
+ * room, set up from relay membership and negotiated over relay `signal` frames. Each link
1121
+ * carries the same labelled channels; frames are opaque strings, what they mean is the
1122
+ * consumer's business.
1087
1123
  *
1088
- * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1089
- * relay-backed session over the same document a peer channel may hand on only envelopes the
1090
- * relay has sequenced, never a peer's own unacknowledged writes.
1124
+ * An origin is one seat: the relay hands a second connection with the same origin the seat
1125
+ * and reports it to the room as a plain join. Links tell seats apart by instance, not by
1126
+ * order: every link announces a random instance id in its signals and, once it knows the
1127
+ * instance across, addresses its signals to it. A signal addressed to an instance this side
1128
+ * no longer has is dropped. An unaddressed signal from an instance other than the one linked
1129
+ * is a new seat or a restarted link, and this side rebuilds its end, addressed; an addressed
1130
+ * one from a new instance is adopted. Only unaddressed signals cause a rebuild and a rebuilt
1131
+ * end never sends one, so a takeover settles in one exchange. Two tabs with the same origin
1132
+ * still take the seat from each other on every reconnect; give each tab its own origin.
1091
1133
  */
1092
- function webRtcMesh(source, opt) {
1134
+ function peerLinks(opt) {
1093
1135
  const injector = opt.injector ?? inject(Injector);
1094
1136
  const connector = opt.connector ?? rtcPeerConnector();
1137
+ const specs = opt.channels?.length ? opt.channels : defaultPeerChannels;
1138
+ const labels = specs.map((c) => c.label);
1139
+ const primary = labels[0];
1095
1140
  const status = signal('connecting', /* @ts-ignore */
1096
1141
  ...(ngDevMode ? [{ debugName: "status" }] : /* istanbul ignore next */ []));
1097
1142
  const openPeers = signal(new Set(), /* @ts-ignore */
1098
1143
  ...(ngDevMode ? [{ debugName: "openPeers" }] : /* istanbul ignore next */ []));
1144
+ const members = signal(new Set(), /* @ts-ignore */
1145
+ ...(ngDevMode ? [{ debugName: "members" }] : /* istanbul ignore next */ []));
1099
1146
  const peers = new Map();
1147
+ const openCbs = new Set();
1148
+ const messageCbs = new Set();
1149
+ const closeCbs = new Set();
1150
+ const endCbs = new Set();
1151
+ const memberCbs = new Set();
1100
1152
  let signalingUnsubs = [];
1101
1153
  let transport = null;
1102
1154
  let reconnectTimer;
1155
+ let connected = false;
1103
1156
  let closed = false;
1104
- const sync = opSync(source, {
1105
- writer: opt.writer,
1106
- policies: opt.policies,
1107
- policyVersion: opt.policyVersion,
1108
- injector,
1109
- });
1110
- const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1111
- const sendTo = (peer, msg) => {
1112
- peer.link.channel.send(JSON.stringify(msg));
1113
- };
1114
- const broadcast = (msg) => {
1115
- for (const peer of peers.values()) {
1116
- if (peer.open)
1117
- sendTo(peer, msg);
1118
- }
1157
+ // links are told apart by instance, never by order: a random tag plus a counter
1158
+ const tag = Math.random().toString(36).slice(2, 10);
1159
+ let linkSeq = 0;
1160
+ const port = typeof opt.signaling === 'function' ? null : opt.signaling;
1161
+ const sendSignal = (msg) => {
1162
+ if (port)
1163
+ port.send(msg);
1164
+ else
1165
+ transport?.send(msg);
1119
1166
  };
1120
1167
  const dropPeer = (origin) => {
1121
1168
  const peer = peers.get(origin);
@@ -1130,75 +1177,149 @@ function webRtcMesh(source, opt) {
1130
1177
  next.delete(origin);
1131
1178
  return next;
1132
1179
  });
1180
+ for (const cb of [...closeCbs])
1181
+ cb(origin);
1133
1182
  };
1134
- const ensurePeer = (origin) => {
1135
- let peer = peers.get(origin);
1136
- if (peer)
1137
- return peer;
1138
- const link = connector({
1139
- remote: origin,
1140
- polite: sync.origin > origin,
1141
- sendSignal: (data) => transport?.send({ t: 'signal', room: opt.room, to: origin, data }),
1142
- });
1143
- peer = { link, open: false, unsubs: [] };
1144
- peers.set(origin, peer);
1145
- peer.unsubs.push(link.channel.onOpen(() => {
1146
- peer.open = true;
1147
- openPeers.update((set) => new Set(set).add(origin));
1148
- sendTo(peer, { t: 'hello', wm: sync.watermark() });
1149
- }), link.channel.onMessage((frame) => {
1150
- let msg;
1151
- try {
1152
- msg = JSON.parse(frame);
1153
- }
1154
- catch {
1183
+ /**
1184
+ * Builds the link to `origin`; `remote` is the instance on the other side when the link is
1185
+ * built in answer to one of its signals, so everything this side sends is addressed to it.
1186
+ */
1187
+ const ensurePeer = (origin, remote) => {
1188
+ const existing = peers.get(origin);
1189
+ if (existing)
1190
+ return existing;
1191
+ const id = `${tag}.${++linkSeq}`;
1192
+ // signals the connector sends while it is still being built wait until the peer is
1193
+ // registered, so the remote's synchronous answer finds it instead of building another
1194
+ let building = [];
1195
+ let retired = false;
1196
+ const signal = (data) => {
1197
+ if (retired)
1155
1198
  return;
1156
- }
1157
- handlePeerMsg(peer, msg);
1158
- }), link.channel.onClose(() => dropPeer(origin)));
1159
- return peer;
1160
- };
1161
- const handlePeerMsg = (peer, msg) => {
1162
- switch (msg.t) {
1163
- case 'hello': {
1164
- const snap = sync.snapshot();
1165
- if (covered(snap.wm, msg.wm))
1166
- sendTo(peer, { t: 'uptodate' });
1167
- else
1168
- sendTo(peer, { t: 'state', state: snap });
1199
+ if (building) {
1200
+ building.push(data);
1169
1201
  return;
1170
1202
  }
1171
- case 'state': {
1172
- if (covered(sync.watermark(), msg.state.wm)) {
1173
- sync.hydrate(msg.state);
1203
+ const stamped = typeof data === 'object' && data !== null
1204
+ ? {
1205
+ ...data,
1206
+ link: id,
1207
+ ...(p.remote === undefined ? {} : { to: p.remote }),
1174
1208
  }
1175
- return;
1209
+ : data;
1210
+ sendSignal({ t: 'signal', room: opt.room, to: origin, data: stamped });
1211
+ };
1212
+ const link = connector({
1213
+ remote: origin,
1214
+ polite: opt.origin > origin,
1215
+ sendSignal: signal,
1216
+ channels: specs,
1217
+ });
1218
+ const p = {
1219
+ id,
1220
+ remote,
1221
+ link,
1222
+ channels: new Map(),
1223
+ unsubs: [() => (retired = true)],
1224
+ };
1225
+ peers.set(origin, p);
1226
+ const early = building;
1227
+ building = null;
1228
+ // announce the instance, so a side that still holds a link to an earlier seat of this
1229
+ // origin (a takeover the relay reports as a plain join) replaces it
1230
+ signal({});
1231
+ for (const data of early)
1232
+ signal(data);
1233
+ for (const label of labels) {
1234
+ const channel = link.channels?.[label] ??
1235
+ (label === primary ? link.channel : undefined);
1236
+ if (!channel) {
1237
+ if (isDevMode()) {
1238
+ console.warn(`[@mmstack/mesh] the peer connector returned no channel labelled '${label}'`);
1239
+ }
1240
+ continue;
1176
1241
  }
1177
- case 'uptodate':
1178
- return;
1179
- case 'env':
1180
- sync.receive(msg.env);
1181
- return;
1242
+ const state = { channel, open: false };
1243
+ p.channels.set(label, state);
1244
+ p.unsubs.push(channel.onOpen(() => {
1245
+ state.open = true;
1246
+ if (labels.every((l) => p.channels.get(l)?.open)) {
1247
+ openPeers.update((set) => new Set(set).add(origin));
1248
+ }
1249
+ for (const cb of [...openCbs])
1250
+ cb(origin, label);
1251
+ }), channel.onMessage((frame) => {
1252
+ for (const cb of [...messageCbs])
1253
+ cb(origin, frame, label);
1254
+ }), channel.onClose(() => dropPeer(origin)));
1182
1255
  }
1256
+ return p;
1257
+ };
1258
+ const setMembers = (origins) => {
1259
+ const next = new Set(origins);
1260
+ members.set(next);
1261
+ for (const cb of [...memberCbs])
1262
+ cb([...next]);
1263
+ };
1264
+ const welcomeMembers = (origins) => {
1265
+ setMembers(origins);
1266
+ for (const origin of [...peers.keys()])
1267
+ if (!members().has(origin))
1268
+ dropPeer(origin);
1269
+ for (const origin of origins)
1270
+ ensurePeer(origin);
1271
+ status.set('live');
1183
1272
  };
1184
1273
  const handleSignaling = (msg) => {
1185
- if (msg.room !== opt.room)
1274
+ if (closed || msg.room !== opt.room)
1186
1275
  return;
1187
1276
  switch (msg.t) {
1188
1277
  case 'welcome':
1189
- for (const origin of msg.members)
1190
- ensurePeer(origin);
1191
- status.set('live');
1278
+ welcomeMembers(msg.members);
1192
1279
  return;
1193
1280
  case 'member':
1281
+ setMembers(msg.gone
1282
+ ? [...members()].filter((origin) => origin !== msg.origin)
1283
+ : [...new Set([...members(), msg.origin])]);
1194
1284
  if (msg.gone)
1195
1285
  dropPeer(msg.origin);
1196
1286
  else
1197
1287
  ensurePeer(msg.origin);
1198
1288
  return;
1199
- case 'signal':
1200
- ensurePeer(msg.from).link.signal(msg.data);
1289
+ case 'signal': {
1290
+ const { link, to, payload } = unwrapSignal(msg.data);
1291
+ let peer = peers.get(msg.from);
1292
+ if (link === undefined) {
1293
+ // an unstamped sender: nothing to tell instances apart by
1294
+ peer ??= ensurePeer(msg.from);
1295
+ }
1296
+ else if (to !== undefined && to !== peer?.id) {
1297
+ // addressed to an instance this side no longer has: a retired link's leftovers
1298
+ return;
1299
+ }
1300
+ else if (!peer) {
1301
+ peer = ensurePeer(msg.from, link);
1302
+ }
1303
+ else if (peer.remote === undefined) {
1304
+ peer.remote = link;
1305
+ }
1306
+ else if (peer.remote !== link) {
1307
+ if (to === undefined) {
1308
+ // a new instance over there that does not know this side yet: a new seat or a
1309
+ // restarted link, so this side rebuilds, addressing it, which is what makes the
1310
+ // rebuild final: the other side never rebuilds in answer to an addressed signal
1311
+ dropPeer(msg.from);
1312
+ peer = ensurePeer(msg.from, link);
1313
+ }
1314
+ else {
1315
+ // built for this very instance, so it is the newer end of this link: adopt it
1316
+ peer.remote = link;
1317
+ }
1318
+ }
1319
+ if (payload !== undefined)
1320
+ peer.link.signal(payload);
1201
1321
  return;
1322
+ }
1202
1323
  case 'reject':
1203
1324
  close();
1204
1325
  return;
@@ -1209,6 +1330,18 @@ function webRtcMesh(source, opt) {
1209
1330
  return;
1210
1331
  for (const unsub of signalingUnsubs.splice(0))
1211
1332
  unsub();
1333
+ if (port) {
1334
+ const unsub = port.onMessage(handleSignaling);
1335
+ if (closed) {
1336
+ unsub();
1337
+ return;
1338
+ }
1339
+ signalingUnsubs = [unsub];
1340
+ const current = port.members();
1341
+ if (current !== undefined)
1342
+ welcomeMembers(current);
1343
+ return;
1344
+ }
1212
1345
  const t = opt.signaling();
1213
1346
  transport = t;
1214
1347
  signalingUnsubs = [
@@ -1217,39 +1350,337 @@ function webRtcMesh(source, opt) {
1217
1350
  if (closed || transport !== t)
1218
1351
  return;
1219
1352
  transport = null;
1353
+ status.set('connecting');
1220
1354
  reconnectTimer = setTimeout(connectSignaling, 1000);
1221
1355
  }),
1222
1356
  ];
1223
1357
  t.send({
1224
1358
  t: 'hello',
1225
1359
  room: opt.room,
1226
- origin: sync.origin,
1360
+ origin: opt.origin,
1227
1361
  proto: MESH_PROTO_VERSION,
1228
1362
  policyVersion: opt.policyVersion ?? 0,
1229
1363
  });
1230
1364
  };
1231
- const unsubLocal = sync.subscribe((env) => broadcast({ t: 'env', env }));
1365
+ const connect = () => {
1366
+ if (connected || closed)
1367
+ return;
1368
+ connected = true;
1369
+ connectSignaling();
1370
+ };
1232
1371
  const close = () => {
1233
1372
  if (closed)
1234
1373
  return;
1235
1374
  closed = true;
1236
1375
  if (reconnectTimer !== undefined)
1237
1376
  clearTimeout(reconnectTimer);
1238
- unsubLocal();
1239
1377
  for (const origin of [...peers.keys()])
1240
1378
  dropPeer(origin);
1241
1379
  for (const unsub of signalingUnsubs.splice(0))
1242
1380
  unsub();
1243
1381
  transport?.close();
1244
1382
  transport = null;
1245
- sync.destroy();
1383
+ setMembers([]);
1384
+ memberCbs.clear();
1246
1385
  status.set('connecting');
1386
+ for (const cb of [...endCbs])
1387
+ cb();
1388
+ endCbs.clear();
1389
+ };
1390
+ const openChannel = (origin, label) => {
1391
+ const state = peers.get(origin)?.channels.get(label);
1392
+ return state?.open ? state.channel : null;
1247
1393
  };
1248
1394
  injector.get(DestroyRef).onDestroy(close);
1249
- connectSignaling();
1395
+ if (opt.autoConnect !== false)
1396
+ connect();
1250
1397
  return {
1251
1398
  status: status.asReadonly(),
1252
1399
  peers: computed(() => [...openPeers()]),
1400
+ members: computed(() => [...members()]),
1401
+ onMembers: (cb) => {
1402
+ if (!closed)
1403
+ memberCbs.add(cb);
1404
+ cb([...members()]);
1405
+ return () => memberCbs.delete(cb);
1406
+ },
1407
+ channels: labels,
1408
+ onOpen: (cb) => {
1409
+ openCbs.add(cb);
1410
+ for (const [origin, peer] of peers) {
1411
+ for (const [label, state] of peer.channels) {
1412
+ if (state.open)
1413
+ cb(origin, label);
1414
+ }
1415
+ }
1416
+ return () => openCbs.delete(cb);
1417
+ },
1418
+ onMessage: (cb) => (messageCbs.add(cb), () => messageCbs.delete(cb)),
1419
+ onClose: (cb) => (closeCbs.add(cb), () => closeCbs.delete(cb)),
1420
+ onEnd: (cb) => (endCbs.add(cb), () => endCbs.delete(cb)),
1421
+ send: (origin, frame, channel = primary) => {
1422
+ openChannel(origin, channel)?.send(frame);
1423
+ },
1424
+ broadcast: (frame, channel = primary) => {
1425
+ for (const origin of peers.keys())
1426
+ openChannel(origin, channel)?.send(frame);
1427
+ },
1428
+ connect,
1429
+ close,
1430
+ };
1431
+ }
1432
+
1433
+ /**
1434
+ * Peer-to-peer mesh sync: the relay only signals
1435
+ * and tracks membership; envelopes flow over WebRTC data channels and converge via the
1436
+ * per-path register map. Catch-up is pairwise: on channel open both sides exchange
1437
+ * watermarks; a side whose state is strictly covered hydrates from the other's FULL
1438
+ * checkpoint (root + per-path register state + watermark), so supersession and precedence
1439
+ * carry over intact: a late joiner is indistinguishable from a peer that saw every
1440
+ * envelope. Two peers that each hold envelopes the other lacks keep their convergent
1441
+ * go-forward guarantees but do not exchange the missed envelopes retroactively.
1442
+ *
1443
+ * There is no relay admission here: no sequence, no generation, no refusals. Beside a
1444
+ * relay-backed session over the same document a peer channel may hand on only envelopes the
1445
+ * relay has sequenced, never a peer's own unacknowledged writes.
1446
+ */
1447
+ function webRtcMesh(source, opt) {
1448
+ const injector = opt.injector ?? inject(Injector);
1449
+ const meshChannel = defaultPeerChannels[0];
1450
+ let closed = false;
1451
+ const sync = opSync(source, {
1452
+ writer: opt.writer,
1453
+ origin: opt.origin,
1454
+ policies: opt.policies,
1455
+ policyVersion: opt.policyVersion,
1456
+ injector,
1457
+ });
1458
+ // subscribe before signaling starts: a link can open, and its first frame arrive, while
1459
+ // the hello is still being answered
1460
+ const links = peerLinks({
1461
+ room: opt.room,
1462
+ origin: sync.origin,
1463
+ signaling: opt.signaling,
1464
+ connector: opt.connector,
1465
+ channels: [
1466
+ meshChannel,
1467
+ ...(opt.channels ?? []).filter((c) => c.label !== meshChannel.label),
1468
+ ],
1469
+ policyVersion: opt.policyVersion,
1470
+ autoConnect: false,
1471
+ injector,
1472
+ });
1473
+ const covered = (mine, theirs) => Object.entries(mine).every(([o, v]) => (theirs[o] ?? 0) >= v);
1474
+ const sendTo = (origin, msg) => {
1475
+ links.send(origin, JSON.stringify(msg));
1476
+ };
1477
+ const handlePeerMsg = (origin, msg) => {
1478
+ switch (msg.t) {
1479
+ case 'hello': {
1480
+ const snap = sync.snapshot();
1481
+ if (covered(snap.wm, msg.wm))
1482
+ sendTo(origin, { t: 'uptodate' });
1483
+ else
1484
+ sendTo(origin, { t: 'state', state: snap });
1485
+ return;
1486
+ }
1487
+ case 'state': {
1488
+ if (covered(sync.watermark(), msg.state.wm)) {
1489
+ sync.hydrate(msg.state);
1490
+ }
1491
+ return;
1492
+ }
1493
+ case 'uptodate':
1494
+ return;
1495
+ case 'env':
1496
+ sync.receive(msg.env);
1497
+ return;
1498
+ }
1499
+ };
1500
+ links.onOpen((origin, channel) => {
1501
+ if (channel === meshChannel.label)
1502
+ sendTo(origin, { t: 'hello', wm: sync.watermark() });
1503
+ });
1504
+ links.onMessage((origin, frame, channel) => {
1505
+ if (channel !== meshChannel.label)
1506
+ return;
1507
+ let msg;
1508
+ try {
1509
+ msg = JSON.parse(frame);
1510
+ }
1511
+ catch {
1512
+ return;
1513
+ }
1514
+ handlePeerMsg(origin, msg);
1515
+ });
1516
+ const unsubLocal = sync.subscribe((env) => links.broadcast(JSON.stringify({ t: 'env', env })));
1517
+ const close = () => {
1518
+ if (closed)
1519
+ return;
1520
+ closed = true;
1521
+ unsubLocal();
1522
+ links.close();
1523
+ sync.destroy();
1524
+ };
1525
+ // a relay reject ends the links; the mesh ends with them
1526
+ links.onEnd(close);
1527
+ links.connect();
1528
+ return {
1529
+ origin: sync.origin,
1530
+ status: links.status,
1531
+ peers: links.peers,
1532
+ links,
1533
+ close,
1534
+ };
1535
+ }
1536
+
1537
+ /**
1538
+ * The channel `rtcPresence` uses by default. Lossy and unordered on purpose: a pointer that
1539
+ * waits for a retransmit is already stale, and ordering would hold newer frames behind it.
1540
+ * Put it in the `channels` of the {@link PeerLinks} the presence rides on.
1541
+ */
1542
+ const presenceChannel = {
1543
+ label: 'mmstack-presence',
1544
+ ordered: false,
1545
+ maxRetransmits: 0,
1546
+ };
1547
+ const none = Symbol('none');
1548
+ // one send counter per links object and channel, shared by every sender created on them
1549
+ const counters = new WeakMap();
1550
+ const counterOf = (links, label) => {
1551
+ let byLabel = counters.get(links);
1552
+ if (!byLabel)
1553
+ counters.set(links, (byLabel = new Map()));
1554
+ let counter = byLabel.get(label);
1555
+ if (!counter)
1556
+ byLabel.set(label, (counter = { seq: 0 }));
1557
+ return counter;
1558
+ };
1559
+ const isNum = (x) => typeof x === 'number' && Number.isFinite(x);
1560
+ /**
1561
+ * Ephemeral per-peer values (pointers, viewports) over peer links: last value per sender, no
1562
+ * ordering, no retransmits, no catch-up and no persistence. A new link sees nothing until the
1563
+ * sender's next `set`.
1564
+ *
1565
+ * Order comes from causality the receiver observes, never from clocks or from numbers chosen
1566
+ * by different senders. A value is held only for an origin in the roster, and it is removed
1567
+ * as soon as the origin leaves. Within one link the highest `seq` wins and anything at or
1568
+ * below it is dropped: one counter stamps every frame sent on that link in send order, so a
1569
+ * lower `seq` was sent earlier. A link that opens or closes starts its origin fresh, and a
1570
+ * frame of an old link cannot arrive on a new one. An origin that leaves and comes back
1571
+ * starts fresh. Every roster transition is consumed synchronously, even if no frame arrives
1572
+ * and nobody reads `peers` between leave and rejoin.
1573
+ *
1574
+ * The counter belongs to the links and the channel, not to this sender, so a sender closed
1575
+ * and recreated on the same links carries on where the last one stopped and is heard at
1576
+ * once. A new tab or device is a new link, which every receiver already treats as fresh.
1577
+ *
1578
+ * Values travel as JSON.
1579
+ */
1580
+ function rtcPresence(links, opt) {
1581
+ const injector = opt.injector ?? inject(Injector);
1582
+ const label = opt.channel ?? presenceChannel.label;
1583
+ if (!links.channels.includes(label)) {
1584
+ throw new Error(`[@mmstack/mesh] rtcPresence needs a '${label}' channel on its peer links`);
1585
+ }
1586
+ const held = new Map();
1587
+ const version = signal(0, /* @ts-ignore */
1588
+ ...(ngDevMode ? [{ debugName: "version" }] : /* istanbul ignore next */ []));
1589
+ const counter = counterOf(links, label);
1590
+ let closed = false;
1591
+ let roster = new Set();
1592
+ const forget = (origin) => {
1593
+ if (held.delete(origin))
1594
+ version.update((v) => v + 1);
1595
+ };
1596
+ const receive = (origin, frame) => {
1597
+ if (closed)
1598
+ return;
1599
+ let msg;
1600
+ try {
1601
+ msg = JSON.parse(frame);
1602
+ }
1603
+ catch {
1604
+ return;
1605
+ }
1606
+ if (typeof msg !== 'object' ||
1607
+ msg === null ||
1608
+ !isNum(msg.seq) ||
1609
+ !('value' in msg)) {
1610
+ return;
1611
+ }
1612
+ if (!roster.has(origin))
1613
+ return;
1614
+ const prev = held.get(origin);
1615
+ if (prev && msg.seq <= prev.seq)
1616
+ return;
1617
+ held.set(origin, { seq: msg.seq, value: msg.value });
1618
+ version.update((v) => v + 1);
1619
+ };
1620
+ const unsubs = [
1621
+ opt.roster((members) => {
1622
+ roster = new Set(members);
1623
+ for (const origin of held.keys())
1624
+ if (!roster.has(origin))
1625
+ forget(origin);
1626
+ }),
1627
+ links.onMessage((origin, frame, channel) => {
1628
+ if (channel === label)
1629
+ receive(origin, frame);
1630
+ }),
1631
+ // the link is the epoch: a new or lost link starts the origin fresh
1632
+ links.onOpen((origin, channel) => {
1633
+ if (channel === label)
1634
+ forget(origin);
1635
+ }),
1636
+ links.onClose(forget),
1637
+ links.onEnd(() => close()),
1638
+ ];
1639
+ const peers = computed(() => {
1640
+ version();
1641
+ if (closed)
1642
+ return new Map();
1643
+ const out = new Map();
1644
+ for (const [origin, entry] of held) {
1645
+ if (roster.has(origin))
1646
+ out.set(origin, entry.value);
1647
+ }
1648
+ return out;
1649
+ }, /* @ts-ignore */
1650
+ ...(ngDevMode ? [{ debugName: "peers" }] : /* istanbul ignore next */ []));
1651
+ const destroyRef = injector.get(DestroyRef);
1652
+ const outgoing = throttled(none, {
1653
+ ms: opt.throttleMs ?? 33,
1654
+ leading: true,
1655
+ trailing: true,
1656
+ destroyRef,
1657
+ });
1658
+ const publisher = effect(() => {
1659
+ const value = outgoing();
1660
+ if (value === none || closed)
1661
+ return;
1662
+ untracked(() => links.broadcast(JSON.stringify({
1663
+ seq: counter.seq++,
1664
+ value,
1665
+ }), label));
1666
+ }, { ...(ngDevMode ? { debugName: "publisher" } : /* istanbul ignore next */ {}), injector });
1667
+ const close = () => {
1668
+ if (closed)
1669
+ return;
1670
+ closed = true;
1671
+ publisher.destroy();
1672
+ for (const unsub of unsubs.splice(0))
1673
+ unsub();
1674
+ held.clear();
1675
+ version.update((v) => v + 1);
1676
+ };
1677
+ destroyRef.onDestroy(close);
1678
+ return {
1679
+ set: (value) => {
1680
+ if (!closed)
1681
+ outgoing.set(value);
1682
+ },
1683
+ peers,
1253
1684
  close,
1254
1685
  };
1255
1686
  }
@@ -1258,5 +1689,5 @@ function webRtcMesh(source, opt) {
1258
1689
  * Generated bundle index. Do not edit.
1259
1690
  */
1260
1691
 
1261
- export { agentSeat, describeOp, directTransport, meshSync, rtcPeerConnector, setAtPath, webRtcMesh, webSocketTransport };
1692
+ export { agentSeat, defaultPeerChannels, describeOp, directTransport, meshSync, peerLinks, presenceChannel, rtcPeerConnector, rtcPresence, setAtPath, webRtcMesh, webSocketTransport };
1262
1693
  //# sourceMappingURL=mmstack-mesh.mjs.map