@replit/river 0.10.13 → 0.12.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 (83) hide show
  1. package/README.md +28 -8
  2. package/dist/{builder-1f26296b.d.ts → builder-c593de11.d.ts} +14 -13
  3. package/dist/{chunk-3JGVFWKQ.js → chunk-24O3BKZA.js} +205 -180
  4. package/dist/chunk-4HOR4NUO.js +40 -0
  5. package/dist/chunk-ANGOKBE5.js +708 -0
  6. package/dist/{chunk-R6H2BIMC.js → chunk-GZ7HCLLM.js} +31 -7
  7. package/dist/{chunk-T7M7OKPE.js → chunk-H4BYJELI.js} +5 -1
  8. package/dist/chunk-IIBVKYDB.js +62 -0
  9. package/dist/chunk-IUDKWAOK.js +47 -0
  10. package/dist/chunk-WTOIOXB7.js +125 -0
  11. package/dist/chunk-XOTIAXAH.js +44 -0
  12. package/dist/codec/index.cjs +13 -7
  13. package/dist/codec/index.js +2 -4
  14. package/dist/connection-2956a1c5.d.ts +17 -0
  15. package/dist/connection-aaea7c88.d.ts +15 -0
  16. package/dist/connection-cd963ed5.d.ts +18 -0
  17. package/dist/index-d91775d9.d.ts +442 -0
  18. package/dist/logging/index.cjs +8 -3
  19. package/dist/logging/index.d.cts +6 -1
  20. package/dist/logging/index.d.ts +6 -1
  21. package/dist/logging/index.js +5 -3
  22. package/dist/messageFraming-b200ef25.d.ts +20 -0
  23. package/dist/router/index.cjs +249 -211
  24. package/dist/router/index.d.cts +6 -7
  25. package/dist/router/index.d.ts +6 -7
  26. package/dist/router/index.js +3 -3
  27. package/dist/transport/impls/stdio/client.cjs +891 -0
  28. package/dist/transport/impls/stdio/client.d.cts +27 -0
  29. package/dist/transport/impls/stdio/client.d.ts +27 -0
  30. package/dist/transport/impls/stdio/client.js +42 -0
  31. package/dist/transport/impls/stdio/server.cjs +861 -0
  32. package/dist/transport/impls/stdio/server.d.cts +25 -0
  33. package/dist/transport/impls/stdio/server.d.ts +25 -0
  34. package/dist/transport/impls/stdio/server.js +33 -0
  35. package/dist/transport/impls/uds/client.cjs +893 -0
  36. package/dist/transport/impls/uds/client.d.cts +16 -0
  37. package/dist/transport/impls/uds/client.d.ts +16 -0
  38. package/dist/transport/impls/uds/client.js +44 -0
  39. package/dist/transport/impls/uds/server.cjs +863 -0
  40. package/dist/transport/impls/uds/server.d.cts +16 -0
  41. package/dist/transport/impls/uds/server.d.ts +16 -0
  42. package/dist/transport/impls/uds/server.js +39 -0
  43. package/dist/transport/impls/ws/client.cjs +587 -248
  44. package/dist/transport/impls/ws/client.d.cts +6 -21
  45. package/dist/transport/impls/ws/client.d.ts +6 -21
  46. package/dist/transport/impls/ws/client.js +77 -7
  47. package/dist/transport/impls/ws/server.cjs +541 -194
  48. package/dist/transport/impls/ws/server.d.cts +6 -10
  49. package/dist/transport/impls/ws/server.d.ts +6 -10
  50. package/dist/transport/impls/ws/server.js +31 -8
  51. package/dist/transport/index.cjs +652 -129
  52. package/dist/transport/index.d.cts +3 -276
  53. package/dist/transport/index.d.ts +3 -276
  54. package/dist/transport/index.js +13 -10
  55. package/dist/util/testHelpers.cjs +40 -602
  56. package/dist/util/testHelpers.d.cts +18 -37
  57. package/dist/util/testHelpers.d.ts +18 -37
  58. package/dist/util/testHelpers.js +27 -47
  59. package/package.json +29 -14
  60. package/dist/chunk-3MQETIGZ.js +0 -80
  61. package/dist/chunk-5IC5XMWK.js +0 -140
  62. package/dist/chunk-L7D75G4K.js +0 -29
  63. package/dist/chunk-LQXPKF3A.js +0 -282
  64. package/dist/chunk-PJ2EUO7O.js +0 -63
  65. package/dist/chunk-WVT5QXMZ.js +0 -20
  66. package/dist/chunk-ZE4MX7DF.js +0 -75
  67. package/dist/connection-2529fc14.d.ts +0 -10
  68. package/dist/connection-316d6e3a.d.ts +0 -10
  69. package/dist/connection-8e19874c.d.ts +0 -11
  70. package/dist/connection-f7688cc1.d.ts +0 -11
  71. package/dist/transport/impls/stdio/stdio.cjs +0 -508
  72. package/dist/transport/impls/stdio/stdio.d.cts +0 -26
  73. package/dist/transport/impls/stdio/stdio.d.ts +0 -26
  74. package/dist/transport/impls/stdio/stdio.js +0 -70
  75. package/dist/transport/impls/unixsocket/client.cjs +0 -506
  76. package/dist/transport/impls/unixsocket/client.d.cts +0 -16
  77. package/dist/transport/impls/unixsocket/client.d.ts +0 -16
  78. package/dist/transport/impls/unixsocket/client.js +0 -67
  79. package/dist/transport/impls/unixsocket/server.cjs +0 -510
  80. package/dist/transport/impls/unixsocket/server.d.cts +0 -18
  81. package/dist/transport/impls/unixsocket/server.d.ts +0 -18
  82. package/dist/transport/impls/unixsocket/server.js +0 -73
  83. /package/dist/{chunk-ORAG7IAU.js → chunk-5IZ2UHWV.js} +0 -0
@@ -0,0 +1,891 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // transport/impls/stdio/client.ts
21
+ var client_exports = {};
22
+ __export(client_exports, {
23
+ StdioClientTransport: () => StdioClientTransport
24
+ });
25
+ module.exports = __toCommonJS(client_exports);
26
+
27
+ // logging/index.ts
28
+ var log;
29
+
30
+ // transport/transport.ts
31
+ var import_value = require("@sinclair/typebox/value");
32
+
33
+ // transport/message.ts
34
+ var import_typebox = require("@sinclair/typebox");
35
+ var import_nanoid = require("nanoid");
36
+ var TransportMessageSchema = (t) => import_typebox.Type.Object({
37
+ id: import_typebox.Type.String(),
38
+ from: import_typebox.Type.String(),
39
+ to: import_typebox.Type.String(),
40
+ seq: import_typebox.Type.Integer(),
41
+ ack: import_typebox.Type.Integer(),
42
+ serviceName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
43
+ procedureName: import_typebox.Type.Optional(import_typebox.Type.Union([import_typebox.Type.String(), import_typebox.Type.Null()])),
44
+ streamId: import_typebox.Type.String(),
45
+ controlFlags: import_typebox.Type.Integer(),
46
+ payload: t
47
+ });
48
+ var ControlMessageAckSchema = import_typebox.Type.Object({
49
+ type: import_typebox.Type.Literal("ACK")
50
+ });
51
+ var ControlMessageCloseSchema = import_typebox.Type.Object({
52
+ type: import_typebox.Type.Literal("CLOSE")
53
+ });
54
+ var PROTOCOL_VERSION = "v1";
55
+ var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
56
+ type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
57
+ protocolVersion: import_typebox.Type.Literal(PROTOCOL_VERSION)
58
+ });
59
+ var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
60
+ type: import_typebox.Type.Literal("HANDSHAKE_RESP"),
61
+ status: import_typebox.Type.Union([
62
+ import_typebox.Type.Object({
63
+ ok: import_typebox.Type.Literal(true),
64
+ instanceId: import_typebox.Type.String()
65
+ }),
66
+ import_typebox.Type.Object({
67
+ ok: import_typebox.Type.Literal(false),
68
+ reason: import_typebox.Type.Union([import_typebox.Type.Literal("VERSION_MISMATCH")])
69
+ })
70
+ ])
71
+ });
72
+ var ControlMessagePayloadSchema = import_typebox.Type.Union([
73
+ ControlMessageCloseSchema,
74
+ ControlMessageAckSchema,
75
+ ControlMessageHandshakeRequestSchema,
76
+ ControlMessageHandshakeResponseSchema
77
+ ]);
78
+ var OpaqueTransportMessageSchema = TransportMessageSchema(
79
+ import_typebox.Type.Unknown()
80
+ );
81
+ function bootRequestMessage(from, to) {
82
+ return {
83
+ id: (0, import_nanoid.nanoid)(),
84
+ from,
85
+ to,
86
+ seq: 0,
87
+ ack: 0,
88
+ streamId: (0, import_nanoid.nanoid)(),
89
+ controlFlags: 0,
90
+ payload: {
91
+ type: "HANDSHAKE_REQ",
92
+ protocolVersion: PROTOCOL_VERSION
93
+ }
94
+ };
95
+ }
96
+ function isAck(controlFlag) {
97
+ return (controlFlag & 1 /* AckBit */) === 1 /* AckBit */;
98
+ }
99
+
100
+ // transport/events.ts
101
+ var EventDispatcher = class {
102
+ eventListeners = {};
103
+ numberOfListeners(eventType) {
104
+ return this.eventListeners[eventType]?.size ?? 0;
105
+ }
106
+ addEventListener(eventType, handler) {
107
+ if (!this.eventListeners[eventType]) {
108
+ this.eventListeners[eventType] = /* @__PURE__ */ new Set();
109
+ }
110
+ this.eventListeners[eventType]?.add(handler);
111
+ }
112
+ removeEventListener(eventType, handler) {
113
+ const handlers = this.eventListeners[eventType];
114
+ if (handlers) {
115
+ this.eventListeners[eventType]?.delete(handler);
116
+ }
117
+ }
118
+ dispatchEvent(eventType, event) {
119
+ const handlers = this.eventListeners[eventType];
120
+ if (handlers) {
121
+ for (const handler of handlers) {
122
+ handler(event);
123
+ }
124
+ }
125
+ }
126
+ };
127
+
128
+ // transport/session.ts
129
+ var import_nanoid2 = require("nanoid");
130
+ var nanoid2 = (0, import_nanoid2.customAlphabet)("1234567890abcdefghijklmnopqrstuvxyz", 6);
131
+ var unsafeId = () => nanoid2();
132
+ var Connection = class {
133
+ debugId;
134
+ constructor() {
135
+ this.debugId = `conn-${unsafeId()}`;
136
+ }
137
+ };
138
+ var HEARTBEAT_INTERVAL_MS = 250;
139
+ var HEARTBEATS_TILL_DEAD = 4;
140
+ var SESSION_DISCONNECT_GRACE_MS = 3e3;
141
+ var Session = class {
142
+ codec;
143
+ /**
144
+ * The buffer of messages that have been sent but not yet acknowledged.
145
+ */
146
+ sendBuffer = [];
147
+ /**
148
+ * The active connection associated with this session
149
+ */
150
+ connection;
151
+ from;
152
+ to;
153
+ /**
154
+ * The unique ID of this session.
155
+ */
156
+ debugId;
157
+ /**
158
+ * Number of messages we've sent along this session (excluding handshake)
159
+ */
160
+ seq = 0;
161
+ /**
162
+ * Number of unique messages we've received this session (excluding handshake)
163
+ */
164
+ ack = 0;
165
+ /**
166
+ * The grace period between when the inner connection is disconnected
167
+ * and when we should consider the entire session disconnected.
168
+ */
169
+ disconnectionGrace;
170
+ /**
171
+ * Number of heartbeats we've sent without a response.
172
+ */
173
+ heartbeatMisses;
174
+ /**
175
+ * The interval for sending heartbeats.
176
+ */
177
+ heartbeat;
178
+ constructor(codec, from, connectedTo, conn) {
179
+ this.debugId = `sess-${unsafeId()}`;
180
+ this.from = from;
181
+ this.to = connectedTo;
182
+ this.connection = conn;
183
+ this.codec = codec;
184
+ this.heartbeatMisses = 0;
185
+ this.heartbeat = setInterval(
186
+ () => this.sendHeartbeat(),
187
+ HEARTBEAT_INTERVAL_MS
188
+ );
189
+ }
190
+ /**
191
+ * Sends a message over the session's connection.
192
+ * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
193
+ *
194
+ * @param msg The partial message to be sent, which will be constructed into a full message.
195
+ * @param skipRetry Optional. If true, the message will not be buffered for retry on failure. This should only be used for
196
+ * ack hearbeats, which contain information that can already be found in the other buffered messages.
197
+ * @returns The full transport ID of the message that was attempted to be sent.
198
+ */
199
+ send(msg, skipRetry) {
200
+ const fullMsg = this.constructMsg(msg);
201
+ log?.debug(`${this.from} -- sending ${JSON.stringify(fullMsg)}`);
202
+ if (this.connection) {
203
+ const ok = this.connection.send(this.codec.toBuffer(fullMsg));
204
+ if (ok)
205
+ return fullMsg.id;
206
+ log?.info(
207
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection (id: ${this.connection.debugId}) is probably dead`
208
+ );
209
+ } else {
210
+ log?.info(
211
+ `${this.from} -- failed to send ${fullMsg.id} to ${fullMsg.to}, connection not ready yet`
212
+ );
213
+ }
214
+ if (skipRetry)
215
+ return fullMsg.id;
216
+ this.addToSendBuff(fullMsg);
217
+ log?.info(
218
+ `${this.from} -- buffering msg ${fullMsg.id} until connection is healthy again`
219
+ );
220
+ return fullMsg.id;
221
+ }
222
+ sendHeartbeat() {
223
+ if (this.heartbeatMisses >= HEARTBEATS_TILL_DEAD && this.connection) {
224
+ log?.info(
225
+ `${this.from} -- closing connection (id: ${this.connection.debugId}) to ${this.to} due to inactivity`
226
+ );
227
+ this.halfCloseConnection();
228
+ return;
229
+ }
230
+ this.send(
231
+ {
232
+ streamId: "heartbeat",
233
+ controlFlags: 1 /* AckBit */,
234
+ payload: {
235
+ type: "ACK"
236
+ }
237
+ },
238
+ true
239
+ );
240
+ this.heartbeatMisses++;
241
+ }
242
+ resetBufferedMessages() {
243
+ this.sendBuffer = [];
244
+ this.seq = 0;
245
+ this.ack = 0;
246
+ }
247
+ sendBufferedMessages() {
248
+ if (!this.connection) {
249
+ const msg = `${this.from} -- tried sending buffered messages without a connection (if you hit this code path something is seriously wrong)`;
250
+ log?.error(msg);
251
+ throw new Error(msg);
252
+ }
253
+ for (const msg of this.sendBuffer) {
254
+ log?.debug(`${this.from} -- resending ${JSON.stringify(msg)}`);
255
+ const ok = this.connection.send(this.codec.toBuffer(msg));
256
+ if (!ok) {
257
+ const msg2 = `${this.from} -- failed to send buffered message to ${this.to} in session (id: ${this.debugId}) (if you hit this code path something is seriously wrong)`;
258
+ log?.error(msg2);
259
+ throw new Error(msg2);
260
+ }
261
+ }
262
+ }
263
+ updateBookkeeping(ack, seq) {
264
+ this.heartbeatMisses = 0;
265
+ this.sendBuffer = this.sendBuffer.filter((unacked) => unacked.seq > ack);
266
+ this.ack = seq + 1;
267
+ }
268
+ addToSendBuff(msg) {
269
+ this.sendBuffer.push(msg);
270
+ log?.debug(
271
+ `${this.from} -- send buff to ${this.to} now tracking ${this.sendBuffer.length} messages`
272
+ );
273
+ }
274
+ closeStaleConnection(conn) {
275
+ if (!this.connection || this.connection !== conn)
276
+ return;
277
+ log?.info(
278
+ `${this.from} -- closing old inner connection (id: ${this.connection.debugId}) from session (id: ${this.debugId}) to ${this.to}`
279
+ );
280
+ this.connection.close();
281
+ this.connection = void 0;
282
+ }
283
+ replaceWithNewConnection(newConn) {
284
+ this.closeStaleConnection(this.connection);
285
+ this.cancelGrace();
286
+ this.connection = newConn;
287
+ }
288
+ beginGrace(cb) {
289
+ this.disconnectionGrace = setTimeout(() => {
290
+ this.resetBufferedMessages();
291
+ clearInterval(this.heartbeat);
292
+ cb();
293
+ }, SESSION_DISCONNECT_GRACE_MS);
294
+ }
295
+ cancelGrace() {
296
+ clearTimeout(this.disconnectionGrace);
297
+ }
298
+ get connected() {
299
+ return this.connection !== void 0;
300
+ }
301
+ get nextExpectedSeq() {
302
+ return this.ack;
303
+ }
304
+ constructMsg(partialMsg) {
305
+ const msg = {
306
+ ...partialMsg,
307
+ id: unsafeId(),
308
+ to: this.to,
309
+ from: this.from,
310
+ seq: this.seq,
311
+ ack: this.ack
312
+ };
313
+ this.seq++;
314
+ return msg;
315
+ }
316
+ /**
317
+ * Closes the out-going connection but doesn't remove the listeners
318
+ * for incoming messages. The connection will eventually call onClose
319
+ * when it is ready to be cleaned up and only then will {@link connection} be set back
320
+ * to undefined
321
+ */
322
+ halfCloseConnection() {
323
+ this.connection?.close();
324
+ }
325
+ inspectSendBuffer() {
326
+ return this.sendBuffer;
327
+ }
328
+ };
329
+
330
+ // codec/json.ts
331
+ var encoder = new TextEncoder();
332
+ var decoder = new TextDecoder();
333
+ function uint8ArrayToBase64(uint8Array) {
334
+ let binary = "";
335
+ uint8Array.forEach((byte) => {
336
+ binary += String.fromCharCode(byte);
337
+ });
338
+ return btoa(binary);
339
+ }
340
+ function base64ToUint8Array(base64) {
341
+ const binaryString = atob(base64);
342
+ const uint8Array = new Uint8Array(binaryString.length);
343
+ for (let i = 0; i < binaryString.length; i++) {
344
+ uint8Array[i] = binaryString.charCodeAt(i);
345
+ }
346
+ return uint8Array;
347
+ }
348
+ var NaiveJsonCodec = {
349
+ toBuffer: (obj) => {
350
+ return encoder.encode(
351
+ JSON.stringify(obj, function replacer(key) {
352
+ const val = this[key];
353
+ if (val instanceof Uint8Array) {
354
+ return { $t: uint8ArrayToBase64(val) };
355
+ } else {
356
+ return val;
357
+ }
358
+ })
359
+ );
360
+ },
361
+ fromBuffer: (buff) => {
362
+ try {
363
+ const parsed = JSON.parse(
364
+ decoder.decode(buff),
365
+ function reviver(_key, val) {
366
+ if (val?.$t) {
367
+ return base64ToUint8Array(val.$t);
368
+ } else {
369
+ return val;
370
+ }
371
+ }
372
+ );
373
+ if (typeof parsed === "object")
374
+ return parsed;
375
+ return null;
376
+ } catch {
377
+ return null;
378
+ }
379
+ }
380
+ };
381
+
382
+ // transport/transport.ts
383
+ var import_nanoid3 = require("nanoid");
384
+
385
+ // util/stringify.ts
386
+ function coerceErrorString(err) {
387
+ if (err instanceof Error) {
388
+ return err.message;
389
+ }
390
+ return `[coerced to error] ${String(err)}`;
391
+ }
392
+
393
+ // transport/transport.ts
394
+ var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
395
+ var DEFAULT_RECONNECT_INTERVAL_MS = 250;
396
+ var defaultTransportOptions = {
397
+ retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
398
+ retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
399
+ retryAttemptsMax: 5,
400
+ codec: NaiveJsonCodec
401
+ };
402
+ var Transport = class {
403
+ /**
404
+ * A flag indicating whether the transport has been destroyed.
405
+ * A destroyed transport will not attempt to reconnect and cannot be used again.
406
+ */
407
+ state;
408
+ /**
409
+ * The {@link Codec} used to encode and decode messages.
410
+ */
411
+ codec;
412
+ /**
413
+ * The client ID of this transport.
414
+ */
415
+ clientId;
416
+ /**
417
+ * The map of {@link Session}s managed by this transport.
418
+ */
419
+ sessions;
420
+ /**
421
+ * The map of {@link Connection}s managed by this transport.
422
+ */
423
+ get connections() {
424
+ return new Map(
425
+ [...this.sessions].map(([client, session]) => [client, session.connection]).filter((entry) => entry[1] !== void 0)
426
+ );
427
+ }
428
+ /**
429
+ * The event dispatcher for handling events of type EventTypes.
430
+ */
431
+ eventDispatcher;
432
+ /**
433
+ * The options for this transport.
434
+ */
435
+ options;
436
+ /**
437
+ * Creates a new Transport instance.
438
+ * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
439
+ * @param codec The codec used to encode and decode messages.
440
+ * @param clientId The client ID of this transport.
441
+ */
442
+ constructor(clientId, providedOptions) {
443
+ this.options = { ...defaultTransportOptions, ...providedOptions };
444
+ this.eventDispatcher = new EventDispatcher();
445
+ this.sessions = /* @__PURE__ */ new Map();
446
+ this.codec = this.options.codec;
447
+ this.clientId = clientId;
448
+ this.state = "open";
449
+ }
450
+ sessionByClientId(clientId) {
451
+ const session = this.sessions.get(clientId);
452
+ if (!session) {
453
+ const err = `${this.clientId} -- (invariant violation) no existing session for ${clientId}`;
454
+ log?.error(err);
455
+ throw new Error(err);
456
+ }
457
+ return session;
458
+ }
459
+ /**
460
+ * Called when a new connection is established
461
+ * and we know the identity of the connected client.
462
+ * @param conn The connection object.
463
+ */
464
+ onConnect(conn, connectedTo) {
465
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
466
+ status: "connect",
467
+ conn
468
+ });
469
+ const session = this.sessions.get(connectedTo);
470
+ if (session === void 0) {
471
+ const newSession = this.createSession(connectedTo, conn);
472
+ log?.info(
473
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for new session (id: ${newSession.debugId}) to ${connectedTo}`
474
+ );
475
+ return newSession;
476
+ }
477
+ log?.info(
478
+ `${this.clientId} -- new connection (id: ${conn.debugId}) for existing session (id: ${session.debugId}) to ${connectedTo}`
479
+ );
480
+ session.replaceWithNewConnection(conn);
481
+ session.sendBufferedMessages();
482
+ return session;
483
+ }
484
+ createSession(connectedTo, conn) {
485
+ const session = new Session(
486
+ this.codec,
487
+ this.clientId,
488
+ connectedTo,
489
+ conn
490
+ );
491
+ this.sessions.set(session.to, session);
492
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
493
+ status: "connect",
494
+ session
495
+ });
496
+ return session;
497
+ }
498
+ deleteSession(session) {
499
+ this.sessions.delete(session.to);
500
+ this.eventDispatcher.dispatchEvent("sessionStatus", {
501
+ status: "disconnect",
502
+ session
503
+ });
504
+ log?.info(
505
+ `${this.clientId} -- session ${session.debugId} disconnect from ${session.to}`
506
+ );
507
+ }
508
+ /**
509
+ * The downstream implementation needs to call this when a connection is closed.
510
+ * @param conn The connection object.
511
+ */
512
+ onDisconnect(conn, connectedTo) {
513
+ this.eventDispatcher.dispatchEvent("connectionStatus", {
514
+ status: "disconnect",
515
+ conn
516
+ });
517
+ if (!connectedTo)
518
+ return;
519
+ const session = this.sessionByClientId(connectedTo);
520
+ log?.info(
521
+ `${this.clientId} -- connection (id: ${conn.debugId}) disconnect from ${connectedTo}, ${SESSION_DISCONNECT_GRACE_MS}ms until session (id: ${session.debugId}) disconnect`
522
+ );
523
+ session.closeStaleConnection(conn);
524
+ session.beginGrace(() => this.deleteSession(session));
525
+ }
526
+ /**
527
+ * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
528
+ * @param msg The message to parse.
529
+ * @returns The parsed message, or null if the message is malformed or invalid.
530
+ */
531
+ parseMsg(msg) {
532
+ const parsedMsg = this.codec.fromBuffer(msg);
533
+ if (parsedMsg === null) {
534
+ const decodedBuffer = new TextDecoder().decode(msg);
535
+ log?.warn(`${this.clientId} -- received malformed msg: ${decodedBuffer}`);
536
+ return null;
537
+ }
538
+ if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
539
+ log?.warn(
540
+ `${this.clientId} -- received invalid msg: ${JSON.stringify(
541
+ parsedMsg
542
+ )}`
543
+ );
544
+ return null;
545
+ }
546
+ return {
547
+ ...parsedMsg,
548
+ serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
549
+ procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
550
+ };
551
+ }
552
+ /**
553
+ * Called when a message is received by this transport.
554
+ * You generally shouldn't need to override this in downstream transport implementations.
555
+ * @param msg The received message.
556
+ */
557
+ handleMsg(msg) {
558
+ if (!msg) {
559
+ return;
560
+ }
561
+ const session = this.sessionByClientId(msg.from);
562
+ session.cancelGrace();
563
+ log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
564
+ if (msg.seq !== session.nextExpectedSeq) {
565
+ log?.warn(
566
+ `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
567
+ msg
568
+ )}`
569
+ );
570
+ return;
571
+ }
572
+ if (!isAck(msg.controlFlags)) {
573
+ this.eventDispatcher.dispatchEvent("message", msg);
574
+ }
575
+ session.updateBookkeeping(msg.ack, msg.seq);
576
+ }
577
+ /**
578
+ * Adds a listener to this transport.
579
+ * @param the type of event to listen for
580
+ * @param handler The message handler to add.
581
+ */
582
+ addEventListener(type, handler) {
583
+ this.eventDispatcher.addEventListener(type, handler);
584
+ }
585
+ /**
586
+ * Removes a listener from this transport.
587
+ * @param the type of event to unlisten on
588
+ * @param handler The message handler to remove.
589
+ */
590
+ removeEventListener(type, handler) {
591
+ this.eventDispatcher.removeEventListener(type, handler);
592
+ }
593
+ /**
594
+ * Sends a message over this transport, delegating to the appropriate connection to actually
595
+ * send the message.
596
+ * @param msg The message to send.
597
+ * @returns The ID of the sent message or undefined if it wasn't sent
598
+ */
599
+ send(to, msg) {
600
+ if (this.state === "destroyed") {
601
+ const err = "transport is destroyed, cant send";
602
+ log?.error(`${this.clientId} -- ` + err + `: ${JSON.stringify(msg)}`);
603
+ throw new Error(err);
604
+ } else if (this.state === "closed") {
605
+ log?.info(
606
+ `${this.clientId} -- transport closed when sending, discarding : ${JSON.stringify(
607
+ msg
608
+ )}`
609
+ );
610
+ return void 0;
611
+ }
612
+ let session = this.sessions.get(to);
613
+ if (!session) {
614
+ session = this.createSession(to, void 0);
615
+ log?.info(
616
+ `${this.clientId} -- no session for ${to}, created a new one (id: ${session.debugId})`
617
+ );
618
+ }
619
+ return session.send(msg);
620
+ }
621
+ // control helpers
622
+ sendCloseStream(to, streamId) {
623
+ return this.send(to, {
624
+ streamId,
625
+ controlFlags: 4 /* StreamClosedBit */,
626
+ payload: {
627
+ type: "CLOSE"
628
+ }
629
+ });
630
+ }
631
+ /**
632
+ * Default close implementation for transports. You should override this in the downstream
633
+ * implementation if you need to do any additional cleanup and call super.close() at the end.
634
+ * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
635
+ */
636
+ close() {
637
+ for (const session of this.sessions.values()) {
638
+ session.halfCloseConnection();
639
+ }
640
+ this.state = "closed";
641
+ log?.info(`${this.clientId} -- manually closed transport`);
642
+ }
643
+ /**
644
+ * Default destroy implementation for transports. You should override this in the downstream
645
+ * implementation if you need to do any additional cleanup and call super.destroy() at the end.
646
+ * Destroys the transport. Any messages sent while the transport is destroyed will throw an error.
647
+ */
648
+ destroy() {
649
+ for (const session of this.sessions.values()) {
650
+ session.closeStaleConnection(session.connection);
651
+ }
652
+ this.state = "destroyed";
653
+ log?.info(`${this.clientId} -- manually destroyed transport`);
654
+ }
655
+ };
656
+ var ClientTransport = class extends Transport {
657
+ /**
658
+ * The map of reconnect promises for each client ID.
659
+ */
660
+ inflightConnectionPromises;
661
+ tryReconnecting = true;
662
+ serverInstanceIds = /* @__PURE__ */ new Map();
663
+ constructor(clientId, providedOptions) {
664
+ super(clientId, providedOptions);
665
+ this.inflightConnectionPromises = /* @__PURE__ */ new Map();
666
+ }
667
+ handleConnection(conn, to) {
668
+ const bootHandler = this.receiveWithBootSequence(conn, () => {
669
+ conn.removeDataListener(bootHandler);
670
+ conn.addDataListener((data) => this.handleMsg(this.parseMsg(data)));
671
+ });
672
+ conn.addDataListener(bootHandler);
673
+ conn.addCloseListener(() => {
674
+ this.onDisconnect(conn, to);
675
+ void this.connect(to);
676
+ });
677
+ conn.addErrorListener((err) => {
678
+ log?.warn(
679
+ `${this.clientId} -- error in connection (id: ${conn.debugId}) to ${to}: ${coerceErrorString(err)}`
680
+ );
681
+ });
682
+ }
683
+ /**
684
+ * Manually attempts to connect to a client.
685
+ * @param to The client ID of the node to connect to.
686
+ */
687
+ async connect(to, attempt = 0) {
688
+ if (this.state !== "open" || !this.tryReconnecting) {
689
+ log?.info(
690
+ `${this.clientId} -- transport state is no longer open, not attempting connection`
691
+ );
692
+ return;
693
+ }
694
+ let reconnectPromise = this.inflightConnectionPromises.get(to);
695
+ if (!reconnectPromise) {
696
+ reconnectPromise = this.createNewOutgoingConnection(to);
697
+ this.inflightConnectionPromises.set(to, reconnectPromise);
698
+ }
699
+ try {
700
+ const conn = await reconnectPromise;
701
+ this.state = "open";
702
+ const requestMsg = bootRequestMessage(this.clientId, to);
703
+ log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
704
+ conn.send(this.codec.toBuffer(requestMsg));
705
+ } catch (error) {
706
+ const errStr = coerceErrorString(error);
707
+ this.inflightConnectionPromises.delete(to);
708
+ if (attempt >= this.options.retryAttemptsMax) {
709
+ const errMsg = `connection to ${to} failed after ${attempt} attempts (${errStr}), giving up`;
710
+ log?.error(`${this.clientId} -- ${errMsg}`);
711
+ throw new Error(errMsg);
712
+ } else {
713
+ const jitter = Math.floor(Math.random() * this.options.retryJitterMs);
714
+ const backoffMs = this.options.retryIntervalMs * 2 ** attempt + jitter;
715
+ log?.warn(
716
+ `${this.clientId} -- connection to ${to} failed (${errStr}), trying again in ${backoffMs}ms`
717
+ );
718
+ setTimeout(() => void this.connect(to, attempt + 1), backoffMs);
719
+ }
720
+ }
721
+ }
722
+ receiveWithBootSequence(conn, sessionCb) {
723
+ const bootHandler = (data) => {
724
+ const parsed = this.parseMsg(data);
725
+ if (!parsed)
726
+ return;
727
+ if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
728
+ log?.warn(
729
+ `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
730
+ );
731
+ return;
732
+ }
733
+ if (!parsed.payload.status.ok) {
734
+ log?.warn(
735
+ `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
736
+ parsed
737
+ )}`
738
+ );
739
+ return;
740
+ }
741
+ const oldSession = this.sessions.get(parsed.from);
742
+ const serverInstanceId = parsed.payload.status.instanceId;
743
+ const lastServerInstanceId = this.serverInstanceIds.get(parsed.from);
744
+ if (oldSession && lastServerInstanceId !== serverInstanceId && lastServerInstanceId !== void 0) {
745
+ log?.debug(
746
+ `${this.clientId} -- handshake from ${parsed.from} has different server instance (got: ${serverInstanceId}, last connected to: ${lastServerInstanceId}), starting a new session`
747
+ );
748
+ oldSession.resetBufferedMessages();
749
+ oldSession.closeStaleConnection();
750
+ this.deleteSession(oldSession);
751
+ }
752
+ log?.debug(
753
+ `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
754
+ );
755
+ this.serverInstanceIds.set(parsed.from, serverInstanceId);
756
+ sessionCb(this.onConnect(conn, parsed.from));
757
+ };
758
+ return bootHandler;
759
+ }
760
+ onDisconnect(conn, connectedTo) {
761
+ if (connectedTo)
762
+ this.inflightConnectionPromises.delete(connectedTo);
763
+ super.onDisconnect(conn, connectedTo);
764
+ }
765
+ };
766
+
767
+ // transport/transforms/messageFraming.ts
768
+ var import_node_stream = require("stream");
769
+ var Uint32LengthPrefixFraming = class extends import_node_stream.Transform {
770
+ receivedBuffer;
771
+ maxBufferSizeBytes;
772
+ constructor({ maxBufferSizeBytes, ...options }) {
773
+ super(options);
774
+ this.maxBufferSizeBytes = maxBufferSizeBytes;
775
+ this.receivedBuffer = Buffer.alloc(0);
776
+ }
777
+ _transform(chunk, _encoding, cb) {
778
+ if (this.receivedBuffer.byteLength + chunk.byteLength > this.maxBufferSizeBytes) {
779
+ const err = new Error(
780
+ `buffer overflow: ${this.receivedBuffer.byteLength}B > ${this.maxBufferSizeBytes}B`
781
+ );
782
+ this.emit("error", err);
783
+ cb(err);
784
+ return;
785
+ }
786
+ this.receivedBuffer = Buffer.concat([this.receivedBuffer, chunk]);
787
+ while (this.receivedBuffer.length > 4) {
788
+ const claimedMessageLength = this.receivedBuffer.readUInt32BE(0) + 4;
789
+ if (this.receivedBuffer.length >= claimedMessageLength) {
790
+ const message = this.receivedBuffer.subarray(4, claimedMessageLength);
791
+ this.push(message);
792
+ this.receivedBuffer = this.receivedBuffer.subarray(claimedMessageLength);
793
+ } else {
794
+ break;
795
+ }
796
+ }
797
+ cb();
798
+ }
799
+ _flush(cb) {
800
+ if (this.receivedBuffer.length) {
801
+ this.emit("error", new Error("got incomplete message while flushing"));
802
+ }
803
+ this.receivedBuffer = Buffer.alloc(0);
804
+ cb();
805
+ }
806
+ _destroy(error, callback) {
807
+ this.receivedBuffer = Buffer.alloc(0);
808
+ super._destroy(error, callback);
809
+ }
810
+ };
811
+ function createLengthEncodedStream(options) {
812
+ return new Uint32LengthPrefixFraming({
813
+ maxBufferSizeBytes: options?.maxBufferSizeBytes ?? 16 * 1024 * 1024
814
+ // 16MB
815
+ });
816
+ }
817
+ var MessageFramer = {
818
+ createFramedStream: createLengthEncodedStream,
819
+ write: (buf) => {
820
+ const lengthPrefix = Buffer.alloc(4);
821
+ lengthPrefix.writeUInt32BE(buf.length, 0);
822
+ return Buffer.concat([lengthPrefix, buf]);
823
+ }
824
+ };
825
+
826
+ // transport/impls/stdio/connection.ts
827
+ var StreamConnection = class extends Connection {
828
+ input;
829
+ output;
830
+ framer;
831
+ constructor(input, output) {
832
+ super();
833
+ this.framer = MessageFramer.createFramedStream();
834
+ this.input = input.pipe(this.framer);
835
+ this.output = output;
836
+ }
837
+ addDataListener(cb) {
838
+ this.input.on("data", cb);
839
+ }
840
+ removeDataListener(cb) {
841
+ this.input.off("data", cb);
842
+ }
843
+ addCloseListener(cb) {
844
+ this.input.on("close", cb);
845
+ this.output.on("close", cb);
846
+ }
847
+ addErrorListener(cb) {
848
+ this.input.on("error", cb);
849
+ this.output.on("error", cb);
850
+ }
851
+ send(payload) {
852
+ if (!this.output.writable)
853
+ return false;
854
+ return this.output.write(MessageFramer.write(payload));
855
+ }
856
+ close() {
857
+ this.output.end();
858
+ this.input.unpipe(this.framer);
859
+ this.framer.destroy();
860
+ }
861
+ };
862
+
863
+ // transport/impls/stdio/client.ts
864
+ var StdioClientTransport = class extends ClientTransport {
865
+ input = process.stdin;
866
+ output = process.stdout;
867
+ serverId;
868
+ /**
869
+ * Constructs a new StdioClientTransport instance.
870
+ * @param clientId - The ID of the client associated with this transport.
871
+ * @param input - The readable stream to use as input. Defaults to process.stdin.
872
+ * @param output - The writable stream to use as output. Defaults to process.stdout.
873
+ */
874
+ constructor(clientId, input = process.stdin, output = process.stdout, serverId, providedOptions) {
875
+ super(clientId, providedOptions);
876
+ this.input = input;
877
+ this.output = output;
878
+ this.serverId = serverId;
879
+ void this.connect(serverId);
880
+ }
881
+ async createNewOutgoingConnection(to) {
882
+ log?.info(`${this.clientId} -- establishing a new stream to ${to}`);
883
+ const conn = new StreamConnection(this.input, this.output);
884
+ this.handleConnection(conn, to);
885
+ return Promise.resolve(conn);
886
+ }
887
+ };
888
+ // Annotate the CommonJS export names for ESM import in node:
889
+ 0 && (module.exports = {
890
+ StdioClientTransport
891
+ });