@replit/river 0.23.16 → 0.24.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 (85) hide show
  1. package/README.md +21 -20
  2. package/dist/{chunk-UDXM64QK.js → chunk-AASMR3CQ.js} +24 -18
  3. package/dist/chunk-AASMR3CQ.js.map +1 -0
  4. package/dist/chunk-JA57I7MG.js +653 -0
  5. package/dist/chunk-JA57I7MG.js.map +1 -0
  6. package/dist/chunk-KX5PQRVN.js +382 -0
  7. package/dist/chunk-KX5PQRVN.js.map +1 -0
  8. package/dist/{chunk-LTSLICON.js → chunk-KYYB4DUR.js} +68 -519
  9. package/dist/chunk-KYYB4DUR.js.map +1 -0
  10. package/dist/chunk-NLQPPDOT.js +399 -0
  11. package/dist/chunk-NLQPPDOT.js.map +1 -0
  12. package/dist/{chunk-TXSQRTZB.js → chunk-PJGGC3LV.js} +55 -41
  13. package/dist/chunk-PJGGC3LV.js.map +1 -0
  14. package/dist/chunk-RXJLI2OP.js +50 -0
  15. package/dist/chunk-RXJLI2OP.js.map +1 -0
  16. package/dist/{chunk-6LCL2ZZF.js → chunk-TAH2GVTJ.js} +1 -1
  17. package/dist/chunk-TAH2GVTJ.js.map +1 -0
  18. package/dist/chunk-ZAT3R4CU.js +277 -0
  19. package/dist/chunk-ZAT3R4CU.js.map +1 -0
  20. package/dist/{client-0926d3d6.d.ts → client-ba0d3315.d.ts} +12 -15
  21. package/dist/{connection-99a67d3e.d.ts → connection-c3a96d09.d.ts} +1 -5
  22. package/dist/connection-d33e3246.d.ts +11 -0
  23. package/dist/{handshake-75d0124f.d.ts → handshake-cdead82a.d.ts} +149 -180
  24. package/dist/logging/index.cjs.map +1 -1
  25. package/dist/logging/index.d.cts +1 -1
  26. package/dist/logging/index.d.ts +1 -1
  27. package/dist/logging/index.js +1 -1
  28. package/dist/{index-ea74cdbb.d.ts → message-e6c560fd.d.ts} +2 -2
  29. package/dist/router/index.cjs +107 -530
  30. package/dist/router/index.cjs.map +1 -1
  31. package/dist/router/index.d.cts +12 -50
  32. package/dist/router/index.d.ts +12 -50
  33. package/dist/router/index.js +2 -4
  34. package/dist/server-2ef5e6ec.d.ts +42 -0
  35. package/dist/{services-75e84a9f.d.ts → services-e1417b33.d.ts} +7 -7
  36. package/dist/transport/impls/uds/client.cjs +1242 -1223
  37. package/dist/transport/impls/uds/client.cjs.map +1 -1
  38. package/dist/transport/impls/uds/client.d.cts +4 -4
  39. package/dist/transport/impls/uds/client.d.ts +4 -4
  40. package/dist/transport/impls/uds/client.js +7 -13
  41. package/dist/transport/impls/uds/client.js.map +1 -1
  42. package/dist/transport/impls/uds/server.cjs +1301 -1151
  43. package/dist/transport/impls/uds/server.cjs.map +1 -1
  44. package/dist/transport/impls/uds/server.d.cts +4 -4
  45. package/dist/transport/impls/uds/server.d.ts +4 -4
  46. package/dist/transport/impls/uds/server.js +6 -6
  47. package/dist/transport/impls/ws/client.cjs +980 -969
  48. package/dist/transport/impls/ws/client.cjs.map +1 -1
  49. package/dist/transport/impls/ws/client.d.cts +4 -4
  50. package/dist/transport/impls/ws/client.d.ts +4 -4
  51. package/dist/transport/impls/ws/client.js +6 -7
  52. package/dist/transport/impls/ws/client.js.map +1 -1
  53. package/dist/transport/impls/ws/server.cjs +1182 -1047
  54. package/dist/transport/impls/ws/server.cjs.map +1 -1
  55. package/dist/transport/impls/ws/server.d.cts +4 -4
  56. package/dist/transport/impls/ws/server.d.ts +4 -4
  57. package/dist/transport/impls/ws/server.js +6 -6
  58. package/dist/transport/index.cjs +1434 -1360
  59. package/dist/transport/index.cjs.map +1 -1
  60. package/dist/transport/index.d.cts +4 -4
  61. package/dist/transport/index.d.ts +4 -4
  62. package/dist/transport/index.js +9 -9
  63. package/dist/util/testHelpers.cjs +743 -309
  64. package/dist/util/testHelpers.cjs.map +1 -1
  65. package/dist/util/testHelpers.d.cts +10 -7
  66. package/dist/util/testHelpers.d.ts +10 -7
  67. package/dist/util/testHelpers.js +33 -10
  68. package/dist/util/testHelpers.js.map +1 -1
  69. package/package.json +1 -1
  70. package/dist/chunk-6LCL2ZZF.js.map +0 -1
  71. package/dist/chunk-JA7XGTAL.js +0 -476
  72. package/dist/chunk-JA7XGTAL.js.map +0 -1
  73. package/dist/chunk-LTSLICON.js.map +0 -1
  74. package/dist/chunk-MQCGG6KL.js +0 -335
  75. package/dist/chunk-MQCGG6KL.js.map +0 -1
  76. package/dist/chunk-R47IZD67.js +0 -59
  77. package/dist/chunk-R47IZD67.js.map +0 -1
  78. package/dist/chunk-TXSQRTZB.js.map +0 -1
  79. package/dist/chunk-UDXM64QK.js.map +0 -1
  80. package/dist/chunk-WN77AT67.js +0 -476
  81. package/dist/chunk-WN77AT67.js.map +0 -1
  82. package/dist/chunk-YXDAOVP7.js +0 -347
  83. package/dist/chunk-YXDAOVP7.js.map +0 -1
  84. package/dist/connection-d738cc08.d.ts +0 -17
  85. package/dist/server-3740c5d9.d.ts +0 -24
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../transport/events.ts","../transport/transport.ts","../transport/connection.ts"],"sourcesContent":["import { Connection } from './connection';\nimport { OpaqueTransportMessage } from './message';\nimport { Session, SessionState } from './sessionStateMachine';\nimport { TransportStatus } from './transport';\n\nexport const ProtocolError = {\n RetriesExceeded: 'conn_retry_exceeded',\n HandshakeFailed: 'handshake_failed',\n MessageOrderingViolated: 'message_ordering_violated',\n} as const;\n\nexport type ProtocolErrorType =\n (typeof ProtocolError)[keyof typeof ProtocolError];\n\nexport interface EventMap {\n message: OpaqueTransportMessage;\n sessionStatus: {\n status: 'connect' | 'disconnect';\n session: Session<Connection>;\n };\n sessionTransition:\n | { state: SessionState.Connected }\n | { state: SessionState.Handshaking }\n | { state: SessionState.Connecting }\n | { state: SessionState.NoConnection };\n protocolError: {\n type: ProtocolErrorType;\n message: string;\n };\n transportStatus: {\n status: TransportStatus;\n };\n}\n\nexport type EventTypes = keyof EventMap;\nexport type EventHandler<K extends EventTypes> = (\n event: EventMap[K],\n) => unknown;\n\nexport class EventDispatcher<T extends EventTypes> {\n private eventListeners: { [K in T]?: Set<EventHandler<K>> } = {};\n\n removeAllListeners() {\n this.eventListeners = {};\n }\n\n numberOfListeners<K extends T>(eventType: K) {\n return this.eventListeners[eventType]?.size ?? 0;\n }\n\n addEventListener<K extends T>(eventType: K, handler: EventHandler<K>) {\n if (!this.eventListeners[eventType]) {\n this.eventListeners[eventType] = new Set();\n }\n\n this.eventListeners[eventType]?.add(handler);\n }\n\n removeEventListener<K extends T>(eventType: K, handler: EventHandler<K>) {\n const handlers = this.eventListeners[eventType];\n if (handlers) {\n this.eventListeners[eventType]?.delete(handler);\n }\n }\n\n dispatchEvent<K extends T>(eventType: K, event: EventMap[K]) {\n const handlers = this.eventListeners[eventType];\n if (handlers) {\n // copying ensures that adding more listeners in a handler doesn't\n // affect the current dispatch.\n const copy = [...handlers];\n for (const handler of copy) {\n handler(event);\n }\n }\n }\n}\n","import {\n OpaqueTransportMessage,\n TransportClientId,\n PartialTransportMessage,\n} from './message';\nimport {\n BaseLogger,\n LogFn,\n Logger,\n LoggingLevel,\n createLogProxy,\n} from '../logging/log';\nimport {\n EventDispatcher,\n EventHandler,\n EventMap,\n EventTypes,\n ProtocolErrorType,\n} from './events';\nimport {\n ProvidedTransportOptions,\n TransportOptions,\n defaultTransportOptions,\n} from './options';\nimport {\n Session,\n SessionConnected,\n SessionConnecting,\n SessionHandshaking,\n SessionNoConnection,\n SessionState,\n SessionStateGraph,\n} from './sessionStateMachine';\nimport { Connection } from './connection';\n\n/**\n * Represents the possible states of a transport.\n * @property {'open'} open - The transport is open and operational (note that this doesn't mean it is actively connected)\n * @property {'closed'} closed - The transport is permanently closed and cannot be reopened.\n */\nexport type TransportStatus = 'open' | 'closed';\n\n/**\n * Transports manage the lifecycle (creation/deletion) of sessions\n *\n * ```plaintext\n * ▲\n * incoming │\n * messages │\n * ▼\n * ┌─────────────┐ 1:N ┌───────────┐ 1:1* ┌────────────┐\n * │ Transport │ ◄─────► │ Session │ ◄─────► │ Connection │\n * └─────────────┘ └───────────┘ └────────────┘\n * ▲ * (may or may not be initialized yet)\n * │\n * ▼\n * ┌───────────┐\n * │ Message │\n * │ Listeners │\n * └───────────┘\n * ```\n * @abstract\n */\nexport abstract class Transport<ConnType extends Connection> {\n /**\n * The status of the transport.\n */\n private status: TransportStatus;\n\n /**\n * The client ID of this transport.\n */\n clientId: TransportClientId;\n\n /**\n * The event dispatcher for handling events of type EventTypes.\n */\n eventDispatcher: EventDispatcher<EventTypes>;\n\n /**\n * The options for this transport.\n */\n protected options: TransportOptions;\n log?: Logger;\n\n sessions: Map<TransportClientId, Session<ConnType>>;\n\n /**\n * Creates a new Transport instance.\n * @param codec The codec used to encode and decode messages.\n * @param clientId The client ID of this transport.\n */\n constructor(\n clientId: TransportClientId,\n providedOptions?: ProvidedTransportOptions,\n ) {\n this.options = { ...defaultTransportOptions, ...providedOptions };\n this.eventDispatcher = new EventDispatcher();\n this.clientId = clientId;\n this.status = 'open';\n this.sessions = new Map();\n }\n\n bindLogger(fn: LogFn | Logger, level?: LoggingLevel) {\n // construct logger from fn\n if (typeof fn === 'function') {\n this.log = createLogProxy(new BaseLogger(fn, level));\n return;\n }\n\n // object case, just assign\n this.log = createLogProxy(fn);\n }\n\n /**\n * Called when a message is received by this transport.\n * You generally shouldn't need to override this in downstream transport implementations.\n * @param msg The received message.\n */\n protected handleMsg(msg: OpaqueTransportMessage) {\n if (this.getStatus() !== 'open') return;\n this.eventDispatcher.dispatchEvent('message', msg);\n }\n\n /**\n * Adds a listener to this transport.\n * @param the type of event to listen for\n * @param handler The message handler to add.\n */\n addEventListener<K extends EventTypes, T extends EventHandler<K>>(\n type: K,\n handler: T,\n ): void {\n this.eventDispatcher.addEventListener(type, handler);\n }\n\n /**\n * Removes a listener from this transport.\n * @param the type of event to un-listen on\n * @param handler The message handler to remove.\n */\n removeEventListener<K extends EventTypes, T extends EventHandler<K>>(\n type: K,\n handler: T,\n ): void {\n this.eventDispatcher.removeEventListener(type, handler);\n }\n\n /**\n * Sends a message over this transport, delegating to the appropriate connection to actually\n * send the message.\n * @param msg The message to send.\n * @returns The ID of the sent message or undefined if it wasn't sent\n */\n abstract send(to: TransportClientId, msg: PartialTransportMessage): string;\n\n protected protocolError(type: ProtocolErrorType, message: string) {\n this.eventDispatcher.dispatchEvent('protocolError', { type, message });\n }\n\n /**\n * Default close implementation for transports. You should override this in the downstream\n * implementation if you need to do any additional cleanup and call super.close() at the end.\n * Closes the transport. Any messages sent while the transport is closed will be silently discarded.\n */\n close() {\n this.status = 'closed';\n\n for (const session of this.sessions.values()) {\n this.deleteSession(session);\n }\n\n this.eventDispatcher.dispatchEvent('transportStatus', {\n status: this.status,\n });\n\n this.eventDispatcher.removeAllListeners();\n\n this.log?.info(`manually closed transport`, { clientId: this.clientId });\n }\n\n getStatus(): TransportStatus {\n return this.status;\n }\n\n protected updateSession<S extends Session<ConnType>>(session: S): S {\n const activeSession = this.sessions.get(session.to);\n if (activeSession && activeSession.id !== session.id) {\n const msg = `attempt to transition active session for ${session.to} but active session (${activeSession.id}) is different from handle (${session.id})`;\n throw new Error(msg);\n }\n\n this.sessions.set(session.to, session);\n\n if (!activeSession) {\n this.eventDispatcher.dispatchEvent('sessionStatus', {\n status: 'connect',\n session: session,\n });\n }\n\n this.eventDispatcher.dispatchEvent('sessionTransition', {\n state: session.state,\n session: session,\n } as EventMap['sessionTransition']);\n\n return session;\n }\n\n // state transitions\n protected deleteSession(session: Session<ConnType>) {\n session.log?.info(`closing session ${session.id}`, session.loggingMetadata);\n\n this.eventDispatcher.dispatchEvent('sessionStatus', {\n status: 'disconnect',\n session: session,\n });\n\n session.close();\n this.sessions.delete(session.to);\n }\n\n // common listeners\n protected onSessionGracePeriodElapsed(session: SessionNoConnection) {\n this.log?.warn(\n `session to ${session.to} grace period elapsed, closing`,\n session.loggingMetadata,\n );\n\n this.deleteSession(session);\n }\n\n protected onConnectingFailed(\n session: SessionConnecting<ConnType>,\n ): SessionNoConnection {\n // transition to no connection\n const noConnectionSession =\n SessionStateGraph.transition.ConnectingToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n\n return this.updateSession(noConnectionSession);\n }\n\n protected onConnClosed(\n session: SessionHandshaking<ConnType> | SessionConnected<ConnType>,\n ): SessionNoConnection {\n // transition to no connection\n let noConnectionSession: SessionNoConnection;\n if (session.state === SessionState.Handshaking) {\n noConnectionSession =\n SessionStateGraph.transition.HandshakingToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n } else {\n noConnectionSession =\n SessionStateGraph.transition.ConnectedToNoConnection(session, {\n onSessionGracePeriodElapsed: () => {\n this.onSessionGracePeriodElapsed(noConnectionSession);\n },\n });\n }\n\n return this.updateSession(noConnectionSession);\n }\n}\n","import { TelemetryInfo } from '../tracing';\nimport { MessageMetadata } from '../logging';\nimport { generateId } from './id';\n\n/**\n * A connection is the actual raw underlying transport connection.\n * It’s responsible for dispatching to/from the actual connection itself\n * This should be instantiated as soon as the client/server has a connection\n * It’s tied to the lifecycle of the underlying transport connection (i.e. if the WS drops, this connection should be deleted)\n */\nexport abstract class Connection {\n id: string;\n telemetry?: TelemetryInfo;\n constructor() {\n this.id = `conn-${generateId()}`; // for debugging, no collision safety needed\n }\n\n get loggingMetadata(): MessageMetadata {\n const metadata: MessageMetadata = { connId: this.id };\n const spanContext = this.telemetry?.span.spanContext();\n\n if (this.telemetry?.span.isRecording() && spanContext) {\n metadata.telemetry = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n };\n }\n\n return metadata;\n }\n\n // can't use event emitter because we need this to work in both node + browser\n private _dataListeners = new Set<(msg: Uint8Array) => void>();\n private _closeListeners = new Set<() => void>();\n private _errorListeners = new Set<(err: Error) => void>();\n\n get dataListeners() {\n return [...this._dataListeners];\n }\n\n get closeListeners() {\n return [...this._closeListeners];\n }\n\n get errorListeners() {\n return [...this._errorListeners];\n }\n\n /**\n * Handle adding a callback for when a message is received.\n * @param msg The message that was received.\n */\n addDataListener(cb: (msg: Uint8Array) => void) {\n this._dataListeners.add(cb);\n }\n\n removeDataListener(cb: (msg: Uint8Array) => void): void {\n this._dataListeners.delete(cb);\n }\n\n /**\n * Handle adding a callback for when the connection is closed.\n * This should also be called if an error happens and after notifying all the error listeners.\n * @param cb The callback to call when the connection is closed.\n */\n addCloseListener(cb: () => void): void {\n this._closeListeners.add(cb);\n }\n\n removeCloseListener(cb: () => void): void {\n this._closeListeners.delete(cb);\n }\n\n /**\n * Handle adding a callback for when an error is received.\n * This should only be used for this.logging errors, all cleanup\n * should be delegated to addCloseListener.\n *\n * The implementer should take care such that the implemented\n * connection will call both the close and error callbacks\n * on an error.\n *\n * @param cb The callback to call when an error is received.\n */\n addErrorListener(cb: (err: Error) => void): void {\n this._errorListeners.add(cb);\n }\n\n removeErrorListener(cb: (err: Error) => void): void {\n this._errorListeners.delete(cb);\n }\n\n /**\n * Sends a message over the connection.\n * @param msg The message to send.\n * @returns true if the message was sent, false otherwise.\n */\n abstract send(msg: Uint8Array): boolean;\n\n /**\n * Closes the connection.\n */\n abstract close(): void;\n}\n"],"mappings":";;;;;;;;;;;;;AAKO,IAAM,gBAAgB;AAAA,EAC3B,iBAAiB;AAAA,EACjB,iBAAiB;AAAA,EACjB,yBAAyB;AAC3B;AA8BO,IAAM,kBAAN,MAA4C;AAAA,EACzC,iBAAsD,CAAC;AAAA,EAE/D,qBAAqB;AACnB,SAAK,iBAAiB,CAAC;AAAA,EACzB;AAAA,EAEA,kBAA+B,WAAc;AAC3C,WAAO,KAAK,eAAe,SAAS,GAAG,QAAQ;AAAA,EACjD;AAAA,EAEA,iBAA8B,WAAc,SAA0B;AACpE,QAAI,CAAC,KAAK,eAAe,SAAS,GAAG;AACnC,WAAK,eAAe,SAAS,IAAI,oBAAI,IAAI;AAAA,IAC3C;AAEA,SAAK,eAAe,SAAS,GAAG,IAAI,OAAO;AAAA,EA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AAA;AAAA,EAGQ,iBAAiB,oBAAI,IAA+B;AAAA,EACpD,kBAAkB,oBAAI,IAAgB;AAAA,EACtC,kBAAkB,oBAAI,IAA0B;AAAA,EAExD,IAAI,gBAAgB;AAClB,WAAO,CAAC,GAAG,KAAK,cAAc;AAAA,EAChC;AAAA,EAEA,IAAI,iBAAiB;AACnB,WAAO,CAAC,GAAG,KAAK,eAAe;AAAA,EACjC;AAAA,EAEA,IAAI,iBAAiB;AACnB,WAAO,CAAC,GAAG,KAAK,eAAe;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,gBAAgB,IAA+B;AAC7C,SAAK,eAAe,IAAI,EAAE;AAAA,EAC5B;AAAA,EAEA,mBAAmB,IAAqC;AACtD,SAAK,eAAe,OAAO,EAAE;AAAA,EAC/B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,iBAAiB,IAAsB;AACrC,SAAK,gBAAgB,IAAI,EAAE;AAAA,EAC7B;AAAA,EAEA,oBAAoB,IAAsB;AACxC,SAAK,gBAAgB,OAAO,EAAE;AAAA,EAChC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,iBAAiB,IAAgC;AAC/C,SAAK,gBAAgB,IAAI,EAAE;AAAA,EAC7B;AAAA,EAEA,oBAAoB,IAAgC;AAClD,SAAK,gBAAgB,OAAO,EAAE;AAAA,EAChC;AAaF;","names":[]}
@@ -1,15 +1,11 @@
1
- import { C as Connection, T as Transport, j as ClientTransportOptions, L as LeakyBucketRateLimit, k as ClientHandshakeOptions, b as ProvidedClientTransportOptions, S as Session } from './handshake-75d0124f.js';
2
- import { c as TransportClientId } from './index-ea74cdbb.js';
1
+ import { C as Connection, T as Transport, o as ClientTransportOptions, L as LeakyBucketRateLimit, p as ClientHandshakeOptions, b as ProvidedClientTransportOptions, f as SessionConnecting, e as SessionNoConnection, g as SessionHandshaking, h as SessionConnected } from './handshake-cdead82a.js';
2
+ import { c as TransportClientId, P as PartialTransportMessage, b as OpaqueTransportMessage } from './message-e6c560fd.js';
3
3
 
4
4
  declare abstract class ClientTransport<ConnType extends Connection> extends Transport<ConnType> {
5
5
  /**
6
6
  * The options for this transport.
7
7
  */
8
8
  protected options: ClientTransportOptions;
9
- /**
10
- * The map of reconnect promises for each client ID.
11
- */
12
- inflightConnectionPromises: Map<TransportClientId, Promise<ConnType>>;
13
9
  retryBudget: LeakyBucketRateLimit;
14
10
  /**
15
11
  * A flag indicating whether the transport should automatically reconnect
@@ -24,8 +20,6 @@ declare abstract class ClientTransport<ConnType extends Connection> extends Tran
24
20
  handshakeExtensions?: ClientHandshakeOptions;
25
21
  constructor(clientId: TransportClientId, providedOptions?: ProvidedClientTransportOptions);
26
22
  extendHandshake(options: ClientHandshakeOptions): void;
27
- protected handleConnection(conn: ConnType, to: TransportClientId): void;
28
- receiveHandshakeResponseMessage(data: Uint8Array, conn: ConnType): Session<ConnType> | false;
29
23
  /**
30
24
  * Abstract method that creates a new {@link Connection} object.
31
25
  * This should call {@link handleConnection} when the connection is created.
@@ -35,17 +29,20 @@ declare abstract class ClientTransport<ConnType extends Connection> extends Tran
35
29
  * @returns The new connection object.
36
30
  */
37
31
  protected abstract createNewOutgoingConnection(to: TransportClientId): Promise<ConnType>;
32
+ private tryReconnecting;
33
+ send(to: string, msg: PartialTransportMessage): string;
34
+ private createUnconnectedSession;
35
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
36
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
37
+ protected onConnectionEstablished(session: SessionConnecting<ConnType>, conn: ConnType): SessionHandshaking<ConnType>;
38
+ private rejectHandshakeResponse;
39
+ protected onHandshakeResponse(session: SessionHandshaking<ConnType>, msg: OpaqueTransportMessage): void;
38
40
  /**
39
41
  * Manually attempts to connect to a client.
40
42
  * @param to The client ID of the node to connect to.
41
43
  */
42
- connect(to: TransportClientId): Promise<void>;
43
- protected deleteSession({ session, closeHandshakingConnection, handshakingConn, }: {
44
- session: Session<ConnType>;
45
- closeHandshakingConnection: boolean;
46
- handshakingConn?: ConnType;
47
- }): void;
48
- protected sendHandshake(to: TransportClientId, conn: ConnType): Promise<boolean>;
44
+ connect(to: TransportClientId): void;
45
+ private sendHandshake;
49
46
  close(): void;
50
47
  }
51
48
 
@@ -1,6 +1,6 @@
1
- import { C as Connection } from './handshake-75d0124f.js';
2
1
  import { Socket } from 'node:net';
3
2
  import stream, { Transform, TransformCallback, TransformOptions } from 'node:stream';
3
+ import { C as Connection } from './handshake-cdead82a.js';
4
4
 
5
5
  interface LengthEncodedOptions extends TransformOptions {
6
6
  /** Maximum in-memory buffer size before we throw */
@@ -24,10 +24,6 @@ declare class UdsConnection extends Connection {
24
24
  input: stream.Readable;
25
25
  framer: Uint32LengthPrefixFraming;
26
26
  constructor(sock: Socket);
27
- addDataListener(cb: (msg: Uint8Array) => void): void;
28
- removeDataListener(cb: (msg: Uint8Array) => void): void;
29
- addCloseListener(cb: () => void): void;
30
- addErrorListener(cb: (err: Error) => void): void;
31
27
  send(payload: Uint8Array): boolean;
32
28
  close(): void;
33
29
  }
@@ -0,0 +1,11 @@
1
+ import { C as Connection } from './handshake-cdead82a.js';
2
+ import { W as WsLike } from './wslike-e0b32dd5.js';
3
+
4
+ declare class WebSocketConnection extends Connection {
5
+ ws: WsLike;
6
+ constructor(ws: WsLike);
7
+ send(payload: Uint8Array): boolean;
8
+ close(): void;
9
+ }
10
+
11
+ export { WebSocketConnection as W };
@@ -1,5 +1,5 @@
1
+ import { e as TelemetryInfo, M as MessageMetadata, a as TransportMessage, b as OpaqueTransportMessage, P as PartialTransportMessage, c as TransportClientId, L as Logger, f as LogFn, g as LoggingLevel } from './message-e6c560fd.js';
1
2
  import { C as Codec } from './types-3e5768ec.js';
2
- import { e as TelemetryInfo, M as MessageMetadata, c as TransportClientId, f as PropagationContext, L as Logger, P as PartialTransportMessage, a as TransportMessage, b as OpaqueTransportMessage, g as LogFn, h as LoggingLevel } from './index-ea74cdbb.js';
3
3
  import { TSchema, Static } from '@sinclair/typebox';
4
4
 
5
5
  /**
@@ -13,18 +13,25 @@ declare abstract class Connection {
13
13
  telemetry?: TelemetryInfo;
14
14
  constructor();
15
15
  get loggingMetadata(): MessageMetadata;
16
+ private _dataListeners;
17
+ private _closeListeners;
18
+ private _errorListeners;
19
+ get dataListeners(): ((msg: Uint8Array) => void)[];
20
+ get closeListeners(): (() => void)[];
21
+ get errorListeners(): ((err: Error) => void)[];
16
22
  /**
17
23
  * Handle adding a callback for when a message is received.
18
24
  * @param msg The message that was received.
19
25
  */
20
- abstract addDataListener(cb: (msg: Uint8Array) => void): void;
21
- abstract removeDataListener(cb: (msg: Uint8Array) => void): void;
26
+ addDataListener(cb: (msg: Uint8Array) => void): void;
27
+ removeDataListener(cb: (msg: Uint8Array) => void): void;
22
28
  /**
23
29
  * Handle adding a callback for when the connection is closed.
24
- * This should also be called if an error happens.
30
+ * This should also be called if an error happens and after notifying all the error listeners.
25
31
  * @param cb The callback to call when the connection is closed.
26
32
  */
27
- abstract addCloseListener(cb: () => void): void;
33
+ addCloseListener(cb: () => void): void;
34
+ removeCloseListener(cb: () => void): void;
28
35
  /**
29
36
  * Handle adding a callback for when an error is received.
30
37
  * This should only be used for this.logging errors, all cleanup
@@ -36,7 +43,8 @@ declare abstract class Connection {
36
43
  *
37
44
  * @param cb The callback to call when an error is received.
38
45
  */
39
- abstract addErrorListener(cb: (err: Error) => void): void;
46
+ addErrorListener(cb: (err: Error) => void): void;
47
+ removeErrorListener(cb: (err: Error) => void): void;
40
48
  /**
41
49
  * Sends a message over the connection.
42
50
  * @param msg The message to send.
@@ -48,6 +56,93 @@ declare abstract class Connection {
48
56
  */
49
57
  abstract close(): void;
50
58
  }
59
+
60
+ interface SessionNoConnectionListeners {
61
+ onSessionGracePeriodElapsed: () => void;
62
+ }
63
+ declare class SessionNoConnection extends IdentifiedSession {
64
+ readonly state: SessionState.NoConnection;
65
+ listeners: SessionNoConnectionListeners;
66
+ gracePeriodTimeout?: ReturnType<typeof setTimeout>;
67
+ constructor(listeners: SessionNoConnectionListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
68
+ _handleClose(): void;
69
+ _handleStateExit(): void;
70
+ }
71
+
72
+ interface SessionConnectingListeners {
73
+ onConnectionEstablished: (conn: Connection) => void;
74
+ onConnectionFailed: (err: unknown) => void;
75
+ onConnectionTimeout: () => void;
76
+ }
77
+ declare class SessionConnecting<ConnType extends Connection> extends IdentifiedSession {
78
+ readonly state: SessionState.Connecting;
79
+ connPromise: Promise<ConnType>;
80
+ listeners: SessionConnectingListeners;
81
+ connectionTimeout?: ReturnType<typeof setTimeout>;
82
+ constructor(connPromise: Promise<ConnType>, listeners: SessionConnectingListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
83
+ bestEffortClose(): void;
84
+ _handleStateExit(): void;
85
+ _handleClose(): void;
86
+ }
87
+
88
+ interface SessionHandshakingListeners {
89
+ onConnectionErrored: (err: unknown) => void;
90
+ onConnectionClosed: () => void;
91
+ onHandshake: (msg: OpaqueTransportMessage) => void;
92
+ onInvalidHandshake: (reason: string) => void;
93
+ onHandshakeTimeout: () => void;
94
+ }
95
+ declare class SessionHandshaking<ConnType extends Connection> extends IdentifiedSession {
96
+ readonly state: SessionState.Handshaking;
97
+ conn: ConnType;
98
+ listeners: SessionHandshakingListeners;
99
+ handshakeTimeout: ReturnType<typeof setTimeout>;
100
+ constructor(conn: ConnType, listeners: SessionHandshakingListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
101
+ onHandshakeData: (msg: Uint8Array) => void;
102
+ sendHandshake(msg: TransportMessage): boolean;
103
+ _handleStateExit(): void;
104
+ _handleClose(): void;
105
+ }
106
+
107
+ interface SessionConnectedListeners {
108
+ onConnectionErrored: (err: unknown) => void;
109
+ onConnectionClosed: () => void;
110
+ onMessage: (msg: OpaqueTransportMessage) => void;
111
+ onInvalidMessage: (reason: string) => void;
112
+ }
113
+ declare class SessionConnected<ConnType extends Connection> extends IdentifiedSession {
114
+ readonly state: SessionState.Connected;
115
+ conn: ConnType;
116
+ listeners: SessionConnectedListeners;
117
+ heartbeatHandle?: ReturnType<typeof setInterval> | undefined;
118
+ heartbeatMisses: number;
119
+ get isActivelyHeartbeating(): boolean;
120
+ updateBookkeeping(ack: number, seq: number): void;
121
+ send(msg: PartialTransportMessage): string;
122
+ constructor(conn: ConnType, listeners: SessionConnectedListeners, ...args: ConstructorParameters<typeof IdentifiedSession>);
123
+ startActiveHeartbeat(): void;
124
+ private sendHeartbeat;
125
+ onMessageData: (msg: Uint8Array) => void;
126
+ _handleStateExit(): void;
127
+ _handleClose(): void;
128
+ }
129
+
130
+ declare const enum SessionState {
131
+ NoConnection = "NoConnection",
132
+ Connecting = "Connecting",
133
+ Handshaking = "Handshaking",
134
+ Connected = "Connected",
135
+ WaitingForHandshake = "WaitingForHandshake"
136
+ }
137
+ type Session<ConnType extends Connection> = SessionNoConnection | SessionConnecting<ConnType> | SessionHandshaking<ConnType> | SessionConnected<ConnType>;
138
+ declare abstract class StateMachineState {
139
+ abstract readonly state: SessionState;
140
+ _isConsumed: boolean;
141
+ abstract _handleStateExit(): void;
142
+ abstract _handleClose(): void;
143
+ close(): void;
144
+ constructor();
145
+ }
51
146
  interface SessionOptions {
52
147
  /**
53
148
  * Frequency at which to send heartbeat acknowledgements
@@ -63,107 +158,49 @@ interface SessionOptions {
63
158
  */
64
159
  sessionDisconnectGraceMs: number;
65
160
  /**
66
- * The codec to use for encoding/decoding messages over the wire
161
+ * Connection timeout in milliseconds
67
162
  */
68
- codec: Codec;
69
- }
70
- /**
71
- * A session is a higher-level abstraction that operates over the span of potentially multiple transport-level connections
72
- * - It’s responsible for tracking any metadata for a particular client that might need to be persisted across connections (i.e. the sendBuffer, ack, seq)
73
- * - This will only be considered disconnected if
74
- * - the server tells the client that we’ve reconnected but it doesn’t recognize us anymore (server definitely died) or
75
- * - we hit a grace period after a connection disconnect
76
- */
77
- declare class Session<ConnType extends Connection> {
78
- private codec;
79
- private options;
80
- readonly telemetry: TelemetryInfo;
81
- /**
82
- * The buffer of messages that have been sent but not yet acknowledged.
83
- */
84
- private sendBuffer;
163
+ connectionTimeoutMs: number;
85
164
  /**
86
- * The active connection associated with this session
165
+ * Handshake timeout in milliseconds
87
166
  */
88
- connection?: ConnType;
167
+ handshakeTimeoutMs: number;
89
168
  /**
90
- * A connection that is currently undergoing handshaking. Used to distinguish between the active
91
- * connection, but still be able to close it if needed.
169
+ * The codec to use for encoding/decoding messages over the wire
92
170
  */
93
- private handshakingConnection?;
171
+ codec: Codec;
172
+ }
173
+ declare abstract class CommonSession extends StateMachineState {
94
174
  readonly from: TransportClientId;
175
+ readonly options: SessionOptions;
176
+ log?: Logger;
177
+ abstract get loggingMetadata(): MessageMetadata;
178
+ constructor(from: TransportClientId, options: SessionOptions, log: Logger | undefined);
179
+ parseMsg(msg: Uint8Array): OpaqueTransportMessage | null;
180
+ }
181
+ type SessionId = string;
182
+ declare abstract class IdentifiedSession extends CommonSession {
183
+ readonly id: SessionId;
184
+ readonly telemetry: TelemetryInfo;
95
185
  readonly to: TransportClientId;
96
186
  /**
97
- * The unique ID of this session.
98
- */
99
- readonly id: string;
100
- /**
101
- * What the other side advertised as their session ID
102
- * for this session.
103
- */
104
- advertisedSessionId?: string;
105
- /**
106
- * Number of messages we've sent along this session (excluding handshake and acks)
187
+ * Index of the message we will send next (excluding handshake)
107
188
  */
108
- private seq;
189
+ seq: number;
109
190
  /**
110
- * Number of unique messages we've received this session (excluding handshake and acks)
191
+ * Number of unique messages we've received this session (excluding handshake)
111
192
  */
112
- private ack;
113
- /**
114
- * The grace period between when the inner connection is disconnected
115
- * and when we should consider the entire session disconnected.
116
- */
117
- private disconnectionGrace?;
118
- /**
119
- * Number of heartbeats we've sent without a response.
120
- */
121
- private heartbeatMisses;
122
- /**
123
- * The interval for sending heartbeats.
124
- */
125
- private heartbeat;
126
- private log?;
127
- constructor(conn: ConnType | undefined, from: TransportClientId, to: TransportClientId, options: SessionOptions, propagationCtx?: PropagationContext);
128
- bindLogger(log: Logger): void;
193
+ ack: number;
194
+ sendBuffer: Array<OpaqueTransportMessage>;
195
+ constructor(id: SessionId, from: TransportClientId, to: TransportClientId, seq: number, ack: number, sendBuffer: Array<OpaqueTransportMessage>, telemetry: TelemetryInfo, options: SessionOptions, log: Logger | undefined);
129
196
  get loggingMetadata(): MessageMetadata;
130
- /**
131
- * Sends a message over the session's connection.
132
- * If the connection is not ready or the message fails to send, the message can be buffered for retry unless skipped.
133
- *
134
- * @param msg The partial message to be sent, which will be constructed into a full message.
135
- * @param addToSendBuff Whether to add the message to the send buffer for retry.
136
- * @returns The full transport ID of the message that was attempted to be sent.
137
- */
138
- send(msg: PartialTransportMessage): string;
139
- sendHeartbeat(): void;
140
- resetBufferedMessages(): void;
141
- sendBufferedMessages(conn: ConnType): void;
142
- updateBookkeeping(ack: number, seq: number): void;
143
- private closeStaleConnection;
144
- replaceWithNewConnection(newConn: ConnType, isTransparentReconnect: boolean): void;
145
- replaceWithNewHandshakingConnection(newConn: ConnType): void;
146
- beginGrace(cb: () => void): void;
147
- cancelGrace(): void;
148
- /**
149
- * Used to close the handshaking connection, if set.
150
- */
151
- closeHandshakingConnection(expectedHandshakingConn?: ConnType): void;
152
- close(): void;
153
- get connected(): boolean;
154
- get nextExpectedAck(): number;
155
- get nextExpectedSeq(): number;
156
- /**
157
- * Check that the peer's next expected seq number matches something that is in our send buffer
158
- * _or_ matches our actual next seq.
159
- */
160
- nextExpectedSeqInRange(nextExpectedSeq: number): boolean;
161
- advanceAckForTesting(by: number): void;
162
197
  constructMsg<Payload>(partialMsg: PartialTransportMessage<Payload>): TransportMessage<Payload>;
163
- inspectSendBuffer(): ReadonlyArray<OpaqueTransportMessage>;
198
+ nextSeq(): number;
199
+ send(msg: PartialTransportMessage): string;
200
+ _handleStateExit(): void;
201
+ _handleClose(): void;
164
202
  }
165
203
 
166
- type ConnectionStatus = 'connect' | 'disconnect';
167
204
  declare const ProtocolError: {
168
205
  readonly RetriesExceeded: "conn_retry_exceeded";
169
206
  readonly HandshakeFailed: "handshake_failed";
@@ -172,14 +209,19 @@ declare const ProtocolError: {
172
209
  type ProtocolErrorType = (typeof ProtocolError)[keyof typeof ProtocolError];
173
210
  interface EventMap {
174
211
  message: OpaqueTransportMessage;
175
- connectionStatus: {
176
- status: ConnectionStatus;
177
- conn: Connection;
178
- };
179
212
  sessionStatus: {
180
- status: ConnectionStatus;
213
+ status: 'connect' | 'disconnect';
181
214
  session: Session<Connection>;
182
215
  };
216
+ sessionTransition: {
217
+ state: SessionState.Connected;
218
+ } | {
219
+ state: SessionState.Handshaking;
220
+ } | {
221
+ state: SessionState.Connecting;
222
+ } | {
223
+ state: SessionState.NoConnection;
224
+ };
183
225
  protocolError: {
184
226
  type: ProtocolErrorType;
185
227
  message: string;
@@ -265,16 +307,7 @@ type ProvidedServerTransportOptions = Partial<ServerTransportOptions>;
265
307
  */
266
308
  type TransportStatus = 'open' | 'closed';
267
309
  /**
268
- * Transports manage the lifecycle (creation/deletion) of sessions and connections. Its responsibilities include:
269
- *
270
- * 1) Constructing a new {@link Session} and {@link Connection} on {@link TransportMessage}s from new clients.
271
- * After constructing the {@link Connection}, {@link onConnect} is called which adds it to the connection map.
272
- * 2) Delegating message listening of the connection to the newly created {@link Connection}.
273
- * From this point on, the {@link Connection} is responsible for *reading* and *writing*
274
- * messages from the connection.
275
- * 3) When a connection is closed, the {@link Transport} calls {@link onDisconnect} which closes the
276
- * connection via {@link Connection.close} and removes it from the {@link connections} map.
277
-
310
+ * Transports manage the lifecycle (creation/deletion) of sessions
278
311
  *
279
312
  * ```plaintext
280
313
  * ▲
@@ -299,22 +332,10 @@ declare abstract class Transport<ConnType extends Connection> {
299
332
  * The status of the transport.
300
333
  */
301
334
  private status;
302
- /**
303
- * The {@link Codec} used to encode and decode messages.
304
- */
305
- codec: Codec;
306
335
  /**
307
336
  * The client ID of this transport.
308
337
  */
309
338
  clientId: TransportClientId;
310
- /**
311
- * The map of {@link Session}s managed by this transport.
312
- */
313
- sessions: Map<TransportClientId, Session<ConnType>>;
314
- /**
315
- * The map of {@link Connection}s managed by this transport.
316
- */
317
- get connections(): Map<string, ConnType>;
318
339
  /**
319
340
  * The event dispatcher for handling events of type EventTypes.
320
341
  */
@@ -324,75 +345,20 @@ declare abstract class Transport<ConnType extends Connection> {
324
345
  */
325
346
  protected options: TransportOptions;
326
347
  log?: Logger;
348
+ sessions: Map<TransportClientId, Session<ConnType>>;
327
349
  /**
328
350
  * Creates a new Transport instance.
329
- * This should also set up {@link onConnect}, and {@link onDisconnect} listeners.
330
351
  * @param codec The codec used to encode and decode messages.
331
352
  * @param clientId The client ID of this transport.
332
353
  */
333
354
  constructor(clientId: TransportClientId, providedOptions?: ProvidedTransportOptions);
334
355
  bindLogger(fn: LogFn | Logger, level?: LoggingLevel): void;
335
- /**
336
- * This is called immediately after a new connection is established and we
337
- * may or may not know the identity of the connected client.
338
- * It should attach all the necessary listeners to the connection for lifecycle
339
- * events (i.e. data, close, error)
340
- *
341
- * This method is implemented by {@link ClientTransport} and {@link ServerTransport}.
342
- */
343
- protected abstract handleConnection(conn: ConnType, to: TransportClientId): void;
344
- /**
345
- * Called when a new connection is established
346
- * and we know the identity of the connected client.
347
- * @param conn The connection object.
348
- */
349
- protected onConnect(conn: ConnType, session: Session<ConnType>, isTransparentReconnect: boolean): void;
350
- protected createSession(to: TransportClientId, conn?: ConnType, propagationCtx?: PropagationContext): Session<ConnType>;
351
- protected createNewSession({ to, conn, sessionId, propagationCtx, }: {
352
- to: TransportClientId;
353
- conn: ConnType;
354
- sessionId: string;
355
- propagationCtx?: PropagationContext;
356
- }): Session<ConnType>;
357
- protected getExistingSession({ to, sessionId, nextExpectedSeq, }: {
358
- to: TransportClientId;
359
- sessionId: string;
360
- nextExpectedSeq: number;
361
- }): false | Session<ConnType>;
362
- protected getOrCreateSession({ to, conn, handshakingConn, sessionId, propagationCtx, }: {
363
- to: TransportClientId;
364
- conn?: ConnType;
365
- handshakingConn?: ConnType;
366
- sessionId?: string;
367
- propagationCtx?: PropagationContext;
368
- }): {
369
- session: Session<ConnType>;
370
- isReconnect: boolean;
371
- isTransparentReconnect: boolean;
372
- };
373
- protected deleteSession({ session, closeHandshakingConnection, handshakingConn, }: {
374
- session: Session<ConnType>;
375
- closeHandshakingConnection: boolean;
376
- handshakingConn?: ConnType;
377
- }): void;
378
- /**
379
- * The downstream implementation needs to call this when a connection is closed.
380
- * @param conn The connection object.
381
- * @param connectedTo The peer we are connected to.
382
- */
383
- protected onDisconnect(conn: ConnType, session: Session<ConnType>): void;
384
- /**
385
- * Parses a message from a Uint8Array into a {@link OpaqueTransportMessage}.
386
- * @param msg The message to parse.
387
- * @returns The parsed message, or null if the message is malformed or invalid.
388
- */
389
- protected parseMsg(msg: Uint8Array, conn: ConnType): OpaqueTransportMessage | null;
390
356
  /**
391
357
  * Called when a message is received by this transport.
392
358
  * You generally shouldn't need to override this in downstream transport implementations.
393
359
  * @param msg The received message.
394
360
  */
395
- protected handleMsg(msg: OpaqueTransportMessage, conn: ConnType): void;
361
+ protected handleMsg(msg: OpaqueTransportMessage): void;
396
362
  /**
397
363
  * Adds a listener to this transport.
398
364
  * @param the type of event to listen for
@@ -411,8 +377,7 @@ declare abstract class Transport<ConnType extends Connection> {
411
377
  * @param msg The message to send.
412
378
  * @returns The ID of the sent message or undefined if it wasn't sent
413
379
  */
414
- send(to: TransportClientId, msg: PartialTransportMessage): string;
415
- sendCloseStream(to: TransportClientId, streamId: string): string;
380
+ abstract send(to: TransportClientId, msg: PartialTransportMessage): string;
416
381
  protected protocolError(type: ProtocolErrorType, message: string): void;
417
382
  /**
418
383
  * Default close implementation for transports. You should override this in the downstream
@@ -421,6 +386,11 @@ declare abstract class Transport<ConnType extends Connection> {
421
386
  */
422
387
  close(): void;
423
388
  getStatus(): TransportStatus;
389
+ protected updateSession<S extends Session<ConnType>>(session: S): S;
390
+ protected deleteSession(session: Session<ConnType>): void;
391
+ protected onSessionGracePeriodElapsed(session: SessionNoConnection): void;
392
+ protected onConnectingFailed(session: SessionConnecting<ConnType>): SessionNoConnection;
393
+ protected onConnClosed(session: SessionHandshaking<ConnType> | SessionConnected<ConnType>): SessionNoConnection;
424
394
  }
425
395
 
426
396
  /**
@@ -474,7 +444,6 @@ type ServiceContextWithTransportInfo<State> = ServiceContext & {
474
444
  to: TransportClientId;
475
445
  from: TransportClientId;
476
446
  streamId: string;
477
- session: Session<Connection>;
478
447
  metadata: ParsedMetadata;
479
448
  };
480
449
 
@@ -513,4 +482,4 @@ interface ServerHandshakeOptions<MetadataSchema extends TSchema = TSchema> {
513
482
  declare function createClientHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, construct: ConstructHandshake<MetadataSchema>): ClientHandshakeOptions;
514
483
  declare function createServerHandshakeOptions<MetadataSchema extends TSchema = TSchema>(schema: MetadataSchema, validate: ValidateHandshake<MetadataSchema>): ServerHandshakeOptions;
515
484
 
516
- export { Connection as C, EventMap as E, LeakyBucketRateLimit as L, ProvidedTransportOptions as P, Session as S, Transport as T, TransportStatus as a, ProvidedClientTransportOptions as b, ProvidedServerTransportOptions as c, EventTypes as d, EventHandler as e, ProtocolError as f, ProtocolErrorType as g, SessionOptions as h, ServiceContext as i, ClientTransportOptions as j, ClientHandshakeOptions as k, ServerTransportOptions as l, ServerHandshakeOptions as m, ParsedMetadata as n, ServiceContextWithState as o, ServiceContextWithTransportInfo as p, createClientHandshakeOptions as q, createServerHandshakeOptions as r };
485
+ export { Connection as C, EventMap as E, LeakyBucketRateLimit as L, ProvidedTransportOptions as P, Session as S, Transport as T, TransportStatus as a, ProvidedClientTransportOptions as b, ProvidedServerTransportOptions as c, SessionState as d, SessionNoConnection as e, SessionConnecting as f, SessionHandshaking as g, SessionConnected as h, EventTypes as i, EventHandler as j, ProtocolError as k, ProtocolErrorType as l, SessionOptions as m, ServiceContext as n, ClientTransportOptions as o, ClientHandshakeOptions as p, ServerHandshakeOptions as q, ParsedMetadata as r, ServiceContextWithState as s, ServiceContextWithTransportInfo as t, createClientHandshakeOptions as u, createServerHandshakeOptions as v, CommonSession as w, SessionHandshakingListeners as x, ServerTransportOptions as y };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../logging/index.ts","../../logging/log.ts"],"sourcesContent":["export { stringLogger, coloredStringLogger, jsonLogger } from './log';\nexport type { Logger, LogFn, MessageMetadata } from './log';\n","import { ValueError } from '@sinclair/typebox/value';\nimport { OpaqueTransportMessage } from '../transport/message';\n\nconst LoggingLevels = {\n debug: -1,\n info: 0,\n warn: 1,\n error: 2,\n} as const;\nexport type LoggingLevel = keyof typeof LoggingLevels;\n\nexport type LogFn = (\n msg: string,\n ctx?: MessageMetadata,\n level?: LoggingLevel,\n) => void;\nexport type Logger = {\n [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;\n};\n\nexport type Tags = 'invariant-violation';\n\nconst cleanedLogFn = (log: LogFn) => {\n return (msg: string, metadata?: MessageMetadata) => {\n // skip cloning object if metadata has no transportMessage\n if (!metadata?.transportMessage) {\n log(msg, metadata);\n return;\n }\n\n // clone metadata and clean transportMessage\n const { payload, ...rest } = metadata.transportMessage;\n metadata.transportMessage = rest;\n log(msg, metadata);\n };\n};\n\nexport type MessageMetadata = Partial<{\n protocolVersion: string;\n clientId: string;\n connectedTo: string;\n sessionId: string;\n connId: string;\n transportMessage: Partial<OpaqueTransportMessage>;\n validationErrors: Array<ValueError>;\n tags: Array<Tags>;\n telemetry: {\n traceId: string;\n spanId: string;\n };\n}>;\n\nexport class BaseLogger implements Logger {\n minLevel: LoggingLevel;\n private output: LogFn;\n\n constructor(output: LogFn, minLevel: LoggingLevel = 'info') {\n this.minLevel = minLevel;\n this.output = output;\n }\n\n debug(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {\n this.output(msg, metadata ?? {}, 'debug');\n }\n }\n\n info(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {\n this.output(msg, metadata ?? {}, 'info');\n }\n }\n\n warn(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {\n this.output(msg, metadata ?? {}, 'warn');\n }\n }\n\n error(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {\n this.output(msg, metadata ?? {}, 'error');\n }\n }\n}\n\nexport const stringLogger: LogFn = (msg, ctx, level = 'info') => {\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${level}] ${from}${msg}`);\n};\n\nconst colorMap = {\n debug: '\\u001b[34m',\n info: '\\u001b[32m',\n warn: '\\u001b[33m',\n error: '\\u001b[31m',\n};\n\nexport const coloredStringLogger: LogFn = (msg, ctx, level = 'info') => {\n const color = colorMap[level];\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${color}${level}\\u001b[0m] ${from}${msg}`);\n};\n\nexport const jsonLogger: LogFn = (msg, ctx, level) => {\n console.log(JSON.stringify({ msg, ctx, level }));\n};\n\nexport const createLogProxy = (log: Logger) => ({\n debug: cleanedLogFn(log.debug.bind(log)),\n info: cleanedLogFn(log.info.bind(log)),\n warn: cleanedLogFn(log.warn.bind(log)),\n error: cleanedLogFn(log.error.bind(log)),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsFO,IAAM,eAAsB,CAAC,KAAK,KAAK,QAAQ,WAAW;AAC/D,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,KAAK,IAAI,GAAG,GAAG,EAAE;AAC9C;AAEA,IAAM,WAAW;AAAA,EACf,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAEO,IAAM,sBAA6B,CAAC,KAAK,KAAK,QAAQ,WAAW;AACtE,QAAM,QAAQ,SAAS,KAAK;AAC5B,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,GAAG,KAAK,YAAc,IAAI,GAAG,GAAG,EAAE;AAC/D;AAEO,IAAM,aAAoB,CAAC,KAAK,KAAK,UAAU;AACpD,UAAQ,IAAI,KAAK,UAAU,EAAE,KAAK,KAAK,MAAM,CAAC,CAAC;AACjD;","names":[]}
1
+ {"version":3,"sources":["../../logging/index.ts","../../logging/log.ts"],"sourcesContent":["export { stringLogger, coloredStringLogger, jsonLogger } from './log';\nexport type { Logger, LogFn, MessageMetadata } from './log';\n","import { ValueError } from '@sinclair/typebox/value';\nimport { OpaqueTransportMessage } from '../transport/message';\n\nconst LoggingLevels = {\n debug: -1,\n info: 0,\n warn: 1,\n error: 2,\n} as const;\nexport type LoggingLevel = keyof typeof LoggingLevels;\n\nexport type LogFn = (\n msg: string,\n ctx?: MessageMetadata,\n level?: LoggingLevel,\n) => void;\nexport type Logger = {\n [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;\n};\n\nexport type Tags = 'invariant-violation' | 'state-transition';\n\nconst cleanedLogFn = (log: LogFn) => {\n return (msg: string, metadata?: MessageMetadata) => {\n // skip cloning object if metadata has no transportMessage\n if (!metadata?.transportMessage) {\n log(msg, metadata);\n return;\n }\n\n // clone metadata and clean transportMessage\n const { payload, ...rest } = metadata.transportMessage;\n metadata.transportMessage = rest;\n log(msg, metadata);\n };\n};\n\nexport type MessageMetadata = Partial<{\n protocolVersion: string;\n clientId: string;\n connectedTo: string;\n sessionId: string;\n connId: string;\n transportMessage: Partial<OpaqueTransportMessage>;\n validationErrors: Array<ValueError>;\n tags: Array<Tags>;\n telemetry: {\n traceId: string;\n spanId: string;\n };\n}>;\n\nexport class BaseLogger implements Logger {\n minLevel: LoggingLevel;\n private output: LogFn;\n\n constructor(output: LogFn, minLevel: LoggingLevel = 'info') {\n this.minLevel = minLevel;\n this.output = output;\n }\n\n debug(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.debug) {\n this.output(msg, metadata ?? {}, 'debug');\n }\n }\n\n info(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.info) {\n this.output(msg, metadata ?? {}, 'info');\n }\n }\n\n warn(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.warn) {\n this.output(msg, metadata ?? {}, 'warn');\n }\n }\n\n error(msg: string, metadata?: MessageMetadata) {\n if (LoggingLevels[this.minLevel] <= LoggingLevels.error) {\n this.output(msg, metadata ?? {}, 'error');\n }\n }\n}\n\nexport const stringLogger: LogFn = (msg, ctx, level = 'info') => {\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${level}] ${from}${msg}`);\n};\n\nconst colorMap = {\n debug: '\\u001b[34m',\n info: '\\u001b[32m',\n warn: '\\u001b[33m',\n error: '\\u001b[31m',\n};\n\nexport const coloredStringLogger: LogFn = (msg, ctx, level = 'info') => {\n const color = colorMap[level];\n const from = ctx?.clientId ? `${ctx.clientId} -- ` : '';\n console.log(`[river:${color}${level}\\u001b[0m] ${from}${msg}`);\n};\n\nexport const jsonLogger: LogFn = (msg, ctx, level) => {\n console.log(JSON.stringify({ msg, ctx, level }));\n};\n\nexport const createLogProxy = (log: Logger) => ({\n debug: cleanedLogFn(log.debug.bind(log)),\n info: cleanedLogFn(log.info.bind(log)),\n warn: cleanedLogFn(log.warn.bind(log)),\n error: cleanedLogFn(log.error.bind(log)),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsFO,IAAM,eAAsB,CAAC,KAAK,KAAK,QAAQ,WAAW;AAC/D,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,KAAK,IAAI,GAAG,GAAG,EAAE;AAC9C;AAEA,IAAM,WAAW;AAAA,EACf,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AAEO,IAAM,sBAA6B,CAAC,KAAK,KAAK,QAAQ,WAAW;AACtE,QAAM,QAAQ,SAAS,KAAK;AAC5B,QAAM,OAAO,KAAK,WAAW,GAAG,IAAI,QAAQ,SAAS;AACrD,UAAQ,IAAI,UAAU,KAAK,GAAG,KAAK,YAAc,IAAI,GAAG,GAAG,EAAE;AAC/D;AAEO,IAAM,aAAoB,CAAC,KAAK,KAAK,UAAU;AACpD,UAAQ,IAAI,KAAK,UAAU,EAAE,KAAK,KAAK,MAAM,CAAC,CAAC;AACjD;","names":[]}
@@ -1,4 +1,4 @@
1
- export { g as LogFn, L as Logger, M as MessageMetadata, j as coloredStringLogger, k as jsonLogger, s as stringLogger } from '../index-ea74cdbb.js';
1
+ export { f as LogFn, L as Logger, M as MessageMetadata, h as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../message-e6c560fd.js';
2
2
  import '@sinclair/typebox/value';
3
3
  import '@sinclair/typebox';
4
4
  import '@opentelemetry/api';
@@ -1,4 +1,4 @@
1
- export { g as LogFn, L as Logger, M as MessageMetadata, j as coloredStringLogger, k as jsonLogger, s as stringLogger } from '../index-ea74cdbb.js';
1
+ export { f as LogFn, L as Logger, M as MessageMetadata, h as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../message-e6c560fd.js';
2
2
  import '@sinclair/typebox/value';
3
3
  import '@sinclair/typebox';
4
4
  import '@opentelemetry/api';
@@ -2,7 +2,7 @@ import {
2
2
  coloredStringLogger,
3
3
  jsonLogger,
4
4
  stringLogger
5
- } from "../chunk-6LCL2ZZF.js";
5
+ } from "../chunk-TAH2GVTJ.js";
6
6
  export {
7
7
  coloredStringLogger,
8
8
  jsonLogger,
@@ -14,7 +14,7 @@ type LogFn = (msg: string, ctx?: MessageMetadata, level?: LoggingLevel) => void;
14
14
  type Logger = {
15
15
  [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;
16
16
  };
17
- type Tags = 'invariant-violation';
17
+ type Tags = 'invariant-violation' | 'state-transition';
18
18
  type MessageMetadata = Partial<{
19
19
  protocolVersion: string;
20
20
  clientId: string;
@@ -133,4 +133,4 @@ declare function isStreamOpen(controlFlag: number): boolean;
133
133
  */
134
134
  declare function isStreamClose(controlFlag: number): boolean;
135
135
 
136
- export { Logger as L, MessageMetadata as M, OpaqueTransportMessageSchema as O, PartialTransportMessage as P, TransportMessageSchema as T, TransportMessage as a, OpaqueTransportMessage as b, TransportClientId as c, isStreamClose as d, TelemetryInfo as e, PropagationContext as f, LogFn as g, LoggingLevel as h, isStreamOpen as i, coloredStringLogger as j, jsonLogger as k, stringLogger as s };
136
+ export { Logger as L, MessageMetadata as M, OpaqueTransportMessageSchema as O, PartialTransportMessage as P, TransportMessageSchema as T, TransportMessage as a, OpaqueTransportMessage as b, TransportClientId as c, isStreamClose as d, TelemetryInfo as e, LogFn as f, LoggingLevel as g, coloredStringLogger as h, isStreamOpen as i, jsonLogger as j, stringLogger as s };