@replit/river 0.12.6 → 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-VLBVQX5H.js → chunk-NPXAAD7M.js} +1 -1
  7. package/dist/{chunk-4SDJ5VN4.js → chunk-R2IMXRVU.js} +150 -116
  8. package/dist/{connection-ba37d174.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-54e0f99c.d.ts → index-21c1b21d.d.ts} +29 -13
  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 +143 -121
  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 +151 -127
  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 +147 -123
  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 +151 -127
  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 +202 -167
  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-PBPXYLI6.js +0 -44
  41. package/dist/chunk-Q7GL34DZ.js +0 -47
  42. package/dist/connection-1f9971d8.d.ts +0 -17
  43. package/dist/connection-24d878ac.d.ts +0 -18
  44. package/dist/transport/impls/stdio/client.cjs +0 -904
  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 -879
  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
@@ -1,904 +0,0 @@
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.closeStaleConnection(this.connection);
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.close();
294
- cb();
295
- }, SESSION_DISCONNECT_GRACE_MS);
296
- }
297
- // called on reconnect of the underlying session
298
- cancelGrace() {
299
- this.heartbeatMisses = 0;
300
- clearTimeout(this.disconnectionGrace);
301
- }
302
- // closed when we want to discard the whole session
303
- // (i.e. shutdown or session disconnect)
304
- close() {
305
- this.closeStaleConnection(this.connection);
306
- this.cancelGrace();
307
- this.resetBufferedMessages();
308
- clearInterval(this.heartbeat);
309
- }
310
- get connected() {
311
- return this.connection !== void 0;
312
- }
313
- get nextExpectedSeq() {
314
- return this.ack;
315
- }
316
- constructMsg(partialMsg) {
317
- const msg = {
318
- ...partialMsg,
319
- id: unsafeId(),
320
- to: this.to,
321
- from: this.from,
322
- seq: this.seq,
323
- ack: this.ack
324
- };
325
- this.seq++;
326
- return msg;
327
- }
328
- inspectSendBuffer() {
329
- return this.sendBuffer;
330
- }
331
- };
332
-
333
- // codec/json.ts
334
- var encoder = new TextEncoder();
335
- var decoder = new TextDecoder();
336
- function uint8ArrayToBase64(uint8Array) {
337
- let binary = "";
338
- uint8Array.forEach((byte) => {
339
- binary += String.fromCharCode(byte);
340
- });
341
- return btoa(binary);
342
- }
343
- function base64ToUint8Array(base64) {
344
- const binaryString = atob(base64);
345
- const uint8Array = new Uint8Array(binaryString.length);
346
- for (let i = 0; i < binaryString.length; i++) {
347
- uint8Array[i] = binaryString.charCodeAt(i);
348
- }
349
- return uint8Array;
350
- }
351
- var NaiveJsonCodec = {
352
- toBuffer: (obj) => {
353
- return encoder.encode(
354
- JSON.stringify(obj, function replacer(key) {
355
- const val = this[key];
356
- if (val instanceof Uint8Array) {
357
- return { $t: uint8ArrayToBase64(val) };
358
- } else {
359
- return val;
360
- }
361
- })
362
- );
363
- },
364
- fromBuffer: (buff) => {
365
- try {
366
- const parsed = JSON.parse(
367
- decoder.decode(buff),
368
- function reviver(_key, val) {
369
- if (val?.$t) {
370
- return base64ToUint8Array(val.$t);
371
- } else {
372
- return val;
373
- }
374
- }
375
- );
376
- if (typeof parsed === "object")
377
- return parsed;
378
- return null;
379
- } catch {
380
- return null;
381
- }
382
- }
383
- };
384
-
385
- // transport/transport.ts
386
- var import_nanoid3 = require("nanoid");
387
-
388
- // util/stringify.ts
389
- function coerceErrorString(err) {
390
- if (err instanceof Error) {
391
- return err.message;
392
- }
393
- return `[coerced to error] ${String(err)}`;
394
- }
395
-
396
- // transport/transport.ts
397
- var DEFAULT_RECONNECT_JITTER_MAX_MS = 500;
398
- var DEFAULT_RECONNECT_INTERVAL_MS = 250;
399
- var defaultTransportOptions = {
400
- retryIntervalMs: DEFAULT_RECONNECT_INTERVAL_MS,
401
- retryJitterMs: DEFAULT_RECONNECT_JITTER_MAX_MS,
402
- retryAttemptsMax: 5,
403
- codec: NaiveJsonCodec
404
- };
405
- var Transport = class {
406
- /**
407
- * Unique per instance of the transport.
408
- * This allows us to distinguish reconnects to different
409
- * transports.
410
- */
411
- instanceId = (0, import_nanoid3.nanoid)();
412
- connectedInstanceIds = /* @__PURE__ */ new Map();
413
- /**
414
- * A flag indicating whether the transport has been destroyed.
415
- * A destroyed transport will not attempt to reconnect and cannot be used again.
416
- */
417
- state;
418
- /**
419
- * The {@link Codec} used to encode and decode messages.
420
- */
421
- codec;
422
- /**
423
- * The client ID of this transport.
424
- */
425
- clientId;
426
- /**
427
- * The map of {@link Session}s managed by this transport.
428
- */
429
- sessions;
430
- /**
431
- * The map of {@link Connection}s managed by this transport.
432
- */
433
- get connections() {
434
- return new Map(
435
- [...this.sessions].map(([client, session]) => [client, session.connection]).filter((entry) => entry[1] !== void 0)
436
- );
437
- }
438
- /**
439
- * The event dispatcher for handling events of type EventTypes.
440
- */
441
- eventDispatcher;
442
- /**
443
- * The options for this transport.
444
- */
445
- options;
446
- /**
447
- * Creates a new Transport instance.
448
- * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
449
- * @param codec The codec used to encode and decode messages.
450
- * @param clientId The client ID of this transport.
451
- */
452
- constructor(clientId, providedOptions) {
453
- this.options = { ...defaultTransportOptions, ...providedOptions };
454
- this.eventDispatcher = new EventDispatcher();
455
- this.sessions = /* @__PURE__ */ new Map();
456
- this.codec = this.options.codec;
457
- this.clientId = clientId;
458
- this.state = "open";
459
- }
460
- /**
461
- * Called when a new connection is established
462
- * and we know the identity of the connected client.
463
- * @param conn The connection object.
464
- */
465
- onConnect(conn, connectedTo, instanceId) {
466
- this.eventDispatcher.dispatchEvent("connectionStatus", {
467
- status: "connect",
468
- conn
469
- });
470
- let oldSession = this.sessions.get(connectedTo);
471
- const lastInstanceId = this.connectedInstanceIds.get(connectedTo);
472
- if (oldSession && lastInstanceId !== void 0 && lastInstanceId !== instanceId) {
473
- log?.warn(
474
- `${this.clientId} -- handshake from ${connectedTo} is a different instance (got: ${instanceId}, last connected to: ${lastInstanceId}), starting a new session`
475
- );
476
- oldSession.close();
477
- this.deleteSession(oldSession);
478
- oldSession = void 0;
479
- }
480
- this.connectedInstanceIds.set(connectedTo, instanceId);
481
- if (oldSession === void 0) {
482
- const newSession = this.createSession(connectedTo, conn);
483
- log?.info(
484
- `${this.clientId} -- new connection (id: ${conn.debugId}) for new session (id: ${newSession.debugId}) to ${connectedTo}`
485
- );
486
- return newSession;
487
- }
488
- log?.info(
489
- `${this.clientId} -- new connection (id: ${conn.debugId}) for existing session (id: ${oldSession.debugId}) to ${connectedTo}`
490
- );
491
- oldSession.replaceWithNewConnection(conn);
492
- oldSession.sendBufferedMessages();
493
- return oldSession;
494
- }
495
- createSession(connectedTo, conn) {
496
- const session = new Session(
497
- this.codec,
498
- this.clientId,
499
- connectedTo,
500
- conn
501
- );
502
- this.sessions.set(session.to, session);
503
- this.eventDispatcher.dispatchEvent("sessionStatus", {
504
- status: "connect",
505
- session
506
- });
507
- return session;
508
- }
509
- deleteSession(session) {
510
- this.sessions.delete(session.to);
511
- log?.info(
512
- `${this.clientId} -- session ${session.debugId} disconnect from ${session.to}`
513
- );
514
- this.eventDispatcher.dispatchEvent("sessionStatus", {
515
- status: "disconnect",
516
- session
517
- });
518
- }
519
- /**
520
- * The downstream implementation needs to call this when a connection is closed.
521
- * @param conn The connection object.
522
- * @param connectedTo The peer we are connected to.
523
- */
524
- onDisconnect(conn, connectedTo) {
525
- this.eventDispatcher.dispatchEvent("connectionStatus", {
526
- status: "disconnect",
527
- conn
528
- });
529
- const session = this.sessions.get(connectedTo);
530
- if (!session)
531
- return;
532
- session.connection = void 0;
533
- session.beginGrace(() => this.deleteSession(session));
534
- }
535
- /**
536
- * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
537
- * @param msg The message to parse.
538
- * @returns The parsed message, or null if the message is malformed or invalid.
539
- */
540
- parseMsg(msg) {
541
- const parsedMsg = this.codec.fromBuffer(msg);
542
- if (parsedMsg === null) {
543
- const decodedBuffer = new TextDecoder().decode(msg);
544
- log?.error(
545
- `${this.clientId} -- received malformed msg, killing conn: ${decodedBuffer}`
546
- );
547
- return null;
548
- }
549
- if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
550
- log?.error(
551
- `${this.clientId} -- received invalid msg: ${JSON.stringify(
552
- parsedMsg
553
- )}`
554
- );
555
- return null;
556
- }
557
- return {
558
- ...parsedMsg,
559
- serviceName: parsedMsg.serviceName === null ? void 0 : parsedMsg.serviceName,
560
- procedureName: parsedMsg.procedureName === null ? void 0 : parsedMsg.procedureName
561
- };
562
- }
563
- /**
564
- * Called when a message is received by this transport.
565
- * You generally shouldn't need to override this in downstream transport implementations.
566
- * @param msg The received message.
567
- */
568
- handleMsg(msg) {
569
- if (this.state !== "open")
570
- return;
571
- const session = this.sessions.get(msg.from);
572
- if (!session) {
573
- const err = `${this.clientId} -- (invariant violation) no existing session for ${msg.from}`;
574
- log?.error(err);
575
- return;
576
- }
577
- session.cancelGrace();
578
- log?.debug(`${this.clientId} -- received msg: ${JSON.stringify(msg)}`);
579
- if (msg.seq !== session.nextExpectedSeq) {
580
- log?.warn(
581
- `${this.clientId} -- received out-of-order msg (got: ${msg.seq}, wanted: ${session.nextExpectedSeq}), discarding: ${JSON.stringify(
582
- msg
583
- )}`
584
- );
585
- return;
586
- }
587
- if (!isAck(msg.controlFlags)) {
588
- this.eventDispatcher.dispatchEvent("message", msg);
589
- }
590
- session.updateBookkeeping(msg.ack, msg.seq);
591
- }
592
- /**
593
- * Adds a listener to this transport.
594
- * @param the type of event to listen for
595
- * @param handler The message handler to add.
596
- */
597
- addEventListener(type, handler) {
598
- this.eventDispatcher.addEventListener(type, handler);
599
- }
600
- /**
601
- * Removes a listener from this transport.
602
- * @param the type of event to unlisten on
603
- * @param handler The message handler to remove.
604
- */
605
- removeEventListener(type, handler) {
606
- this.eventDispatcher.removeEventListener(type, handler);
607
- }
608
- /**
609
- * Sends a message over this transport, delegating to the appropriate connection to actually
610
- * send the message.
611
- * @param msg The message to send.
612
- * @returns The ID of the sent message or undefined if it wasn't sent
613
- */
614
- send(to, msg) {
615
- if (this.state === "destroyed") {
616
- const err = "transport is destroyed, cant send";
617
- log?.error(`${this.clientId} -- ` + err + `: ${JSON.stringify(msg)}`);
618
- throw new Error(err);
619
- } else if (this.state === "closed") {
620
- log?.info(
621
- `${this.clientId} -- transport closed when sending, discarding : ${JSON.stringify(
622
- msg
623
- )}`
624
- );
625
- return void 0;
626
- }
627
- let session = this.sessions.get(to);
628
- if (!session) {
629
- session = this.createSession(to, void 0);
630
- log?.info(
631
- `${this.clientId} -- no session for ${to}, created a new one (id: ${session.debugId})`
632
- );
633
- }
634
- return session.send(msg);
635
- }
636
- // control helpers
637
- sendCloseStream(to, streamId) {
638
- return this.send(to, {
639
- streamId,
640
- controlFlags: 4 /* StreamClosedBit */,
641
- payload: {
642
- type: "CLOSE"
643
- }
644
- });
645
- }
646
- /**
647
- * Default close implementation for transports. You should override this in the downstream
648
- * implementation if you need to do any additional cleanup and call super.close() at the end.
649
- * Closes the transport. Any messages sent while the transport is closed will be silently discarded.
650
- */
651
- close() {
652
- this.state = "closed";
653
- for (const session of this.sessions.values()) {
654
- session.close();
655
- this.deleteSession(session);
656
- }
657
- log?.info(`${this.clientId} -- manually closed transport`);
658
- }
659
- /**
660
- * Default destroy implementation for transports. You should override this in the downstream
661
- * implementation if you need to do any additional cleanup and call super.destroy() at the end.
662
- * Destroys the transport. Any messages sent while the transport is destroyed will throw an error.
663
- */
664
- destroy() {
665
- this.state = "destroyed";
666
- for (const session of this.sessions.values()) {
667
- session.close();
668
- this.deleteSession(session);
669
- }
670
- log?.info(`${this.clientId} -- manually destroyed transport`);
671
- }
672
- };
673
- var ClientTransport = class extends Transport {
674
- /**
675
- * The map of reconnect promises for each client ID.
676
- */
677
- inflightConnectionPromises;
678
- tryReconnecting = true;
679
- constructor(clientId, providedOptions) {
680
- super(clientId, providedOptions);
681
- this.inflightConnectionPromises = /* @__PURE__ */ new Map();
682
- }
683
- handleConnection(conn, to) {
684
- const bootHandler = this.receiveWithBootSequence(conn, () => {
685
- conn.removeDataListener(bootHandler);
686
- conn.addDataListener((data) => {
687
- const parsed = this.parseMsg(data);
688
- if (!parsed) {
689
- conn.close();
690
- return;
691
- }
692
- this.handleMsg(parsed);
693
- });
694
- });
695
- conn.addDataListener(bootHandler);
696
- conn.addCloseListener(() => {
697
- this.onDisconnect(conn, to);
698
- void this.connect(to);
699
- });
700
- conn.addErrorListener((err) => {
701
- log?.warn(
702
- `${this.clientId} -- error in connection (id: ${conn.debugId}) to ${to}: ${coerceErrorString(err)}`
703
- );
704
- });
705
- }
706
- /**
707
- * Manually attempts to connect to a client.
708
- * @param to The client ID of the node to connect to.
709
- */
710
- async connect(to, attempt = 0) {
711
- if (this.state !== "open" || !this.tryReconnecting) {
712
- log?.info(
713
- `${this.clientId} -- transport state is no longer open, not attempting connection`
714
- );
715
- return;
716
- }
717
- let reconnectPromise = this.inflightConnectionPromises.get(to);
718
- if (!reconnectPromise) {
719
- reconnectPromise = this.createNewOutgoingConnection(to);
720
- this.inflightConnectionPromises.set(to, reconnectPromise);
721
- }
722
- try {
723
- const conn = await reconnectPromise;
724
- this.state = "open";
725
- const requestMsg = bootRequestMessage(this.clientId, to, this.instanceId);
726
- log?.debug(`${this.clientId} -- sending boot handshake to ${to}`);
727
- conn.send(this.codec.toBuffer(requestMsg));
728
- } catch (error) {
729
- const errStr = coerceErrorString(error);
730
- this.inflightConnectionPromises.delete(to);
731
- if (attempt >= this.options.retryAttemptsMax) {
732
- const errMsg = `connection to ${to} failed after ${attempt} attempts (${errStr}), giving up`;
733
- log?.error(`${this.clientId} -- ${errMsg}`);
734
- throw new Error(errMsg);
735
- } else {
736
- const jitter = Math.floor(Math.random() * this.options.retryJitterMs);
737
- const backoffMs = this.options.retryIntervalMs * 2 ** attempt + jitter;
738
- log?.warn(
739
- `${this.clientId} -- connection to ${to} failed (${errStr}), trying again in ${backoffMs}ms`
740
- );
741
- setTimeout(() => void this.connect(to, attempt + 1), backoffMs);
742
- }
743
- }
744
- }
745
- receiveWithBootSequence(conn, sessionCb) {
746
- const bootHandler = (data) => {
747
- const parsed = this.parseMsg(data);
748
- if (!parsed) {
749
- conn.close();
750
- return;
751
- }
752
- if (!import_value.Value.Check(ControlMessageHandshakeResponseSchema, parsed.payload)) {
753
- log?.warn(
754
- `${this.clientId} -- received invalid handshake resp: ${JSON.stringify(parsed)}`
755
- );
756
- return;
757
- }
758
- if (!parsed.payload.status.ok) {
759
- log?.warn(
760
- `${this.clientId} -- received failed handshake resp: ${JSON.stringify(
761
- parsed
762
- )}`
763
- );
764
- return;
765
- }
766
- const serverInstanceId = parsed.payload.status.instanceId;
767
- log?.debug(
768
- `${this.clientId} -- handshake from ${parsed.from} ok (server instance: ${serverInstanceId})`
769
- );
770
- sessionCb(this.onConnect(conn, parsed.from, serverInstanceId));
771
- };
772
- return bootHandler;
773
- }
774
- onDisconnect(conn, connectedTo) {
775
- this.inflightConnectionPromises.delete(connectedTo);
776
- super.onDisconnect(conn, connectedTo);
777
- }
778
- };
779
-
780
- // transport/transforms/messageFraming.ts
781
- var import_node_stream = require("stream");
782
- var Uint32LengthPrefixFraming = class extends import_node_stream.Transform {
783
- receivedBuffer;
784
- maxBufferSizeBytes;
785
- constructor({ maxBufferSizeBytes, ...options }) {
786
- super(options);
787
- this.maxBufferSizeBytes = maxBufferSizeBytes;
788
- this.receivedBuffer = Buffer.alloc(0);
789
- }
790
- _transform(chunk, _encoding, cb) {
791
- if (this.receivedBuffer.byteLength + chunk.byteLength > this.maxBufferSizeBytes) {
792
- const err = new Error(
793
- `buffer overflow: ${this.receivedBuffer.byteLength}B > ${this.maxBufferSizeBytes}B`
794
- );
795
- this.emit("error", err);
796
- cb(err);
797
- return;
798
- }
799
- this.receivedBuffer = Buffer.concat([this.receivedBuffer, chunk]);
800
- while (this.receivedBuffer.length > 4) {
801
- const claimedMessageLength = this.receivedBuffer.readUInt32BE(0) + 4;
802
- if (this.receivedBuffer.length >= claimedMessageLength) {
803
- const message = this.receivedBuffer.subarray(4, claimedMessageLength);
804
- this.push(message);
805
- this.receivedBuffer = this.receivedBuffer.subarray(claimedMessageLength);
806
- } else {
807
- break;
808
- }
809
- }
810
- cb();
811
- }
812
- _flush(cb) {
813
- if (this.receivedBuffer.length) {
814
- this.emit("error", new Error("got incomplete message while flushing"));
815
- }
816
- this.receivedBuffer = Buffer.alloc(0);
817
- cb();
818
- }
819
- _destroy(error, callback) {
820
- this.receivedBuffer = Buffer.alloc(0);
821
- super._destroy(error, callback);
822
- }
823
- };
824
- function createLengthEncodedStream(options) {
825
- return new Uint32LengthPrefixFraming({
826
- maxBufferSizeBytes: options?.maxBufferSizeBytes ?? 16 * 1024 * 1024
827
- // 16MB
828
- });
829
- }
830
- var MessageFramer = {
831
- createFramedStream: createLengthEncodedStream,
832
- write: (buf) => {
833
- const lengthPrefix = Buffer.alloc(4);
834
- lengthPrefix.writeUInt32BE(buf.length, 0);
835
- return Buffer.concat([lengthPrefix, buf]);
836
- }
837
- };
838
-
839
- // transport/impls/stdio/connection.ts
840
- var StreamConnection = class extends Connection {
841
- input;
842
- output;
843
- framer;
844
- constructor(input, output) {
845
- super();
846
- this.framer = MessageFramer.createFramedStream();
847
- this.input = input.pipe(this.framer);
848
- this.output = output;
849
- }
850
- addDataListener(cb) {
851
- this.input.on("data", cb);
852
- }
853
- removeDataListener(cb) {
854
- this.input.off("data", cb);
855
- }
856
- addCloseListener(cb) {
857
- this.input.on("close", cb);
858
- this.output.on("close", cb);
859
- }
860
- addErrorListener(cb) {
861
- this.input.on("error", cb);
862
- this.output.on("error", cb);
863
- }
864
- send(payload) {
865
- if (!this.output.writable)
866
- return false;
867
- return this.output.write(MessageFramer.write(payload));
868
- }
869
- close() {
870
- this.output.end();
871
- this.input.unpipe(this.framer);
872
- this.framer.destroy();
873
- }
874
- };
875
-
876
- // transport/impls/stdio/client.ts
877
- var StdioClientTransport = class extends ClientTransport {
878
- input = process.stdin;
879
- output = process.stdout;
880
- serverId;
881
- /**
882
- * Constructs a new StdioClientTransport instance.
883
- * @param clientId - The ID of the client associated with this transport.
884
- * @param input - The readable stream to use as input. Defaults to process.stdin.
885
- * @param output - The writable stream to use as output. Defaults to process.stdout.
886
- */
887
- constructor(clientId, input = process.stdin, output = process.stdout, serverId, providedOptions) {
888
- super(clientId, providedOptions);
889
- this.input = input;
890
- this.output = output;
891
- this.serverId = serverId;
892
- void this.connect(serverId);
893
- }
894
- async createNewOutgoingConnection(to) {
895
- log?.info(`${this.clientId} -- establishing a new stream to ${to}`);
896
- const conn = new StreamConnection(this.input, this.output);
897
- this.handleConnection(conn, to);
898
- return Promise.resolve(conn);
899
- }
900
- };
901
- // Annotate the CommonJS export names for ESM import in node:
902
- 0 && (module.exports = {
903
- StdioClientTransport
904
- });