@silicaclaw/cli 1.0.0-beta.2 → 1.0.0-beta.21

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.
Files changed (79) hide show
  1. package/CHANGELOG.md +8 -0
  2. package/INSTALL.md +36 -0
  3. package/README.md +40 -0
  4. package/apps/local-console/public/index.html +81 -63
  5. package/apps/local-console/src/server.ts +41 -21
  6. package/docs/CLOUDFLARE_RELAY.md +61 -0
  7. package/package.json +6 -1
  8. package/packages/core/dist/crypto.d.ts +6 -0
  9. package/packages/core/dist/crypto.js +50 -0
  10. package/packages/core/dist/directory.d.ts +17 -0
  11. package/packages/core/dist/directory.js +145 -0
  12. package/packages/core/dist/identity.d.ts +2 -0
  13. package/packages/core/dist/identity.js +18 -0
  14. package/packages/core/dist/index.d.ts +11 -0
  15. package/packages/core/dist/index.js +27 -0
  16. package/packages/core/dist/indexing.d.ts +6 -0
  17. package/packages/core/dist/indexing.js +43 -0
  18. package/packages/core/dist/presence.d.ts +4 -0
  19. package/packages/core/dist/presence.js +23 -0
  20. package/packages/core/dist/profile.d.ts +4 -0
  21. package/packages/core/dist/profile.js +39 -0
  22. package/packages/core/dist/publicProfileSummary.d.ts +70 -0
  23. package/packages/core/dist/publicProfileSummary.js +103 -0
  24. package/packages/core/dist/socialConfig.d.ts +99 -0
  25. package/packages/core/dist/socialConfig.js +288 -0
  26. package/packages/core/dist/socialResolver.d.ts +46 -0
  27. package/packages/core/dist/socialResolver.js +237 -0
  28. package/packages/core/dist/socialTemplate.d.ts +2 -0
  29. package/packages/core/dist/socialTemplate.js +88 -0
  30. package/packages/core/dist/types.d.ts +37 -0
  31. package/packages/core/dist/types.js +2 -0
  32. package/packages/core/src/socialConfig.ts +7 -6
  33. package/packages/core/src/socialResolver.ts +17 -5
  34. package/packages/network/dist/abstractions/messageEnvelope.d.ts +28 -0
  35. package/packages/network/dist/abstractions/messageEnvelope.js +36 -0
  36. package/packages/network/dist/abstractions/peerDiscovery.d.ts +43 -0
  37. package/packages/network/dist/abstractions/peerDiscovery.js +2 -0
  38. package/packages/network/dist/abstractions/topicCodec.d.ts +4 -0
  39. package/packages/network/dist/abstractions/topicCodec.js +2 -0
  40. package/packages/network/dist/abstractions/transport.d.ts +36 -0
  41. package/packages/network/dist/abstractions/transport.js +2 -0
  42. package/packages/network/dist/codec/jsonMessageEnvelopeCodec.d.ts +5 -0
  43. package/packages/network/dist/codec/jsonMessageEnvelopeCodec.js +24 -0
  44. package/packages/network/dist/codec/jsonTopicCodec.d.ts +5 -0
  45. package/packages/network/dist/codec/jsonTopicCodec.js +12 -0
  46. package/packages/network/dist/discovery/heartbeatPeerDiscovery.d.ts +28 -0
  47. package/packages/network/dist/discovery/heartbeatPeerDiscovery.js +144 -0
  48. package/packages/network/dist/index.d.ts +14 -0
  49. package/packages/network/dist/index.js +30 -0
  50. package/packages/network/dist/localEventBus.d.ts +9 -0
  51. package/packages/network/dist/localEventBus.js +47 -0
  52. package/packages/network/dist/mock.d.ts +8 -0
  53. package/packages/network/dist/mock.js +24 -0
  54. package/packages/network/dist/realPreview.d.ts +105 -0
  55. package/packages/network/dist/realPreview.js +327 -0
  56. package/packages/network/dist/relayPreview.d.ts +133 -0
  57. package/packages/network/dist/relayPreview.js +320 -0
  58. package/packages/network/dist/transport/udpLanBroadcastTransport.d.ts +23 -0
  59. package/packages/network/dist/transport/udpLanBroadcastTransport.js +153 -0
  60. package/packages/network/dist/types.d.ts +6 -0
  61. package/packages/network/dist/types.js +2 -0
  62. package/packages/network/dist/webrtcPreview.d.ts +163 -0
  63. package/packages/network/dist/webrtcPreview.js +844 -0
  64. package/packages/network/src/index.ts +1 -0
  65. package/packages/network/src/relayPreview.ts +425 -0
  66. package/packages/storage/dist/index.d.ts +3 -0
  67. package/packages/storage/dist/index.js +19 -0
  68. package/packages/storage/dist/jsonRepo.d.ts +7 -0
  69. package/packages/storage/dist/jsonRepo.js +29 -0
  70. package/packages/storage/dist/repos.d.ts +21 -0
  71. package/packages/storage/dist/repos.js +41 -0
  72. package/packages/storage/dist/socialRuntimeRepo.d.ts +5 -0
  73. package/packages/storage/dist/socialRuntimeRepo.js +52 -0
  74. package/packages/storage/src/socialRuntimeRepo.ts +3 -3
  75. package/packages/storage/tsconfig.json +6 -1
  76. package/scripts/quickstart.sh +286 -20
  77. package/scripts/silicaclaw-cli.mjs +271 -1
  78. package/scripts/silicaclaw-gateway.mjs +411 -0
  79. package/scripts/webrtc-signaling-server.mjs +52 -1
@@ -0,0 +1,320 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RelayPreviewAdapter = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const messageEnvelope_1 = require("./abstractions/messageEnvelope");
6
+ const jsonMessageEnvelopeCodec_1 = require("./codec/jsonMessageEnvelopeCodec");
7
+ const jsonTopicCodec_1 = require("./codec/jsonTopicCodec");
8
+ function dedupe(values) {
9
+ return Array.from(new Set(values.map((value) => value.trim()).filter(Boolean)));
10
+ }
11
+ class RelayPreviewAdapter {
12
+ peerId;
13
+ namespace;
14
+ signalingEndpoints;
15
+ room;
16
+ seedPeers;
17
+ bootstrapHints;
18
+ bootstrapSources;
19
+ maxMessageBytes;
20
+ pollIntervalMs;
21
+ maxFutureDriftMs;
22
+ maxPastDriftMs;
23
+ envelopeCodec;
24
+ topicCodec;
25
+ started = false;
26
+ poller = null;
27
+ handlers = new Map();
28
+ peers = new Map();
29
+ seenMessageIds = new Set();
30
+ activeEndpoint = "";
31
+ discoveryEvents = [];
32
+ discoveryEventsTotal = 0;
33
+ lastDiscoveryEventAt = 0;
34
+ signalingMessagesSentTotal = 0;
35
+ signalingMessagesReceivedTotal = 0;
36
+ reconnectAttemptsTotal = 0;
37
+ stats = {
38
+ publish_attempted: 0,
39
+ publish_sent: 0,
40
+ received_total: 0,
41
+ delivered_total: 0,
42
+ dropped_malformed: 0,
43
+ dropped_oversized: 0,
44
+ dropped_namespace_mismatch: 0,
45
+ dropped_timestamp_future_drift: 0,
46
+ dropped_timestamp_past_drift: 0,
47
+ dropped_decode_failed: 0,
48
+ dropped_self: 0,
49
+ dropped_topic_decode_error: 0,
50
+ dropped_handler_error: 0,
51
+ signaling_errors: 0,
52
+ invalid_signaling_payload_total: 0,
53
+ duplicate_sdp_total: 0,
54
+ duplicate_ice_total: 0,
55
+ start_errors: 0,
56
+ stop_errors: 0,
57
+ received_validated: 0,
58
+ };
59
+ constructor(options = {}) {
60
+ this.peerId = options.peerId ?? `peer-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
61
+ this.namespace = String(options.namespace || "silicaclaw.preview").trim() || "silicaclaw.preview";
62
+ this.signalingEndpoints = dedupe((options.signalingUrls && options.signalingUrls.length > 0
63
+ ? options.signalingUrls
64
+ : [options.signalingUrl || "http://localhost:4510"]));
65
+ this.activeEndpoint = this.signalingEndpoints[0] || "http://localhost:4510";
66
+ this.room = String(options.room || "silicaclaw-global-preview").trim() || "silicaclaw-global-preview";
67
+ this.seedPeers = dedupe(options.seedPeers || []);
68
+ this.bootstrapHints = dedupe(options.bootstrapHints || []);
69
+ this.bootstrapSources = dedupe(options.bootstrapSources || []);
70
+ this.maxMessageBytes = options.maxMessageBytes ?? 64 * 1024;
71
+ this.pollIntervalMs = options.pollIntervalMs ?? 2000;
72
+ this.maxFutureDriftMs = options.maxFutureDriftMs ?? 30_000;
73
+ this.maxPastDriftMs = options.maxPastDriftMs ?? 120_000;
74
+ this.envelopeCodec = new jsonMessageEnvelopeCodec_1.JsonMessageEnvelopeCodec();
75
+ this.topicCodec = new jsonTopicCodec_1.JsonTopicCodec();
76
+ }
77
+ async start() {
78
+ if (this.started)
79
+ return;
80
+ try {
81
+ await this.post("/join", { room: this.room, peer_id: this.peerId });
82
+ this.started = true;
83
+ await this.refreshPeers();
84
+ await this.pollOnce();
85
+ this.poller = setInterval(() => {
86
+ this.pollOnce().catch(() => { });
87
+ }, this.pollIntervalMs);
88
+ this.recordDiscovery("signaling_connected", { endpoint: this.activeEndpoint });
89
+ }
90
+ catch (error) {
91
+ this.stats.start_errors += 1;
92
+ throw new Error(`Relay start failed: ${error instanceof Error ? error.message : String(error)}`);
93
+ }
94
+ }
95
+ async stop() {
96
+ if (!this.started)
97
+ return;
98
+ if (this.poller) {
99
+ clearInterval(this.poller);
100
+ this.poller = null;
101
+ }
102
+ try {
103
+ await this.post("/leave", { room: this.room, peer_id: this.peerId });
104
+ }
105
+ catch {
106
+ this.stats.stop_errors += 1;
107
+ }
108
+ this.started = false;
109
+ this.recordDiscovery("signaling_disconnected", { endpoint: this.activeEndpoint });
110
+ }
111
+ async publish(topic, data) {
112
+ if (!this.started)
113
+ return;
114
+ this.stats.publish_attempted += 1;
115
+ const envelope = {
116
+ version: 1,
117
+ message_id: (0, crypto_1.randomUUID)(),
118
+ topic: `${this.namespace}:${topic}`,
119
+ source_peer_id: this.peerId,
120
+ timestamp: Date.now(),
121
+ payload: this.topicCodec.encode(topic, data),
122
+ };
123
+ const raw = this.envelopeCodec.encode(envelope);
124
+ if (raw.length > this.maxMessageBytes) {
125
+ this.stats.dropped_oversized += 1;
126
+ return;
127
+ }
128
+ await this.post("/relay/publish", { room: this.room, peer_id: this.peerId, envelope });
129
+ this.stats.publish_sent += 1;
130
+ this.signalingMessagesSentTotal += 1;
131
+ }
132
+ subscribe(topic, handler) {
133
+ const key = `${this.namespace}:${topic}`;
134
+ if (!this.handlers.has(key)) {
135
+ this.handlers.set(key, new Set());
136
+ }
137
+ this.handlers.get(key)?.add(handler);
138
+ }
139
+ getDiagnostics() {
140
+ const peerItems = Array.from(this.peers.values()).sort((a, b) => b.last_seen_at - a.last_seen_at);
141
+ return {
142
+ adapter: "relay-preview",
143
+ peer_id: this.peerId,
144
+ namespace: this.namespace,
145
+ room: this.room,
146
+ signaling_url: this.activeEndpoint,
147
+ signaling_endpoints: this.signalingEndpoints,
148
+ bootstrap_sources: this.bootstrapSources,
149
+ seed_peers_count: this.seedPeers.length,
150
+ bootstrap_hints_count: this.bootstrapHints.length,
151
+ discovery_events_total: this.discoveryEventsTotal,
152
+ last_discovery_event_at: this.lastDiscoveryEventAt,
153
+ discovery_events: this.discoveryEvents,
154
+ signaling_messages_sent_total: this.signalingMessagesSentTotal,
155
+ signaling_messages_received_total: this.signalingMessagesReceivedTotal,
156
+ reconnect_attempts_total: this.reconnectAttemptsTotal,
157
+ active_webrtc_peers: peerItems.length,
158
+ components: {
159
+ transport: "HttpRelayTransport",
160
+ discovery: "RelayRoomPeerList",
161
+ envelope_codec: this.envelopeCodec.constructor.name,
162
+ topic_codec: this.topicCodec.constructor.name,
163
+ },
164
+ limits: {
165
+ max_message_bytes: this.maxMessageBytes,
166
+ max_future_drift_ms: this.maxFutureDriftMs,
167
+ max_past_drift_ms: this.maxPastDriftMs,
168
+ },
169
+ config: {
170
+ started: this.started,
171
+ topic_handler_count: this.handlers.size,
172
+ poll_interval_ms: this.pollIntervalMs,
173
+ },
174
+ peers: {
175
+ total: peerItems.length,
176
+ online: peerItems.length,
177
+ stale: 0,
178
+ items: peerItems,
179
+ },
180
+ stats: { ...this.stats },
181
+ };
182
+ }
183
+ async pollOnce() {
184
+ const payload = await this.get(`/relay/poll?room=${encodeURIComponent(this.room)}&peer_id=${encodeURIComponent(this.peerId)}`);
185
+ const messages = Array.isArray(payload?.messages) ? payload.messages : [];
186
+ for (const message of messages) {
187
+ this.signalingMessagesReceivedTotal += 1;
188
+ this.onEnvelope(message?.envelope);
189
+ }
190
+ await this.refreshPeers();
191
+ }
192
+ async refreshPeers() {
193
+ const payload = await this.get(`/peers?room=${encodeURIComponent(this.room)}`);
194
+ const peerIds = Array.isArray(payload?.peers) ? payload.peers.map((value) => String(value || "").trim()).filter(Boolean) : [];
195
+ const now = Date.now();
196
+ const next = new Map();
197
+ for (const peerId of peerIds) {
198
+ if (peerId === this.peerId)
199
+ continue;
200
+ const existing = this.peers.get(peerId);
201
+ if (!existing) {
202
+ this.recordDiscovery("peer_joined", { peer_id: peerId });
203
+ }
204
+ next.set(peerId, {
205
+ peer_id: peerId,
206
+ status: "online",
207
+ first_seen_at: existing?.first_seen_at ?? now,
208
+ last_seen_at: now,
209
+ messages_seen: existing?.messages_seen ?? 0,
210
+ reconnect_attempts: existing?.reconnect_attempts ?? 0,
211
+ });
212
+ }
213
+ for (const peerId of this.peers.keys()) {
214
+ if (!next.has(peerId)) {
215
+ this.recordDiscovery("peer_removed", { peer_id: peerId });
216
+ }
217
+ }
218
+ this.peers = next;
219
+ }
220
+ onEnvelope(envelope) {
221
+ this.stats.received_total += 1;
222
+ const validated = (0, messageEnvelope_1.validateNetworkMessageEnvelope)(envelope, {
223
+ max_future_drift_ms: this.maxFutureDriftMs,
224
+ max_past_drift_ms: this.maxPastDriftMs,
225
+ });
226
+ if (!validated.ok || !validated.envelope) {
227
+ if (validated.reason === "timestamp_future_drift") {
228
+ this.stats.dropped_timestamp_future_drift += 1;
229
+ }
230
+ else if (validated.reason === "timestamp_past_drift") {
231
+ this.stats.dropped_timestamp_past_drift += 1;
232
+ }
233
+ else {
234
+ this.stats.dropped_malformed += 1;
235
+ }
236
+ return;
237
+ }
238
+ const message = validated.envelope;
239
+ if (message.source_peer_id === this.peerId) {
240
+ this.stats.dropped_self += 1;
241
+ return;
242
+ }
243
+ if (!message.topic.startsWith(`${this.namespace}:`)) {
244
+ this.stats.dropped_namespace_mismatch += 1;
245
+ return;
246
+ }
247
+ if (this.seenMessageIds.has(message.message_id)) {
248
+ return;
249
+ }
250
+ this.seenMessageIds.add(message.message_id);
251
+ if (this.seenMessageIds.size > 10000) {
252
+ const first = this.seenMessageIds.values().next().value;
253
+ if (first)
254
+ this.seenMessageIds.delete(first);
255
+ }
256
+ this.stats.received_validated += 1;
257
+ const topicKey = message.topic;
258
+ const topic = topicKey.slice(this.namespace.length + 1);
259
+ const handlers = this.handlers.get(topicKey);
260
+ if (!handlers || handlers.size === 0)
261
+ return;
262
+ const peer = this.peers.get(message.source_peer_id);
263
+ if (peer) {
264
+ peer.last_seen_at = Date.now();
265
+ peer.messages_seen += 1;
266
+ }
267
+ let payload;
268
+ try {
269
+ payload = this.topicCodec.decode(topic, message.payload);
270
+ }
271
+ catch {
272
+ this.stats.dropped_topic_decode_error += 1;
273
+ return;
274
+ }
275
+ for (const handler of handlers) {
276
+ try {
277
+ handler(payload);
278
+ this.stats.delivered_total += 1;
279
+ }
280
+ catch {
281
+ this.stats.dropped_handler_error += 1;
282
+ }
283
+ }
284
+ }
285
+ recordDiscovery(type, extra = {}) {
286
+ const event = {
287
+ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,
288
+ type,
289
+ at: Date.now(),
290
+ ...extra,
291
+ };
292
+ this.discoveryEvents.unshift(event);
293
+ this.discoveryEvents = this.discoveryEvents.slice(0, 200);
294
+ this.discoveryEventsTotal += 1;
295
+ this.lastDiscoveryEventAt = event.at;
296
+ }
297
+ async get(path) {
298
+ const endpoint = this.activeEndpoint.replace(/\/+$/, "");
299
+ const response = await fetch(`${endpoint}${path}`);
300
+ if (!response.ok) {
301
+ this.stats.signaling_errors += 1;
302
+ throw new Error(`Relay GET failed (${response.status})`);
303
+ }
304
+ return response.json();
305
+ }
306
+ async post(path, body) {
307
+ const endpoint = this.activeEndpoint.replace(/\/+$/, "");
308
+ const response = await fetch(`${endpoint}${path}`, {
309
+ method: "POST",
310
+ headers: { "content-type": "application/json" },
311
+ body: JSON.stringify(body),
312
+ });
313
+ if (!response.ok) {
314
+ this.stats.signaling_errors += 1;
315
+ throw new Error(`Relay POST failed (${response.status})`);
316
+ }
317
+ return response.json();
318
+ }
319
+ }
320
+ exports.RelayPreviewAdapter = RelayPreviewAdapter;
@@ -0,0 +1,23 @@
1
+ import { NetworkTransport, TransportConfigSnapshot, TransportMessageMeta, TransportStats } from "../abstractions/transport";
2
+ type UdpLanBroadcastTransportOptions = {
3
+ port?: number;
4
+ bindAddress?: string;
5
+ broadcastAddress?: string;
6
+ };
7
+ export declare class UdpLanBroadcastTransport implements NetworkTransport {
8
+ private socket;
9
+ private handlers;
10
+ private state;
11
+ private stats;
12
+ private port;
13
+ private bindAddress;
14
+ private broadcastAddress;
15
+ constructor(options?: UdpLanBroadcastTransportOptions);
16
+ start(): Promise<void>;
17
+ stop(): Promise<void>;
18
+ send(data: Buffer): Promise<void>;
19
+ onMessage(handler: (data: Buffer, meta: TransportMessageMeta) => void): () => void;
20
+ getStats(): TransportStats;
21
+ getConfig(): TransportConfigSnapshot;
22
+ }
23
+ export {};
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.UdpLanBroadcastTransport = void 0;
7
+ const dgram_1 = __importDefault(require("dgram"));
8
+ class UdpLanBroadcastTransport {
9
+ socket = null;
10
+ handlers = new Set();
11
+ state = "stopped";
12
+ stats = {
13
+ starts: 0,
14
+ stops: 0,
15
+ start_errors: 0,
16
+ stop_errors: 0,
17
+ sent_messages: 0,
18
+ sent_bytes: 0,
19
+ send_errors: 0,
20
+ received_messages: 0,
21
+ received_bytes: 0,
22
+ receive_errors: 0,
23
+ last_sent_at: 0,
24
+ last_received_at: 0,
25
+ last_error_at: 0,
26
+ };
27
+ port;
28
+ bindAddress;
29
+ broadcastAddress;
30
+ constructor(options = {}) {
31
+ this.port = options.port ?? 44123;
32
+ this.bindAddress = options.bindAddress ?? "0.0.0.0";
33
+ this.broadcastAddress = options.broadcastAddress ?? "255.255.255.255";
34
+ }
35
+ async start() {
36
+ if (this.socket) {
37
+ return;
38
+ }
39
+ this.state = "starting";
40
+ this.socket = dgram_1.default.createSocket({ type: "udp4", reuseAddr: true });
41
+ this.socket.on("error", () => {
42
+ this.stats.receive_errors += 1;
43
+ this.stats.last_error_at = Date.now();
44
+ this.state = "error";
45
+ });
46
+ this.socket.on("message", (msg, rinfo) => {
47
+ this.stats.received_messages += 1;
48
+ this.stats.received_bytes += msg.length;
49
+ this.stats.last_received_at = Date.now();
50
+ const meta = {
51
+ remote_address: rinfo.address,
52
+ remote_port: rinfo.port,
53
+ transport: "udp-lan-broadcast",
54
+ };
55
+ for (const handler of this.handlers) {
56
+ try {
57
+ handler(msg, meta);
58
+ }
59
+ catch {
60
+ this.stats.receive_errors += 1;
61
+ this.stats.last_error_at = Date.now();
62
+ }
63
+ }
64
+ });
65
+ await new Promise((resolve, reject) => {
66
+ if (!this.socket) {
67
+ this.state = "error";
68
+ reject(new Error("Transport socket unavailable"));
69
+ return;
70
+ }
71
+ this.socket.once("error", reject);
72
+ this.socket.bind(this.port, this.bindAddress, () => {
73
+ if (!this.socket) {
74
+ this.state = "error";
75
+ reject(new Error("Transport socket unavailable after bind"));
76
+ return;
77
+ }
78
+ this.socket.setBroadcast(true);
79
+ this.socket.off("error", reject);
80
+ this.stats.starts += 1;
81
+ this.state = "running";
82
+ resolve();
83
+ });
84
+ }).catch((error) => {
85
+ this.stats.start_errors += 1;
86
+ this.stats.last_error_at = Date.now();
87
+ this.state = "error";
88
+ this.socket = null;
89
+ throw error;
90
+ });
91
+ }
92
+ async stop() {
93
+ if (!this.socket) {
94
+ return;
95
+ }
96
+ this.state = "stopping";
97
+ const socket = this.socket;
98
+ this.socket = null;
99
+ await new Promise((resolve) => {
100
+ socket.close(() => resolve());
101
+ }).then(() => {
102
+ this.stats.stops += 1;
103
+ this.state = "stopped";
104
+ }).catch((error) => {
105
+ this.stats.stop_errors += 1;
106
+ this.stats.last_error_at = Date.now();
107
+ this.state = "error";
108
+ throw error;
109
+ });
110
+ }
111
+ async send(data) {
112
+ if (!this.socket) {
113
+ return;
114
+ }
115
+ await new Promise((resolve, reject) => {
116
+ if (!this.socket) {
117
+ resolve();
118
+ return;
119
+ }
120
+ this.socket.send(data, this.port, this.broadcastAddress, (error) => {
121
+ if (error) {
122
+ this.stats.send_errors += 1;
123
+ this.stats.last_error_at = Date.now();
124
+ reject(error);
125
+ return;
126
+ }
127
+ this.stats.sent_messages += 1;
128
+ this.stats.sent_bytes += data.length;
129
+ this.stats.last_sent_at = Date.now();
130
+ resolve();
131
+ });
132
+ });
133
+ }
134
+ onMessage(handler) {
135
+ this.handlers.add(handler);
136
+ return () => {
137
+ this.handlers.delete(handler);
138
+ };
139
+ }
140
+ getStats() {
141
+ return { ...this.stats };
142
+ }
143
+ getConfig() {
144
+ return {
145
+ transport: "udp-lan-broadcast",
146
+ state: this.state,
147
+ bind_address: this.bindAddress,
148
+ broadcast_address: this.broadcastAddress,
149
+ port: this.port,
150
+ };
151
+ }
152
+ }
153
+ exports.UdpLanBroadcastTransport = UdpLanBroadcastTransport;
@@ -0,0 +1,6 @@
1
+ export interface NetworkAdapter {
2
+ start(): Promise<void>;
3
+ stop(): Promise<void>;
4
+ publish(topic: string, data: any): Promise<void>;
5
+ subscribe(topic: string, handler: (data: any) => void): void;
6
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,163 @@
1
+ import { NetworkAdapter } from "./types";
2
+ type WebRTCPreviewOptions = {
3
+ peerId?: string;
4
+ namespace?: string;
5
+ signalingUrl?: string;
6
+ signalingUrls?: string[];
7
+ room?: string;
8
+ seedPeers?: string[];
9
+ bootstrapHints?: string[];
10
+ bootstrapSources?: string[];
11
+ maxMessageBytes?: number;
12
+ pollIntervalMs?: number;
13
+ maxFutureDriftMs?: number;
14
+ maxPastDriftMs?: number;
15
+ discoveryEventsLimit?: number;
16
+ };
17
+ type PeerStatus = "connecting" | "online" | "stale";
18
+ type WebRTCConnectionState = "new" | "connecting" | "connected" | "disconnected" | "failed" | "closed" | "unknown";
19
+ type WebRTCDataChannelState = "connecting" | "open" | "closing" | "closed" | "unknown";
20
+ type StateSummary<T extends string> = Record<T, number>;
21
+ type WebRTCDiagnostics = {
22
+ adapter: "webrtc-preview";
23
+ peer_id: string;
24
+ namespace: string;
25
+ room: string;
26
+ signaling_url: string;
27
+ signaling_endpoints: string[];
28
+ bootstrap_sources: string[];
29
+ seed_peers_count: number;
30
+ bootstrap_hints_count: number;
31
+ discovery_events_total: number;
32
+ last_discovery_event_at: number;
33
+ discovery_events: DiscoveryEvent[];
34
+ connection_states_summary: StateSummary<WebRTCConnectionState>;
35
+ datachannel_states_summary: StateSummary<WebRTCDataChannelState>;
36
+ signaling_messages_sent_total: number;
37
+ signaling_messages_received_total: number;
38
+ reconnect_attempts_total: number;
39
+ active_webrtc_peers: number;
40
+ components: {
41
+ transport: string;
42
+ discovery: string;
43
+ envelope_codec: string;
44
+ topic_codec: string;
45
+ };
46
+ limits: {
47
+ max_message_bytes: number;
48
+ max_future_drift_ms: number;
49
+ max_past_drift_ms: number;
50
+ };
51
+ config: {
52
+ started: boolean;
53
+ topic_handler_count: number;
54
+ poll_interval_ms: number;
55
+ };
56
+ peers: {
57
+ total: number;
58
+ online: number;
59
+ stale: number;
60
+ items: Array<{
61
+ peer_id: string;
62
+ status: PeerStatus;
63
+ first_seen_at: number;
64
+ last_seen_at: number;
65
+ messages_seen: number;
66
+ reconnect_attempts: number;
67
+ connection_state: WebRTCConnectionState;
68
+ datachannel_state: WebRTCDataChannelState;
69
+ }>;
70
+ };
71
+ stats: {
72
+ publish_attempted: number;
73
+ publish_sent: number;
74
+ received_total: number;
75
+ delivered_total: number;
76
+ dropped_malformed: number;
77
+ dropped_oversized: number;
78
+ dropped_namespace_mismatch: number;
79
+ dropped_timestamp_future_drift: number;
80
+ dropped_timestamp_past_drift: number;
81
+ dropped_decode_failed: number;
82
+ dropped_self: number;
83
+ dropped_topic_decode_error: number;
84
+ dropped_handler_error: number;
85
+ signaling_errors: number;
86
+ invalid_signaling_payload_total: number;
87
+ duplicate_sdp_total: number;
88
+ duplicate_ice_total: number;
89
+ start_errors: number;
90
+ stop_errors: number;
91
+ received_validated: number;
92
+ };
93
+ };
94
+ type DiscoveryEventType = "peer_joined" | "peer_stale" | "peer_removed" | "signaling_connected" | "signaling_disconnected" | "reconnect_started" | "reconnect_succeeded" | "reconnect_failed" | "malformed_signal_dropped" | "duplicate_signal_dropped";
95
+ type DiscoveryEvent = {
96
+ id: string;
97
+ type: DiscoveryEventType;
98
+ at: number;
99
+ peer_id?: string;
100
+ endpoint?: string;
101
+ detail?: string;
102
+ };
103
+ export declare class WebRTCPreviewAdapter implements NetworkAdapter {
104
+ private readonly peerId;
105
+ private readonly namespace;
106
+ private readonly signalingUrl;
107
+ private readonly signalingEndpoints;
108
+ private readonly room;
109
+ private readonly seedPeers;
110
+ private readonly bootstrapHints;
111
+ private readonly bootstrapSources;
112
+ private readonly maxMessageBytes;
113
+ private readonly pollIntervalMs;
114
+ private readonly maxFutureDriftMs;
115
+ private readonly maxPastDriftMs;
116
+ private readonly discoveryEventsLimit;
117
+ private readonly envelopeCodec;
118
+ private readonly topicCodec;
119
+ private readonly handlers;
120
+ private readonly sessions;
121
+ private started;
122
+ private poller;
123
+ private wrtc;
124
+ private processedSignalIds;
125
+ private signalingConnectivity;
126
+ private signalingIndex;
127
+ private activeSignalingEndpoint;
128
+ private discoveryEvents;
129
+ private discoveryEventsTotal;
130
+ private lastDiscoveryEventAt;
131
+ private signalingMessagesSentTotal;
132
+ private signalingMessagesReceivedTotal;
133
+ private reconnectAttemptsTotal;
134
+ private stats;
135
+ constructor(options?: WebRTCPreviewOptions);
136
+ start(): Promise<void>;
137
+ stop(): Promise<void>;
138
+ publish(topic: string, data: any): Promise<void>;
139
+ subscribe(topic: string, handler: (data: any) => void): void;
140
+ getDiagnostics(): WebRTCDiagnostics;
141
+ private resolveWebRTCImplementation;
142
+ private pollOnce;
143
+ private syncPeersFromSignaling;
144
+ private ensureSession;
145
+ private shouldAttemptConnect;
146
+ private attemptReconnect;
147
+ private createPeerConnection;
148
+ private bindDataChannel;
149
+ private handleSignalMessage;
150
+ private flushBufferedIce;
151
+ private onDataMessage;
152
+ private cleanupProcessedSignalIds;
153
+ private isInitiatorFor;
154
+ private closePeerSession;
155
+ private sendSignal;
156
+ private postJson;
157
+ private getJson;
158
+ private requestJson;
159
+ private markSignalingConnected;
160
+ private markSignalingDisconnected;
161
+ private recordDiscoveryEvent;
162
+ }
163
+ export {};