@moqtap/codec 0.1.0 → 0.2.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 (277) hide show
  1. package/README.md +99 -95
  2. package/dist/chunk-4RIXXEII.js +1275 -0
  3. package/dist/chunk-4XYGE53S.cjs +698 -0
  4. package/dist/chunk-4YJANAXU.cjs +1109 -0
  5. package/dist/chunk-6AEHWULA.cjs +641 -0
  6. package/dist/chunk-7DUBLRXC.js +680 -0
  7. package/dist/{chunk-WNTXF3DE.cjs → chunk-7IVGHMKJ.cjs} +164 -62
  8. package/dist/{chunk-YBSEOSSP.js → chunk-A27S7HW7.js} +5 -1
  9. package/dist/chunk-BISI45MN.cjs +680 -0
  10. package/dist/{chunk-3BSZ55L3.cjs → chunk-BPNL5YFQ.cjs} +158 -24
  11. package/dist/chunk-CXDHOMHG.js +1097 -0
  12. package/dist/chunk-DUBCL3WF.cjs +749 -0
  13. package/dist/chunk-DWK5ZQZ4.js +642 -0
  14. package/dist/chunk-E6E3NQYU.js +680 -0
  15. package/dist/chunk-EFM5T7OM.js +698 -0
  16. package/dist/chunk-ENURAVHI.cjs +680 -0
  17. package/dist/{chunk-5WFXFLL4.cjs → chunk-FUFTMAQD.cjs} +96 -63
  18. package/dist/{chunk-2NARXGVA.cjs → chunk-FWISIR26.cjs} +5 -1
  19. package/dist/{chunk-YPXLV5YK.js → chunk-FXZ2MYKJ.js} +376 -38
  20. package/dist/chunk-G26SJ6XS.cjs +1341 -0
  21. package/dist/chunk-G7GI7LJA.js +737 -0
  22. package/dist/chunk-GXEW4COZ.cjs +737 -0
  23. package/dist/chunk-HSVYF6XX.cjs +1361 -0
  24. package/dist/chunk-IBVM4DMJ.cjs +1097 -0
  25. package/dist/chunk-IV2H5CFI.cjs +1275 -0
  26. package/dist/chunk-IV2HRJVT.js +1198 -0
  27. package/dist/chunk-JSQM2MG3.js +680 -0
  28. package/dist/chunk-K4OLITS2.cjs +1055 -0
  29. package/dist/{chunk-UOBWHJA5.js → chunk-KFTCU2P6.js} +2 -3
  30. package/dist/chunk-LH4NTURO.js +1361 -0
  31. package/dist/{chunk-DC4L6ZIT.js → chunk-MFAP7R6L.js} +154 -20
  32. package/dist/chunk-NGVE2RZT.js +1097 -0
  33. package/dist/chunk-NUX5BHWO.js +1341 -0
  34. package/dist/chunk-PJRA2TQ5.js +1055 -0
  35. package/dist/chunk-RVJAGE4S.cjs +1198 -0
  36. package/dist/{chunk-QYG6KGOV.cjs → chunk-RWQ43Z4F.cjs} +2 -3
  37. package/dist/chunk-RZHAPEXO.js +749 -0
  38. package/dist/chunk-ST24APEO.js +1109 -0
  39. package/dist/chunk-SYHW3FLI.cjs +642 -0
  40. package/dist/chunk-TLYNOOQP.cjs +432 -0
  41. package/dist/{chunk-23YG7F46.js → chunk-TMNGRIPL.js} +153 -51
  42. package/dist/{chunk-IQPDRQVC.js → chunk-U2B3B42P.js} +62 -29
  43. package/dist/chunk-UNS34PTA.cjs +680 -0
  44. package/dist/chunk-UR6JKS56.js +432 -0
  45. package/dist/{chunk-GDRGWFEK.cjs → chunk-UYXTY6ZQ.cjs} +376 -38
  46. package/dist/chunk-XUUCOLWU.cjs +1097 -0
  47. package/dist/chunk-YG5KJESI.js +641 -0
  48. package/dist/chunk-ZBKE2QRQ.js +1401 -0
  49. package/dist/chunk-ZSPO2GF2.cjs +1401 -0
  50. package/dist/codec-95k8CAu5.d.cts +35 -0
  51. package/dist/codec-AFuOxfsO.d.ts +60 -0
  52. package/dist/codec-B-UJ5Iow.d.cts +75 -0
  53. package/dist/codec-BC5jfvMb.d.ts +35 -0
  54. package/dist/codec-BECYPfY8.d.ts +35 -0
  55. package/dist/codec-BsPU1vNC.d.ts +39 -0
  56. package/dist/codec-BvpuF-6u.d.cts +39 -0
  57. package/dist/codec-C8jZI5Cx.d.cts +39 -0
  58. package/dist/codec-CAevkgf5.d.cts +33 -0
  59. package/dist/codec-CSUqCrRs.d.ts +39 -0
  60. package/dist/codec-C_HMXNK_.d.ts +33 -0
  61. package/dist/{codec-CTvFtQQI.d.cts → codec-CpuvYTSV.d.cts} +5 -5
  62. package/dist/codec-D0x8-SCw.d.cts +35 -0
  63. package/dist/codec-D7ARhpG1.d.ts +75 -0
  64. package/dist/codec-DNAUGshO.d.cts +60 -0
  65. package/dist/codec-DPx_QNn0.d.ts +31 -0
  66. package/dist/{codec-qPzfmLNu.d.ts → codec-DRhCx_hw.d.ts} +5 -5
  67. package/dist/codec-Db7YPe3l.d.ts +31 -0
  68. package/dist/codec-axkJpb7D.d.cts +31 -0
  69. package/dist/codec-ujAbFaep.d.cts +31 -0
  70. package/dist/draft10-session.cjs +6 -0
  71. package/dist/draft10-session.d.cts +8 -0
  72. package/dist/draft10-session.d.ts +8 -0
  73. package/dist/draft10-session.js +6 -0
  74. package/dist/draft10.cjs +115 -0
  75. package/dist/draft10.d.cts +95 -0
  76. package/dist/draft10.d.ts +95 -0
  77. package/dist/draft10.js +115 -0
  78. package/dist/draft11-session.cjs +6 -0
  79. package/dist/draft11-session.d.cts +8 -0
  80. package/dist/draft11-session.d.ts +8 -0
  81. package/dist/draft11-session.js +6 -0
  82. package/dist/draft11.cjs +109 -0
  83. package/dist/draft11.d.cts +99 -0
  84. package/dist/draft11.d.ts +99 -0
  85. package/dist/draft11.js +109 -0
  86. package/dist/draft12-session.cjs +6 -0
  87. package/dist/draft12-session.d.cts +8 -0
  88. package/dist/draft12-session.d.ts +8 -0
  89. package/dist/draft12-session.js +6 -0
  90. package/dist/draft12.cjs +117 -0
  91. package/dist/draft12.d.cts +106 -0
  92. package/dist/draft12.d.ts +106 -0
  93. package/dist/draft12.js +117 -0
  94. package/dist/draft13-session.cjs +6 -0
  95. package/dist/draft13-session.d.cts +8 -0
  96. package/dist/draft13-session.d.ts +8 -0
  97. package/dist/draft13-session.js +6 -0
  98. package/dist/draft13.cjs +119 -0
  99. package/dist/draft13.d.cts +108 -0
  100. package/dist/draft13.d.ts +108 -0
  101. package/dist/draft13.js +119 -0
  102. package/dist/draft14-session.cjs +2 -2
  103. package/dist/draft14-session.d.cts +4 -4
  104. package/dist/draft14-session.d.ts +4 -4
  105. package/dist/draft14-session.js +1 -1
  106. package/dist/draft14.cjs +4 -4
  107. package/dist/draft14.d.cts +27 -15
  108. package/dist/draft14.d.ts +27 -15
  109. package/dist/draft14.js +3 -3
  110. package/dist/draft15-session.cjs +6 -0
  111. package/dist/draft15-session.d.cts +8 -0
  112. package/dist/draft15-session.d.ts +8 -0
  113. package/dist/draft15-session.js +6 -0
  114. package/dist/draft15.cjs +111 -0
  115. package/dist/draft15.d.cts +93 -0
  116. package/dist/draft15.d.ts +93 -0
  117. package/dist/draft15.js +111 -0
  118. package/dist/draft16-session.cjs +6 -0
  119. package/dist/draft16-session.d.cts +8 -0
  120. package/dist/draft16-session.d.ts +8 -0
  121. package/dist/draft16-session.js +6 -0
  122. package/dist/draft16.cjs +113 -0
  123. package/dist/draft16.d.cts +94 -0
  124. package/dist/draft16.d.ts +94 -0
  125. package/dist/draft16.js +113 -0
  126. package/dist/draft17-session.cjs +8 -0
  127. package/dist/draft17-session.d.cts +51 -0
  128. package/dist/draft17-session.d.ts +51 -0
  129. package/dist/draft17-session.js +8 -0
  130. package/dist/draft17.cjs +99 -0
  131. package/dist/draft17.d.cts +40 -0
  132. package/dist/draft17.d.ts +40 -0
  133. package/dist/draft17.js +99 -0
  134. package/dist/draft7-session.cjs +3 -3
  135. package/dist/draft7-session.d.cts +3 -3
  136. package/dist/draft7-session.d.ts +3 -3
  137. package/dist/draft7-session.js +2 -2
  138. package/dist/draft7.cjs +6 -6
  139. package/dist/draft7.d.cts +10 -10
  140. package/dist/draft7.d.ts +10 -10
  141. package/dist/draft7.js +3 -3
  142. package/dist/draft8-session.cjs +6 -0
  143. package/dist/draft8-session.d.cts +8 -0
  144. package/dist/draft8-session.d.ts +8 -0
  145. package/dist/draft8-session.js +6 -0
  146. package/dist/draft8.cjs +115 -0
  147. package/dist/draft8.d.cts +95 -0
  148. package/dist/draft8.d.ts +95 -0
  149. package/dist/draft8.js +115 -0
  150. package/dist/draft9-session.cjs +6 -0
  151. package/dist/draft9-session.d.cts +8 -0
  152. package/dist/draft9-session.d.ts +8 -0
  153. package/dist/draft9-session.js +6 -0
  154. package/dist/draft9.cjs +115 -0
  155. package/dist/draft9.d.cts +95 -0
  156. package/dist/draft9.d.ts +95 -0
  157. package/dist/draft9.js +115 -0
  158. package/dist/index.cjs +79 -7
  159. package/dist/index.d.cts +71 -8
  160. package/dist/index.d.ts +71 -8
  161. package/dist/index.js +77 -5
  162. package/dist/{session-types-B9NIf7_F.d.ts → session-types-CJIFbTPd.d.ts} +20 -20
  163. package/dist/{session-types-CCo-oA-d.d.cts → session-types-Cbq8IGCP.d.cts} +20 -20
  164. package/dist/session.cjs +5 -5
  165. package/dist/session.d.cts +3 -3
  166. package/dist/session.d.ts +3 -3
  167. package/dist/session.js +5 -5
  168. package/dist/types-4VxSL2Ho.d.cts +261 -0
  169. package/dist/types-4VxSL2Ho.d.ts +261 -0
  170. package/dist/types-B2afJZM-.d.cts +236 -0
  171. package/dist/types-B2afJZM-.d.ts +236 -0
  172. package/dist/{types-CIk5W10V.d.ts → types-BTFeKYCb.d.cts} +37 -37
  173. package/dist/{types-CIk5W10V.d.cts → types-BTFeKYCb.d.ts} +37 -37
  174. package/dist/types-Bg6QYNVt.d.cts +290 -0
  175. package/dist/types-Bg6QYNVt.d.ts +290 -0
  176. package/dist/types-C_1HrqBl.d.cts +306 -0
  177. package/dist/types-C_1HrqBl.d.ts +306 -0
  178. package/dist/types-Cw4WE9dh.d.cts +261 -0
  179. package/dist/types-Cw4WE9dh.d.ts +261 -0
  180. package/dist/types-D5gNQiDj.d.cts +261 -0
  181. package/dist/types-D5gNQiDj.d.ts +261 -0
  182. package/dist/types-DqCDFqgB.d.cts +230 -0
  183. package/dist/types-DqCDFqgB.d.ts +230 -0
  184. package/dist/types-ERexTpT8.d.cts +217 -0
  185. package/dist/types-ERexTpT8.d.ts +217 -0
  186. package/dist/{types-ClXELFGN.d.cts → types-QNXoxC9Y.d.cts} +36 -41
  187. package/dist/{types-ClXELFGN.d.ts → types-QNXoxC9Y.d.ts} +36 -41
  188. package/dist/types-r-CasCf1.d.cts +262 -0
  189. package/dist/types-r-CasCf1.d.ts +262 -0
  190. package/package.json +116 -8
  191. package/src/core/buffer-reader.ts +16 -9
  192. package/src/core/buffer-writer.ts +2 -2
  193. package/src/core/errors.ts +1 -1
  194. package/src/core/session-types.ts +28 -41
  195. package/src/core/types.ts +92 -75
  196. package/src/drafts/draft07/announce-fsm.ts +1 -1
  197. package/src/drafts/draft07/codec.ts +235 -118
  198. package/src/drafts/draft07/index.ts +43 -44
  199. package/src/drafts/draft07/messages.ts +1 -1
  200. package/src/drafts/draft07/parameters.ts +2 -2
  201. package/src/drafts/draft07/rules.ts +67 -38
  202. package/src/drafts/draft07/session-fsm.ts +330 -117
  203. package/src/drafts/draft07/session.ts +10 -10
  204. package/src/drafts/draft07/subscription-fsm.ts +1 -1
  205. package/src/drafts/draft07/varint.ts +4 -4
  206. package/src/drafts/draft08/codec.ts +1254 -0
  207. package/src/drafts/draft08/index.ts +125 -0
  208. package/src/drafts/draft08/messages.ts +72 -0
  209. package/src/drafts/draft08/rules.ts +91 -0
  210. package/src/drafts/draft08/session-fsm.ts +718 -0
  211. package/src/drafts/draft08/session.ts +26 -0
  212. package/src/drafts/draft08/types.ts +377 -0
  213. package/src/drafts/draft09/codec.ts +1235 -0
  214. package/src/drafts/draft09/index.ts +125 -0
  215. package/src/drafts/draft09/messages.ts +72 -0
  216. package/src/drafts/draft09/rules.ts +91 -0
  217. package/src/drafts/draft09/session-fsm.ts +718 -0
  218. package/src/drafts/draft09/session.ts +26 -0
  219. package/src/drafts/draft09/types.ts +376 -0
  220. package/src/drafts/draft10/codec.ts +1235 -0
  221. package/src/drafts/draft10/index.ts +125 -0
  222. package/src/drafts/draft10/messages.ts +72 -0
  223. package/src/drafts/draft10/rules.ts +91 -0
  224. package/src/drafts/draft10/session-fsm.ts +718 -0
  225. package/src/drafts/draft10/session.ts +26 -0
  226. package/src/drafts/draft10/types.ts +376 -0
  227. package/src/drafts/draft11/codec.ts +1198 -0
  228. package/src/drafts/draft11/index.ts +123 -0
  229. package/src/drafts/draft11/messages.ts +71 -0
  230. package/src/drafts/draft11/rules.ts +100 -0
  231. package/src/drafts/draft11/session-fsm.ts +758 -0
  232. package/src/drafts/draft11/session.ts +26 -0
  233. package/src/drafts/draft11/types.ts +375 -0
  234. package/src/drafts/draft12/codec.ts +1354 -0
  235. package/src/drafts/draft12/index.ts +130 -0
  236. package/src/drafts/draft12/messages.ts +84 -0
  237. package/src/drafts/draft12/rules.ts +106 -0
  238. package/src/drafts/draft12/session-fsm.ts +805 -0
  239. package/src/drafts/draft12/session.ts +26 -0
  240. package/src/drafts/draft12/types.ts +414 -0
  241. package/src/drafts/draft13/codec.ts +1438 -0
  242. package/src/drafts/draft13/index.ts +132 -0
  243. package/src/drafts/draft13/messages.ts +86 -0
  244. package/src/drafts/draft13/rules.ts +108 -0
  245. package/src/drafts/draft13/session-fsm.ts +819 -0
  246. package/src/drafts/draft13/session.ts +26 -0
  247. package/src/drafts/draft13/types.ts +433 -0
  248. package/src/drafts/draft14/codec.ts +339 -189
  249. package/src/drafts/draft14/index.ts +103 -108
  250. package/src/drafts/draft14/messages.ts +61 -61
  251. package/src/drafts/draft14/rules.ts +77 -34
  252. package/src/drafts/draft14/session-fsm.ts +640 -147
  253. package/src/drafts/draft14/session.ts +13 -13
  254. package/src/drafts/draft14/types.ts +68 -68
  255. package/src/drafts/draft15/codec.ts +1661 -0
  256. package/src/drafts/draft15/index.ts +121 -0
  257. package/src/drafts/draft15/messages.ts +64 -0
  258. package/src/drafts/draft15/rules.ts +95 -0
  259. package/src/drafts/draft15/session-fsm.ts +687 -0
  260. package/src/drafts/draft15/session.ts +26 -0
  261. package/src/drafts/draft15/types.ts +336 -0
  262. package/src/drafts/draft16/codec.ts +1623 -0
  263. package/src/drafts/draft16/index.ts +123 -0
  264. package/src/drafts/draft16/messages.ts +67 -0
  265. package/src/drafts/draft16/rules.ts +96 -0
  266. package/src/drafts/draft16/session-fsm.ts +682 -0
  267. package/src/drafts/draft16/session.ts +26 -0
  268. package/src/drafts/draft16/types.ts +354 -0
  269. package/src/drafts/draft17/codec.ts +1621 -0
  270. package/src/drafts/draft17/index.ts +105 -0
  271. package/src/drafts/draft17/messages.ts +53 -0
  272. package/src/drafts/draft17/rules.ts +85 -0
  273. package/src/drafts/draft17/session-fsm.ts +437 -0
  274. package/src/drafts/draft17/session.ts +15 -0
  275. package/src/drafts/draft17/types.ts +310 -0
  276. package/src/index.ts +283 -33
  277. package/src/session.ts +20 -20
@@ -0,0 +1,1438 @@
1
+ import { BufferReader } from "../../core/buffer-reader.js";
2
+ import { BufferWriter } from "../../core/buffer-writer.js";
3
+ import type { BaseCodec, DecodeResult } from "../../core/types.js";
4
+ import { DecodeError } from "../../core/types.js";
5
+ import {
6
+ MESSAGE_ID_MAP,
7
+ MSG_ANNOUNCE,
8
+ MSG_ANNOUNCE_CANCEL,
9
+ MSG_ANNOUNCE_ERROR,
10
+ MSG_ANNOUNCE_OK,
11
+ MSG_CLIENT_SETUP,
12
+ MSG_FETCH,
13
+ MSG_FETCH_CANCEL,
14
+ MSG_FETCH_ERROR,
15
+ MSG_FETCH_OK,
16
+ MSG_GOAWAY,
17
+ MSG_MAX_REQUEST_ID,
18
+ MSG_PUBLISH,
19
+ MSG_PUBLISH_ERROR,
20
+ MSG_PUBLISH_OK,
21
+ MSG_REQUESTS_BLOCKED,
22
+ MSG_SERVER_SETUP,
23
+ MSG_SUBSCRIBE,
24
+ MSG_SUBSCRIBE_DONE,
25
+ MSG_SUBSCRIBE_ERROR,
26
+ MSG_SUBSCRIBE_NAMESPACE,
27
+ MSG_SUBSCRIBE_NAMESPACE_ERROR,
28
+ MSG_SUBSCRIBE_NAMESPACE_OK,
29
+ MSG_SUBSCRIBE_OK,
30
+ MSG_SUBSCRIBE_UPDATE,
31
+ MSG_TRACK_STATUS,
32
+ MSG_TRACK_STATUS_ERROR,
33
+ MSG_TRACK_STATUS_OK,
34
+ MSG_UNANNOUNCE,
35
+ MSG_UNSUBSCRIBE,
36
+ MSG_UNSUBSCRIBE_NAMESPACE,
37
+ PARAM_AUTHORIZATION_TOKEN,
38
+ PARAM_DELIVERY_TIMEOUT,
39
+ SETUP_PARAM_MAX_REQUEST_ID,
40
+ SETUP_PARAM_PATH,
41
+ VARINT_FRAMED_MESSAGES,
42
+ } from "./messages.js";
43
+ import type {
44
+ DatagramObject,
45
+ Draft13DataStream,
46
+ Draft13Fetch,
47
+ Draft13Message,
48
+ Draft13Params,
49
+ Draft13SetupParams,
50
+ FetchObjectPayload,
51
+ FetchStream,
52
+ JoiningFetch,
53
+ LargestLocation,
54
+ ObjectPayload,
55
+ StandaloneFetch,
56
+ SubgroupStream,
57
+ UnknownParam,
58
+ } from "./types.js";
59
+
60
+ // ─── Helpers ───────────────────────────────────────────────────────────────────
61
+
62
+ function bytesToHex(bytes: Uint8Array): string {
63
+ let hex = "";
64
+ for (let i = 0; i < bytes.byteLength; i++) {
65
+ hex += (bytes[i] as number).toString(16).padStart(2, "0");
66
+ }
67
+ return hex;
68
+ }
69
+
70
+ function hexToBytes(hex: string): Uint8Array {
71
+ const bytes = new Uint8Array(hex.length / 2);
72
+ for (let i = 0; i < hex.length; i += 2) {
73
+ bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
74
+ }
75
+ return bytes;
76
+ }
77
+
78
+ // ─── Setup Parameter Encoding/Decoding (even/odd convention) ────────────────────
79
+
80
+ function encodeSetupParams(params: Draft13SetupParams, w: BufferWriter): void {
81
+ let count = 0;
82
+ if (params.path !== undefined) count++;
83
+ if (params.max_request_id !== undefined) count++;
84
+ if (params.unknown) count += params.unknown.length;
85
+
86
+ w.writeVarInt(count);
87
+
88
+ if (params.path !== undefined) {
89
+ w.writeVarInt(SETUP_PARAM_PATH);
90
+ const encoded = new TextEncoder().encode(params.path);
91
+ w.writeVarInt(encoded.byteLength);
92
+ w.writeBytes(encoded);
93
+ }
94
+ if (params.max_request_id !== undefined) {
95
+ w.writeVarInt(SETUP_PARAM_MAX_REQUEST_ID);
96
+ w.writeVarInt(params.max_request_id);
97
+ }
98
+ if (params.unknown) {
99
+ for (const u of params.unknown) {
100
+ const id = BigInt(u.id);
101
+ w.writeVarInt(id);
102
+ if (id % 2n === 0n) {
103
+ const raw = hexToBytes(u.raw_hex);
104
+ const tmpReader = new BufferReader(raw);
105
+ w.writeVarInt(tmpReader.readVarInt());
106
+ } else {
107
+ const raw = hexToBytes(u.raw_hex);
108
+ w.writeVarInt(raw.byteLength);
109
+ w.writeBytes(raw);
110
+ }
111
+ }
112
+ }
113
+ }
114
+
115
+ function decodeSetupParams(r: BufferReader): Draft13SetupParams {
116
+ const count = Number(r.readVarInt());
117
+ const result: Draft13SetupParams = {};
118
+ const unknown: UnknownParam[] = [];
119
+
120
+ for (let i = 0; i < count; i++) {
121
+ const paramType = r.readVarInt();
122
+ if (paramType % 2n === 0n) {
123
+ const value = r.readVarInt();
124
+ if (paramType === SETUP_PARAM_MAX_REQUEST_ID) {
125
+ result.max_request_id = value;
126
+ } else {
127
+ const tmpW = new BufferWriter(16);
128
+ tmpW.writeVarInt(value);
129
+ const raw = tmpW.finish();
130
+ unknown.push({
131
+ id: `0x${paramType.toString(16)}`,
132
+ length: raw.byteLength,
133
+ raw_hex: bytesToHex(raw),
134
+ });
135
+ }
136
+ } else {
137
+ const length = Number(r.readVarInt());
138
+ const bytes = r.readBytes(length);
139
+ if (paramType === SETUP_PARAM_PATH) {
140
+ result.path = new TextDecoder().decode(bytes);
141
+ } else {
142
+ unknown.push({ id: `0x${paramType.toString(16)}`, length, raw_hex: bytesToHex(bytes) });
143
+ }
144
+ }
145
+ }
146
+
147
+ if (unknown.length > 0) result.unknown = unknown;
148
+ return result;
149
+ }
150
+
151
+ // ─── Version-Specific Parameter Encoding/Decoding ───────────────────────────────
152
+ // Uses even/odd convention: even type → bare varint value, odd type → length-prefixed blob
153
+
154
+ function encodeParams(params: Draft13Params, w: BufferWriter): void {
155
+ let count = params.unknown ? params.unknown.length : 0;
156
+ if (params.authorization_token !== undefined) count++;
157
+ if (params.delivery_timeout !== undefined) count++;
158
+ w.writeVarInt(count);
159
+
160
+ if (params.authorization_token !== undefined) {
161
+ // AUTHORIZATION_TOKEN = 0x01 (odd → length-prefixed)
162
+ w.writeVarInt(PARAM_AUTHORIZATION_TOKEN);
163
+ const at = params.authorization_token;
164
+ const tmpW = new BufferWriter(64);
165
+ tmpW.writeVarInt(at.alias_type);
166
+ tmpW.writeVarInt(at.token_type);
167
+ const tokenBytes = new TextEncoder().encode(at.token_value);
168
+ tmpW.writeBytes(tokenBytes);
169
+ const raw = tmpW.finish();
170
+ w.writeVarInt(raw.byteLength);
171
+ w.writeBytes(raw);
172
+ }
173
+ if (params.delivery_timeout !== undefined) {
174
+ // DELIVERY_TIMEOUT = 0x03 (odd → length-prefixed varint)
175
+ w.writeVarInt(PARAM_DELIVERY_TIMEOUT);
176
+ const tmpW = new BufferWriter(16);
177
+ tmpW.writeVarInt(params.delivery_timeout);
178
+ const raw = tmpW.finish();
179
+ w.writeVarInt(raw.byteLength);
180
+ w.writeBytes(raw);
181
+ }
182
+ if (params.unknown) {
183
+ for (const u of params.unknown) {
184
+ const id = BigInt(u.id);
185
+ w.writeVarInt(id);
186
+ if (id % 2n === 0n) {
187
+ // Even → bare varint
188
+ const raw = hexToBytes(u.raw_hex);
189
+ const tmpReader = new BufferReader(raw);
190
+ w.writeVarInt(tmpReader.readVarInt());
191
+ } else {
192
+ // Odd → length-prefixed
193
+ const raw = hexToBytes(u.raw_hex);
194
+ w.writeVarInt(raw.byteLength);
195
+ w.writeBytes(raw);
196
+ }
197
+ }
198
+ }
199
+ }
200
+
201
+ function decodeParams(r: BufferReader): Draft13Params {
202
+ const count = Number(r.readVarInt());
203
+ const result: Draft13Params = {};
204
+ const unknown: UnknownParam[] = [];
205
+
206
+ for (let i = 0; i < count; i++) {
207
+ const paramType = r.readVarInt();
208
+
209
+ if (paramType % 2n === 0n) {
210
+ // Even type → bare varint value
211
+ const value = r.readVarInt();
212
+ const tmpW = new BufferWriter(16);
213
+ tmpW.writeVarInt(value);
214
+ const raw = tmpW.finish();
215
+ unknown.push({
216
+ id: `0x${paramType.toString(16)}`,
217
+ length: raw.byteLength,
218
+ raw_hex: bytesToHex(raw),
219
+ });
220
+ } else {
221
+ // Odd type → length-prefixed blob
222
+ const length = Number(r.readVarInt());
223
+ const startOff = r.offset;
224
+
225
+ if (paramType === PARAM_AUTHORIZATION_TOKEN) {
226
+ const alias_type = r.readVarInt();
227
+ const token_type = r.readVarInt();
228
+ const tokenBytesLen = length - (r.offset - startOff);
229
+ const tokenBytes = r.readBytes(tokenBytesLen);
230
+ result.authorization_token = {
231
+ alias_type,
232
+ token_type,
233
+ token_value: new TextDecoder().decode(tokenBytes),
234
+ };
235
+ } else if (paramType === PARAM_DELIVERY_TIMEOUT) {
236
+ const blob = r.readBytes(length);
237
+ const tmpReader = new BufferReader(blob);
238
+ result.delivery_timeout = tmpReader.readVarInt();
239
+ } else {
240
+ const bytes = r.readBytes(length);
241
+ unknown.push({ id: `0x${paramType.toString(16)}`, length, raw_hex: bytesToHex(bytes) });
242
+ }
243
+ }
244
+ }
245
+
246
+ if (unknown.length > 0) result.unknown = unknown;
247
+ return result;
248
+ }
249
+
250
+ // ─── Payload Encoders ──────────────────────────────────────────────────────────
251
+
252
+ function encodeClientSetupPayload(
253
+ msg: Draft13Message & { type: "client_setup" },
254
+ w: BufferWriter,
255
+ ): void {
256
+ w.writeVarInt(msg.supported_versions.length);
257
+ for (const v of msg.supported_versions) w.writeVarInt(v);
258
+ encodeSetupParams(msg.parameters, w);
259
+ }
260
+
261
+ function encodeServerSetupPayload(
262
+ msg: Draft13Message & { type: "server_setup" },
263
+ w: BufferWriter,
264
+ ): void {
265
+ w.writeVarInt(msg.selected_version);
266
+ encodeSetupParams(msg.parameters, w);
267
+ }
268
+
269
+ function encodeSubscribePayload(
270
+ msg: Draft13Message & { type: "subscribe" },
271
+ w: BufferWriter,
272
+ ): void {
273
+ w.writeVarInt(msg.request_id);
274
+ w.writeTuple(msg.track_namespace);
275
+ w.writeString(msg.track_name);
276
+ w.writeUint8(msg.subscriber_priority);
277
+ w.writeVarInt(msg.group_order);
278
+ w.writeVarInt(msg.forward);
279
+ w.writeVarInt(msg.filter_type);
280
+ const ft = Number(msg.filter_type);
281
+ if (ft === 3 || ft === 4) {
282
+ w.writeVarInt(msg.start_group!);
283
+ w.writeVarInt(msg.start_object!);
284
+ }
285
+ if (ft === 4) {
286
+ w.writeVarInt(msg.end_group!);
287
+ }
288
+ encodeParams(msg.parameters, w);
289
+ }
290
+
291
+ function encodeSubscribeOkPayload(
292
+ msg: Draft13Message & { type: "subscribe_ok" },
293
+ w: BufferWriter,
294
+ ): void {
295
+ w.writeVarInt(msg.request_id);
296
+ w.writeVarInt(msg.track_alias);
297
+ w.writeVarInt(msg.expires);
298
+ w.writeVarInt(msg.group_order);
299
+ w.writeVarInt(msg.content_exists);
300
+ if (msg.content_exists === 1n && msg.largest_location) {
301
+ w.writeVarInt(msg.largest_location.group);
302
+ w.writeVarInt(msg.largest_location.object);
303
+ }
304
+ encodeParams(msg.parameters, w);
305
+ }
306
+
307
+ function encodeSubscribeErrorPayload(
308
+ msg: Draft13Message & { type: "subscribe_error" },
309
+ w: BufferWriter,
310
+ ): void {
311
+ w.writeVarInt(msg.request_id);
312
+ w.writeVarInt(msg.error_code);
313
+ w.writeString(msg.reason_phrase);
314
+ }
315
+
316
+ function encodeSubscribeUpdatePayload(
317
+ msg: Draft13Message & { type: "subscribe_update" },
318
+ w: BufferWriter,
319
+ ): void {
320
+ w.writeVarInt(msg.request_id);
321
+ w.writeVarInt(msg.start_group);
322
+ w.writeVarInt(msg.start_object);
323
+ w.writeVarInt(msg.end_group);
324
+ w.writeUint8(msg.subscriber_priority);
325
+ w.writeVarInt(msg.forward);
326
+ encodeParams(msg.parameters, w);
327
+ }
328
+
329
+ function encodeSubscribeDonePayload(
330
+ msg: Draft13Message & { type: "subscribe_done" },
331
+ w: BufferWriter,
332
+ ): void {
333
+ w.writeVarInt(msg.request_id);
334
+ w.writeVarInt(msg.status_code);
335
+ w.writeVarInt(msg.stream_count);
336
+ w.writeString(msg.reason_phrase);
337
+ }
338
+
339
+ function encodeUnsubscribePayload(
340
+ msg: Draft13Message & { type: "unsubscribe" },
341
+ w: BufferWriter,
342
+ ): void {
343
+ w.writeVarInt(msg.request_id);
344
+ }
345
+
346
+ function encodeAnnouncePayload(msg: Draft13Message & { type: "announce" }, w: BufferWriter): void {
347
+ w.writeVarInt(msg.request_id);
348
+ w.writeTuple(msg.track_namespace);
349
+ encodeParams(msg.parameters, w);
350
+ }
351
+
352
+ function encodeAnnounceOkPayload(
353
+ msg: Draft13Message & { type: "announce_ok" },
354
+ w: BufferWriter,
355
+ ): void {
356
+ w.writeVarInt(msg.request_id);
357
+ }
358
+
359
+ function encodeAnnounceErrorPayload(
360
+ msg: Draft13Message & { type: "announce_error" },
361
+ w: BufferWriter,
362
+ ): void {
363
+ w.writeVarInt(msg.request_id);
364
+ w.writeVarInt(msg.error_code);
365
+ w.writeString(msg.reason_phrase);
366
+ }
367
+
368
+ function encodeUnannouncePayload(
369
+ msg: Draft13Message & { type: "unannounce" },
370
+ w: BufferWriter,
371
+ ): void {
372
+ w.writeTuple(msg.track_namespace);
373
+ }
374
+
375
+ function encodeAnnounceCancelPayload(
376
+ msg: Draft13Message & { type: "announce_cancel" },
377
+ w: BufferWriter,
378
+ ): void {
379
+ w.writeTuple(msg.track_namespace);
380
+ w.writeVarInt(msg.error_code);
381
+ w.writeString(msg.reason_phrase);
382
+ }
383
+
384
+ // Draft-13: subscribe_namespace (renamed from subscribe_announces, same wire format)
385
+ function encodeSubscribeNamespacePayload(
386
+ msg: Draft13Message & { type: "subscribe_namespace" },
387
+ w: BufferWriter,
388
+ ): void {
389
+ w.writeVarInt(msg.request_id);
390
+ w.writeTuple(msg.track_namespace_prefix);
391
+ encodeParams(msg.parameters, w);
392
+ }
393
+
394
+ function encodeSubscribeNamespaceOkPayload(
395
+ msg: Draft13Message & { type: "subscribe_namespace_ok" },
396
+ w: BufferWriter,
397
+ ): void {
398
+ w.writeVarInt(msg.request_id);
399
+ }
400
+
401
+ function encodeSubscribeNamespaceErrorPayload(
402
+ msg: Draft13Message & { type: "subscribe_namespace_error" },
403
+ w: BufferWriter,
404
+ ): void {
405
+ w.writeVarInt(msg.request_id);
406
+ w.writeVarInt(msg.error_code);
407
+ w.writeString(msg.reason_phrase);
408
+ }
409
+
410
+ function encodeUnsubscribeNamespacePayload(
411
+ msg: Draft13Message & { type: "unsubscribe_namespace" },
412
+ w: BufferWriter,
413
+ ): void {
414
+ w.writeTuple(msg.track_namespace_prefix);
415
+ }
416
+
417
+ function encodePublishPayload(msg: Draft13Message & { type: "publish" }, w: BufferWriter): void {
418
+ w.writeVarInt(msg.request_id);
419
+ w.writeTuple(msg.track_namespace);
420
+ w.writeString(msg.track_name);
421
+ w.writeVarInt(msg.track_alias);
422
+ w.writeVarInt(msg.group_order);
423
+ w.writeVarInt(msg.content_exists);
424
+ if (msg.content_exists === 1n && msg.largest_location) {
425
+ w.writeVarInt(msg.largest_location.group);
426
+ w.writeVarInt(msg.largest_location.object);
427
+ }
428
+ w.writeVarInt(msg.forward);
429
+ encodeParams(msg.parameters, w);
430
+ }
431
+
432
+ function encodePublishOkPayload(
433
+ msg: Draft13Message & { type: "publish_ok" },
434
+ w: BufferWriter,
435
+ ): void {
436
+ w.writeVarInt(msg.request_id);
437
+ w.writeVarInt(msg.forward);
438
+ w.writeUint8(msg.subscriber_priority);
439
+ w.writeVarInt(msg.group_order);
440
+ w.writeVarInt(msg.filter_type);
441
+ const ft = Number(msg.filter_type);
442
+ if (ft === 3 || ft === 4) {
443
+ w.writeVarInt(msg.start_group!);
444
+ w.writeVarInt(msg.start_object!);
445
+ }
446
+ if (ft === 4) {
447
+ w.writeVarInt(msg.end_group!);
448
+ }
449
+ encodeParams(msg.parameters, w);
450
+ }
451
+
452
+ function encodePublishErrorPayload(
453
+ msg: Draft13Message & { type: "publish_error" },
454
+ w: BufferWriter,
455
+ ): void {
456
+ w.writeVarInt(msg.request_id);
457
+ w.writeVarInt(msg.error_code);
458
+ w.writeString(msg.reason_phrase);
459
+ }
460
+
461
+ function encodeFetchPayload(msg: Draft13Message & { type: "fetch" }, w: BufferWriter): void {
462
+ w.writeVarInt(msg.request_id);
463
+ w.writeUint8(msg.subscriber_priority);
464
+ w.writeVarInt(msg.group_order);
465
+ w.writeVarInt(msg.fetch_type);
466
+ const ft = Number(msg.fetch_type);
467
+ if (ft === 1 && msg.standalone) {
468
+ w.writeTuple(msg.standalone.track_namespace);
469
+ w.writeString(msg.standalone.track_name);
470
+ w.writeVarInt(msg.standalone.start_group);
471
+ w.writeVarInt(msg.standalone.start_object);
472
+ w.writeVarInt(msg.standalone.end_group);
473
+ w.writeVarInt(msg.standalone.end_object);
474
+ } else if ((ft === 2 || ft === 3) && msg.joining) {
475
+ w.writeVarInt(msg.joining.joining_subscribe_id);
476
+ w.writeVarInt(msg.joining.joining_start);
477
+ }
478
+ encodeParams(msg.parameters, w);
479
+ }
480
+
481
+ function encodeFetchOkPayload(msg: Draft13Message & { type: "fetch_ok" }, w: BufferWriter): void {
482
+ w.writeVarInt(msg.request_id);
483
+ w.writeVarInt(msg.group_order);
484
+ w.writeVarInt(msg.end_of_track);
485
+ w.writeVarInt(msg.end_location.group);
486
+ w.writeVarInt(msg.end_location.object);
487
+ encodeParams(msg.parameters, w);
488
+ }
489
+
490
+ function encodeFetchErrorPayload(
491
+ msg: Draft13Message & { type: "fetch_error" },
492
+ w: BufferWriter,
493
+ ): void {
494
+ w.writeVarInt(msg.request_id);
495
+ w.writeVarInt(msg.error_code);
496
+ w.writeString(msg.reason_phrase);
497
+ }
498
+
499
+ function encodeFetchCancelPayload(
500
+ msg: Draft13Message & { type: "fetch_cancel" },
501
+ w: BufferWriter,
502
+ ): void {
503
+ w.writeVarInt(msg.request_id);
504
+ }
505
+
506
+ // Draft-13: track_status is now SUBSCRIBE-like
507
+ function encodeTrackStatusPayload(
508
+ msg: Draft13Message & { type: "track_status" },
509
+ w: BufferWriter,
510
+ ): void {
511
+ w.writeVarInt(msg.request_id);
512
+ w.writeTuple(msg.track_namespace);
513
+ w.writeString(msg.track_name);
514
+ w.writeUint8(msg.subscriber_priority);
515
+ w.writeVarInt(msg.group_order);
516
+ w.writeVarInt(msg.forward);
517
+ w.writeVarInt(msg.filter_type);
518
+ const ft = Number(msg.filter_type);
519
+ if (ft === 3 || ft === 4) {
520
+ w.writeVarInt(msg.start_group!);
521
+ w.writeVarInt(msg.start_object!);
522
+ }
523
+ if (ft === 4) {
524
+ w.writeVarInt(msg.end_group!);
525
+ }
526
+ encodeParams(msg.parameters, w);
527
+ }
528
+
529
+ // Draft-13: track_status_ok is SUBSCRIBE_OK-like
530
+ function encodeTrackStatusOkPayload(
531
+ msg: Draft13Message & { type: "track_status_ok" },
532
+ w: BufferWriter,
533
+ ): void {
534
+ w.writeVarInt(msg.request_id);
535
+ w.writeVarInt(msg.track_alias);
536
+ w.writeVarInt(msg.expires);
537
+ w.writeVarInt(msg.group_order);
538
+ w.writeVarInt(msg.content_exists);
539
+ if (msg.content_exists === 1n && msg.largest_location) {
540
+ w.writeVarInt(msg.largest_location.group);
541
+ w.writeVarInt(msg.largest_location.object);
542
+ }
543
+ encodeParams(msg.parameters, w);
544
+ }
545
+
546
+ // Draft-13: track_status_error
547
+ function encodeTrackStatusErrorPayload(
548
+ msg: Draft13Message & { type: "track_status_error" },
549
+ w: BufferWriter,
550
+ ): void {
551
+ w.writeVarInt(msg.request_id);
552
+ w.writeVarInt(msg.error_code);
553
+ w.writeString(msg.reason_phrase);
554
+ }
555
+
556
+ function encodeGoAwayPayload(msg: Draft13Message & { type: "goaway" }, w: BufferWriter): void {
557
+ w.writeString(msg.new_session_uri);
558
+ }
559
+
560
+ function encodeMaxRequestIdPayload(
561
+ msg: Draft13Message & { type: "max_request_id" },
562
+ w: BufferWriter,
563
+ ): void {
564
+ w.writeVarInt(msg.request_id);
565
+ }
566
+
567
+ function encodeRequestsBlockedPayload(
568
+ msg: Draft13Message & { type: "requests_blocked" },
569
+ w: BufferWriter,
570
+ ): void {
571
+ w.writeVarInt(msg.maximum_request_id);
572
+ }
573
+
574
+ // ─── Payload Decoders ──────────────────────────────────────────────────────────
575
+
576
+ function decodeClientSetupPayload(r: BufferReader): Draft13Message {
577
+ const numVersions = Number(r.readVarInt());
578
+ if (numVersions === 0) {
579
+ throw new DecodeError("CONSTRAINT_VIOLATION", "supported_versions must not be empty", r.offset);
580
+ }
581
+ const supported_versions: bigint[] = [];
582
+ for (let i = 0; i < numVersions; i++) supported_versions.push(r.readVarInt());
583
+ const parameters = decodeSetupParams(r);
584
+ return { type: "client_setup", supported_versions, parameters };
585
+ }
586
+
587
+ function decodeServerSetupPayload(r: BufferReader): Draft13Message {
588
+ const selected_version = r.readVarInt();
589
+ const parameters = decodeSetupParams(r);
590
+ return { type: "server_setup", selected_version, parameters };
591
+ }
592
+
593
+ function decodeSubscribePayload(r: BufferReader): Draft13Message {
594
+ const request_id = r.readVarInt();
595
+ const track_namespace = r.readTuple();
596
+ const track_name = r.readString();
597
+ const subscriber_priority = r.readUint8();
598
+ const group_order = r.readVarInt();
599
+ const forward = r.readVarInt();
600
+ const filter_type = r.readVarInt();
601
+ const ft = Number(filter_type);
602
+ if (ft < 1 || ft > 4) {
603
+ throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid filter_type: ${ft}`, r.offset);
604
+ }
605
+ let start_group: bigint | undefined;
606
+ let start_object: bigint | undefined;
607
+ let end_group: bigint | undefined;
608
+ if (ft === 3 || ft === 4) {
609
+ start_group = r.readVarInt();
610
+ start_object = r.readVarInt();
611
+ }
612
+ if (ft === 4) {
613
+ end_group = r.readVarInt();
614
+ }
615
+ const parameters = decodeParams(r);
616
+ const msg: Record<string, unknown> = {
617
+ type: "subscribe",
618
+ request_id,
619
+ track_namespace,
620
+ track_name,
621
+ subscriber_priority,
622
+ group_order,
623
+ forward,
624
+ filter_type,
625
+ parameters,
626
+ };
627
+ if (start_group !== undefined) msg.start_group = start_group;
628
+ if (start_object !== undefined) msg.start_object = start_object;
629
+ if (end_group !== undefined) msg.end_group = end_group;
630
+ return msg as unknown as Draft13Message;
631
+ }
632
+
633
+ function decodeSubscribeOkPayload(r: BufferReader): Draft13Message {
634
+ const request_id = r.readVarInt();
635
+ const track_alias = r.readVarInt();
636
+ const expires = r.readVarInt();
637
+ const group_order = r.readVarInt();
638
+ const content_exists = r.readVarInt();
639
+ let largest_location: LargestLocation | undefined;
640
+ if (content_exists === 1n) {
641
+ const group = r.readVarInt();
642
+ const object = r.readVarInt();
643
+ largest_location = { group, object };
644
+ }
645
+ const parameters = decodeParams(r);
646
+ const msg: Record<string, unknown> = {
647
+ type: "subscribe_ok",
648
+ request_id,
649
+ track_alias,
650
+ expires,
651
+ group_order,
652
+ content_exists,
653
+ parameters,
654
+ };
655
+ if (largest_location) msg.largest_location = largest_location;
656
+ return msg as unknown as Draft13Message;
657
+ }
658
+
659
+ function decodeSubscribeErrorPayload(r: BufferReader): Draft13Message {
660
+ const request_id = r.readVarInt();
661
+ const error_code = r.readVarInt();
662
+ const reason_phrase = r.readString();
663
+ return { type: "subscribe_error", request_id, error_code, reason_phrase };
664
+ }
665
+
666
+ function decodeSubscribeUpdatePayload(r: BufferReader): Draft13Message {
667
+ const request_id = r.readVarInt();
668
+ const start_group = r.readVarInt();
669
+ const start_object = r.readVarInt();
670
+ const end_group = r.readVarInt();
671
+ const subscriber_priority = r.readUint8();
672
+ const forward = r.readVarInt();
673
+ const parameters = decodeParams(r);
674
+ return {
675
+ type: "subscribe_update",
676
+ request_id,
677
+ start_group,
678
+ start_object,
679
+ end_group,
680
+ subscriber_priority,
681
+ forward,
682
+ parameters,
683
+ };
684
+ }
685
+
686
+ function decodeSubscribeDonePayload(r: BufferReader): Draft13Message {
687
+ const request_id = r.readVarInt();
688
+ const status_code = r.readVarInt();
689
+ const stream_count = r.readVarInt();
690
+ const reason_phrase = r.readString();
691
+ return { type: "subscribe_done", request_id, status_code, stream_count, reason_phrase };
692
+ }
693
+
694
+ function decodeUnsubscribePayload(r: BufferReader): Draft13Message {
695
+ const request_id = r.readVarInt();
696
+ return { type: "unsubscribe", request_id };
697
+ }
698
+
699
+ function decodeAnnouncePayload(r: BufferReader): Draft13Message {
700
+ const request_id = r.readVarInt();
701
+ const track_namespace = r.readTuple();
702
+ const parameters = decodeParams(r);
703
+ return { type: "announce", request_id, track_namespace, parameters };
704
+ }
705
+
706
+ function decodeAnnounceOkPayload(r: BufferReader): Draft13Message {
707
+ const request_id = r.readVarInt();
708
+ return { type: "announce_ok", request_id };
709
+ }
710
+
711
+ function decodeAnnounceErrorPayload(r: BufferReader): Draft13Message {
712
+ const request_id = r.readVarInt();
713
+ const error_code = r.readVarInt();
714
+ const reason_phrase = r.readString();
715
+ return { type: "announce_error", request_id, error_code, reason_phrase };
716
+ }
717
+
718
+ function decodeUnannouncePayload(r: BufferReader): Draft13Message {
719
+ const track_namespace = r.readTuple();
720
+ return { type: "unannounce", track_namespace };
721
+ }
722
+
723
+ function decodeAnnounceCancelPayload(r: BufferReader): Draft13Message {
724
+ const track_namespace = r.readTuple();
725
+ const error_code = r.readVarInt();
726
+ const reason_phrase = r.readString();
727
+ return { type: "announce_cancel", track_namespace, error_code, reason_phrase };
728
+ }
729
+
730
+ // Draft-13: subscribe_namespace (renamed from subscribe_announces)
731
+ function decodeSubscribeNamespacePayload(r: BufferReader): Draft13Message {
732
+ const request_id = r.readVarInt();
733
+ const track_namespace_prefix = r.readTuple();
734
+ const parameters = decodeParams(r);
735
+ return { type: "subscribe_namespace", request_id, track_namespace_prefix, parameters };
736
+ }
737
+
738
+ function decodeSubscribeNamespaceOkPayload(r: BufferReader): Draft13Message {
739
+ const request_id = r.readVarInt();
740
+ return { type: "subscribe_namespace_ok", request_id };
741
+ }
742
+
743
+ function decodeSubscribeNamespaceErrorPayload(r: BufferReader): Draft13Message {
744
+ const request_id = r.readVarInt();
745
+ const error_code = r.readVarInt();
746
+ const reason_phrase = r.readString();
747
+ return { type: "subscribe_namespace_error", request_id, error_code, reason_phrase };
748
+ }
749
+
750
+ function decodeUnsubscribeNamespacePayload(r: BufferReader): Draft13Message {
751
+ const track_namespace_prefix = r.readTuple();
752
+ return { type: "unsubscribe_namespace", track_namespace_prefix };
753
+ }
754
+
755
+ function decodePublishPayload(r: BufferReader): Draft13Message {
756
+ const request_id = r.readVarInt();
757
+ const track_namespace = r.readTuple();
758
+ const track_name = r.readString();
759
+ const track_alias = r.readVarInt();
760
+ const group_order = r.readVarInt();
761
+ const content_exists = r.readVarInt();
762
+ let largest_location: LargestLocation | undefined;
763
+ if (content_exists === 1n) {
764
+ const group = r.readVarInt();
765
+ const object = r.readVarInt();
766
+ largest_location = { group, object };
767
+ }
768
+ const forward = r.readVarInt();
769
+ const parameters = decodeParams(r);
770
+ const msg: Record<string, unknown> = {
771
+ type: "publish",
772
+ request_id,
773
+ track_namespace,
774
+ track_name,
775
+ track_alias,
776
+ group_order,
777
+ content_exists,
778
+ forward,
779
+ parameters,
780
+ };
781
+ if (largest_location) msg.largest_location = largest_location;
782
+ return msg as unknown as Draft13Message;
783
+ }
784
+
785
+ function decodePublishOkPayload(r: BufferReader): Draft13Message {
786
+ const request_id = r.readVarInt();
787
+ const forward = r.readVarInt();
788
+ const subscriber_priority = r.readUint8();
789
+ const group_order = r.readVarInt();
790
+ const filter_type = r.readVarInt();
791
+ const ft = Number(filter_type);
792
+ let start_group: bigint | undefined;
793
+ let start_object: bigint | undefined;
794
+ let end_group: bigint | undefined;
795
+ if (ft === 3 || ft === 4) {
796
+ start_group = r.readVarInt();
797
+ start_object = r.readVarInt();
798
+ }
799
+ if (ft === 4) {
800
+ end_group = r.readVarInt();
801
+ }
802
+ const parameters = decodeParams(r);
803
+ const msg: Record<string, unknown> = {
804
+ type: "publish_ok",
805
+ request_id,
806
+ forward,
807
+ subscriber_priority,
808
+ group_order,
809
+ filter_type,
810
+ parameters,
811
+ };
812
+ if (start_group !== undefined) msg.start_group = start_group;
813
+ if (start_object !== undefined) msg.start_object = start_object;
814
+ if (end_group !== undefined) msg.end_group = end_group;
815
+ return msg as unknown as Draft13Message;
816
+ }
817
+
818
+ function decodePublishErrorPayload(r: BufferReader): Draft13Message {
819
+ const request_id = r.readVarInt();
820
+ const error_code = r.readVarInt();
821
+ const reason_phrase = r.readString();
822
+ return { type: "publish_error", request_id, error_code, reason_phrase };
823
+ }
824
+
825
+ function decodeFetchPayload(r: BufferReader): Draft13Message {
826
+ const request_id = r.readVarInt();
827
+ const subscriber_priority = r.readUint8();
828
+ const group_order = r.readVarInt();
829
+ const fetch_type = r.readVarInt();
830
+ const ft = Number(fetch_type);
831
+
832
+ if (ft < 1 || ft > 3) {
833
+ throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid fetch_type: ${ft}`, r.offset);
834
+ }
835
+
836
+ let standalone: StandaloneFetch | undefined;
837
+ let joining: JoiningFetch | undefined;
838
+
839
+ if (ft === 1) {
840
+ const track_namespace = r.readTuple();
841
+ const track_name = r.readString();
842
+ const start_group = r.readVarInt();
843
+ const start_object = r.readVarInt();
844
+ const end_group = r.readVarInt();
845
+ const end_object = r.readVarInt();
846
+ standalone = { track_namespace, track_name, start_group, start_object, end_group, end_object };
847
+ } else {
848
+ const joining_subscribe_id = r.readVarInt();
849
+ const joining_start = r.readVarInt();
850
+ joining = { joining_subscribe_id, joining_start };
851
+ }
852
+
853
+ const parameters = decodeParams(r);
854
+ return {
855
+ type: "fetch",
856
+ request_id,
857
+ subscriber_priority,
858
+ group_order,
859
+ fetch_type,
860
+ standalone,
861
+ joining,
862
+ parameters,
863
+ } as Draft13Fetch;
864
+ }
865
+
866
+ function decodeFetchOkPayload(r: BufferReader): Draft13Message {
867
+ const request_id = r.readVarInt();
868
+ const group_order = r.readVarInt();
869
+ const end_of_track = r.readVarInt();
870
+ const group = r.readVarInt();
871
+ const object = r.readVarInt();
872
+ const parameters = decodeParams(r);
873
+ return {
874
+ type: "fetch_ok",
875
+ request_id,
876
+ group_order,
877
+ end_of_track,
878
+ end_location: { group, object },
879
+ parameters,
880
+ };
881
+ }
882
+
883
+ function decodeFetchErrorPayload(r: BufferReader): Draft13Message {
884
+ const request_id = r.readVarInt();
885
+ const error_code = r.readVarInt();
886
+ const reason_phrase = r.readString();
887
+ return { type: "fetch_error", request_id, error_code, reason_phrase };
888
+ }
889
+
890
+ function decodeFetchCancelPayload(r: BufferReader): Draft13Message {
891
+ const request_id = r.readVarInt();
892
+ return { type: "fetch_cancel", request_id };
893
+ }
894
+
895
+ // Draft-13: track_status is SUBSCRIBE-like
896
+ function decodeTrackStatusPayload(r: BufferReader): Draft13Message {
897
+ const request_id = r.readVarInt();
898
+ const track_namespace = r.readTuple();
899
+ const track_name = r.readString();
900
+ const subscriber_priority = r.readUint8();
901
+ const group_order = r.readVarInt();
902
+ const forward = r.readVarInt();
903
+ const filter_type = r.readVarInt();
904
+ const ft = Number(filter_type);
905
+ if (ft < 1 || ft > 4) {
906
+ throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid filter_type: ${ft}`, r.offset);
907
+ }
908
+ let start_group: bigint | undefined;
909
+ let start_object: bigint | undefined;
910
+ let end_group: bigint | undefined;
911
+ if (ft === 3 || ft === 4) {
912
+ start_group = r.readVarInt();
913
+ start_object = r.readVarInt();
914
+ }
915
+ if (ft === 4) {
916
+ end_group = r.readVarInt();
917
+ }
918
+ const parameters = decodeParams(r);
919
+ const msg: Record<string, unknown> = {
920
+ type: "track_status",
921
+ request_id,
922
+ track_namespace,
923
+ track_name,
924
+ subscriber_priority,
925
+ group_order,
926
+ forward,
927
+ filter_type,
928
+ parameters,
929
+ };
930
+ if (start_group !== undefined) msg.start_group = start_group;
931
+ if (start_object !== undefined) msg.start_object = start_object;
932
+ if (end_group !== undefined) msg.end_group = end_group;
933
+ return msg as unknown as Draft13Message;
934
+ }
935
+
936
+ // Draft-13: track_status_ok is SUBSCRIBE_OK-like
937
+ function decodeTrackStatusOkPayload(r: BufferReader): Draft13Message {
938
+ const request_id = r.readVarInt();
939
+ const track_alias = r.readVarInt();
940
+ const expires = r.readVarInt();
941
+ const group_order = r.readVarInt();
942
+ const content_exists = r.readVarInt();
943
+ let largest_location: LargestLocation | undefined;
944
+ if (content_exists === 1n) {
945
+ const group = r.readVarInt();
946
+ const object = r.readVarInt();
947
+ largest_location = { group, object };
948
+ }
949
+ const parameters = decodeParams(r);
950
+ const msg: Record<string, unknown> = {
951
+ type: "track_status_ok",
952
+ request_id,
953
+ track_alias,
954
+ expires,
955
+ group_order,
956
+ content_exists,
957
+ parameters,
958
+ };
959
+ if (largest_location) msg.largest_location = largest_location;
960
+ return msg as unknown as Draft13Message;
961
+ }
962
+
963
+ // Draft-13: track_status_error
964
+ function decodeTrackStatusErrorPayload(r: BufferReader): Draft13Message {
965
+ const request_id = r.readVarInt();
966
+ const error_code = r.readVarInt();
967
+ const reason_phrase = r.readString();
968
+ return { type: "track_status_error", request_id, error_code, reason_phrase };
969
+ }
970
+
971
+ function decodeGoAwayPayload(r: BufferReader): Draft13Message {
972
+ const new_session_uri = r.readString();
973
+ return { type: "goaway", new_session_uri };
974
+ }
975
+
976
+ function decodeMaxRequestIdPayload(r: BufferReader): Draft13Message {
977
+ const request_id = r.readVarInt();
978
+ return { type: "max_request_id", request_id };
979
+ }
980
+
981
+ function decodeRequestsBlockedPayload(r: BufferReader): Draft13Message {
982
+ const maximum_request_id = r.readVarInt();
983
+ return { type: "requests_blocked", maximum_request_id };
984
+ }
985
+
986
+ // ─── Payload dispatch tables ───────────────────────────────────────────────────
987
+
988
+ const payloadDecoders: ReadonlyMap<bigint, (r: BufferReader) => Draft13Message> = new Map([
989
+ [MSG_CLIENT_SETUP, decodeClientSetupPayload],
990
+ [MSG_SERVER_SETUP, decodeServerSetupPayload],
991
+ [MSG_SUBSCRIBE, decodeSubscribePayload],
992
+ [MSG_SUBSCRIBE_OK, decodeSubscribeOkPayload],
993
+ [MSG_SUBSCRIBE_ERROR, decodeSubscribeErrorPayload],
994
+ [MSG_SUBSCRIBE_UPDATE, decodeSubscribeUpdatePayload],
995
+ [MSG_SUBSCRIBE_DONE, decodeSubscribeDonePayload],
996
+ [MSG_UNSUBSCRIBE, decodeUnsubscribePayload],
997
+ [MSG_ANNOUNCE, decodeAnnouncePayload],
998
+ [MSG_ANNOUNCE_OK, decodeAnnounceOkPayload],
999
+ [MSG_ANNOUNCE_ERROR, decodeAnnounceErrorPayload],
1000
+ [MSG_UNANNOUNCE, decodeUnannouncePayload],
1001
+ [MSG_ANNOUNCE_CANCEL, decodeAnnounceCancelPayload],
1002
+ [MSG_SUBSCRIBE_NAMESPACE, decodeSubscribeNamespacePayload],
1003
+ [MSG_SUBSCRIBE_NAMESPACE_OK, decodeSubscribeNamespaceOkPayload],
1004
+ [MSG_SUBSCRIBE_NAMESPACE_ERROR, decodeSubscribeNamespaceErrorPayload],
1005
+ [MSG_UNSUBSCRIBE_NAMESPACE, decodeUnsubscribeNamespacePayload],
1006
+ [MSG_PUBLISH, decodePublishPayload],
1007
+ [MSG_PUBLISH_OK, decodePublishOkPayload],
1008
+ [MSG_PUBLISH_ERROR, decodePublishErrorPayload],
1009
+ [MSG_FETCH, decodeFetchPayload],
1010
+ [MSG_FETCH_OK, decodeFetchOkPayload],
1011
+ [MSG_FETCH_ERROR, decodeFetchErrorPayload],
1012
+ [MSG_FETCH_CANCEL, decodeFetchCancelPayload],
1013
+ [MSG_TRACK_STATUS, decodeTrackStatusPayload],
1014
+ [MSG_TRACK_STATUS_OK, decodeTrackStatusOkPayload],
1015
+ [MSG_TRACK_STATUS_ERROR, decodeTrackStatusErrorPayload],
1016
+ [MSG_GOAWAY, decodeGoAwayPayload],
1017
+ [MSG_MAX_REQUEST_ID, decodeMaxRequestIdPayload],
1018
+ [MSG_REQUESTS_BLOCKED, decodeRequestsBlockedPayload],
1019
+ ]);
1020
+
1021
+ // ─── Public API ────────────────────────────────────────────────────────────────
1022
+
1023
+ /**
1024
+ * Encode a draft-13 control message.
1025
+ * Most messages use type(varint) + length(uint16 BE) + payload.
1026
+ * PUBLISH family uses type(varint) + length(varint) + payload.
1027
+ */
1028
+ export function encodeMessage(message: Draft13Message): Uint8Array {
1029
+ const typeId = MESSAGE_ID_MAP.get(message.type);
1030
+ if (typeId === undefined) throw new Error(`Unknown message type: ${message.type}`);
1031
+
1032
+ const payloadWriter = new BufferWriter();
1033
+ encodePayload(message, payloadWriter);
1034
+ const payload = payloadWriter.finish();
1035
+
1036
+ const writer = new BufferWriter();
1037
+ writer.writeVarInt(typeId);
1038
+
1039
+ if (VARINT_FRAMED_MESSAGES.has(typeId)) {
1040
+ // PUBLISH family: varint length framing
1041
+ writer.writeVarInt(payload.byteLength);
1042
+ } else {
1043
+ // All other messages: uint16 BE length framing
1044
+ if (payload.byteLength > 0xffff) {
1045
+ throw new Error(`Payload too large for 16-bit length: ${payload.byteLength}`);
1046
+ }
1047
+ writer.writeUint8((payload.byteLength >> 8) & 0xff);
1048
+ writer.writeUint8(payload.byteLength & 0xff);
1049
+ }
1050
+
1051
+ writer.writeBytes(payload);
1052
+ return writer.finish();
1053
+ }
1054
+
1055
+ function encodePayload(msg: Draft13Message, w: BufferWriter): void {
1056
+ switch (msg.type) {
1057
+ case "client_setup":
1058
+ return encodeClientSetupPayload(msg, w);
1059
+ case "server_setup":
1060
+ return encodeServerSetupPayload(msg, w);
1061
+ case "subscribe":
1062
+ return encodeSubscribePayload(msg, w);
1063
+ case "subscribe_ok":
1064
+ return encodeSubscribeOkPayload(msg, w);
1065
+ case "subscribe_error":
1066
+ return encodeSubscribeErrorPayload(msg, w);
1067
+ case "subscribe_update":
1068
+ return encodeSubscribeUpdatePayload(msg, w);
1069
+ case "subscribe_done":
1070
+ return encodeSubscribeDonePayload(msg, w);
1071
+ case "unsubscribe":
1072
+ return encodeUnsubscribePayload(msg, w);
1073
+ case "announce":
1074
+ return encodeAnnouncePayload(msg, w);
1075
+ case "announce_ok":
1076
+ return encodeAnnounceOkPayload(msg, w);
1077
+ case "announce_error":
1078
+ return encodeAnnounceErrorPayload(msg, w);
1079
+ case "unannounce":
1080
+ return encodeUnannouncePayload(msg, w);
1081
+ case "announce_cancel":
1082
+ return encodeAnnounceCancelPayload(msg, w);
1083
+ case "subscribe_namespace":
1084
+ return encodeSubscribeNamespacePayload(msg, w);
1085
+ case "subscribe_namespace_ok":
1086
+ return encodeSubscribeNamespaceOkPayload(msg, w);
1087
+ case "subscribe_namespace_error":
1088
+ return encodeSubscribeNamespaceErrorPayload(msg, w);
1089
+ case "unsubscribe_namespace":
1090
+ return encodeUnsubscribeNamespacePayload(msg, w);
1091
+ case "publish":
1092
+ return encodePublishPayload(msg, w);
1093
+ case "publish_ok":
1094
+ return encodePublishOkPayload(msg, w);
1095
+ case "publish_error":
1096
+ return encodePublishErrorPayload(msg, w);
1097
+ case "fetch":
1098
+ return encodeFetchPayload(msg, w);
1099
+ case "fetch_ok":
1100
+ return encodeFetchOkPayload(msg, w);
1101
+ case "fetch_error":
1102
+ return encodeFetchErrorPayload(msg, w);
1103
+ case "fetch_cancel":
1104
+ return encodeFetchCancelPayload(msg, w);
1105
+ case "track_status":
1106
+ return encodeTrackStatusPayload(msg, w);
1107
+ case "track_status_ok":
1108
+ return encodeTrackStatusOkPayload(msg, w);
1109
+ case "track_status_error":
1110
+ return encodeTrackStatusErrorPayload(msg, w);
1111
+ case "goaway":
1112
+ return encodeGoAwayPayload(msg, w);
1113
+ case "max_request_id":
1114
+ return encodeMaxRequestIdPayload(msg, w);
1115
+ case "requests_blocked":
1116
+ return encodeRequestsBlockedPayload(msg, w);
1117
+ default: {
1118
+ const _exhaustive: never = msg;
1119
+ throw new Error(`Unhandled message type: ${(_exhaustive as Draft13Message).type}`);
1120
+ }
1121
+ }
1122
+ }
1123
+
1124
+ /**
1125
+ * Decode a draft-13 control message from bytes.
1126
+ */
1127
+ export function decodeMessage(bytes: Uint8Array): DecodeResult<Draft13Message> {
1128
+ try {
1129
+ const reader = new BufferReader(bytes);
1130
+ const typeId = reader.readVarInt();
1131
+
1132
+ let payloadLength: number;
1133
+ if (VARINT_FRAMED_MESSAGES.has(typeId)) {
1134
+ // PUBLISH family: varint length framing
1135
+ payloadLength = Number(reader.readVarInt());
1136
+ } else {
1137
+ // All other messages: uint16 BE length framing
1138
+ const lenHi = reader.readUint8();
1139
+ const lenLo = reader.readUint8();
1140
+ payloadLength = (lenHi << 8) | lenLo;
1141
+ }
1142
+
1143
+ const payloadBytes = reader.readBytes(payloadLength);
1144
+ const payloadReader = new BufferReader(payloadBytes);
1145
+
1146
+ const decoder = payloadDecoders.get(typeId);
1147
+ if (!decoder) {
1148
+ return {
1149
+ ok: false,
1150
+ error: new DecodeError(
1151
+ "UNKNOWN_MESSAGE_TYPE",
1152
+ `Unknown message type ID: 0x${typeId.toString(16)}`,
1153
+ 0,
1154
+ ),
1155
+ };
1156
+ }
1157
+
1158
+ const message = decoder(payloadReader);
1159
+ return { ok: true, value: message, bytesRead: reader.offset };
1160
+ } catch (e) {
1161
+ if (e instanceof DecodeError) return { ok: false, error: e };
1162
+ throw e;
1163
+ }
1164
+ }
1165
+
1166
+ // ─── Data Stream Encoding/Decoding ─────────────────────────────────────────────
1167
+
1168
+ const FETCH_STREAM_TYPE = 0x05n;
1169
+
1170
+ export function encodeSubgroupStream(stream: SubgroupStream): Uint8Array {
1171
+ const w = new BufferWriter();
1172
+ const typeId = stream.streamTypeId;
1173
+ w.writeVarInt(BigInt(typeId));
1174
+ w.writeVarInt(stream.trackAlias);
1175
+ w.writeVarInt(stream.groupId);
1176
+ if (typeId === 0x0c) w.writeVarInt(stream.subgroupId);
1177
+ w.writeUint8(stream.publisherPriority);
1178
+ for (const obj of stream.objects) {
1179
+ w.writeVarInt(obj.objectId);
1180
+ w.writeVarInt(obj.payloadLength);
1181
+ if (obj.payloadLength === 0 && obj.status !== undefined) {
1182
+ w.writeVarInt(obj.status);
1183
+ } else {
1184
+ w.writeBytes(obj.payload);
1185
+ }
1186
+ }
1187
+ return w.finish();
1188
+ }
1189
+
1190
+ export function encodeDatagram(dg: DatagramObject): Uint8Array {
1191
+ const w = new BufferWriter();
1192
+ w.writeVarInt(BigInt(dg.streamTypeId));
1193
+ w.writeVarInt(dg.trackAlias);
1194
+ w.writeVarInt(dg.groupId);
1195
+ w.writeVarInt(dg.objectId);
1196
+ w.writeUint8(dg.publisherPriority);
1197
+ if (dg.streamTypeId === 0x02) {
1198
+ w.writeVarInt(dg.objectStatus ?? 0n);
1199
+ } else {
1200
+ w.writeBytes(dg.payload);
1201
+ }
1202
+ return w.finish();
1203
+ }
1204
+
1205
+ export function encodeFetchStream(stream: FetchStream): Uint8Array {
1206
+ const w = new BufferWriter();
1207
+ w.writeVarInt(FETCH_STREAM_TYPE);
1208
+ w.writeVarInt(stream.requestId);
1209
+ for (const obj of stream.objects) {
1210
+ w.writeVarInt(obj.groupId);
1211
+ w.writeVarInt(obj.subgroupId);
1212
+ w.writeVarInt(obj.objectId);
1213
+ w.writeUint8(obj.publisherPriority);
1214
+ w.writeVarInt(obj.extensionHeadersLength);
1215
+ w.writeVarInt(obj.payloadLength);
1216
+ w.writeBytes(obj.payload);
1217
+ }
1218
+ return w.finish();
1219
+ }
1220
+
1221
+ export function decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream> {
1222
+ try {
1223
+ const r = new BufferReader(bytes);
1224
+ const streamTypeId = Number(r.readVarInt());
1225
+ if (streamTypeId !== 0x08 && streamTypeId !== 0x0c) {
1226
+ return {
1227
+ ok: false,
1228
+ error: new DecodeError(
1229
+ "CONSTRAINT_VIOLATION",
1230
+ `Expected subgroup type 0x08 or 0x0C, got 0x${streamTypeId.toString(16)}`,
1231
+ 0,
1232
+ ),
1233
+ };
1234
+ }
1235
+ const trackAlias = r.readVarInt();
1236
+ const groupId = r.readVarInt();
1237
+ let subgroupId = 0n;
1238
+ if (streamTypeId === 0x0c) subgroupId = r.readVarInt();
1239
+ const publisherPriority = r.readUint8();
1240
+ const objects: ObjectPayload[] = [];
1241
+ while (r.remaining > 0) {
1242
+ const objectId = r.readVarInt();
1243
+ const payloadLength = Number(r.readVarInt());
1244
+ let payload: Uint8Array;
1245
+ let status: bigint | undefined;
1246
+ if (payloadLength === 0) {
1247
+ status = r.readVarInt();
1248
+ payload = new Uint8Array(0);
1249
+ } else {
1250
+ payload = r.readBytes(payloadLength);
1251
+ }
1252
+ const obj: ObjectPayload = { type: "object", objectId, payloadLength, payload };
1253
+ if (status !== undefined) (obj as unknown as Record<string, unknown>).status = status;
1254
+ objects.push(obj);
1255
+ }
1256
+ return {
1257
+ ok: true,
1258
+ value: {
1259
+ type: "subgroup",
1260
+ streamTypeId,
1261
+ trackAlias,
1262
+ groupId,
1263
+ subgroupId,
1264
+ publisherPriority,
1265
+ objects,
1266
+ },
1267
+ bytesRead: r.offset,
1268
+ };
1269
+ } catch (e) {
1270
+ if (e instanceof DecodeError) return { ok: false, error: e };
1271
+ throw e;
1272
+ }
1273
+ }
1274
+
1275
+ export function decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject> {
1276
+ try {
1277
+ const r = new BufferReader(bytes);
1278
+ const streamTypeId = Number(r.readVarInt());
1279
+ if (streamTypeId !== 0x00 && streamTypeId !== 0x02) {
1280
+ return {
1281
+ ok: false,
1282
+ error: new DecodeError(
1283
+ "CONSTRAINT_VIOLATION",
1284
+ `Expected datagram type 0x00 or 0x02, got 0x${streamTypeId.toString(16)}`,
1285
+ 0,
1286
+ ),
1287
+ };
1288
+ }
1289
+ const trackAlias = r.readVarInt();
1290
+ const groupId = r.readVarInt();
1291
+ const objectId = r.readVarInt();
1292
+ const publisherPriority = r.readUint8();
1293
+ let objectStatus: bigint | undefined;
1294
+ let payload: Uint8Array;
1295
+ if (streamTypeId === 0x02) {
1296
+ objectStatus = r.readVarInt();
1297
+ payload = new Uint8Array(0);
1298
+ } else {
1299
+ payload = r.readBytes(r.remaining);
1300
+ }
1301
+ const result: DatagramObject = {
1302
+ type: "datagram",
1303
+ streamTypeId,
1304
+ trackAlias,
1305
+ groupId,
1306
+ objectId,
1307
+ publisherPriority,
1308
+ payloadLength: payload.byteLength,
1309
+ payload,
1310
+ };
1311
+ if (objectStatus !== undefined)
1312
+ (result as unknown as Record<string, unknown>).objectStatus = objectStatus;
1313
+ return { ok: true, value: result, bytesRead: r.offset };
1314
+ } catch (e) {
1315
+ if (e instanceof DecodeError) return { ok: false, error: e };
1316
+ throw e;
1317
+ }
1318
+ }
1319
+
1320
+ export function decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream> {
1321
+ try {
1322
+ const r = new BufferReader(bytes);
1323
+ const streamType = r.readVarInt();
1324
+ if (streamType !== FETCH_STREAM_TYPE) {
1325
+ return {
1326
+ ok: false,
1327
+ error: new DecodeError(
1328
+ "CONSTRAINT_VIOLATION",
1329
+ `Expected fetch type 0x05, got 0x${streamType.toString(16)}`,
1330
+ 0,
1331
+ ),
1332
+ };
1333
+ }
1334
+ const requestId = r.readVarInt();
1335
+ const objects: FetchObjectPayload[] = [];
1336
+ while (r.remaining > 0) {
1337
+ const groupId = r.readVarInt();
1338
+ const subgroupId = r.readVarInt();
1339
+ const objectId = r.readVarInt();
1340
+ const publisherPriority = r.readUint8();
1341
+ const extensionHeadersLength = r.readVarInt();
1342
+ if (extensionHeadersLength > 0n) r.readBytes(Number(extensionHeadersLength));
1343
+ const payloadLength = Number(r.readVarInt());
1344
+ const payload = payloadLength > 0 ? r.readBytes(payloadLength) : new Uint8Array(0);
1345
+ objects.push({
1346
+ type: "object",
1347
+ groupId,
1348
+ subgroupId,
1349
+ objectId,
1350
+ publisherPriority,
1351
+ extensionHeadersLength,
1352
+ payloadLength,
1353
+ payload,
1354
+ });
1355
+ }
1356
+ return { ok: true, value: { type: "fetch", requestId, objects }, bytesRead: r.offset };
1357
+ } catch (e) {
1358
+ if (e instanceof DecodeError) return { ok: false, error: e };
1359
+ throw e;
1360
+ }
1361
+ }
1362
+
1363
+ export function decodeDataStream(
1364
+ streamType: "subgroup" | "datagram" | "fetch",
1365
+ bytes: Uint8Array,
1366
+ ): DecodeResult<Draft13DataStream> {
1367
+ switch (streamType) {
1368
+ case "subgroup":
1369
+ return decodeSubgroupStream(bytes);
1370
+ case "datagram":
1371
+ return decodeDatagram(bytes);
1372
+ case "fetch":
1373
+ return decodeFetchStream(bytes);
1374
+ default: {
1375
+ const _: never = streamType;
1376
+ throw new Error(`Unknown: ${_}`);
1377
+ }
1378
+ }
1379
+ }
1380
+
1381
+ export function createStreamDecoder(): TransformStream<Uint8Array, Draft13Message> {
1382
+ let buffer = new Uint8Array(0);
1383
+ return new TransformStream<Uint8Array, Draft13Message>({
1384
+ transform(chunk, controller) {
1385
+ const newBuffer = new Uint8Array(buffer.length + chunk.length);
1386
+ newBuffer.set(buffer, 0);
1387
+ newBuffer.set(chunk, buffer.length);
1388
+ buffer = newBuffer;
1389
+ while (buffer.length > 0) {
1390
+ const result = decodeMessage(buffer);
1391
+ if (!result.ok) {
1392
+ if (result.error.code === "UNEXPECTED_END") break;
1393
+ controller.error(result.error);
1394
+ return;
1395
+ }
1396
+ controller.enqueue(result.value);
1397
+ buffer = buffer.slice(result.bytesRead);
1398
+ }
1399
+ },
1400
+ flush(controller) {
1401
+ if (buffer.length > 0)
1402
+ controller.error(new DecodeError("UNEXPECTED_END", "Stream ended with incomplete data", 0));
1403
+ },
1404
+ });
1405
+ }
1406
+
1407
+ // ─── Codec Factory ─────────────────────────────────────────────────────────────
1408
+
1409
+ export interface Draft13Codec extends BaseCodec<Draft13Message> {
1410
+ readonly draft: "draft-ietf-moq-transport-13";
1411
+ encodeSubgroupStream(stream: SubgroupStream): Uint8Array;
1412
+ encodeDatagram(dg: DatagramObject): Uint8Array;
1413
+ encodeFetchStream(stream: FetchStream): Uint8Array;
1414
+ decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream>;
1415
+ decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject>;
1416
+ decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream>;
1417
+ decodeDataStream(
1418
+ streamType: "subgroup" | "datagram" | "fetch",
1419
+ bytes: Uint8Array,
1420
+ ): DecodeResult<Draft13DataStream>;
1421
+ createStreamDecoder(): TransformStream<Uint8Array, Draft13Message>;
1422
+ }
1423
+
1424
+ export function createDraft13Codec(): Draft13Codec {
1425
+ return {
1426
+ draft: "draft-ietf-moq-transport-13",
1427
+ encodeMessage,
1428
+ decodeMessage,
1429
+ encodeSubgroupStream,
1430
+ encodeDatagram,
1431
+ encodeFetchStream,
1432
+ decodeSubgroupStream,
1433
+ decodeDatagram,
1434
+ decodeFetchStream,
1435
+ decodeDataStream,
1436
+ createStreamDecoder,
1437
+ };
1438
+ }