@moqtap/codec 0.2.3 → 0.3.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 (299) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +100 -99
  3. package/dist/{chunk-RZHAPEXO.js → chunk-2A57DRXV.js} +36 -10
  4. package/dist/{chunk-73MWUKSJ.js → chunk-2UTVXWFF.js} +190 -102
  5. package/dist/{chunk-JTVCOMBI.cjs → chunk-3XKO6PCR.cjs} +290 -183
  6. package/dist/{chunk-ACQ4CUJP.cjs → chunk-4BDEU3D4.cjs} +237 -158
  7. package/dist/{chunk-4N4INRE7.cjs → chunk-4HBKHNU2.cjs} +144 -110
  8. package/dist/{chunk-2ZT6CVSE.js → chunk-4IVZZOY3.js} +269 -162
  9. package/dist/{chunk-GLBQDG4L.cjs → chunk-5O764MBD.cjs} +508 -117
  10. package/dist/chunk-7KBAWOBA.js +1212 -0
  11. package/dist/{chunk-JSQM2MG3.js → chunk-7QOPNSDF.js} +44 -12
  12. package/dist/{chunk-SYHW3FLI.cjs → chunk-7RE6KSIY.cjs} +28 -8
  13. package/dist/{chunk-YG5KJESI.js → chunk-AY6IAHUM.js} +28 -8
  14. package/dist/{chunk-EFM5T7OM.js → chunk-BLQDWOSG.js} +36 -10
  15. package/dist/{chunk-UYXTY6ZQ.cjs → chunk-E65QKRSN.cjs} +20 -12
  16. package/dist/{chunk-BISI45MN.cjs → chunk-EAHE3IOG.cjs} +44 -12
  17. package/dist/{chunk-PZBPH2D7.js → chunk-GCBFHZW6.js} +216 -137
  18. package/dist/{chunk-GXEW4COZ.cjs → chunk-H5NSL4MO.cjs} +36 -10
  19. package/dist/chunk-HZHSO7EW.cjs +1212 -0
  20. package/dist/{chunk-KZCYQ7ED.cjs → chunk-IILNSDEQ.cjs} +69 -41
  21. package/dist/{chunk-4XYGE53S.cjs → chunk-J3XCPBW3.cjs} +36 -10
  22. package/dist/{chunk-6AEHWULA.cjs → chunk-JKOEJZ5B.cjs} +28 -8
  23. package/dist/{chunk-RUPCJTC3.cjs → chunk-JL3NEW3O.cjs} +23 -1
  24. package/dist/{chunk-G7GI7LJA.js → chunk-LORZMJJB.js} +36 -10
  25. package/dist/{chunk-DUBCL3WF.cjs → chunk-LV5C6MEC.cjs} +36 -10
  26. package/dist/{chunk-ENURAVHI.cjs → chunk-MYXAD5JC.cjs} +44 -12
  27. package/dist/{chunk-FXZ2MYKJ.js → chunk-MZ7HUCGJ.js} +20 -12
  28. package/dist/{chunk-S74DWJE2.cjs → chunk-OKG2HT25.cjs} +277 -88
  29. package/dist/{chunk-BGWGVINJ.cjs → chunk-PKEOQSSZ.cjs} +144 -110
  30. package/dist/{chunk-2GODRVT5.js → chunk-Q46ZURKX.js} +325 -48
  31. package/dist/{chunk-UR6JKS56.js → chunk-Q7IGWV3P.js} +41 -9
  32. package/dist/{chunk-XSNX2IUJ.js → chunk-RW4UG7CN.js} +121 -87
  33. package/dist/{chunk-DWK5ZQZ4.js → chunk-RZTLQAKF.js} +28 -8
  34. package/dist/{chunk-UNS34PTA.cjs → chunk-S6IPIN66.cjs} +44 -12
  35. package/dist/{chunk-YIG2C3LF.cjs → chunk-SDWRXXOO.cjs} +214 -126
  36. package/dist/{chunk-CEH7ESNC.js → chunk-SHMA4PBY.js} +121 -87
  37. package/dist/{chunk-MC7W6PMI.js → chunk-U3ZVLT5L.js} +483 -135
  38. package/dist/{chunk-VJUUZ4W2.cjs → chunk-UJU63EFY.cjs} +374 -97
  39. package/dist/{chunk-7L43FE6P.js → chunk-VOU7PNHI.js} +23 -1
  40. package/dist/{chunk-E6E3NQYU.js → chunk-WRHGCVYN.js} +44 -12
  41. package/dist/{chunk-FPISPJ5N.cjs → chunk-XNWYLVGU.cjs} +529 -181
  42. package/dist/{chunk-U3IPZYPX.js → chunk-XS77RBY7.js} +228 -39
  43. package/dist/{chunk-JGG7CMSZ.cjs → chunk-XZE5R57R.cjs} +144 -110
  44. package/dist/{chunk-77MNXX3M.js → chunk-Y6KCSM3V.js} +121 -87
  45. package/dist/{chunk-TLYNOOQP.cjs → chunk-YTPZZI2M.cjs} +41 -9
  46. package/dist/{chunk-7DUBLRXC.js → chunk-YWRCSQBA.js} +44 -12
  47. package/dist/{chunk-MRJWLGYH.js → chunk-Z3VKP3PJ.js} +69 -41
  48. package/dist/{chunk-E6P74GDT.js → chunk-Z6U26IRI.js} +464 -73
  49. package/dist/{codec-FvGCxIhr.d.ts → codec-25u4_1HS.d.ts} +4 -4
  50. package/dist/{codec-DRcsBCsb.d.ts → codec-3Ppy_5Gd.d.ts} +4 -4
  51. package/dist/{codec-BdVMRMOI.d.ts → codec-BB0U8MF2.d.cts} +4 -4
  52. package/dist/{codec-B2cH-f5V.d.cts → codec-BHHfBTnV.d.ts} +4 -4
  53. package/dist/{codec-B5K73Bdj.d.ts → codec-BN6jk0Td.d.cts} +4 -4
  54. package/dist/{codec-R8GrCPt2.d.ts → codec-BU0gaSZm.d.ts} +4 -4
  55. package/dist/{codec-Bq-tLtfP.d.ts → codec-C-Yk2RNa.d.ts} +4 -4
  56. package/dist/codec-CFWQY9Lj.d.cts +18 -0
  57. package/dist/{codec-CPlK3Pi5.d.ts → codec-COy4uuPO.d.cts} +4 -4
  58. package/dist/codec-CewFCsEy.d.ts +18 -0
  59. package/dist/{codec-KXHvXZVb.d.cts → codec-Ck7ZwFF1.d.cts} +4 -4
  60. package/dist/{codec-DZhZSIii.d.cts → codec-D2QVSH9D.d.ts} +4 -4
  61. package/dist/{codec-BwFgpeQu.d.ts → codec-DDUBJGn0.d.cts} +4 -4
  62. package/dist/{codec-BFeliJFc.d.ts → codec-DNfml-se.d.ts} +4 -4
  63. package/dist/{codec-C4n1PS09.d.cts → codec-DoOGjjDq.d.cts} +4 -4
  64. package/dist/{codec-Bap882Fh.d.cts → codec-J7ekOSMc.d.ts} +4 -4
  65. package/dist/{codec-SKBeHQk7.d.ts → codec-R9TJCq-E.d.cts} +4 -4
  66. package/dist/{codec-DNUIgLqc.d.cts → codec-ZwV-Njt6.d.ts} +4 -4
  67. package/dist/{codec-HgBgHkFI.d.cts → codec-j819z_hL.d.cts} +4 -4
  68. package/dist/{codec-DY4QH364.d.cts → codec-w8z2j_uo.d.cts} +4 -4
  69. package/dist/{codec-CPvPq0sb.d.cts → codec-wtt6WF1K.d.ts} +4 -4
  70. package/dist/{codec-BUMjz0J4.d.cts → codec-z6_2PSzi.d.cts} +4 -4
  71. package/dist/draft10-session.cjs +2 -2
  72. package/dist/draft10-session.d.cts +6 -6
  73. package/dist/draft10-session.d.ts +6 -6
  74. package/dist/draft10-session.js +1 -1
  75. package/dist/draft10.cjs +8 -5
  76. package/dist/draft10.d.cts +14 -12
  77. package/dist/draft10.d.ts +14 -12
  78. package/dist/draft10.js +16 -13
  79. package/dist/draft11-session.cjs +2 -2
  80. package/dist/draft11-session.d.cts +6 -6
  81. package/dist/draft11-session.d.ts +6 -6
  82. package/dist/draft11-session.js +1 -1
  83. package/dist/draft11.cjs +8 -5
  84. package/dist/draft11.d.cts +14 -12
  85. package/dist/draft11.d.ts +14 -12
  86. package/dist/draft11.js +16 -13
  87. package/dist/draft12-session.cjs +2 -2
  88. package/dist/draft12-session.d.cts +6 -6
  89. package/dist/draft12-session.d.ts +6 -6
  90. package/dist/draft12-session.js +1 -1
  91. package/dist/draft12.cjs +8 -5
  92. package/dist/draft12.d.cts +16 -14
  93. package/dist/draft12.d.ts +16 -14
  94. package/dist/draft12.js +16 -13
  95. package/dist/draft13-session.cjs +2 -2
  96. package/dist/draft13-session.d.cts +6 -6
  97. package/dist/draft13-session.d.ts +6 -6
  98. package/dist/draft13-session.js +1 -1
  99. package/dist/draft13.cjs +8 -5
  100. package/dist/draft13.d.cts +16 -14
  101. package/dist/draft13.d.ts +16 -14
  102. package/dist/draft13.js +16 -13
  103. package/dist/draft14-session.cjs +2 -2
  104. package/dist/draft14-session.d.cts +6 -6
  105. package/dist/draft14-session.d.ts +6 -6
  106. package/dist/draft14-session.js +1 -1
  107. package/dist/draft14.cjs +14 -5
  108. package/dist/draft14.d.cts +14 -12
  109. package/dist/draft14.d.ts +14 -12
  110. package/dist/draft14.js +13 -4
  111. package/dist/draft15-session.cjs +2 -2
  112. package/dist/draft15-session.d.cts +6 -6
  113. package/dist/draft15-session.d.ts +6 -6
  114. package/dist/draft15-session.js +1 -1
  115. package/dist/draft15.cjs +8 -5
  116. package/dist/draft15.d.cts +14 -12
  117. package/dist/draft15.d.ts +14 -12
  118. package/dist/draft15.js +16 -13
  119. package/dist/draft16-session.cjs +2 -2
  120. package/dist/draft16-session.d.cts +6 -6
  121. package/dist/draft16-session.d.ts +6 -6
  122. package/dist/draft16-session.js +1 -1
  123. package/dist/draft16.cjs +8 -5
  124. package/dist/draft16.d.cts +14 -12
  125. package/dist/draft16.d.ts +14 -12
  126. package/dist/draft16.js +16 -13
  127. package/dist/draft17-session.cjs +2 -2
  128. package/dist/draft17-session.d.cts +7 -7
  129. package/dist/draft17-session.d.ts +7 -7
  130. package/dist/draft17-session.js +1 -1
  131. package/dist/draft17.cjs +8 -5
  132. package/dist/draft17.d.cts +11 -9
  133. package/dist/draft17.d.ts +11 -9
  134. package/dist/draft17.js +16 -13
  135. package/dist/draft7-session.cjs +2 -2
  136. package/dist/draft7-session.d.cts +6 -5
  137. package/dist/draft7-session.d.ts +6 -5
  138. package/dist/draft7-session.js +1 -1
  139. package/dist/draft7.cjs +71 -14
  140. package/dist/draft7.d.cts +53 -134
  141. package/dist/draft7.d.ts +53 -134
  142. package/dist/draft7.js +76 -19
  143. package/dist/draft8-session.cjs +2 -2
  144. package/dist/draft8-session.d.cts +6 -6
  145. package/dist/draft8-session.d.ts +6 -6
  146. package/dist/draft8-session.js +1 -1
  147. package/dist/draft8.cjs +8 -5
  148. package/dist/draft8.d.cts +14 -12
  149. package/dist/draft8.d.ts +14 -12
  150. package/dist/draft8.js +7 -4
  151. package/dist/draft9-session.cjs +2 -2
  152. package/dist/draft9-session.d.cts +6 -6
  153. package/dist/draft9-session.d.ts +6 -6
  154. package/dist/draft9-session.js +1 -1
  155. package/dist/draft9.cjs +8 -5
  156. package/dist/draft9.d.cts +14 -12
  157. package/dist/draft9.d.ts +14 -12
  158. package/dist/draft9.js +7 -4
  159. package/dist/index.cjs +52 -74
  160. package/dist/index.d.cts +41 -60
  161. package/dist/index.d.ts +41 -60
  162. package/dist/index.js +40 -62
  163. package/dist/{session-types-CJIFbTPd.d.ts → session-types-C7UONex5.d.cts} +28 -27
  164. package/dist/{session-types-Cbq8IGCP.d.cts → session-types-X-IYEGoG.d.ts} +28 -27
  165. package/dist/session.cjs +46 -13
  166. package/dist/session.d.cts +28 -9
  167. package/dist/session.d.ts +28 -9
  168. package/dist/session.js +46 -13
  169. package/dist/{types-DxSFvL2b.d.cts → types--Q7_DcvP.d.cts} +43 -39
  170. package/dist/{types-DxSFvL2b.d.ts → types--Q7_DcvP.d.ts} +43 -39
  171. package/dist/{types-B0FT5Qs2.d.ts → types-0IWbU9Z_.d.cts} +36 -36
  172. package/dist/{types-B0FT5Qs2.d.cts → types-0IWbU9Z_.d.ts} +36 -36
  173. package/dist/{types-gQsr0AAA.d.cts → types-B3g5G9KP.d.cts} +36 -36
  174. package/dist/{types-gQsr0AAA.d.ts → types-B3g5G9KP.d.ts} +36 -36
  175. package/dist/{types-Pme7sua0.d.cts → types-BFpFNM_m.d.cts} +57 -32
  176. package/dist/{types-Pme7sua0.d.ts → types-BFpFNM_m.d.ts} +57 -32
  177. package/dist/{types-8gUGeMgs.d.ts → types-Br7fm2mf.d.cts} +48 -26
  178. package/dist/{types-8gUGeMgs.d.cts → types-Br7fm2mf.d.ts} +48 -26
  179. package/dist/{types-BeAVNU-F.d.cts → types-C2qKTRR_.d.cts} +50 -45
  180. package/dist/{types-BeAVNU-F.d.ts → types-C2qKTRR_.d.ts} +50 -45
  181. package/dist/{types-DKpsfD3i.d.cts → types-DEaypVsD.d.cts} +115 -55
  182. package/dist/{types-DKpsfD3i.d.ts → types-DEaypVsD.d.ts} +115 -55
  183. package/dist/types-Dl4IaAHR.d.cts +282 -0
  184. package/dist/types-Dl4IaAHR.d.ts +282 -0
  185. package/dist/{types-CDa7F5ct.d.cts → types-DrQpTW1G.d.cts} +58 -50
  186. package/dist/{types-CDa7F5ct.d.ts → types-DrQpTW1G.d.ts} +58 -50
  187. package/dist/types-DuIO7cWK.d.cts +25 -0
  188. package/dist/types-DuIO7cWK.d.ts +25 -0
  189. package/dist/{types-B9A2g05r.d.cts → types-DuxfOYiO.d.cts} +47 -31
  190. package/dist/{types-B9A2g05r.d.ts → types-DuxfOYiO.d.ts} +47 -31
  191. package/dist/{types-D1dI_oTX.d.cts → types-jV1yDDBA.d.cts} +36 -36
  192. package/dist/{types-D1dI_oTX.d.ts → types-jV1yDDBA.d.ts} +36 -36
  193. package/package.json +192 -192
  194. package/src/core/buffer-reader.ts +130 -130
  195. package/src/core/buffer-writer.ts +100 -100
  196. package/src/core/errors.ts +1 -1
  197. package/src/core/hex.ts +21 -21
  198. package/src/core/session-types.ts +61 -59
  199. package/src/core/types.ts +18 -361
  200. package/src/drafts/draft07/codec.ts +1058 -938
  201. package/src/drafts/draft07/data-streams.ts +240 -240
  202. package/src/drafts/draft07/index.ts +124 -89
  203. package/src/drafts/draft07/messages.ts +76 -42
  204. package/src/drafts/draft07/rules.ts +107 -101
  205. package/src/drafts/draft07/session-fsm.ts +315 -287
  206. package/src/drafts/draft07/session.ts +8 -6
  207. package/src/drafts/draft07/types.ts +406 -72
  208. package/src/drafts/draft07/varint.ts +51 -51
  209. package/src/drafts/draft08/codec.ts +985 -953
  210. package/src/drafts/draft08/data-streams.ts +363 -359
  211. package/src/drafts/draft08/index.ts +10 -9
  212. package/src/drafts/draft08/messages.ts +59 -59
  213. package/src/drafts/draft08/rules.ts +73 -73
  214. package/src/drafts/draft08/session-fsm.ts +335 -303
  215. package/src/drafts/draft08/session.ts +6 -7
  216. package/src/drafts/draft08/types.ts +380 -384
  217. package/src/drafts/draft09/codec.ts +977 -945
  218. package/src/drafts/draft09/data-streams.ts +336 -332
  219. package/src/drafts/draft09/index.ts +10 -9
  220. package/src/drafts/draft09/messages.ts +59 -59
  221. package/src/drafts/draft09/rules.ts +73 -73
  222. package/src/drafts/draft09/session-fsm.ts +335 -303
  223. package/src/drafts/draft09/session.ts +6 -7
  224. package/src/drafts/draft09/types.ts +380 -384
  225. package/src/drafts/draft10/codec.ts +977 -945
  226. package/src/drafts/draft10/data-streams.ts +336 -332
  227. package/src/drafts/draft10/index.ts +10 -9
  228. package/src/drafts/draft10/messages.ts +59 -59
  229. package/src/drafts/draft10/rules.ts +73 -73
  230. package/src/drafts/draft10/session-fsm.ts +335 -303
  231. package/src/drafts/draft10/session.ts +6 -7
  232. package/src/drafts/draft10/types.ts +380 -384
  233. package/src/drafts/draft11/codec.ts +1054 -988
  234. package/src/drafts/draft11/data-streams.ts +316 -269
  235. package/src/drafts/draft11/index.ts +10 -9
  236. package/src/drafts/draft11/messages.ts +60 -59
  237. package/src/drafts/draft11/rules.ts +73 -73
  238. package/src/drafts/draft11/session-fsm.ts +359 -333
  239. package/src/drafts/draft11/session.ts +6 -7
  240. package/src/drafts/draft11/types.ts +385 -381
  241. package/src/drafts/draft12/codec.ts +1178 -1122
  242. package/src/drafts/draft12/data-streams.ts +324 -275
  243. package/src/drafts/draft12/index.ts +10 -9
  244. package/src/drafts/draft12/messages.ts +67 -66
  245. package/src/drafts/draft12/rules.ts +79 -79
  246. package/src/drafts/draft12/session-fsm.ts +384 -358
  247. package/src/drafts/draft12/session.ts +6 -7
  248. package/src/drafts/draft12/types.ts +424 -419
  249. package/src/drafts/draft13/codec.ts +1296 -1206
  250. package/src/drafts/draft13/data-streams.ts +326 -275
  251. package/src/drafts/draft13/index.ts +10 -9
  252. package/src/drafts/draft13/messages.ts +73 -68
  253. package/src/drafts/draft13/rules.ts +81 -81
  254. package/src/drafts/draft13/session-fsm.ts +392 -366
  255. package/src/drafts/draft13/session.ts +6 -7
  256. package/src/drafts/draft13/types.ts +447 -438
  257. package/src/drafts/draft14/codec.ts +1347 -1043
  258. package/src/drafts/draft14/data-streams.ts +831 -813
  259. package/src/drafts/draft14/index.ts +17 -9
  260. package/src/drafts/draft14/messages.ts +65 -65
  261. package/src/drafts/draft14/rules.ts +81 -81
  262. package/src/drafts/draft14/session-fsm.ts +415 -405
  263. package/src/drafts/draft14/session.ts +6 -7
  264. package/src/drafts/draft14/types.ts +451 -381
  265. package/src/drafts/draft15/codec.ts +1138 -978
  266. package/src/drafts/draft15/data-streams.ts +842 -794
  267. package/src/drafts/draft15/index.ts +10 -9
  268. package/src/drafts/draft15/messages.ts +54 -53
  269. package/src/drafts/draft15/rules.ts +67 -67
  270. package/src/drafts/draft15/session-fsm.ts +319 -299
  271. package/src/drafts/draft15/session.ts +6 -7
  272. package/src/drafts/draft15/types.ts +357 -339
  273. package/src/drafts/draft16/codec.ts +1242 -966
  274. package/src/drafts/draft16/data-streams.ts +835 -789
  275. package/src/drafts/draft16/index.ts +10 -9
  276. package/src/drafts/draft16/messages.ts +56 -55
  277. package/src/drafts/draft16/rules.ts +69 -69
  278. package/src/drafts/draft16/session-fsm.ts +319 -299
  279. package/src/drafts/draft16/session.ts +6 -7
  280. package/src/drafts/draft16/types.ts +386 -357
  281. package/src/drafts/draft17/codec.ts +1209 -971
  282. package/src/drafts/draft17/data-streams.ts +969 -758
  283. package/src/drafts/draft17/index.ts +9 -7
  284. package/src/drafts/draft17/messages.ts +43 -42
  285. package/src/drafts/draft17/rules.ts +58 -58
  286. package/src/drafts/draft17/session-fsm.ts +248 -216
  287. package/src/drafts/draft17/session.ts +5 -5
  288. package/src/drafts/draft17/types.ts +337 -313
  289. package/src/index.ts +85 -274
  290. package/src/session.ts +62 -23
  291. package/dist/chunk-FZDIEHQL.cjs +0 -1042
  292. package/dist/chunk-HDWJ2GDE.js +0 -24
  293. package/dist/chunk-KNDYS3DK.cjs +0 -24
  294. package/dist/chunk-N2KBF5Q2.js +0 -1042
  295. package/dist/types-QNXoxC9Y.d.cts +0 -236
  296. package/dist/types-QNXoxC9Y.d.ts +0 -236
  297. package/src/drafts/draft07/announce-fsm.ts +0 -2
  298. package/src/drafts/draft07/parameters.ts +0 -12
  299. package/src/drafts/draft07/subscription-fsm.ts +0 -3
@@ -1,1122 +1,1178 @@
1
- import { bytesToHex, hexToBytes } from "../../core/hex.js";
2
- import { BufferReader } from "../../core/buffer-reader.js";
3
- import { BufferWriter } from "../../core/buffer-writer.js";
4
- import type { BaseCodec, DecodeResult } from "../../core/types.js";
5
- import { DecodeError } from "../../core/types.js";
6
- import {
7
- MESSAGE_ID_MAP,
8
- MSG_ANNOUNCE,
9
- MSG_ANNOUNCE_CANCEL,
10
- MSG_ANNOUNCE_ERROR,
11
- MSG_ANNOUNCE_OK,
12
- MSG_CLIENT_SETUP,
13
- MSG_FETCH,
14
- MSG_FETCH_CANCEL,
15
- MSG_FETCH_ERROR,
16
- MSG_FETCH_OK,
17
- MSG_GOAWAY,
18
- MSG_MAX_REQUEST_ID,
19
- MSG_PUBLISH,
20
- MSG_PUBLISH_ERROR,
21
- MSG_PUBLISH_OK,
22
- MSG_REQUESTS_BLOCKED,
23
- MSG_SERVER_SETUP,
24
- MSG_SUBSCRIBE,
25
- MSG_SUBSCRIBE_ANNOUNCES,
26
- MSG_SUBSCRIBE_ANNOUNCES_ERROR,
27
- MSG_SUBSCRIBE_ANNOUNCES_OK,
28
- MSG_SUBSCRIBE_DONE,
29
- MSG_SUBSCRIBE_ERROR,
30
- MSG_SUBSCRIBE_OK,
31
- MSG_SUBSCRIBE_UPDATE,
32
- MSG_TRACK_STATUS,
33
- MSG_TRACK_STATUS_REQUEST,
34
- MSG_UNANNOUNCE,
35
- MSG_UNSUBSCRIBE,
36
- MSG_UNSUBSCRIBE_ANNOUNCES,
37
- PARAM_AUTHORIZATION_TOKEN,
38
- PARAM_DELIVERY_TIMEOUT,
39
- SETUP_PARAM_MAX_REQUEST_ID,
40
- SETUP_PARAM_PATH,
41
- } from "./messages.js";
42
- import type {
43
- DatagramObject,
44
- Draft12DataStream,
45
- Draft12Fetch,
46
- Draft12Message,
47
- Draft12Params,
48
- Draft12SetupParams,
49
- FetchObjectPayload,
50
- FetchStream,
51
- JoiningFetch,
52
- LargestLocation,
53
- ObjectPayload,
54
- StandaloneFetch,
55
- SubgroupStream,
56
- UnknownParam,
57
- } from "./types.js";
58
-
59
- const textEncoder = /* @__PURE__ */ new TextEncoder();
60
- const textDecoder = /* @__PURE__ */ new TextDecoder();
61
-
62
- // ─── Setup Parameter Encoding/Decoding (even/odd convention) ────────────────────
63
-
64
- function encodeSetupParams(params: Draft12SetupParams, w: BufferWriter): void {
65
- let count = 0;
66
- if (params.path !== undefined) count++;
67
- if (params.max_request_id !== undefined) count++;
68
- if (params.unknown) count += params.unknown.length;
69
-
70
- w.writeVarInt(count);
71
-
72
- if (params.path !== undefined) {
73
- w.writeVarInt(SETUP_PARAM_PATH);
74
- const encoded = textEncoder.encode(params.path);
75
- w.writeVarInt(encoded.byteLength);
76
- w.writeBytes(encoded);
77
- }
78
- if (params.max_request_id !== undefined) {
79
- w.writeVarInt(SETUP_PARAM_MAX_REQUEST_ID);
80
- w.writeVarInt(params.max_request_id);
81
- }
82
- if (params.unknown) {
83
- for (const u of params.unknown) {
84
- const id = BigInt(u.id);
85
- w.writeVarInt(id);
86
- if (id % 2n === 0n) {
87
- const raw = hexToBytes(u.raw_hex);
88
- const tmpReader = new BufferReader(raw);
89
- w.writeVarInt(tmpReader.readVarInt());
90
- } else {
91
- const raw = hexToBytes(u.raw_hex);
92
- w.writeVarInt(raw.byteLength);
93
- w.writeBytes(raw);
94
- }
95
- }
96
- }
97
- }
98
-
99
- function decodeSetupParams(r: BufferReader): Draft12SetupParams {
100
- const count = Number(r.readVarInt());
101
- const result: Draft12SetupParams = {};
102
- const unknown: UnknownParam[] = [];
103
-
104
- for (let i = 0; i < count; i++) {
105
- const paramType = r.readVarInt();
106
- if (paramType % 2n === 0n) {
107
- const value = r.readVarInt();
108
- if (paramType === SETUP_PARAM_MAX_REQUEST_ID) {
109
- result.max_request_id = value;
110
- } else {
111
- const tmpW = new BufferWriter(16);
112
- tmpW.writeVarInt(value);
113
- const raw = tmpW.finish();
114
- unknown.push({
115
- id: `0x${paramType.toString(16)}`,
116
- length: raw.byteLength,
117
- raw_hex: bytesToHex(raw),
118
- });
119
- }
120
- } else {
121
- const length = Number(r.readVarInt());
122
- const bytes = r.readBytes(length);
123
- if (paramType === SETUP_PARAM_PATH) {
124
- result.path = textDecoder.decode(bytes);
125
- } else {
126
- unknown.push({ id: `0x${paramType.toString(16)}`, length, raw_hex: bytesToHex(bytes) });
127
- }
128
- }
129
- }
130
-
131
- if (unknown.length > 0) result.unknown = unknown;
132
- return result;
133
- }
134
-
135
- // ─── Version-Specific Parameter Encoding/Decoding ───────────────────────────────
136
- // Uses even/odd convention: even type → bare varint value, odd type → length-prefixed blob
137
-
138
- function encodeParams(params: Draft12Params, w: BufferWriter): void {
139
- let count = params.unknown ? params.unknown.length : 0;
140
- if (params.authorization_token !== undefined) count++;
141
- if (params.delivery_timeout !== undefined) count++;
142
- w.writeVarInt(count);
143
-
144
- if (params.authorization_token !== undefined) {
145
- // AUTHORIZATION_TOKEN = 0x01 (odd → length-prefixed)
146
- w.writeVarInt(PARAM_AUTHORIZATION_TOKEN);
147
- const at = params.authorization_token;
148
- const tmpW = new BufferWriter(64);
149
- tmpW.writeVarInt(at.alias_type);
150
- tmpW.writeVarInt(at.token_type);
151
- const tokenBytes = textEncoder.encode(at.token_value);
152
- tmpW.writeBytes(tokenBytes);
153
- const raw = tmpW.finish();
154
- w.writeVarInt(raw.byteLength);
155
- w.writeBytes(raw);
156
- }
157
- if (params.delivery_timeout !== undefined) {
158
- // DELIVERY_TIMEOUT = 0x03 (oddlength-prefixed varint)
159
- w.writeVarInt(PARAM_DELIVERY_TIMEOUT);
160
- const tmpW = new BufferWriter(16);
161
- tmpW.writeVarInt(params.delivery_timeout);
162
- const raw = tmpW.finish();
163
- w.writeVarInt(raw.byteLength);
164
- w.writeBytes(raw);
165
- }
166
- if (params.unknown) {
167
- for (const u of params.unknown) {
168
- const id = BigInt(u.id);
169
- w.writeVarInt(id);
170
- if (id % 2n === 0n) {
171
- // Even bare varint
172
- const raw = hexToBytes(u.raw_hex);
173
- const tmpReader = new BufferReader(raw);
174
- w.writeVarInt(tmpReader.readVarInt());
175
- } else {
176
- // Oddlength-prefixed
177
- const raw = hexToBytes(u.raw_hex);
178
- w.writeVarInt(raw.byteLength);
179
- w.writeBytes(raw);
180
- }
181
- }
182
- }
183
- }
184
-
185
- function decodeParams(r: BufferReader): Draft12Params {
186
- const count = Number(r.readVarInt());
187
- const result: Draft12Params = {};
188
- const unknown: UnknownParam[] = [];
189
-
190
- for (let i = 0; i < count; i++) {
191
- const paramType = r.readVarInt();
192
-
193
- if (paramType % 2n === 0n) {
194
- // Even type → bare varint value
195
- const value = r.readVarInt();
196
- const tmpW = new BufferWriter(16);
197
- tmpW.writeVarInt(value);
198
- const raw = tmpW.finish();
199
- unknown.push({
200
- id: `0x${paramType.toString(16)}`,
201
- length: raw.byteLength,
202
- raw_hex: bytesToHex(raw),
203
- });
204
- } else {
205
- // Odd type → length-prefixed blob
206
- const length = Number(r.readVarInt());
207
- const startOff = r.offset;
208
-
209
- if (paramType === PARAM_AUTHORIZATION_TOKEN) {
210
- const alias_type = r.readVarInt();
211
- const token_type = r.readVarInt();
212
- const tokenBytesLen = length - (r.offset - startOff);
213
- const tokenBytes = r.readBytes(tokenBytesLen);
214
- result.authorization_token = {
215
- alias_type,
216
- token_type,
217
- token_value: textDecoder.decode(tokenBytes),
218
- };
219
- } else if (paramType === PARAM_DELIVERY_TIMEOUT) {
220
- const blob = r.readBytes(length);
221
- const tmpReader = new BufferReader(blob);
222
- result.delivery_timeout = tmpReader.readVarInt();
223
- } else {
224
- const bytes = r.readBytes(length);
225
- unknown.push({ id: `0x${paramType.toString(16)}`, length, raw_hex: bytesToHex(bytes) });
226
- }
227
- }
228
- }
229
-
230
- if (unknown.length > 0) result.unknown = unknown;
231
- return result;
232
- }
233
-
234
- // ─── Payload Encoders ──────────────────────────────────────────────────────────
235
-
236
- function encodeClientSetupPayload(
237
- msg: Draft12Message & { type: "client_setup" },
238
- w: BufferWriter,
239
- ): void {
240
- w.writeVarInt(msg.supported_versions.length);
241
- for (const v of msg.supported_versions) w.writeVarInt(v);
242
- encodeSetupParams(msg.parameters, w);
243
- }
244
-
245
- function encodeServerSetupPayload(
246
- msg: Draft12Message & { type: "server_setup" },
247
- w: BufferWriter,
248
- ): void {
249
- w.writeVarInt(msg.selected_version);
250
- encodeSetupParams(msg.parameters, w);
251
- }
252
-
253
- function encodeSubscribePayload(
254
- msg: Draft12Message & { type: "subscribe" },
255
- w: BufferWriter,
256
- ): void {
257
- w.writeVarInt(msg.request_id);
258
- // Draft-12: no track_alias in subscribe (moved to subscribe_ok)
259
- w.writeTuple(msg.track_namespace);
260
- w.writeString(msg.track_name);
261
- w.writeUint8(msg.subscriber_priority);
262
- w.writeVarInt(msg.group_order);
263
- w.writeVarInt(msg.forward);
264
- w.writeVarInt(msg.filter_type);
265
- const ft = Number(msg.filter_type);
266
- if (ft === 3 || ft === 4) {
267
- w.writeVarInt(msg.start_group!);
268
- w.writeVarInt(msg.start_object!);
269
- }
270
- if (ft === 4) {
271
- w.writeVarInt(msg.end_group!);
272
- }
273
- encodeParams(msg.parameters, w);
274
- }
275
-
276
- function encodeSubscribeOkPayload(
277
- msg: Draft12Message & { type: "subscribe_ok" },
278
- w: BufferWriter,
279
- ): void {
280
- w.writeVarInt(msg.request_id);
281
- w.writeVarInt(msg.track_alias);
282
- w.writeVarInt(msg.expires);
283
- w.writeVarInt(msg.group_order);
284
- w.writeVarInt(msg.content_exists);
285
- if (msg.content_exists === 1n && msg.largest_location) {
286
- w.writeVarInt(msg.largest_location.group);
287
- w.writeVarInt(msg.largest_location.object);
288
- }
289
- encodeParams(msg.parameters, w);
290
- }
291
-
292
- function encodeSubscribeErrorPayload(
293
- msg: Draft12Message & { type: "subscribe_error" },
294
- w: BufferWriter,
295
- ): void {
296
- w.writeVarInt(msg.request_id);
297
- w.writeVarInt(msg.error_code);
298
- w.writeString(msg.reason_phrase);
299
- // Draft-12: no track_alias in subscribe_error
300
- }
301
-
302
- function encodeSubscribeUpdatePayload(
303
- msg: Draft12Message & { type: "subscribe_update" },
304
- w: BufferWriter,
305
- ): void {
306
- w.writeVarInt(msg.request_id);
307
- w.writeVarInt(msg.start_group);
308
- w.writeVarInt(msg.start_object);
309
- w.writeVarInt(msg.end_group);
310
- w.writeUint8(msg.subscriber_priority);
311
- w.writeVarInt(msg.forward);
312
- encodeParams(msg.parameters, w);
313
- }
314
-
315
- function encodeSubscribeDonePayload(
316
- msg: Draft12Message & { type: "subscribe_done" },
317
- w: BufferWriter,
318
- ): void {
319
- w.writeVarInt(msg.request_id);
320
- w.writeVarInt(msg.status_code);
321
- w.writeVarInt(msg.stream_count);
322
- w.writeString(msg.reason_phrase);
323
- }
324
-
325
- function encodeUnsubscribePayload(
326
- msg: Draft12Message & { type: "unsubscribe" },
327
- w: BufferWriter,
328
- ): void {
329
- w.writeVarInt(msg.request_id);
330
- }
331
-
332
- function encodeAnnouncePayload(msg: Draft12Message & { type: "announce" }, w: BufferWriter): void {
333
- w.writeVarInt(msg.request_id);
334
- w.writeTuple(msg.track_namespace);
335
- encodeParams(msg.parameters, w);
336
- }
337
-
338
- function encodeAnnounceOkPayload(
339
- msg: Draft12Message & { type: "announce_ok" },
340
- w: BufferWriter,
341
- ): void {
342
- w.writeVarInt(msg.request_id);
343
- }
344
-
345
- function encodeAnnounceErrorPayload(
346
- msg: Draft12Message & { type: "announce_error" },
347
- w: BufferWriter,
348
- ): void {
349
- w.writeVarInt(msg.request_id);
350
- w.writeVarInt(msg.error_code);
351
- w.writeString(msg.reason_phrase);
352
- }
353
-
354
- function encodeUnannouncePayload(
355
- msg: Draft12Message & { type: "unannounce" },
356
- w: BufferWriter,
357
- ): void {
358
- w.writeTuple(msg.track_namespace);
359
- }
360
-
361
- function encodeAnnounceCancelPayload(
362
- msg: Draft12Message & { type: "announce_cancel" },
363
- w: BufferWriter,
364
- ): void {
365
- w.writeTuple(msg.track_namespace);
366
- w.writeVarInt(msg.error_code);
367
- w.writeString(msg.reason_phrase);
368
- }
369
-
370
- function encodeSubscribeAnnouncesPayload(
371
- msg: Draft12Message & { type: "subscribe_announces" },
372
- w: BufferWriter,
373
- ): void {
374
- w.writeVarInt(msg.request_id);
375
- w.writeTuple(msg.track_namespace_prefix);
376
- encodeParams(msg.parameters, w);
377
- }
378
-
379
- function encodeSubscribeAnnouncesOkPayload(
380
- msg: Draft12Message & { type: "subscribe_announces_ok" },
381
- w: BufferWriter,
382
- ): void {
383
- w.writeVarInt(msg.request_id);
384
- }
385
-
386
- function encodeSubscribeAnnouncesErrorPayload(
387
- msg: Draft12Message & { type: "subscribe_announces_error" },
388
- w: BufferWriter,
389
- ): void {
390
- w.writeVarInt(msg.request_id);
391
- w.writeVarInt(msg.error_code);
392
- w.writeString(msg.reason_phrase);
393
- }
394
-
395
- function encodeUnsubscribeAnnouncesPayload(
396
- msg: Draft12Message & { type: "unsubscribe_announces" },
397
- w: BufferWriter,
398
- ): void {
399
- w.writeTuple(msg.track_namespace_prefix);
400
- }
401
-
402
- function encodePublishPayload(msg: Draft12Message & { type: "publish" }, w: BufferWriter): void {
403
- w.writeVarInt(msg.request_id);
404
- w.writeTuple(msg.track_namespace);
405
- w.writeString(msg.track_name);
406
- w.writeVarInt(msg.track_alias);
407
- w.writeVarInt(msg.group_order);
408
- w.writeVarInt(msg.content_exists);
409
- if (msg.content_exists === 1n && msg.largest_location) {
410
- w.writeVarInt(msg.largest_location.group);
411
- w.writeVarInt(msg.largest_location.object);
412
- }
413
- w.writeVarInt(msg.forward);
414
- encodeParams(msg.parameters, w);
415
- }
416
-
417
- function encodePublishOkPayload(
418
- msg: Draft12Message & { type: "publish_ok" },
419
- w: BufferWriter,
420
- ): void {
421
- w.writeVarInt(msg.request_id);
422
- w.writeVarInt(msg.forward);
423
- w.writeUint8(msg.subscriber_priority);
424
- w.writeVarInt(msg.group_order);
425
- w.writeVarInt(msg.filter_type);
426
- const ft = Number(msg.filter_type);
427
- if (ft === 3 || ft === 4) {
428
- w.writeVarInt(msg.start_group!);
429
- w.writeVarInt(msg.start_object!);
430
- }
431
- if (ft === 4) {
432
- w.writeVarInt(msg.end_group!);
433
- }
434
- encodeParams(msg.parameters, w);
435
- }
436
-
437
- function encodePublishErrorPayload(
438
- msg: Draft12Message & { type: "publish_error" },
439
- w: BufferWriter,
440
- ): void {
441
- w.writeVarInt(msg.request_id);
442
- w.writeVarInt(msg.error_code);
443
- w.writeString(msg.reason_phrase);
444
- }
445
-
446
- function encodeFetchPayload(msg: Draft12Message & { type: "fetch" }, w: BufferWriter): void {
447
- w.writeVarInt(msg.request_id);
448
- w.writeUint8(msg.subscriber_priority);
449
- w.writeVarInt(msg.group_order);
450
- w.writeVarInt(msg.fetch_type);
451
- const ft = Number(msg.fetch_type);
452
- if (ft === 1 && msg.standalone) {
453
- w.writeTuple(msg.standalone.track_namespace);
454
- w.writeString(msg.standalone.track_name);
455
- w.writeVarInt(msg.standalone.start_group);
456
- w.writeVarInt(msg.standalone.start_object);
457
- w.writeVarInt(msg.standalone.end_group);
458
- w.writeVarInt(msg.standalone.end_object);
459
- } else if ((ft === 2 || ft === 3) && msg.joining) {
460
- w.writeVarInt(msg.joining.joining_subscribe_id);
461
- w.writeVarInt(msg.joining.joining_start);
462
- }
463
- encodeParams(msg.parameters, w);
464
- }
465
-
466
- function encodeFetchOkPayload(msg: Draft12Message & { type: "fetch_ok" }, w: BufferWriter): void {
467
- w.writeVarInt(msg.request_id);
468
- w.writeVarInt(msg.group_order);
469
- w.writeVarInt(msg.end_of_track);
470
- w.writeVarInt(msg.end_location.group);
471
- w.writeVarInt(msg.end_location.object);
472
- encodeParams(msg.parameters, w);
473
- }
474
-
475
- function encodeFetchErrorPayload(
476
- msg: Draft12Message & { type: "fetch_error" },
477
- w: BufferWriter,
478
- ): void {
479
- w.writeVarInt(msg.request_id);
480
- w.writeVarInt(msg.error_code);
481
- w.writeString(msg.reason_phrase);
482
- }
483
-
484
- function encodeFetchCancelPayload(
485
- msg: Draft12Message & { type: "fetch_cancel" },
486
- w: BufferWriter,
487
- ): void {
488
- w.writeVarInt(msg.request_id);
489
- }
490
-
491
- function encodeTrackStatusRequestPayload(
492
- msg: Draft12Message & { type: "track_status_request" },
493
- w: BufferWriter,
494
- ): void {
495
- w.writeVarInt(msg.request_id);
496
- w.writeTuple(msg.track_namespace);
497
- w.writeString(msg.track_name);
498
- encodeParams(msg.parameters, w);
499
- }
500
-
501
- function encodeTrackStatusPayload(
502
- msg: Draft12Message & { type: "track_status" },
503
- w: BufferWriter,
504
- ): void {
505
- w.writeVarInt(msg.request_id);
506
- w.writeVarInt(msg.status_code);
507
- w.writeVarInt(msg.largest_location.group);
508
- w.writeVarInt(msg.largest_location.object);
509
- encodeParams(msg.parameters, w);
510
- }
511
-
512
- function encodeGoAwayPayload(msg: Draft12Message & { type: "goaway" }, w: BufferWriter): void {
513
- w.writeString(msg.new_session_uri);
514
- }
515
-
516
- function encodeMaxRequestIdPayload(
517
- msg: Draft12Message & { type: "max_request_id" },
518
- w: BufferWriter,
519
- ): void {
520
- w.writeVarInt(msg.request_id);
521
- }
522
-
523
- function encodeRequestsBlockedPayload(
524
- msg: Draft12Message & { type: "requests_blocked" },
525
- w: BufferWriter,
526
- ): void {
527
- w.writeVarInt(msg.maximum_request_id);
528
- }
529
-
530
- // ─── Payload Decoders ──────────────────────────────────────────────────────────
531
-
532
- function decodeClientSetupPayload(r: BufferReader): Draft12Message {
533
- const numVersions = Number(r.readVarInt());
534
- if (numVersions === 0) {
535
- throw new DecodeError("CONSTRAINT_VIOLATION", "supported_versions must not be empty", r.offset);
536
- }
537
- const supported_versions: bigint[] = [];
538
- for (let i = 0; i < numVersions; i++) supported_versions.push(r.readVarInt());
539
- const parameters = decodeSetupParams(r);
540
- return { type: "client_setup", supported_versions, parameters };
541
- }
542
-
543
- function decodeServerSetupPayload(r: BufferReader): Draft12Message {
544
- const selected_version = r.readVarInt();
545
- const parameters = decodeSetupParams(r);
546
- return { type: "server_setup", selected_version, parameters };
547
- }
548
-
549
- function decodeSubscribePayload(r: BufferReader): Draft12Message {
550
- const request_id = r.readVarInt();
551
- // Draft-12: no track_alias in subscribe
552
- const track_namespace = r.readTuple();
553
- const track_name = r.readString();
554
- const subscriber_priority = r.readUint8();
555
- const group_order = r.readVarInt();
556
- const forward = r.readVarInt();
557
- const filter_type = r.readVarInt();
558
- const ft = Number(filter_type);
559
- if (ft < 1 || ft > 4) {
560
- throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid filter_type: ${ft}`, r.offset);
561
- }
562
- let start_group: bigint | undefined;
563
- let start_object: bigint | undefined;
564
- let end_group: bigint | undefined;
565
- if (ft === 3 || ft === 4) {
566
- start_group = r.readVarInt();
567
- start_object = r.readVarInt();
568
- }
569
- if (ft === 4) {
570
- end_group = r.readVarInt();
571
- }
572
- const parameters = decodeParams(r);
573
- const msg: Record<string, unknown> = {
574
- type: "subscribe",
575
- request_id,
576
- track_namespace,
577
- track_name,
578
- subscriber_priority,
579
- group_order,
580
- forward,
581
- filter_type,
582
- parameters,
583
- };
584
- if (start_group !== undefined) msg.start_group = start_group;
585
- if (start_object !== undefined) msg.start_object = start_object;
586
- if (end_group !== undefined) msg.end_group = end_group;
587
- return msg as unknown as Draft12Message;
588
- }
589
-
590
- function decodeSubscribeOkPayload(r: BufferReader): Draft12Message {
591
- const request_id = r.readVarInt();
592
- const track_alias = r.readVarInt();
593
- const expires = r.readVarInt();
594
- const group_order = r.readVarInt();
595
- const content_exists = r.readVarInt();
596
- let largest_location: LargestLocation | undefined;
597
- if (content_exists === 1n) {
598
- const group = r.readVarInt();
599
- const object = r.readVarInt();
600
- largest_location = { group, object };
601
- }
602
- const parameters = decodeParams(r);
603
- const msg: Record<string, unknown> = {
604
- type: "subscribe_ok",
605
- request_id,
606
- track_alias,
607
- expires,
608
- group_order,
609
- content_exists,
610
- parameters,
611
- };
612
- if (largest_location) msg.largest_location = largest_location;
613
- return msg as unknown as Draft12Message;
614
- }
615
-
616
- function decodeSubscribeErrorPayload(r: BufferReader): Draft12Message {
617
- const request_id = r.readVarInt();
618
- const error_code = r.readVarInt();
619
- const reason_phrase = r.readString();
620
- // Draft-12: no track_alias in subscribe_error
621
- return { type: "subscribe_error", request_id, error_code, reason_phrase };
622
- }
623
-
624
- function decodeSubscribeUpdatePayload(r: BufferReader): Draft12Message {
625
- const request_id = r.readVarInt();
626
- const start_group = r.readVarInt();
627
- const start_object = r.readVarInt();
628
- const end_group = r.readVarInt();
629
- const subscriber_priority = r.readUint8();
630
- const forward = r.readVarInt();
631
- const parameters = decodeParams(r);
632
- return {
633
- type: "subscribe_update",
634
- request_id,
635
- start_group,
636
- start_object,
637
- end_group,
638
- subscriber_priority,
639
- forward,
640
- parameters,
641
- };
642
- }
643
-
644
- function decodeSubscribeDonePayload(r: BufferReader): Draft12Message {
645
- const request_id = r.readVarInt();
646
- const status_code = r.readVarInt();
647
- const stream_count = r.readVarInt();
648
- const reason_phrase = r.readString();
649
- return { type: "subscribe_done", request_id, status_code, stream_count, reason_phrase };
650
- }
651
-
652
- function decodeUnsubscribePayload(r: BufferReader): Draft12Message {
653
- const request_id = r.readVarInt();
654
- return { type: "unsubscribe", request_id };
655
- }
656
-
657
- function decodeAnnouncePayload(r: BufferReader): Draft12Message {
658
- const request_id = r.readVarInt();
659
- const track_namespace = r.readTuple();
660
- const parameters = decodeParams(r);
661
- return { type: "announce", request_id, track_namespace, parameters };
662
- }
663
-
664
- function decodeAnnounceOkPayload(r: BufferReader): Draft12Message {
665
- const request_id = r.readVarInt();
666
- return { type: "announce_ok", request_id };
667
- }
668
-
669
- function decodeAnnounceErrorPayload(r: BufferReader): Draft12Message {
670
- const request_id = r.readVarInt();
671
- const error_code = r.readVarInt();
672
- const reason_phrase = r.readString();
673
- return { type: "announce_error", request_id, error_code, reason_phrase };
674
- }
675
-
676
- function decodeUnannouncePayload(r: BufferReader): Draft12Message {
677
- const track_namespace = r.readTuple();
678
- return { type: "unannounce", track_namespace };
679
- }
680
-
681
- function decodeAnnounceCancelPayload(r: BufferReader): Draft12Message {
682
- const track_namespace = r.readTuple();
683
- const error_code = r.readVarInt();
684
- const reason_phrase = r.readString();
685
- return { type: "announce_cancel", track_namespace, error_code, reason_phrase };
686
- }
687
-
688
- function decodeSubscribeAnnouncesPayload(r: BufferReader): Draft12Message {
689
- const request_id = r.readVarInt();
690
- const track_namespace_prefix = r.readTuple();
691
- const parameters = decodeParams(r);
692
- return { type: "subscribe_announces", request_id, track_namespace_prefix, parameters };
693
- }
694
-
695
- function decodeSubscribeAnnouncesOkPayload(r: BufferReader): Draft12Message {
696
- const request_id = r.readVarInt();
697
- return { type: "subscribe_announces_ok", request_id };
698
- }
699
-
700
- function decodeSubscribeAnnouncesErrorPayload(r: BufferReader): Draft12Message {
701
- const request_id = r.readVarInt();
702
- const error_code = r.readVarInt();
703
- const reason_phrase = r.readString();
704
- return { type: "subscribe_announces_error", request_id, error_code, reason_phrase };
705
- }
706
-
707
- function decodeUnsubscribeAnnouncesPayload(r: BufferReader): Draft12Message {
708
- const track_namespace_prefix = r.readTuple();
709
- return { type: "unsubscribe_announces", track_namespace_prefix };
710
- }
711
-
712
- function decodePublishPayload(r: BufferReader): Draft12Message {
713
- const request_id = r.readVarInt();
714
- const track_namespace = r.readTuple();
715
- const track_name = r.readString();
716
- const track_alias = r.readVarInt();
717
- const group_order = r.readVarInt();
718
- const content_exists = r.readVarInt();
719
- let largest_location: LargestLocation | undefined;
720
- if (content_exists === 1n) {
721
- const group = r.readVarInt();
722
- const object = r.readVarInt();
723
- largest_location = { group, object };
724
- }
725
- const forward = r.readVarInt();
726
- const parameters = decodeParams(r);
727
- const msg: Record<string, unknown> = {
728
- type: "publish",
729
- request_id,
730
- track_namespace,
731
- track_name,
732
- track_alias,
733
- group_order,
734
- content_exists,
735
- forward,
736
- parameters,
737
- };
738
- if (largest_location) msg.largest_location = largest_location;
739
- return msg as unknown as Draft12Message;
740
- }
741
-
742
- function decodePublishOkPayload(r: BufferReader): Draft12Message {
743
- const request_id = r.readVarInt();
744
- const forward = r.readVarInt();
745
- const subscriber_priority = r.readUint8();
746
- const group_order = r.readVarInt();
747
- const filter_type = r.readVarInt();
748
- const ft = Number(filter_type);
749
- let start_group: bigint | undefined;
750
- let start_object: bigint | undefined;
751
- let end_group: bigint | undefined;
752
- if (ft === 3 || ft === 4) {
753
- start_group = r.readVarInt();
754
- start_object = r.readVarInt();
755
- }
756
- if (ft === 4) {
757
- end_group = r.readVarInt();
758
- }
759
- const parameters = decodeParams(r);
760
- const msg: Record<string, unknown> = {
761
- type: "publish_ok",
762
- request_id,
763
- forward,
764
- subscriber_priority,
765
- group_order,
766
- filter_type,
767
- parameters,
768
- };
769
- if (start_group !== undefined) msg.start_group = start_group;
770
- if (start_object !== undefined) msg.start_object = start_object;
771
- if (end_group !== undefined) msg.end_group = end_group;
772
- return msg as unknown as Draft12Message;
773
- }
774
-
775
- function decodePublishErrorPayload(r: BufferReader): Draft12Message {
776
- const request_id = r.readVarInt();
777
- const error_code = r.readVarInt();
778
- const reason_phrase = r.readString();
779
- return { type: "publish_error", request_id, error_code, reason_phrase };
780
- }
781
-
782
- function decodeFetchPayload(r: BufferReader): Draft12Message {
783
- const request_id = r.readVarInt();
784
- const subscriber_priority = r.readUint8();
785
- const group_order = r.readVarInt();
786
- const fetch_type = r.readVarInt();
787
- const ft = Number(fetch_type);
788
-
789
- if (ft < 1 || ft > 3) {
790
- throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid fetch_type: ${ft}`, r.offset);
791
- }
792
-
793
- let standalone: StandaloneFetch | undefined;
794
- let joining: JoiningFetch | undefined;
795
-
796
- if (ft === 1) {
797
- const track_namespace = r.readTuple();
798
- const track_name = r.readString();
799
- const start_group = r.readVarInt();
800
- const start_object = r.readVarInt();
801
- const end_group = r.readVarInt();
802
- const end_object = r.readVarInt();
803
- standalone = { track_namespace, track_name, start_group, start_object, end_group, end_object };
804
- } else {
805
- const joining_subscribe_id = r.readVarInt();
806
- const joining_start = r.readVarInt();
807
- joining = { joining_subscribe_id, joining_start };
808
- }
809
-
810
- const parameters = decodeParams(r);
811
- return {
812
- type: "fetch",
813
- request_id,
814
- subscriber_priority,
815
- group_order,
816
- fetch_type,
817
- standalone,
818
- joining,
819
- parameters,
820
- } as Draft12Fetch;
821
- }
822
-
823
- function decodeFetchOkPayload(r: BufferReader): Draft12Message {
824
- const request_id = r.readVarInt();
825
- const group_order = r.readVarInt();
826
- const end_of_track = r.readVarInt();
827
- const group = r.readVarInt();
828
- const object = r.readVarInt();
829
- const parameters = decodeParams(r);
830
- return {
831
- type: "fetch_ok",
832
- request_id,
833
- group_order,
834
- end_of_track,
835
- end_location: { group, object },
836
- parameters,
837
- };
838
- }
839
-
840
- function decodeFetchErrorPayload(r: BufferReader): Draft12Message {
841
- const request_id = r.readVarInt();
842
- const error_code = r.readVarInt();
843
- const reason_phrase = r.readString();
844
- return { type: "fetch_error", request_id, error_code, reason_phrase };
845
- }
846
-
847
- function decodeFetchCancelPayload(r: BufferReader): Draft12Message {
848
- const request_id = r.readVarInt();
849
- return { type: "fetch_cancel", request_id };
850
- }
851
-
852
- function decodeTrackStatusRequestPayload(r: BufferReader): Draft12Message {
853
- const request_id = r.readVarInt();
854
- const track_namespace = r.readTuple();
855
- const track_name = r.readString();
856
- const parameters = decodeParams(r);
857
- return { type: "track_status_request", request_id, track_namespace, track_name, parameters };
858
- }
859
-
860
- function decodeTrackStatusPayload(r: BufferReader): Draft12Message {
861
- const request_id = r.readVarInt();
862
- const status_code = r.readVarInt();
863
- const group = r.readVarInt();
864
- const object = r.readVarInt();
865
- const parameters = decodeParams(r);
866
- return {
867
- type: "track_status",
868
- request_id,
869
- status_code,
870
- largest_location: { group, object },
871
- parameters,
872
- };
873
- }
874
-
875
- function decodeGoAwayPayload(r: BufferReader): Draft12Message {
876
- const new_session_uri = r.readString();
877
- return { type: "goaway", new_session_uri };
878
- }
879
-
880
- function decodeMaxRequestIdPayload(r: BufferReader): Draft12Message {
881
- const request_id = r.readVarInt();
882
- return { type: "max_request_id", request_id };
883
- }
884
-
885
- function decodeRequestsBlockedPayload(r: BufferReader): Draft12Message {
886
- const maximum_request_id = r.readVarInt();
887
- return { type: "requests_blocked", maximum_request_id };
888
- }
889
-
890
- // ─── Payload dispatch tables ───────────────────────────────────────────────────
891
-
892
- const payloadDecoders: ReadonlyMap<bigint, (r: BufferReader) => Draft12Message> = new Map([
893
- [MSG_CLIENT_SETUP, decodeClientSetupPayload],
894
- [MSG_SERVER_SETUP, decodeServerSetupPayload],
895
- [MSG_SUBSCRIBE, decodeSubscribePayload],
896
- [MSG_SUBSCRIBE_OK, decodeSubscribeOkPayload],
897
- [MSG_SUBSCRIBE_ERROR, decodeSubscribeErrorPayload],
898
- [MSG_SUBSCRIBE_UPDATE, decodeSubscribeUpdatePayload],
899
- [MSG_SUBSCRIBE_DONE, decodeSubscribeDonePayload],
900
- [MSG_UNSUBSCRIBE, decodeUnsubscribePayload],
901
- [MSG_ANNOUNCE, decodeAnnouncePayload],
902
- [MSG_ANNOUNCE_OK, decodeAnnounceOkPayload],
903
- [MSG_ANNOUNCE_ERROR, decodeAnnounceErrorPayload],
904
- [MSG_UNANNOUNCE, decodeUnannouncePayload],
905
- [MSG_ANNOUNCE_CANCEL, decodeAnnounceCancelPayload],
906
- [MSG_SUBSCRIBE_ANNOUNCES, decodeSubscribeAnnouncesPayload],
907
- [MSG_SUBSCRIBE_ANNOUNCES_OK, decodeSubscribeAnnouncesOkPayload],
908
- [MSG_SUBSCRIBE_ANNOUNCES_ERROR, decodeSubscribeAnnouncesErrorPayload],
909
- [MSG_UNSUBSCRIBE_ANNOUNCES, decodeUnsubscribeAnnouncesPayload],
910
- [MSG_PUBLISH, decodePublishPayload],
911
- [MSG_PUBLISH_OK, decodePublishOkPayload],
912
- [MSG_PUBLISH_ERROR, decodePublishErrorPayload],
913
- [MSG_FETCH, decodeFetchPayload],
914
- [MSG_FETCH_OK, decodeFetchOkPayload],
915
- [MSG_FETCH_ERROR, decodeFetchErrorPayload],
916
- [MSG_FETCH_CANCEL, decodeFetchCancelPayload],
917
- [MSG_TRACK_STATUS_REQUEST, decodeTrackStatusRequestPayload],
918
- [MSG_TRACK_STATUS, decodeTrackStatusPayload],
919
- [MSG_GOAWAY, decodeGoAwayPayload],
920
- [MSG_MAX_REQUEST_ID, decodeMaxRequestIdPayload],
921
- [MSG_REQUESTS_BLOCKED, decodeRequestsBlockedPayload],
922
- ]);
923
-
924
- // ─── Public API ────────────────────────────────────────────────────────────────
925
-
926
- /**
927
- * Encode a draft-12 control message.
928
- * Most messages use type(varint) + length(uint16 BE) + payload.
929
- * PUBLISH family uses type(varint) + length(varint) + payload.
930
- */
931
- export function encodeMessage(message: Draft12Message): Uint8Array {
932
- const typeId = MESSAGE_ID_MAP.get(message.type);
933
- if (typeId === undefined) throw new Error(`Unknown message type: ${message.type}`);
934
-
935
- const payloadWriter = new BufferWriter();
936
- encodePayload(message, payloadWriter);
937
- const payload = payloadWriter.finishView();
938
-
939
- const writer = new BufferWriter(payload.byteLength + 16);
940
- writer.writeVarInt(typeId);
941
-
942
- if (payload.byteLength > 0xffff) {
943
- throw new Error(`Payload too large for 16-bit length: ${payload.byteLength}`);
944
- }
945
- writer.writeUint8((payload.byteLength >> 8) & 0xff);
946
- writer.writeUint8(payload.byteLength & 0xff);
947
-
948
- writer.writeBytes(payload);
949
- return writer.finish();
950
- }
951
-
952
- function encodePayload(msg: Draft12Message, w: BufferWriter): void {
953
- switch (msg.type) {
954
- case "client_setup":
955
- return encodeClientSetupPayload(msg, w);
956
- case "server_setup":
957
- return encodeServerSetupPayload(msg, w);
958
- case "subscribe":
959
- return encodeSubscribePayload(msg, w);
960
- case "subscribe_ok":
961
- return encodeSubscribeOkPayload(msg, w);
962
- case "subscribe_error":
963
- return encodeSubscribeErrorPayload(msg, w);
964
- case "subscribe_update":
965
- return encodeSubscribeUpdatePayload(msg, w);
966
- case "subscribe_done":
967
- return encodeSubscribeDonePayload(msg, w);
968
- case "unsubscribe":
969
- return encodeUnsubscribePayload(msg, w);
970
- case "announce":
971
- return encodeAnnouncePayload(msg, w);
972
- case "announce_ok":
973
- return encodeAnnounceOkPayload(msg, w);
974
- case "announce_error":
975
- return encodeAnnounceErrorPayload(msg, w);
976
- case "unannounce":
977
- return encodeUnannouncePayload(msg, w);
978
- case "announce_cancel":
979
- return encodeAnnounceCancelPayload(msg, w);
980
- case "subscribe_announces":
981
- return encodeSubscribeAnnouncesPayload(msg, w);
982
- case "subscribe_announces_ok":
983
- return encodeSubscribeAnnouncesOkPayload(msg, w);
984
- case "subscribe_announces_error":
985
- return encodeSubscribeAnnouncesErrorPayload(msg, w);
986
- case "unsubscribe_announces":
987
- return encodeUnsubscribeAnnouncesPayload(msg, w);
988
- case "publish":
989
- return encodePublishPayload(msg, w);
990
- case "publish_ok":
991
- return encodePublishOkPayload(msg, w);
992
- case "publish_error":
993
- return encodePublishErrorPayload(msg, w);
994
- case "fetch":
995
- return encodeFetchPayload(msg, w);
996
- case "fetch_ok":
997
- return encodeFetchOkPayload(msg, w);
998
- case "fetch_error":
999
- return encodeFetchErrorPayload(msg, w);
1000
- case "fetch_cancel":
1001
- return encodeFetchCancelPayload(msg, w);
1002
- case "track_status_request":
1003
- return encodeTrackStatusRequestPayload(msg, w);
1004
- case "track_status":
1005
- return encodeTrackStatusPayload(msg, w);
1006
- case "goaway":
1007
- return encodeGoAwayPayload(msg, w);
1008
- case "max_request_id":
1009
- return encodeMaxRequestIdPayload(msg, w);
1010
- case "requests_blocked":
1011
- return encodeRequestsBlockedPayload(msg, w);
1012
- default: {
1013
- const _exhaustive: never = msg;
1014
- throw new Error(`Unhandled message type: ${(_exhaustive as Draft12Message).type}`);
1015
- }
1016
- }
1017
- }
1018
-
1019
- /**
1020
- * Decode a draft-12 control message from bytes.
1021
- */
1022
- export function decodeMessage(bytes: Uint8Array): DecodeResult<Draft12Message> {
1023
- try {
1024
- const reader = new BufferReader(bytes);
1025
- const typeId = reader.readVarInt();
1026
-
1027
- // Read 16-bit big-endian payload length
1028
- const lenHi = reader.readUint8();
1029
- const lenLo = reader.readUint8();
1030
- const payloadLength = (lenHi << 8) | lenLo;
1031
-
1032
- const payloadBytes = reader.readBytes(payloadLength);
1033
- const payloadReader = new BufferReader(payloadBytes);
1034
-
1035
- const decoder = payloadDecoders.get(typeId);
1036
- if (!decoder) {
1037
- return {
1038
- ok: false,
1039
- error: new DecodeError(
1040
- "UNKNOWN_MESSAGE_TYPE",
1041
- `Unknown message type ID: 0x${typeId.toString(16)}`,
1042
- 0,
1043
- ),
1044
- };
1045
- }
1046
-
1047
- const message = decoder(payloadReader);
1048
- return { ok: true, value: message, bytesRead: reader.offset };
1049
- } catch (e) {
1050
- if (e instanceof DecodeError) return { ok: false, error: e };
1051
- throw e;
1052
- }
1053
- }
1054
-
1055
- // ─── Data Stream Encoding/Decoding ─────────────────────────────────────────────
1056
-
1057
- export { encodeSubgroupStream, encodeDatagram, encodeFetchStream, decodeSubgroupStream, decodeDatagram, decodeFetchStream, decodeDataStream } from "./data-streams.js";
1058
- import { encodeSubgroupStream, encodeDatagram, encodeFetchStream, decodeSubgroupStream, decodeDatagram, decodeFetchStream, decodeDataStream } from "./data-streams.js";
1059
-
1060
- export function createStreamDecoder(): TransformStream<Uint8Array, Draft12Message> {
1061
- let buffer = new Uint8Array(0);
1062
- let offset = 0;
1063
- return new TransformStream<Uint8Array, Draft12Message>({
1064
- transform(chunk, controller) {
1065
- if (offset > 0) {
1066
- buffer = buffer.subarray(offset);
1067
- offset = 0;
1068
- }
1069
- const newBuffer = new Uint8Array(buffer.length + chunk.length);
1070
- newBuffer.set(buffer, 0);
1071
- newBuffer.set(chunk, buffer.length);
1072
- buffer = newBuffer;
1073
- while (offset < buffer.length) {
1074
- const result = decodeMessage(buffer.subarray(offset));
1075
- if (!result.ok) {
1076
- if (result.error.code === "UNEXPECTED_END") break;
1077
- controller.error(result.error);
1078
- return;
1079
- }
1080
- controller.enqueue(result.value);
1081
- offset += result.bytesRead;
1082
- }
1083
- },
1084
- flush(controller) {
1085
- if (offset < buffer.length)
1086
- controller.error(new DecodeError("UNEXPECTED_END", "Stream ended with incomplete data", 0));
1087
- },
1088
- });
1089
- }
1090
-
1091
- // ─── Codec Factory ─────────────────────────────────────────────────────────────
1092
-
1093
- export interface Draft12Codec extends BaseCodec<Draft12Message> {
1094
- readonly draft: "draft-ietf-moq-transport-12";
1095
- encodeSubgroupStream(stream: SubgroupStream): Uint8Array;
1096
- encodeDatagram(dg: DatagramObject): Uint8Array;
1097
- encodeFetchStream(stream: FetchStream): Uint8Array;
1098
- decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream>;
1099
- decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject>;
1100
- decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream>;
1101
- decodeDataStream(
1102
- streamType: "subgroup" | "datagram" | "fetch",
1103
- bytes: Uint8Array,
1104
- ): DecodeResult<Draft12DataStream>;
1105
- createStreamDecoder(): TransformStream<Uint8Array, Draft12Message>;
1106
- }
1107
-
1108
- export function createDraft12Codec(): Draft12Codec {
1109
- return {
1110
- draft: "draft-ietf-moq-transport-12",
1111
- encodeMessage,
1112
- decodeMessage,
1113
- encodeSubgroupStream,
1114
- encodeDatagram,
1115
- encodeFetchStream,
1116
- decodeSubgroupStream,
1117
- decodeDatagram,
1118
- decodeFetchStream,
1119
- decodeDataStream,
1120
- createStreamDecoder,
1121
- };
1122
- }
1
+ import { BufferReader } from '../../core/buffer-reader.js'
2
+ import { BufferWriter } from '../../core/buffer-writer.js'
3
+ import { bytesToHex, hexToBytes } from '../../core/hex.js'
4
+ import type { BaseCodec, DecodeResult } from '../../core/types.js'
5
+ import { DecodeError } from '../../core/types.js'
6
+ import {
7
+ decodeDatagram,
8
+ decodeDataStream,
9
+ decodeFetchStream,
10
+ decodeSubgroupStream,
11
+ encodeDatagram,
12
+ encodeFetchStream,
13
+ encodeSubgroupStream,
14
+ } from './data-streams.js'
15
+ import {
16
+ MESSAGE_ID_MAP,
17
+ MSG_ANNOUNCE,
18
+ MSG_ANNOUNCE_CANCEL,
19
+ MSG_ANNOUNCE_ERROR,
20
+ MSG_ANNOUNCE_OK,
21
+ MSG_CLIENT_SETUP,
22
+ MSG_FETCH,
23
+ MSG_FETCH_CANCEL,
24
+ MSG_FETCH_ERROR,
25
+ MSG_FETCH_OK,
26
+ MSG_GOAWAY,
27
+ MSG_MAX_REQUEST_ID,
28
+ MSG_PUBLISH,
29
+ MSG_PUBLISH_ERROR,
30
+ MSG_PUBLISH_OK,
31
+ MSG_REQUESTS_BLOCKED,
32
+ MSG_SERVER_SETUP,
33
+ MSG_SUBSCRIBE,
34
+ MSG_SUBSCRIBE_ANNOUNCES,
35
+ MSG_SUBSCRIBE_ANNOUNCES_ERROR,
36
+ MSG_SUBSCRIBE_ANNOUNCES_OK,
37
+ MSG_SUBSCRIBE_DONE,
38
+ MSG_SUBSCRIBE_ERROR,
39
+ MSG_SUBSCRIBE_OK,
40
+ MSG_SUBSCRIBE_UPDATE,
41
+ MSG_TRACK_STATUS,
42
+ MSG_TRACK_STATUS_REQUEST,
43
+ MSG_UNANNOUNCE,
44
+ MSG_UNSUBSCRIBE,
45
+ MSG_UNSUBSCRIBE_ANNOUNCES,
46
+ PARAM_AUTHORIZATION_TOKEN,
47
+ PARAM_DELIVERY_TIMEOUT,
48
+ PARAM_MAX_CACHE_DURATION,
49
+ SETUP_PARAM_MAX_REQUEST_ID,
50
+ SETUP_PARAM_PATH,
51
+ } from './messages.js'
52
+ import type {
53
+ DatagramObject,
54
+ Draft12DataStream,
55
+ Draft12Fetch,
56
+ Draft12Message,
57
+ Draft12Params,
58
+ Draft12SetupParams,
59
+ FetchStream,
60
+ JoiningFetch,
61
+ LargestLocation,
62
+ StandaloneFetch,
63
+ SubgroupStream,
64
+ UnknownParam,
65
+ } from './types.js'
66
+
67
+ const textEncoder = /* @__PURE__ */ new TextEncoder()
68
+ const textDecoder = /* @__PURE__ */ new TextDecoder()
69
+
70
+ // ─── Setup Parameter Encoding/Decoding (even/odd convention) ────────────────────
71
+
72
+ function encodeSetupParams(params: Draft12SetupParams, w: BufferWriter): void {
73
+ let count = 0
74
+ if (params.path !== undefined) count++
75
+ if (params.max_request_id !== undefined) count++
76
+ if (params.unknown) count += params.unknown.length
77
+
78
+ w.writeVarInt(count)
79
+
80
+ if (params.path !== undefined) {
81
+ w.writeVarInt(SETUP_PARAM_PATH)
82
+ const encoded = textEncoder.encode(params.path)
83
+ w.writeVarInt(encoded.byteLength)
84
+ w.writeBytes(encoded)
85
+ }
86
+ if (params.max_request_id !== undefined) {
87
+ w.writeVarInt(SETUP_PARAM_MAX_REQUEST_ID)
88
+ w.writeVarInt(params.max_request_id)
89
+ }
90
+ if (params.unknown) {
91
+ for (const u of params.unknown) {
92
+ const id = BigInt(u.id)
93
+ w.writeVarInt(id)
94
+ if (id % 2n === 0n) {
95
+ const raw = hexToBytes(u.raw_hex)
96
+ const tmpReader = new BufferReader(raw)
97
+ w.writeVarInt(tmpReader.readVarInt())
98
+ } else {
99
+ const raw = hexToBytes(u.raw_hex)
100
+ w.writeVarInt(raw.byteLength)
101
+ w.writeBytes(raw)
102
+ }
103
+ }
104
+ }
105
+ }
106
+
107
+ function decodeSetupParams(r: BufferReader): Draft12SetupParams {
108
+ const count = Number(r.readVarInt())
109
+ const result: Draft12SetupParams = {}
110
+ const unknown: UnknownParam[] = []
111
+
112
+ for (let i = 0; i < count; i++) {
113
+ const paramType = r.readVarInt()
114
+ if (paramType % 2n === 0n) {
115
+ const value = r.readVarInt()
116
+ if (paramType === SETUP_PARAM_MAX_REQUEST_ID) {
117
+ result.max_request_id = value
118
+ } else {
119
+ const tmpW = new BufferWriter(16)
120
+ tmpW.writeVarInt(value)
121
+ const raw = tmpW.finish()
122
+ unknown.push({
123
+ id: `0x${paramType.toString(16)}`,
124
+ length: raw.byteLength,
125
+ raw_hex: bytesToHex(raw),
126
+ })
127
+ }
128
+ } else {
129
+ const length = Number(r.readVarInt())
130
+ const bytes = r.readBytes(length)
131
+ if (paramType === SETUP_PARAM_PATH) {
132
+ result.path = textDecoder.decode(bytes)
133
+ } else {
134
+ unknown.push({
135
+ id: `0x${paramType.toString(16)}`,
136
+ length,
137
+ raw_hex: bytesToHex(bytes),
138
+ })
139
+ }
140
+ }
141
+ }
142
+
143
+ if (unknown.length > 0) result.unknown = unknown
144
+ return result
145
+ }
146
+
147
+ // ─── Version-Specific Parameter Encoding/Decoding ───────────────────────────────
148
+ // Uses even/odd convention: even type → bare varint value, odd type → length-prefixed blob
149
+
150
+ function encodeParams(params: Draft12Params, w: BufferWriter): void {
151
+ let count = params.unknown ? params.unknown.length : 0
152
+ if (params.delivery_timeout !== undefined) count++
153
+ if (params.authorization_token !== undefined) count++
154
+ if (params.max_cache_duration !== undefined) count++
155
+ w.writeVarInt(count)
156
+
157
+ if (params.delivery_timeout !== undefined) {
158
+ // DELIVERY_TIMEOUT = 0x02 (evenbare varint)
159
+ w.writeVarInt(PARAM_DELIVERY_TIMEOUT)
160
+ w.writeVarInt(params.delivery_timeout)
161
+ }
162
+ if (params.authorization_token !== undefined) {
163
+ // AUTHORIZATION_TOKEN = 0x03 (odd → length-prefixed)
164
+ w.writeVarInt(PARAM_AUTHORIZATION_TOKEN)
165
+ const at = params.authorization_token
166
+ const tmpW = new BufferWriter(64)
167
+ tmpW.writeVarInt(at.alias_type)
168
+ tmpW.writeVarInt(at.token_type)
169
+ const tokenBytes = textEncoder.encode(at.token_value)
170
+ tmpW.writeBytes(tokenBytes)
171
+ const raw = tmpW.finish()
172
+ w.writeVarInt(raw.byteLength)
173
+ w.writeBytes(raw)
174
+ }
175
+ if (params.max_cache_duration !== undefined) {
176
+ // MAX_CACHE_DURATION = 0x04 (even bare varint)
177
+ w.writeVarInt(PARAM_MAX_CACHE_DURATION)
178
+ w.writeVarInt(params.max_cache_duration)
179
+ }
180
+ if (params.unknown) {
181
+ for (const u of params.unknown) {
182
+ const id = BigInt(u.id)
183
+ w.writeVarInt(id)
184
+ if (id % 2n === 0n) {
185
+ // Even bare varint
186
+ const raw = hexToBytes(u.raw_hex)
187
+ const tmpReader = new BufferReader(raw)
188
+ w.writeVarInt(tmpReader.readVarInt())
189
+ } else {
190
+ // Odd length-prefixed
191
+ const raw = hexToBytes(u.raw_hex)
192
+ w.writeVarInt(raw.byteLength)
193
+ w.writeBytes(raw)
194
+ }
195
+ }
196
+ }
197
+ }
198
+
199
+ function decodeParams(r: BufferReader): Draft12Params {
200
+ const count = Number(r.readVarInt())
201
+ const result: Draft12Params = {}
202
+ const unknown: UnknownParam[] = []
203
+
204
+ for (let i = 0; i < count; i++) {
205
+ const paramType = r.readVarInt()
206
+
207
+ if (paramType % 2n === 0n) {
208
+ // Even type → bare varint value
209
+ const value = r.readVarInt()
210
+ if (paramType === PARAM_DELIVERY_TIMEOUT) {
211
+ result.delivery_timeout = value
212
+ } else if (paramType === PARAM_MAX_CACHE_DURATION) {
213
+ result.max_cache_duration = value
214
+ } else {
215
+ const tmpW = new BufferWriter(16)
216
+ tmpW.writeVarInt(value)
217
+ const raw = tmpW.finish()
218
+ unknown.push({
219
+ id: `0x${paramType.toString(16)}`,
220
+ length: raw.byteLength,
221
+ raw_hex: bytesToHex(raw),
222
+ })
223
+ }
224
+ } else {
225
+ // Odd type length-prefixed blob
226
+ const length = Number(r.readVarInt())
227
+ const startOff = r.offset
228
+
229
+ if (paramType === PARAM_AUTHORIZATION_TOKEN) {
230
+ const alias_type = r.readVarInt()
231
+ const token_type = r.readVarInt()
232
+ const tokenBytesLen = length - (r.offset - startOff)
233
+ const tokenBytes = r.readBytes(tokenBytesLen)
234
+ result.authorization_token = {
235
+ alias_type,
236
+ token_type,
237
+ token_value: textDecoder.decode(tokenBytes),
238
+ }
239
+ } else {
240
+ const bytes = r.readBytes(length)
241
+ unknown.push({
242
+ id: `0x${paramType.toString(16)}`,
243
+ length,
244
+ raw_hex: bytesToHex(bytes),
245
+ })
246
+ }
247
+ }
248
+ }
249
+
250
+ if (unknown.length > 0) result.unknown = unknown
251
+ return result
252
+ }
253
+
254
+ // ─── Payload Encoders ──────────────────────────────────────────────────────────
255
+
256
+ function encodeClientSetupPayload(
257
+ msg: Draft12Message & { type: 'client_setup' },
258
+ w: BufferWriter,
259
+ ): void {
260
+ w.writeVarInt(msg.supported_versions.length)
261
+ for (const v of msg.supported_versions) w.writeVarInt(v)
262
+ encodeSetupParams(msg.parameters, w)
263
+ }
264
+
265
+ function encodeServerSetupPayload(
266
+ msg: Draft12Message & { type: 'server_setup' },
267
+ w: BufferWriter,
268
+ ): void {
269
+ w.writeVarInt(msg.selected_version)
270
+ encodeSetupParams(msg.parameters, w)
271
+ }
272
+
273
+ function encodeSubscribePayload(
274
+ msg: Draft12Message & { type: 'subscribe' },
275
+ w: BufferWriter,
276
+ ): void {
277
+ w.writeVarInt(msg.request_id)
278
+ // Draft-12: no track_alias in subscribe (moved to subscribe_ok)
279
+ w.writeTuple(msg.track_namespace)
280
+ w.writeString(msg.track_name)
281
+ w.writeUint8(msg.subscriber_priority)
282
+ w.writeUint8(msg.group_order)
283
+ w.writeVarInt(msg.forward)
284
+ w.writeVarInt(msg.filter_type)
285
+ const ft = Number(msg.filter_type)
286
+ if (ft === 3 || ft === 4) {
287
+ w.writeVarInt(msg.start_group!)
288
+ w.writeVarInt(msg.start_object!)
289
+ }
290
+ if (ft === 4) {
291
+ w.writeVarInt(msg.end_group!)
292
+ }
293
+ encodeParams(msg.parameters, w)
294
+ }
295
+
296
+ function encodeSubscribeOkPayload(
297
+ msg: Draft12Message & { type: 'subscribe_ok' },
298
+ w: BufferWriter,
299
+ ): void {
300
+ w.writeVarInt(msg.request_id)
301
+ w.writeVarInt(msg.track_alias)
302
+ w.writeVarInt(msg.expires)
303
+ w.writeUint8(msg.group_order)
304
+ w.writeVarInt(msg.content_exists)
305
+ if (msg.content_exists === 1n && msg.largest_location) {
306
+ w.writeVarInt(msg.largest_location.group)
307
+ w.writeVarInt(msg.largest_location.object)
308
+ }
309
+ encodeParams(msg.parameters, w)
310
+ }
311
+
312
+ function encodeSubscribeErrorPayload(
313
+ msg: Draft12Message & { type: 'subscribe_error' },
314
+ w: BufferWriter,
315
+ ): void {
316
+ w.writeVarInt(msg.request_id)
317
+ w.writeVarInt(msg.error_code)
318
+ w.writeString(msg.reason_phrase)
319
+ // Draft-12: no track_alias in subscribe_error
320
+ }
321
+
322
+ function encodeSubscribeUpdatePayload(
323
+ msg: Draft12Message & { type: 'subscribe_update' },
324
+ w: BufferWriter,
325
+ ): void {
326
+ w.writeVarInt(msg.request_id)
327
+ w.writeVarInt(msg.start_group)
328
+ w.writeVarInt(msg.start_object)
329
+ w.writeVarInt(msg.end_group)
330
+ w.writeUint8(msg.subscriber_priority)
331
+ w.writeVarInt(msg.forward)
332
+ encodeParams(msg.parameters, w)
333
+ }
334
+
335
+ function encodeSubscribeDonePayload(
336
+ msg: Draft12Message & { type: 'subscribe_done' },
337
+ w: BufferWriter,
338
+ ): void {
339
+ w.writeVarInt(msg.request_id)
340
+ w.writeVarInt(msg.status_code)
341
+ w.writeVarInt(msg.stream_count)
342
+ w.writeString(msg.reason_phrase)
343
+ }
344
+
345
+ function encodeUnsubscribePayload(
346
+ msg: Draft12Message & { type: 'unsubscribe' },
347
+ w: BufferWriter,
348
+ ): void {
349
+ w.writeVarInt(msg.request_id)
350
+ }
351
+
352
+ function encodeAnnouncePayload(msg: Draft12Message & { type: 'announce' }, w: BufferWriter): void {
353
+ w.writeVarInt(msg.request_id)
354
+ w.writeTuple(msg.track_namespace)
355
+ encodeParams(msg.parameters, w)
356
+ }
357
+
358
+ function encodeAnnounceOkPayload(
359
+ msg: Draft12Message & { type: 'announce_ok' },
360
+ w: BufferWriter,
361
+ ): void {
362
+ w.writeVarInt(msg.request_id)
363
+ }
364
+
365
+ function encodeAnnounceErrorPayload(
366
+ msg: Draft12Message & { type: 'announce_error' },
367
+ w: BufferWriter,
368
+ ): void {
369
+ w.writeVarInt(msg.request_id)
370
+ w.writeVarInt(msg.error_code)
371
+ w.writeString(msg.reason_phrase)
372
+ }
373
+
374
+ function encodeUnannouncePayload(
375
+ msg: Draft12Message & { type: 'unannounce' },
376
+ w: BufferWriter,
377
+ ): void {
378
+ w.writeTuple(msg.track_namespace)
379
+ }
380
+
381
+ function encodeAnnounceCancelPayload(
382
+ msg: Draft12Message & { type: 'announce_cancel' },
383
+ w: BufferWriter,
384
+ ): void {
385
+ w.writeTuple(msg.track_namespace)
386
+ w.writeVarInt(msg.error_code)
387
+ w.writeString(msg.reason_phrase)
388
+ }
389
+
390
+ function encodeSubscribeAnnouncesPayload(
391
+ msg: Draft12Message & { type: 'subscribe_announces' },
392
+ w: BufferWriter,
393
+ ): void {
394
+ w.writeVarInt(msg.request_id)
395
+ w.writeTuple(msg.track_namespace_prefix)
396
+ encodeParams(msg.parameters, w)
397
+ }
398
+
399
+ function encodeSubscribeAnnouncesOkPayload(
400
+ msg: Draft12Message & { type: 'subscribe_announces_ok' },
401
+ w: BufferWriter,
402
+ ): void {
403
+ w.writeVarInt(msg.request_id)
404
+ }
405
+
406
+ function encodeSubscribeAnnouncesErrorPayload(
407
+ msg: Draft12Message & { type: 'subscribe_announces_error' },
408
+ w: BufferWriter,
409
+ ): void {
410
+ w.writeVarInt(msg.request_id)
411
+ w.writeVarInt(msg.error_code)
412
+ w.writeString(msg.reason_phrase)
413
+ }
414
+
415
+ function encodeUnsubscribeAnnouncesPayload(
416
+ msg: Draft12Message & { type: 'unsubscribe_announces' },
417
+ w: BufferWriter,
418
+ ): void {
419
+ w.writeTuple(msg.track_namespace_prefix)
420
+ }
421
+
422
+ function encodePublishPayload(msg: Draft12Message & { type: 'publish' }, w: BufferWriter): void {
423
+ w.writeVarInt(msg.request_id)
424
+ w.writeTuple(msg.track_namespace)
425
+ w.writeString(msg.track_name)
426
+ w.writeVarInt(msg.track_alias)
427
+ w.writeUint8(msg.group_order)
428
+ w.writeVarInt(msg.content_exists)
429
+ if (msg.content_exists === 1n && msg.largest_location) {
430
+ w.writeVarInt(msg.largest_location.group)
431
+ w.writeVarInt(msg.largest_location.object)
432
+ }
433
+ w.writeVarInt(msg.forward)
434
+ encodeParams(msg.parameters, w)
435
+ }
436
+
437
+ function encodePublishOkPayload(
438
+ msg: Draft12Message & { type: 'publish_ok' },
439
+ w: BufferWriter,
440
+ ): void {
441
+ w.writeVarInt(msg.request_id)
442
+ w.writeVarInt(msg.forward)
443
+ w.writeUint8(msg.subscriber_priority)
444
+ w.writeUint8(msg.group_order)
445
+ w.writeVarInt(msg.filter_type)
446
+ const ft = Number(msg.filter_type)
447
+ if (ft === 3 || ft === 4) {
448
+ w.writeVarInt(msg.start_group!)
449
+ w.writeVarInt(msg.start_object!)
450
+ }
451
+ if (ft === 4) {
452
+ w.writeVarInt(msg.end_group!)
453
+ }
454
+ encodeParams(msg.parameters, w)
455
+ }
456
+
457
+ function encodePublishErrorPayload(
458
+ msg: Draft12Message & { type: 'publish_error' },
459
+ w: BufferWriter,
460
+ ): void {
461
+ w.writeVarInt(msg.request_id)
462
+ w.writeVarInt(msg.error_code)
463
+ w.writeString(msg.reason_phrase)
464
+ }
465
+
466
+ function encodeFetchPayload(msg: Draft12Message & { type: 'fetch' }, w: BufferWriter): void {
467
+ w.writeVarInt(msg.request_id)
468
+ w.writeUint8(msg.subscriber_priority)
469
+ w.writeUint8(msg.group_order)
470
+ w.writeVarInt(msg.fetch_type)
471
+ const ft = Number(msg.fetch_type)
472
+ if (ft === 1 && msg.standalone) {
473
+ w.writeTuple(msg.standalone.track_namespace)
474
+ w.writeString(msg.standalone.track_name)
475
+ w.writeVarInt(msg.standalone.start_group)
476
+ w.writeVarInt(msg.standalone.start_object)
477
+ w.writeVarInt(msg.standalone.end_group)
478
+ w.writeVarInt(msg.standalone.end_object)
479
+ } else if ((ft === 2 || ft === 3) && msg.joining) {
480
+ w.writeVarInt(msg.joining.joining_subscribe_id)
481
+ w.writeVarInt(msg.joining.joining_start)
482
+ }
483
+ encodeParams(msg.parameters, w)
484
+ }
485
+
486
+ function encodeFetchOkPayload(msg: Draft12Message & { type: 'fetch_ok' }, w: BufferWriter): void {
487
+ w.writeVarInt(msg.request_id)
488
+ w.writeUint8(msg.group_order)
489
+ w.writeVarInt(msg.end_of_track)
490
+ w.writeVarInt(msg.end_location.group)
491
+ w.writeVarInt(msg.end_location.object)
492
+ encodeParams(msg.parameters, w)
493
+ }
494
+
495
+ function encodeFetchErrorPayload(
496
+ msg: Draft12Message & { type: 'fetch_error' },
497
+ w: BufferWriter,
498
+ ): void {
499
+ w.writeVarInt(msg.request_id)
500
+ w.writeVarInt(msg.error_code)
501
+ w.writeString(msg.reason_phrase)
502
+ }
503
+
504
+ function encodeFetchCancelPayload(
505
+ msg: Draft12Message & { type: 'fetch_cancel' },
506
+ w: BufferWriter,
507
+ ): void {
508
+ w.writeVarInt(msg.request_id)
509
+ }
510
+
511
+ function encodeTrackStatusRequestPayload(
512
+ msg: Draft12Message & { type: 'track_status_request' },
513
+ w: BufferWriter,
514
+ ): void {
515
+ w.writeVarInt(msg.request_id)
516
+ w.writeTuple(msg.track_namespace)
517
+ w.writeString(msg.track_name)
518
+ encodeParams(msg.parameters, w)
519
+ }
520
+
521
+ function encodeTrackStatusPayload(
522
+ msg: Draft12Message & { type: 'track_status' },
523
+ w: BufferWriter,
524
+ ): void {
525
+ w.writeVarInt(msg.request_id)
526
+ w.writeVarInt(msg.status_code)
527
+ w.writeVarInt(msg.largest_location.group)
528
+ w.writeVarInt(msg.largest_location.object)
529
+ encodeParams(msg.parameters, w)
530
+ }
531
+
532
+ function encodeGoAwayPayload(msg: Draft12Message & { type: 'goaway' }, w: BufferWriter): void {
533
+ w.writeString(msg.new_session_uri)
534
+ }
535
+
536
+ function encodeMaxRequestIdPayload(
537
+ msg: Draft12Message & { type: 'max_request_id' },
538
+ w: BufferWriter,
539
+ ): void {
540
+ w.writeVarInt(msg.request_id)
541
+ }
542
+
543
+ function encodeRequestsBlockedPayload(
544
+ msg: Draft12Message & { type: 'requests_blocked' },
545
+ w: BufferWriter,
546
+ ): void {
547
+ w.writeVarInt(msg.maximum_request_id)
548
+ }
549
+
550
+ // ─── Payload Decoders ──────────────────────────────────────────────────────────
551
+
552
+ function decodeClientSetupPayload(r: BufferReader): Draft12Message {
553
+ const numVersions = Number(r.readVarInt())
554
+ if (numVersions === 0) {
555
+ throw new DecodeError('CONSTRAINT_VIOLATION', 'supported_versions must not be empty', r.offset)
556
+ }
557
+ const supported_versions: bigint[] = []
558
+ for (let i = 0; i < numVersions; i++) supported_versions.push(r.readVarInt())
559
+ const parameters = decodeSetupParams(r)
560
+ return { type: 'client_setup', supported_versions, parameters }
561
+ }
562
+
563
+ function decodeServerSetupPayload(r: BufferReader): Draft12Message {
564
+ const selected_version = r.readVarInt()
565
+ const parameters = decodeSetupParams(r)
566
+ return { type: 'server_setup', selected_version, parameters }
567
+ }
568
+
569
+ function decodeSubscribePayload(r: BufferReader): Draft12Message {
570
+ const request_id = r.readVarInt()
571
+ // Draft-12: no track_alias in subscribe
572
+ const track_namespace = r.readTuple()
573
+ const track_name = r.readString()
574
+ const subscriber_priority = r.readUint8()
575
+ const group_order = r.readUint8()
576
+ const forward = r.readVarInt()
577
+ const filter_type = r.readVarInt()
578
+ const ft = Number(filter_type)
579
+ if (ft < 1 || ft > 4) {
580
+ throw new DecodeError('CONSTRAINT_VIOLATION', `Invalid filter_type: ${ft}`, r.offset)
581
+ }
582
+ let start_group: bigint | undefined
583
+ let start_object: bigint | undefined
584
+ let end_group: bigint | undefined
585
+ if (ft === 3 || ft === 4) {
586
+ start_group = r.readVarInt()
587
+ start_object = r.readVarInt()
588
+ }
589
+ if (ft === 4) {
590
+ end_group = r.readVarInt()
591
+ }
592
+ const parameters = decodeParams(r)
593
+ const msg: Record<string, unknown> = {
594
+ type: 'subscribe',
595
+ request_id,
596
+ track_namespace,
597
+ track_name,
598
+ subscriber_priority,
599
+ group_order,
600
+ forward,
601
+ filter_type,
602
+ parameters,
603
+ }
604
+ if (start_group !== undefined) msg.start_group = start_group
605
+ if (start_object !== undefined) msg.start_object = start_object
606
+ if (end_group !== undefined) msg.end_group = end_group
607
+ return msg as unknown as Draft12Message
608
+ }
609
+
610
+ function decodeSubscribeOkPayload(r: BufferReader): Draft12Message {
611
+ const request_id = r.readVarInt()
612
+ const track_alias = r.readVarInt()
613
+ const expires = r.readVarInt()
614
+ const group_order = r.readUint8()
615
+ const content_exists = r.readVarInt()
616
+ let largest_location: LargestLocation | undefined
617
+ if (content_exists === 1n) {
618
+ const group = r.readVarInt()
619
+ const object = r.readVarInt()
620
+ largest_location = { group, object }
621
+ }
622
+ const parameters = decodeParams(r)
623
+ const msg: Record<string, unknown> = {
624
+ type: 'subscribe_ok',
625
+ request_id,
626
+ track_alias,
627
+ expires,
628
+ group_order,
629
+ content_exists,
630
+ parameters,
631
+ }
632
+ if (largest_location) msg.largest_location = largest_location
633
+ return msg as unknown as Draft12Message
634
+ }
635
+
636
+ function decodeSubscribeErrorPayload(r: BufferReader): Draft12Message {
637
+ const request_id = r.readVarInt()
638
+ const error_code = r.readVarInt()
639
+ const reason_phrase = r.readString()
640
+ // Draft-12: no track_alias in subscribe_error
641
+ return { type: 'subscribe_error', request_id, error_code, reason_phrase }
642
+ }
643
+
644
+ function decodeSubscribeUpdatePayload(r: BufferReader): Draft12Message {
645
+ const request_id = r.readVarInt()
646
+ const start_group = r.readVarInt()
647
+ const start_object = r.readVarInt()
648
+ const end_group = r.readVarInt()
649
+ const subscriber_priority = r.readUint8()
650
+ const forward = r.readVarInt()
651
+ const parameters = decodeParams(r)
652
+ return {
653
+ type: 'subscribe_update',
654
+ request_id,
655
+ start_group,
656
+ start_object,
657
+ end_group,
658
+ subscriber_priority,
659
+ forward,
660
+ parameters,
661
+ }
662
+ }
663
+
664
+ function decodeSubscribeDonePayload(r: BufferReader): Draft12Message {
665
+ const request_id = r.readVarInt()
666
+ const status_code = r.readVarInt()
667
+ const stream_count = r.readVarInt()
668
+ const reason_phrase = r.readString()
669
+ return {
670
+ type: 'subscribe_done',
671
+ request_id,
672
+ status_code,
673
+ stream_count,
674
+ reason_phrase,
675
+ }
676
+ }
677
+
678
+ function decodeUnsubscribePayload(r: BufferReader): Draft12Message {
679
+ const request_id = r.readVarInt()
680
+ return { type: 'unsubscribe', request_id }
681
+ }
682
+
683
+ function decodeAnnouncePayload(r: BufferReader): Draft12Message {
684
+ const request_id = r.readVarInt()
685
+ const track_namespace = r.readTuple()
686
+ const parameters = decodeParams(r)
687
+ return { type: 'announce', request_id, track_namespace, parameters }
688
+ }
689
+
690
+ function decodeAnnounceOkPayload(r: BufferReader): Draft12Message {
691
+ const request_id = r.readVarInt()
692
+ return { type: 'announce_ok', request_id }
693
+ }
694
+
695
+ function decodeAnnounceErrorPayload(r: BufferReader): Draft12Message {
696
+ const request_id = r.readVarInt()
697
+ const error_code = r.readVarInt()
698
+ const reason_phrase = r.readString()
699
+ return { type: 'announce_error', request_id, error_code, reason_phrase }
700
+ }
701
+
702
+ function decodeUnannouncePayload(r: BufferReader): Draft12Message {
703
+ const track_namespace = r.readTuple()
704
+ return { type: 'unannounce', track_namespace }
705
+ }
706
+
707
+ function decodeAnnounceCancelPayload(r: BufferReader): Draft12Message {
708
+ const track_namespace = r.readTuple()
709
+ const error_code = r.readVarInt()
710
+ const reason_phrase = r.readString()
711
+ return { type: 'announce_cancel', track_namespace, error_code, reason_phrase }
712
+ }
713
+
714
+ function decodeSubscribeAnnouncesPayload(r: BufferReader): Draft12Message {
715
+ const request_id = r.readVarInt()
716
+ const track_namespace_prefix = r.readTuple()
717
+ const parameters = decodeParams(r)
718
+ return {
719
+ type: 'subscribe_announces',
720
+ request_id,
721
+ track_namespace_prefix,
722
+ parameters,
723
+ }
724
+ }
725
+
726
+ function decodeSubscribeAnnouncesOkPayload(r: BufferReader): Draft12Message {
727
+ const request_id = r.readVarInt()
728
+ return { type: 'subscribe_announces_ok', request_id }
729
+ }
730
+
731
+ function decodeSubscribeAnnouncesErrorPayload(r: BufferReader): Draft12Message {
732
+ const request_id = r.readVarInt()
733
+ const error_code = r.readVarInt()
734
+ const reason_phrase = r.readString()
735
+ return {
736
+ type: 'subscribe_announces_error',
737
+ request_id,
738
+ error_code,
739
+ reason_phrase,
740
+ }
741
+ }
742
+
743
+ function decodeUnsubscribeAnnouncesPayload(r: BufferReader): Draft12Message {
744
+ const track_namespace_prefix = r.readTuple()
745
+ return { type: 'unsubscribe_announces', track_namespace_prefix }
746
+ }
747
+
748
+ function decodePublishPayload(r: BufferReader): Draft12Message {
749
+ const request_id = r.readVarInt()
750
+ const track_namespace = r.readTuple()
751
+ const track_name = r.readString()
752
+ const track_alias = r.readVarInt()
753
+ const group_order = r.readUint8()
754
+ const content_exists = r.readVarInt()
755
+ let largest_location: LargestLocation | undefined
756
+ if (content_exists === 1n) {
757
+ const group = r.readVarInt()
758
+ const object = r.readVarInt()
759
+ largest_location = { group, object }
760
+ }
761
+ const forward = r.readVarInt()
762
+ const parameters = decodeParams(r)
763
+ const msg: Record<string, unknown> = {
764
+ type: 'publish',
765
+ request_id,
766
+ track_namespace,
767
+ track_name,
768
+ track_alias,
769
+ group_order,
770
+ content_exists,
771
+ forward,
772
+ parameters,
773
+ }
774
+ if (largest_location) msg.largest_location = largest_location
775
+ return msg as unknown as Draft12Message
776
+ }
777
+
778
+ function decodePublishOkPayload(r: BufferReader): Draft12Message {
779
+ const request_id = r.readVarInt()
780
+ const forward = r.readVarInt()
781
+ const subscriber_priority = r.readUint8()
782
+ const group_order = r.readUint8()
783
+ const filter_type = r.readVarInt()
784
+ const ft = Number(filter_type)
785
+ let start_group: bigint | undefined
786
+ let start_object: bigint | undefined
787
+ let end_group: bigint | undefined
788
+ if (ft === 3 || ft === 4) {
789
+ start_group = r.readVarInt()
790
+ start_object = r.readVarInt()
791
+ }
792
+ if (ft === 4) {
793
+ end_group = r.readVarInt()
794
+ }
795
+ const parameters = decodeParams(r)
796
+ const msg: Record<string, unknown> = {
797
+ type: 'publish_ok',
798
+ request_id,
799
+ forward,
800
+ subscriber_priority,
801
+ group_order,
802
+ filter_type,
803
+ parameters,
804
+ }
805
+ if (start_group !== undefined) msg.start_group = start_group
806
+ if (start_object !== undefined) msg.start_object = start_object
807
+ if (end_group !== undefined) msg.end_group = end_group
808
+ return msg as unknown as Draft12Message
809
+ }
810
+
811
+ function decodePublishErrorPayload(r: BufferReader): Draft12Message {
812
+ const request_id = r.readVarInt()
813
+ const error_code = r.readVarInt()
814
+ const reason_phrase = r.readString()
815
+ return { type: 'publish_error', request_id, error_code, reason_phrase }
816
+ }
817
+
818
+ function decodeFetchPayload(r: BufferReader): Draft12Message {
819
+ const request_id = r.readVarInt()
820
+ const subscriber_priority = r.readUint8()
821
+ const group_order = r.readUint8()
822
+ const fetch_type = r.readVarInt()
823
+ const ft = Number(fetch_type)
824
+
825
+ if (ft < 1 || ft > 3) {
826
+ throw new DecodeError('CONSTRAINT_VIOLATION', `Invalid fetch_type: ${ft}`, r.offset)
827
+ }
828
+
829
+ let standalone: StandaloneFetch | undefined
830
+ let joining: JoiningFetch | undefined
831
+
832
+ if (ft === 1) {
833
+ const track_namespace = r.readTuple()
834
+ const track_name = r.readString()
835
+ const start_group = r.readVarInt()
836
+ const start_object = r.readVarInt()
837
+ const end_group = r.readVarInt()
838
+ const end_object = r.readVarInt()
839
+ standalone = {
840
+ track_namespace,
841
+ track_name,
842
+ start_group,
843
+ start_object,
844
+ end_group,
845
+ end_object,
846
+ }
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 Draft12Fetch
864
+ }
865
+
866
+ function decodeFetchOkPayload(r: BufferReader): Draft12Message {
867
+ const request_id = r.readVarInt()
868
+ const group_order = r.readUint8()
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): Draft12Message {
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): Draft12Message {
891
+ const request_id = r.readVarInt()
892
+ return { type: 'fetch_cancel', request_id }
893
+ }
894
+
895
+ function decodeTrackStatusRequestPayload(r: BufferReader): Draft12Message {
896
+ const request_id = r.readVarInt()
897
+ const track_namespace = r.readTuple()
898
+ const track_name = r.readString()
899
+ const parameters = decodeParams(r)
900
+ return {
901
+ type: 'track_status_request',
902
+ request_id,
903
+ track_namespace,
904
+ track_name,
905
+ parameters,
906
+ }
907
+ }
908
+
909
+ function decodeTrackStatusPayload(r: BufferReader): Draft12Message {
910
+ const request_id = r.readVarInt()
911
+ const status_code = r.readVarInt()
912
+ const group = r.readVarInt()
913
+ const object = r.readVarInt()
914
+ const parameters = decodeParams(r)
915
+ return {
916
+ type: 'track_status',
917
+ request_id,
918
+ status_code,
919
+ largest_location: { group, object },
920
+ parameters,
921
+ }
922
+ }
923
+
924
+ function decodeGoAwayPayload(r: BufferReader): Draft12Message {
925
+ const new_session_uri = r.readString()
926
+ return { type: 'goaway', new_session_uri }
927
+ }
928
+
929
+ function decodeMaxRequestIdPayload(r: BufferReader): Draft12Message {
930
+ const request_id = r.readVarInt()
931
+ return { type: 'max_request_id', request_id }
932
+ }
933
+
934
+ function decodeRequestsBlockedPayload(r: BufferReader): Draft12Message {
935
+ const maximum_request_id = r.readVarInt()
936
+ return { type: 'requests_blocked', maximum_request_id }
937
+ }
938
+
939
+ // ─── Payload dispatch tables ───────────────────────────────────────────────────
940
+
941
+ const payloadDecoders: ReadonlyMap<bigint, (r: BufferReader) => Draft12Message> = new Map([
942
+ [MSG_CLIENT_SETUP, decodeClientSetupPayload],
943
+ [MSG_SERVER_SETUP, decodeServerSetupPayload],
944
+ [MSG_SUBSCRIBE, decodeSubscribePayload],
945
+ [MSG_SUBSCRIBE_OK, decodeSubscribeOkPayload],
946
+ [MSG_SUBSCRIBE_ERROR, decodeSubscribeErrorPayload],
947
+ [MSG_SUBSCRIBE_UPDATE, decodeSubscribeUpdatePayload],
948
+ [MSG_SUBSCRIBE_DONE, decodeSubscribeDonePayload],
949
+ [MSG_UNSUBSCRIBE, decodeUnsubscribePayload],
950
+ [MSG_ANNOUNCE, decodeAnnouncePayload],
951
+ [MSG_ANNOUNCE_OK, decodeAnnounceOkPayload],
952
+ [MSG_ANNOUNCE_ERROR, decodeAnnounceErrorPayload],
953
+ [MSG_UNANNOUNCE, decodeUnannouncePayload],
954
+ [MSG_ANNOUNCE_CANCEL, decodeAnnounceCancelPayload],
955
+ [MSG_SUBSCRIBE_ANNOUNCES, decodeSubscribeAnnouncesPayload],
956
+ [MSG_SUBSCRIBE_ANNOUNCES_OK, decodeSubscribeAnnouncesOkPayload],
957
+ [MSG_SUBSCRIBE_ANNOUNCES_ERROR, decodeSubscribeAnnouncesErrorPayload],
958
+ [MSG_UNSUBSCRIBE_ANNOUNCES, decodeUnsubscribeAnnouncesPayload],
959
+ [MSG_PUBLISH, decodePublishPayload],
960
+ [MSG_PUBLISH_OK, decodePublishOkPayload],
961
+ [MSG_PUBLISH_ERROR, decodePublishErrorPayload],
962
+ [MSG_FETCH, decodeFetchPayload],
963
+ [MSG_FETCH_OK, decodeFetchOkPayload],
964
+ [MSG_FETCH_ERROR, decodeFetchErrorPayload],
965
+ [MSG_FETCH_CANCEL, decodeFetchCancelPayload],
966
+ [MSG_TRACK_STATUS_REQUEST, decodeTrackStatusRequestPayload],
967
+ [MSG_TRACK_STATUS, decodeTrackStatusPayload],
968
+ [MSG_GOAWAY, decodeGoAwayPayload],
969
+ [MSG_MAX_REQUEST_ID, decodeMaxRequestIdPayload],
970
+ [MSG_REQUESTS_BLOCKED, decodeRequestsBlockedPayload],
971
+ ])
972
+
973
+ // ─── Public API ────────────────────────────────────────────────────────────────
974
+
975
+ /**
976
+ * Encode a draft-12 control message.
977
+ * Most messages use type(varint) + length(uint16 BE) + payload.
978
+ * PUBLISH family uses type(varint) + length(varint) + payload.
979
+ */
980
+ export function encodeMessage(message: Draft12Message): Uint8Array {
981
+ const typeId = MESSAGE_ID_MAP.get(message.type)
982
+ if (typeId === undefined) throw new Error(`Unknown message type: ${message.type}`)
983
+
984
+ const payloadWriter = new BufferWriter()
985
+ encodePayload(message, payloadWriter)
986
+ const payload = payloadWriter.finishView()
987
+
988
+ const writer = new BufferWriter(payload.byteLength + 16)
989
+ writer.writeVarInt(typeId)
990
+
991
+ if (payload.byteLength > 0xffff) {
992
+ throw new Error(`Payload too large for 16-bit length: ${payload.byteLength}`)
993
+ }
994
+ writer.writeUint8((payload.byteLength >> 8) & 0xff)
995
+ writer.writeUint8(payload.byteLength & 0xff)
996
+
997
+ writer.writeBytes(payload)
998
+ return writer.finish()
999
+ }
1000
+
1001
+ function encodePayload(msg: Draft12Message, w: BufferWriter): void {
1002
+ switch (msg.type) {
1003
+ case 'client_setup':
1004
+ return encodeClientSetupPayload(msg, w)
1005
+ case 'server_setup':
1006
+ return encodeServerSetupPayload(msg, w)
1007
+ case 'subscribe':
1008
+ return encodeSubscribePayload(msg, w)
1009
+ case 'subscribe_ok':
1010
+ return encodeSubscribeOkPayload(msg, w)
1011
+ case 'subscribe_error':
1012
+ return encodeSubscribeErrorPayload(msg, w)
1013
+ case 'subscribe_update':
1014
+ return encodeSubscribeUpdatePayload(msg, w)
1015
+ case 'subscribe_done':
1016
+ return encodeSubscribeDonePayload(msg, w)
1017
+ case 'unsubscribe':
1018
+ return encodeUnsubscribePayload(msg, w)
1019
+ case 'announce':
1020
+ return encodeAnnouncePayload(msg, w)
1021
+ case 'announce_ok':
1022
+ return encodeAnnounceOkPayload(msg, w)
1023
+ case 'announce_error':
1024
+ return encodeAnnounceErrorPayload(msg, w)
1025
+ case 'unannounce':
1026
+ return encodeUnannouncePayload(msg, w)
1027
+ case 'announce_cancel':
1028
+ return encodeAnnounceCancelPayload(msg, w)
1029
+ case 'subscribe_announces':
1030
+ return encodeSubscribeAnnouncesPayload(msg, w)
1031
+ case 'subscribe_announces_ok':
1032
+ return encodeSubscribeAnnouncesOkPayload(msg, w)
1033
+ case 'subscribe_announces_error':
1034
+ return encodeSubscribeAnnouncesErrorPayload(msg, w)
1035
+ case 'unsubscribe_announces':
1036
+ return encodeUnsubscribeAnnouncesPayload(msg, w)
1037
+ case 'publish':
1038
+ return encodePublishPayload(msg, w)
1039
+ case 'publish_ok':
1040
+ return encodePublishOkPayload(msg, w)
1041
+ case 'publish_error':
1042
+ return encodePublishErrorPayload(msg, w)
1043
+ case 'fetch':
1044
+ return encodeFetchPayload(msg, w)
1045
+ case 'fetch_ok':
1046
+ return encodeFetchOkPayload(msg, w)
1047
+ case 'fetch_error':
1048
+ return encodeFetchErrorPayload(msg, w)
1049
+ case 'fetch_cancel':
1050
+ return encodeFetchCancelPayload(msg, w)
1051
+ case 'track_status_request':
1052
+ return encodeTrackStatusRequestPayload(msg, w)
1053
+ case 'track_status':
1054
+ return encodeTrackStatusPayload(msg, w)
1055
+ case 'goaway':
1056
+ return encodeGoAwayPayload(msg, w)
1057
+ case 'max_request_id':
1058
+ return encodeMaxRequestIdPayload(msg, w)
1059
+ case 'requests_blocked':
1060
+ return encodeRequestsBlockedPayload(msg, w)
1061
+ default: {
1062
+ const _exhaustive: never = msg
1063
+ throw new Error(`Unhandled message type: ${(_exhaustive as Draft12Message).type}`)
1064
+ }
1065
+ }
1066
+ }
1067
+
1068
+ /**
1069
+ * Decode a draft-12 control message from bytes.
1070
+ */
1071
+ export function decodeMessage(bytes: Uint8Array): DecodeResult<Draft12Message> {
1072
+ try {
1073
+ const reader = new BufferReader(bytes)
1074
+ const typeId = reader.readVarInt()
1075
+
1076
+ // Read 16-bit big-endian payload length
1077
+ const lenHi = reader.readUint8()
1078
+ const lenLo = reader.readUint8()
1079
+ const payloadLength = (lenHi << 8) | lenLo
1080
+
1081
+ const payloadBytes = reader.readBytes(payloadLength)
1082
+ const payloadReader = new BufferReader(payloadBytes)
1083
+
1084
+ const decoder = payloadDecoders.get(typeId)
1085
+ if (!decoder) {
1086
+ return {
1087
+ ok: false,
1088
+ error: new DecodeError(
1089
+ 'UNKNOWN_MESSAGE_TYPE',
1090
+ `Unknown message type ID: 0x${typeId.toString(16)}`,
1091
+ 0,
1092
+ ),
1093
+ }
1094
+ }
1095
+
1096
+ const message = decoder(payloadReader)
1097
+ return { ok: true, value: message, bytesRead: reader.offset }
1098
+ } catch (e) {
1099
+ if (e instanceof DecodeError) return { ok: false, error: e }
1100
+ throw e
1101
+ }
1102
+ }
1103
+
1104
+ // ─── Data Stream Encoding/Decoding ─────────────────────────────────────────────
1105
+
1106
+ export {
1107
+ decodeDatagram,
1108
+ decodeDataStream,
1109
+ decodeFetchStream,
1110
+ decodeSubgroupStream,
1111
+ encodeDatagram,
1112
+ encodeFetchStream,
1113
+ encodeSubgroupStream,
1114
+ } from './data-streams.js'
1115
+
1116
+ export function createStreamDecoder(): TransformStream<Uint8Array, Draft12Message> {
1117
+ let buffer = new Uint8Array(0)
1118
+ let offset = 0
1119
+ return new TransformStream<Uint8Array, Draft12Message>({
1120
+ transform(chunk, controller) {
1121
+ if (offset > 0) {
1122
+ buffer = buffer.subarray(offset)
1123
+ offset = 0
1124
+ }
1125
+ const newBuffer = new Uint8Array(buffer.length + chunk.length)
1126
+ newBuffer.set(buffer, 0)
1127
+ newBuffer.set(chunk, buffer.length)
1128
+ buffer = newBuffer
1129
+ while (offset < buffer.length) {
1130
+ const result = decodeMessage(buffer.subarray(offset))
1131
+ if (!result.ok) {
1132
+ if (result.error.code === 'UNEXPECTED_END') break
1133
+ controller.error(result.error)
1134
+ return
1135
+ }
1136
+ controller.enqueue(result.value)
1137
+ offset += result.bytesRead
1138
+ }
1139
+ },
1140
+ flush(controller) {
1141
+ if (offset < buffer.length)
1142
+ controller.error(new DecodeError('UNEXPECTED_END', 'Stream ended with incomplete data', 0))
1143
+ },
1144
+ })
1145
+ }
1146
+
1147
+ // ─── Codec Factory ─────────────────────────────────────────────────────────────
1148
+
1149
+ export interface Draft12Codec extends BaseCodec<Draft12Message> {
1150
+ readonly draft: '12'
1151
+ encodeSubgroupStream(stream: SubgroupStream): Uint8Array
1152
+ encodeDatagram(dg: DatagramObject): Uint8Array
1153
+ encodeFetchStream(stream: FetchStream): Uint8Array
1154
+ decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream>
1155
+ decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject>
1156
+ decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream>
1157
+ decodeDataStream(
1158
+ streamType: 'subgroup' | 'datagram' | 'fetch',
1159
+ bytes: Uint8Array,
1160
+ ): DecodeResult<Draft12DataStream>
1161
+ createStreamDecoder(): TransformStream<Uint8Array, Draft12Message>
1162
+ }
1163
+
1164
+ export function createDraft12Codec(): Draft12Codec {
1165
+ return {
1166
+ draft: '12',
1167
+ encodeMessage,
1168
+ decodeMessage,
1169
+ encodeSubgroupStream,
1170
+ encodeDatagram,
1171
+ encodeFetchStream,
1172
+ decodeSubgroupStream,
1173
+ decodeDatagram,
1174
+ decodeFetchStream,
1175
+ decodeDataStream,
1176
+ createStreamDecoder,
1177
+ }
1178
+ }