@replit/river 0.216.1 → 0.217.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 (76) hide show
  1. package/README.md +2 -2
  2. package/dist/{adapter-BXCk-dmy.d.ts → adapter-Dl5Mewp3.d.ts} +1 -1
  3. package/dist/{chunk-C4EPHIKQ.js → chunk-JFFRB3SS.js} +48 -26
  4. package/dist/chunk-JFFRB3SS.js.map +1 -0
  5. package/dist/{chunk-62BM2WOT.js → chunk-VK3VJZGG.js} +19 -18
  6. package/dist/chunk-VK3VJZGG.js.map +1 -0
  7. package/dist/chunk-WMPWPIA4.js +72 -0
  8. package/dist/chunk-WMPWPIA4.js.map +1 -0
  9. package/dist/{client-BNc5Pj_4.d.ts → client-YP9bECp8.d.ts} +2 -2
  10. package/dist/codec/index.d.ts +3 -3
  11. package/dist/codec/index.js +2 -2
  12. package/dist/{connection-ou9w2dSY.d.ts → connection-D_HE_YQB.d.ts} +3 -3
  13. package/dist/customSchemas/index.d.ts +34 -0
  14. package/dist/customSchemas/index.js +9 -0
  15. package/dist/customSchemas/index.js.map +1 -0
  16. package/dist/{index-ZWkoesQD.d.ts → index-DgUMnNOi.d.ts} +1 -1
  17. package/dist/logging/index.d.ts +3 -3
  18. package/dist/{message-CpXWqmJw.d.ts → message-DxS8db8A.d.ts} +30 -31
  19. package/dist/protobuf/index.d.ts +11 -15
  20. package/dist/protobuf/index.js +7 -5
  21. package/dist/protobuf/index.js.map +1 -1
  22. package/dist/router/index.d.ts +11 -11
  23. package/dist/router/index.js +1 -1
  24. package/dist/{server-BPu7Td80.d.ts → server-BfM3_JLq.d.ts} +5 -5
  25. package/dist/{services-DpT2yNtt.d.ts → services-CL6k3HMH.d.ts} +8 -9
  26. package/dist/testUtil/index.d.ts +8 -8
  27. package/dist/testUtil/index.js +2 -2
  28. package/dist/testUtil/index.js.map +1 -1
  29. package/dist/transport/impls/ws/client.d.ts +7 -7
  30. package/dist/transport/impls/ws/client.js +2 -2
  31. package/dist/transport/impls/ws/server.d.ts +7 -7
  32. package/dist/transport/impls/ws/server.js +2 -2
  33. package/dist/transport/impls/ws/server.js.map +1 -1
  34. package/dist/transport/index.d.ts +8 -8
  35. package/dist/transport/index.js +2 -2
  36. package/dist/{transport-B1MUtXL7.d.ts → transport-CUpXnch7.d.ts} +4 -4
  37. package/package.json +14 -39
  38. package/dist/adapter-D5X11kmP.d.cts +0 -29
  39. package/dist/chunk-62BM2WOT.js.map +0 -1
  40. package/dist/chunk-C4EPHIKQ.js.map +0 -1
  41. package/dist/client-BZUvFL6B.d.cts +0 -54
  42. package/dist/codec/index.cjs +0 -268
  43. package/dist/codec/index.cjs.map +0 -1
  44. package/dist/codec/index.d.cts +0 -19
  45. package/dist/connection-xxgJHs2o.d.cts +0 -40
  46. package/dist/index-BAGGleT3.d.cts +0 -37
  47. package/dist/logging/index.cjs +0 -55
  48. package/dist/logging/index.cjs.map +0 -1
  49. package/dist/logging/index.d.cts +0 -4
  50. package/dist/message-CpXWqmJw.d.cts +0 -119
  51. package/dist/protobuf/codec.cjs +0 -107
  52. package/dist/protobuf/codec.cjs.map +0 -1
  53. package/dist/protobuf/codec.d.cts +0 -13
  54. package/dist/protobuf/index.cjs +0 -1877
  55. package/dist/protobuf/index.cjs.map +0 -1
  56. package/dist/protobuf/index.d.cts +0 -488
  57. package/dist/router/index.cjs +0 -2043
  58. package/dist/router/index.cjs.map +0 -1
  59. package/dist/router/index.d.cts +0 -80
  60. package/dist/server-JdnoVO11.d.cts +0 -72
  61. package/dist/services-CjigASqe.d.cts +0 -1135
  62. package/dist/testUtil/index.cjs +0 -3051
  63. package/dist/testUtil/index.cjs.map +0 -1
  64. package/dist/testUtil/index.d.cts +0 -122
  65. package/dist/transport/impls/ws/client.cjs +0 -2308
  66. package/dist/transport/impls/ws/client.cjs.map +0 -1
  67. package/dist/transport/impls/ws/client.d.cts +0 -33
  68. package/dist/transport/impls/ws/server.cjs +0 -2179
  69. package/dist/transport/impls/ws/server.cjs.map +0 -1
  70. package/dist/transport/impls/ws/server.d.cts +0 -21
  71. package/dist/transport/index.cjs +0 -2727
  72. package/dist/transport/index.cjs.map +0 -1
  73. package/dist/transport/index.d.cts +0 -11
  74. package/dist/transport-BnU3Zb0Q.d.cts +0 -590
  75. package/dist/types-BGGvYIJM.d.cts +0 -20
  76. package/dist/wslike-Dng9H1C7.d.cts +0 -40
@@ -1,268 +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
- // codec/index.ts
21
- var codec_exports = {};
22
- __export(codec_exports, {
23
- BinaryCodec: () => BinaryCodec,
24
- CodecMessageAdapter: () => CodecMessageAdapter,
25
- NaiveJsonCodec: () => NaiveJsonCodec
26
- });
27
- module.exports = __toCommonJS(codec_exports);
28
-
29
- // codec/binary.ts
30
- var import_msgpack = require("@msgpack/msgpack");
31
- var BIGINT_EXT_TYPE = 0;
32
- var extensionCodec = new import_msgpack.ExtensionCodec();
33
- extensionCodec.register({
34
- type: BIGINT_EXT_TYPE,
35
- encode(input) {
36
- if (typeof input === "bigint") {
37
- if (input <= Number.MAX_SAFE_INTEGER && input >= Number.MIN_SAFE_INTEGER) {
38
- return (0, import_msgpack.encode)(Number(input));
39
- } else {
40
- return (0, import_msgpack.encode)(String(input));
41
- }
42
- } else {
43
- return null;
44
- }
45
- },
46
- decode(data) {
47
- const val = (0, import_msgpack.decode)(data);
48
- if (!(typeof val === "string" || typeof val === "number")) {
49
- throw new import_msgpack.DecodeError(`unexpected BigInt source: ${typeof val}`);
50
- }
51
- return BigInt(val);
52
- }
53
- });
54
- var BinaryCodec = {
55
- toBuffer(obj) {
56
- return (0, import_msgpack.encode)(obj, {
57
- ignoreUndefined: true,
58
- initialBufferSize: 512,
59
- extensionCodec
60
- });
61
- },
62
- fromBuffer: (buff) => {
63
- const res = (0, import_msgpack.decode)(buff, { extensionCodec });
64
- if (typeof res !== "object" || res === null) {
65
- throw new Error("unpacked msg is not an object");
66
- }
67
- return res;
68
- }
69
- };
70
-
71
- // codec/json.ts
72
- var encoder = new TextEncoder();
73
- var decoder = new TextDecoder();
74
- function uint8ArrayToBase64(uint8Array) {
75
- let binary = "";
76
- uint8Array.forEach((byte) => {
77
- binary += String.fromCharCode(byte);
78
- });
79
- return btoa(binary);
80
- }
81
- function base64ToUint8Array(base64) {
82
- const binaryString = atob(base64);
83
- const uint8Array = new Uint8Array(binaryString.length);
84
- for (let i = 0; i < binaryString.length; i++) {
85
- uint8Array[i] = binaryString.charCodeAt(i);
86
- }
87
- return uint8Array;
88
- }
89
- var NaiveJsonCodec = {
90
- toBuffer: (obj) => {
91
- return encoder.encode(
92
- JSON.stringify(obj, function replacer(key) {
93
- const val = this[key];
94
- if (val instanceof Uint8Array) {
95
- return { $t: uint8ArrayToBase64(val) };
96
- } else if (typeof val === "bigint") {
97
- return { $b: val.toString() };
98
- } else {
99
- return val;
100
- }
101
- })
102
- );
103
- },
104
- fromBuffer: (buff) => {
105
- const parsed = JSON.parse(
106
- decoder.decode(buff),
107
- function reviver(_key, val) {
108
- if (val?.$t !== void 0) {
109
- return base64ToUint8Array(val.$t);
110
- } else if (val?.$b !== void 0) {
111
- return BigInt(val.$b);
112
- } else {
113
- return val;
114
- }
115
- }
116
- );
117
- if (typeof parsed !== "object" || parsed === null) {
118
- throw new Error("unpacked msg is not an object");
119
- }
120
- return parsed;
121
- }
122
- };
123
-
124
- // codec/adapter.ts
125
- var import_value = require("@sinclair/typebox/value");
126
-
127
- // transport/message.ts
128
- var import_typebox = require("@sinclair/typebox");
129
- var TransportMessageSchema = (t) => import_typebox.Type.Object({
130
- id: import_typebox.Type.String(),
131
- from: import_typebox.Type.String(),
132
- to: import_typebox.Type.String(),
133
- seq: import_typebox.Type.Integer(),
134
- ack: import_typebox.Type.Integer(),
135
- serviceName: import_typebox.Type.Optional(import_typebox.Type.String()),
136
- procedureName: import_typebox.Type.Optional(import_typebox.Type.String()),
137
- streamId: import_typebox.Type.String(),
138
- controlFlags: import_typebox.Type.Integer(),
139
- tracing: import_typebox.Type.Optional(
140
- import_typebox.Type.Object({
141
- traceparent: import_typebox.Type.String(),
142
- tracestate: import_typebox.Type.String()
143
- })
144
- ),
145
- payload: t
146
- });
147
- var ControlMessageAckSchema = import_typebox.Type.Object({
148
- type: import_typebox.Type.Literal("ACK")
149
- });
150
- var ControlMessageCloseSchema = import_typebox.Type.Object({
151
- type: import_typebox.Type.Literal("CLOSE")
152
- });
153
- var ControlMessageHandshakeRequestSchema = import_typebox.Type.Object({
154
- type: import_typebox.Type.Literal("HANDSHAKE_REQ"),
155
- protocolVersion: import_typebox.Type.String(),
156
- sessionId: import_typebox.Type.String(),
157
- /**
158
- * Specifies what the server's expected session state (from the pov of the client). This can be
159
- * used by the server to know whether this is a new or a reestablished connection, and whether it
160
- * is compatible with what it already has.
161
- */
162
- expectedSessionState: import_typebox.Type.Object({
163
- // what the client expects the server to send next
164
- nextExpectedSeq: import_typebox.Type.Integer(),
165
- nextSentSeq: import_typebox.Type.Integer()
166
- }),
167
- metadata: import_typebox.Type.Optional(import_typebox.Type.Unknown())
168
- });
169
- var HandshakeErrorRetriableResponseCodes = import_typebox.Type.Union([
170
- import_typebox.Type.Literal("SESSION_STATE_MISMATCH")
171
- ]);
172
- var HandshakeErrorCustomHandlerFatalResponseCodes = import_typebox.Type.Union([
173
- // The custom validation handler rejected the handler because the client is unsupported.
174
- import_typebox.Type.Literal("REJECTED_UNSUPPORTED_CLIENT"),
175
- // The custom validation handler rejected the handshake.
176
- import_typebox.Type.Literal("REJECTED_BY_CUSTOM_HANDLER")
177
- ]);
178
- var HandshakeErrorFatalResponseCodes = import_typebox.Type.Union([
179
- HandshakeErrorCustomHandlerFatalResponseCodes,
180
- // The ciient sent a handshake that doesn't comply with the extended handshake metadata.
181
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE_META"),
182
- // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.
183
- import_typebox.Type.Literal("MALFORMED_HANDSHAKE"),
184
- // The client's protocol version does not match the server's.
185
- import_typebox.Type.Literal("PROTOCOL_VERSION_MISMATCH")
186
- ]);
187
- var HandshakeErrorResponseCodes = import_typebox.Type.Union([
188
- HandshakeErrorRetriableResponseCodes,
189
- HandshakeErrorFatalResponseCodes
190
- ]);
191
- var ControlMessageHandshakeResponseSchema = import_typebox.Type.Object({
192
- type: import_typebox.Type.Literal("HANDSHAKE_RESP"),
193
- status: import_typebox.Type.Union([
194
- import_typebox.Type.Object({
195
- ok: import_typebox.Type.Literal(true),
196
- sessionId: import_typebox.Type.String()
197
- }),
198
- import_typebox.Type.Object({
199
- ok: import_typebox.Type.Literal(false),
200
- reason: import_typebox.Type.String(),
201
- code: HandshakeErrorResponseCodes
202
- })
203
- ])
204
- });
205
- var ControlMessagePayloadSchema = import_typebox.Type.Union([
206
- ControlMessageCloseSchema,
207
- ControlMessageAckSchema,
208
- ControlMessageHandshakeRequestSchema,
209
- ControlMessageHandshakeResponseSchema
210
- ]);
211
- var OpaqueTransportMessageSchema = TransportMessageSchema(
212
- import_typebox.Type.Unknown()
213
- );
214
-
215
- // transport/stringifyError.ts
216
- function coerceErrorString(err) {
217
- if (err instanceof Error) {
218
- return err.message || "unknown reason";
219
- }
220
- return `[coerced to error] ${String(err)}`;
221
- }
222
-
223
- // codec/adapter.ts
224
- var CodecMessageAdapter = class {
225
- constructor(codec) {
226
- this.codec = codec;
227
- }
228
- toBuffer(msg) {
229
- try {
230
- return {
231
- ok: true,
232
- value: this.codec.toBuffer(msg)
233
- };
234
- } catch (e) {
235
- return {
236
- ok: false,
237
- reason: coerceErrorString(e)
238
- };
239
- }
240
- }
241
- fromBuffer(buf) {
242
- try {
243
- const parsedMsg = this.codec.fromBuffer(buf);
244
- if (!import_value.Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {
245
- return {
246
- ok: false,
247
- reason: "transport message schema mismatch"
248
- };
249
- }
250
- return {
251
- ok: true,
252
- value: parsedMsg
253
- };
254
- } catch (e) {
255
- return {
256
- ok: false,
257
- reason: coerceErrorString(e)
258
- };
259
- }
260
- }
261
- };
262
- // Annotate the CommonJS export names for ESM import in node:
263
- 0 && (module.exports = {
264
- BinaryCodec,
265
- CodecMessageAdapter,
266
- NaiveJsonCodec
267
- });
268
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../codec/index.ts","../../codec/binary.ts","../../codec/json.ts","../../codec/adapter.ts","../../transport/message.ts","../../transport/stringifyError.ts"],"sourcesContent":["export { BinaryCodec } from './binary';\nexport { NaiveJsonCodec } from './json';\nexport type { Codec } from './types';\nexport { CodecMessageAdapter } from './adapter';\n","import { DecodeError, ExtensionCodec, decode, encode } from '@msgpack/msgpack';\nimport { Codec } from './types';\n\nconst BIGINT_EXT_TYPE = 0;\nconst extensionCodec = new ExtensionCodec();\nextensionCodec.register({\n type: BIGINT_EXT_TYPE,\n encode(input: unknown): Uint8Array | null {\n if (typeof input === 'bigint') {\n if (\n input <= Number.MAX_SAFE_INTEGER &&\n input >= Number.MIN_SAFE_INTEGER\n ) {\n return encode(Number(input));\n } else {\n return encode(String(input));\n }\n } else {\n return null;\n }\n },\n decode(data: Uint8Array): bigint {\n const val = decode(data);\n if (!(typeof val === 'string' || typeof val === 'number')) {\n throw new DecodeError(`unexpected BigInt source: ${typeof val}`);\n }\n\n return BigInt(val);\n },\n});\n\n/**\n * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood\n * @type {Codec}\n */\nexport const BinaryCodec: Codec = {\n toBuffer(obj) {\n return encode(obj, {\n ignoreUndefined: true,\n initialBufferSize: 512,\n extensionCodec,\n });\n },\n fromBuffer: (buff: Uint8Array) => {\n const res = decode(buff, { extensionCodec });\n if (typeof res !== 'object' || res === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return res;\n },\n};\n","import { Codec } from './types';\n\nconst encoder = new TextEncoder();\nconst decoder = new TextDecoder();\n\n// Convert Uint8Array to base64\nfunction uint8ArrayToBase64(uint8Array: Uint8Array) {\n let binary = '';\n uint8Array.forEach((byte) => {\n binary += String.fromCharCode(byte);\n });\n\n return btoa(binary);\n}\n\n// Convert base64 to Uint8Array\nfunction base64ToUint8Array(base64: string) {\n const binaryString = atob(base64);\n const uint8Array = new Uint8Array(binaryString.length);\n for (let i = 0; i < binaryString.length; i++) {\n uint8Array[i] = binaryString.charCodeAt(i);\n }\n\n return uint8Array;\n}\n\ninterface Base64EncodedValue {\n $t: string;\n}\n\ninterface BigIntEncodedValue {\n $b: string;\n}\n\n/**\n * Naive JSON codec implementation using JSON.stringify and JSON.parse.\n * @type {Codec}\n */\nexport const NaiveJsonCodec: Codec = {\n toBuffer: (obj: object) => {\n return encoder.encode(\n JSON.stringify(obj, function replacer<\n T extends object,\n >(this: T, key: keyof T) {\n const val = this[key];\n if (val instanceof Uint8Array) {\n return { $t: uint8ArrayToBase64(val) } satisfies Base64EncodedValue;\n } else if (typeof val === 'bigint') {\n return { $b: val.toString() } satisfies BigIntEncodedValue;\n } else {\n return val;\n }\n }),\n );\n },\n fromBuffer: (buff: Uint8Array) => {\n const parsed = JSON.parse(\n decoder.decode(buff),\n function reviver(_key, val: unknown) {\n if ((val as Base64EncodedValue | undefined)?.$t !== undefined) {\n return base64ToUint8Array((val as Base64EncodedValue).$t);\n } else if ((val as BigIntEncodedValue | undefined)?.$b !== undefined) {\n return BigInt((val as BigIntEncodedValue).$b);\n } else {\n return val;\n }\n },\n ) as unknown;\n if (typeof parsed !== 'object' || parsed === null) {\n throw new Error('unpacked msg is not an object');\n }\n\n return parsed;\n },\n};\n","import { Value } from '@sinclair/typebox/value';\nimport {\n OpaqueTransportMessage,\n OpaqueTransportMessageSchema,\n} from '../transport';\nimport { Codec } from './types';\nimport { DeserializeResult, SerializeResult } from '../transport/results';\nimport { coerceErrorString } from '../transport/stringifyError';\n\n/**\n * Adapts a {@link Codec} to the {@link OpaqueTransportMessage} format,\n * accounting for fallibility of toBuffer and fromBuffer and wrapping\n * it with a Result type.\n */\nexport class CodecMessageAdapter {\n constructor(private readonly codec: Codec) {}\n\n toBuffer(msg: OpaqueTransportMessage): SerializeResult {\n try {\n return {\n ok: true,\n value: this.codec.toBuffer(msg),\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n\n fromBuffer(buf: Uint8Array): DeserializeResult {\n try {\n const parsedMsg = this.codec.fromBuffer(buf);\n if (!Value.Check(OpaqueTransportMessageSchema, parsedMsg)) {\n return {\n ok: false,\n reason: 'transport message schema mismatch',\n };\n }\n\n return {\n ok: true,\n value: parsedMsg,\n };\n } catch (e) {\n return {\n ok: false,\n reason: coerceErrorString(e),\n };\n }\n }\n}\n","import { Type, TSchema, Static } from '@sinclair/typebox';\nimport { PropagationContext } from '../tracing';\nimport { generateId } from './id';\nimport { ErrResult } from '../router';\nimport type { ErrorPayload } from '../router/result';\n\n/**\n * Control flags for transport messages.\n */\nexport const enum ControlFlags {\n /**\n * Used in heartbeat messages.\n */\n AckBit = 0b00001,\n /**\n * Used in stream open requests.\n */\n StreamOpenBit = 0b00010,\n /**\n * Used when a stream is cancelled due errors or to explicit cancellation\n */\n StreamCancelBit = 0b00100,\n /**\n * Used when writer closes the stream.\n */\n StreamClosedBit = 0b01000,\n}\n\n/**\n * Generic Typebox schema for a transport message.\n * @template T The type of the payload.\n * @param {T} t The payload schema.\n * @returns The transport message schema.\n */\nexport const TransportMessageSchema = <T extends TSchema>(t: T) =>\n Type.Object({\n id: Type.String(),\n from: Type.String(),\n to: Type.String(),\n seq: Type.Integer(),\n ack: Type.Integer(),\n serviceName: Type.Optional(Type.String()),\n procedureName: Type.Optional(Type.String()),\n streamId: Type.String(),\n controlFlags: Type.Integer(),\n tracing: Type.Optional(\n Type.Object({\n traceparent: Type.String(),\n tracestate: Type.String(),\n }),\n ),\n payload: t,\n });\n\n/**\n * Defines the schema for a transport acknowledgement message. This is never constructed manually\n * and is only used internally by the library for tracking inflight messages.\n * @returns The transport message schema.\n */\nexport const ControlMessageAckSchema = Type.Object({\n type: Type.Literal('ACK'),\n});\n\n/**\n * Defines the schema for a transport close message. This is never constructed manually and is only\n * used internally by the library for closing and cleaning up streams.\n */\nexport const ControlMessageCloseSchema = Type.Object({\n type: Type.Literal('CLOSE'),\n});\n\nexport type ProtocolVersion = 'v1.1' | 'v2.0';\nexport const currentProtocolVersion = 'v2.0' satisfies ProtocolVersion;\nexport const acceptedProtocolVersions = ['v1.1', currentProtocolVersion];\nexport function isAcceptedProtocolVersion(\n version: string,\n): version is ProtocolVersion {\n return acceptedProtocolVersions.includes(version);\n}\n\nexport const ControlMessageHandshakeRequestSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_REQ'),\n protocolVersion: Type.String(),\n sessionId: Type.String(),\n /**\n * Specifies what the server's expected session state (from the pov of the client). This can be\n * used by the server to know whether this is a new or a reestablished connection, and whether it\n * is compatible with what it already has.\n */\n expectedSessionState: Type.Object({\n // what the client expects the server to send next\n nextExpectedSeq: Type.Integer(),\n nextSentSeq: Type.Integer(),\n }),\n\n metadata: Type.Optional(Type.Unknown()),\n});\n\nexport const HandshakeErrorRetriableResponseCodes = Type.Union([\n Type.Literal('SESSION_STATE_MISMATCH'),\n]);\n\nexport const HandshakeErrorCustomHandlerFatalResponseCodes = Type.Union([\n // The custom validation handler rejected the handler because the client is unsupported.\n Type.Literal('REJECTED_UNSUPPORTED_CLIENT'),\n // The custom validation handler rejected the handshake.\n Type.Literal('REJECTED_BY_CUSTOM_HANDLER'),\n]);\n\nexport const HandshakeErrorFatalResponseCodes = Type.Union([\n HandshakeErrorCustomHandlerFatalResponseCodes,\n // The ciient sent a handshake that doesn't comply with the extended handshake metadata.\n Type.Literal('MALFORMED_HANDSHAKE_META'),\n // The ciient sent a handshake that doesn't comply with ControlMessageHandshakeRequestSchema.\n Type.Literal('MALFORMED_HANDSHAKE'),\n // The client's protocol version does not match the server's.\n Type.Literal('PROTOCOL_VERSION_MISMATCH'),\n]);\n\nexport const HandshakeErrorResponseCodes = Type.Union([\n HandshakeErrorRetriableResponseCodes,\n HandshakeErrorFatalResponseCodes,\n]);\n\nexport const ControlMessageHandshakeResponseSchema = Type.Object({\n type: Type.Literal('HANDSHAKE_RESP'),\n status: Type.Union([\n Type.Object({\n ok: Type.Literal(true),\n sessionId: Type.String(),\n }),\n Type.Object({\n ok: Type.Literal(false),\n reason: Type.String(),\n code: HandshakeErrorResponseCodes,\n }),\n ]),\n});\n\nexport const ControlMessagePayloadSchema = Type.Union([\n ControlMessageCloseSchema,\n ControlMessageAckSchema,\n ControlMessageHandshakeRequestSchema,\n ControlMessageHandshakeResponseSchema,\n]);\n\n/**\n * Defines the schema for an opaque transport message that is agnostic to any\n * procedure/service.\n * @returns The transport message schema.\n */\nexport const OpaqueTransportMessageSchema = TransportMessageSchema(\n Type.Unknown(),\n);\n\n/**\n * Represents a transport message. This is the same type as {@link TransportMessageSchema} but\n * we can't statically infer generics from generic Typebox schemas so we have to define it again here.\n *\n * TypeScript can't enforce types when a bitmask is involved, so these are the semantics of\n * `controlFlags`:\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `streamId` must be set to a unique value\n * (suggestion: use `nanoid`).\n * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `serviceName` and `procedureName` must be set.\n * * If `controlFlags & StreamClosedBit == StreamClosedBit` and the kind is `stream` or `subscription`,\n * `payload` should be discarded (usually contains a control message).\n * * If `controlFlags & AckBit == AckBit`, the message is an explicit acknowledgement message and doesn't\n * contain any payload that is relevant to the application so should not be delivered.\n * @template Payload The type of the payload.\n */\nexport interface TransportMessage<Payload = unknown> {\n id: string;\n from: TransportClientId;\n to: TransportClientId;\n seq: number;\n ack: number;\n serviceName?: string;\n procedureName?: string;\n streamId: string;\n controlFlags: number;\n tracing?: PropagationContext;\n payload: Payload;\n}\n\nexport type PartialTransportMessage<Payload = unknown> = Omit<\n TransportMessage<Payload>,\n 'id' | 'from' | 'to' | 'seq' | 'ack'\n>;\n\nexport function handshakeRequestMessage({\n from,\n to,\n sessionId,\n expectedSessionState,\n metadata,\n tracing,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n sessionId: string;\n expectedSessionState: Static<\n typeof ControlMessageHandshakeRequestSchema\n >['expectedSessionState'];\n metadata?: unknown;\n tracing?: PropagationContext;\n}): TransportMessage<Static<typeof ControlMessageHandshakeRequestSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n tracing,\n payload: {\n type: 'HANDSHAKE_REQ',\n protocolVersion: currentProtocolVersion,\n sessionId,\n expectedSessionState,\n metadata,\n } satisfies Static<typeof ControlMessageHandshakeRequestSchema>,\n };\n}\n\n/**\n * This is a reason that can be given during the handshake to indicate that the peer has the wrong\n * session state.\n */\nexport const SESSION_STATE_MISMATCH = 'session state mismatch';\n\nexport function handshakeResponseMessage({\n from,\n to,\n status,\n}: {\n from: TransportClientId;\n to: TransportClientId;\n status: Static<typeof ControlMessageHandshakeResponseSchema>['status'];\n}): TransportMessage<Static<typeof ControlMessageHandshakeResponseSchema>> {\n return {\n id: generateId(),\n from,\n to,\n seq: 0,\n ack: 0,\n streamId: generateId(),\n controlFlags: 0,\n payload: {\n type: 'HANDSHAKE_RESP',\n status,\n } satisfies Static<typeof ControlMessageHandshakeResponseSchema>,\n };\n}\n\nexport function closeStreamMessage(streamId: string): PartialTransportMessage {\n return {\n streamId,\n controlFlags: ControlFlags.StreamClosedBit,\n payload: {\n type: 'CLOSE' as const,\n } satisfies Static<typeof ControlMessagePayloadSchema>,\n };\n}\n\nexport function cancelMessage(\n streamId: string,\n payload: ErrResult<ErrorPayload>,\n) {\n return {\n streamId,\n controlFlags: ControlFlags.StreamCancelBit,\n payload,\n };\n}\n\n/**\n * A type alias for a transport message with an opaque payload.\n * @template T - The type of the opaque payload.\n */\nexport type OpaqueTransportMessage = TransportMessage;\nexport type TransportClientId = string;\n\n/**\n * An encoded message that is ready to be sent over the transport.\n * The seq number is kept to track which messages have been\n * acked by the peer and can be dropped from the send buffer.\n */\nexport interface EncodedTransportMessage {\n id: string;\n seq: number;\n msg: PartialTransportMessage;\n data: Uint8Array;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an ack message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the AckBit, false otherwise.\n */\nexport function isAck(controlFlag: number): boolean {\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n return (controlFlag & ControlFlags.AckBit) === ControlFlags.AckBit;\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream open message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamOpenBit, false otherwise.\n */\nexport function isStreamOpen(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamOpenBit) === ControlFlags.StreamOpenBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is a stream close message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the StreamCloseBit, false otherwise.\n */\nexport function isStreamClose(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamClosedBit) ===\n ControlFlags.StreamClosedBit\n );\n}\n\n/**\n * Checks if the given control flag (usually found in msg.controlFlag) is an cancel message.\n * @param controlFlag - The control flag to check.\n * @returns True if the control flag contains the CancelBit, false otherwise\n */\nexport function isStreamCancel(controlFlag: number): boolean {\n return (\n /* eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison */\n (controlFlag & ControlFlags.StreamCancelBit) ===\n ControlFlags.StreamCancelBit\n );\n}\n","export function coerceErrorString(err: unknown): string {\n if (err instanceof Error) {\n return err.message || 'unknown reason';\n }\n\n return `[coerced to error] ${String(err)}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,qBAA4D;AAG5D,IAAM,kBAAkB;AACxB,IAAM,iBAAiB,IAAI,8BAAe;AAC1C,eAAe,SAAS;AAAA,EACtB,MAAM;AAAA,EACN,OAAO,OAAmC;AACxC,QAAI,OAAO,UAAU,UAAU;AAC7B,UACE,SAAS,OAAO,oBAChB,SAAS,OAAO,kBAChB;AACA,mBAAO,uBAAO,OAAO,KAAK,CAAC;AAAA,MAC7B,OAAO;AACL,mBAAO,uBAAO,OAAO,KAAK,CAAC;AAAA,MAC7B;AAAA,IACF,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EACA,OAAO,MAA0B;AAC/B,UAAM,UAAM,uBAAO,IAAI;AACvB,QAAI,EAAE,OAAO,QAAQ,YAAY,OAAO,QAAQ,WAAW;AACzD,YAAM,IAAI,2BAAY,6BAA6B,OAAO,GAAG,EAAE;AAAA,IACjE;AAEA,WAAO,OAAO,GAAG;AAAA,EACnB;AACF,CAAC;AAMM,IAAM,cAAqB;AAAA,EAChC,SAAS,KAAK;AACZ,eAAO,uBAAO,KAAK;AAAA,MACjB,iBAAiB;AAAA,MACjB,mBAAmB;AAAA,MACnB;AAAA,IACF,CAAC;AAAA,EACH;AAAA,EACA,YAAY,CAAC,SAAqB;AAChC,UAAM,UAAM,uBAAO,MAAM,EAAE,eAAe,CAAC;AAC3C,QAAI,OAAO,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rD,QAAI;AACF,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO,KAAK,MAAM,SAAS,GAAG;AAAA,MAChC;AAAA,IACF,SAAS,GAAG;AACV,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ,kBAAkB,CAAC;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AAAA,EAEA,WAAW,KAAoC;AAC7C,QAAI;AACF,YAAM,YAAY,KAAK,MAAM,WAAW,GAAG;AAC3C,UAAI,CAAC,mBAAM,MAAM,8BAA8B,SAAS,GAAG;AACzD,eAAO;AAAA,UACL,IAAI;AAAA,UACJ,QAAQ;AAAA,QACV;AAAA,MACF;AAEA,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,OAAO;AAAA,MACT;AAAA,IACF,SAAS,GAAG;AACV,aAAO;AAAA,QACL,IAAI;AAAA,QACJ,QAAQ,kBAAkB,CAAC;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
@@ -1,19 +0,0 @@
1
- import { C as Codec } from '../types-BGGvYIJM.cjs';
2
- export { C as CodecMessageAdapter } from '../adapter-D5X11kmP.cjs';
3
- import '../message-CpXWqmJw.cjs';
4
- import '@sinclair/typebox';
5
- import '@opentelemetry/api';
6
-
7
- /**
8
- * Binary codec, uses [msgpack](https://www.npmjs.com/package/@msgpack/msgpack) under the hood
9
- * @type {Codec}
10
- */
11
- declare const BinaryCodec: Codec;
12
-
13
- /**
14
- * Naive JSON codec implementation using JSON.stringify and JSON.parse.
15
- * @type {Codec}
16
- */
17
- declare const NaiveJsonCodec: Codec;
18
-
19
- export { BinaryCodec, Codec, NaiveJsonCodec };
@@ -1,40 +0,0 @@
1
- import { T as Tags } from './index-BAGGleT3.cjs';
2
- import { P as ProtocolVersion, O as OpaqueTransportMessage } from './message-CpXWqmJw.cjs';
3
- import { C as Connection } from './transport-BnU3Zb0Q.cjs';
4
- import { W as WsLike } from './wslike-Dng9H1C7.cjs';
5
-
6
- interface ConnectionInfoExtras extends Record<string, unknown> {
7
- headers: Record<string, string>;
8
- }
9
- declare class WebSocketCloseError extends Error {
10
- code: number;
11
- reason: string;
12
- constructor(code: number, reason: string);
13
- }
14
- declare class WebSocketConnection extends Connection {
15
- ws: WsLike;
16
- extras?: ConnectionInfoExtras;
17
- get loggingMetadata(): Partial<{
18
- protocolVersion: ProtocolVersion;
19
- clientId: string;
20
- connectedTo: string;
21
- sessionId: string;
22
- connId: string;
23
- transportMessage: Partial<OpaqueTransportMessage>;
24
- validationErrors: {
25
- path: string;
26
- message: string;
27
- }[];
28
- tags: Tags[];
29
- telemetry: {
30
- traceId: string;
31
- spanId: string;
32
- };
33
- extras?: Record<string, unknown> | undefined;
34
- }>;
35
- constructor(ws: WsLike, extras?: ConnectionInfoExtras);
36
- send(payload: Uint8Array): boolean;
37
- close(): void;
38
- }
39
-
40
- export { WebSocketCloseError as W, WebSocketConnection as a };
@@ -1,37 +0,0 @@
1
- import { P as ProtocolVersion, O as OpaqueTransportMessage } from './message-CpXWqmJw.cjs';
2
-
3
- declare const LoggingLevels: {
4
- readonly debug: -1;
5
- readonly info: 0;
6
- readonly warn: 1;
7
- readonly error: 2;
8
- };
9
- type LoggingLevel = keyof typeof LoggingLevels;
10
- type LogFn = (msg: string, ctx?: MessageMetadata, level?: LoggingLevel) => void;
11
- type Logger = {
12
- [key in LoggingLevel]: (msg: string, metadata?: MessageMetadata) => void;
13
- };
14
- type Tags = 'invariant-violation' | 'state-transition' | 'invalid-request' | 'unhealthy-session' | 'uncaught-handler-error';
15
- type MessageMetadata = Partial<{
16
- protocolVersion: ProtocolVersion;
17
- clientId: string;
18
- connectedTo: string;
19
- sessionId: string;
20
- connId: string;
21
- transportMessage: Partial<OpaqueTransportMessage>;
22
- validationErrors: Array<{
23
- path: string;
24
- message: string;
25
- }>;
26
- tags: Array<Tags>;
27
- telemetry: {
28
- traceId: string;
29
- spanId: string;
30
- };
31
- extras?: Record<string, unknown>;
32
- }>;
33
- declare const stringLogger: LogFn;
34
- declare const coloredStringLogger: LogFn;
35
- declare const jsonLogger: LogFn;
36
-
37
- export { type Logger as L, type MessageMetadata as M, type Tags as T, type LogFn as a, type LoggingLevel as b, coloredStringLogger as c, jsonLogger as j, stringLogger as s };
@@ -1,55 +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
- // logging/index.ts
21
- var logging_exports = {};
22
- __export(logging_exports, {
23
- coloredStringLogger: () => coloredStringLogger,
24
- jsonLogger: () => jsonLogger,
25
- stringLogger: () => stringLogger
26
- });
27
- module.exports = __toCommonJS(logging_exports);
28
-
29
- // logging/log.ts
30
- var import_api = require("@opentelemetry/api");
31
- var stringLogger = (msg, ctx, level = "info") => {
32
- const from = ctx?.clientId ? `${ctx.clientId} -- ` : "";
33
- console.log(`[river:${level}] ${from}${msg}`);
34
- };
35
- var colorMap = {
36
- debug: "\x1B[34m",
37
- info: "\x1B[32m",
38
- warn: "\x1B[33m",
39
- error: "\x1B[31m"
40
- };
41
- var coloredStringLogger = (msg, ctx, level = "info") => {
42
- const color = colorMap[level];
43
- const from = ctx?.clientId ? `${ctx.clientId} -- ` : "";
44
- console.log(`[river:${color}${level}\x1B[0m] ${from}${msg}`);
45
- };
46
- var jsonLogger = (msg, ctx, level) => {
47
- console.log(JSON.stringify({ msg, ctx, level }));
48
- };
49
- // Annotate the CommonJS export names for ESM import in node:
50
- 0 && (module.exports = {
51
- coloredStringLogger,
52
- jsonLogger,
53
- stringLogger
54
- });
55
- //# sourceMappingURL=index.cjs.map
@@ -1 +0,0 @@
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 { OpaqueTransportMessage, ProtocolVersion } from '../transport/message';\nimport { context, trace } from '@opentelemetry/api';\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 =\n | 'invariant-violation'\n | 'state-transition'\n | 'invalid-request'\n | 'unhealthy-session'\n | 'uncaught-handler-error';\n\nconst cleanedLogFn = (log: LogFn) => {\n return (msg: string, metadata?: MessageMetadata) => {\n // try to infer telemetry\n if (metadata && !metadata.telemetry) {\n const span = trace.getSpan(context.active());\n if (span) {\n metadata.telemetry = {\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n };\n }\n }\n\n // skip cloning object if metadata has no transportMessage\n if (!metadata?.transportMessage) {\n log(msg, metadata);\n\n return;\n }\n\n // clone metadata and clean transportMessage\n const { payload, ...rest } = metadata.transportMessage;\n metadata.transportMessage = rest;\n\n log(msg, metadata);\n };\n};\n\nexport type MessageMetadata = Partial<{\n protocolVersion: ProtocolVersion;\n clientId: string;\n connectedTo: string;\n sessionId: string;\n connId: string;\n transportMessage: Partial<OpaqueTransportMessage>;\n validationErrors: Array<{ path: string; message: string }>;\n tags: Array<Tags>;\n telemetry: {\n traceId: string;\n spanId: string;\n };\n extras?: Record<string, unknown>;\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;;;ACCA,iBAA+B;AAwGxB,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 +0,0 @@
1
- export { a as LogFn, L as Logger, M as MessageMetadata, c as coloredStringLogger, j as jsonLogger, s as stringLogger } from '../index-BAGGleT3.cjs';
2
- import '../message-CpXWqmJw.cjs';
3
- import '@sinclair/typebox';
4
- import '@opentelemetry/api';
@@ -1,119 +0,0 @@
1
- import * as _sinclair_typebox from '@sinclair/typebox';
2
- import { TSchema } from '@sinclair/typebox';
3
- import { Span, Context } from '@opentelemetry/api';
4
-
5
- interface PropagationContext {
6
- traceparent: string;
7
- tracestate: string;
8
- }
9
- interface TelemetryInfo {
10
- span: Span;
11
- ctx: Context;
12
- }
13
-
14
- /**
15
- * Generic Typebox schema for a transport message.
16
- * @template T The type of the payload.
17
- * @param {T} t The payload schema.
18
- * @returns The transport message schema.
19
- */
20
- declare const TransportMessageSchema: <T extends TSchema>(t: T) => _sinclair_typebox.TObject<{
21
- id: _sinclair_typebox.TString;
22
- from: _sinclair_typebox.TString;
23
- to: _sinclair_typebox.TString;
24
- seq: _sinclair_typebox.TInteger;
25
- ack: _sinclair_typebox.TInteger;
26
- serviceName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
27
- procedureName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
28
- streamId: _sinclair_typebox.TString;
29
- controlFlags: _sinclair_typebox.TInteger;
30
- tracing: _sinclair_typebox.TOptional<_sinclair_typebox.TObject<{
31
- traceparent: _sinclair_typebox.TString;
32
- tracestate: _sinclair_typebox.TString;
33
- }>>;
34
- payload: T;
35
- }>;
36
- type ProtocolVersion = 'v1.1' | 'v2.0';
37
- declare const HandshakeErrorCustomHandlerFatalResponseCodes: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"REJECTED_UNSUPPORTED_CLIENT">, _sinclair_typebox.TLiteral<"REJECTED_BY_CUSTOM_HANDLER">]>;
38
- declare const HandshakeErrorResponseCodes: _sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"SESSION_STATE_MISMATCH">, _sinclair_typebox.TUnion<[_sinclair_typebox.TUnion<[_sinclair_typebox.TLiteral<"REJECTED_UNSUPPORTED_CLIENT">, _sinclair_typebox.TLiteral<"REJECTED_BY_CUSTOM_HANDLER">]>, _sinclair_typebox.TLiteral<"MALFORMED_HANDSHAKE_META">, _sinclair_typebox.TLiteral<"MALFORMED_HANDSHAKE">, _sinclair_typebox.TLiteral<"PROTOCOL_VERSION_MISMATCH">]>]>;
39
- /**
40
- * Defines the schema for an opaque transport message that is agnostic to any
41
- * procedure/service.
42
- * @returns The transport message schema.
43
- */
44
- declare const OpaqueTransportMessageSchema: _sinclair_typebox.TObject<{
45
- id: _sinclair_typebox.TString;
46
- from: _sinclair_typebox.TString;
47
- to: _sinclair_typebox.TString;
48
- seq: _sinclair_typebox.TInteger;
49
- ack: _sinclair_typebox.TInteger;
50
- serviceName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
51
- procedureName: _sinclair_typebox.TOptional<_sinclair_typebox.TString>;
52
- streamId: _sinclair_typebox.TString;
53
- controlFlags: _sinclair_typebox.TInteger;
54
- tracing: _sinclair_typebox.TOptional<_sinclair_typebox.TObject<{
55
- traceparent: _sinclair_typebox.TString;
56
- tracestate: _sinclair_typebox.TString;
57
- }>>;
58
- payload: _sinclair_typebox.TUnknown;
59
- }>;
60
- /**
61
- * Represents a transport message. This is the same type as {@link TransportMessageSchema} but
62
- * we can't statically infer generics from generic Typebox schemas so we have to define it again here.
63
- *
64
- * TypeScript can't enforce types when a bitmask is involved, so these are the semantics of
65
- * `controlFlags`:
66
- * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `streamId` must be set to a unique value
67
- * (suggestion: use `nanoid`).
68
- * * If `controlFlags & StreamOpenBit == StreamOpenBit`, `serviceName` and `procedureName` must be set.
69
- * * If `controlFlags & StreamClosedBit == StreamClosedBit` and the kind is `stream` or `subscription`,
70
- * `payload` should be discarded (usually contains a control message).
71
- * * If `controlFlags & AckBit == AckBit`, the message is an explicit acknowledgement message and doesn't
72
- * contain any payload that is relevant to the application so should not be delivered.
73
- * @template Payload The type of the payload.
74
- */
75
- interface TransportMessage<Payload = unknown> {
76
- id: string;
77
- from: TransportClientId;
78
- to: TransportClientId;
79
- seq: number;
80
- ack: number;
81
- serviceName?: string;
82
- procedureName?: string;
83
- streamId: string;
84
- controlFlags: number;
85
- tracing?: PropagationContext;
86
- payload: Payload;
87
- }
88
- type PartialTransportMessage<Payload = unknown> = Omit<TransportMessage<Payload>, 'id' | 'from' | 'to' | 'seq' | 'ack'>;
89
- /**
90
- * A type alias for a transport message with an opaque payload.
91
- * @template T - The type of the opaque payload.
92
- */
93
- type OpaqueTransportMessage = TransportMessage;
94
- type TransportClientId = string;
95
- /**
96
- * An encoded message that is ready to be sent over the transport.
97
- * The seq number is kept to track which messages have been
98
- * acked by the peer and can be dropped from the send buffer.
99
- */
100
- interface EncodedTransportMessage {
101
- id: string;
102
- seq: number;
103
- msg: PartialTransportMessage;
104
- data: Uint8Array;
105
- }
106
- /**
107
- * Checks if the given control flag (usually found in msg.controlFlag) is a stream open message.
108
- * @param controlFlag - The control flag to check.
109
- * @returns True if the control flag contains the StreamOpenBit, false otherwise.
110
- */
111
- declare function isStreamOpen(controlFlag: number): boolean;
112
- /**
113
- * Checks if the given control flag (usually found in msg.controlFlag) is a stream close message.
114
- * @param controlFlag - The control flag to check.
115
- * @returns True if the control flag contains the StreamCloseBit, false otherwise.
116
- */
117
- declare function isStreamClose(controlFlag: number): boolean;
118
-
119
- export { type EncodedTransportMessage as E, HandshakeErrorResponseCodes as H, type OpaqueTransportMessage as O, type ProtocolVersion as P, type TransportClientId as T, OpaqueTransportMessageSchema as a, type TransportMessage as b, TransportMessageSchema as c, isStreamOpen as d, type PartialTransportMessage as e, HandshakeErrorCustomHandlerFatalResponseCodes as f, type TelemetryInfo as g, isStreamClose as i };