@johnhenry/browsermesh-discovery 0.0.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.
@@ -0,0 +1,1584 @@
1
+ import { silentCatch } from './silent-catch.mjs'
2
+ /**
3
+ * clawser-mesh-discovery.js -- Peer discovery and service directory for BrowserMesh.
4
+ *
5
+ * Provides multi-strategy peer discovery (BroadcastChannel, relay, manual) and
6
+ * a local service directory with svc:// URI routing for the mesh network.
7
+ *
8
+ * DiscoveryRecord represents a discovered peer with TTL-based expiration.
9
+ * DiscoveryStrategy is the abstract base for pluggable discovery backends.
10
+ * BroadcastChannelStrategy discovers peers in same-origin tabs via BroadcastChannel.
11
+ * RelayStrategy discovers peers via a relay/signaling server.
12
+ * ManualStrategy allows explicit peer addition and removal.
13
+ * DiscoveryManager orchestrates multiple strategies with periodic announce/prune.
14
+ * ServiceEndpoint describes a svc:// service offered by a pod.
15
+ * ServiceDirectory manages local and remote service registrations with URI lookup.
16
+ *
17
+ * No browser-only imports at module level.
18
+ *
19
+ * Run tests:
20
+ * node --import ./web/test/_setup-globals.mjs --test web/test/clawser-mesh-discovery.test.mjs
21
+ */
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Wire Constants
25
+ // ---------------------------------------------------------------------------
26
+
27
+ /** Discovery announcement message type. */
28
+ export const DISCOVERY_ANNOUNCE = 0xC0;
29
+
30
+ /** Discovery query message type. */
31
+ export const DISCOVERY_QUERY = 0xC1;
32
+
33
+ /** Discovery response message type. */
34
+ export const DISCOVERY_RESPONSE = 0xC2;
35
+
36
+ /** Discovery goodbye (peer departure) message type. */
37
+ export const DISCOVERY_GOODBYE = 0xC3;
38
+
39
+ /** Service registration message type. */
40
+ export const SVC_REGISTER = 0xC4;
41
+
42
+ /** Service lookup message type. */
43
+ export const SVC_LOOKUP = 0xC5;
44
+
45
+ /** SharedWorker relay register message type. */
46
+ export const RELAY_REGISTER = 0x96;
47
+
48
+ /** SharedWorker relay query message type. */
49
+ export const RELAY_QUERY = 0x97;
50
+
51
+ // ---------------------------------------------------------------------------
52
+ // PEER_TYPE — taxonomy
53
+ // ---------------------------------------------------------------------------
54
+
55
+ /**
56
+ * Canonical peer type taxonomy.
57
+ *
58
+ * - `chat` — Standard agent peer offering conversational chat.
59
+ * - `runtime` — Hosts a remote-runtime endpoint (wsh server, exec
60
+ * capable). Routing prefers these for code/file ops.
61
+ * - `host-shell` — A fixed host shell (e.g. browser tab acting as a
62
+ * stationary backplane); accepts inbound `wsh` sessions.
63
+ * - `vm-compute` — VM-backed compute peer (v86/WebVM); routing target for
64
+ * long-running compute jobs that need a real OS.
65
+ * - `unknown` — Default for older peers without a `peerType` field.
66
+ *
67
+ * @readonly
68
+ */
69
+ export const PEER_TYPE = Object.freeze({
70
+ CHAT: 'chat',
71
+ RUNTIME: 'runtime',
72
+ HOST_SHELL: 'host-shell',
73
+ VM_COMPUTE: 'vm-compute',
74
+ UNKNOWN: 'unknown',
75
+ });
76
+
77
+ /** @type {ReadonlySet<string>} Valid peer-type values. */
78
+ export const PEER_TYPES = new Set(Object.values(PEER_TYPE));
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // DiscoveryRecord
82
+ // ---------------------------------------------------------------------------
83
+
84
+ /**
85
+ * Represents a discovered peer in the mesh network.
86
+ */
87
+ export class DiscoveryRecord {
88
+ /**
89
+ * @param {object} opts
90
+ * @param {string} opts.podId - Unique pod identifier
91
+ * @param {string} [opts.label] - Human-readable label
92
+ * @param {string} [opts.endpoint] - Connection endpoint (URL)
93
+ * @param {string} [opts.transport] - Transport protocol name
94
+ * @param {string[]} [opts.capabilities] - List of capability tags
95
+ * @param {object} [opts.metadata] - Arbitrary metadata
96
+ * @param {number} [opts.ttl] - Time-to-live in ms (default 30000)
97
+ * @param {number} [opts.discoveredAt] - Timestamp when discovered
98
+ * @param {string} [opts.source] - Discovery source strategy type
99
+ * @param {string} [opts.peerType] - Canonical peer type (see PEER_TYPE).
100
+ * Unknown values are accepted but normalised to `'unknown'` to keep the
101
+ * wire format forward-compatible with future taxonomies.
102
+ */
103
+ constructor({
104
+ podId,
105
+ label = null,
106
+ endpoint = null,
107
+ transport = null,
108
+ capabilities = [],
109
+ metadata = {},
110
+ ttl = 30_000,
111
+ discoveredAt,
112
+ source = null,
113
+ peerType = PEER_TYPE.UNKNOWN,
114
+ }) {
115
+ if (!podId || typeof podId !== 'string') {
116
+ throw new Error('podId is required and must be a non-empty string');
117
+ }
118
+ this.podId = podId;
119
+ this.label = label;
120
+ this.endpoint = endpoint;
121
+ this.transport = transport;
122
+ this.capabilities = [...capabilities];
123
+ this.metadata = { ...metadata };
124
+ this.ttl = ttl;
125
+ this.discoveredAt = discoveredAt ?? Date.now();
126
+ this.source = source;
127
+ this.peerType = PEER_TYPES.has(peerType) ? peerType : PEER_TYPE.UNKNOWN;
128
+ }
129
+
130
+ /**
131
+ * Check whether this record has expired.
132
+ *
133
+ * @param {number} [now=Date.now()] - Current timestamp in ms
134
+ * @returns {boolean}
135
+ */
136
+ isExpired(now = Date.now()) {
137
+ return now >= this.discoveredAt + this.ttl;
138
+ }
139
+
140
+ /**
141
+ * Check whether this record matches a filter.
142
+ *
143
+ * @param {object} [filter]
144
+ * @param {string[]} [filter.capabilities] - Required capabilities
145
+ * @param {string|string[]} [filter.peerType] - Required peer type(s)
146
+ * @returns {boolean}
147
+ */
148
+ matchesFilter(filter) {
149
+ if (!filter) return true;
150
+ if (filter.capabilities) {
151
+ for (const cap of filter.capabilities) {
152
+ if (!this.capabilities.includes(cap)) return false;
153
+ }
154
+ }
155
+ if (filter.peerType) {
156
+ const allowed = Array.isArray(filter.peerType) ? filter.peerType : [filter.peerType];
157
+ if (!allowed.includes(this.peerType)) return false;
158
+ }
159
+ return true;
160
+ }
161
+
162
+ /**
163
+ * Serialize to a JSON-safe object.
164
+ * @returns {object}
165
+ */
166
+ toJSON() {
167
+ return {
168
+ podId: this.podId,
169
+ label: this.label,
170
+ endpoint: this.endpoint,
171
+ transport: this.transport,
172
+ capabilities: [...this.capabilities],
173
+ metadata: { ...this.metadata },
174
+ ttl: this.ttl,
175
+ discoveredAt: this.discoveredAt,
176
+ source: this.source,
177
+ peerType: this.peerType,
178
+ };
179
+ }
180
+
181
+ /**
182
+ * Re-hydrate from a plain object.
183
+ * @param {object} data
184
+ * @returns {DiscoveryRecord}
185
+ */
186
+ static fromJSON(data) {
187
+ return new DiscoveryRecord(data);
188
+ }
189
+ }
190
+
191
+ // ---------------------------------------------------------------------------
192
+ // DiscoveryStrategy (abstract base)
193
+ // ---------------------------------------------------------------------------
194
+
195
+ /**
196
+ * Abstract base class for discovery backends.
197
+ * Subclasses must implement start(), stop(), announce(), and query().
198
+ */
199
+ export class DiscoveryStrategy {
200
+ /** @type {string} */
201
+ #type;
202
+
203
+ /** @type {boolean} */
204
+ #active = false;
205
+
206
+ /** @type {Function[]} */
207
+ #discoveredCallbacks = [];
208
+
209
+ /**
210
+ * @param {object} opts
211
+ * @param {string} opts.type - Strategy type identifier (e.g., 'broadcast', 'relay', 'manual')
212
+ */
213
+ constructor({ type }) {
214
+ if (!type || typeof type !== 'string') {
215
+ throw new Error('type is required and must be a non-empty string');
216
+ }
217
+ this.#type = type;
218
+ }
219
+
220
+ /** @returns {string} Strategy type identifier */
221
+ get type() {
222
+ return this.#type;
223
+ }
224
+
225
+ /** @returns {boolean} Whether the strategy is currently active */
226
+ get active() {
227
+ return this.#active;
228
+ }
229
+
230
+ /** @param {boolean} value */
231
+ set _active(value) {
232
+ this.#active = value;
233
+ }
234
+
235
+ /**
236
+ * Register a callback for when a peer is discovered.
237
+ * @param {Function} cb - Callback receiving a DiscoveryRecord
238
+ */
239
+ onDiscovered(cb) {
240
+ this.#discoveredCallbacks.push(cb);
241
+ }
242
+
243
+ /**
244
+ * Fire all discovered callbacks.
245
+ * @param {DiscoveryRecord} record
246
+ * @protected
247
+ */
248
+ _fireDiscovered(record) {
249
+ for (const cb of this.#discoveredCallbacks) {
250
+ cb(record);
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Start the discovery strategy.
256
+ * @abstract
257
+ * @returns {Promise<void>}
258
+ */
259
+ async start() {
260
+ throw new Error('start() must be implemented by subclass');
261
+ }
262
+
263
+ /**
264
+ * Stop the discovery strategy.
265
+ * @abstract
266
+ * @returns {Promise<void>}
267
+ */
268
+ async stop() {
269
+ throw new Error('stop() must be implemented by subclass');
270
+ }
271
+
272
+ /**
273
+ * Announce a local record to peers.
274
+ * @abstract
275
+ * @param {DiscoveryRecord} record
276
+ * @returns {Promise<void>}
277
+ */
278
+ async announce(record) {
279
+ throw new Error('announce() must be implemented by subclass');
280
+ }
281
+
282
+ /**
283
+ * Query for discovered peers, optionally filtered.
284
+ * @abstract
285
+ * @param {object} [filter]
286
+ * @returns {Promise<DiscoveryRecord[]>}
287
+ */
288
+ async query(filter) {
289
+ throw new Error('query() must be implemented by subclass');
290
+ }
291
+ }
292
+
293
+ // ---------------------------------------------------------------------------
294
+ // BroadcastChannelStrategy
295
+ // ---------------------------------------------------------------------------
296
+
297
+ /**
298
+ * Discovers peers in same-origin browser tabs using BroadcastChannel.
299
+ */
300
+ export class BroadcastChannelStrategy extends DiscoveryStrategy {
301
+ /** @type {string} */
302
+ #channelName;
303
+
304
+ /** @type {BroadcastChannel|null} */
305
+ #channel = null;
306
+
307
+ /** @type {Map<string, DiscoveryRecord>} */
308
+ #peers = new Map();
309
+
310
+ /**
311
+ * @param {object} [opts]
312
+ * @param {string} [opts.channelName='mesh-discovery'] - BroadcastChannel name
313
+ */
314
+ constructor({ channelName = 'mesh-discovery' } = {}) {
315
+ super({ type: 'broadcast' });
316
+ this.#channelName = channelName;
317
+ }
318
+
319
+ /**
320
+ * Start listening on the BroadcastChannel.
321
+ * @returns {Promise<void>}
322
+ */
323
+ async start() {
324
+ if (this.active) return;
325
+ this.#channel = new BroadcastChannel(this.#channelName);
326
+ this.#channel.onmessage = (event) => {
327
+ this.#handleMessage(event.data);
328
+ };
329
+ this._active = true;
330
+ }
331
+
332
+ /**
333
+ * Stop listening and close the channel.
334
+ * @returns {Promise<void>}
335
+ */
336
+ async stop() {
337
+ if (!this.active) return;
338
+ if (this.#channel) {
339
+ this.#channel.close();
340
+ this.#channel = null;
341
+ }
342
+ this._active = false;
343
+ }
344
+
345
+ /**
346
+ * Announce a record to all tabs on the same BroadcastChannel.
347
+ * @param {DiscoveryRecord} record
348
+ * @returns {Promise<void>}
349
+ */
350
+ async announce(record) {
351
+ if (this.#channel) {
352
+ this.#channel.postMessage({
353
+ type: DISCOVERY_ANNOUNCE,
354
+ record: record.toJSON(),
355
+ });
356
+ }
357
+ }
358
+
359
+ /**
360
+ * Query for peers discovered via BroadcastChannel.
361
+ * Posts a query and returns currently known peers.
362
+ *
363
+ * @param {object} [filter]
364
+ * @returns {Promise<DiscoveryRecord[]>}
365
+ */
366
+ async query(filter) {
367
+ if (this.#channel) {
368
+ this.#channel.postMessage({ type: DISCOVERY_QUERY, filter });
369
+ }
370
+ const results = [];
371
+ for (const record of this.#peers.values()) {
372
+ if (!record.isExpired() && record.matchesFilter(filter)) {
373
+ results.push(record);
374
+ }
375
+ }
376
+ return results;
377
+ }
378
+
379
+ /**
380
+ * Handle an incoming BroadcastChannel message.
381
+ * @param {object} data
382
+ * @private
383
+ */
384
+ #handleMessage(data) {
385
+ if (!data || typeof data !== 'object') return;
386
+
387
+ if (data.type === DISCOVERY_ANNOUNCE && data.record) {
388
+ const record = DiscoveryRecord.fromJSON(data.record);
389
+ record.source = 'broadcast';
390
+ this.#peers.set(record.podId, record);
391
+ this._fireDiscovered(record);
392
+ } else if (data.type === DISCOVERY_RESPONSE && data.record) {
393
+ const record = DiscoveryRecord.fromJSON(data.record);
394
+ record.source = 'broadcast';
395
+ this.#peers.set(record.podId, record);
396
+ this._fireDiscovered(record);
397
+ } else if (data.type === DISCOVERY_GOODBYE && data.podId) {
398
+ this.#peers.delete(data.podId);
399
+ }
400
+ }
401
+ }
402
+
403
+ // ---------------------------------------------------------------------------
404
+ // RelayStrategy
405
+ // ---------------------------------------------------------------------------
406
+
407
+ /**
408
+ * Discovers peers via a relay/signaling server.
409
+ */
410
+ export class RelayStrategy extends DiscoveryStrategy {
411
+ /** @type {string} */
412
+ #relayUrl;
413
+
414
+ /** @type {string} */
415
+ #podId;
416
+
417
+ /** @type {Map<string, DiscoveryRecord>} */
418
+ #peers = new Map();
419
+
420
+ /** @type {Function|null} */
421
+ #signFn;
422
+
423
+ /**
424
+ * @param {object} opts
425
+ * @param {string} opts.relayUrl - URL of the relay/signaling server
426
+ * @param {string} opts.podId - Local pod identifier for registration
427
+ * @param {Function} [opts.signFn] - Optional async (podId) => { pubKey, signature }
428
+ */
429
+ constructor({ relayUrl, podId, signFn }) {
430
+ super({ type: 'relay' });
431
+ if (!relayUrl || typeof relayUrl !== 'string') {
432
+ throw new Error('relayUrl is required and must be a non-empty string');
433
+ }
434
+ if (!podId || typeof podId !== 'string') {
435
+ throw new Error('podId is required and must be a non-empty string');
436
+ }
437
+ this.#relayUrl = relayUrl;
438
+ this.#podId = podId;
439
+ this.#signFn = signFn ?? null;
440
+ }
441
+
442
+ /** @type {WebSocket|null} */
443
+ #ws = null;
444
+
445
+ /** @type {number|null} */
446
+ #reconnectTimer = null;
447
+
448
+ /**
449
+ * Connect to the relay/signaling server and start listening for peers.
450
+ * Automatically reconnects on disconnect while active.
451
+ * @returns {Promise<void>}
452
+ */
453
+ async start() {
454
+ if (this.active) return;
455
+ this._active = true;
456
+ await this.#connect();
457
+ }
458
+
459
+ /**
460
+ * Close the WebSocket and stop listening.
461
+ * @returns {Promise<void>}
462
+ */
463
+ async stop() {
464
+ if (!this.active) return;
465
+ this._active = false;
466
+ clearTimeout(this.#reconnectTimer);
467
+ this.#reconnectTimer = null;
468
+ if (this.#ws) {
469
+ this.#ws.onclose = null; // prevent reconnect
470
+ this.#ws.close(1000, 'strategy stopped');
471
+ this.#ws = null;
472
+ }
473
+ this.#peers.clear();
474
+ }
475
+
476
+ /**
477
+ * Announce a discovery record to the relay server.
478
+ * The signaling server broadcasts our presence to other peers on registration,
479
+ * so this sends a lightweight announce if the connection is open.
480
+ * @param {DiscoveryRecord} record
481
+ * @returns {Promise<void>}
482
+ */
483
+ async announce(record) {
484
+ if (this.#ws && this.#ws.readyState === 1) {
485
+ this.#ws.send(JSON.stringify({
486
+ type: 'signal',
487
+ target: '__broadcast__',
488
+ data: { type: 'discovery-announce', record: record.toJSON?.() ?? record },
489
+ }));
490
+ }
491
+ }
492
+
493
+ /**
494
+ * Query cached peers matching an optional filter.
495
+ * @param {object} [filter]
496
+ * @returns {Promise<DiscoveryRecord[]>}
497
+ */
498
+ async query(filter) {
499
+ const results = [];
500
+ for (const record of this.#peers.values()) {
501
+ if (!record.isExpired() && record.matchesFilter(filter)) {
502
+ results.push(record);
503
+ }
504
+ }
505
+ return results;
506
+ }
507
+
508
+ // ── Internal ──────────────────────────────────────────────────────
509
+
510
+ /** Open WebSocket, register, and wire message handlers. */
511
+ async #connect() {
512
+ if (!this.active) return;
513
+
514
+ try {
515
+ const WS = globalThis.WebSocket;
516
+ if (!WS) throw new Error('WebSocket not available');
517
+ const ws = new WS(this.#relayUrl);
518
+ this.#ws = ws;
519
+
520
+ await new Promise((resolve, reject) => {
521
+ ws.onopen = async () => {
522
+ try {
523
+ const regMsg = { type: 'register', podId: this.#podId };
524
+ if (this.#signFn) {
525
+ const { pubKey, signature } = await this.#signFn(this.#podId);
526
+ regMsg.pubKey = pubKey;
527
+ regMsg.signature = signature;
528
+ }
529
+ ws.send(JSON.stringify(regMsg));
530
+ resolve();
531
+ } catch (err) {
532
+ reject(err);
533
+ }
534
+ };
535
+ ws.onerror = () => reject(new Error('WebSocket connection failed'));
536
+ setTimeout(() => reject(new Error('WebSocket connection timeout')), 10000);
537
+ });
538
+
539
+ ws.onmessage = (event) => {
540
+ try {
541
+ const msg = JSON.parse(event.data);
542
+ this.#handleMessage(msg);
543
+ } catch (e) { silentCatch('clawser-mesh-discovery', 'ignore-malformed', e) }
544
+ };
545
+
546
+ ws.onclose = () => {
547
+ this.#ws = null;
548
+ // Auto-reconnect after 3s if still active
549
+ if (this.active) {
550
+ this.#reconnectTimer = setTimeout(() => this.#connect(), 3000);
551
+ }
552
+ };
553
+ } catch {
554
+ // Retry after 5s on connection failure
555
+ if (this.active) {
556
+ this.#reconnectTimer = setTimeout(() => this.#connect(), 5000);
557
+ }
558
+ }
559
+ }
560
+
561
+ /** Handle incoming signaling messages and fire discovery callbacks. */
562
+ #handleMessage(msg) {
563
+ if (msg.type === 'peers') {
564
+ // Full peer list from server — sync our cache
565
+ for (const podId of msg.peers) {
566
+ if (podId === this.#podId) continue;
567
+ if (!this.#peers.has(podId)) {
568
+ const record = new DiscoveryRecord({
569
+ podId,
570
+ label: podId.slice(0, 8),
571
+ transport: 'relay',
572
+ source: 'relay',
573
+ });
574
+ this.#peers.set(podId, record);
575
+ this._fireDiscovered(record);
576
+ }
577
+ }
578
+ }
579
+
580
+ if (msg.type === 'peer-joined') {
581
+ const { podId } = msg;
582
+ if (podId && podId !== this.#podId && !this.#peers.has(podId)) {
583
+ const record = new DiscoveryRecord({
584
+ podId,
585
+ label: podId.slice(0, 8),
586
+ transport: 'relay',
587
+ source: 'relay',
588
+ });
589
+ this.#peers.set(podId, record);
590
+ this._fireDiscovered(record);
591
+ }
592
+ }
593
+
594
+ if (msg.type === 'peer-left') {
595
+ this.#peers.delete(msg.podId);
596
+ }
597
+ }
598
+ }
599
+
600
+ // ---------------------------------------------------------------------------
601
+ // ManualStrategy
602
+ // ---------------------------------------------------------------------------
603
+
604
+ /**
605
+ * Allows explicit manual peer addition and removal.
606
+ */
607
+ export class ManualStrategy extends DiscoveryStrategy {
608
+ /** @type {Map<string, DiscoveryRecord>} */
609
+ #peers = new Map();
610
+
611
+ /**
612
+ * @param {object} [opts]
613
+ */
614
+ constructor(opts = {}) {
615
+ super({ type: 'manual' });
616
+ }
617
+
618
+ /**
619
+ * Start the manual strategy (no-op but marks active).
620
+ * @returns {Promise<void>}
621
+ */
622
+ async start() {
623
+ this._active = true;
624
+ }
625
+
626
+ /**
627
+ * Stop the manual strategy.
628
+ * @returns {Promise<void>}
629
+ */
630
+ async stop() {
631
+ this._active = false;
632
+ }
633
+
634
+ /**
635
+ * Announce is a no-op for manual strategy.
636
+ * @param {DiscoveryRecord} record
637
+ * @returns {Promise<void>}
638
+ */
639
+ async announce(record) {
640
+ // No-op for manual strategy
641
+ }
642
+
643
+ /**
644
+ * Add a peer record manually.
645
+ * @param {DiscoveryRecord} record
646
+ */
647
+ addPeer(record) {
648
+ this.#peers.set(record.podId, record);
649
+ this._fireDiscovered(record);
650
+ }
651
+
652
+ /**
653
+ * Remove a manually added peer.
654
+ * @param {string} podId
655
+ * @returns {boolean} true if the peer existed
656
+ */
657
+ removePeer(podId) {
658
+ return this.#peers.delete(podId);
659
+ }
660
+
661
+ /**
662
+ * Query all manually added peers, optionally filtered.
663
+ * @param {object} [filter]
664
+ * @returns {DiscoveryRecord[]}
665
+ */
666
+ query(filter) {
667
+ const results = [];
668
+ for (const record of this.#peers.values()) {
669
+ if (record.matchesFilter(filter)) {
670
+ results.push(record);
671
+ }
672
+ }
673
+ return results;
674
+ }
675
+ }
676
+
677
+ // ---------------------------------------------------------------------------
678
+ // PexStrategy — Peer Exchange
679
+ // ---------------------------------------------------------------------------
680
+
681
+ /**
682
+ * Discovers peers by exchanging peer lists with directly connected peers.
683
+ *
684
+ * When a new peer connects, both sides exchange their known peer lists.
685
+ * This reduces dependency on the signaling server — peers can discover
686
+ * each other transitively through the mesh itself.
687
+ *
688
+ * Usage:
689
+ * const pex = new PexStrategy({ localId: podId })
690
+ * discoveryManager.addStrategy(pex)
691
+ * // When a WebRTC peer connects:
692
+ * pex.addPeer(remotePodId, sendFn)
693
+ * // When a WebRTC message arrives with type PEX_EXCHANGE:
694
+ * pex.handleMessage(fromPodId, msg)
695
+ */
696
+ export class PexStrategy extends DiscoveryStrategy {
697
+ /** @type {string} */
698
+ #localId;
699
+
700
+ /** @type {Map<string, DiscoveryRecord>} */
701
+ #peers = new Map();
702
+
703
+ /** @type {Map<string, function>} podId -> sendFn */
704
+ #transports = new Map();
705
+
706
+ /** @type {number} */
707
+ #exchangeIntervalMs;
708
+
709
+ /** @type {*} */
710
+ #timer = null;
711
+
712
+ /**
713
+ * @param {object} opts
714
+ * @param {string} opts.localId - Local pod identifier
715
+ * @param {number} [opts.exchangeIntervalMs=30000] - Periodic exchange interval
716
+ */
717
+ constructor({ localId, exchangeIntervalMs = 30000 }) {
718
+ super({ type: 'pex' });
719
+ if (!localId || typeof localId !== 'string') {
720
+ throw new Error('localId is required and must be a non-empty string');
721
+ }
722
+ this.#localId = localId;
723
+ this.#exchangeIntervalMs = exchangeIntervalMs;
724
+ }
725
+
726
+ /**
727
+ * Start periodic peer exchange.
728
+ * @returns {Promise<void>}
729
+ */
730
+ async start() {
731
+ if (this.active) return;
732
+ this._active = true;
733
+ this.#timer = setInterval(() => this.#exchangeAll(), this.#exchangeIntervalMs);
734
+ }
735
+
736
+ /**
737
+ * Stop periodic exchange and clear state.
738
+ * @returns {Promise<void>}
739
+ */
740
+ async stop() {
741
+ if (!this.active) return;
742
+ this._active = false;
743
+ clearInterval(this.#timer);
744
+ this.#timer = null;
745
+ this.#transports.clear();
746
+ this.#peers.clear();
747
+ }
748
+
749
+ /**
750
+ * Announce is a no-op for PEX — peers are announced via exchange.
751
+ * @param {DiscoveryRecord} _record
752
+ * @returns {Promise<void>}
753
+ */
754
+ async announce(_record) { /* no-op */ }
755
+
756
+ /**
757
+ * Return cached peers matching an optional filter.
758
+ * @param {object} [filter]
759
+ * @returns {Promise<DiscoveryRecord[]>}
760
+ */
761
+ async query(filter) {
762
+ const results = [];
763
+ for (const record of this.#peers.values()) {
764
+ if (!record.isExpired() && record.matchesFilter(filter)) {
765
+ results.push(record);
766
+ }
767
+ }
768
+ return results;
769
+ }
770
+
771
+ /**
772
+ * Register a directly connected peer and immediately exchange peer lists.
773
+ *
774
+ * @param {string} podId - Remote peer's pod identifier
775
+ * @param {function} sendFn - (msg: object) => void — sends to this peer
776
+ */
777
+ addPeer(podId, sendFn) {
778
+ if (podId === this.#localId) return;
779
+ this.#transports.set(podId, sendFn);
780
+
781
+ // Add as a discovered peer if not already known
782
+ if (!this.#peers.has(podId)) {
783
+ const record = new DiscoveryRecord({
784
+ podId,
785
+ label: podId.slice(0, 8),
786
+ transport: 'webrtc',
787
+ source: 'pex',
788
+ });
789
+ this.#peers.set(podId, record);
790
+ this._fireDiscovered(record);
791
+ }
792
+
793
+ // Immediately send our peer list to the new peer
794
+ this.#sendExchange(podId);
795
+ }
796
+
797
+ /**
798
+ * Remove a disconnected peer's transport.
799
+ *
800
+ * @param {string} podId
801
+ */
802
+ removePeer(podId) {
803
+ this.#transports.delete(podId);
804
+ }
805
+
806
+ /**
807
+ * Handle an incoming PEX exchange message from a remote peer.
808
+ * Creates DiscoveryRecords for any unknown peers and fires callbacks.
809
+ *
810
+ * @param {string} fromPodId
811
+ * @param {object} msg - { type: 'pex-exchange', peers: string[] }
812
+ */
813
+ handleMessage(fromPodId, msg) {
814
+ if (msg.type !== 'pex-exchange' || !Array.isArray(msg.peers)) return;
815
+
816
+ for (const podId of msg.peers) {
817
+ if (podId === this.#localId) continue;
818
+ if (this.#peers.has(podId)) continue;
819
+
820
+ const record = new DiscoveryRecord({
821
+ podId,
822
+ label: podId.slice(0, 8),
823
+ transport: 'webrtc',
824
+ source: 'pex',
825
+ });
826
+ this.#peers.set(podId, record);
827
+ this._fireDiscovered(record);
828
+ }
829
+ }
830
+
831
+ /** @returns {string[]} List of known peer IDs */
832
+ knownPeers() {
833
+ return [...this.#peers.keys()];
834
+ }
835
+
836
+ /** @returns {number} Number of peers with active transports */
837
+ get connectedCount() {
838
+ return this.#transports.size;
839
+ }
840
+
841
+ // ── Internal ──────────────────────────────────────────────────────
842
+
843
+ /** Send our peer list to a specific peer. */
844
+ #sendExchange(targetPodId) {
845
+ const sendFn = this.#transports.get(targetPodId);
846
+ if (!sendFn) return;
847
+ sendFn({
848
+ type: 'pex-exchange',
849
+ from: this.#localId,
850
+ peers: [...this.#peers.keys()],
851
+ });
852
+ }
853
+
854
+ /** Exchange peer lists with all connected peers. */
855
+ #exchangeAll() {
856
+ for (const podId of this.#transports.keys()) {
857
+ this.#sendExchange(podId);
858
+ }
859
+ }
860
+ }
861
+
862
+ // ---------------------------------------------------------------------------
863
+ // SharedWorkerRelayStrategy
864
+ // ---------------------------------------------------------------------------
865
+
866
+ const WORKER_SCRIPT = `
867
+ const registry = new Map();
868
+ const ports = new Map();
869
+
870
+ self.onconnect = (e) => {
871
+ const port = e.ports[0];
872
+ let connPodId = null;
873
+
874
+ port.onmessage = ({ data }) => {
875
+ if (data.type === 'register') {
876
+ connPodId = data.podId;
877
+ registry.set(data.podId, data.profile);
878
+ ports.set(data.podId, port);
879
+ // Broadcast to all other ports
880
+ for (const [id, p] of ports) {
881
+ if (id !== data.podId) {
882
+ p.postMessage({ type: 'announce', record: data.profile });
883
+ }
884
+ }
885
+ } else if (data.type === 'query') {
886
+ const peers = [];
887
+ for (const [id, profile] of registry) {
888
+ if (id !== connPodId) peers.push(profile);
889
+ }
890
+ port.postMessage({ type: 'peers', peers });
891
+ } else if (data.type === 'relay' && data.targetPodId) {
892
+ const target = ports.get(data.targetPodId);
893
+ if (target) {
894
+ target.postMessage({ type: 'relay', from: connPodId, payload: data.payload });
895
+ }
896
+ } else if (data.type === 'unregister') {
897
+ if (connPodId) {
898
+ registry.delete(connPodId);
899
+ ports.delete(connPodId);
900
+ }
901
+ }
902
+ };
903
+ port.start();
904
+ };
905
+ `;
906
+
907
+ /**
908
+ * Discovers peers within same-origin tabs using a SharedWorker as relay.
909
+ * The SharedWorker maintains a peer registry and forwards messages
910
+ * between connected ports.
911
+ */
912
+ export class SharedWorkerRelayStrategy extends DiscoveryStrategy {
913
+ /** @type {Function|null} */
914
+ #createWorkerFn;
915
+
916
+ /** @type {object|null} */
917
+ #worker = null;
918
+
919
+ /** @type {object|null} */
920
+ #port = null;
921
+
922
+ /** @type {Map<string, DiscoveryRecord>} */
923
+ #peers = new Map();
924
+
925
+ /**
926
+ * @param {object} [opts]
927
+ * @param {Function} [opts.createWorkerFn] - Injectable factory for testing
928
+ */
929
+ constructor({ createWorkerFn } = {}) {
930
+ super({ type: 'shared-worker' })
931
+ this.#createWorkerFn = createWorkerFn ?? null
932
+ this.#peers = new Map()
933
+ }
934
+
935
+ /**
936
+ * Start the SharedWorker relay strategy.
937
+ * @returns {Promise<void>}
938
+ */
939
+ async start() {
940
+ if (this.active) return
941
+
942
+ const factory = this.#createWorkerFn ?? (() => {
943
+ const blob = new Blob([WORKER_SCRIPT], { type: 'application/javascript' })
944
+ const url = URL.createObjectURL(blob)
945
+ const worker = new SharedWorker(url, 'clawser-mesh-relay')
946
+ URL.revokeObjectURL(url)
947
+ return worker
948
+ })
949
+
950
+ this.#worker = factory()
951
+ this.#port = this.#worker.port
952
+ this.#port.onmessage = (event) => {
953
+ this.#handleMessage(event.data)
954
+ }
955
+ if (typeof this.#port.start === 'function') {
956
+ this.#port.start()
957
+ }
958
+ this._active = true
959
+ }
960
+
961
+ /**
962
+ * Stop the SharedWorker relay strategy.
963
+ * @returns {Promise<void>}
964
+ */
965
+ async stop() {
966
+ if (!this.active) return
967
+ if (this.#port) {
968
+ this.#port.postMessage({ type: 'unregister' })
969
+ if (typeof this.#port.close === 'function') {
970
+ this.#port.close()
971
+ }
972
+ this.#port = null
973
+ }
974
+ this.#worker = null
975
+ this._active = false
976
+ }
977
+
978
+ /**
979
+ * Announce a record via the SharedWorker relay.
980
+ * @param {DiscoveryRecord} record
981
+ * @returns {Promise<void>}
982
+ */
983
+ async announce(record) {
984
+ if (this.#port) {
985
+ this.#port.postMessage({
986
+ type: 'register',
987
+ podId: record.podId,
988
+ profile: record.toJSON(),
989
+ })
990
+ }
991
+ }
992
+
993
+ /**
994
+ * Query for peers discovered via the SharedWorker relay.
995
+ * Sends a query to the worker and returns currently cached peers.
996
+ *
997
+ * @param {object} [filter]
998
+ * @returns {Promise<DiscoveryRecord[]>}
999
+ */
1000
+ async query(filter) {
1001
+ if (this.#port) {
1002
+ this.#port.postMessage({ type: 'query', filter })
1003
+ }
1004
+ const results = []
1005
+ for (const record of this.#peers.values()) {
1006
+ if (!record.isExpired() && record.matchesFilter(filter)) {
1007
+ results.push(record)
1008
+ }
1009
+ }
1010
+ return results
1011
+ }
1012
+
1013
+ /**
1014
+ * Handle an incoming message from the SharedWorker port.
1015
+ * @param {object} data
1016
+ * @private
1017
+ */
1018
+ #handleMessage(data) {
1019
+ if (!data || typeof data !== 'object') return
1020
+
1021
+ if (data.type === 'peers' && Array.isArray(data.peers)) {
1022
+ for (const peerData of data.peers) {
1023
+ const record = DiscoveryRecord.fromJSON(peerData)
1024
+ record.source = 'shared-worker'
1025
+ this.#peers.set(record.podId, record)
1026
+ }
1027
+ } else if (data.type === 'announce' && data.record) {
1028
+ const record = DiscoveryRecord.fromJSON(data.record)
1029
+ record.source = 'shared-worker'
1030
+ this.#peers.set(record.podId, record)
1031
+ this._fireDiscovered(record)
1032
+ } else if (data.type === 'relay') {
1033
+ // Handle relayed payload — if it looks like a discovery record, fire discovered
1034
+ if (data.payload && data.payload.podId) {
1035
+ const record = DiscoveryRecord.fromJSON(data.payload)
1036
+ record.source = 'shared-worker'
1037
+ this.#peers.set(record.podId, record)
1038
+ this._fireDiscovered(record)
1039
+ }
1040
+ }
1041
+ }
1042
+ }
1043
+
1044
+ // ---------------------------------------------------------------------------
1045
+ // DiscoveryManager
1046
+ // ---------------------------------------------------------------------------
1047
+
1048
+ /**
1049
+ * Orchestrates multiple discovery strategies with periodic announce and
1050
+ * TTL-based pruning.
1051
+ */
1052
+ export class DiscoveryManager {
1053
+ /** @type {DiscoveryStrategy[]} */
1054
+ #strategies = [];
1055
+
1056
+ /** @type {DiscoveryRecord} */
1057
+ #localRecord;
1058
+
1059
+ /** @type {number} */
1060
+ #announceInterval;
1061
+
1062
+ /** @type {Map<string, DiscoveryRecord>} peers indexed by podId */
1063
+ #peers = new Map();
1064
+
1065
+ /** @type {Function[]} */
1066
+ #peerDiscoveredCallbacks = [];
1067
+
1068
+ /** @type {Function[]} */
1069
+ #peerLostCallbacks = [];
1070
+
1071
+ /** @type {number|null} */
1072
+ #announceTimer = null;
1073
+
1074
+ /** @type {number|null} */
1075
+ #pruneTimer = null;
1076
+
1077
+ /**
1078
+ * @param {object} opts
1079
+ * @param {DiscoveryStrategy[]} [opts.strategies=[]] - Initial strategies
1080
+ * @param {DiscoveryRecord} opts.localRecord - Record describing the local node
1081
+ * @param {number} [opts.announceInterval=15000] - How often to re-announce (ms)
1082
+ */
1083
+ constructor({ strategies = [], localRecord, announceInterval = 15_000 } = {}) {
1084
+ if (!localRecord) {
1085
+ throw new Error('localRecord is required');
1086
+ }
1087
+ this.#localRecord = localRecord;
1088
+ this.#announceInterval = announceInterval;
1089
+ for (const s of strategies) {
1090
+ this.#strategies.push(s);
1091
+ this.#wireStrategy(s);
1092
+ }
1093
+ }
1094
+
1095
+ /**
1096
+ * Wire a strategy's onDiscovered callback to propagate into the manager.
1097
+ * @param {DiscoveryStrategy} strategy
1098
+ * @private
1099
+ */
1100
+ #wireStrategy(strategy) {
1101
+ strategy.onDiscovered((record) => {
1102
+ this.#peers.set(record.podId, record);
1103
+ for (const cb of this.#peerDiscoveredCallbacks) {
1104
+ cb(record);
1105
+ }
1106
+ });
1107
+ }
1108
+
1109
+ /**
1110
+ * Start all strategies, begin periodic announce and pruning.
1111
+ * @returns {Promise<void>}
1112
+ */
1113
+ async start() {
1114
+ for (const s of this.#strategies) {
1115
+ await s.start();
1116
+ }
1117
+ // Initial announce
1118
+ await this.announce();
1119
+ // Periodic announce (skip in test / no-timer environments)
1120
+ if (typeof setInterval === 'function') {
1121
+ this.#announceTimer = setInterval(() => {
1122
+ this.announce().catch(() => {});
1123
+ this._pruneExpired();
1124
+ }, this.#announceInterval);
1125
+ // Unref so it doesn't keep Node alive in tests
1126
+ if (this.#announceTimer && typeof this.#announceTimer === 'object' && this.#announceTimer.unref) {
1127
+ this.#announceTimer.unref();
1128
+ }
1129
+ }
1130
+ }
1131
+
1132
+ /**
1133
+ * Stop all strategies and clear timers.
1134
+ * @returns {Promise<void>}
1135
+ */
1136
+ async stop() {
1137
+ if (this.#announceTimer !== null) {
1138
+ clearInterval(this.#announceTimer);
1139
+ this.#announceTimer = null;
1140
+ }
1141
+ if (this.#pruneTimer !== null) {
1142
+ clearInterval(this.#pruneTimer);
1143
+ this.#pruneTimer = null;
1144
+ }
1145
+ for (const s of this.#strategies) {
1146
+ await s.stop();
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * Announce the local record to all strategies.
1152
+ * @returns {Promise<void>}
1153
+ */
1154
+ async announce() {
1155
+ for (const s of this.#strategies) {
1156
+ try {
1157
+ await s.announce(this.#localRecord);
1158
+ } catch {
1159
+ // Ignore announce failures on individual strategies
1160
+ }
1161
+ }
1162
+ }
1163
+
1164
+ /**
1165
+ * Query all strategies, merge and deduplicate results.
1166
+ * @param {object} [filter]
1167
+ * @returns {Promise<DiscoveryRecord[]>}
1168
+ */
1169
+ async discover(filter) {
1170
+ const seen = new Map();
1171
+ for (const s of this.#strategies) {
1172
+ try {
1173
+ const results = await s.query(filter);
1174
+ for (const r of results) {
1175
+ if (!seen.has(r.podId)) {
1176
+ seen.set(r.podId, r);
1177
+ // Also add to internal peers map
1178
+ this.#peers.set(r.podId, r);
1179
+ }
1180
+ }
1181
+ } catch {
1182
+ // Ignore query failures on individual strategies
1183
+ }
1184
+ }
1185
+ return [...seen.values()];
1186
+ }
1187
+
1188
+ /**
1189
+ * Add a new discovery strategy.
1190
+ * @param {DiscoveryStrategy} strategy
1191
+ */
1192
+ addStrategy(strategy) {
1193
+ this.#strategies.push(strategy);
1194
+ this.#wireStrategy(strategy);
1195
+ }
1196
+
1197
+ /**
1198
+ * Remove a strategy by type.
1199
+ * @param {string} type
1200
+ * @returns {boolean} true if a strategy was removed
1201
+ */
1202
+ removeStrategy(type) {
1203
+ const idx = this.#strategies.findIndex(s => s.type === type);
1204
+ if (idx === -1) return false;
1205
+ this.#strategies.splice(idx, 1);
1206
+ return true;
1207
+ }
1208
+
1209
+ /**
1210
+ * Register a callback for when a new peer is discovered.
1211
+ * @param {Function} cb - Callback receiving a DiscoveryRecord
1212
+ */
1213
+ onPeerDiscovered(cb) {
1214
+ this.#peerDiscoveredCallbacks.push(cb);
1215
+ }
1216
+
1217
+ /**
1218
+ * Register a callback for when a peer is lost (expired/pruned).
1219
+ * @param {Function} cb - Callback receiving a DiscoveryRecord
1220
+ */
1221
+ onPeerLost(cb) {
1222
+ this.#peerLostCallbacks.push(cb);
1223
+ }
1224
+
1225
+ /**
1226
+ * Get all known peers.
1227
+ * @returns {Map<string, DiscoveryRecord>}
1228
+ */
1229
+ getPeers() {
1230
+ return new Map(this.#peers);
1231
+ }
1232
+
1233
+ /**
1234
+ * Get a single peer by podId.
1235
+ * @param {string} podId
1236
+ * @returns {DiscoveryRecord|null}
1237
+ */
1238
+ getPeer(podId) {
1239
+ return this.#peers.get(podId) ?? null;
1240
+ }
1241
+
1242
+ /**
1243
+ * Remove expired records from the internal peers map.
1244
+ * Fires onPeerLost callbacks for each removed peer.
1245
+ * @internal
1246
+ */
1247
+ _pruneExpired() {
1248
+ const now = Date.now();
1249
+ for (const [podId, record] of this.#peers) {
1250
+ if (record.isExpired(now)) {
1251
+ this.#peers.delete(podId);
1252
+ for (const cb of this.#peerLostCallbacks) {
1253
+ cb(record);
1254
+ }
1255
+ }
1256
+ }
1257
+ }
1258
+
1259
+ /**
1260
+ * Serialize to a JSON-safe object.
1261
+ * @returns {object}
1262
+ */
1263
+ toJSON() {
1264
+ return {
1265
+ localRecord: this.#localRecord.toJSON(),
1266
+ announceInterval: this.#announceInterval,
1267
+ strategies: this.#strategies.map(s => s.type),
1268
+ peers: [...this.#peers.values()].map(r => r.toJSON()),
1269
+ };
1270
+ }
1271
+
1272
+ /**
1273
+ * Re-hydrate from serialized data.
1274
+ * Creates a manager with no strategies (strategies must be re-added manually).
1275
+ * Restores the peers map from serialized data.
1276
+ *
1277
+ * @param {object} data
1278
+ * @returns {DiscoveryManager}
1279
+ */
1280
+ static fromJSON(data) {
1281
+ const localRecord = DiscoveryRecord.fromJSON(data.localRecord);
1282
+ const mgr = new DiscoveryManager({
1283
+ strategies: [],
1284
+ localRecord,
1285
+ announceInterval: data.announceInterval,
1286
+ });
1287
+ for (const peerData of data.peers || []) {
1288
+ const record = DiscoveryRecord.fromJSON(peerData);
1289
+ mgr.#peers.set(record.podId, record);
1290
+ }
1291
+ return mgr;
1292
+ }
1293
+ }
1294
+
1295
+ // ---------------------------------------------------------------------------
1296
+ // ServiceEndpoint
1297
+ // ---------------------------------------------------------------------------
1298
+
1299
+ /**
1300
+ * Describes a svc:// service offered by a mesh pod.
1301
+ */
1302
+ export class ServiceEndpoint {
1303
+ /**
1304
+ * @param {object} opts
1305
+ * @param {string} opts.name - Service name
1306
+ * @param {string} opts.podId - Pod offering this service
1307
+ * @param {string} [opts.protocol='svc'] - Protocol (always 'svc')
1308
+ * @param {string} [opts.version='1.0'] - Service version
1309
+ * @param {object} [opts.metadata={}] - Arbitrary metadata
1310
+ * @param {number} [opts.ttl=60000] - Time-to-live in ms
1311
+ * @param {number} [opts.registeredAt] - Registration timestamp
1312
+ */
1313
+ constructor({
1314
+ name,
1315
+ podId,
1316
+ protocol = 'svc',
1317
+ version = '1.0',
1318
+ metadata = {},
1319
+ ttl = 60_000,
1320
+ registeredAt,
1321
+ }) {
1322
+ if (!name || typeof name !== 'string') {
1323
+ throw new Error('name is required and must be a non-empty string');
1324
+ }
1325
+ if (!podId || typeof podId !== 'string') {
1326
+ throw new Error('podId is required and must be a non-empty string');
1327
+ }
1328
+ this.name = name;
1329
+ this.podId = podId;
1330
+ this.protocol = protocol;
1331
+ this.version = version;
1332
+ this.metadata = { ...metadata };
1333
+ this.ttl = ttl;
1334
+ this.registeredAt = registeredAt ?? Date.now();
1335
+ }
1336
+
1337
+ /**
1338
+ * Get the full svc:// URI for this service.
1339
+ * @returns {string}
1340
+ */
1341
+ get uri() {
1342
+ return `svc://${this.podId}/${this.name}`;
1343
+ }
1344
+
1345
+ /**
1346
+ * Check whether this endpoint has expired.
1347
+ *
1348
+ * @param {number} [now=Date.now()] - Current timestamp in ms
1349
+ * @returns {boolean}
1350
+ */
1351
+ isExpired(now = Date.now()) {
1352
+ return now >= this.registeredAt + this.ttl;
1353
+ }
1354
+
1355
+ /**
1356
+ * Serialize to a JSON-safe object.
1357
+ * @returns {object}
1358
+ */
1359
+ toJSON() {
1360
+ return {
1361
+ name: this.name,
1362
+ podId: this.podId,
1363
+ protocol: this.protocol,
1364
+ version: this.version,
1365
+ metadata: { ...this.metadata },
1366
+ ttl: this.ttl,
1367
+ registeredAt: this.registeredAt,
1368
+ };
1369
+ }
1370
+
1371
+ /**
1372
+ * Re-hydrate from a plain object.
1373
+ * @param {object} data
1374
+ * @returns {ServiceEndpoint}
1375
+ */
1376
+ static fromJSON(data) {
1377
+ return new ServiceEndpoint(data);
1378
+ }
1379
+ }
1380
+
1381
+ // ---------------------------------------------------------------------------
1382
+ // ServiceDirectory
1383
+ // ---------------------------------------------------------------------------
1384
+
1385
+ /**
1386
+ * Local service registry and directory with svc:// URI routing.
1387
+ * Manages both local service handlers and remote service endpoint references.
1388
+ */
1389
+ export class ServiceDirectory {
1390
+ /** @type {string} */
1391
+ #localPodId;
1392
+
1393
+ /** @type {Map<string, { endpoint: ServiceEndpoint, handler: Function }>} name -> local svc */
1394
+ #local = new Map();
1395
+
1396
+ /** @type {Map<string, ServiceEndpoint>} uri -> remote endpoint */
1397
+ #remote = new Map();
1398
+
1399
+ /** @type {Function[]} */
1400
+ #registerCallbacks = [];
1401
+
1402
+ /** @type {Function[]} */
1403
+ #unregisterCallbacks = [];
1404
+
1405
+ /**
1406
+ * @param {object} opts
1407
+ * @param {string} opts.localPodId - This node's pod identifier
1408
+ */
1409
+ constructor({ localPodId }) {
1410
+ if (!localPodId || typeof localPodId !== 'string') {
1411
+ throw new Error('localPodId is required and must be a non-empty string');
1412
+ }
1413
+ this.#localPodId = localPodId;
1414
+ }
1415
+
1416
+ /**
1417
+ * Register a local service handler.
1418
+ *
1419
+ * @param {string} name - Service name
1420
+ * @param {Function} handler - Handler function for incoming requests
1421
+ * @param {object} [opts]
1422
+ * @param {object} [opts.metadata] - Metadata for the endpoint
1423
+ * @param {number} [opts.ttl] - TTL for the endpoint
1424
+ * @returns {ServiceEndpoint}
1425
+ */
1426
+ register(name, handler, opts = {}) {
1427
+ if (!name || typeof name !== 'string') {
1428
+ throw new Error('name is required and must be a non-empty string');
1429
+ }
1430
+ if (!handler || typeof handler !== 'function') {
1431
+ throw new Error('handler is required and must be a function');
1432
+ }
1433
+ if (this.#local.has(name)) {
1434
+ throw new Error(`Service '${name}' is already registered`);
1435
+ }
1436
+ const endpoint = new ServiceEndpoint({
1437
+ name,
1438
+ podId: this.#localPodId,
1439
+ metadata: opts.metadata,
1440
+ ttl: opts.ttl,
1441
+ });
1442
+ this.#local.set(name, { endpoint, handler });
1443
+ for (const cb of this.#registerCallbacks) {
1444
+ cb(endpoint);
1445
+ }
1446
+ return endpoint;
1447
+ }
1448
+
1449
+ /**
1450
+ * Unregister a local service.
1451
+ *
1452
+ * @param {string} name
1453
+ * @returns {boolean} true if the service existed
1454
+ */
1455
+ unregister(name) {
1456
+ if (!this.#local.has(name)) return false;
1457
+ this.#local.delete(name);
1458
+ for (const cb of this.#unregisterCallbacks) {
1459
+ cb(name);
1460
+ }
1461
+ return true;
1462
+ }
1463
+
1464
+ /**
1465
+ * Look up a service by its svc:// URI.
1466
+ * Parses the URI to extract podId and service name, then checks
1467
+ * local services first, then remote endpoints.
1468
+ *
1469
+ * @param {string} uri - URI in format svc://podId/serviceName
1470
+ * @returns {{ endpoint: ServiceEndpoint, isLocal: boolean }|null}
1471
+ */
1472
+ lookup(uri) {
1473
+ const parsed = ServiceDirectory.#parseUri(uri);
1474
+ if (!parsed) return null;
1475
+
1476
+ const { podId, name } = parsed;
1477
+
1478
+ // Check local services
1479
+ if (podId === this.#localPodId && this.#local.has(name)) {
1480
+ return { endpoint: this.#local.get(name).endpoint, isLocal: true };
1481
+ }
1482
+
1483
+ // Check remote endpoints
1484
+ const remoteKey = `svc://${podId}/${name}`;
1485
+ if (this.#remote.has(remoteKey)) {
1486
+ return { endpoint: this.#remote.get(remoteKey), isLocal: false };
1487
+ }
1488
+
1489
+ return null;
1490
+ }
1491
+
1492
+ /**
1493
+ * Find all endpoints (local and remote) offering a service by name.
1494
+ *
1495
+ * @param {string} name
1496
+ * @returns {ServiceEndpoint[]}
1497
+ */
1498
+ lookupByName(name) {
1499
+ const results = [];
1500
+ // Local
1501
+ if (this.#local.has(name)) {
1502
+ results.push(this.#local.get(name).endpoint);
1503
+ }
1504
+ // Remote
1505
+ for (const ep of this.#remote.values()) {
1506
+ if (ep.name === name) {
1507
+ results.push(ep);
1508
+ }
1509
+ }
1510
+ return results;
1511
+ }
1512
+
1513
+ /**
1514
+ * Add a remote service endpoint reference.
1515
+ *
1516
+ * @param {ServiceEndpoint} endpoint
1517
+ */
1518
+ addRemote(endpoint) {
1519
+ this.#remote.set(endpoint.uri, endpoint);
1520
+ }
1521
+
1522
+ /**
1523
+ * Remove a remote service endpoint by URI.
1524
+ *
1525
+ * @param {string} uri
1526
+ * @returns {boolean} true if the endpoint existed
1527
+ */
1528
+ removeRemote(uri) {
1529
+ return this.#remote.delete(uri);
1530
+ }
1531
+
1532
+ /**
1533
+ * List all locally registered service endpoints.
1534
+ * @returns {ServiceEndpoint[]}
1535
+ */
1536
+ listLocal() {
1537
+ return [...this.#local.values()].map(e => e.endpoint);
1538
+ }
1539
+
1540
+ /**
1541
+ * List all remote service endpoints.
1542
+ * @returns {ServiceEndpoint[]}
1543
+ */
1544
+ listRemote() {
1545
+ return [...this.#remote.values()];
1546
+ }
1547
+
1548
+ /**
1549
+ * List all service endpoints (local + remote).
1550
+ * @returns {ServiceEndpoint[]}
1551
+ */
1552
+ listAll() {
1553
+ return [...this.listLocal(), ...this.listRemote()];
1554
+ }
1555
+
1556
+ /**
1557
+ * Register a callback for when a local service is registered.
1558
+ * @param {Function} cb - Callback receiving a ServiceEndpoint
1559
+ */
1560
+ onRegister(cb) {
1561
+ this.#registerCallbacks.push(cb);
1562
+ }
1563
+
1564
+ /**
1565
+ * Register a callback for when a local service is unregistered.
1566
+ * @param {Function} cb - Callback receiving the service name
1567
+ */
1568
+ onUnregister(cb) {
1569
+ this.#unregisterCallbacks.push(cb);
1570
+ }
1571
+
1572
+ /**
1573
+ * Parse a svc:// URI into podId and name.
1574
+ * @param {string} uri
1575
+ * @returns {{ podId: string, name: string }|null}
1576
+ * @private
1577
+ */
1578
+ static #parseUri(uri) {
1579
+ if (!uri || typeof uri !== 'string') return null;
1580
+ const match = uri.match(/^svc:\/\/([^/]+)\/(.+)$/);
1581
+ if (!match) return null;
1582
+ return { podId: match[1], name: match[2] };
1583
+ }
1584
+ }