@moqtap/codec 0.2.3 → 0.4.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 (313) 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/{draft7-session.cjs → draft07-session.cjs} +2 -2
  72. package/dist/draft07-session.d.cts +8 -0
  73. package/dist/draft07-session.d.ts +8 -0
  74. package/dist/{draft7-session.js → draft07-session.js} +1 -1
  75. package/dist/draft07.cjs +129 -0
  76. package/dist/draft07.d.cts +67 -0
  77. package/dist/draft07.d.ts +67 -0
  78. package/dist/draft07.js +129 -0
  79. package/dist/draft08-session.cjs +6 -0
  80. package/dist/draft08-session.d.cts +8 -0
  81. package/dist/draft08-session.d.ts +8 -0
  82. package/dist/{draft8-session.js → draft08-session.js} +1 -1
  83. package/dist/draft08.cjs +119 -0
  84. package/dist/{draft8.d.cts → draft08.d.cts} +15 -13
  85. package/dist/{draft8.d.ts → draft08.d.ts} +15 -13
  86. package/dist/{draft8.js → draft08.js} +7 -4
  87. package/dist/draft09-session.cjs +6 -0
  88. package/dist/draft09-session.d.cts +8 -0
  89. package/dist/draft09-session.d.ts +8 -0
  90. package/dist/{draft9-session.js → draft09-session.js} +1 -1
  91. package/dist/draft09.cjs +119 -0
  92. package/dist/{draft9.d.cts → draft09.d.cts} +15 -13
  93. package/dist/{draft9.d.ts → draft09.d.ts} +15 -13
  94. package/dist/{draft9.js → draft09.js} +7 -4
  95. package/dist/draft10-session.cjs +2 -2
  96. package/dist/draft10-session.d.cts +6 -6
  97. package/dist/draft10-session.d.ts +6 -6
  98. package/dist/draft10-session.js +1 -1
  99. package/dist/draft10.cjs +8 -5
  100. package/dist/draft10.d.cts +14 -12
  101. package/dist/draft10.d.ts +14 -12
  102. package/dist/draft10.js +16 -13
  103. package/dist/draft11-session.cjs +2 -2
  104. package/dist/draft11-session.d.cts +6 -6
  105. package/dist/draft11-session.d.ts +6 -6
  106. package/dist/draft11-session.js +1 -1
  107. package/dist/draft11.cjs +8 -5
  108. package/dist/draft11.d.cts +14 -12
  109. package/dist/draft11.d.ts +14 -12
  110. package/dist/draft11.js +16 -13
  111. package/dist/draft12-session.cjs +2 -2
  112. package/dist/draft12-session.d.cts +6 -6
  113. package/dist/draft12-session.d.ts +6 -6
  114. package/dist/draft12-session.js +1 -1
  115. package/dist/draft12.cjs +8 -5
  116. package/dist/draft12.d.cts +16 -14
  117. package/dist/draft12.d.ts +16 -14
  118. package/dist/draft12.js +16 -13
  119. package/dist/draft13-session.cjs +2 -2
  120. package/dist/draft13-session.d.cts +6 -6
  121. package/dist/draft13-session.d.ts +6 -6
  122. package/dist/draft13-session.js +1 -1
  123. package/dist/draft13.cjs +8 -5
  124. package/dist/draft13.d.cts +16 -14
  125. package/dist/draft13.d.ts +16 -14
  126. package/dist/draft13.js +16 -13
  127. package/dist/draft14-session.cjs +2 -2
  128. package/dist/draft14-session.d.cts +6 -6
  129. package/dist/draft14-session.d.ts +6 -6
  130. package/dist/draft14-session.js +1 -1
  131. package/dist/draft14.cjs +14 -5
  132. package/dist/draft14.d.cts +14 -12
  133. package/dist/draft14.d.ts +14 -12
  134. package/dist/draft14.js +13 -4
  135. package/dist/draft15-session.cjs +2 -2
  136. package/dist/draft15-session.d.cts +6 -6
  137. package/dist/draft15-session.d.ts +6 -6
  138. package/dist/draft15-session.js +1 -1
  139. package/dist/draft15.cjs +8 -5
  140. package/dist/draft15.d.cts +14 -12
  141. package/dist/draft15.d.ts +14 -12
  142. package/dist/draft15.js +16 -13
  143. package/dist/draft16-session.cjs +2 -2
  144. package/dist/draft16-session.d.cts +6 -6
  145. package/dist/draft16-session.d.ts +6 -6
  146. package/dist/draft16-session.js +1 -1
  147. package/dist/draft16.cjs +8 -5
  148. package/dist/draft16.d.cts +14 -12
  149. package/dist/draft16.d.ts +14 -12
  150. package/dist/draft16.js +16 -13
  151. package/dist/draft17-session.cjs +2 -2
  152. package/dist/draft17-session.d.cts +7 -7
  153. package/dist/draft17-session.d.ts +7 -7
  154. package/dist/draft17-session.js +1 -1
  155. package/dist/draft17.cjs +8 -5
  156. package/dist/draft17.d.cts +11 -9
  157. package/dist/draft17.d.ts +11 -9
  158. package/dist/draft17.js +16 -13
  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 +29 -11
  167. package/dist/session.d.ts +29 -11
  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.cts → types-0IWbU9Z_.d.cts} +36 -36
  172. package/dist/{types-B0FT5Qs2.d.ts → 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.cts → types-Br7fm2mf.d.cts} +48 -26
  178. package/dist/{types-8gUGeMgs.d.ts → 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 +63 -25
  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/draft7-session.d.cts +0 -7
  296. package/dist/draft7-session.d.ts +0 -7
  297. package/dist/draft7.cjs +0 -72
  298. package/dist/draft7.d.cts +0 -148
  299. package/dist/draft7.d.ts +0 -148
  300. package/dist/draft7.js +0 -72
  301. package/dist/draft8-session.cjs +0 -6
  302. package/dist/draft8-session.d.cts +0 -8
  303. package/dist/draft8-session.d.ts +0 -8
  304. package/dist/draft8.cjs +0 -116
  305. package/dist/draft9-session.cjs +0 -6
  306. package/dist/draft9-session.d.cts +0 -8
  307. package/dist/draft9-session.d.ts +0 -8
  308. package/dist/draft9.cjs +0 -116
  309. package/dist/types-QNXoxC9Y.d.cts +0 -236
  310. package/dist/types-QNXoxC9Y.d.ts +0 -236
  311. package/src/drafts/draft07/announce-fsm.ts +0 -2
  312. package/src/drafts/draft07/parameters.ts +0 -12
  313. package/src/drafts/draft07/subscription-fsm.ts +0 -3
@@ -1,1043 +1,1347 @@
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_CLIENT_SETUP,
9
- MSG_FETCH,
10
- MSG_FETCH_CANCEL,
11
- MSG_FETCH_ERROR,
12
- MSG_FETCH_OK,
13
- MSG_GOAWAY,
14
- MSG_MAX_REQUEST_ID,
15
- MSG_PUBLISH,
16
- MSG_PUBLISH_DONE,
17
- MSG_PUBLISH_ERROR,
18
- MSG_PUBLISH_NAMESPACE,
19
- MSG_PUBLISH_NAMESPACE_CANCEL,
20
- MSG_PUBLISH_NAMESPACE_DONE,
21
- MSG_PUBLISH_NAMESPACE_ERROR,
22
- MSG_PUBLISH_NAMESPACE_OK,
23
- MSG_PUBLISH_OK,
24
- MSG_REQUESTS_BLOCKED,
25
- MSG_SERVER_SETUP,
26
- MSG_SUBSCRIBE,
27
- MSG_SUBSCRIBE_ERROR,
28
- MSG_SUBSCRIBE_NAMESPACE,
29
- MSG_SUBSCRIBE_NAMESPACE_ERROR,
30
- MSG_SUBSCRIBE_NAMESPACE_OK,
31
- MSG_SUBSCRIBE_OK,
32
- MSG_SUBSCRIBE_UPDATE,
33
- MSG_TRACK_STATUS,
34
- MSG_TRACK_STATUS_ERROR,
35
- MSG_TRACK_STATUS_OK,
36
- MSG_UNSUBSCRIBE,
37
- MSG_UNSUBSCRIBE_NAMESPACE,
38
- PARAM_MAX_REQUEST_ID,
39
- PARAM_PATH,
40
- PARAM_ROLE,
41
- } from "./messages.js";
42
- import type {
43
- DatagramObject,
44
- DataStreamEvent,
45
- Draft14DataStream,
46
- Draft14Message,
47
- Draft14Params,
48
- FetchObjectPayload,
49
- FetchStream,
50
- FetchStreamHeader,
51
- ObjectPayload,
52
- SubgroupStream,
53
- SubgroupStreamHeader,
54
- UnknownParam,
55
- } from "./types.js";
56
-
57
- const textEncoder = /* @__PURE__ */ new TextEncoder();
58
- const textDecoder = /* @__PURE__ */ new TextDecoder();
59
-
60
- // ─── Parameter Encoding/Decoding ───────────────────────────────────────────────
61
-
62
- function encodeParams(params: Draft14Params, writer: BufferWriter): void {
63
- // Count total params
64
- let count = 0;
65
- if (params.role !== undefined) count++;
66
- if (params.path !== undefined) count++;
67
- if (params.max_request_id !== undefined) count++;
68
- if (params.unknown) count += params.unknown.length;
69
-
70
- writer.writeVarInt(count);
71
-
72
- // ROLE (0x00) - even, varint value
73
- if (params.role !== undefined) {
74
- writer.writeVarInt(PARAM_ROLE);
75
- writer.writeVarInt(params.role);
76
- }
77
-
78
- // PATH (0x01) - odd, length-prefixed bytes
79
- if (params.path !== undefined) {
80
- writer.writeVarInt(PARAM_PATH);
81
- const encoded = textEncoder.encode(params.path);
82
- writer.writeVarInt(encoded.byteLength);
83
- writer.writeBytes(encoded);
84
- }
85
-
86
- // MAX_REQUEST_ID (0x02) - even, varint value
87
- if (params.max_request_id !== undefined) {
88
- writer.writeVarInt(PARAM_MAX_REQUEST_ID);
89
- writer.writeVarInt(params.max_request_id);
90
- }
91
-
92
- // Unknown params
93
- if (params.unknown) {
94
- for (const u of params.unknown) {
95
- const id = BigInt(u.id);
96
- writer.writeVarInt(id);
97
- const raw = hexToBytes(u.raw_hex);
98
- writer.writeVarInt(raw.byteLength);
99
- writer.writeBytes(raw);
100
- }
101
- }
102
- }
103
-
104
- function decodeParams(reader: BufferReader): Draft14Params {
105
- const count = Number(reader.readVarInt());
106
- const result: Draft14Params = {};
107
- const unknown: UnknownParam[] = [];
108
-
109
- for (let i = 0; i < count; i++) {
110
- const paramType = reader.readVarInt();
111
-
112
- if (paramType % 2n === 0n) {
113
- // Even: value is a varint directly
114
- const value = reader.readVarInt();
115
- if (paramType === PARAM_ROLE) {
116
- result.role = value;
117
- } else if (paramType === PARAM_MAX_REQUEST_ID) {
118
- result.max_request_id = value;
119
- } else {
120
- // Unknown even param — encode the varint value as raw bytes
121
- const tmpWriter = new BufferWriter(16);
122
- tmpWriter.writeVarInt(value);
123
- const raw = tmpWriter.finish();
124
- unknown.push({
125
- id: `0x${paramType.toString(16)}`,
126
- length: raw.byteLength,
127
- raw_hex: bytesToHex(raw),
128
- });
129
- }
130
- } else {
131
- // Odd: value is length-prefixed bytes
132
- const length = Number(reader.readVarInt());
133
- const bytes = reader.readBytes(length);
134
- if (paramType === PARAM_PATH) {
135
- result.path = textDecoder.decode(bytes);
136
- } else {
137
- unknown.push({
138
- id: `0x${paramType.toString(16)}`,
139
- length,
140
- raw_hex: bytesToHex(bytes),
141
- });
142
- }
143
- }
144
- }
145
-
146
- if (unknown.length > 0) {
147
- result.unknown = unknown;
148
- }
149
-
150
- return result;
151
- }
152
-
153
- // ─── Payload Encoders ──────────────────────────────────────────────────────────
154
-
155
- function encodeClientSetupPayload(
156
- msg: Draft14Message & { type: "client_setup" },
157
- w: BufferWriter,
158
- ): void {
159
- w.writeVarInt(msg.supported_versions.length);
160
- for (const v of msg.supported_versions) {
161
- w.writeVarInt(v);
162
- }
163
- encodeParams(msg.parameters, w);
164
- }
165
-
166
- function encodeServerSetupPayload(
167
- msg: Draft14Message & { type: "server_setup" },
168
- w: BufferWriter,
169
- ): void {
170
- w.writeVarInt(msg.selected_version);
171
- encodeParams(msg.parameters, w);
172
- }
173
-
174
- function encodeSubscribePayload(
175
- msg: Draft14Message & { type: "subscribe" },
176
- w: BufferWriter,
177
- ): void {
178
- w.writeVarInt(msg.request_id);
179
- w.writeTuple(msg.track_namespace);
180
- w.writeString(msg.track_name);
181
- w.writeUint8(Number(msg.subscriber_priority));
182
- w.writeVarInt(msg.group_order);
183
- w.writeVarInt(msg.forward);
184
- w.writeVarInt(msg.filter_type);
185
- const ft = Number(msg.filter_type);
186
- if (ft >= 3) {
187
- w.writeVarInt(msg.start_group!);
188
- w.writeVarInt(msg.start_object!);
189
- }
190
- if (ft === 4) {
191
- w.writeVarInt(msg.end_group!);
192
- }
193
- encodeParams(msg.parameters, w);
194
- }
195
-
196
- function encodeSubscribeOkPayload(
197
- msg: Draft14Message & { type: "subscribe_ok" },
198
- w: BufferWriter,
199
- ): void {
200
- w.writeVarInt(msg.request_id);
201
- w.writeVarInt(msg.track_alias);
202
- w.writeVarInt(msg.expires);
203
- w.writeVarInt(msg.group_order);
204
- w.writeVarInt(msg.content_exists);
205
- if (Number(msg.content_exists) === 1) {
206
- w.writeVarInt(msg.largest_group!);
207
- w.writeVarInt(msg.largest_object!);
208
- }
209
- encodeParams(msg.parameters, w);
210
- }
211
-
212
- function encodeSubscribeUpdatePayload(
213
- msg: Draft14Message & { type: "subscribe_update" },
214
- w: BufferWriter,
215
- ): void {
216
- w.writeVarInt(msg.request_id);
217
- w.writeVarInt(msg.start_group);
218
- w.writeVarInt(msg.start_object);
219
- w.writeVarInt(msg.end_group);
220
- w.writeUint8(Number(msg.subscriber_priority));
221
- w.writeVarInt(msg.forward);
222
- encodeParams(msg.parameters, w);
223
- }
224
-
225
- function encodeSubscribeErrorPayload(
226
- msg: Draft14Message & { type: "subscribe_error" },
227
- w: BufferWriter,
228
- ): void {
229
- w.writeVarInt(msg.request_id);
230
- w.writeVarInt(msg.error_code);
231
- w.writeString(msg.reason_phrase);
232
- }
233
-
234
- function encodeUnsubscribePayload(
235
- msg: Draft14Message & { type: "unsubscribe" },
236
- w: BufferWriter,
237
- ): void {
238
- w.writeVarInt(msg.request_id);
239
- }
240
-
241
- function encodePublishPayload(msg: Draft14Message & { type: "publish" }, w: BufferWriter): void {
242
- w.writeVarInt(msg.request_id);
243
- w.writeTuple(msg.track_namespace);
244
- w.writeString(msg.track_name);
245
- w.writeVarInt(msg.forward);
246
- encodeParams(msg.parameters, w);
247
- }
248
-
249
- function encodePublishOkPayload(
250
- msg: Draft14Message & { type: "publish_ok" },
251
- w: BufferWriter,
252
- ): void {
253
- w.writeVarInt(msg.request_id);
254
- w.writeVarInt(msg.track_alias);
255
- w.writeVarInt(msg.forward);
256
- encodeParams(msg.parameters, w);
257
- }
258
-
259
- function encodePublishErrorPayload(
260
- msg: Draft14Message & { type: "publish_error" },
261
- w: BufferWriter,
262
- ): void {
263
- w.writeVarInt(msg.request_id);
264
- w.writeVarInt(msg.error_code);
265
- w.writeString(msg.reason_phrase);
266
- }
267
-
268
- function encodePublishDonePayload(
269
- msg: Draft14Message & { type: "publish_done" },
270
- w: BufferWriter,
271
- ): void {
272
- w.writeVarInt(msg.request_id);
273
- w.writeVarInt(msg.status_code);
274
- w.writeString(msg.reason_phrase);
275
- }
276
-
277
- function encodePublishNamespacePayload(
278
- msg: Draft14Message & { type: "publish_namespace" },
279
- w: BufferWriter,
280
- ): void {
281
- w.writeVarInt(msg.request_id);
282
- w.writeTuple(msg.track_namespace);
283
- encodeParams(msg.parameters, w);
284
- }
285
-
286
- function encodePublishNamespaceOkPayload(
287
- msg: Draft14Message & { type: "publish_namespace_ok" },
288
- w: BufferWriter,
289
- ): void {
290
- w.writeVarInt(msg.request_id);
291
- encodeParams(msg.parameters, w);
292
- }
293
-
294
- function encodePublishNamespaceErrorPayload(
295
- msg: Draft14Message & { type: "publish_namespace_error" },
296
- w: BufferWriter,
297
- ): void {
298
- w.writeVarInt(msg.request_id);
299
- w.writeVarInt(msg.error_code);
300
- w.writeString(msg.reason_phrase);
301
- }
302
-
303
- function encodePublishNamespaceDonePayload(
304
- msg: Draft14Message & { type: "publish_namespace_done" },
305
- w: BufferWriter,
306
- ): void {
307
- w.writeVarInt(msg.request_id);
308
- w.writeVarInt(msg.status_code);
309
- w.writeString(msg.reason_phrase);
310
- }
311
-
312
- function encodePublishNamespaceCancelPayload(
313
- msg: Draft14Message & { type: "publish_namespace_cancel" },
314
- w: BufferWriter,
315
- ): void {
316
- w.writeVarInt(msg.request_id);
317
- }
318
-
319
- function encodeSubscribeNamespacePayload(
320
- msg: Draft14Message & { type: "subscribe_namespace" },
321
- w: BufferWriter,
322
- ): void {
323
- w.writeVarInt(msg.request_id);
324
- w.writeTuple(msg.namespace_prefix);
325
- encodeParams(msg.parameters, w);
326
- }
327
-
328
- function encodeSubscribeNamespaceOkPayload(
329
- msg: Draft14Message & { type: "subscribe_namespace_ok" },
330
- w: BufferWriter,
331
- ): void {
332
- w.writeVarInt(msg.request_id);
333
- encodeParams(msg.parameters, w);
334
- }
335
-
336
- function encodeSubscribeNamespaceErrorPayload(
337
- msg: Draft14Message & { type: "subscribe_namespace_error" },
338
- w: BufferWriter,
339
- ): void {
340
- w.writeVarInt(msg.request_id);
341
- w.writeVarInt(msg.error_code);
342
- w.writeString(msg.reason_phrase);
343
- }
344
-
345
- function encodeUnsubscribeNamespacePayload(
346
- msg: Draft14Message & { type: "unsubscribe_namespace" },
347
- w: BufferWriter,
348
- ): void {
349
- w.writeVarInt(msg.request_id);
350
- }
351
-
352
- function encodeFetchPayload(msg: Draft14Message & { type: "fetch" }, w: BufferWriter): void {
353
- w.writeVarInt(msg.request_id);
354
- w.writeTuple(msg.track_namespace);
355
- w.writeString(msg.track_name);
356
- w.writeVarInt(msg.start_group);
357
- w.writeVarInt(msg.start_object);
358
- w.writeVarInt(msg.end_group);
359
- encodeParams(msg.parameters, w);
360
- }
361
-
362
- function encodeFetchOkPayload(msg: Draft14Message & { type: "fetch_ok" }, w: BufferWriter): void {
363
- w.writeVarInt(msg.request_id);
364
- w.writeVarInt(msg.track_alias);
365
- w.writeVarInt(msg.end_of_track);
366
- encodeParams(msg.parameters, w);
367
- }
368
-
369
- function encodeFetchErrorPayload(
370
- msg: Draft14Message & { type: "fetch_error" },
371
- w: BufferWriter,
372
- ): void {
373
- w.writeVarInt(msg.request_id);
374
- w.writeVarInt(msg.error_code);
375
- w.writeString(msg.reason_phrase);
376
- }
377
-
378
- function encodeFetchCancelPayload(
379
- msg: Draft14Message & { type: "fetch_cancel" },
380
- w: BufferWriter,
381
- ): void {
382
- w.writeVarInt(msg.request_id);
383
- }
384
-
385
- function encodeTrackStatusPayload(
386
- msg: Draft14Message & { type: "track_status" },
387
- w: BufferWriter,
388
- ): void {
389
- w.writeVarInt(msg.request_id);
390
- w.writeTuple(msg.track_namespace);
391
- w.writeString(msg.track_name);
392
- encodeParams(msg.parameters, w);
393
- }
394
-
395
- function encodeTrackStatusOkPayload(
396
- msg: Draft14Message & { type: "track_status_ok" },
397
- w: BufferWriter,
398
- ): void {
399
- w.writeVarInt(msg.request_id);
400
- w.writeVarInt(msg.status_code);
401
- const sc = Number(msg.status_code);
402
- if (sc === 0 || sc === 3) {
403
- w.writeVarInt(msg.largest_group!);
404
- w.writeVarInt(msg.largest_object!);
405
- }
406
- encodeParams(msg.parameters, w);
407
- }
408
-
409
- function encodeTrackStatusErrorPayload(
410
- msg: Draft14Message & { type: "track_status_error" },
411
- w: BufferWriter,
412
- ): void {
413
- w.writeVarInt(msg.request_id);
414
- w.writeVarInt(msg.error_code);
415
- w.writeString(msg.reason_phrase);
416
- }
417
-
418
- function encodeGoAwayPayload(msg: Draft14Message & { type: "goaway" }, w: BufferWriter): void {
419
- w.writeString(msg.new_session_uri);
420
- }
421
-
422
- function encodeMaxRequestIdPayload(
423
- msg: Draft14Message & { type: "max_request_id" },
424
- w: BufferWriter,
425
- ): void {
426
- w.writeVarInt(msg.request_id);
427
- }
428
-
429
- function encodeRequestsBlockedPayload(
430
- msg: Draft14Message & { type: "requests_blocked" },
431
- w: BufferWriter,
432
- ): void {
433
- w.writeVarInt(msg.request_id);
434
- }
435
-
436
- // ─── Payload Decoders ──────────────────────────────────────────────────────────
437
-
438
- function decodeClientSetupPayload(r: BufferReader): Draft14Message {
439
- const numVersions = Number(r.readVarInt());
440
- if (numVersions === 0) {
441
- throw new DecodeError(
442
- "CONSTRAINT_VIOLATION",
443
- "CLIENT_SETUP must offer at least one version",
444
- r.offset,
445
- );
446
- }
447
- const supported_versions: bigint[] = [];
448
- for (let i = 0; i < numVersions; i++) {
449
- supported_versions.push(r.readVarInt());
450
- }
451
- const parameters = decodeParams(r);
452
- return { type: "client_setup", supported_versions, parameters };
453
- }
454
-
455
- function decodeServerSetupPayload(r: BufferReader): Draft14Message {
456
- const selected_version = r.readVarInt();
457
- const parameters = decodeParams(r);
458
- return { type: "server_setup", selected_version, parameters };
459
- }
460
-
461
- function decodeSubscribePayload(r: BufferReader): Draft14Message {
462
- const request_id = r.readVarInt();
463
- const track_namespace = r.readTuple();
464
- const track_name = r.readString();
465
- const subscriber_priority = BigInt(r.readUint8());
466
- const group_order = r.readVarInt();
467
- const forward = r.readVarInt();
468
- const filter_type = r.readVarInt();
469
- const ft = Number(filter_type);
470
-
471
- if (ft < 1 || ft > 4) {
472
- throw new DecodeError("CONSTRAINT_VIOLATION", `Invalid filter_type: ${ft}`, r.offset);
473
- }
474
-
475
- let start_group: bigint | undefined;
476
- let start_object: bigint | undefined;
477
- let end_group: bigint | undefined;
478
-
479
- if (ft >= 3) {
480
- start_group = r.readVarInt();
481
- start_object = r.readVarInt();
482
- }
483
- if (ft === 4) {
484
- end_group = r.readVarInt();
485
- }
486
-
487
- const parameters = decodeParams(r);
488
-
489
- const msg: Draft14Message & { type: "subscribe" } = {
490
- type: "subscribe",
491
- request_id,
492
- track_namespace,
493
- track_name,
494
- subscriber_priority,
495
- group_order,
496
- forward,
497
- filter_type,
498
- parameters,
499
- };
500
-
501
- if (start_group !== undefined) {
502
- return { ...msg, start_group, start_object, end_group } as Draft14Message;
503
- }
504
-
505
- return msg;
506
- }
507
-
508
- function decodeSubscribeOkPayload(r: BufferReader): Draft14Message {
509
- const request_id = r.readVarInt();
510
- const track_alias = r.readVarInt();
511
- const expires = r.readVarInt();
512
- const group_order = r.readVarInt();
513
- const content_exists = r.readVarInt();
514
-
515
- let largest_group: bigint | undefined;
516
- let largest_object: bigint | undefined;
517
-
518
- if (Number(content_exists) === 1) {
519
- largest_group = r.readVarInt();
520
- largest_object = r.readVarInt();
521
- }
522
-
523
- const parameters = decodeParams(r);
524
-
525
- const msg: Draft14Message = {
526
- type: "subscribe_ok",
527
- request_id,
528
- track_alias,
529
- expires,
530
- group_order,
531
- content_exists,
532
- parameters,
533
- ...(largest_group !== undefined ? { largest_group, largest_object } : {}),
534
- } as Draft14Message;
535
-
536
- return msg;
537
- }
538
-
539
- function decodeSubscribeUpdatePayload(r: BufferReader): Draft14Message {
540
- const request_id = r.readVarInt();
541
- const start_group = r.readVarInt();
542
- const start_object = r.readVarInt();
543
- const end_group = r.readVarInt();
544
- const subscriber_priority = BigInt(r.readUint8());
545
- const forward = r.readVarInt();
546
- const parameters = decodeParams(r);
547
- return {
548
- type: "subscribe_update",
549
- request_id,
550
- start_group,
551
- start_object,
552
- end_group,
553
- subscriber_priority,
554
- forward,
555
- parameters,
556
- };
557
- }
558
-
559
- function decodeSubscribeErrorPayload(r: BufferReader): Draft14Message {
560
- const request_id = r.readVarInt();
561
- const error_code = r.readVarInt();
562
- const reason_phrase = r.readString();
563
- return { type: "subscribe_error", request_id, error_code, reason_phrase };
564
- }
565
-
566
- function decodeUnsubscribePayload(r: BufferReader): Draft14Message {
567
- const request_id = r.readVarInt();
568
- return { type: "unsubscribe", request_id };
569
- }
570
-
571
- function decodePublishPayload(r: BufferReader): Draft14Message {
572
- const request_id = r.readVarInt();
573
- const track_namespace = r.readTuple();
574
- const track_name = r.readString();
575
- const forward = r.readVarInt();
576
- const parameters = decodeParams(r);
577
- return { type: "publish", request_id, track_namespace, track_name, forward, parameters };
578
- }
579
-
580
- function decodePublishOkPayload(r: BufferReader): Draft14Message {
581
- const request_id = r.readVarInt();
582
- const track_alias = r.readVarInt();
583
- const forward = r.readVarInt();
584
- const parameters = decodeParams(r);
585
- return { type: "publish_ok", request_id, track_alias, forward, parameters };
586
- }
587
-
588
- function decodePublishErrorPayload(r: BufferReader): Draft14Message {
589
- const request_id = r.readVarInt();
590
- const error_code = r.readVarInt();
591
- const reason_phrase = r.readString();
592
- return { type: "publish_error", request_id, error_code, reason_phrase };
593
- }
594
-
595
- function decodePublishDonePayload(r: BufferReader): Draft14Message {
596
- const request_id = r.readVarInt();
597
- const status_code = r.readVarInt();
598
- const reason_phrase = r.readString();
599
- return { type: "publish_done", request_id, status_code, reason_phrase };
600
- }
601
-
602
- function decodePublishNamespacePayload(r: BufferReader): Draft14Message {
603
- const request_id = r.readVarInt();
604
- const track_namespace = r.readTuple();
605
- const parameters = decodeParams(r);
606
- return { type: "publish_namespace", request_id, track_namespace, parameters };
607
- }
608
-
609
- function decodePublishNamespaceOkPayload(r: BufferReader): Draft14Message {
610
- const request_id = r.readVarInt();
611
- const parameters = decodeParams(r);
612
- return { type: "publish_namespace_ok", request_id, parameters };
613
- }
614
-
615
- function decodePublishNamespaceErrorPayload(r: BufferReader): Draft14Message {
616
- const request_id = r.readVarInt();
617
- const error_code = r.readVarInt();
618
- const reason_phrase = r.readString();
619
- return { type: "publish_namespace_error", request_id, error_code, reason_phrase };
620
- }
621
-
622
- function decodePublishNamespaceDonePayload(r: BufferReader): Draft14Message {
623
- const request_id = r.readVarInt();
624
- const status_code = r.readVarInt();
625
- const reason_phrase = r.readString();
626
- return { type: "publish_namespace_done", request_id, status_code, reason_phrase };
627
- }
628
-
629
- function decodePublishNamespaceCancelPayload(r: BufferReader): Draft14Message {
630
- const request_id = r.readVarInt();
631
- return { type: "publish_namespace_cancel", request_id };
632
- }
633
-
634
- function decodeSubscribeNamespacePayload(r: BufferReader): Draft14Message {
635
- const request_id = r.readVarInt();
636
- const namespace_prefix = r.readTuple();
637
- const parameters = decodeParams(r);
638
- return { type: "subscribe_namespace", request_id, namespace_prefix, parameters };
639
- }
640
-
641
- function decodeSubscribeNamespaceOkPayload(r: BufferReader): Draft14Message {
642
- const request_id = r.readVarInt();
643
- const parameters = decodeParams(r);
644
- return { type: "subscribe_namespace_ok", request_id, parameters };
645
- }
646
-
647
- function decodeSubscribeNamespaceErrorPayload(r: BufferReader): Draft14Message {
648
- const request_id = r.readVarInt();
649
- const error_code = r.readVarInt();
650
- const reason_phrase = r.readString();
651
- return { type: "subscribe_namespace_error", request_id, error_code, reason_phrase };
652
- }
653
-
654
- function decodeUnsubscribeNamespacePayload(r: BufferReader): Draft14Message {
655
- const request_id = r.readVarInt();
656
- return { type: "unsubscribe_namespace", request_id };
657
- }
658
-
659
- function decodeFetchPayload(r: BufferReader): Draft14Message {
660
- const request_id = r.readVarInt();
661
- const track_namespace = r.readTuple();
662
- const track_name = r.readString();
663
- const start_group = r.readVarInt();
664
- const start_object = r.readVarInt();
665
- const end_group = r.readVarInt();
666
- const parameters = decodeParams(r);
667
- return {
668
- type: "fetch",
669
- request_id,
670
- track_namespace,
671
- track_name,
672
- start_group,
673
- start_object,
674
- end_group,
675
- parameters,
676
- };
677
- }
678
-
679
- function decodeFetchOkPayload(r: BufferReader): Draft14Message {
680
- const request_id = r.readVarInt();
681
- const track_alias = r.readVarInt();
682
- const end_of_track = r.readVarInt();
683
- const parameters = decodeParams(r);
684
- return { type: "fetch_ok", request_id, track_alias, end_of_track, parameters };
685
- }
686
-
687
- function decodeFetchErrorPayload(r: BufferReader): Draft14Message {
688
- const request_id = r.readVarInt();
689
- const error_code = r.readVarInt();
690
- const reason_phrase = r.readString();
691
- return { type: "fetch_error", request_id, error_code, reason_phrase };
692
- }
693
-
694
- function decodeFetchCancelPayload(r: BufferReader): Draft14Message {
695
- const request_id = r.readVarInt();
696
- return { type: "fetch_cancel", request_id };
697
- }
698
-
699
- function decodeTrackStatusPayload(r: BufferReader): Draft14Message {
700
- const request_id = r.readVarInt();
701
- const track_namespace = r.readTuple();
702
- const track_name = r.readString();
703
- const parameters = decodeParams(r);
704
- return { type: "track_status", request_id, track_namespace, track_name, parameters };
705
- }
706
-
707
- function decodeTrackStatusOkPayload(r: BufferReader): Draft14Message {
708
- const request_id = r.readVarInt();
709
- const status_code = r.readVarInt();
710
- const sc = Number(status_code);
711
-
712
- let largest_group: bigint | undefined;
713
- let largest_object: bigint | undefined;
714
-
715
- if (sc === 0 || sc === 3) {
716
- largest_group = r.readVarInt();
717
- largest_object = r.readVarInt();
718
- }
719
-
720
- const parameters = decodeParams(r);
721
-
722
- return {
723
- type: "track_status_ok",
724
- request_id,
725
- status_code,
726
- parameters,
727
- ...(largest_group !== undefined ? { largest_group, largest_object } : {}),
728
- } as Draft14Message;
729
- }
730
-
731
- function decodeTrackStatusErrorPayload(r: BufferReader): Draft14Message {
732
- const request_id = r.readVarInt();
733
- const error_code = r.readVarInt();
734
- const reason_phrase = r.readString();
735
- return { type: "track_status_error", request_id, error_code, reason_phrase };
736
- }
737
-
738
- function decodeGoAwayPayload(r: BufferReader): Draft14Message {
739
- const new_session_uri = r.readString();
740
- return { type: "goaway", new_session_uri };
741
- }
742
-
743
- function decodeMaxRequestIdPayload(r: BufferReader): Draft14Message {
744
- const request_id = r.readVarInt();
745
- return { type: "max_request_id", request_id };
746
- }
747
-
748
- function decodeRequestsBlockedPayload(r: BufferReader): Draft14Message {
749
- const request_id = r.readVarInt();
750
- return { type: "requests_blocked", request_id };
751
- }
752
-
753
- // ─── Payload dispatch tables ───────────────────────────────────────────────────
754
-
755
- const payloadDecoders: ReadonlyMap<bigint, (r: BufferReader) => Draft14Message> = new Map([
756
- [MSG_CLIENT_SETUP, decodeClientSetupPayload],
757
- [MSG_SERVER_SETUP, decodeServerSetupPayload],
758
- [MSG_SUBSCRIBE, decodeSubscribePayload],
759
- [MSG_SUBSCRIBE_OK, decodeSubscribeOkPayload],
760
- [MSG_SUBSCRIBE_UPDATE, decodeSubscribeUpdatePayload],
761
- [MSG_SUBSCRIBE_ERROR, decodeSubscribeErrorPayload],
762
- [MSG_UNSUBSCRIBE, decodeUnsubscribePayload],
763
- [MSG_PUBLISH, decodePublishPayload],
764
- [MSG_PUBLISH_OK, decodePublishOkPayload],
765
- [MSG_PUBLISH_ERROR, decodePublishErrorPayload],
766
- [MSG_PUBLISH_DONE, decodePublishDonePayload],
767
- [MSG_PUBLISH_NAMESPACE, decodePublishNamespacePayload],
768
- [MSG_PUBLISH_NAMESPACE_OK, decodePublishNamespaceOkPayload],
769
- [MSG_PUBLISH_NAMESPACE_ERROR, decodePublishNamespaceErrorPayload],
770
- [MSG_PUBLISH_NAMESPACE_DONE, decodePublishNamespaceDonePayload],
771
- [MSG_PUBLISH_NAMESPACE_CANCEL, decodePublishNamespaceCancelPayload],
772
- [MSG_SUBSCRIBE_NAMESPACE, decodeSubscribeNamespacePayload],
773
- [MSG_SUBSCRIBE_NAMESPACE_OK, decodeSubscribeNamespaceOkPayload],
774
- [MSG_SUBSCRIBE_NAMESPACE_ERROR, decodeSubscribeNamespaceErrorPayload],
775
- [MSG_UNSUBSCRIBE_NAMESPACE, decodeUnsubscribeNamespacePayload],
776
- [MSG_FETCH, decodeFetchPayload],
777
- [MSG_FETCH_OK, decodeFetchOkPayload],
778
- [MSG_FETCH_ERROR, decodeFetchErrorPayload],
779
- [MSG_FETCH_CANCEL, decodeFetchCancelPayload],
780
- [MSG_TRACK_STATUS, decodeTrackStatusPayload],
781
- [MSG_TRACK_STATUS_OK, decodeTrackStatusOkPayload],
782
- [MSG_TRACK_STATUS_ERROR, decodeTrackStatusErrorPayload],
783
- [MSG_GOAWAY, decodeGoAwayPayload],
784
- [MSG_MAX_REQUEST_ID, decodeMaxRequestIdPayload],
785
- [MSG_REQUESTS_BLOCKED, decodeRequestsBlockedPayload],
786
- ]);
787
-
788
- // ─── Public API ────────────────────────────────────────────────────────────────
789
-
790
- /**
791
- * Encode a draft-14 control message with type(varint) + length(uint16 BE) + payload.
792
- */
793
- export function encodeMessage(message: Draft14Message): Uint8Array {
794
- const typeId = MESSAGE_ID_MAP.get(message.type);
795
- if (typeId === undefined) {
796
- throw new Error(`Unknown message type: ${message.type}`);
797
- }
798
-
799
- // Encode payload into a separate buffer
800
- const payloadWriter = new BufferWriter();
801
- encodePayload(message, payloadWriter);
802
- const payload = payloadWriter.finishView();
803
-
804
- if (payload.byteLength > 0xffff) {
805
- throw new Error(`Payload too large for 16-bit length: ${payload.byteLength}`);
806
- }
807
-
808
- // Write framed message: type(varint) + length(uint16 BE) + payload
809
- const writer = new BufferWriter(payload.byteLength + 16);
810
- writer.writeVarInt(typeId);
811
- writer.writeUint8((payload.byteLength >> 8) & 0xff);
812
- writer.writeUint8(payload.byteLength & 0xff);
813
- writer.writeBytes(payload);
814
-
815
- return writer.finish();
816
- }
817
-
818
- function encodePayload(msg: Draft14Message, w: BufferWriter): void {
819
- switch (msg.type) {
820
- case "client_setup":
821
- return encodeClientSetupPayload(msg, w);
822
- case "server_setup":
823
- return encodeServerSetupPayload(msg, w);
824
- case "subscribe":
825
- return encodeSubscribePayload(msg, w);
826
- case "subscribe_ok":
827
- return encodeSubscribeOkPayload(msg, w);
828
- case "subscribe_update":
829
- return encodeSubscribeUpdatePayload(msg, w);
830
- case "subscribe_error":
831
- return encodeSubscribeErrorPayload(msg, w);
832
- case "unsubscribe":
833
- return encodeUnsubscribePayload(msg, w);
834
- case "publish":
835
- return encodePublishPayload(msg, w);
836
- case "publish_ok":
837
- return encodePublishOkPayload(msg, w);
838
- case "publish_error":
839
- return encodePublishErrorPayload(msg, w);
840
- case "publish_done":
841
- return encodePublishDonePayload(msg, w);
842
- case "publish_namespace":
843
- return encodePublishNamespacePayload(msg, w);
844
- case "publish_namespace_ok":
845
- return encodePublishNamespaceOkPayload(msg, w);
846
- case "publish_namespace_error":
847
- return encodePublishNamespaceErrorPayload(msg, w);
848
- case "publish_namespace_done":
849
- return encodePublishNamespaceDonePayload(msg, w);
850
- case "publish_namespace_cancel":
851
- return encodePublishNamespaceCancelPayload(msg, w);
852
- case "subscribe_namespace":
853
- return encodeSubscribeNamespacePayload(msg, w);
854
- case "subscribe_namespace_ok":
855
- return encodeSubscribeNamespaceOkPayload(msg, w);
856
- case "subscribe_namespace_error":
857
- return encodeSubscribeNamespaceErrorPayload(msg, w);
858
- case "unsubscribe_namespace":
859
- return encodeUnsubscribeNamespacePayload(msg, w);
860
- case "fetch":
861
- return encodeFetchPayload(msg, w);
862
- case "fetch_ok":
863
- return encodeFetchOkPayload(msg, w);
864
- case "fetch_error":
865
- return encodeFetchErrorPayload(msg, w);
866
- case "fetch_cancel":
867
- return encodeFetchCancelPayload(msg, w);
868
- case "track_status":
869
- return encodeTrackStatusPayload(msg, w);
870
- case "track_status_ok":
871
- return encodeTrackStatusOkPayload(msg, w);
872
- case "track_status_error":
873
- return encodeTrackStatusErrorPayload(msg, w);
874
- case "goaway":
875
- return encodeGoAwayPayload(msg, w);
876
- case "max_request_id":
877
- return encodeMaxRequestIdPayload(msg, w);
878
- case "requests_blocked":
879
- return encodeRequestsBlockedPayload(msg, w);
880
- default: {
881
- const _exhaustive: never = msg;
882
- throw new Error(`Unhandled message type: ${(_exhaustive as Draft14Message).type}`);
883
- }
884
- }
885
- }
886
-
887
- /**
888
- * Decode a draft-14 control message from bytes (type + uint16 length + payload).
889
- */
890
- export function decodeMessage(bytes: Uint8Array): DecodeResult<Draft14Message> {
891
- try {
892
- const reader = new BufferReader(bytes);
893
- const typeId = reader.readVarInt();
894
-
895
- // Read 16-bit big-endian payload length
896
- const lenHi = reader.readUint8();
897
- const lenLo = reader.readUint8();
898
- const payloadLength = (lenHi << 8) | lenLo;
899
-
900
- // Read exactly payloadLength bytes
901
- const payloadBytes = reader.readBytes(payloadLength);
902
- const payloadReader = new BufferReader(payloadBytes);
903
-
904
- const decoder = payloadDecoders.get(typeId);
905
- if (!decoder) {
906
- return {
907
- ok: false,
908
- error: new DecodeError(
909
- "UNKNOWN_MESSAGE_TYPE",
910
- `Unknown message type ID: 0x${typeId.toString(16)}`,
911
- 0,
912
- ),
913
- };
914
- }
915
-
916
- const message = decoder(payloadReader);
917
- return { ok: true, value: message, bytesRead: reader.offset };
918
- } catch (e) {
919
- if (e instanceof DecodeError) {
920
- return { ok: false, error: e };
921
- }
922
- throw e;
923
- }
924
- }
925
-
926
- // ─── Data Stream Re-exports ───────────────────────────────────────────────────
927
-
928
- import {
929
- encodeSubgroupStream,
930
- decodeSubgroupStream,
931
- encodeDatagram,
932
- decodeDatagram,
933
- encodeFetchStream,
934
- decodeFetchStream,
935
- decodeDataStream,
936
- createSubgroupStreamDecoder,
937
- createFetchStreamDecoder,
938
- createDataStreamDecoder,
939
- } from "./data-streams.js";
940
-
941
- export {
942
- encodeSubgroupStream,
943
- decodeSubgroupStream,
944
- encodeDatagram,
945
- decodeDatagram,
946
- encodeFetchStream,
947
- decodeFetchStream,
948
- decodeDataStream,
949
- createSubgroupStreamDecoder,
950
- createFetchStreamDecoder,
951
- createDataStreamDecoder,
952
- };
953
-
954
- // ─── Stream Decoders ───────────────────────────────────────────────────────────
955
-
956
- /**
957
- * Create a TransformStream that decodes a continuous byte stream (e.g. the
958
- * WebTransport bidirectional control stream) into individual Draft14Message
959
- * objects. Uses the varint(type) + uint16_BE(length) + payload framing.
960
- */
961
- export function createStreamDecoder(): TransformStream<Uint8Array, Draft14Message> {
962
- let buffer = new Uint8Array(0);
963
- let offset = 0;
964
-
965
- return new TransformStream<Uint8Array, Draft14Message>({
966
- transform(chunk, controller) {
967
- // Compact before accumulating new data
968
- if (offset > 0) {
969
- buffer = buffer.subarray(offset);
970
- offset = 0;
971
- }
972
- const newBuffer = new Uint8Array(buffer.length + chunk.length);
973
- newBuffer.set(buffer, 0);
974
- newBuffer.set(chunk, buffer.length);
975
- buffer = newBuffer;
976
-
977
- // Try to decode messages from the buffer
978
- while (offset < buffer.length) {
979
- const result = decodeMessage(buffer.subarray(offset));
980
- if (!result.ok) {
981
- if (result.error.code === "UNEXPECTED_END") {
982
- // Need more data -- wait for next chunk
983
- break;
984
- }
985
- // Fatal decode error
986
- controller.error(result.error);
987
- return;
988
- }
989
- controller.enqueue(result.value);
990
- // Advance offset past the consumed bytes
991
- offset += result.bytesRead;
992
- }
993
- },
994
-
995
- flush(controller) {
996
- // If there is remaining data in the buffer, it is a truncated message
997
- if (offset < buffer.length) {
998
- controller.error(
999
- new DecodeError("UNEXPECTED_END", "Stream ended with incomplete message data", 0),
1000
- );
1001
- }
1002
- },
1003
- });
1004
- }
1005
-
1006
- // ─── Codec Factory ─────────────────────────────────────────────────────────────
1007
-
1008
- export interface Draft14Codec extends BaseCodec<Draft14Message> {
1009
- readonly draft: "draft-ietf-moq-transport-14";
1010
- encodeSubgroupStream(stream: SubgroupStream): Uint8Array;
1011
- encodeDatagram(dg: DatagramObject): Uint8Array;
1012
- encodeFetchStream(stream: FetchStream): Uint8Array;
1013
- decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream>;
1014
- decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject>;
1015
- decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream>;
1016
- decodeDataStream(
1017
- streamType: "subgroup" | "datagram" | "fetch",
1018
- bytes: Uint8Array,
1019
- ): DecodeResult<Draft14DataStream>;
1020
- createStreamDecoder(): TransformStream<Uint8Array, Draft14Message>;
1021
- createSubgroupStreamDecoder(): TransformStream<Uint8Array, SubgroupStreamHeader | ObjectPayload>;
1022
- createFetchStreamDecoder(): TransformStream<Uint8Array, FetchStreamHeader | ObjectPayload>;
1023
- createDataStreamDecoder(): TransformStream<Uint8Array, DataStreamEvent>;
1024
- }
1025
-
1026
- export function createDraft14Codec(): Draft14Codec {
1027
- return {
1028
- draft: "draft-ietf-moq-transport-14",
1029
- encodeMessage,
1030
- decodeMessage,
1031
- encodeSubgroupStream,
1032
- encodeDatagram,
1033
- encodeFetchStream,
1034
- decodeSubgroupStream,
1035
- decodeDatagram,
1036
- decodeFetchStream,
1037
- decodeDataStream,
1038
- createStreamDecoder,
1039
- createSubgroupStreamDecoder,
1040
- createFetchStreamDecoder,
1041
- createDataStreamDecoder,
1042
- };
1043
- }
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
+ MESSAGE_ID_MAP,
8
+ MSG_CLIENT_SETUP,
9
+ MSG_FETCH,
10
+ MSG_FETCH_CANCEL,
11
+ MSG_FETCH_ERROR,
12
+ MSG_FETCH_OK,
13
+ MSG_GOAWAY,
14
+ MSG_MAX_REQUEST_ID,
15
+ MSG_PUBLISH,
16
+ MSG_PUBLISH_DONE,
17
+ MSG_PUBLISH_ERROR,
18
+ MSG_PUBLISH_NAMESPACE,
19
+ MSG_PUBLISH_NAMESPACE_CANCEL,
20
+ MSG_PUBLISH_NAMESPACE_DONE,
21
+ MSG_PUBLISH_NAMESPACE_ERROR,
22
+ MSG_PUBLISH_NAMESPACE_OK,
23
+ MSG_PUBLISH_OK,
24
+ MSG_REQUESTS_BLOCKED,
25
+ MSG_SERVER_SETUP,
26
+ MSG_SUBSCRIBE,
27
+ MSG_SUBSCRIBE_ERROR,
28
+ MSG_SUBSCRIBE_NAMESPACE,
29
+ MSG_SUBSCRIBE_NAMESPACE_ERROR,
30
+ MSG_SUBSCRIBE_NAMESPACE_OK,
31
+ MSG_SUBSCRIBE_OK,
32
+ MSG_SUBSCRIBE_UPDATE,
33
+ MSG_TRACK_STATUS,
34
+ MSG_TRACK_STATUS_ERROR,
35
+ MSG_TRACK_STATUS_OK,
36
+ MSG_UNSUBSCRIBE,
37
+ MSG_UNSUBSCRIBE_NAMESPACE,
38
+ PARAM_MAX_REQUEST_ID,
39
+ PARAM_PATH,
40
+ PARAM_ROLE,
41
+ } from './messages.js'
42
+ import type {
43
+ AuthorizationToken,
44
+ DatagramObject,
45
+ DataStreamEvent,
46
+ Draft14DataStream,
47
+ Draft14Message,
48
+ Draft14Params,
49
+ FetchStream,
50
+ FetchStreamHeader,
51
+ Location,
52
+ ObjectPayload,
53
+ SubgroupStream,
54
+ SubgroupStreamHeader,
55
+ UnknownParam,
56
+ } from './types.js'
57
+ import { FetchType, FilterType } from './types.js'
58
+
59
+ const textEncoder = /* @__PURE__ */ new TextEncoder()
60
+ const textDecoder = /* @__PURE__ */ new TextDecoder()
61
+
62
+ // ─── Parameter Constants ──────────────────────────────────────────────────────
63
+
64
+ // Setup-only parameter IDs (CLIENT_SETUP / SERVER_SETUP)
65
+ const PARAM_AUTHORITY = 0x05n
66
+ const PARAM_MAX_AUTH_TOKEN_CACHE_SIZE = 0x04n
67
+
68
+ // Message parameter IDs (SUBSCRIBE, PUBLISH, etc.)
69
+ const PARAM_DELIVERY_TIMEOUT = 0x02n
70
+ const PARAM_AUTHORIZATION_TOKEN = 0x03n
71
+ const PARAM_MAX_CACHE_DURATION = 0x04n
72
+
73
+ // ─── Parameter Encoding/Decoding ───────────────────────────────────────────────
74
+
75
+ function encodeSetupParams(params: Draft14Params, writer: BufferWriter): void {
76
+ let count = 0
77
+ if (params.role !== undefined) count++
78
+ if (params.path !== undefined) count++
79
+ if (params.max_request_id !== undefined) count++
80
+ if (params.authority !== undefined) count++
81
+ if (params.max_auth_token_cache_size !== undefined) count++
82
+ if (params.unknown) count += params.unknown.length
83
+
84
+ writer.writeVarInt(count)
85
+
86
+ if (params.role !== undefined) {
87
+ writer.writeVarInt(PARAM_ROLE)
88
+ writer.writeVarInt(params.role)
89
+ }
90
+ if (params.path !== undefined) {
91
+ writer.writeVarInt(PARAM_PATH)
92
+ const encoded = textEncoder.encode(params.path)
93
+ writer.writeVarInt(encoded.byteLength)
94
+ writer.writeBytes(encoded)
95
+ }
96
+ if (params.max_request_id !== undefined) {
97
+ writer.writeVarInt(PARAM_MAX_REQUEST_ID)
98
+ writer.writeVarInt(params.max_request_id)
99
+ }
100
+ if (params.max_auth_token_cache_size !== undefined) {
101
+ writer.writeVarInt(PARAM_MAX_AUTH_TOKEN_CACHE_SIZE)
102
+ writer.writeVarInt(params.max_auth_token_cache_size)
103
+ }
104
+ if (params.authority !== undefined) {
105
+ writer.writeVarInt(PARAM_AUTHORITY)
106
+ const encoded = textEncoder.encode(params.authority)
107
+ writer.writeVarInt(encoded.byteLength)
108
+ writer.writeBytes(encoded)
109
+ }
110
+ if (params.unknown) {
111
+ for (const u of params.unknown) {
112
+ const id = BigInt(u.id)
113
+ writer.writeVarInt(id)
114
+ const raw = hexToBytes(u.raw_hex)
115
+ writer.writeVarInt(raw.byteLength)
116
+ writer.writeBytes(raw)
117
+ }
118
+ }
119
+ }
120
+
121
+ function decodeSetupParams(reader: BufferReader): Draft14Params {
122
+ const count = Number(reader.readVarInt())
123
+ const result: Draft14Params = {}
124
+ const unknown: UnknownParam[] = []
125
+
126
+ for (let i = 0; i < count; i++) {
127
+ const paramType = reader.readVarInt()
128
+
129
+ if (paramType % 2n === 0n) {
130
+ const value = reader.readVarInt()
131
+ if (paramType === PARAM_ROLE) {
132
+ result.role = value
133
+ } else if (paramType === PARAM_MAX_REQUEST_ID) {
134
+ result.max_request_id = value
135
+ } else if (paramType === PARAM_MAX_AUTH_TOKEN_CACHE_SIZE) {
136
+ result.max_auth_token_cache_size = value
137
+ } else {
138
+ const tmpWriter = new BufferWriter(16)
139
+ tmpWriter.writeVarInt(value)
140
+ const raw = tmpWriter.finish()
141
+ unknown.push({
142
+ id: `0x${paramType.toString(16)}`,
143
+ length: raw.byteLength,
144
+ raw_hex: bytesToHex(raw),
145
+ })
146
+ }
147
+ } else {
148
+ const length = Number(reader.readVarInt())
149
+ const bytes = reader.readBytes(length)
150
+ if (paramType === PARAM_PATH) {
151
+ result.path = textDecoder.decode(bytes)
152
+ } else if (paramType === PARAM_AUTHORITY) {
153
+ result.authority = textDecoder.decode(bytes)
154
+ } else {
155
+ unknown.push({
156
+ id: `0x${paramType.toString(16)}`,
157
+ length,
158
+ raw_hex: bytesToHex(bytes),
159
+ })
160
+ }
161
+ }
162
+ }
163
+
164
+ if (unknown.length > 0) result.unknown = unknown
165
+ return result
166
+ }
167
+
168
+ function encodeMessageParams(params: Draft14Params, writer: BufferWriter): void {
169
+ let count = 0
170
+ if (params.delivery_timeout !== undefined) count++
171
+ if (params.authorization_token !== undefined) count++
172
+ if (params.max_cache_duration !== undefined) count++
173
+ if (params.unknown) count += params.unknown.length
174
+
175
+ writer.writeVarInt(count)
176
+
177
+ if (params.delivery_timeout !== undefined) {
178
+ writer.writeVarInt(PARAM_DELIVERY_TIMEOUT)
179
+ writer.writeVarInt(params.delivery_timeout)
180
+ }
181
+ if (params.authorization_token !== undefined) {
182
+ writer.writeVarInt(PARAM_AUTHORIZATION_TOKEN)
183
+ const tok = params.authorization_token
184
+ const tmpWriter = new BufferWriter(64)
185
+ tmpWriter.writeVarInt(tok.alias_type)
186
+ if (tok.token_type !== undefined) {
187
+ tmpWriter.writeVarInt(tok.token_type)
188
+ }
189
+ if (tok.token_value !== undefined) {
190
+ tmpWriter.writeBytes(hexToBytes(tok.token_value))
191
+ }
192
+ if (tok.token_alias !== undefined) {
193
+ tmpWriter.writeVarInt(tok.token_alias)
194
+ }
195
+ const tokenBytes = tmpWriter.finish()
196
+ writer.writeVarInt(tokenBytes.byteLength)
197
+ writer.writeBytes(tokenBytes)
198
+ }
199
+ if (params.max_cache_duration !== undefined) {
200
+ writer.writeVarInt(PARAM_MAX_CACHE_DURATION)
201
+ writer.writeVarInt(params.max_cache_duration)
202
+ }
203
+ if (params.unknown) {
204
+ for (const u of params.unknown) {
205
+ const id = BigInt(u.id)
206
+ writer.writeVarInt(id)
207
+ const raw = hexToBytes(u.raw_hex)
208
+ writer.writeVarInt(raw.byteLength)
209
+ writer.writeBytes(raw)
210
+ }
211
+ }
212
+ }
213
+
214
+ function decodeMessageParams(reader: BufferReader): Draft14Params {
215
+ const count = Number(reader.readVarInt())
216
+ const result: Draft14Params = {}
217
+ const unknown: UnknownParam[] = []
218
+
219
+ for (let i = 0; i < count; i++) {
220
+ const paramType = reader.readVarInt()
221
+
222
+ if (paramType % 2n === 0n) {
223
+ const value = reader.readVarInt()
224
+ if (paramType === PARAM_DELIVERY_TIMEOUT) {
225
+ result.delivery_timeout = value
226
+ } else if (paramType === PARAM_MAX_CACHE_DURATION) {
227
+ result.max_cache_duration = value
228
+ } else {
229
+ const tmpWriter = new BufferWriter(16)
230
+ tmpWriter.writeVarInt(value)
231
+ const raw = tmpWriter.finish()
232
+ unknown.push({
233
+ id: `0x${paramType.toString(16)}`,
234
+ length: raw.byteLength,
235
+ raw_hex: bytesToHex(raw),
236
+ })
237
+ }
238
+ } else {
239
+ const length = Number(reader.readVarInt())
240
+ const bytes = reader.readBytes(length)
241
+ if (paramType === PARAM_AUTHORIZATION_TOKEN) {
242
+ const tokenReader = new BufferReader(bytes)
243
+ const alias_type = tokenReader.readVarInt()
244
+ const tok: Record<string, unknown> = { alias_type }
245
+ if (tokenReader.remaining > 0) {
246
+ tok.token_type = tokenReader.readVarInt()
247
+ if (tokenReader.remaining > 0) {
248
+ const tokenValue = tokenReader.readBytesView(tokenReader.remaining)
249
+ tok.token_value = bytesToHex(tokenValue)
250
+ }
251
+ }
252
+ result.authorization_token = tok as unknown as AuthorizationToken
253
+ } else {
254
+ unknown.push({
255
+ id: `0x${paramType.toString(16)}`,
256
+ length,
257
+ raw_hex: bytesToHex(bytes),
258
+ })
259
+ }
260
+ }
261
+ }
262
+
263
+ if (unknown.length > 0) result.unknown = unknown
264
+ return result
265
+ }
266
+
267
+ // ─── Payload Encoders ──────────────────────────────────────────────────────────
268
+
269
+ function encodeClientSetupPayload(
270
+ msg: Draft14Message & { type: 'client_setup' },
271
+ w: BufferWriter,
272
+ ): void {
273
+ w.writeVarInt(msg.supported_versions.length)
274
+ for (const v of msg.supported_versions) {
275
+ w.writeVarInt(v)
276
+ }
277
+ encodeSetupParams(msg.parameters, w)
278
+ }
279
+
280
+ function encodeServerSetupPayload(
281
+ msg: Draft14Message & { type: 'server_setup' },
282
+ w: BufferWriter,
283
+ ): void {
284
+ w.writeVarInt(msg.selected_version)
285
+ encodeSetupParams(msg.parameters, w)
286
+ }
287
+
288
+ function encodeSubscribePayload(
289
+ msg: Draft14Message & { type: 'subscribe' },
290
+ w: BufferWriter,
291
+ ): void {
292
+ w.writeVarInt(msg.request_id)
293
+ w.writeTuple(msg.track_namespace)
294
+ w.writeString(msg.track_name)
295
+ w.writeUint8(Number(msg.subscriber_priority))
296
+ w.writeUint8(Number(msg.group_order))
297
+ w.writeVarInt(msg.forward)
298
+ w.writeVarInt(msg.filter_type)
299
+ const ft = msg.filter_type
300
+ if (ft >= FilterType.AbsoluteStart) {
301
+ w.writeVarInt(msg.start_group!)
302
+ w.writeVarInt(msg.start_object!)
303
+ }
304
+ if (ft === FilterType.AbsoluteRange) {
305
+ w.writeVarInt(msg.end_group!)
306
+ }
307
+ encodeMessageParams(msg.parameters, w)
308
+ }
309
+
310
+ function encodeSubscribeOkPayload(
311
+ msg: Draft14Message & { type: 'subscribe_ok' },
312
+ w: BufferWriter,
313
+ ): void {
314
+ w.writeVarInt(msg.request_id)
315
+ w.writeVarInt(msg.track_alias)
316
+ w.writeVarInt(msg.expires)
317
+ w.writeUint8(Number(msg.group_order))
318
+ w.writeVarInt(msg.content_exists)
319
+ if (msg.content_exists === 1n) {
320
+ w.writeVarInt(msg.largest_location!.group)
321
+ w.writeVarInt(msg.largest_location!.object)
322
+ }
323
+ encodeMessageParams(msg.parameters, w)
324
+ }
325
+
326
+ function encodeSubscribeUpdatePayload(
327
+ msg: Draft14Message & { type: 'subscribe_update' },
328
+ w: BufferWriter,
329
+ ): void {
330
+ w.writeVarInt(msg.request_id)
331
+ w.writeVarInt(msg.subscription_request_id)
332
+ w.writeVarInt(msg.start_group)
333
+ w.writeVarInt(msg.start_object)
334
+ w.writeVarInt(msg.end_group)
335
+ w.writeUint8(Number(msg.subscriber_priority))
336
+ w.writeVarInt(msg.forward)
337
+ encodeMessageParams(msg.parameters, w)
338
+ }
339
+
340
+ function encodeSubscribeErrorPayload(
341
+ msg: Draft14Message & { type: 'subscribe_error' },
342
+ w: BufferWriter,
343
+ ): void {
344
+ w.writeVarInt(msg.request_id)
345
+ w.writeVarInt(msg.error_code)
346
+ w.writeString(msg.reason_phrase)
347
+ }
348
+
349
+ function encodeUnsubscribePayload(
350
+ msg: Draft14Message & { type: 'unsubscribe' },
351
+ w: BufferWriter,
352
+ ): void {
353
+ w.writeVarInt(msg.request_id)
354
+ }
355
+
356
+ function encodePublishPayload(msg: Draft14Message & { type: 'publish' }, w: BufferWriter): void {
357
+ w.writeVarInt(msg.request_id)
358
+ w.writeTuple(msg.track_namespace)
359
+ w.writeString(msg.track_name)
360
+ w.writeVarInt(msg.track_alias)
361
+ w.writeUint8(Number(msg.group_order))
362
+ w.writeVarInt(msg.content_exists)
363
+ if (msg.content_exists === 1n) {
364
+ w.writeVarInt(msg.largest_location!.group)
365
+ w.writeVarInt(msg.largest_location!.object)
366
+ }
367
+ w.writeVarInt(msg.forward)
368
+ encodeMessageParams(msg.parameters, w)
369
+ }
370
+
371
+ function encodePublishOkPayload(
372
+ msg: Draft14Message & { type: 'publish_ok' },
373
+ w: BufferWriter,
374
+ ): void {
375
+ w.writeVarInt(msg.request_id)
376
+ w.writeVarInt(msg.forward)
377
+ w.writeUint8(Number(msg.subscriber_priority))
378
+ w.writeUint8(Number(msg.group_order))
379
+ w.writeVarInt(msg.filter_type)
380
+ const ft = msg.filter_type
381
+ if (ft >= FilterType.AbsoluteStart) {
382
+ w.writeVarInt(msg.start_group!)
383
+ w.writeVarInt(msg.start_object!)
384
+ }
385
+ if (ft === FilterType.AbsoluteRange) {
386
+ w.writeVarInt(msg.end_group!)
387
+ }
388
+ encodeMessageParams(msg.parameters, w)
389
+ }
390
+
391
+ function encodePublishErrorPayload(
392
+ msg: Draft14Message & { type: 'publish_error' },
393
+ w: BufferWriter,
394
+ ): void {
395
+ w.writeVarInt(msg.request_id)
396
+ w.writeVarInt(msg.error_code)
397
+ w.writeString(msg.reason_phrase)
398
+ }
399
+
400
+ function encodePublishDonePayload(
401
+ msg: Draft14Message & { type: 'publish_done' },
402
+ w: BufferWriter,
403
+ ): void {
404
+ w.writeVarInt(msg.request_id)
405
+ w.writeVarInt(msg.status_code)
406
+ w.writeVarInt(msg.stream_count)
407
+ w.writeString(msg.reason_phrase)
408
+ }
409
+
410
+ function encodePublishNamespacePayload(
411
+ msg: Draft14Message & { type: 'publish_namespace' },
412
+ w: BufferWriter,
413
+ ): void {
414
+ w.writeVarInt(msg.request_id)
415
+ w.writeTuple(msg.track_namespace)
416
+ encodeMessageParams(msg.parameters, w)
417
+ }
418
+
419
+ function encodePublishNamespaceOkPayload(
420
+ msg: Draft14Message & { type: 'publish_namespace_ok' },
421
+ w: BufferWriter,
422
+ ): void {
423
+ w.writeVarInt(msg.request_id)
424
+ encodeMessageParams(msg.parameters, w)
425
+ }
426
+
427
+ function encodePublishNamespaceErrorPayload(
428
+ msg: Draft14Message & { type: 'publish_namespace_error' },
429
+ w: BufferWriter,
430
+ ): void {
431
+ w.writeVarInt(msg.request_id)
432
+ w.writeVarInt(msg.error_code)
433
+ w.writeString(msg.reason_phrase)
434
+ }
435
+
436
+ function encodePublishNamespaceDonePayload(
437
+ msg: Draft14Message & { type: 'publish_namespace_done' },
438
+ w: BufferWriter,
439
+ ): void {
440
+ w.writeTuple(msg.track_namespace)
441
+ }
442
+
443
+ function encodePublishNamespaceCancelPayload(
444
+ msg: Draft14Message & { type: 'publish_namespace_cancel' },
445
+ w: BufferWriter,
446
+ ): void {
447
+ w.writeTuple(msg.track_namespace)
448
+ w.writeVarInt(msg.error_code)
449
+ w.writeString(msg.reason_phrase)
450
+ }
451
+
452
+ function encodeSubscribeNamespacePayload(
453
+ msg: Draft14Message & { type: 'subscribe_namespace' },
454
+ w: BufferWriter,
455
+ ): void {
456
+ w.writeVarInt(msg.request_id)
457
+ w.writeTuple(msg.namespace_prefix)
458
+ encodeMessageParams(msg.parameters, w)
459
+ }
460
+
461
+ function encodeSubscribeNamespaceOkPayload(
462
+ msg: Draft14Message & { type: 'subscribe_namespace_ok' },
463
+ w: BufferWriter,
464
+ ): void {
465
+ w.writeVarInt(msg.request_id)
466
+ encodeMessageParams(msg.parameters, w)
467
+ }
468
+
469
+ function encodeSubscribeNamespaceErrorPayload(
470
+ msg: Draft14Message & { type: 'subscribe_namespace_error' },
471
+ w: BufferWriter,
472
+ ): void {
473
+ w.writeVarInt(msg.request_id)
474
+ w.writeVarInt(msg.error_code)
475
+ w.writeString(msg.reason_phrase)
476
+ }
477
+
478
+ function encodeUnsubscribeNamespacePayload(
479
+ msg: Draft14Message & { type: 'unsubscribe_namespace' },
480
+ w: BufferWriter,
481
+ ): void {
482
+ w.writeTuple(msg.track_namespace_prefix)
483
+ }
484
+
485
+ function encodeFetchPayload(msg: Draft14Message & { type: 'fetch' }, w: BufferWriter): void {
486
+ w.writeVarInt(msg.request_id)
487
+ w.writeUint8(Number(msg.subscriber_priority))
488
+ w.writeUint8(Number(msg.group_order))
489
+ w.writeVarInt(msg.fetch_type)
490
+ const ft = msg.fetch_type
491
+ if (ft === FetchType.Standalone) {
492
+ w.writeTuple(msg.track_namespace!)
493
+ w.writeString(msg.track_name!)
494
+ w.writeVarInt(msg.start_group!)
495
+ w.writeVarInt(msg.start_object!)
496
+ w.writeVarInt(msg.end_group!)
497
+ w.writeVarInt(msg.end_object!)
498
+ } else {
499
+ w.writeVarInt(msg.joining_request_id!)
500
+ w.writeVarInt(msg.joining_start!)
501
+ }
502
+ encodeMessageParams(msg.parameters, w)
503
+ }
504
+
505
+ function encodeFetchOkPayload(msg: Draft14Message & { type: 'fetch_ok' }, w: BufferWriter): void {
506
+ w.writeVarInt(msg.request_id)
507
+ w.writeUint8(Number(msg.group_order))
508
+ w.writeVarInt(msg.end_of_track)
509
+ w.writeVarInt(msg.end_location.group)
510
+ w.writeVarInt(msg.end_location.object)
511
+ encodeMessageParams(msg.parameters, w)
512
+ }
513
+
514
+ function encodeFetchErrorPayload(
515
+ msg: Draft14Message & { type: 'fetch_error' },
516
+ w: BufferWriter,
517
+ ): void {
518
+ w.writeVarInt(msg.request_id)
519
+ w.writeVarInt(msg.error_code)
520
+ w.writeString(msg.reason_phrase)
521
+ }
522
+
523
+ function encodeFetchCancelPayload(
524
+ msg: Draft14Message & { type: 'fetch_cancel' },
525
+ w: BufferWriter,
526
+ ): void {
527
+ w.writeVarInt(msg.request_id)
528
+ }
529
+
530
+ function encodeTrackStatusPayload(
531
+ msg: Draft14Message & { type: 'track_status' },
532
+ w: BufferWriter,
533
+ ): void {
534
+ w.writeVarInt(msg.request_id)
535
+ w.writeTuple(msg.track_namespace)
536
+ w.writeString(msg.track_name)
537
+ w.writeUint8(Number(msg.subscriber_priority))
538
+ w.writeUint8(Number(msg.group_order))
539
+ w.writeVarInt(msg.forward)
540
+ w.writeVarInt(msg.filter_type)
541
+ const ft = msg.filter_type
542
+ if (ft >= FilterType.AbsoluteStart) {
543
+ w.writeVarInt(msg.start_group!)
544
+ w.writeVarInt(msg.start_object!)
545
+ }
546
+ encodeMessageParams(msg.parameters, w)
547
+ }
548
+
549
+ function encodeTrackStatusOkPayload(
550
+ msg: Draft14Message & { type: 'track_status_ok' },
551
+ w: BufferWriter,
552
+ ): void {
553
+ w.writeVarInt(msg.request_id)
554
+ w.writeVarInt(msg.track_alias)
555
+ w.writeVarInt(msg.expires)
556
+ w.writeUint8(Number(msg.group_order))
557
+ w.writeVarInt(msg.content_exists)
558
+ if (msg.content_exists === 1n) {
559
+ w.writeVarInt(msg.largest_location!.group)
560
+ w.writeVarInt(msg.largest_location!.object)
561
+ }
562
+ encodeMessageParams(msg.parameters, w)
563
+ }
564
+
565
+ function encodeTrackStatusErrorPayload(
566
+ msg: Draft14Message & { type: 'track_status_error' },
567
+ w: BufferWriter,
568
+ ): void {
569
+ w.writeVarInt(msg.request_id)
570
+ w.writeVarInt(msg.error_code)
571
+ w.writeString(msg.reason_phrase)
572
+ }
573
+
574
+ function encodeGoAwayPayload(msg: Draft14Message & { type: 'goaway' }, w: BufferWriter): void {
575
+ w.writeString(msg.new_session_uri)
576
+ }
577
+
578
+ function encodeMaxRequestIdPayload(
579
+ msg: Draft14Message & { type: 'max_request_id' },
580
+ w: BufferWriter,
581
+ ): void {
582
+ w.writeVarInt(msg.request_id)
583
+ }
584
+
585
+ function encodeRequestsBlockedPayload(
586
+ msg: Draft14Message & { type: 'requests_blocked' },
587
+ w: BufferWriter,
588
+ ): void {
589
+ w.writeVarInt(msg.request_id)
590
+ }
591
+
592
+ // ─── Payload Decoders ──────────────────────────────────────────────────────────
593
+
594
+ function decodeClientSetupPayload(r: BufferReader): Draft14Message {
595
+ const numVersions = Number(r.readVarInt())
596
+ if (numVersions === 0) {
597
+ throw new DecodeError(
598
+ 'CONSTRAINT_VIOLATION',
599
+ 'CLIENT_SETUP must offer at least one version',
600
+ r.offset,
601
+ )
602
+ }
603
+ const supported_versions: bigint[] = []
604
+ for (let i = 0; i < numVersions; i++) {
605
+ supported_versions.push(r.readVarInt())
606
+ }
607
+ const parameters = decodeSetupParams(r)
608
+ return { type: 'client_setup', supported_versions, parameters }
609
+ }
610
+
611
+ function decodeServerSetupPayload(r: BufferReader): Draft14Message {
612
+ const selected_version = r.readVarInt()
613
+ const parameters = decodeSetupParams(r)
614
+ return { type: 'server_setup', selected_version, parameters }
615
+ }
616
+
617
+ function decodeSubscribePayload(r: BufferReader): Draft14Message {
618
+ const request_id = r.readVarInt()
619
+ const track_namespace = r.readTuple()
620
+ const track_name = r.readString()
621
+ const subscriber_priority = BigInt(r.readUint8())
622
+ const group_order = BigInt(r.readUint8())
623
+ const forward = r.readVarInt()
624
+ const filter_type = r.readVarInt()
625
+
626
+ if (filter_type < FilterType.NextGroupStart || filter_type > FilterType.AbsoluteRange) {
627
+ throw new DecodeError('CONSTRAINT_VIOLATION', `Invalid filter_type: ${filter_type}`, r.offset)
628
+ }
629
+
630
+ let start_group: bigint | undefined
631
+ let start_object: bigint | undefined
632
+ let end_group: bigint | undefined
633
+
634
+ if (filter_type >= FilterType.AbsoluteStart) {
635
+ start_group = r.readVarInt()
636
+ start_object = r.readVarInt()
637
+ }
638
+ if (filter_type === FilterType.AbsoluteRange) {
639
+ end_group = r.readVarInt()
640
+ }
641
+
642
+ const parameters = decodeMessageParams(r)
643
+
644
+ const msg: Draft14Message & { type: 'subscribe' } = {
645
+ type: 'subscribe',
646
+ request_id,
647
+ track_namespace,
648
+ track_name,
649
+ subscriber_priority,
650
+ group_order,
651
+ forward,
652
+ filter_type,
653
+ parameters,
654
+ }
655
+
656
+ if (start_group !== undefined) {
657
+ return { ...msg, start_group, start_object, end_group } as Draft14Message
658
+ }
659
+
660
+ return msg
661
+ }
662
+
663
+ function decodeSubscribeOkPayload(r: BufferReader): Draft14Message {
664
+ const request_id = r.readVarInt()
665
+ const track_alias = r.readVarInt()
666
+ const expires = r.readVarInt()
667
+ const group_order = BigInt(r.readUint8())
668
+ const content_exists = r.readVarInt()
669
+
670
+ let largest_location: Location | undefined
671
+ if (content_exists === 1n) {
672
+ largest_location = {
673
+ group: r.readVarInt(),
674
+ object: r.readVarInt(),
675
+ }
676
+ }
677
+
678
+ const parameters = decodeMessageParams(r)
679
+
680
+ return {
681
+ type: 'subscribe_ok',
682
+ request_id,
683
+ track_alias,
684
+ expires,
685
+ group_order,
686
+ content_exists,
687
+ parameters,
688
+ ...(largest_location !== undefined ? { largest_location } : {}),
689
+ } as Draft14Message
690
+ }
691
+
692
+ function decodeSubscribeUpdatePayload(r: BufferReader): Draft14Message {
693
+ const request_id = r.readVarInt()
694
+ const subscription_request_id = r.readVarInt()
695
+ const start_group = r.readVarInt()
696
+ const start_object = r.readVarInt()
697
+ const end_group = r.readVarInt()
698
+ const subscriber_priority = BigInt(r.readUint8())
699
+ const forward = r.readVarInt()
700
+ const parameters = decodeMessageParams(r)
701
+ return {
702
+ type: 'subscribe_update',
703
+ request_id,
704
+ subscription_request_id,
705
+ start_group,
706
+ start_object,
707
+ end_group,
708
+ subscriber_priority,
709
+ forward,
710
+ parameters,
711
+ }
712
+ }
713
+
714
+ function decodeSubscribeErrorPayload(r: BufferReader): Draft14Message {
715
+ const request_id = r.readVarInt()
716
+ const error_code = r.readVarInt()
717
+ const reason_phrase = r.readString()
718
+ return { type: 'subscribe_error', request_id, error_code, reason_phrase }
719
+ }
720
+
721
+ function decodeUnsubscribePayload(r: BufferReader): Draft14Message {
722
+ const request_id = r.readVarInt()
723
+ return { type: 'unsubscribe', request_id }
724
+ }
725
+
726
+ function decodePublishPayload(r: BufferReader): Draft14Message {
727
+ const request_id = r.readVarInt()
728
+ const track_namespace = r.readTuple()
729
+ const track_name = r.readString()
730
+ const track_alias = r.readVarInt()
731
+ const group_order = BigInt(r.readUint8())
732
+ const content_exists = r.readVarInt()
733
+ let largest_location: Location | undefined
734
+ if (content_exists === 1n) {
735
+ largest_location = {
736
+ group: r.readVarInt(),
737
+ object: r.readVarInt(),
738
+ }
739
+ }
740
+ const forward = r.readVarInt()
741
+ const parameters = decodeMessageParams(r)
742
+ return {
743
+ type: 'publish',
744
+ request_id,
745
+ track_namespace,
746
+ track_name,
747
+ track_alias,
748
+ group_order,
749
+ content_exists,
750
+ forward,
751
+ parameters,
752
+ ...(largest_location !== undefined ? { largest_location } : {}),
753
+ } as Draft14Message
754
+ }
755
+
756
+ function decodePublishOkPayload(r: BufferReader): Draft14Message {
757
+ const request_id = r.readVarInt()
758
+ const forward = r.readVarInt()
759
+ const subscriber_priority = BigInt(r.readUint8())
760
+ const group_order = BigInt(r.readUint8())
761
+ const filter_type = r.readVarInt()
762
+
763
+ let start_group: bigint | undefined
764
+ let start_object: bigint | undefined
765
+ let end_group: bigint | undefined
766
+
767
+ if (filter_type >= FilterType.AbsoluteStart) {
768
+ start_group = r.readVarInt()
769
+ start_object = r.readVarInt()
770
+ }
771
+ if (filter_type === FilterType.AbsoluteRange) {
772
+ end_group = r.readVarInt()
773
+ }
774
+
775
+ const parameters = decodeMessageParams(r)
776
+
777
+ const msg: Record<string, unknown> = {
778
+ type: 'publish_ok',
779
+ request_id,
780
+ forward,
781
+ subscriber_priority,
782
+ group_order,
783
+ filter_type,
784
+ parameters,
785
+ }
786
+ if (start_group !== undefined) msg.start_group = start_group
787
+ if (start_object !== undefined) msg.start_object = start_object
788
+ if (end_group !== undefined) msg.end_group = end_group
789
+
790
+ return msg as unknown as Draft14Message
791
+ }
792
+
793
+ function decodePublishErrorPayload(r: BufferReader): Draft14Message {
794
+ const request_id = r.readVarInt()
795
+ const error_code = r.readVarInt()
796
+ const reason_phrase = r.readString()
797
+ return { type: 'publish_error', request_id, error_code, reason_phrase }
798
+ }
799
+
800
+ function decodePublishDonePayload(r: BufferReader): Draft14Message {
801
+ const request_id = r.readVarInt()
802
+ const status_code = r.readVarInt()
803
+ const stream_count = r.readVarInt()
804
+ const reason_phrase = r.readString()
805
+ return {
806
+ type: 'publish_done',
807
+ request_id,
808
+ status_code,
809
+ stream_count,
810
+ reason_phrase,
811
+ }
812
+ }
813
+
814
+ function decodePublishNamespacePayload(r: BufferReader): Draft14Message {
815
+ const request_id = r.readVarInt()
816
+ const track_namespace = r.readTuple()
817
+ const parameters = decodeMessageParams(r)
818
+ return { type: 'publish_namespace', request_id, track_namespace, parameters }
819
+ }
820
+
821
+ function decodePublishNamespaceOkPayload(r: BufferReader): Draft14Message {
822
+ const request_id = r.readVarInt()
823
+ const parameters = decodeMessageParams(r)
824
+ return { type: 'publish_namespace_ok', request_id, parameters }
825
+ }
826
+
827
+ function decodePublishNamespaceErrorPayload(r: BufferReader): Draft14Message {
828
+ const request_id = r.readVarInt()
829
+ const error_code = r.readVarInt()
830
+ const reason_phrase = r.readString()
831
+ return {
832
+ type: 'publish_namespace_error',
833
+ request_id,
834
+ error_code,
835
+ reason_phrase,
836
+ }
837
+ }
838
+
839
+ function decodePublishNamespaceDonePayload(r: BufferReader): Draft14Message {
840
+ const track_namespace = r.readTuple()
841
+ return { type: 'publish_namespace_done', track_namespace }
842
+ }
843
+
844
+ function decodePublishNamespaceCancelPayload(r: BufferReader): Draft14Message {
845
+ const track_namespace = r.readTuple()
846
+ const error_code = r.readVarInt()
847
+ const reason_phrase = r.readString()
848
+ return {
849
+ type: 'publish_namespace_cancel',
850
+ track_namespace,
851
+ error_code,
852
+ reason_phrase,
853
+ }
854
+ }
855
+
856
+ function decodeSubscribeNamespacePayload(r: BufferReader): Draft14Message {
857
+ const request_id = r.readVarInt()
858
+ const namespace_prefix = r.readTuple()
859
+ const parameters = decodeMessageParams(r)
860
+ return {
861
+ type: 'subscribe_namespace',
862
+ request_id,
863
+ namespace_prefix,
864
+ parameters,
865
+ }
866
+ }
867
+
868
+ function decodeSubscribeNamespaceOkPayload(r: BufferReader): Draft14Message {
869
+ const request_id = r.readVarInt()
870
+ const parameters = decodeMessageParams(r)
871
+ return { type: 'subscribe_namespace_ok', request_id, parameters }
872
+ }
873
+
874
+ function decodeSubscribeNamespaceErrorPayload(r: BufferReader): Draft14Message {
875
+ const request_id = r.readVarInt()
876
+ const error_code = r.readVarInt()
877
+ const reason_phrase = r.readString()
878
+ return {
879
+ type: 'subscribe_namespace_error',
880
+ request_id,
881
+ error_code,
882
+ reason_phrase,
883
+ }
884
+ }
885
+
886
+ function decodeUnsubscribeNamespacePayload(r: BufferReader): Draft14Message {
887
+ const track_namespace_prefix = r.readTuple()
888
+ return { type: 'unsubscribe_namespace', track_namespace_prefix }
889
+ }
890
+
891
+ function decodeFetchPayload(r: BufferReader): Draft14Message {
892
+ const request_id = r.readVarInt()
893
+ const subscriber_priority = BigInt(r.readUint8())
894
+ const group_order = BigInt(r.readUint8())
895
+ const fetch_type = r.readVarInt()
896
+
897
+ if (fetch_type < FetchType.Standalone || fetch_type > FetchType.AbsoluteJoining) {
898
+ throw new DecodeError('CONSTRAINT_VIOLATION', `Invalid fetch_type: ${fetch_type}`, r.offset)
899
+ }
900
+
901
+ if (fetch_type === FetchType.Standalone) {
902
+ const track_namespace = r.readTuple()
903
+ const track_name = r.readString()
904
+ const start_group = r.readVarInt()
905
+ const start_object = r.readVarInt()
906
+ const end_group = r.readVarInt()
907
+ const end_object = r.readVarInt()
908
+ const parameters = decodeMessageParams(r)
909
+ return {
910
+ type: 'fetch',
911
+ request_id,
912
+ subscriber_priority,
913
+ group_order,
914
+ fetch_type,
915
+ track_namespace,
916
+ track_name,
917
+ start_group,
918
+ start_object,
919
+ end_group,
920
+ end_object,
921
+ parameters,
922
+ }
923
+ } else {
924
+ const joining_request_id = r.readVarInt()
925
+ const joining_start = r.readVarInt()
926
+ const parameters = decodeMessageParams(r)
927
+ return {
928
+ type: 'fetch',
929
+ request_id,
930
+ subscriber_priority,
931
+ group_order,
932
+ fetch_type,
933
+ joining_request_id,
934
+ joining_start,
935
+ parameters,
936
+ }
937
+ }
938
+ }
939
+
940
+ function decodeFetchOkPayload(r: BufferReader): Draft14Message {
941
+ const request_id = r.readVarInt()
942
+ const group_order = BigInt(r.readUint8())
943
+ const end_of_track = r.readVarInt()
944
+ const end_location: Location = {
945
+ group: r.readVarInt(),
946
+ object: r.readVarInt(),
947
+ }
948
+ const parameters = decodeMessageParams(r)
949
+ return {
950
+ type: 'fetch_ok',
951
+ request_id,
952
+ group_order,
953
+ end_of_track,
954
+ end_location,
955
+ parameters,
956
+ }
957
+ }
958
+
959
+ function decodeFetchErrorPayload(r: BufferReader): Draft14Message {
960
+ const request_id = r.readVarInt()
961
+ const error_code = r.readVarInt()
962
+ const reason_phrase = r.readString()
963
+ return { type: 'fetch_error', request_id, error_code, reason_phrase }
964
+ }
965
+
966
+ function decodeFetchCancelPayload(r: BufferReader): Draft14Message {
967
+ const request_id = r.readVarInt()
968
+ return { type: 'fetch_cancel', request_id }
969
+ }
970
+
971
+ function decodeTrackStatusPayload(r: BufferReader): Draft14Message {
972
+ const request_id = r.readVarInt()
973
+ const track_namespace = r.readTuple()
974
+ const track_name = r.readString()
975
+ const subscriber_priority = BigInt(r.readUint8())
976
+ const group_order = BigInt(r.readUint8())
977
+ const forward = r.readVarInt()
978
+ const filter_type = r.readVarInt()
979
+
980
+ let start_group: bigint | undefined
981
+ let start_object: bigint | undefined
982
+ if (filter_type >= FilterType.AbsoluteStart) {
983
+ start_group = r.readVarInt()
984
+ start_object = r.readVarInt()
985
+ }
986
+
987
+ const parameters = decodeMessageParams(r)
988
+
989
+ const msg: Record<string, unknown> = {
990
+ type: 'track_status',
991
+ request_id,
992
+ track_namespace,
993
+ track_name,
994
+ subscriber_priority,
995
+ group_order,
996
+ forward,
997
+ filter_type,
998
+ parameters,
999
+ }
1000
+ if (start_group !== undefined) msg.start_group = start_group
1001
+ if (start_object !== undefined) msg.start_object = start_object
1002
+
1003
+ return msg as unknown as Draft14Message
1004
+ }
1005
+
1006
+ function decodeTrackStatusOkPayload(r: BufferReader): Draft14Message {
1007
+ const request_id = r.readVarInt()
1008
+ const track_alias = r.readVarInt()
1009
+ const expires = r.readVarInt()
1010
+ const group_order = BigInt(r.readUint8())
1011
+ const content_exists = r.readVarInt()
1012
+
1013
+ let largest_location: Location | undefined
1014
+ if (content_exists === 1n) {
1015
+ largest_location = {
1016
+ group: r.readVarInt(),
1017
+ object: r.readVarInt(),
1018
+ }
1019
+ }
1020
+
1021
+ const parameters = decodeMessageParams(r)
1022
+
1023
+ return {
1024
+ type: 'track_status_ok',
1025
+ request_id,
1026
+ track_alias,
1027
+ expires,
1028
+ group_order,
1029
+ content_exists,
1030
+ parameters,
1031
+ ...(largest_location !== undefined ? { largest_location } : {}),
1032
+ } as Draft14Message
1033
+ }
1034
+
1035
+ function decodeTrackStatusErrorPayload(r: BufferReader): Draft14Message {
1036
+ const request_id = r.readVarInt()
1037
+ const error_code = r.readVarInt()
1038
+ const reason_phrase = r.readString()
1039
+ return { type: 'track_status_error', request_id, error_code, reason_phrase }
1040
+ }
1041
+
1042
+ function decodeGoAwayPayload(r: BufferReader): Draft14Message {
1043
+ const new_session_uri = r.readString()
1044
+ return { type: 'goaway', new_session_uri }
1045
+ }
1046
+
1047
+ function decodeMaxRequestIdPayload(r: BufferReader): Draft14Message {
1048
+ const request_id = r.readVarInt()
1049
+ return { type: 'max_request_id', request_id }
1050
+ }
1051
+
1052
+ function decodeRequestsBlockedPayload(r: BufferReader): Draft14Message {
1053
+ const request_id = r.readVarInt()
1054
+ return { type: 'requests_blocked', request_id }
1055
+ }
1056
+
1057
+ // ─── Payload dispatch tables ───────────────────────────────────────────────────
1058
+
1059
+ const payloadDecoders: ReadonlyMap<bigint, (r: BufferReader) => Draft14Message> = new Map([
1060
+ [MSG_CLIENT_SETUP, decodeClientSetupPayload],
1061
+ [MSG_SERVER_SETUP, decodeServerSetupPayload],
1062
+ [MSG_SUBSCRIBE, decodeSubscribePayload],
1063
+ [MSG_SUBSCRIBE_OK, decodeSubscribeOkPayload],
1064
+ [MSG_SUBSCRIBE_UPDATE, decodeSubscribeUpdatePayload],
1065
+ [MSG_SUBSCRIBE_ERROR, decodeSubscribeErrorPayload],
1066
+ [MSG_UNSUBSCRIBE, decodeUnsubscribePayload],
1067
+ [MSG_PUBLISH, decodePublishPayload],
1068
+ [MSG_PUBLISH_OK, decodePublishOkPayload],
1069
+ [MSG_PUBLISH_ERROR, decodePublishErrorPayload],
1070
+ [MSG_PUBLISH_DONE, decodePublishDonePayload],
1071
+ [MSG_PUBLISH_NAMESPACE, decodePublishNamespacePayload],
1072
+ [MSG_PUBLISH_NAMESPACE_OK, decodePublishNamespaceOkPayload],
1073
+ [MSG_PUBLISH_NAMESPACE_ERROR, decodePublishNamespaceErrorPayload],
1074
+ [MSG_PUBLISH_NAMESPACE_DONE, decodePublishNamespaceDonePayload],
1075
+ [MSG_PUBLISH_NAMESPACE_CANCEL, decodePublishNamespaceCancelPayload],
1076
+ [MSG_SUBSCRIBE_NAMESPACE, decodeSubscribeNamespacePayload],
1077
+ [MSG_SUBSCRIBE_NAMESPACE_OK, decodeSubscribeNamespaceOkPayload],
1078
+ [MSG_SUBSCRIBE_NAMESPACE_ERROR, decodeSubscribeNamespaceErrorPayload],
1079
+ [MSG_UNSUBSCRIBE_NAMESPACE, decodeUnsubscribeNamespacePayload],
1080
+ [MSG_FETCH, decodeFetchPayload],
1081
+ [MSG_FETCH_OK, decodeFetchOkPayload],
1082
+ [MSG_FETCH_ERROR, decodeFetchErrorPayload],
1083
+ [MSG_FETCH_CANCEL, decodeFetchCancelPayload],
1084
+ [MSG_TRACK_STATUS, decodeTrackStatusPayload],
1085
+ [MSG_TRACK_STATUS_OK, decodeTrackStatusOkPayload],
1086
+ [MSG_TRACK_STATUS_ERROR, decodeTrackStatusErrorPayload],
1087
+ [MSG_GOAWAY, decodeGoAwayPayload],
1088
+ [MSG_MAX_REQUEST_ID, decodeMaxRequestIdPayload],
1089
+ [MSG_REQUESTS_BLOCKED, decodeRequestsBlockedPayload],
1090
+ ])
1091
+
1092
+ // ─── Public API ────────────────────────────────────────────────────────────────
1093
+
1094
+ /**
1095
+ * Encode a draft-14 control message with type(varint) + length(uint16 BE) + payload.
1096
+ */
1097
+ export function encodeMessage(message: Draft14Message): Uint8Array {
1098
+ const typeId = MESSAGE_ID_MAP.get(message.type)
1099
+ if (typeId === undefined) {
1100
+ throw new Error(`Unknown message type: ${message.type}`)
1101
+ }
1102
+
1103
+ // Encode payload into a separate buffer
1104
+ const payloadWriter = new BufferWriter()
1105
+ encodePayload(message, payloadWriter)
1106
+ const payload = payloadWriter.finishView()
1107
+
1108
+ if (payload.byteLength > 0xffff) {
1109
+ throw new Error(`Payload too large for 16-bit length: ${payload.byteLength}`)
1110
+ }
1111
+
1112
+ // Write framed message: type(varint) + length(uint16 BE) + payload
1113
+ const writer = new BufferWriter(payload.byteLength + 16)
1114
+ writer.writeVarInt(typeId)
1115
+ writer.writeUint8((payload.byteLength >> 8) & 0xff)
1116
+ writer.writeUint8(payload.byteLength & 0xff)
1117
+ writer.writeBytes(payload)
1118
+
1119
+ return writer.finish()
1120
+ }
1121
+
1122
+ function encodePayload(msg: Draft14Message, w: BufferWriter): void {
1123
+ switch (msg.type) {
1124
+ case 'client_setup':
1125
+ return encodeClientSetupPayload(msg, w)
1126
+ case 'server_setup':
1127
+ return encodeServerSetupPayload(msg, w)
1128
+ case 'subscribe':
1129
+ return encodeSubscribePayload(msg, w)
1130
+ case 'subscribe_ok':
1131
+ return encodeSubscribeOkPayload(msg, w)
1132
+ case 'subscribe_update':
1133
+ return encodeSubscribeUpdatePayload(msg, w)
1134
+ case 'subscribe_error':
1135
+ return encodeSubscribeErrorPayload(msg, w)
1136
+ case 'unsubscribe':
1137
+ return encodeUnsubscribePayload(msg, w)
1138
+ case 'publish':
1139
+ return encodePublishPayload(msg, w)
1140
+ case 'publish_ok':
1141
+ return encodePublishOkPayload(msg, w)
1142
+ case 'publish_error':
1143
+ return encodePublishErrorPayload(msg, w)
1144
+ case 'publish_done':
1145
+ return encodePublishDonePayload(msg, w)
1146
+ case 'publish_namespace':
1147
+ return encodePublishNamespacePayload(msg, w)
1148
+ case 'publish_namespace_ok':
1149
+ return encodePublishNamespaceOkPayload(msg, w)
1150
+ case 'publish_namespace_error':
1151
+ return encodePublishNamespaceErrorPayload(msg, w)
1152
+ case 'publish_namespace_done':
1153
+ return encodePublishNamespaceDonePayload(msg, w)
1154
+ case 'publish_namespace_cancel':
1155
+ return encodePublishNamespaceCancelPayload(msg, w)
1156
+ case 'subscribe_namespace':
1157
+ return encodeSubscribeNamespacePayload(msg, w)
1158
+ case 'subscribe_namespace_ok':
1159
+ return encodeSubscribeNamespaceOkPayload(msg, w)
1160
+ case 'subscribe_namespace_error':
1161
+ return encodeSubscribeNamespaceErrorPayload(msg, w)
1162
+ case 'unsubscribe_namespace':
1163
+ return encodeUnsubscribeNamespacePayload(msg, w)
1164
+ case 'fetch':
1165
+ return encodeFetchPayload(msg, w)
1166
+ case 'fetch_ok':
1167
+ return encodeFetchOkPayload(msg, w)
1168
+ case 'fetch_error':
1169
+ return encodeFetchErrorPayload(msg, w)
1170
+ case 'fetch_cancel':
1171
+ return encodeFetchCancelPayload(msg, w)
1172
+ case 'track_status':
1173
+ return encodeTrackStatusPayload(msg, w)
1174
+ case 'track_status_ok':
1175
+ return encodeTrackStatusOkPayload(msg, w)
1176
+ case 'track_status_error':
1177
+ return encodeTrackStatusErrorPayload(msg, w)
1178
+ case 'goaway':
1179
+ return encodeGoAwayPayload(msg, w)
1180
+ case 'max_request_id':
1181
+ return encodeMaxRequestIdPayload(msg, w)
1182
+ case 'requests_blocked':
1183
+ return encodeRequestsBlockedPayload(msg, w)
1184
+ default: {
1185
+ const _exhaustive: never = msg
1186
+ throw new Error(`Unhandled message type: ${(_exhaustive as Draft14Message).type}`)
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ /**
1192
+ * Decode a draft-14 control message from bytes (type + uint16 length + payload).
1193
+ */
1194
+ export function decodeMessage(bytes: Uint8Array): DecodeResult<Draft14Message> {
1195
+ try {
1196
+ const reader = new BufferReader(bytes)
1197
+ const typeId = reader.readVarInt()
1198
+
1199
+ // Read 16-bit big-endian payload length
1200
+ const lenHi = reader.readUint8()
1201
+ const lenLo = reader.readUint8()
1202
+ const payloadLength = (lenHi << 8) | lenLo
1203
+
1204
+ // Read exactly payloadLength bytes
1205
+ const payloadBytes = reader.readBytes(payloadLength)
1206
+ const payloadReader = new BufferReader(payloadBytes)
1207
+
1208
+ const decoder = payloadDecoders.get(typeId)
1209
+ if (!decoder) {
1210
+ return {
1211
+ ok: false,
1212
+ error: new DecodeError(
1213
+ 'UNKNOWN_MESSAGE_TYPE',
1214
+ `Unknown message type ID: 0x${typeId.toString(16)}`,
1215
+ 0,
1216
+ ),
1217
+ }
1218
+ }
1219
+
1220
+ const message = decoder(payloadReader)
1221
+ return { ok: true, value: message, bytesRead: reader.offset }
1222
+ } catch (e) {
1223
+ if (e instanceof DecodeError) {
1224
+ return { ok: false, error: e }
1225
+ }
1226
+ throw e
1227
+ }
1228
+ }
1229
+
1230
+ // ─── Data Stream Re-exports ───────────────────────────────────────���───────────
1231
+
1232
+ import {
1233
+ createDataStreamDecoder,
1234
+ createFetchStreamDecoder,
1235
+ createSubgroupStreamDecoder,
1236
+ decodeDatagram,
1237
+ decodeDataStream,
1238
+ decodeFetchStream,
1239
+ decodeSubgroupStream,
1240
+ encodeDatagram,
1241
+ encodeFetchStream,
1242
+ encodeSubgroupStream,
1243
+ } from './data-streams.js'
1244
+
1245
+ export {
1246
+ createDataStreamDecoder,
1247
+ createFetchStreamDecoder,
1248
+ createSubgroupStreamDecoder,
1249
+ decodeDatagram,
1250
+ decodeDataStream,
1251
+ decodeFetchStream,
1252
+ decodeSubgroupStream,
1253
+ encodeDatagram,
1254
+ encodeFetchStream,
1255
+ encodeSubgroupStream,
1256
+ }
1257
+
1258
+ // ─── Stream Decoders ───────────────────────────────────────────────────────────
1259
+
1260
+ /**
1261
+ * Create a TransformStream that decodes a continuous byte stream (e.g. the
1262
+ * WebTransport bidirectional control stream) into individual Draft14Message
1263
+ * objects. Uses the varint(type) + uint16_BE(length) + payload framing.
1264
+ */
1265
+ export function createStreamDecoder(): TransformStream<Uint8Array, Draft14Message> {
1266
+ let buffer = new Uint8Array(0)
1267
+ let offset = 0
1268
+
1269
+ return new TransformStream<Uint8Array, Draft14Message>({
1270
+ transform(chunk, controller) {
1271
+ // Compact before accumulating new data
1272
+ if (offset > 0) {
1273
+ buffer = buffer.subarray(offset)
1274
+ offset = 0
1275
+ }
1276
+ const newBuffer = new Uint8Array(buffer.length + chunk.length)
1277
+ newBuffer.set(buffer, 0)
1278
+ newBuffer.set(chunk, buffer.length)
1279
+ buffer = newBuffer
1280
+
1281
+ // Try to decode messages from the buffer
1282
+ while (offset < buffer.length) {
1283
+ const result = decodeMessage(buffer.subarray(offset))
1284
+ if (!result.ok) {
1285
+ if (result.error.code === 'UNEXPECTED_END') {
1286
+ // Need more data -- wait for next chunk
1287
+ break
1288
+ }
1289
+ // Fatal decode error
1290
+ controller.error(result.error)
1291
+ return
1292
+ }
1293
+ controller.enqueue(result.value)
1294
+ // Advance offset past the consumed bytes
1295
+ offset += result.bytesRead
1296
+ }
1297
+ },
1298
+
1299
+ flush(controller) {
1300
+ // If there is remaining data in the buffer, it is a truncated message
1301
+ if (offset < buffer.length) {
1302
+ controller.error(
1303
+ new DecodeError('UNEXPECTED_END', 'Stream ended with incomplete message data', 0),
1304
+ )
1305
+ }
1306
+ },
1307
+ })
1308
+ }
1309
+
1310
+ // ─── Codec Factory ─────────────────────────────────────────────────────────────
1311
+
1312
+ export interface Draft14Codec extends BaseCodec<Draft14Message> {
1313
+ readonly draft: '14'
1314
+ encodeSubgroupStream(stream: SubgroupStream): Uint8Array
1315
+ encodeDatagram(dg: DatagramObject): Uint8Array
1316
+ encodeFetchStream(stream: FetchStream): Uint8Array
1317
+ decodeSubgroupStream(bytes: Uint8Array): DecodeResult<SubgroupStream>
1318
+ decodeDatagram(bytes: Uint8Array): DecodeResult<DatagramObject>
1319
+ decodeFetchStream(bytes: Uint8Array): DecodeResult<FetchStream>
1320
+ decodeDataStream(
1321
+ streamType: 'subgroup' | 'datagram' | 'fetch',
1322
+ bytes: Uint8Array,
1323
+ ): DecodeResult<Draft14DataStream>
1324
+ createStreamDecoder(): TransformStream<Uint8Array, Draft14Message>
1325
+ createSubgroupStreamDecoder(): TransformStream<Uint8Array, SubgroupStreamHeader | ObjectPayload>
1326
+ createFetchStreamDecoder(): TransformStream<Uint8Array, FetchStreamHeader | ObjectPayload>
1327
+ createDataStreamDecoder(): TransformStream<Uint8Array, DataStreamEvent>
1328
+ }
1329
+
1330
+ export function createDraft14Codec(): Draft14Codec {
1331
+ return {
1332
+ draft: '14',
1333
+ encodeMessage,
1334
+ decodeMessage,
1335
+ encodeSubgroupStream,
1336
+ encodeDatagram,
1337
+ encodeFetchStream,
1338
+ decodeSubgroupStream,
1339
+ decodeDatagram,
1340
+ decodeFetchStream,
1341
+ decodeDataStream,
1342
+ createStreamDecoder,
1343
+ createSubgroupStreamDecoder,
1344
+ createFetchStreamDecoder,
1345
+ createDataStreamDecoder,
1346
+ }
1347
+ }