@automerge/automerge-repo-network-websocket 1.1.0-alpha.1 → 1.1.0-alpha.13

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,5 +1,5 @@
1
1
  /// <reference types="ws" />
2
- import { NetworkAdapter, type PeerId, type StorageId } from "@automerge/automerge-repo";
2
+ import { NetworkAdapter, PeerId, PeerMetadata } from "@automerge/automerge-repo";
3
3
  import WebSocket from "isomorphic-ws";
4
4
  import { FromClientMessage } from "./messages.js";
5
5
  declare abstract class WebSocketNetworkAdapter extends NetworkAdapter {
@@ -7,19 +7,20 @@ declare abstract class WebSocketNetworkAdapter extends NetworkAdapter {
7
7
  }
8
8
  export declare class BrowserWebSocketClientAdapter extends WebSocketNetworkAdapter {
9
9
  #private;
10
- timerId?: ReturnType<typeof setTimeout>;
10
+ readonly url: string;
11
+ readonly retryInterval: number;
11
12
  remotePeerId?: PeerId;
12
- url: string;
13
- constructor(url: string);
14
- connect(peerId: PeerId, storageId: StorageId | undefined, isEphemeral: boolean): void;
13
+ constructor(url: string, retryInterval?: number);
14
+ connect(peerId: PeerId, peerMetadata?: PeerMetadata): void;
15
15
  onOpen: () => void;
16
16
  onClose: () => void;
17
17
  onMessage: (event: WebSocket.MessageEvent) => void;
18
+ onError: (event: WebSocket.ErrorEvent) => void;
18
19
  join(): void;
19
20
  disconnect(): void;
20
21
  send(message: FromClientMessage): void;
21
- announceConnection(peerId: PeerId, storageId: StorageId | undefined, isEphemeral: boolean): void;
22
- receiveMessage(message: Uint8Array): void;
22
+ peerCandidate(remotePeerId: PeerId, peerMetadata: PeerMetadata): void;
23
+ receiveMessage(messageBytes: Uint8Array): void;
23
24
  }
24
25
  export {};
25
26
  //# sourceMappingURL=BrowserWebSocketClientAdapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"BrowserWebSocketClientAdapter.d.ts","sourceRoot":"","sources":["../src/BrowserWebSocketClientAdapter.ts"],"names":[],"mappings":";A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B,YAAY,CAAC,EAAE,MAAM,CAAA;gBAGH,GAAG,EAAE,MAAM,EACX,aAAa,SAAO;IAMtC,OAAO,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,CAAC,EAAE,YAAY;IAqCnD,MAAM,aAKL;IAGD,OAAO,aAWN;IAED,SAAS,UAAW,sBAAsB,UAEzC;IAED,OAAO,UAAW,oBAAoB,UAQrC;IAQD,IAAI;IAUJ,UAAU;IAMV,IAAI,CAAC,OAAO,EAAE,iBAAiB;IAY/B,aAAa,CAAC,YAAY,EAAE,MAAM,EAAE,YAAY,EAAE,YAAY;IAU9D,cAAc,CAAC,YAAY,EAAE,UAAU;CAiBxC"}
@@ -1,150 +1,153 @@
1
1
  import { NetworkAdapter, cbor, } from "@automerge/automerge-repo";
2
2
  import WebSocket from "isomorphic-ws";
3
3
  import debug from "debug";
4
+ import { isErrorMessage, isPeerMessage, } from "./messages.js";
4
5
  import { ProtocolV1 } from "./protocolVersion.js";
5
- const log = debug("WebsocketClient");
6
+ import { assert } from "./assert.js";
7
+ import { toArrayBuffer } from "./toArrayBuffer.js";
6
8
  class WebSocketNetworkAdapter extends NetworkAdapter {
7
9
  socket;
8
10
  }
9
11
  export class BrowserWebSocketClientAdapter extends WebSocketNetworkAdapter {
10
- // Type trickery required for platform independence,
11
- // see https://stackoverflow.com/questions/45802988/typescript-use-correct-version-of-settimeout-node-vs-window
12
- timerId;
13
- remotePeerId; // this adapter only connects to one remote client at a time
14
- #startupComplete = false;
15
12
  url;
16
- constructor(url) {
13
+ retryInterval;
14
+ #isReady = false;
15
+ #retryIntervalId;
16
+ #log = debug("automerge-repo:websocket:browser");
17
+ remotePeerId; // this adapter only connects to one remote client at a time
18
+ constructor(url, retryInterval = 5000) {
17
19
  super();
18
20
  this.url = url;
21
+ this.retryInterval = retryInterval;
22
+ this.#log = this.#log.extend(url);
19
23
  }
20
- connect(peerId, storageId, isEphemeral) {
21
- // If we're reconnecting make sure we remove the old event listeners
22
- // before creating a new connection.
23
- if (this.socket) {
24
+ connect(peerId, peerMetadata) {
25
+ if (!this.socket || !this.peerId) {
26
+ // first time connecting
27
+ this.#log("connecting");
28
+ this.peerId = peerId;
29
+ this.peerMetadata = peerMetadata ?? {};
30
+ }
31
+ else {
32
+ this.#log("reconnecting");
33
+ assert(peerId === this.peerId);
34
+ // Remove the old event listeners before creating a new connection.
24
35
  this.socket.removeEventListener("open", this.onOpen);
25
36
  this.socket.removeEventListener("close", this.onClose);
26
37
  this.socket.removeEventListener("message", this.onMessage);
38
+ this.socket.removeEventListener("error", this.onError);
27
39
  }
28
- if (!this.timerId) {
29
- this.timerId = setInterval(() => this.connect(peerId, storageId, isEphemeral), 5000);
30
- }
31
- this.peerId = peerId;
32
- this.storageId = storageId;
33
- this.isEphemeral = isEphemeral;
40
+ // Wire up retries
41
+ if (!this.#retryIntervalId)
42
+ this.#retryIntervalId = setInterval(() => {
43
+ this.connect(peerId, peerMetadata);
44
+ }, this.retryInterval);
34
45
  this.socket = new WebSocket(this.url);
35
46
  this.socket.binaryType = "arraybuffer";
36
47
  this.socket.addEventListener("open", this.onOpen);
37
48
  this.socket.addEventListener("close", this.onClose);
38
49
  this.socket.addEventListener("message", this.onMessage);
39
- // mark this adapter as ready if we haven't received an ack in 1 second.
50
+ this.socket.addEventListener("error", this.onError);
51
+ // Mark this adapter as ready if we haven't received an ack in 1 second.
40
52
  // We might hear back from the other end at some point but we shouldn't
41
53
  // hold up marking things as unavailable for any longer
42
- setTimeout(() => {
43
- if (!this.#startupComplete) {
44
- this.#startupComplete = true;
45
- this.emit("ready", { network: this });
46
- }
47
- }, 1000);
54
+ setTimeout(() => this.#ready(), 1000);
48
55
  this.join();
49
56
  }
50
57
  onOpen = () => {
51
- log(`@ ${this.url}: open`);
52
- clearInterval(this.timerId);
53
- this.timerId = undefined;
54
- this.send(joinMessage(this.peerId, this.storageId, this.isEphemeral));
58
+ this.#log("open");
59
+ clearInterval(this.#retryIntervalId);
60
+ this.#retryIntervalId = undefined;
61
+ this.join();
55
62
  };
56
63
  // When a socket closes, or disconnects, remove it from the array.
57
64
  onClose = () => {
58
- log(`${this.url}: close`);
59
- if (this.remotePeerId) {
65
+ this.#log("close");
66
+ if (this.remotePeerId)
60
67
  this.emit("peer-disconnected", { peerId: this.remotePeerId });
61
- }
62
- if (!this.timerId) {
63
- if (this.peerId) {
64
- this.connect(this.peerId, this.storageId, this.isEphemeral);
65
- }
66
- }
68
+ if (this.retryInterval > 0 && !this.#retryIntervalId)
69
+ // try to reconnect
70
+ setTimeout(() => {
71
+ assert(this.peerId);
72
+ return this.connect(this.peerId, this.peerMetadata);
73
+ }, this.retryInterval);
67
74
  };
68
75
  onMessage = (event) => {
69
76
  this.receiveMessage(event.data);
70
77
  };
71
- join() {
72
- if (!this.socket) {
73
- throw new Error("WTF, get a socket");
78
+ onError = (event) => {
79
+ const { code } = event.error;
80
+ if (code === "ECONNREFUSED") {
81
+ this.#log("Connection refused, retrying...");
74
82
  }
83
+ else {
84
+ /* c8 ignore next */
85
+ throw event.error;
86
+ }
87
+ };
88
+ #ready() {
89
+ if (this.#isReady)
90
+ return;
91
+ this.#isReady = true;
92
+ this.emit("ready", { network: this });
93
+ }
94
+ join() {
95
+ assert(this.peerId);
96
+ assert(this.socket);
75
97
  if (this.socket.readyState === WebSocket.OPEN) {
76
- this.send(joinMessage(this.peerId, this.storageId, this.isEphemeral));
98
+ this.send(joinMessage(this.peerId, this.peerMetadata));
77
99
  }
78
100
  else {
79
- // The onOpen handler automatically sends a join message
101
+ // We'll try again in the `onOpen` handler
80
102
  }
81
103
  }
82
104
  disconnect() {
83
- if (!this.socket) {
84
- throw new Error("WTF, get a socket");
85
- }
105
+ assert(this.peerId);
106
+ assert(this.socket);
86
107
  this.send({ type: "leave", senderId: this.peerId });
87
108
  }
88
109
  send(message) {
89
- if ("data" in message && message.data.byteLength === 0) {
90
- throw new Error("tried to send a zero-length message");
91
- }
92
- if (!this.peerId) {
93
- throw new Error("Why don't we have a PeerID?");
94
- }
95
- if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
96
- throw new Error("Websocket Socket not ready!");
97
- }
110
+ if ("data" in message && message.data?.byteLength === 0)
111
+ throw new Error("Tried to send a zero-length message");
112
+ assert(this.peerId);
113
+ assert(this.socket);
114
+ if (this.socket.readyState !== WebSocket.OPEN)
115
+ throw new Error(`Websocket not ready (${this.socket.readyState})`);
98
116
  const encoded = cbor.encode(message);
99
- // This incantation deals with websocket sending the whole
100
- // underlying buffer even if we just have a uint8array view on it
101
- const arrayBuf = encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
102
- this.socket?.send(arrayBuf);
117
+ this.socket.send(toArrayBuffer(encoded));
103
118
  }
104
- announceConnection(peerId, storageId, isEphemeral) {
105
- // return a peer object
106
- const myPeerId = this.peerId;
107
- if (!myPeerId) {
108
- throw new Error("we should have a peer ID by now");
109
- }
110
- if (!this.#startupComplete) {
111
- this.#startupComplete = true;
112
- this.emit("ready", { network: this });
113
- }
114
- this.remotePeerId = peerId;
115
- this.emit("peer-candidate", { peerId, storageId, isEphemeral });
119
+ peerCandidate(remotePeerId, peerMetadata) {
120
+ assert(this.socket);
121
+ this.#ready();
122
+ this.remotePeerId = remotePeerId;
123
+ this.emit("peer-candidate", {
124
+ peerId: remotePeerId,
125
+ peerMetadata,
126
+ });
116
127
  }
117
- receiveMessage(message) {
118
- const decoded = cbor.decode(new Uint8Array(message));
119
- const { type, senderId } = decoded;
120
- const socket = this.socket;
121
- if (!socket) {
122
- throw new Error("Missing socket at receiveMessage");
123
- }
124
- if (message.byteLength === 0) {
128
+ receiveMessage(messageBytes) {
129
+ const message = cbor.decode(new Uint8Array(messageBytes));
130
+ assert(this.socket);
131
+ if (messageBytes.byteLength === 0)
125
132
  throw new Error("received a zero-length message");
133
+ if (isPeerMessage(message)) {
134
+ const { peerMetadata } = message;
135
+ this.#log(`peer: ${message.senderId}`);
136
+ this.peerCandidate(message.senderId, peerMetadata);
126
137
  }
127
- switch (type) {
128
- case "peer": {
129
- const { storageId, isEphemeral } = decoded;
130
- log(`peer: ${senderId}`);
131
- this.announceConnection(senderId, storageId, isEphemeral);
132
- break;
133
- }
134
- case "error":
135
- log(`error: ${decoded.message}`);
136
- break;
137
- default:
138
- this.emit("message", decoded);
138
+ else if (isErrorMessage(message)) {
139
+ this.#log(`error: ${message.message}`);
140
+ }
141
+ else {
142
+ this.emit("message", message);
139
143
  }
140
144
  }
141
145
  }
142
- function joinMessage(senderId, storageId, isEphemeral) {
146
+ function joinMessage(senderId, peerMetadata) {
143
147
  return {
144
148
  type: "join",
145
149
  senderId,
146
- storageId,
147
- isEphemeral,
150
+ peerMetadata,
148
151
  supportedProtocolVersions: [ProtocolV1],
149
152
  };
150
153
  }
@@ -1,17 +1,19 @@
1
1
  /// <reference types="ws" />
2
2
  import WebSocket from "isomorphic-ws";
3
3
  import { type WebSocketServer } from "isomorphic-ws";
4
- import { NetworkAdapter, type PeerId, type StorageId } from "@automerge/automerge-repo";
4
+ import { NetworkAdapter, type PeerMetadata, type PeerId } from "@automerge/automerge-repo";
5
5
  import { FromServerMessage } from "./messages.js";
6
6
  export declare class NodeWSServerAdapter extends NetworkAdapter {
7
- server: WebSocketServer;
7
+ #private;
8
+ private server;
9
+ private keepAliveInterval;
8
10
  sockets: {
9
11
  [peerId: PeerId]: WebSocket;
10
12
  };
11
- constructor(server: WebSocketServer);
12
- connect(peerId: PeerId, storageId: StorageId | undefined, isEphemeral: boolean): void;
13
+ constructor(server: WebSocketServer, keepAliveInterval?: number);
14
+ connect(peerId: PeerId, peerMetadata: PeerMetadata): void;
13
15
  disconnect(): void;
14
16
  send(message: FromServerMessage): void;
15
- receiveMessage(message: Uint8Array, socket: WebSocket): void;
17
+ receiveMessage(messageBytes: Uint8Array, socket: WebSocket): void;
16
18
  }
17
19
  //# sourceMappingURL=NodeWSServerAdapter.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"NodeWSServerAdapter.d.ts","sourceRoot":"","sources":["../src/NodeWSServerAdap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AyClD,UAAU;IAQV,IAAI,CAAC,OAAO,EAAE,iBAAiB;IAqB/B,cAAc,CAAC,YAAY,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS;CA0E3D"}
@@ -2,31 +2,31 @@ import WebSocket from "isomorphic-ws";
2
2
  import debug from "debug";
3
3
  const log = debug("WebsocketServer");
4
4
  import { cbor as cborHelpers, NetworkAdapter, } from "@automerge/automerge-repo";
5
+ import { isJoinMessage, isLeaveMessage, } from "./messages.js";
5
6
  import { ProtocolV1 } from "./protocolVersion.js";
7
+ import assert from "assert";
8
+ import { toArrayBuffer } from "./toArrayBuffer.js";
6
9
  const { encode, decode } = cborHelpers;
7
10
  export class NodeWSServerAdapter extends NetworkAdapter {
8
11
  server;
12
+ keepAliveInterval;
9
13
  sockets = {};
10
- constructor(server) {
14
+ constructor(server, keepAliveInterval = 5000) {
11
15
  super();
12
16
  this.server = server;
17
+ this.keepAliveInterval = keepAliveInterval;
13
18
  }
14
- connect(peerId, storageId, isEphemeral) {
19
+ connect(peerId, peerMetadata) {
15
20
  this.peerId = peerId;
16
- this.storageId = storageId;
17
- this.isEphemeral = isEphemeral;
18
- this.server.on("close", function close() {
19
- clearInterval(interval);
21
+ this.peerMetadata = peerMetadata;
22
+ this.server.on("close", () => {
23
+ clearInterval(keepAliveId);
24
+ this.disconnect();
20
25
  });
21
26
  this.server.on("connection", (socket) => {
22
27
  // When a socket closes, or disconnects, remove it from our list
23
28
  socket.on("close", () => {
24
- for (const [otherPeerId, otherSocket] of Object.entries(this.sockets)) {
25
- if (socket === otherSocket) {
26
- this.emit("peer-disconnected", { peerId: otherPeerId });
27
- delete this.sockets[otherPeerId];
28
- }
29
- }
29
+ this.#removeSocket(socket);
30
30
  });
31
31
  socket.on("message", message => this.receiveMessage(message, socket));
32
32
  // Start out "alive", and every time we get a pong, reset that state.
@@ -34,117 +34,117 @@ export class NodeWSServerAdapter extends NetworkAdapter {
34
34
  socket.on("pong", () => (socket.isAlive = true));
35
35
  this.emit("ready", { network: this });
36
36
  });
37
- // Every interval, terminate connections to lost clients,
38
- // then mark all clients as potentially dead and then ping them.
39
- const interval = setInterval(() => {
40
- ;
41
- this.server.clients.forEach(socket => {
42
- if (socket.isAlive === false) {
43
- // Make sure we clean up this socket even though we're terminating.
44
- // This might be unnecessary but I have read reports of the close() not happening for 30s.
45
- for (const [otherPeerId, otherSocket] of Object.entries(this.sockets)) {
46
- if (socket === otherSocket) {
47
- this.emit("peer-disconnected", { peerId: otherPeerId });
48
- delete this.sockets[otherPeerId];
49
- }
50
- }
51
- return socket.terminate();
37
+ const keepAliveId = setInterval(() => {
38
+ // Terminate connections to lost clients
39
+ const clients = this.server.clients;
40
+ clients.forEach(socket => {
41
+ if (socket.isAlive) {
42
+ // Mark all clients as potentially dead until we hear from them
43
+ socket.isAlive = false;
44
+ socket.ping();
45
+ }
46
+ else {
47
+ this.#terminate(socket);
52
48
  }
53
- socket.isAlive = false;
54
- socket.ping();
55
49
  });
56
- }, 5000);
50
+ }, this.keepAliveInterval);
57
51
  }
58
52
  disconnect() {
59
- // throw new Error("The server doesn't join channels.")
53
+ const clients = this.server.clients;
54
+ clients.forEach(socket => {
55
+ this.#terminate(socket);
56
+ this.#removeSocket(socket);
57
+ });
60
58
  }
61
59
  send(message) {
62
- if ("data" in message && message.data.byteLength === 0) {
63
- throw new Error("tried to send a zero-length message");
64
- }
60
+ assert("targetId" in message && message.targetId !== undefined);
61
+ if ("data" in message && message.data?.byteLength === 0)
62
+ throw new Error("Tried to send a zero-length message");
65
63
  const senderId = this.peerId;
66
- if (!senderId) {
67
- throw new Error("No peerId set for the websocket server network adapter.");
68
- }
69
- if (this.sockets[message.targetId] === undefined) {
70
- log(`Tried to send message to disconnected peer: ${message.targetId}`);
64
+ assert(senderId, "No peerId set for the websocket server network adapter.");
65
+ const socket = this.sockets[message.targetId];
66
+ if (!socket) {
67
+ log(`Tried to send to disconnected peer: ${message.targetId}`);
71
68
  return;
72
69
  }
73
70
  const encoded = encode(message);
74
- // This incantation deals with websocket sending the whole
75
- // underlying buffer even if we just have a uint8array view on it
76
- const arrayBuf = encoded.buffer.slice(encoded.byteOffset, encoded.byteOffset + encoded.byteLength);
77
- this.sockets[message.targetId]?.send(arrayBuf);
71
+ const arrayBuf = toArrayBuffer(encoded);
72
+ socket.send(arrayBuf);
78
73
  }
79
- receiveMessage(message, socket) {
80
- const cbor = decode(message);
81
- const { type, senderId } = cbor;
74
+ receiveMessage(messageBytes, socket) {
75
+ const message = decode(messageBytes);
76
+ const { type, senderId } = message;
82
77
  const myPeerId = this.peerId;
83
- if (!myPeerId) {
84
- throw new Error("Missing my peer ID.");
85
- }
86
- log(`[${senderId}->${myPeerId}${"documentId" in cbor ? "@" + cbor.documentId : ""}] ${type} | ${message.byteLength} bytes`);
87
- switch (type) {
88
- case "join":
89
- {
90
- const existingSocket = this.sockets[senderId];
91
- if (existingSocket) {
92
- if (existingSocket.readyState === WebSocket.OPEN) {
93
- existingSocket.close();
94
- }
95
- this.emit("peer-disconnected", { peerId: senderId });
96
- }
97
- const { storageId, isEphemeral } = cbor;
98
- // Let the rest of the system know that we have a new connection.
99
- this.emit("peer-candidate", {
100
- peerId: senderId,
101
- storageId,
102
- isEphemeral,
103
- });
104
- this.sockets[senderId] = socket;
105
- // In this client-server connection, there's only ever one peer: us!
106
- // (and we pretend to be joined to every channel)
107
- const selectedProtocolVersion = selectProtocol(cbor.supportedProtocolVersions);
108
- if (selectedProtocolVersion === null) {
109
- this.send({
110
- type: "error",
111
- senderId: this.peerId,
112
- message: "unsupported protocol version",
113
- targetId: senderId,
114
- });
115
- this.sockets[senderId].close();
116
- delete this.sockets[senderId];
117
- }
118
- else {
119
- this.send({
120
- type: "peer",
121
- senderId: this.peerId,
122
- storageId: this.storageId,
123
- isEphemeral: this.isEphemeral,
124
- selectedProtocolVersion: ProtocolV1,
125
- targetId: senderId,
126
- });
127
- }
78
+ assert(myPeerId);
79
+ const documentId = "documentId" in message ? "@" + message.documentId : "";
80
+ const { byteLength } = messageBytes;
81
+ log(`[${senderId}->${myPeerId}${documentId}] ${type} | ${byteLength} bytes`);
82
+ if (isJoinMessage(message)) {
83
+ const { peerMetadata, supportedProtocolVersions } = message;
84
+ const existingSocket = this.sockets[senderId];
85
+ if (existingSocket) {
86
+ if (existingSocket.readyState === WebSocket.OPEN) {
87
+ existingSocket.close();
128
88
  }
129
- break;
130
- case "leave":
131
- // It doesn't seem like this gets called;
132
- // we handle leaving in the socket close logic
133
- // TODO: confirm this
134
- // ?
135
- break;
136
- default:
137
- this.emit("message", cbor);
138
- break;
89
+ this.emit("peer-disconnected", { peerId: senderId });
90
+ }
91
+ // Let the repo know that we have a new connection.
92
+ this.emit("peer-candidate", { peerId: senderId, peerMetadata });
93
+ this.sockets[senderId] = socket;
94
+ const selectedProtocolVersion = selectProtocol(supportedProtocolVersions);
95
+ if (selectedProtocolVersion === null) {
96
+ this.send({
97
+ type: "error",
98
+ senderId: this.peerId,
99
+ message: "unsupported protocol version",
100
+ targetId: senderId,
101
+ });
102
+ this.sockets[senderId].close();
103
+ delete this.sockets[senderId];
104
+ }
105
+ else {
106
+ this.send({
107
+ type: "peer",
108
+ senderId: this.peerId,
109
+ peerMetadata: this.peerMetadata,
110
+ selectedProtocolVersion: ProtocolV1,
111
+ targetId: senderId,
112
+ });
113
+ }
114
+ }
115
+ else if (isLeaveMessage(message)) {
116
+ const { senderId } = message;
117
+ const socket = this.sockets[senderId];
118
+ /* c8 ignore next */
119
+ if (!socket)
120
+ return;
121
+ this.#terminate(socket);
139
122
  }
123
+ else {
124
+ this.emit("message", message);
125
+ }
126
+ }
127
+ #terminate(socket) {
128
+ this.#removeSocket(socket);
129
+ socket.terminate();
130
+ }
131
+ #removeSocket(socket) {
132
+ const peerId = this.#peerIdBySocket(socket);
133
+ if (!peerId)
134
+ return;
135
+ this.emit("peer-disconnected", { peerId });
136
+ delete this.sockets[peerId];
140
137
  }
138
+ #peerIdBySocket = (socket) => {
139
+ const isThisSocket = (peerId) => this.sockets[peerId] === socket;
140
+ const result = Object.keys(this.sockets).find(isThisSocket);
141
+ return result ?? null;
142
+ };
141
143
  }
142
- function selectProtocol(versions) {
143
- if (versions === undefined) {
144
+ const selectProtocol = (versions) => {
145
+ if (versions === undefined)
144
146
  return ProtocolV1;
145
- }
146
- if (versions.includes(ProtocolV1)) {
147
+ if (versions.includes(ProtocolV1))
147
148
  return ProtocolV1;
148
- }
149
149
  return null;
150
- }
150
+ };
@@ -0,0 +1,3 @@
1
+ export declare function assert(value: boolean, message?: string): asserts value;
2
+ export declare function assert<T>(value: T | undefined, message?: string): asserts value is T;
3
+ //# sourceMappingURL=assert.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assert.d.ts","sourceRoot":"","sources":["../src/assert.ts"],"names":[],"mappings":"AAEA,wBAAgB,MAAM,CAAC,KAAK,EAAE,OAAO,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,KAAK,CAAA;AACvE,wBAAgB,MAAM,CAAC,CAAC,EACtB,KAAK,EAAE,CAAC,GAAG,SAAS,EACpB,OAAO,CAAC,EAAE,MAAM,GACf,OAAO,CAAC,KAAK,IAAI,CAAC,CAAA"}
package/dist/assert.js ADDED
@@ -0,0 +1,17 @@
1
+ /* c8 ignore start */
2
+ export function assert(value, message = "Assertion failed") {
3
+ if (value === false || value === null || value === undefined) {
4
+ const error = new Error(trimLines(message));
5
+ error.stack = removeLine(error.stack, "assert.ts");
6
+ throw error;
7
+ }
8
+ }
9
+ const trimLines = (s) => s
10
+ .split("\n")
11
+ .map(s => s.trim())
12
+ .join("\n");
13
+ const removeLine = (s = "", targetText) => s
14
+ .split("\n")
15
+ .filter(line => !line.includes(targetText))
16
+ .join("\n");
17
+ /* c8 ignore end */
@@ -1,4 +1,4 @@
1
- import type { Message, PeerId, StorageId } from "@automerge/automerge-repo";
1
+ import type { Message, PeerId, PeerMetadata } from "@automerge/automerge-repo";
2
2
  import type { ProtocolVersion } from "./protocolVersion.js";
3
3
  /** The sender is disconnecting */
4
4
  export type LeaveMessage = {
@@ -10,11 +10,8 @@ export type JoinMessage = {
10
10
  type: "join";
11
11
  /** The PeerID of the client */
12
12
  senderId: PeerId;
13
- /** Unique ID of the storage that the sender peer is using, is persistent across sessions */
14
- storageId?: StorageId;
15
- /** Indicates whether other peers should persist the sync state of the sender peer.
16
- * Sync state is only persisted for non-ephemeral peers */
17
- isEphemeral: boolean;
13
+ /** Metadata presented by the peer */
14
+ peerMetadata: PeerMetadata;
18
15
  /** The protocol version the client supports */
19
16
  supportedProtocolVersions: ProtocolVersion[];
20
17
  };
@@ -23,11 +20,8 @@ export type PeerMessage = {
23
20
  type: "peer";
24
21
  /** The PeerID of the server */
25
22
  senderId: PeerId;
26
- /** Unique ID of the storage that the sender peer is using, is persistent across sessions */
27
- storageId?: StorageId;
28
- /** Indicates whether other peers should persist the sync state of the sender peer.
29
- * Sync state is only persisted for non-ephemeral peers */
30
- isEphemeral: boolean;
23
+ /** Metadata presented by the peer */
24
+ peerMetadata: PeerMetadata;
31
25
  /** The protocol version the server selected for this connection */
32
26
  selectedProtocolVersion: ProtocolVersion;
33
27
  /** The PeerID of the client */
@@ -47,4 +41,8 @@ export type ErrorMessage = {
47
41
  export type FromClientMessage = JoinMessage | LeaveMessage | Message;
48
42
  /** A message from the server to the client */
49
43
  export type FromServerMessage = PeerMessage | ErrorMessage | Message;
44
+ export declare const isJoinMessage: (message: FromClientMessage) => message is JoinMessage;
45
+ export declare const isLeaveMessage: (message: FromClientMessage) => message is LeaveMessage;
46
+ export declare const isPeerMessage: (message: FromServerMessage) => message is PeerMessage;
47
+ export declare const isErrorMessage: (message: FromServerMessage) => message is ErrorMessage;
50
48
  //# sourceMappingURL=messages.d.ts.map