@replit/river 0.11.0 → 0.12.1

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