@replit/river 0.12.5 → 0.13.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.
Files changed (51) hide show
  1. package/README.md +4 -1
  2. package/dist/{builder-c593de11.d.ts → builder-169fbf7f.d.ts} +16 -7
  3. package/dist/{chunk-AFLZ6INU.js → chunk-CBRQM65K.js} +29 -10
  4. package/dist/{chunk-IIBVKYDB.js → chunk-CDH7QSB4.js} +39 -1
  5. package/dist/{chunk-XFFS4UOD.js → chunk-MGGIUH5O.js} +7 -7
  6. package/dist/{chunk-6OAKPO5R.js → chunk-NPXAAD7M.js} +1 -1
  7. package/dist/{chunk-2PKONGC3.js → chunk-R2IMXRVU.js} +160 -135
  8. package/dist/{connection-4a839b9a.d.ts → connection-ab681c08.d.ts} +1 -1
  9. package/dist/{messageFraming-b200ef25.d.ts → connection-dd789651.d.ts} +17 -2
  10. package/dist/{index-1afc5580.d.ts → index-21c1b21d.d.ts} +32 -18
  11. package/dist/router/index.cjs +31 -13
  12. package/dist/router/index.d.cts +5 -5
  13. package/dist/router/index.d.ts +5 -5
  14. package/dist/router/index.js +2 -2
  15. package/dist/transport/impls/uds/client.cjs +153 -140
  16. package/dist/transport/impls/uds/client.d.cts +2 -3
  17. package/dist/transport/impls/uds/client.d.ts +2 -3
  18. package/dist/transport/impls/uds/client.js +5 -6
  19. package/dist/transport/impls/uds/server.cjs +161 -146
  20. package/dist/transport/impls/uds/server.d.cts +2 -3
  21. package/dist/transport/impls/uds/server.d.ts +2 -3
  22. package/dist/transport/impls/uds/server.js +4 -5
  23. package/dist/transport/impls/ws/client.cjs +157 -142
  24. package/dist/transport/impls/ws/client.d.cts +4 -4
  25. package/dist/transport/impls/ws/client.d.ts +4 -4
  26. package/dist/transport/impls/ws/client.js +7 -7
  27. package/dist/transport/impls/ws/server.cjs +161 -146
  28. package/dist/transport/impls/ws/server.d.cts +2 -2
  29. package/dist/transport/impls/ws/server.d.ts +2 -2
  30. package/dist/transport/impls/ws/server.js +4 -4
  31. package/dist/transport/index.cjs +212 -186
  32. package/dist/transport/index.d.cts +1 -1
  33. package/dist/transport/index.d.ts +1 -1
  34. package/dist/transport/index.js +3 -3
  35. package/dist/util/testHelpers.cjs +294 -16
  36. package/dist/util/testHelpers.d.cts +2 -2
  37. package/dist/util/testHelpers.d.ts +2 -2
  38. package/dist/util/testHelpers.js +30 -8
  39. package/package.json +1 -9
  40. package/dist/chunk-7J66WOIC.js +0 -44
  41. package/dist/chunk-H4QR2K3T.js +0 -47
  42. package/dist/connection-64b9e0ff.d.ts +0 -17
  43. package/dist/connection-a6cc48e8.d.ts +0 -18
  44. package/dist/transport/impls/stdio/client.cjs +0 -913
  45. package/dist/transport/impls/stdio/client.d.cts +0 -27
  46. package/dist/transport/impls/stdio/client.d.ts +0 -27
  47. package/dist/transport/impls/stdio/client.js +0 -42
  48. package/dist/transport/impls/stdio/server.cjs +0 -888
  49. package/dist/transport/impls/stdio/server.d.cts +0 -25
  50. package/dist/transport/impls/stdio/server.d.ts +0 -25
  51. package/dist/transport/impls/stdio/server.js +0 -33
@@ -42,8 +42,8 @@ var TransportMessageSchema = (t) => import_typebox.Type.Object({
42
42
  to: import_typebox.Type.String(),
43
43
  seq: import_typebox.Type.Integer(),
44
44
  ack: import_typebox.Type.Integer(),
45
- serviceName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
46
- procedureName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
45
+ serviceName: import_typebox.Type.Optional(import_typebox.Type.String()),
46
+ procedureName: import_typebox.Type.Optional(import_typebox.Type.String()),
47
47
  streamId: import_typebox.Type.String(),
48
48
  controlFlags: import_typebox.Type.Integer(),
49
49
  payload: t
@@ -57,7 +57,7 @@ var ControlMessageCloseSchema = import_typebox.Type.Object({
57
57
  var PROTOCOL_VERSION = "v1";
58
58
  var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
59
59
  type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
60
- protocolVersion: import_typebox.Type.Literal(PROTOCOL_VERSION),
60
+ protocolVersion: import_typebox.Type.String(),
61
61
  instanceId: import_typebox.Type.String()
62
62
  });
63
63
  var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
@@ -82,7 +82,7 @@ var ControlMessagePayloadSchema = import_typebox.Type.Union([
82
82
  var OpaqueTransportMessageSchema = TransportMessageSchema(
83
83
  import_typebox.Type.Unknown()
84
84
  );
85
- function bootRequestMessage(from, to, instanceId) {
85
+ function handshakeRequestMessage(from, to, instanceId) {
86
86
  return {
87
87
  id: (0, import_nanoid.nanoid)(),
88
88
  from,
@@ -98,7 +98,7 @@ function bootRequestMessage(from, to, instanceId) {
98
98
  }
99
99
  };
100
100
  }
101
- function bootResponseMessage(from, instanceId, to, ok) {
101
+ function handshakeResponseMessage(from, instanceId, to, ok) {
102
102
  return {
103
103
  id: (0, import_nanoid.nanoid)(),
104
104
  from,
@@ -159,6 +159,60 @@ var EventDispatcher = class {
159
159
 
160
160
  // transport/session.ts
161
161
  var import_nanoid2 = require("nanoid");
162
+
163
+ // codec/json.ts
164
+ var encoder = new TextEncoder();
165
+ var decoder = new TextDecoder();
166
+ function uint8ArrayToBase64(uint8Array) {
167
+ let binary = "";
168
+ uint8Array.forEach((byte) => {
169
+ binary += String.fromCharCode(byte);
170
+ });
171
+ return btoa(binary);
172
+ }
173
+ function base64ToUint8Array(base64) {
174
+ const binaryString = atob(base64);
175
+ const uint8Array = new Uint8Array(binaryString.length);
176
+ for (let i = 0; i < binaryString.length; i++) {
177
+ uint8Array[i] = binaryString.charCodeAt(i);
178
+ }
179
+ return uint8Array;
180
+ }
181
+ var NaiveJsonCodec = {
182
+ toBuffer: (obj) => {
183
+ return encoder.encode(
184
+ JSON.stringify(obj, function replacer(key) {
185
+ const val = this[key];
186
+ if (val instanceof Uint8Array) {
187
+ return { $t: uint8ArrayToBase64(val) };
188
+ } else {
189
+ return val;
190
+ }
191
+ })
192
+ );
193
+ },
194
+ fromBuffer: (buff) => {
195
+ try {
196
+ const parsed = JSON.parse(
197
+ decoder.decode(buff),
198
+ function reviver(_key, val) {
199
+ if (val?.$t) {
200
+ return base64ToUint8Array(val.$t);
201
+ } else {
202
+ return val;
203
+ }
204
+ }
205
+ );
206
+ if (typeof parsed === "object")
207
+ return parsed;
208
+ return null;
209
+ } catch {
210
+ return null;
211
+ }
212
+ }
213
+ };
214
+
215
+ // transport/session.ts
162
216
  var nanoid2 = (0, import_nanoid2.customAlphabet)("1234567890abcdefghijklmnopqrstuvxyz", 6);
163
217
  var unsafeId = () => nanoid2();
164
218
  var Connection = class {
@@ -170,8 +224,15 @@ var Connection = class {
170
224
  var HEARTBEAT_INTERVAL_MS = 1e3;
171
225
  var HEARTBEATS_TILL_DEAD = 2;
172
226
  var SESSION_DISCONNECT_GRACE_MS = 5e3;
227
+ var defaultSessionOptions = {
228
+ heartbeatIntervalMs: HEARTBEAT_INTERVAL_MS,
229
+ heartbeatsUntilDead: HEARTBEATS_TILL_DEAD,
230
+ sessionDisconnectGraceMs: SESSION_DISCONNECT_GRACE_MS,
231
+ codec: NaiveJsonCodec
232
+ };
173
233
  var Session = class {
174
234
  codec;
235
+ options;
175
236
  /**
176
237
  * The buffer of messages that have been sent but not yet acknowledged.
177
238
  */
@@ -207,16 +268,17 @@ var Session = class {
207
268
  * The interval for sending heartbeats.
208
269
  */
209
270
  heartbeat;
210
- constructor(codec, from, connectedTo, conn) {
271
+ constructor(from, connectedTo, conn, options) {
272
+ this.options = options;
211
273
  this.debugId = `sess-${unsafeId()}`;
212
274
  this.from = from;
213
275
  this.to = connectedTo;
214
276
  this.connection = conn;
215
- this.codec = codec;
277
+ this.codec = options.codec;
216
278
  this.heartbeatMisses = 0;
217
279
  this.heartbeat = setInterval(
218
280
  () => this.sendHeartbeat(),
219
- HEARTBEAT_INTERVAL_MS
281
+ options.heartbeatIntervalMs
220
282
  );
221
283
  }
222
284
  /**
@@ -252,7 +314,7 @@ var Session = class {
252
314
  return fullMsg.id;
253
315
  }
254
316
  sendHeartbeat() {
255
- if (this.heartbeatMisses >= HEARTBEATS_TILL_DEAD) {
317
+ if (this.heartbeatMisses >= this.options.heartbeatsUntilDead) {
256
318
  if (this.connection) {
257
319
  log?.info(
258
320
  `${this.from} -- closing connection (id: ${this.connection.debugId}) to ${this.to} due to inactivity`
@@ -318,13 +380,11 @@ var Session = class {
318
380
  this.cancelGrace();
319
381
  this.connection = newConn;
320
382
  }
321
- graceCb;
322
383
  beginGrace(cb) {
323
- this.graceCb = cb;
324
384
  this.disconnectionGrace = setTimeout(() => {
325
385
  this.close();
326
386
  cb();
327
- }, SESSION_DISCONNECT_GRACE_MS);
387
+ }, this.options.sessionDisconnectGraceMs);
328
388
  }
329
389
  // called on reconnect of the underlying session
330
390
  cancelGrace() {
@@ -336,8 +396,8 @@ var Session = class {
336
396
  close() {
337
397
  this.closeStaleConnection(this.connection);
338
398
  this.cancelGrace();
339
- clearInterval(this.heartbeat);
340
399
  this.resetBufferedMessages();
400
+ clearInterval(this.heartbeat);
341
401
  }
342
402
  get connected() {
343
403
  return this.connection !== void 0;
@@ -362,58 +422,6 @@ var Session = class {
362
422
  }
363
423
  };
364
424
 
365
- // codec/json.ts
366
- var encoder = new TextEncoder();
367
- var decoder = new TextDecoder();
368
- function uint8ArrayToBase64(uint8Array) {
369
- let binary = "";
370
- uint8Array.forEach((byte) => {
371
- binary += String.fromCharCode(byte);
372
- });
373
- return btoa(binary);
374
- }
375
- function base64ToUint8Array(base64) {
376
- const binaryString = atob(base64);
377
- const uint8Array = new Uint8Array(binaryString.length);
378
- for (let i = 0; i < binaryString.length; i++) {
379
- uint8Array[i] = binaryString.charCodeAt(i);
380
- }
381
- return uint8Array;
382
- }
383
- var NaiveJsonCodec = {
384
- toBuffer: (obj) => {
385
- return encoder.encode(
386
- JSON.stringify(obj, function replacer(key) {
387
- const val = this[key];
388
- if (val instanceof Uint8Array) {
389
- return { $t: uint8ArrayToBase64(val) };
390
- } else {
391
- return val;
392
- }
393
- })
394
- );
395
- },
396
- fromBuffer: (buff) => {
397
- try {
398
- const parsed = JSON.parse(
399
- decoder.decode(buff),
400
- function reviver(_key, val) {
401
- if (val?.$t) {
402
- return base64ToUint8Array(val.$t);
403
- } else {
404
- return val;
405
- }
406
- }
407
- );
408
- if (typeof parsed === "object")
409
- return parsed;
410
- return null;
411
- } catch {
412
- return null;
413
- }
414
- }
415
- };
416
-
417
425
  // transport/transport.ts
418
426
  var import_nanoid3 = require("nanoid");
419
427
 
@@ -426,13 +434,13 @@ function coerceErrorString(err) {
426
434
  }
427
435
 
428
436
  // transport/transport.ts
429
- var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
430
- var DEFAULT_RECONNECT_INTERVAL_MS = 250;
437
+ var RECONNECT_JITTER_MAX_MS = 500;
438
+ var RECONNECT_INTERVAL_MS = 250;
431
439
  var defaultTransportOptions = {
432
- retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
433
- retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
440
+ retryIntervalMs: RECONNECT_INTERVAL_MS,
441
+ retryJitterMs: RECONNECT_JITTER_MAX_MS,
434
442
  retryAttemptsMax: 5,
435
- codec: NaiveJsonCodec
443
+ ...defaultSessionOptions
436
444
  };
437
445
  var Transport = class {
438
446
  /**
@@ -489,15 +497,6 @@ var Transport = class {
489
497
  this.clientId = clientId;
490
498
  this.state = "open";
491
499
  }
492
- sessionByClientId(clientId) {
493
- const session = this.sessions.get(clientId);
494
- if (!session) {
495
- const err = `${this.clientId} -- (invariant violation) no existing session for ${clientId}`;
496
- log?.error(err);
497
- throw new Error(err);
498
- }
499
- return session;
500
- }
501
500
  /**
502
501
  * Called when a new connection is established
503
502
  * and we know the identity of the connected client.
@@ -512,7 +511,7 @@ var Transport = class {
512
511
  const lastInstanceId = this.connectedInstanceIds.get(connectedTo);
513
512
  if (oldSession && lastInstanceId !== void 0 && lastInstanceId !== instanceId) {
514
513
  log?.warn(
515
- `${this.clientId} -- handshake from ${connectedTo} is a different instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
514
+ `${this.clientId} -- connection from ${connectedTo} is a different instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
516
515
  );
517
516
  oldSession.close();
518
517
  this.deleteSession(oldSession);
@@ -535,10 +534,10 @@ var Transport = class {
535
534
  }
536
535
  createSession(connectedTo, conn) {
537
536
  const session = new Session(
538
- this.codec,
539
537
  this.clientId,
540
538
  connectedTo,
541
- conn
539
+ conn,
540
+ this.options
542
541
  );
543
542
  this.sessions.set(session.to, session);
544
543
  this.eventDispatcher.dispatchEvent("sessionStatus", {
@@ -567,13 +566,10 @@ var Transport = class {
567
566
  status: "disconnect",
568
567
  conn
569
568
  });
570
- if (this.state !== "open")
569
+ const session = this.sessions.get(connectedTo);
570
+ if (!session)
571
571
  return;
572
- const session = this.sessionByClientId(connectedTo);
573
- log?.info(
574
- `${this.clientId} -- connection (id: ${conn.debugId}) disconnect from ${connectedTo}, ${SESSION_DISCONNECT_GRACE_MS}ms until session (id: ${session.debugId}) disconnect`
575
- );
576
- session.closeStaleConnection(conn);
572
+ session.connection = void 0;
577
573
  session.beginGrace(() => this.deleteSession(session));
578
574
  }
579
575
  /**
@@ -584,7 +580,7 @@ var Transport = class {
584
580
  parseMsg(msg) {
585
581
  const parsedMsg = this.codec.fromBuffer(msg);
586
582
  if (parsedMsg === null) {
587
- const decodedBuffer = new TextDecoder().decode(msg);
583
+ const decodedBuffer = new TextDecoder().decode(Buffer.from(msg));
588
584
  log?.error(
589
585
  `${this.clientId} -- received malformed msg, killing conn: ${decodedBuffer}`
590
586
  );
@@ -598,11 +594,7 @@ var Transport = class {
598
594
  );
599
595
  return null;
600
596
  }
601
- return {
602
- ...parsedMsg,
603
- serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
604
- procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
605
- };
597
+ return parsedMsg;
606
598
  }
607
599
  /**
608
600
  * Called when a message is received by this transport.
@@ -612,15 +604,27 @@ var Transport = class {
612
604
  handleMsg(msg) {
613
605
  if (this.state !== "open")
614
606
  return;
615
- const session = this.sessionByClientId(msg.from);
607
+ const session = this.sessions.get(msg.from);
608
+ if (!session) {
609
+ const err = `${this.clientId} -- (invariant violation) no existing session for ${msg.from}`;
610
+ log?.error(err);
611
+ return;
612
+ }
616
613
  session.cancelGrace();
617
614
  log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
618
615
  if (msg.seq !== session.nextExpectedSeq) {
619
- log?.warn(
620
- `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
621
- msg
622
- )}`
623
- );
616
+ if (msg.seq < session.nextExpectedSeq) {
617
+ log?.debug(
618
+ `${this.clientId} -- received duplicate msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
619
+ msg
620
+ )}`
621
+ );
622
+ } else {
623
+ log?.error(
624
+ `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), marking connection as dead: ${JSON.stringify(msg)}`
625
+ );
626
+ session.closeStaleConnection(session.connection);
627
+ }
624
628
  return;
625
629
  }
626
630
  if (!isAck(msg.controlFlags)) {
@@ -638,7 +642,7 @@ var Transport = class {
638
642
  }
639
643
  /**
640
644
  * Removes a listener from this transport.
641
- * @param the type of event to unlisten on
645
+ * @param the type of event to un-listen on
642
646
  * @param handler The message handler to remove.
643
647
  */
644
648
  removeEventListener(type, handler) {
@@ -715,23 +719,31 @@ var ClientTransport = class extends Transport {
715
719
  */
716
720
  inflightConnectionPromises;
717
721
  tryReconnecting = true;
718
- constructor(clientId, providedOptions) {
722
+ connectedTo;
723
+ constructor(clientId, connectedTo, providedOptions) {
719
724
  super(clientId, providedOptions);
725
+ this.connectedTo = connectedTo;
720
726
  this.inflightConnectionPromises = /* @__PURE__ */ new Map();
721
727
  }
722
728
  handleConnection(conn, to) {
723
- const bootHandler = this.receiveWithBootSequence(conn, () => {
724
- conn.removeDataListener(bootHandler);
725
- conn.addDataListener((data) => {
726
- const parsed = this.parseMsg(data);
729
+ const handshakeHandler = (data) => {
730
+ const handshake = this.receiveHandshakeResponseMessage(data);
731
+ if (!handshake) {
732
+ conn.close();
733
+ return;
734
+ }
735
+ this.onConnect(conn, handshake.from, handshake.instanceId);
736
+ conn.removeDataListener(handshakeHandler);
737
+ conn.addDataListener((data2) => {
738
+ const parsed = this.parseMsg(data2);
727
739
  if (!parsed) {
728
740
  conn.close();
729
741
  return;
730
742
  }
731
743
  this.handleMsg(parsed);
732
744
  });
733
- });
734
- conn.addDataListener(bootHandler);
745
+ };
746
+ conn.addDataListener(handshakeHandler);
735
747
  conn.addCloseListener(() => {
736
748
  this.onDisconnect(conn, to);
737
749
  void this.connect(to);
@@ -742,6 +754,32 @@ var ClientTransport = class extends Transport {
742
754
  );
743
755
  });
744
756
  }
757
+ receiveHandshakeResponseMessage(data) {
758
+ const parsed = this.parseMsg(data);
759
+ if (!parsed)
760
+ return false;
761
+ if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
762
+ log?.warn(
763
+ `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(
764
+ parsed
765
+ )}`
766
+ );
767
+ return false;
768
+ }
769
+ if (!parsed.payload.status.ok) {
770
+ log?.warn(
771
+ `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
772
+ parsed
773
+ )}`
774
+ );
775
+ return false;
776
+ }
777
+ const instanceId = parsed.payload.status.instanceId;
778
+ log?.debug(
779
+ `${this.clientId} -- handshake from ${parsed.from} ok (instance: ${instanceId})`
780
+ );
781
+ return { instanceId, from: parsed.from };
782
+ }
745
783
  /**
746
784
  * Manually attempts to connect to a client.
747
785
  * @param to The client ID of the node to connect to.
@@ -760,10 +798,7 @@ var ClientTransport = class extends Transport {
760
798
  }
761
799
  try {
762
800
  const conn = await reconnectPromise;
763
- this.state = "open";
764
- const requestMsg = bootRequestMessage(this.clientId, to, this.instanceId);
765
- log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
766
- conn.send(this.codec.toBuffer(requestMsg));
801
+ this.sendHandshake(to, conn);
767
802
  } catch (error) {
768
803
  const errStr = coerceErrorString(error);
769
804
  this.inflightConnectionPromises.delete(to);
@@ -781,34 +816,14 @@ var ClientTransport = class extends Transport {
781
816
  }
782
817
  }
783
818
  }
784
- receiveWithBootSequence(conn, sessionCb) {
785
- const bootHandler = (data) => {
786
- const parsed = this.parseMsg(data);
787
- if (!parsed) {
788
- conn.close();
789
- return;
790
- }
791
- if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
792
- log?.warn(
793
- `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
794
- );
795
- return;
796
- }
797
- if (!parsed.payload.status.ok) {
798
- log?.warn(
799
- `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
800
- parsed
801
- )}`
802
- );
803
- return;
804
- }
805
- const serverInstanceId = parsed.payload.status.instanceId;
806
- log?.debug(
807
- `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
808
- );
809
- sessionCb(this.onConnect(conn, parsed.from, serverInstanceId));
810
- };
811
- return bootHandler;
819
+ sendHandshake(to, conn) {
820
+ const requestMsg = handshakeRequestMessage(
821
+ this.clientId,
822
+ to,
823
+ this.instanceId
824
+ );
825
+ log?.debug(`${this.clientId} -- sending handshake request to ${to}`);
826
+ conn.send(this.codec.toBuffer(requestMsg));
812
827
  }
813
828
  onDisconnect(conn, connectedTo) {
814
829
  this.inflightConnectionPromises.delete(connectedTo);
@@ -825,22 +840,24 @@ var ServerTransport = class extends Transport {
825
840
  handleConnection(conn) {
826
841
  let session = void 0;
827
842
  const client = () => session?.to ?? "unknown";
828
- const bootHandler = this.receiveWithBootSequence(
829
- conn,
830
- (establishedSession) => {
831
- session = establishedSession;
832
- conn.removeDataListener(bootHandler);
833
- conn.addDataListener((data) => {
834
- const parsed = this.parseMsg(data);
835
- if (!parsed) {
836
- conn.close();
837
- return;
838
- }
839
- this.handleMsg(parsed);
840
- });
843
+ const handshakeHandler = (data) => {
844
+ const handshake = this.receiveHandshakeRequestMessage(data, conn);
845
+ if (!handshake) {
846
+ conn.close();
847
+ return;
841
848
  }
842
- );
843
- conn.addDataListener(bootHandler);
849
+ session = this.onConnect(conn, handshake.from, handshake.instanceId);
850
+ conn.removeDataListener(handshakeHandler);
851
+ conn.addDataListener((data2) => {
852
+ const parsed = this.parseMsg(data2);
853
+ if (!parsed) {
854
+ conn.close();
855
+ return;
856
+ }
857
+ this.handleMsg(parsed);
858
+ });
859
+ };
860
+ conn.addDataListener(handshakeHandler);
844
861
  conn.addCloseListener(() => {
845
862
  if (!session)
846
863
  return;
@@ -857,42 +874,51 @@ var ServerTransport = class extends Transport {
857
874
  );
858
875
  });
859
876
  }
860
- receiveWithBootSequence(conn, sessionCb) {
861
- const bootHandler = (data) => {
862
- const parsed = this.parseMsg(data);
863
- if (!parsed) {
864
- conn.close();
865
- return;
866
- }
867
- if (!import_value.Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
868
- const responseMsg2 = bootResponseMessage(
869
- this.clientId,
870
- this.instanceId,
871
- parsed.from,
872
- false
873
- );
874
- conn.send(this.codec.toBuffer(responseMsg2));
875
- log?.warn(
876
- `${this.clientId} -- received invalid handshake msg: ${JSON.stringify(
877
- parsed
878
- )}`
879
- );
880
- return;
881
- }
882
- const instanceId = parsed.payload.instanceId;
883
- log?.debug(
884
- `${this.clientId} -- handshake from ${parsed.from} ok (instance id: ${instanceId}), responding with handshake success`
877
+ receiveHandshakeRequestMessage(data, conn) {
878
+ const parsed = this.parseMsg(data);
879
+ if (!parsed)
880
+ return false;
881
+ if (!import_value.Value.Check(ControlMessageHandshakeRequestSchema, parsed.payload)) {
882
+ const responseMsg2 = handshakeResponseMessage(
883
+ this.clientId,
884
+ this.instanceId,
885
+ parsed.from,
886
+ false
885
887
  );
886
- const responseMsg = bootResponseMessage(
888
+ conn.send(this.codec.toBuffer(responseMsg2));
889
+ log?.warn(
890
+ `${this.clientId} -- received invalid handshake msg: ${JSON.stringify(
891
+ parsed
892
+ )}`
893
+ );
894
+ return false;
895
+ }
896
+ const gotVersion = parsed.payload.protocolVersion;
897
+ if (gotVersion !== PROTOCOL_VERSION) {
898
+ const responseMsg2 = handshakeResponseMessage(
887
899
  this.clientId,
888
900
  this.instanceId,
889
901
  parsed.from,
890
- true
902
+ false
891
903
  );
892
- conn.send(this.codec.toBuffer(responseMsg));
893
- sessionCb(this.onConnect(conn, parsed.from, instanceId));
894
- };
895
- return bootHandler;
904
+ conn.send(this.codec.toBuffer(responseMsg2));
905
+ log?.warn(
906
+ `${this.clientId} -- received handshake msg with incompatible protocol version (got: ${gotVersion}, expected: ${PROTOCOL_VERSION})`
907
+ );
908
+ return false;
909
+ }
910
+ const instanceId = parsed.payload.instanceId;
911
+ log?.debug(
912
+ `${this.clientId} -- handshake from ${parsed.from} ok (instance id: ${instanceId}), responding with handshake success`
913
+ );
914
+ const responseMsg = handshakeResponseMessage(
915
+ this.clientId,
916
+ this.instanceId,
917
+ parsed.from,
918
+ true
919
+ );
920
+ conn.send(this.codec.toBuffer(responseMsg));
921
+ return { instanceId, from: parsed.from };
896
922
  }
897
923
  };
898
924
  // Annotate the CommonJS export names for ESM import in node:
@@ -1,3 +1,3 @@
1
- export { a as ClientTransport, C as Connection, k as EventHandler, E as EventMap, j as EventTypes, O as OpaqueTransportMessage, f as OpaqueTransportMessageSchema, S as ServerTransport, d as Session, T as Transport, b as TransportClientId, g as TransportMessage, e as TransportMessageSchema, h as isStreamClose, i as isStreamOpen } from '../index-1afc5580.js';
1
+ export { a as ClientTransport, C as Connection, k as EventHandler, E as EventMap, j as EventTypes, O as OpaqueTransportMessage, f as OpaqueTransportMessageSchema, S as ServerTransport, d as Session, T as Transport, b as TransportClientId, g as TransportMessage, e as TransportMessageSchema, h as isStreamClose, i as isStreamOpen } from '../index-21c1b21d.js';
2
2
  import '../types-3e5768ec.js';
3
3
  import '@sinclair/typebox';
@@ -1,3 +1,3 @@
1
- export { a as ClientTransport, C as Connection, k as EventHandler, E as EventMap, j as EventTypes, O as OpaqueTransportMessage, f as OpaqueTransportMessageSchema, S as ServerTransport, d as Session, T as Transport, b as TransportClientId, g as TransportMessage, e as TransportMessageSchema, h as isStreamClose, i as isStreamOpen } from '../index-1afc5580.js';
1
+ export { a as ClientTransport, C as Connection, k as EventHandler, E as EventMap, j as EventTypes, O as OpaqueTransportMessage, f as OpaqueTransportMessageSchema, S as ServerTransport, d as Session, T as Transport, b as TransportClientId, g as TransportMessage, e as TransportMessageSchema, h as isStreamClose, i as isStreamOpen } from '../index-21c1b21d.js';
2
2
  import '../types-3e5768ec.js';
3
3
  import '@sinclair/typebox';
@@ -5,13 +5,13 @@ import {
5
5
  ServerTransport,
6
6
  Session,
7
7
  Transport
8
- } from "../chunk-2PKONGC3.js";
9
- import "../chunk-GZ7HCLLM.js";
8
+ } from "../chunk-R2IMXRVU.js";
10
9
  import {
11
10
  OpaqueTransportMessageSchema,
12
11
  TransportMessageSchema
13
- } from "../chunk-XFFS4UOD.js";
12
+ } from "../chunk-MGGIUH5O.js";
14
13
  import "../chunk-H4BYJELI.js";
14
+ import "../chunk-GZ7HCLLM.js";
15
15
  export {
16
16
  ClientTransport,
17
17
  Connection,