@moq/net 0.4.1 → 0.4.2

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 (173) hide show
  1. package/broadcast.d.ts +21 -7
  2. package/broadcast.d.ts.map +1 -1
  3. package/broadcast.js +38 -16
  4. package/broadcast.js.map +1 -1
  5. package/connection/accept.js +6 -4
  6. package/connection/accept.js.map +1 -1
  7. package/connection/connect.d.ts.map +1 -1
  8. package/connection/connect.js +5 -4
  9. package/connection/connect.js.map +1 -1
  10. package/connection/forward.js +54 -47
  11. package/connection/forward.js.map +1 -1
  12. package/connection/goaway.d.ts +34 -0
  13. package/connection/goaway.d.ts.map +1 -0
  14. package/connection/goaway.js +176 -0
  15. package/connection/goaway.js.map +1 -0
  16. package/connection/handshake.d.ts +4 -2
  17. package/connection/handshake.d.ts.map +1 -1
  18. package/connection/handshake.js +42 -10
  19. package/connection/handshake.js.map +1 -1
  20. package/connection/pool.d.ts +16 -1
  21. package/connection/pool.d.ts.map +1 -1
  22. package/connection/pool.js +32 -10
  23. package/connection/pool.js.map +1 -1
  24. package/connection/reload.d.ts.map +1 -1
  25. package/connection/reload.js +184 -30
  26. package/connection/reload.js.map +1 -1
  27. package/error.d.ts +11 -0
  28. package/error.d.ts.map +1 -1
  29. package/error.js +14 -0
  30. package/error.js.map +1 -1
  31. package/errors.d.ts +1 -1
  32. package/errors.d.ts.map +1 -1
  33. package/errors.js +1 -1
  34. package/errors.js.map +1 -1
  35. package/group.d.ts.map +1 -1
  36. package/group.js +5 -4
  37. package/group.js.map +1 -1
  38. package/hop.d.ts +8 -0
  39. package/hop.d.ts.map +1 -1
  40. package/hop.js +16 -0
  41. package/hop.js.map +1 -1
  42. package/ietf/adapter.d.ts +4 -0
  43. package/ietf/adapter.d.ts.map +1 -1
  44. package/ietf/adapter.js +19 -8
  45. package/ietf/adapter.js.map +1 -1
  46. package/ietf/cluster.d.ts +3 -3
  47. package/ietf/cluster.js +3 -3
  48. package/ietf/cluster.js.map +1 -1
  49. package/ietf/connection.d.ts.map +1 -1
  50. package/ietf/connection.js +110 -37
  51. package/ietf/connection.js.map +1 -1
  52. package/ietf/fetch.d.ts +7 -20
  53. package/ietf/fetch.d.ts.map +1 -1
  54. package/ietf/fetch.js +52 -22
  55. package/ietf/fetch.js.map +1 -1
  56. package/ietf/filter.d.ts +2 -0
  57. package/ietf/filter.d.ts.map +1 -1
  58. package/ietf/filter.js +4 -0
  59. package/ietf/filter.js.map +1 -1
  60. package/ietf/goaway.d.ts +9 -1
  61. package/ietf/goaway.d.ts.map +1 -1
  62. package/ietf/goaway.js +20 -0
  63. package/ietf/goaway.js.map +1 -1
  64. package/ietf/hidden.js +1 -1
  65. package/ietf/hidden.js.map +1 -1
  66. package/ietf/index.d.ts +1 -1
  67. package/ietf/index.d.ts.map +1 -1
  68. package/ietf/index.js +1 -1
  69. package/ietf/index.js.map +1 -1
  70. package/ietf/object.d.ts +7 -6
  71. package/ietf/object.d.ts.map +1 -1
  72. package/ietf/object.js +37 -33
  73. package/ietf/object.js.map +1 -1
  74. package/ietf/parameters.d.ts +7 -0
  75. package/ietf/parameters.d.ts.map +1 -1
  76. package/ietf/parameters.js +62 -12
  77. package/ietf/parameters.js.map +1 -1
  78. package/ietf/publish_namespace.d.ts +2 -2
  79. package/ietf/publish_namespace.js +2 -2
  80. package/ietf/publish_namespace.js.map +1 -1
  81. package/ietf/publisher.js +287 -172
  82. package/ietf/publisher.js.map +1 -1
  83. package/ietf/subscribe.d.ts +7 -1
  84. package/ietf/subscribe.d.ts.map +1 -1
  85. package/ietf/subscribe.js +22 -14
  86. package/ietf/subscribe.js.map +1 -1
  87. package/ietf/subscribe_namespace.d.ts.map +1 -1
  88. package/ietf/subscribe_namespace.js +2 -3
  89. package/ietf/subscribe_namespace.js.map +1 -1
  90. package/ietf/subscriber.js +57 -42
  91. package/ietf/subscriber.js.map +1 -1
  92. package/ietf/token.d.ts +2 -0
  93. package/ietf/token.d.ts.map +1 -0
  94. package/ietf/token.js +99 -0
  95. package/ietf/token.js.map +1 -0
  96. package/ietf/track.d.ts +4 -0
  97. package/ietf/track.d.ts.map +1 -1
  98. package/ietf/track.js +6 -20
  99. package/ietf/track.js.map +1 -1
  100. package/index.d.ts +1 -1
  101. package/index.d.ts.map +1 -1
  102. package/index.js.map +1 -1
  103. package/internal.d.ts +12 -3
  104. package/internal.d.ts.map +1 -1
  105. package/internal.js +32 -0
  106. package/internal.js.map +1 -1
  107. package/lite/announce.d.ts.map +1 -1
  108. package/lite/announce.js +7 -4
  109. package/lite/announce.js.map +1 -1
  110. package/lite/connection.d.ts.map +1 -1
  111. package/lite/connection.js +22 -7
  112. package/lite/connection.js.map +1 -1
  113. package/lite/datagram.d.ts +3 -2
  114. package/lite/datagram.d.ts.map +1 -1
  115. package/lite/datagram.js +7 -8
  116. package/lite/datagram.js.map +1 -1
  117. package/lite/group.d.ts +12 -8
  118. package/lite/group.d.ts.map +1 -1
  119. package/lite/group.js +37 -16
  120. package/lite/group.js.map +1 -1
  121. package/lite/message.d.ts +2 -2
  122. package/lite/message.d.ts.map +1 -1
  123. package/lite/message.js +14 -5
  124. package/lite/message.js.map +1 -1
  125. package/lite/publisher.js +19 -37
  126. package/lite/publisher.js.map +1 -1
  127. package/lite/setup.d.ts +1 -1
  128. package/lite/setup.d.ts.map +1 -1
  129. package/lite/setup.js +22 -19
  130. package/lite/setup.js.map +1 -1
  131. package/lite/subscriber.d.ts.map +1 -1
  132. package/lite/subscriber.js +206 -127
  133. package/lite/subscriber.js.map +1 -1
  134. package/origin.d.ts +9 -1
  135. package/origin.d.ts.map +1 -1
  136. package/origin.js +341 -146
  137. package/origin.js.map +1 -1
  138. package/package.json +2 -2
  139. package/stream.d.ts +77 -12
  140. package/stream.d.ts.map +1 -1
  141. package/stream.js +359 -122
  142. package/stream.js.map +1 -1
  143. package/tail.d.ts +7 -0
  144. package/tail.d.ts.map +1 -1
  145. package/tail.js +68 -22
  146. package/tail.js.map +1 -1
  147. package/track.d.ts +14 -3
  148. package/track.d.ts.map +1 -1
  149. package/track.js +170 -76
  150. package/track.js.map +1 -1
  151. package/util/abort.d.ts +2 -0
  152. package/util/abort.d.ts.map +1 -0
  153. package/util/abort.js +20 -0
  154. package/util/abort.js.map +1 -0
  155. package/util/u64.d.ts +39 -0
  156. package/util/u64.d.ts.map +1 -0
  157. package/util/u64.js +83 -0
  158. package/util/u64.js.map +1 -0
  159. package/util/varint.d.ts +29 -0
  160. package/util/varint.d.ts.map +1 -0
  161. package/util/varint.js +198 -0
  162. package/util/varint.js.map +1 -0
  163. package/varint.d.ts +10 -6
  164. package/varint.d.ts.map +1 -1
  165. package/varint.js +40 -237
  166. package/varint.js.map +1 -1
  167. package/wire.d.ts +17 -3
  168. package/wire.d.ts.map +1 -1
  169. package/wire.js.map +1 -1
  170. package/ietf/control.d.ts +0 -135
  171. package/ietf/control.d.ts.map +0 -1
  172. package/ietf/control.js +0 -242
  173. package/ietf/control.js.map +0 -1
package/error.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAQjD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CACvC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAY,EAAe,EAAE,CAAC,eAAe,CAAC,IAAI,CAAgB,EAAE;IAClF,kDAAkD;IAClD,MAAM,EAAE,GAAkB;IAC1B,8DAA8D;IAC9D,QAAQ,EAAE,GAAkB;IAC5B,6FAA6F;IAC7F,YAAY,EAAE,GAAkB;IAChC,2DAA2D;IAC3D,iBAAiB,EAAE,GAAkB;IACrC,oEAAoE;IACpE,kBAAkB,EAAE,GAAkB;IACtC,+DAA+D;IAC/D,aAAa,EAAE,IAAmB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AAG,KAAK,QAAQ,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAE,GAA4B,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;IAC1G,IAAI,IAAI,IAAI,MAAM,KAAK,SAAS;QAAE,OAAO,UAAU,CAAC,IAAI,CAAC,CAAC;IAC1D,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,KAAK,CAAC,GAAY;IACjC,OAAO,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,MAAM,CAAC,GAAY;IAClC,MAAM,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;IAErB,sFAAsF;IACtF,yEAAyE;IACzE,IAAI,OAAO,iBAAiB,KAAK,WAAW,IAAI,CAAC,YAAY,iBAAiB,EAAE,CAAC;QAChF,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,CAAC,eAAe,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC;QACxE,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,sBAAsB,MAAM,EAAE,CAAC;IAChF,CAAC;IAED,OAAO,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,IAAI,IAAI,eAAe,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * Errors, including the code a peer reports when it resets a stream or closes the session.\n *\n * @module\n */\n\nimport { sharedStreamCode } from \"./ietf/error.ts\";\nimport type { IetfVersion } from \"./ietf/version.ts\";\nimport { TimeoutError } from \"./util/timeout.ts\";\n\n/** The nominal brand for session termination codes. */\ndeclare const SESSION_CODE: unique symbol;\n\n/** A code from the session termination registry. */\nexport type SessionCode = number & { readonly [SESSION_CODE]: true };\n\n/**\n * Codes a peer sends when terminating the session, mirroring the Rust `Session`.\n *\n * Specified by moq-lite, which reuses moq-transport's codes unchanged. Call `SessionCode(code)`\n * to construct an application code in the 64+ range. {@link StreamCode} is the other registry,\n * and the two are disjoint, so the same integer means different things in each.\n *\n * Codes 32-47 are reserved: nothing is sent there, and the draft gives a received one no\n * meaning, so treat anything not listed below as an unspecified error rather than guessing.\n *\n * @public\n */\nexport const SessionCode = Object.freeze(\n\tObject.assign((code: number): SessionCode => applicationCode(code) as SessionCode, {\n\t\t/** Ending the session normally, with no error. */\n\t\tCancel: 0x0 as SessionCode,\n\t\t/** Something went wrong that isn't worth a dedicated code. */\n\t\tInternal: 0x1 as SessionCode,\n\t\t/** The credentials don't grant the requested path or operation. Retrying will fail again. */\n\t\tUnauthorized: 0x2 as SessionCode,\n\t\t/** A protocol rule was broken; the session is unusable. */\n\t\tProtocolViolation: 0x3 as SessionCode,\n\t\t/** A key-value pair was malformed or repeated more than allowed. */\n\t\tKeyValueFormatting: 0x6 as SessionCode,\n\t\t/** The peer did not close within the GOAWAY drain deadline. */\n\t\tGoawayTimeout: 0x10 as SessionCode,\n\t\t/** A control message took too long. */\n\t\tTimeout: 0x11 as SessionCode,\n\t\t/** No version could be negotiated. */\n\t\tVersion: 0x15 as SessionCode,\n\t} as const),\n);\n\n/** The nominal brand for stream reset codes. */\ndeclare const STREAM_CODE: unique symbol;\n\n/** A code from the stream reset registry. */\nexport type StreamCode = number & { readonly [STREAM_CODE]: true };\n\n/**\n * Codes a peer sends when resetting a stream, mirroring the Rust `Stream`.\n *\n * The counterpart to {@link SessionCode}, and a disjoint space: a stream reset of 0 is\n * {@link StreamCode.Internal}, not a cancellation ({@link StreamCode.Cancel} is 1). Call\n * `StreamCode(code)` to construct an application code in the 64+ range.\n *\n * Conditions the shared codes don't cover are assigned in moq-lite's own 48-63 range, so a\n * received one is the named code. 32 through 47 is reserved: nothing is sent there and a\n * received one is an unspecified error.\n *\n * @public\n */\nexport const StreamCode = Object.freeze(\n\tObject.assign((code: number): StreamCode => applicationCode(code) as StreamCode, {\n\t\t/** Something went wrong that isn't worth a dedicated code. */\n\t\tInternal: 0x0 as StreamCode,\n\t\t/** The sender is done with this stream, not failing. A routine unsubscribe. */\n\t\tCancel: 0x1 as StreamCode,\n\t\t/** The content missed its delivery deadline. */\n\t\tDeliveryTimeout: 0x2 as StreamCode,\n\t\t/** The session ended, taking this stream with it. */\n\t\tSessionClosed: 0x3 as StreamCode,\n\t\t/** The session is going away (a GOAWAY was received). */\n\t\tGoingAway: 0x4 as StreamCode,\n\t\t/** The reader fell too far behind and content was dropped to catch up. */\n\t\tTooFarBehind: 0x5 as StreamCode,\n\t\t/** The track's content could not be parsed. */\n\t\tMalformedTrack: 0x12 as StreamCode,\n\t\t/** The peer took too long to answer a control request. */\n\t\tControlTimeout: 0x31 as StreamCode,\n\t\t/** The requested broadcast or track does not exist at the peer. */\n\t\tNotFound: 0x33 as StreamCode,\n\t\t/** The group was superseded by a newer one and dropped. */\n\t\tOld: 0x34 as StreamCode,\n\t\t/** The group was dropped under memory pressure, so it can be re-fetched. */\n\t\tEvicted: 0x35 as StreamCode,\n\t\t/** A frame declared a payload larger than the receiver accepts. */\n\t\tFrameTooLarge: 0x38 as StreamCode,\n\t\t/** The publisher could serve this request but has no capacity for it now. */\n\t\tNoCapacity: 0x30 as StreamCode,\n\t\t/** A group grew past its cache budget and was aborted. */\n\t\tGroupTooLarge: 0x32 as StreamCode,\n\t} as const),\n);\n\nfunction applicationCode(code: number): number {\n\tif (!Number.isInteger(code) || code < 64 || code > 0xffffffff) {\n\t\tthrow new RangeError(`invalid application error code: ${code}`);\n\t}\n\treturn code;\n}\n\n/**\n * An error the peer reported by closing the session, carrying its {@link SessionCode}.\n *\n * This surfaces on every transport, so catch this type rather than feature-detecting\n * `WebTransportError`, which a non-browser runtime never defines and the WebSocket fallback\n * never throws.\n *\n * ```ts\n * connection.error.subscribe((err) => {\n * if (err instanceof Session && err.code === SessionCode.Unauthorized) {\n * console.warn(\"server rejected the session\");\n * }\n * });\n * ```\n *\n * @public\n */\nexport class Session extends Error {\n\t/** The session code the peer sent, verbatim. */\n\treadonly code: SessionCode;\n\n\tconstructor(code: SessionCode, options?: { cause?: unknown; reason?: string }) {\n\t\tsuper(options?.reason ? `remote error: ${code} (${options.reason})` : `remote error: ${code}`, options);\n\t\tthis.name = \"Session\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Options for a {@link Stream}. */\nexport interface StreamOptions {\n\t/** The failure this one wraps. */\n\tcause?: unknown;\n\t/** The peer's human-readable reason, appended to the default message. */\n\treason?: string;\n\t/** Replaces the default `remote error: <code>` text, for a condition raised locally. */\n\tmessage?: string;\n}\n\n/**\n * An error carrying a {@link StreamCode}: the code a peer sent when it reset a stream, or the\n * one this side sends when it resets one.\n *\n * This surfaces on every transport, so catch this type rather than feature-detecting\n * `WebTransportError`, which a non-browser runtime never defines and the WebSocket fallback\n * never throws. Local conditions with a code of their own subclass it ({@link TooFarBehind},\n * {@link FrameTooLarge}, {@link GroupTooLarge}, {@link NotFound}), so the same `code` check catches a condition\n * whether it was raised here or reported by the peer.\n *\n * ```ts\n * try {\n * frame = await group.readFrame();\n * } catch (err) {\n * if (err instanceof Stream && err.code === StreamCode.Cancel) return;\n * throw err;\n * }\n * ```\n *\n * @public\n */\nexport class Stream extends Error {\n\t/** The stream code; moq-lite resets forward it verbatim. */\n\treadonly code: StreamCode;\n\n\tconstructor(code: StreamCode, options?: StreamOptions) {\n\t\tsuper(\n\t\t\toptions?.message ??\n\t\t\t\t(options?.reason ? `remote error: ${code} (${options.reason})` : `remote error: ${code}`),\n\t\t\toptions,\n\t\t);\n\t\tthis.name = \"Stream\";\n\t\tthis.code = code;\n\t}\n}\n\n/**\n * The reader asked for a frame the group never held, so the stream has a gap.\n *\n * Raised locally by a frame read, and decoded from a moq-lite peer's `TOO_FAR_BEHIND` reset, since a gap\n * reads the same either way.\n *\n * @public\n */\nexport class TooFarBehind extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.TooFarBehind, {\n\t\t\t...options,\n\t\t\tmessage: \"lagged: frames were evicted before being read\",\n\t\t});\n\t\tthis.name = \"TooFarBehind\";\n\t}\n}\n\n/**\n * A frame is larger than a group can cache, so appending it would exceed the budget by itself.\n *\n * Raised locally by a frame write, and decoded from a moq-lite peer's `FRAME_TOO_LARGE` reset.\n * Mirrors the Rust `Error::FrameTooLarge`, which rejects the same frame before touching any state.\n *\n * @public\n */\nexport class FrameTooLarge extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.FrameTooLarge, {\n\t\t\t...options,\n\t\t\tmessage: \"frame too large: larger than a group can cache\",\n\t\t});\n\t\tthis.name = \"FrameTooLarge\";\n\t}\n}\n\n/**\n * A write grew the group past its cache budget, so the group is aborted.\n *\n * Raised locally by a frame write, and decoded from a moq-lite peer's `GROUP_TOO_LARGE`\n * reset. Mirrors the Rust `Error::GroupTooLarge`.\n *\n * @public\n */\nexport class GroupTooLarge extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.GroupTooLarge, {\n\t\t\t...options,\n\t\t\tmessage: \"group too large: exceeded the cache budget\",\n\t\t});\n\t\tthis.name = \"GroupTooLarge\";\n\t}\n}\n\n/**\n * The requested broadcast or track is not served here.\n *\n * @public\n */\nexport class NotFound extends Stream {\n\tconstructor(what: string, options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.NotFound, { ...options, message: `not found: ${what}` });\n\t\tthis.name = \"NotFound\";\n\t}\n}\n\n/**\n * A peer broke the protocol in a way the spec says must end the session.\n *\n * Thrown where the violation is detected, rather than handled there: a decoder has no session\n * to close. The dispatch that owns the session watches for it and closes, so a nonconforming\n * peer cannot repeat the violation on the next stream.\n *\n * @public\n */\nexport class ProtocolViolation extends Error {\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ProtocolViolation\";\n\t}\n}\n\n/** Package-internal compatibility names used by the wire implementation. */\nexport { Session as SessionError, Stream as StreamError, TooFarBehind as Lagged };\n/** Package-internal compatibility name used by the wire implementation. */\nexport type StreamErrorOptions = StreamOptions;\n\n/** The WebTransport-shaped fields a stream reset code arrives in. */\ntype StreamErrorLike = { source?: unknown; streamErrorCode?: unknown };\n\nfunction streamCode(err: unknown): StreamCode | undefined {\n\tif (typeof err !== \"object\" || err === null) return undefined;\n\n\tconst { source, streamErrorCode } = err as StreamErrorLike;\n\tif (source !== \"stream\" || typeof streamErrorCode !== \"number\") return undefined;\n\n\treturn streamErrorCode as StreamCode;\n}\n\n/** Transport context for encoding and decoding errors. @internal */\ninterface TransportErrorOptions {\n\t/** The negotiated IETF draft, or absent for moq-lite. */\n\tversion?: IetfVersion;\n}\n\n/**\n * Which {@link StreamCode} to send when resetting a stream because of `err`.\n *\n * The counterpart to {@link fromTransport}, and the pair has to agree: a code we send for a\n * condition is the code we read that condition back from, or two peers disagree about what it\n * means. Mirrors the Rust `From<&Error> for Stream`.\n *\n * Lossy on purpose. An error describes what went wrong here, while the registry is what the peer\n * can act on, so anything without a code of its own degrades to {@link StreamCode.Internal}\n * rather than inventing one. A {@link Session} lands there too: the two registries are\n * disjoint, so forwarding its code onto a stream would mistranslate it.\n *\n * On an IETF stream the code has to be one the negotiated draft assigns the same meaning to,\n * so a condition it does not register degrades to INTERNAL_ERROR as well. See\n * {@link sharedStreamCode}.\n *\n * @internal\n */\nexport function toStreamCode(err: unknown, options?: TransportErrorOptions): StreamCode {\n\tconst code = localStreamCode(err);\n\tif (options?.version === undefined) return code;\n\treturn sharedStreamCode(code, options.version) ? code : StreamCode.Internal;\n}\n\n/** The moq-lite code for a local failure, before any draft has a say. */\nfunction localStreamCode(err: unknown): StreamCode {\n\tif (err instanceof Stream) return err.code;\n\tif (err instanceof TimeoutError) return StreamCode.DeliveryTimeout;\n\t// Session-scoped: the peer learns which rule it broke from the session close, not from here.\n\tif (err instanceof ProtocolViolation) return StreamCode.SessionClosed;\n\treturn StreamCode.Internal;\n}\n\n/**\n * The {@link StreamCode.ControlTimeout} error for a control request the peer never answered.\n *\n * A control request that outlives its deadline is not late content, so it does not go out as\n * {@link StreamCode.DeliveryTimeout} the way a bare {@link TimeoutError} would. Callers that\n * bound a request's response build this instead.\n *\n * @internal\n */\nexport function controlTimeout(cause: unknown): Stream {\n\tconst message = cause instanceof Error && cause.message ? cause.message : \"control request timed out\";\n\treturn new Stream(StreamCode.ControlTimeout, { cause, message });\n}\n\n/**\n * Decode a transport failure into a {@link Stream} when it carries a stream reset code,\n * otherwise pass it through.\n *\n * Native WebTransport rejects with a `WebTransportError`; the WebSocket fallback mints an error\n * with the same `source`/`streamErrorCode` fields. Reading the fields rather than the class\n * covers both, and works in a runtime with no `WebTransportError` at all.\n *\n * On moq-lite, a code with a local class decodes back into it, so a peer's condition is caught by\n * the same `instanceof` as one raised here.\n *\n * On an IETF stream a code keeps its value unless moq-lite claims that number for something\n * the draft does not: `0x4` is GOING_AWAY here but UNKNOWN_OBJECT_STATUS on draft-16 and 17,\n * and reading one back as the other would retire a session that is not going anywhere. Those\n * read as {@link StreamCode.Internal} with the wire value kept in the message, since\n * {@link StreamCode} is one numeric space and cannot hold a foreign code without lying about\n * it. A code moq-lite names nothing for survives intact: nothing can misread it.\n *\n * @internal Called at the transport boundary so the raw error never reaches an application.\n */\nexport function fromTransport(err: unknown, options?: TransportErrorOptions): Error {\n\tconst code = streamCode(err);\n\tif (code === undefined) return error(err);\n\tif (options?.version !== undefined && !sharedStreamCode(code, options.version) && claimedLocally(code)) {\n\t\treturn new Stream(StreamCode.Internal, { cause: err, message: `remote error: ${code}` });\n\t}\n\tif (code === StreamCode.TooFarBehind) return new TooFarBehind({ cause: err });\n\tif (code === StreamCode.FrameTooLarge) return new FrameTooLarge({ cause: err });\n\tif (code === StreamCode.GroupTooLarge) return new GroupTooLarge({ cause: err });\n\treturn new Stream(code, { cause: err });\n}\n\n/** The codes moq-lite names, which a foreign one must not borrow. */\nconst NAMED_CODES: ReadonlySet<number> = new Set(Object.values(StreamCode));\n\n/**\n * Whether moq-lite could give `code` a meaning of its own: one of its named codes, or\n * anywhere in the 64+ range, where `StreamCode(code)` mints an application code and an\n * application compares against its own. moq-transport registers nothing above 0x12 and has\n * no application range at all, so a foreign code landing there is never what it looks like.\n */\nfunction claimedLocally(code: number): boolean {\n\treturn code >= 64 || NAMED_CODES.has(code);\n}\n\nconst legacyWebTransportErrors = new WeakSet<object>();\n\n/**\n * Build the `reason` to hand `abort()` / `cancel()` so the transport puts `code` on the wire.\n *\n * Both the WebTransport spec and the WebSocket fallback take the reset code from a\n * `WebTransportError`'s `streamErrorCode` and send 0 for anything else, a plain `Error`\n * included. Since 0 is {@link StreamCode.Internal}, cancelling with a bare `Error` tells the\n * peer we failed rather than that we are done.\n *\n * The native constructor exists exactly where native WebTransport does, which is where the\n * fallback isn't used, so mint a matching shape elsewhere rather than feature-detect a global\n * that will not be there.\n *\n * @internal\n */\nexport function toTransport(code: StreamCode, message: string): Error {\n\tconst Native = (globalThis as { WebTransportError?: typeof WebTransportError }).WebTransportError;\n\tif (Native) {\n\t\tconst Legacy = Native as unknown as new (init: { message: string; streamErrorCode: number }) => Error;\n\t\tif (legacyWebTransportErrors.has(Native)) return new Legacy({ message, streamErrorCode: code });\n\n\t\ttry {\n\t\t\treturn new Native(message, { source: \"stream\", streamErrorCode: code });\n\t\t} catch (err) {\n\t\t\t// Chromium still implements the previous single-dictionary constructor.\n\t\t\tif (!(err instanceof TypeError)) throw err;\n\t\t\tlegacyWebTransportErrors.add(Native);\n\t\t\treturn new Legacy({ message, streamErrorCode: code });\n\t\t}\n\t}\n\n\treturn Object.assign(new Error(message), { source: \"stream\" as const, streamErrorCode: code });\n}\n\n/**\n * Decode a session close into its terminal error: `null` for a clean close\n * ({@link SessionCode.Cancel}), otherwise a {@link Session} carrying the peer's code.\n *\n * @internal Applied to the transport's `closed` info so the code survives to the application.\n */\nexport function fromClose(info: WebTransportCloseInfo): Session | null {\n\tconst code = (info.closeCode ?? SessionCode.Cancel) as SessionCode;\n\tif (code === SessionCode.Cancel) return null;\n\treturn new Session(code, { reason: info.reason });\n}\n\n/**\n * The session's close as the error it ends everything with, carrying the peer's code. A clean\n * close code is still an error here: whatever the close cut off did not end.\n *\n * @internal\n */\nexport function closeError(quic: WebTransport): Promise<Error> {\n\treturn quic.closed.then(\n\t\t(info) => fromClose(info) ?? new Session(SessionCode.Cancel, { reason: info.reason }),\n\t\t(err: unknown) => error(err),\n\t);\n}\n\n/**\n * Report a failure the session's close caused as the session's own error, which carries the\n * peer's close code; any other failure passes through.\n *\n * @internal\n */\nexport async function sessionCause(quic: WebTransport | undefined, err: unknown): Promise<Error> {\n\tconst source = typeof err === \"object\" && err !== null ? (err as { source?: unknown }).source : undefined;\n\tif (quic && source === \"session\") return closeError(quic);\n\treturn error(err);\n}\n\n/**\n * Coerce an unknown thrown value into an `Error`.\n *\n * @internal\n */\nexport function error(err: unknown): Error {\n\treturn err instanceof Error ? err : new Error(String(err));\n}\n\n/**\n * Format an error into a non-empty, human-readable string for logging.\n *\n * Safari always leaves `WebTransportError.message` blank, so a bare `err.message` degrades to\n * an empty string and the reason is lost. This falls back to the error type name and appends\n * the WebTransport `source` and application `streamErrorCode`, so the log line always says\n * something.\n */\nexport function reason(err: unknown): string {\n\tconst e = error(err);\n\n\t// WebTransportError carries the failure origin and the peer's application error code,\n\t// often the only identifying detail since WebKit leaves `message` empty.\n\tif (typeof WebTransportError !== \"undefined\" && e instanceof WebTransportError) {\n\t\tconst parts = [`source=${e.source}`];\n\t\tif (e.streamErrorCode !== null) parts.push(`code=${e.streamErrorCode}`);\n\t\tconst detail = parts.join(\" \");\n\t\treturn e.message ? `${e.message} (${detail})` : `WebTransportError: ${detail}`;\n\t}\n\n\treturn e.message || e.name || \"unknown error\";\n}\n"]}
1
+ {"version":3,"file":"error.js","sourceRoot":"","sources":["../src/error.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAEnD,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAQjD;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,CACvC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAY,EAAe,EAAE,CAAC,eAAe,CAAC,IAAI,CAAgB,EAAE;IAClF,kDAAkD;IAClD,MAAM,EAAE,GAAkB;IAC1B,8DAA8D;IAC9D,QAAQ,EAAE,GAAkB;IAC5B,6FAA6F;IAC7F,YAAY,EAAE,GAAkB;IAChC,2DAA2D;IAC3D,iBAAiB,EAAE,GAAkB;IACrC,oEAAoE;IACpE,kBAAkB,EAAE,GAAkB;IACtC,+DAA+D;IAC/D,aAAa,EAAE,IAAmB;IAClC,uCAAuC;IACvC,OAAO,EAAE,IAAmB;IAC5B,sCAAsC;IACtC,OAAO,EAAE,IAAmB;CACnB,CAAC,CACX,CAAC;AAQF;;;;;;;;;;;;GAYG;AACH,MAAM,CAAC,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,CACtC,MAAM,CAAC,MAAM,CAAC,CAAC,IAAY,EAAc,EAAE,CAAC,eAAe,CAAC,IAAI,CAAe,EAAE;IAChF,8DAA8D;IAC9D,QAAQ,EAAE,GAAiB;IAC3B,+EAA+E;IAC/E,MAAM,EAAE,GAAiB;IACzB,gDAAgD;IAChD,eAAe,EAAE,GAAiB;IAClC,qDAAqD;IACrD,aAAa,EAAE,GAAiB;IAChC,yDAAyD;IACzD,SAAS,EAAE,GAAiB;IAC5B,0EAA0E;IAC1E,YAAY,EAAE,GAAiB;IAC/B,+CAA+C;IAC/C,cAAc,EAAE,IAAkB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IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;AAC5D,CAAC;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,MAAM,CAAC,GAAY;IAClC,MAAM,CAAC,GAAG,KAAK,CAAC,GAAG,CAAC,CAAC;IAErB,sFAAsF;IACtF,yEAAyE;IACzE,IAAI,OAAO,iBAAiB,KAAK,WAAW,IAAI,CAAC,YAAY,iBAAiB,EAAE,CAAC;QAChF,MAAM,KAAK,GAAG,CAAC,UAAU,CAAC,CAAC,MAAM,EAAE,CAAC,CAAC;QACrC,IAAI,CAAC,CAAC,eAAe,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,eAAe,EAAE,CAAC,CAAC;QACxE,MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;QAC/B,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,OAAO,KAAK,MAAM,GAAG,CAAC,CAAC,CAAC,sBAAsB,MAAM,EAAE,CAAC;IAChF,CAAC;IAED,OAAO,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,IAAI,IAAI,eAAe,CAAC;AAC/C,CAAC","sourcesContent":["/**\n * Errors, including the code a peer reports when it resets a stream or closes the session.\n *\n * @module\n */\n\nimport { sharedStreamCode } from \"./ietf/error.ts\";\nimport type { IetfVersion } from \"./ietf/version.ts\";\nimport { TimeoutError } from \"./util/timeout.ts\";\n\n/** The nominal brand for session termination codes. */\ndeclare const SESSION_CODE: unique symbol;\n\n/** A code from the session termination registry. */\nexport type SessionCode = number & { readonly [SESSION_CODE]: true };\n\n/**\n * Codes a peer sends when terminating the session, mirroring the Rust `Session`.\n *\n * Specified by moq-lite, which reuses moq-transport's codes unchanged. Call `SessionCode(code)`\n * to construct an application code in the 64+ range. {@link StreamCode} is the other registry,\n * and the two are disjoint, so the same integer means different things in each.\n *\n * Codes 32-47 are reserved: nothing is sent there, and the draft gives a received one no\n * meaning, so treat anything not listed below as an unspecified error rather than guessing.\n *\n * @public\n */\nexport const SessionCode = Object.freeze(\n\tObject.assign((code: number): SessionCode => applicationCode(code) as SessionCode, {\n\t\t/** Ending the session normally, with no error. */\n\t\tCancel: 0x0 as SessionCode,\n\t\t/** Something went wrong that isn't worth a dedicated code. */\n\t\tInternal: 0x1 as SessionCode,\n\t\t/** The credentials don't grant the requested path or operation. Retrying will fail again. */\n\t\tUnauthorized: 0x2 as SessionCode,\n\t\t/** A protocol rule was broken; the session is unusable. */\n\t\tProtocolViolation: 0x3 as SessionCode,\n\t\t/** A key-value pair was malformed or repeated more than allowed. */\n\t\tKeyValueFormatting: 0x6 as SessionCode,\n\t\t/** The peer did not close within the GOAWAY drain deadline. */\n\t\tGoawayTimeout: 0x10 as SessionCode,\n\t\t/** A control message took too long. */\n\t\tTimeout: 0x11 as SessionCode,\n\t\t/** No version could be negotiated. */\n\t\tVersion: 0x15 as SessionCode,\n\t} as const),\n);\n\n/** The nominal brand for stream reset codes. */\ndeclare const STREAM_CODE: unique symbol;\n\n/** A code from the stream reset registry. */\nexport type StreamCode = number & { readonly [STREAM_CODE]: true };\n\n/**\n * Codes a peer sends when resetting a stream, mirroring the Rust `Stream`.\n *\n * The counterpart to {@link SessionCode}, and a disjoint space: a stream reset of 0 is\n * {@link StreamCode.Internal}, not a cancellation ({@link StreamCode.Cancel} is 1). Call\n * `StreamCode(code)` to construct an application code in the 64+ range.\n *\n * Conditions the shared codes don't cover are assigned in moq-lite's own 48-63 range, so a\n * received one is the named code. 32 through 47 is reserved: nothing is sent there and a\n * received one is an unspecified error.\n *\n * @public\n */\nexport const StreamCode = Object.freeze(\n\tObject.assign((code: number): StreamCode => applicationCode(code) as StreamCode, {\n\t\t/** Something went wrong that isn't worth a dedicated code. */\n\t\tInternal: 0x0 as StreamCode,\n\t\t/** The sender is done with this stream, not failing. A routine unsubscribe. */\n\t\tCancel: 0x1 as StreamCode,\n\t\t/** The content missed its delivery deadline. */\n\t\tDeliveryTimeout: 0x2 as StreamCode,\n\t\t/** The session ended, taking this stream with it. */\n\t\tSessionClosed: 0x3 as StreamCode,\n\t\t/** The session is going away (a GOAWAY was received). */\n\t\tGoingAway: 0x4 as StreamCode,\n\t\t/** The reader fell too far behind and content was dropped to catch up. */\n\t\tTooFarBehind: 0x5 as StreamCode,\n\t\t/** The track's content could not be parsed. */\n\t\tMalformedTrack: 0x12 as StreamCode,\n\t\t/** The peer took too long to answer a control request. */\n\t\tControlTimeout: 0x31 as StreamCode,\n\t\t/** The requested broadcast or track does not exist at the peer. */\n\t\tNotFound: 0x33 as StreamCode,\n\t\t/** The group was superseded by a newer one and dropped. */\n\t\tOld: 0x34 as StreamCode,\n\t\t/** The group was dropped under memory pressure, so it can be re-fetched. */\n\t\tEvicted: 0x35 as StreamCode,\n\t\t/** A frame declared a payload larger than the receiver accepts. */\n\t\tFrameTooLarge: 0x38 as StreamCode,\n\t\t/** The publisher could serve this request but has no capacity for it now. */\n\t\tNoCapacity: 0x30 as StreamCode,\n\t\t/** A group grew past its cache budget and was aborted. */\n\t\tGroupTooLarge: 0x32 as StreamCode,\n\t} as const),\n);\n\nfunction applicationCode(code: number): number {\n\tif (!Number.isInteger(code) || code < 64 || code > 0xffffffff) {\n\t\tthrow new RangeError(`invalid application error code: ${code}`);\n\t}\n\treturn code;\n}\n\n/**\n * An error the peer reported by closing the session, carrying its {@link SessionCode}.\n *\n * This surfaces on every transport, so catch this type rather than feature-detecting\n * `WebTransportError`, which a non-browser runtime never defines and the WebSocket fallback\n * never throws.\n *\n * ```ts\n * connection.error.subscribe((err) => {\n * if (err instanceof Session && err.code === SessionCode.Unauthorized) {\n * console.warn(\"server rejected the session\");\n * }\n * });\n * ```\n *\n * @public\n */\nexport class Session extends Error {\n\t/** The session code the peer sent, verbatim. */\n\treadonly code: SessionCode;\n\n\tconstructor(code: SessionCode, options?: { cause?: unknown; reason?: string }) {\n\t\tsuper(options?.reason ? `remote error: ${code} (${options.reason})` : `remote error: ${code}`, options);\n\t\tthis.name = \"Session\";\n\t\tthis.code = code;\n\t}\n}\n\n/** Options for a {@link Stream}. */\nexport interface StreamOptions {\n\t/** The failure this one wraps. */\n\tcause?: unknown;\n\t/** The peer's human-readable reason, appended to the default message. */\n\treason?: string;\n\t/** Replaces the default `remote error: <code>` text, for a condition raised locally. */\n\tmessage?: string;\n}\n\n/**\n * An error carrying a {@link StreamCode}: the code a peer sent when it reset a stream, or the\n * one this side sends when it resets one.\n *\n * This surfaces on every transport, so catch this type rather than feature-detecting\n * `WebTransportError`, which a non-browser runtime never defines and the WebSocket fallback\n * never throws. Local conditions with a code of their own subclass it ({@link TooFarBehind},\n * {@link FrameTooLarge}, {@link GroupTooLarge}, {@link NotFound}), so the same `code` check catches a condition\n * whether it was raised here or reported by the peer.\n *\n * ```ts\n * try {\n * frame = await group.readFrame();\n * } catch (err) {\n * if (err instanceof Stream && err.code === StreamCode.Cancel) return;\n * throw err;\n * }\n * ```\n *\n * @public\n */\nexport class Stream extends Error {\n\t/** The stream code; moq-lite resets forward it verbatim. */\n\treadonly code: StreamCode;\n\n\tconstructor(code: StreamCode, options?: StreamOptions) {\n\t\tsuper(\n\t\t\toptions?.message ??\n\t\t\t\t(options?.reason ? `remote error: ${code} (${options.reason})` : `remote error: ${code}`),\n\t\t\toptions,\n\t\t);\n\t\tthis.name = \"Stream\";\n\t\tthis.code = code;\n\t}\n}\n\n/**\n * The reader asked for a frame the group never held, so the stream has a gap.\n *\n * Raised locally by a frame read, and decoded from a moq-lite peer's `TOO_FAR_BEHIND` reset, since a gap\n * reads the same either way.\n *\n * @public\n */\nexport class TooFarBehind extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.TooFarBehind, {\n\t\t\t...options,\n\t\t\tmessage: \"lagged: frames were evicted before being read\",\n\t\t});\n\t\tthis.name = \"TooFarBehind\";\n\t}\n}\n\n/**\n * A frame is larger than a group can cache, so appending it would exceed the budget by itself.\n *\n * Raised locally by a frame write, and decoded from a moq-lite peer's `FRAME_TOO_LARGE` reset.\n * Mirrors the Rust `Error::FrameTooLarge`, which rejects the same frame before touching any state.\n *\n * @public\n */\nexport class FrameTooLarge extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.FrameTooLarge, {\n\t\t\t...options,\n\t\t\tmessage: \"frame too large: larger than a group can cache\",\n\t\t});\n\t\tthis.name = \"FrameTooLarge\";\n\t}\n}\n\n/**\n * A write grew the group past its cache budget, so the group is aborted.\n *\n * Raised locally by a frame write, and decoded from a moq-lite peer's `GROUP_TOO_LARGE`\n * reset. Mirrors the Rust `Error::GroupTooLarge`.\n *\n * @public\n */\nexport class GroupTooLarge extends Stream {\n\tconstructor(options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.GroupTooLarge, {\n\t\t\t...options,\n\t\t\tmessage: \"group too large: exceeded the cache budget\",\n\t\t});\n\t\tthis.name = \"GroupTooLarge\";\n\t}\n}\n\n/**\n * The requested broadcast or track is not served here.\n *\n * @public\n */\nexport class NotFound extends Stream {\n\tconstructor(what: string, options?: { cause?: unknown }) {\n\t\tsuper(StreamCode.NotFound, { ...options, message: `not found: ${what}` });\n\t\tthis.name = \"NotFound\";\n\t}\n}\n\n/**\n * A peer's GOAWAY named a redirect the connection refuses, or one it could not parse.\n *\n * Terminal: the peer is leaving, so the connection stops rather than redialing the old\n * address. Mirrors the Rust `Error::RefusedRedirect`.\n *\n * @public\n */\nexport class RefusedRedirect extends Error {\n\tconstructor(reason: string) {\n\t\tsuper(`GOAWAY redirect refused: ${reason}`);\n\t\tthis.name = \"RefusedRedirect\";\n\t}\n}\n\n/**\n * A peer broke the protocol in a way the spec says must end the session.\n *\n * Thrown where the violation is detected, rather than handled there: a decoder has no session\n * to close. The dispatch that owns the session watches for it and closes, so a nonconforming\n * peer cannot repeat the violation on the next stream.\n *\n * @public\n */\nexport class ProtocolViolation extends Error {\n\tconstructor(message: string, options?: { cause?: unknown }) {\n\t\tsuper(message, options);\n\t\tthis.name = \"ProtocolViolation\";\n\t}\n}\n\n/** Package-internal compatibility names used by the wire implementation. */\nexport { Session as SessionError, Stream as StreamError, TooFarBehind as Lagged };\n/** Package-internal compatibility name used by the wire implementation. */\nexport type StreamErrorOptions = StreamOptions;\n\n/** The WebTransport-shaped fields a stream reset code arrives in. */\ntype StreamErrorLike = { source?: unknown; streamErrorCode?: unknown };\n\nfunction streamCode(err: unknown): StreamCode | undefined {\n\tif (typeof err !== \"object\" || err === null) return undefined;\n\n\tconst { source, streamErrorCode } = err as StreamErrorLike;\n\tif (source !== \"stream\" || typeof streamErrorCode !== \"number\") return undefined;\n\n\treturn streamErrorCode as StreamCode;\n}\n\n/** Transport context for encoding and decoding errors. @internal */\ninterface TransportErrorOptions {\n\t/** The negotiated IETF draft, or absent for moq-lite. */\n\tversion?: IetfVersion;\n}\n\n/**\n * Which {@link StreamCode} to send when resetting a stream because of `err`.\n *\n * The counterpart to {@link fromTransport}, and the pair has to agree: a code we send for a\n * condition is the code we read that condition back from, or two peers disagree about what it\n * means. Mirrors the Rust `From<&Error> for Stream`.\n *\n * Lossy on purpose. An error describes what went wrong here, while the registry is what the peer\n * can act on, so anything without a code of its own degrades to {@link StreamCode.Internal}\n * rather than inventing one. A {@link Session} lands there too: the two registries are\n * disjoint, so forwarding its code onto a stream would mistranslate it.\n *\n * On an IETF stream the code has to be one the negotiated draft assigns the same meaning to,\n * so a condition it does not register degrades to INTERNAL_ERROR as well. See\n * {@link sharedStreamCode}.\n *\n * @internal\n */\nexport function toStreamCode(err: unknown, options?: TransportErrorOptions): StreamCode {\n\tconst code = localStreamCode(err);\n\tif (options?.version === undefined) return code;\n\treturn sharedStreamCode(code, options.version) ? code : StreamCode.Internal;\n}\n\n/** The moq-lite code for a local failure, before any draft has a say. */\nfunction localStreamCode(err: unknown): StreamCode {\n\tif (err instanceof Stream) return err.code;\n\tif (err instanceof TimeoutError) return StreamCode.DeliveryTimeout;\n\t// Session-scoped: the peer learns which rule it broke from the session close, not from here.\n\tif (err instanceof ProtocolViolation) return StreamCode.SessionClosed;\n\treturn StreamCode.Internal;\n}\n\n/**\n * The {@link StreamCode.ControlTimeout} error for a control request the peer never answered.\n *\n * A control request that outlives its deadline is not late content, so it does not go out as\n * {@link StreamCode.DeliveryTimeout} the way a bare {@link TimeoutError} would. Callers that\n * bound a request's response build this instead.\n *\n * @internal\n */\nexport function controlTimeout(cause: unknown): Stream {\n\tconst message = cause instanceof Error && cause.message ? cause.message : \"control request timed out\";\n\treturn new Stream(StreamCode.ControlTimeout, { cause, message });\n}\n\n/**\n * Decode a transport failure into a {@link Stream} when it carries a stream reset code,\n * otherwise pass it through.\n *\n * Native WebTransport rejects with a `WebTransportError`; the WebSocket fallback mints an error\n * with the same `source`/`streamErrorCode` fields. Reading the fields rather than the class\n * covers both, and works in a runtime with no `WebTransportError` at all.\n *\n * On moq-lite, a code with a local class decodes back into it, so a peer's condition is caught by\n * the same `instanceof` as one raised here.\n *\n * On an IETF stream a code keeps its value unless moq-lite claims that number for something\n * the draft does not: `0x4` is GOING_AWAY here but UNKNOWN_OBJECT_STATUS on draft-16 and 17,\n * and reading one back as the other would retire a session that is not going anywhere. Those\n * read as {@link StreamCode.Internal} with the wire value kept in the message, since\n * {@link StreamCode} is one numeric space and cannot hold a foreign code without lying about\n * it. A code moq-lite names nothing for survives intact: nothing can misread it.\n *\n * @internal Called at the transport boundary so the raw error never reaches an application.\n */\nexport function fromTransport(err: unknown, options?: TransportErrorOptions): Error {\n\tconst code = streamCode(err);\n\tif (code === undefined) return error(err);\n\tif (options?.version !== undefined && !sharedStreamCode(code, options.version) && claimedLocally(code)) {\n\t\treturn new Stream(StreamCode.Internal, { cause: err, message: `remote error: ${code}` });\n\t}\n\tif (code === StreamCode.TooFarBehind) return new TooFarBehind({ cause: err });\n\tif (code === StreamCode.FrameTooLarge) return new FrameTooLarge({ cause: err });\n\tif (code === StreamCode.GroupTooLarge) return new GroupTooLarge({ cause: err });\n\treturn new Stream(code, { cause: err });\n}\n\n/** The codes moq-lite names, which a foreign one must not borrow. */\nconst NAMED_CODES: ReadonlySet<number> = new Set(Object.values(StreamCode));\n\n/**\n * Whether moq-lite could give `code` a meaning of its own: one of its named codes, or\n * anywhere in the 64+ range, where `StreamCode(code)` mints an application code and an\n * application compares against its own. moq-transport registers nothing above 0x12 and has\n * no application range at all, so a foreign code landing there is never what it looks like.\n */\nfunction claimedLocally(code: number): boolean {\n\treturn code >= 64 || NAMED_CODES.has(code);\n}\n\nconst legacyWebTransportErrors = new WeakSet<object>();\n\n/**\n * Build the `reason` to hand `abort()` / `cancel()` so the transport puts `code` on the wire.\n *\n * Both the WebTransport spec and the WebSocket fallback take the reset code from a\n * `WebTransportError`'s `streamErrorCode` and send 0 for anything else, a plain `Error`\n * included. Since 0 is {@link StreamCode.Internal}, cancelling with a bare `Error` tells the\n * peer we failed rather than that we are done.\n *\n * The native constructor exists exactly where native WebTransport does, which is where the\n * fallback isn't used, so mint a matching shape elsewhere rather than feature-detect a global\n * that will not be there.\n *\n * @internal\n */\nexport function toTransport(code: StreamCode, message: string): Error {\n\tconst Native = (globalThis as { WebTransportError?: typeof WebTransportError }).WebTransportError;\n\tif (Native) {\n\t\tconst Legacy = Native as unknown as new (init: { message: string; streamErrorCode: number }) => Error;\n\t\tif (legacyWebTransportErrors.has(Native)) return new Legacy({ message, streamErrorCode: code });\n\n\t\ttry {\n\t\t\treturn new Native(message, { source: \"stream\", streamErrorCode: code });\n\t\t} catch (err) {\n\t\t\t// Chromium still implements the previous single-dictionary constructor.\n\t\t\tif (!(err instanceof TypeError)) throw err;\n\t\t\tlegacyWebTransportErrors.add(Native);\n\t\t\treturn new Legacy({ message, streamErrorCode: code });\n\t\t}\n\t}\n\n\treturn Object.assign(new Error(message), { source: \"stream\" as const, streamErrorCode: code });\n}\n\n/**\n * Decode a session close into its terminal error: `null` for a clean close\n * ({@link SessionCode.Cancel}), otherwise a {@link Session} carrying the peer's code.\n *\n * @internal Applied to the transport's `closed` info so the code survives to the application.\n */\nexport function fromClose(info: WebTransportCloseInfo): Session | null {\n\tconst code = (info.closeCode ?? SessionCode.Cancel) as SessionCode;\n\tif (code === SessionCode.Cancel) return null;\n\treturn new Session(code, { reason: info.reason });\n}\n\n/**\n * The session's close as the error it ends everything with, carrying the peer's code. A clean\n * close code is still an error here: whatever the close cut off did not end.\n *\n * @internal\n */\nexport function closeError(quic: WebTransport): Promise<Error> {\n\treturn quic.closed.then(\n\t\t(info) => fromClose(info) ?? new Session(SessionCode.Cancel, { reason: info.reason }),\n\t\t(err: unknown) => error(err),\n\t);\n}\n\n/**\n * Report a failure the session's close caused as the session's own error, which carries the\n * peer's close code; any other failure passes through.\n *\n * @internal\n */\nexport async function sessionCause(quic: WebTransport | undefined, err: unknown): Promise<Error> {\n\tconst source = typeof err === \"object\" && err !== null ? (err as { source?: unknown }).source : undefined;\n\tif (quic && source === \"session\") return closeError(quic);\n\treturn error(err);\n}\n\n/**\n * Coerce an unknown thrown value into an `Error`.\n *\n * @internal\n */\nexport function error(err: unknown): Error {\n\treturn err instanceof Error ? err : new Error(String(err));\n}\n\n/**\n * Format an error into a non-empty, human-readable string for logging.\n *\n * Safari always leaves `WebTransportError.message` blank, so a bare `err.message` degrades to\n * an empty string and the reason is lost. This falls back to the error type name and appends\n * the WebTransport `source` and application `streamErrorCode`, so the log line always says\n * something.\n */\nexport function reason(err: unknown): string {\n\tconst e = error(err);\n\n\t// WebTransportError carries the failure origin and the peer's application error code,\n\t// often the only identifying detail since WebKit leaves `message` empty.\n\tif (typeof WebTransportError !== \"undefined\" && e instanceof WebTransportError) {\n\t\tconst parts = [`source=${e.source}`];\n\t\tif (e.streamErrorCode !== null) parts.push(`code=${e.streamErrorCode}`);\n\t\tconst detail = parts.join(\" \");\n\t\treturn e.message ? `${e.message} (${detail})` : `WebTransportError: ${detail}`;\n\t}\n\n\treturn e.message || e.name || \"unknown error\";\n}\n"]}
package/errors.d.ts CHANGED
@@ -3,5 +3,5 @@
3
3
  *
4
4
  * @module
5
5
  */
6
- export { FrameTooLarge, GroupTooLarge, NotFound, ProtocolViolation, Session, Stream, type StreamOptions, TooFarBehind, } from "./error";
6
+ export { FrameTooLarge, GroupTooLarge, NotFound, ProtocolViolation, RefusedRedirect, Session, Stream, type StreamOptions, TooFarBehind, } from "./error";
7
7
  //# sourceMappingURL=errors.d.ts.map
package/errors.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACN,aAAa,EACb,aAAa,EACb,QAAQ,EACR,iBAAiB,EACjB,OAAO,EACP,MAAM,EACN,KAAK,aAAa,EAClB,YAAY,GACZ,MAAM,YAAY,CAAC"}
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACN,aAAa,EACb,aAAa,EACb,QAAQ,EACR,iBAAiB,EACjB,eAAe,EACf,OAAO,EACP,MAAM,EACN,KAAK,aAAa,EAClB,YAAY,GACZ,MAAM,YAAY,CAAC"}
package/errors.js CHANGED
@@ -4,5 +4,5 @@
4
4
  *
5
5
  * @module
6
6
  */
7
- export { FrameTooLarge, GroupTooLarge, NotFound, ProtocolViolation, Session, Stream, TooFarBehind, } from "./error.js";
7
+ export { FrameTooLarge, GroupTooLarge, NotFound, ProtocolViolation, RefusedRedirect, Session, Stream, TooFarBehind, } from "./error.js";
8
8
  //# sourceMappingURL=errors.js.map
package/errors.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACN,aAAa,EACb,aAAa,EACb,QAAQ,EACR,iBAAiB,EACjB,OAAO,EACP,MAAM,EAEN,YAAY,GACZ,MAAM,YAAY,CAAC","sourcesContent":["/**\n * Session and stream error types.\n *\n * @module\n */\nexport {\n\tFrameTooLarge,\n\tGroupTooLarge,\n\tNotFound,\n\tProtocolViolation,\n\tSession,\n\tStream,\n\ttype StreamOptions,\n\tTooFarBehind,\n} from \"./error.ts\";\n"]}
1
+ {"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACN,aAAa,EACb,aAAa,EACb,QAAQ,EACR,iBAAiB,EACjB,eAAe,EACf,OAAO,EACP,MAAM,EAEN,YAAY,GACZ,MAAM,YAAY,CAAC","sourcesContent":["/**\n * Session and stream error types.\n *\n * @module\n */\nexport {\n\tFrameTooLarge,\n\tGroupTooLarge,\n\tNotFound,\n\tProtocolViolation,\n\tRefusedRedirect,\n\tSession,\n\tStream,\n\ttype StreamOptions,\n\tTooFarBehind,\n} from \"./error.ts\";\n"]}
package/group.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"group.d.ts","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAgB,KAAK,UAAU,EAA6B,MAAM,cAAc,CAAC;AAGxF,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,4GAA4G;AAC5G,eAAO,MAAM,qBAAqB,QAAmB,CAAC;AAEtD,uHAAuH;AACvH,eAAO,MAAM,gBAAgB,OAAO,CAAC;AAErC;;;;;GAKG;AACH,MAAM,WAAW,KAAK;IACrB,yBAAyB;IACzB,OAAO,EAAE,UAAU,CAAC;IACpB;;;OAGG;IACH,SAAS,EAAE,SAAS,CAAC;CACrB;AAED,+CAA+C;AAC/C,MAAM,WAAW,WAAW;IAC3B;;;;;OAKG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;CACd;AAED,gCAAgC;AAChC,MAAM,WAAW,IAAI;IACpB,sDAAsD;IACtD,QAAQ,EAAE,MAAM,CAAC;CACjB;AAqCD;;;;GAIG;AACH,qBAAa,QAAQ;;IACpB,sDAAsD;IACtD,QAAQ,CAAC,QAAQ,EA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AG,SAAS,CAAC,CAIlG;IAED,sEAAsE;IAChE,UAAU,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAG9C;IAED,2DAA2D;IACrD,QAAQ,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAG7C;IAED,0EAA0E;IACpE,QAAQ,IAAI,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CAG7C;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAK,CAAC,EAAE,KAAK,QAGlB;CACD"}
package/group.js CHANGED
@@ -340,14 +340,15 @@ export class Consumer {
340
340
  this.#verdict.set(this.#terminal ?? null);
341
341
  return true;
342
342
  }
343
+ // Takes a thunk rather than a started promise, so a group already past its budget
344
+ // never begins the write: an abandoned write would reject later with no handler.
343
345
  #guard(operation) {
344
- if (this.#expire(true))
345
- return Promise.reject(this.#terminal);
346
+ this.#expire(true);
346
347
  if (this.#terminal)
347
348
  return Promise.reject(this.#terminal);
348
349
  const expiry = this.#expiry;
349
350
  if (!expiry)
350
- return operation;
351
+ return operation();
351
352
  return new Promise((resolve, reject) => {
352
353
  let settled = false;
353
354
  const disposes = [];
@@ -368,7 +369,7 @@ export class Consumer {
368
369
  };
369
370
  for (const changed of expiry.changed)
370
371
  disposes.push(changed.subscribe(check));
371
- operation.then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
372
+ operation().then((value) => finish(() => resolve(value)), (error) => finish(() => reject(error)));
372
373
  check();
373
374
  });
374
375
  }
package/group.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA8C,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,KAAK,EAAuB,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,SAAS,EA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AAC,UAAU;QACf,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACpE,CAAC;IAED,2DAA2D;IAC3D,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC;QACtC,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9C,CAAC;IAED,0EAA0E;IAC1E,KAAK,CAAC,QAAQ;QACb,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,SAAS,EAAE,CAAC;QACrC,OAAO,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACnD,CAAC;IAED,+EAA+E;IAC/E,KAAK,CAAC,KAAa;QAClB,IAAI,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;YAAE,OAAO,CAAC,iBAAiB;QACtE,IAAI,CAAC,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;IACvC,CAAC;CACD","sourcesContent":["/**\n * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.\n *\n * @module\n */\nimport { type Dispose, type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport { FrameTooLarge, GroupTooLarge, TooFarBehind } from \"./error.ts\";\nimport { hooks, type ReadGroupFrame } from \"./internal.ts\";\nimport { Timestamp } from \"./time.ts\";\n\n/** Maximum bytes of frames in a group. A write that would exceed this aborts with {@link GroupTooLarge}. */\nexport const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;\n\n/** Maximum number of frames in a group. 8192 is the largest legal group; the 8193rd write is {@link GroupTooLarge}. */\nexport const MAX_GROUP_FRAMES = 8192;\n\n/**\n * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.\n *\n * The timestamp carries its own scale, so a track can pick its units; the wire layer\n * converts it into the track's negotiated timescale.\n */\nexport interface Frame {\n\t/** The frame payload. */\n\tpayload: Uint8Array;\n\t/**\n\t * Presentation timestamp. Required: for a payload with no presentation time of its own\n\t * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.\n\t */\n\ttimestamp: Timestamp;\n}\n\n/** Options for a sequence-aware frame read. */\nexport interface ReadOptions {\n\t/**\n\t * The lowest sequence number the caller wants; defaults to the whole group.\n\t *\n\t * Frames below it are discarded instead of returned. The group still starts at frame 0,\n\t * so this is a reader filter, not a missing prefix.\n\t */\n\tfrom?: number;\n}\n\n/** Immutable group metadata. */\nexport interface Info {\n\t/** Sequence number of this group within its track. */\n\tsequence: number;\n}\n\n/** Reactive backing state shared by the group producer and one consumer. */\nclass GroupState {\n\treadonly sequence: number;\n\tframes = new Signal<Frame[]>([]);\n\tclosed = new Once<Error | null>();\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n\n\t// Absolute sequence of the frame at the front of `frames`, advanced by a read: the\n\t// sequence the next read returns.\n\tstart = 0;\n\n\tcacheBytes = 0;\n\t// The first frame's timestamp, retained after reads.\n\ttimestamp?: Timestamp;\n\t// The newest frame's timestamp: where a reader that has taken every frame sits.\n\tlatest?: Timestamp;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\t}\n}\n\nfunction appendFrame(state: GroupState, frame: Frame) {\n\tif (state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\n\tstate.timestamp ??= frame.timestamp;\n\tstate.latest = frame.timestamp;\n\tstate.cacheBytes += frame.payload.byteLength;\n\tstate.frames.mutate((frames) => {\n\t\tframes.push(frame);\n\t});\n\n\tstate.total.update((total) => total + 1);\n}\n\n/**\n * The write side of an ordered stream of frames within a track.\n *\n * @public\n */\nexport class Producer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#mirrors?: Set<GroupState>;\n\n\t// Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to\n\t// cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),\n\t// so this is what stops a reader-less fetch instead of the stream ending on its own.\n\t#used = new Signal<boolean>(false);\n\n\t// When the group was created or last written. Retention ages a group from this,\n\t// not from its creation, so a group still being filled is never reclaimed.\n\t#activity = performance.now();\n\n\tconstructor(sequence: number) {\n\t\tthis.#state = new GroupState(sequence);\n\t\tthis.sequence = sequence;\n\t}\n\n\t/**\n\t * When the group was created or last written, in `performance.now()` milliseconds.\n\t *\n\t * @internal Track retention only.\n\t */\n\tget activity(): number {\n\t\treturn this.#activity;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this group. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/**\n\t * Create an independent read handle that receives every frame written here.\n\t *\n\t * Frames written so far are replayed synchronously; later writes and close are teed\n\t * in as they happen.\n\t *\n\t * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.\n\t */\n\tmirror(): Consumer {\n\t\tconst dst = new GroupState(this.sequence);\n\t\tdst.timestamp = this.#state.timestamp;\n\t\tdst.latest = this.#state.latest;\n\t\tfor (const frame of this.#state.frames.peek()) appendFrame(dst, frame);\n\t\tdst.start = this.#state.start;\n\t\t// The replay only covers what is still buffered, so the count has to come from the\n\t\t// source: it is what names a frame's absolute sequence, and what a publisher reads\n\t\t// to resolve the live edge.\n\t\tdst.total.set(this.#state.total.peek());\n\n\t\tconst closed = this.#state.closed.peek();\n\t\tif (closed !== undefined) {\n\t\t\tdst.closed.set(closed);\n\t\t\treturn makeConsumer(dst);\n\t\t}\n\n\t\tthis.#mirrors ??= new Set();\n\t\tthis.#mirrors.add(dst);\n\t\tthis.#used.set(true);\n\n\t\t// Track this mirror's close eagerly (not just lazily on the next write) so demand drops the\n\t\t// moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.\n\t\tconst dispose = dst.closed.subscribe((c) => {\n\t\t\tif (c === undefined) return;\n\t\t\tthis.#mirrors?.delete(dst);\n\t\t\tthis.#used.set((this.#mirrors?.size ?? 0) > 0);\n\t\t\tdispose();\n\t\t});\n\n\t\treturn makeConsumer(dst);\n\t}\n\n\t/**\n\t * Whether any mirror reader is currently attached.\n\t *\n\t * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader\n\t * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't\n\t * rely on the stream ending on its own.\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tget used(): Getter<boolean> {\n\t\treturn this.#used;\n\t}\n\n\t/**\n\t * Resolves once no mirror reader remains (or the group closes).\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tasync unused(): Promise<void> {\n\t\twhile (this.#used.peek() && this.#state.closed.peek() === undefined) {\n\t\t\tawait Signal.race(this.#used, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Writes a frame to the group. */\n\twriteFrame(frame: Frame) {\n\t\t// Closed first: a write after a clean close at the cap would otherwise take the\n\t\t// overflow path, wipe committed frames, and leave readers with an empty success.\n\t\tif (this.#state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\t\t// A frame past the cache cap would make the group exceed its budget by itself, so\n\t\t// accepting it would report success for a write nothing can ever read. Rust rejects\n\t\t// it up front with `Error::FrameTooLarge`; do the same rather than silently dropping it.\n\t\tif (frame.payload.byteLength > MAX_GROUP_CACHE_BYTES) throw new FrameTooLarge();\n\t\tif (\n\t\t\tthis.#state.total.peek() >= MAX_GROUP_FRAMES ||\n\t\t\tthis.#state.cacheBytes + frame.payload.byteLength > MAX_GROUP_CACHE_BYTES\n\t\t) {\n\t\t\tconst err = new GroupTooLarge();\n\t\t\tthis.#state.frames.set([]);\n\t\t\tthis.#state.cacheBytes = 0;\n\t\t\tif (this.#mirrors) {\n\t\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\t\tmirror.frames.set([]);\n\t\t\t\t\tmirror.cacheBytes = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.close(err);\n\t\t\tthrow err;\n\t\t}\n\n\t\tthis.#activity = performance.now();\n\t\tappendFrame(this.#state, frame);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() !== undefined) this.#mirrors.delete(mirror);\n\t\t\t\telse appendFrame(mirror, frame);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */\n\twriteString(str: string) {\n\t\tthis.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });\n\t}\n\n\t/** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });\n\t}\n\n\t/** True once the group has been closed. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\tthis.#state.closed.set(abort ?? null);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() === undefined) mirror.closed.set(abort ?? null);\n\t\t\t}\n\t\t\tthis.#mirrors.clear();\n\t\t}\n\t}\n}\n\nlet makeConsumer: (state: GroupState) => Consumer;\n\n// A consumer can finish from its own expiry verdict or from the shared group state. Keep\n// one stable public handle while letting peek() observe either source synchronously, before\n// signal subscribers run in the next microtask.\nclass CombinedClosed implements GetPromise<Error | null> {\n\t#preferred: Once<Error | null>;\n\t#source: Once<Error | null>;\n\t#sourceCleanReady: () => boolean;\n\t#value = new Once<Error | null>();\n\t#dispose?: Dispose;\n\n\tconstructor(preferred: Once<Error | null>, source: Once<Error | null>, sourceCleanReady: () => boolean) {\n\t\tthis.#preferred = preferred;\n\t\tthis.#source = source;\n\t\tthis.#sourceCleanReady = sourceCleanReady;\n\t\tif (this.#sync()) return;\n\n\t\tconst dispose = [preferred.changed(() => this.#sync()), source.changed(() => this.#sync())];\n\t\tthis.#dispose = () => {\n\t\t\tfor (const close of dispose) close();\n\t\t};\n\t}\n\n\t#sync(): boolean {\n\t\tif (this.#value.peek() !== undefined) return true;\n\t\tconst preferred = this.#preferred.peek();\n\t\tconst source = this.#source.peek();\n\t\tconst value =\n\t\t\tpreferred !== undefined\n\t\t\t\t? preferred\n\t\t\t\t: source instanceof Error || this.#sourceCleanReady()\n\t\t\t\t\t? source\n\t\t\t\t\t: undefined;\n\t\tif (value === undefined) return false;\n\n\t\tthis.#value.set(value);\n\t\tthis.#dispose?.();\n\t\tthis.#dispose = undefined;\n\t\treturn true;\n\t}\n\n\trefresh() {\n\t\tthis.#sync();\n\t}\n\n\tpeek(): Error | null | undefined {\n\t\tthis.#sync();\n\t\treturn this.#value.peek();\n\t}\n\n\tchanged(): Promise<Error | null | undefined>;\n\tchanged(fn: (value: Error | null | undefined) => void): Dispose;\n\tchanged(fn?: (value: Error | null | undefined) => void): Promise<Error | null | undefined> | Dispose {\n\t\tthis.#sync();\n\t\treturn fn ? this.#value.changed(fn) : this.#value.changed();\n\t}\n\n\tsubscribe(fn: (value: Error | null | undefined) => void): Dispose {\n\t\tthis.#sync();\n\t\treturn this.#value.subscribe(fn);\n\t}\n\n\t// biome-ignore lint/suspicious/noThenProperty: CombinedClosed is intentionally awaitable.\n\tthen<R1 = Error | null, R2 = never>(\n\t\tonFulfilled?: ((value: Error | null) => R1 | PromiseLike<R1>) | null,\n\t\tonRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n\t): PromiseLike<R1 | R2> {\n\t\tthis.#sync();\n\t\treturn this.#value.then(onFulfilled, onRejected);\n\t}\n}\n\n/**\n * The read side of an ordered stream of frames within a track.\n *\n * Created internally: obtain one from {@link Producer.consume} or a track subscriber's\n * group reads.\n *\n * @public\n */\nexport class Consumer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#expiry?: { expired: () => boolean; changed: readonly Getter<unknown>[] };\n\t// Sticky verdicts, set once. `#ended` is a drained group the budget gave up on,\n\t// which is indistinguishable from one that ended: nothing was lost, so it reads as\n\t// the end of the group. `#terminal` is a failure, including a budget that gave up\n\t// while content was still unread.\n\t#ended = false;\n\t#terminal?: Error;\n\t#verdict = new Once<Error | null>();\n\t#closed?: CombinedClosed;\n\t#pendingFrames = 0;\n\n\tprivate constructor(state: GroupState) {\n\t\tthis.#state = state;\n\t\tthis.sequence = state.sequence;\n\t}\n\n\t/**\n\t * Settles when this consumer reaches a terminal state: `null` after a clean close has no\n\t * unread or in-flight frames, or the terminal {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\tthis.#closed ??= new CombinedClosed(\n\t\t\tthis.#verdict,\n\t\t\tthis.#state.closed,\n\t\t\t() => this.#state.frames.peek().length === 0 && this.#pendingFrames === 0,\n\t\t);\n\t\treturn this.#closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state);\n\t\thooks.groupTimestamp = (group) => group.#state.timestamp;\n\t\thooks.groupLatest = (group) => group.#state.latest;\n\t\thooks.expireGroup = (group, expiry) => {\n\t\t\tgroup.#expiry = expiry;\n\t\t};\n\t\thooks.guardGroup = (group, operation) => group.#guard(operation);\n\t\thooks.readGroupFrame = (group, from) => group.#readFramePosition(true, from);\n\t\thooks.evictGroup = (group) => {\n\t\t\tgroup.#evict();\n\t\t};\n\t}\n\n\t// Evaluate the drift budget for a read that has nothing buffered and is about to\n\t// wait. A group with frames in hand is always drained: the budget bounds a group\n\t// that has stalled while the live edge moved on, not a reader slower than the wire.\n\t// Returns true if a verdict was just reached, so the caller re-checks.\n\t//\n\t// `unread` is for a caller that still holds content the reader has not seen (a\n\t// publisher part-way through writing a frame): giving up there is a truncation, so\n\t// it fails rather than ending.\n\t#expire(unread = false): boolean {\n\t\tif (this.#terminal || this.#ended) return false;\n\t\tif (this.#state.closed.peek() instanceof Error) return false;\n\t\tif (!this.#expiry?.expired()) return false;\n\n\t\tif (unread) {\n\t\t\tthis.#terminal = new Error(\"group exceeded the subscription max age budget\");\n\t\t} else {\n\t\t\tthis.#ended = true;\n\t\t}\n\t\tif (this.#verdict.peek() === undefined) this.#verdict.set(this.#terminal ?? null);\n\t\treturn true;\n\t}\n\n\t#guard<T>(operation: Promise<T>): Promise<T> {\n\t\tif (this.#expire(true)) return Promise.reject(this.#terminal);\n\t\tif (this.#terminal) return Promise.reject(this.#terminal);\n\t\tconst expiry = this.#expiry;\n\t\tif (!expiry) return operation;\n\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst disposes: Dispose[] = [];\n\t\t\tconst finish = (fn: () => void) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tfor (const dispose of disposes) dispose();\n\t\t\t\tfn();\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tthis.#expire(true);\n\t\t\t\tif (this.#terminal) {\n\t\t\t\t\tconst error = this.#terminal;\n\t\t\t\t\tfinish(() => reject(error));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfor (const changed of expiry.changed) disposes.push(changed.subscribe(check));\n\t\t\toperation.then(\n\t\t\t\t(value) => finish(() => resolve(value)),\n\t\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t\t);\n\t\t\tcheck();\n\t\t});\n\t}\n\n\t#evict() {\n\t\tconst frames = this.#state.frames.peek();\n\t\tif (frames.length > 0) {\n\t\t\t// Unread content is going away either way. If the budget had already given up\n\t\t\t// on this group that is the more specific reason, so ask it first; otherwise\n\t\t\t// the reader simply lagged behind the cache.\n\t\t\tthis.#expire(true);\n\t\t\tif (!this.#terminal && !this.#ended) {\n\t\t\t\tthis.#terminal = new TooFarBehind();\n\t\t\t\tif (this.#verdict.peek() === undefined) this.#verdict.set(this.#terminal);\n\t\t\t}\n\t\t}\n\t\tif (frames.length > 0) {\n\t\t\tthis.#state.start += frames.length;\n\t\t}\n\t\tthis.#state.cacheBytes = 0;\n\t\tthis.#state.frames.set([]);\n\t}\n\n\tasync #changed(): Promise<void> {\n\t\tif (!this.#expiry) {\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t\treturn;\n\t\t}\n\t\tawait Signal.race(this.#state.frames, this.#state.closed, ...this.#expiry.changed);\n\t}\n\n\t#readBufferedFrame(pending = false): ReadGroupFrame | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst buffered = frames.shift();\n\t\tif (!buffered) return undefined;\n\n\t\tconst sequence = this.#state.start++;\n\t\tif (pending) this.#pendingFrames++;\n\t\tlet completed = false;\n\t\treturn {\n\t\t\tsequence,\n\t\t\tframe: buffered,\n\t\t\tcomplete: () => {\n\t\t\t\tif (completed) return;\n\t\t\t\tcompleted = true;\n\t\t\t\tif (pending) this.#pendingFrames--;\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t},\n\t\t};\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn (\n\t\t\tthis.#terminal !== undefined ||\n\t\t\tthis.#ended ||\n\t\t\t(this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined)\n\t\t);\n\t}\n\n\t/** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */\n\tget isClosed(): boolean {\n\t\treturn this.#terminal !== undefined || this.#ended || this.#state.closed.peek() !== undefined;\n\t}\n\n\t/**\n\t * How many frames the group has held, including any already read.\n\t *\n\t * It is also the next frame's sequence number, so `frameCount - 1` names the newest\n\t * frame written so far. A publisher snapshots it to resolve the track's live edge.\n\t */\n\tget frameCount(): number {\n\t\treturn this.#state.total.peek();\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is not by itself\n\t * end-of-group: check {@link done} to tell \"no frame buffered yet\" from \"finished\".\n\t */\n\ttryReadFrame(): Frame | undefined {\n\t\tif (this.#terminal || this.#ended) return undefined;\n\t\tconst read = this.#readBufferedFrame();\n\t\tread?.complete();\n\t\treturn read?.frame;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): ({ sequence: number } & Frame) | undefined {\n\t\tif (this.#terminal || this.#ended) return undefined;\n\t\tconst read = this.#readBufferedFrame();\n\t\tif (!read) return undefined;\n\t\tread.complete();\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Resolves once {@link readFrame} would not block. */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#terminal || this.#ended) return;\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek() !== undefined) {\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#expire()) return;\n\t\t\tawait this.#changed();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrame(): Promise<Frame | undefined> {\n\t\treturn (await this.#readFramePosition())?.frame;\n\t}\n\n\tasync #readFramePosition(pending = false, from = 0): Promise<ReadGroupFrame | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#terminal) throw this.#terminal;\n\t\t\tif (this.#ended) return;\n\n\t\t\tconst read = this.#readBufferedFrame(pending);\n\t\t\tif (read) {\n\t\t\t\tif (read.sequence < from) {\n\t\t\t\t\tread.complete();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!pending) read.complete();\n\t\t\t\treturn read;\n\t\t\t}\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) {\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Nothing buffered and the group is still open: this wait is the stall the\n\t\t\t// drift budget bounds, and the only place it applies.\n\t\t\tif (this.#expire()) continue;\n\t\t\tawait this.#changed();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame along with its sequence number within the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrameSequence(options?: ReadOptions): Promise<({ sequence: number } & Frame) | undefined> {\n\t\tconst read = await this.#readFramePosition(false, options?.from ?? 0);\n\t\tif (!read) return undefined;\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Reads the next frame and decodes its payload as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame.payload) : undefined;\n\t}\n\n\t/** Reads the next frame and parses its payload as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes its payload as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame.payload[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. Idempotent. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return; // already closed\n\t\tthis.#state.closed.set(abort ?? null);\n\t}\n}\n"]}
1
+ {"version":3,"file":"group.js","sourceRoot":"","sources":["../src/group.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAA8C,IAAI,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACxF,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AACxE,OAAO,EAAE,KAAK,EAAuB,MAAM,eAAe,CAAC;AAC3D,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAEtC,4GAA4G;AAC5G,MAAM,CAAC,MAAM,qBAAqB,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAEtD,uHAAuH;AACvH,MAAM,CAAC,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAmCrC,4EAA4E;AAC5E,MAAM,UAAU;IACN,QAAQ,CAAS;IAC1B,MAAM,GAAG,IAAI,MAAM,CAAU,EAAE,CAAC,CAAC;IACjC,MAAM,GAAG,IAAI,IAAI,EAAgB,CAAC;IAClC,KAAK,GAAG,IAAI,MAAM,CAAS,CAAC,CAAC,CAAC,CAAC,mDAAmD;IAElF,mFAAmF;IACnF,kCAAkC;IAClC,KAAK,GAAG,CAAC,CAAC;IAEV,UAAU,GAAG,CAAC,CAAC;IACf,qDAAqD;IACrD,SAAS,CAAa;IACtB,gFAAgF;IAChF,MAAM,CAAa;IAEnB,YAAY,QAAgB;QAC3B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAC1B,CAAC;CACD;AAED,SAAS,WAAW,CAAC,KAAiB,EAAE,KAAY;IACnD,IAAI,KAAK,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,SAAS;QAAE,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAE1E,KAAK,CAAC,SAAS,KAAK,KAAK,CAAC,SAAS,CA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ACvC,CAAC;CACD","sourcesContent":["/**\n * Group role handles: an ordered stream of frames within a track, delivered over one QUIC stream.\n *\n * @module\n */\nimport { type Dispose, type GetPromise, type Getter, Once, Signal } from \"@moq/signals\";\nimport { FrameTooLarge, GroupTooLarge, TooFarBehind } from \"./error.ts\";\nimport { hooks, type ReadGroupFrame } from \"./internal.ts\";\nimport { Timestamp } from \"./time.ts\";\n\n/** Maximum bytes of frames in a group. A write that would exceed this aborts with {@link GroupTooLarge}. */\nexport const MAX_GROUP_CACHE_BYTES = 32 * 1024 * 1024;\n\n/** Maximum number of frames in a group. 8192 is the largest legal group; the 8193rd write is {@link GroupTooLarge}. */\nexport const MAX_GROUP_FRAMES = 8192;\n\n/**\n * A frame buffered in a group: its presentation {@link Timestamp} and payload bytes.\n *\n * The timestamp carries its own scale, so a track can pick its units; the wire layer\n * converts it into the track's negotiated timescale.\n */\nexport interface Frame {\n\t/** The frame payload. */\n\tpayload: Uint8Array;\n\t/**\n\t * Presentation timestamp. Required: for a payload with no presentation time of its own\n\t * (a JSON catalog, control state) pass {@link Timestamp.now} explicitly.\n\t */\n\ttimestamp: Timestamp;\n}\n\n/** Options for a sequence-aware frame read. */\nexport interface ReadOptions {\n\t/**\n\t * The lowest sequence number the caller wants; defaults to the whole group.\n\t *\n\t * Frames below it are discarded instead of returned. The group still starts at frame 0,\n\t * so this is a reader filter, not a missing prefix.\n\t */\n\tfrom?: number;\n}\n\n/** Immutable group metadata. */\nexport interface Info {\n\t/** Sequence number of this group within its track. */\n\tsequence: number;\n}\n\n/** Reactive backing state shared by the group producer and one consumer. */\nclass GroupState {\n\treadonly sequence: number;\n\tframes = new Signal<Frame[]>([]);\n\tclosed = new Once<Error | null>();\n\ttotal = new Signal<number>(0); // The total number of frames in the group thus far\n\n\t// Absolute sequence of the frame at the front of `frames`, advanced by a read: the\n\t// sequence the next read returns.\n\tstart = 0;\n\n\tcacheBytes = 0;\n\t// The first frame's timestamp, retained after reads.\n\ttimestamp?: Timestamp;\n\t// The newest frame's timestamp: where a reader that has taken every frame sits.\n\tlatest?: Timestamp;\n\n\tconstructor(sequence: number) {\n\t\tthis.sequence = sequence;\n\t}\n}\n\nfunction appendFrame(state: GroupState, frame: Frame) {\n\tif (state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\n\tstate.timestamp ??= frame.timestamp;\n\tstate.latest = frame.timestamp;\n\tstate.cacheBytes += frame.payload.byteLength;\n\tstate.frames.mutate((frames) => {\n\t\tframes.push(frame);\n\t});\n\n\tstate.total.update((total) => total + 1);\n}\n\n/**\n * The write side of an ordered stream of frames within a track.\n *\n * @public\n */\nexport class Producer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#mirrors?: Set<GroupState>;\n\n\t// Whether any mirror reader is attached (see {@link used}). Fetch coalescing watches it to\n\t// cancel an abandoned download; a group can stay open indefinitely (a catalog or JSON stream),\n\t// so this is what stops a reader-less fetch instead of the stream ending on its own.\n\t#used = new Signal<boolean>(false);\n\n\t// When the group was created or last written. Retention ages a group from this,\n\t// not from its creation, so a group still being filled is never reclaimed.\n\t#activity = performance.now();\n\n\tconstructor(sequence: number) {\n\t\tthis.#state = new GroupState(sequence);\n\t\tthis.sequence = sequence;\n\t}\n\n\t/**\n\t * When the group was created or last written, in `performance.now()` milliseconds.\n\t *\n\t * @internal Track retention only.\n\t */\n\tget activity(): number {\n\t\treturn this.#activity;\n\t}\n\n\t/**\n\t * Settles once the group closes: `null` on a clean close, or the abort {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\treturn this.#state.closed;\n\t}\n\n\t/** A read handle for this group. */\n\tconsume(): Consumer {\n\t\treturn makeConsumer(this.#state);\n\t}\n\n\t/**\n\t * Create an independent read handle that receives every frame written here.\n\t *\n\t * Frames written so far are replayed synchronously; later writes and close are teed\n\t * in as they happen.\n\t *\n\t * @internal Track fan-out and fetch coalescing only. Use {@link consume} instead.\n\t */\n\tmirror(): Consumer {\n\t\tconst dst = new GroupState(this.sequence);\n\t\tdst.timestamp = this.#state.timestamp;\n\t\tdst.latest = this.#state.latest;\n\t\tfor (const frame of this.#state.frames.peek()) appendFrame(dst, frame);\n\t\tdst.start = this.#state.start;\n\t\t// The replay only covers what is still buffered, so the count has to come from the\n\t\t// source: it is what names a frame's absolute sequence, and what a publisher reads\n\t\t// to resolve the live edge.\n\t\tdst.total.set(this.#state.total.peek());\n\n\t\tconst closed = this.#state.closed.peek();\n\t\tif (closed !== undefined) {\n\t\t\tdst.closed.set(closed);\n\t\t\treturn makeConsumer(dst);\n\t\t}\n\n\t\tthis.#mirrors ??= new Set();\n\t\tthis.#mirrors.add(dst);\n\t\tthis.#used.set(true);\n\n\t\t// Track this mirror's close eagerly (not just lazily on the next write) so demand drops the\n\t\t// moment the last reader leaves, letting an abandoned fetch cancel even with no more frames.\n\t\tconst dispose = dst.closed.subscribe((c) => {\n\t\t\tif (c === undefined) return;\n\t\t\tthis.#mirrors?.delete(dst);\n\t\t\tthis.#used.set((this.#mirrors?.size ?? 0) > 0);\n\t\t\tdispose();\n\t\t});\n\n\t\treturn makeConsumer(dst);\n\t}\n\n\t/**\n\t * Whether any mirror reader is currently attached.\n\t *\n\t * Pairs with {@link unused}. Fetch coalescing watches it to cancel a download once every reader\n\t * has gone: a group can stay open indefinitely (a catalog track, a JSON stream), so it can't\n\t * rely on the stream ending on its own.\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tget used(): Getter<boolean> {\n\t\treturn this.#used;\n\t}\n\n\t/**\n\t * Resolves once no mirror reader remains (or the group closes).\n\t *\n\t * @internal Track fan-out and fetch coalescing only.\n\t */\n\tasync unused(): Promise<void> {\n\t\twhile (this.#used.peek() && this.#state.closed.peek() === undefined) {\n\t\t\tawait Signal.race(this.#used, this.#state.closed);\n\t\t}\n\t}\n\n\t/** Writes a frame to the group. */\n\twriteFrame(frame: Frame) {\n\t\t// Closed first: a write after a clean close at the cap would otherwise take the\n\t\t// overflow path, wipe committed frames, and leave readers with an empty success.\n\t\tif (this.#state.closed.peek() !== undefined) throw new Error(\"group is closed\");\n\t\t// A frame past the cache cap would make the group exceed its budget by itself, so\n\t\t// accepting it would report success for a write nothing can ever read. Rust rejects\n\t\t// it up front with `Error::FrameTooLarge`; do the same rather than silently dropping it.\n\t\tif (frame.payload.byteLength > MAX_GROUP_CACHE_BYTES) throw new FrameTooLarge();\n\t\tif (\n\t\t\tthis.#state.total.peek() >= MAX_GROUP_FRAMES ||\n\t\t\tthis.#state.cacheBytes + frame.payload.byteLength > MAX_GROUP_CACHE_BYTES\n\t\t) {\n\t\t\tconst err = new GroupTooLarge();\n\t\t\tthis.#state.frames.set([]);\n\t\t\tthis.#state.cacheBytes = 0;\n\t\t\tif (this.#mirrors) {\n\t\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\t\tmirror.frames.set([]);\n\t\t\t\t\tmirror.cacheBytes = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t\tthis.close(err);\n\t\t\tthrow err;\n\t\t}\n\n\t\tthis.#activity = performance.now();\n\t\tappendFrame(this.#state, frame);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() !== undefined) this.#mirrors.delete(mirror);\n\t\t\t\telse appendFrame(mirror, frame);\n\t\t\t}\n\t\t}\n\t}\n\n\t/** Write a string as a single UTF-8 encoded frame, stamped with {@link Timestamp.now}. */\n\twriteString(str: string) {\n\t\tthis.writeFrame({ payload: new TextEncoder().encode(str), timestamp: Timestamp.now() });\n\t}\n\n\t/** Write a value as a single JSON-encoded frame, stamped with {@link Timestamp.now}. */\n\twriteJson(json: unknown) {\n\t\tthis.writeString(JSON.stringify(json));\n\t}\n\n\t/** Write a boolean as a single one-byte frame, stamped with {@link Timestamp.now}. */\n\twriteBool(bool: boolean) {\n\t\tthis.writeFrame({ payload: new Uint8Array([bool ? 1 : 0]), timestamp: Timestamp.now() });\n\t}\n\n\t/** True once the group has been closed. */\n\tget isClosed(): boolean {\n\t\treturn this.#state.closed.peek() !== undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return;\n\t\tthis.#state.closed.set(abort ?? null);\n\n\t\tif (this.#mirrors) {\n\t\t\tfor (const mirror of this.#mirrors) {\n\t\t\t\tif (mirror.closed.peek() === undefined) mirror.closed.set(abort ?? null);\n\t\t\t}\n\t\t\tthis.#mirrors.clear();\n\t\t}\n\t}\n}\n\nlet makeConsumer: (state: GroupState) => Consumer;\n\n// A consumer can finish from its own expiry verdict or from the shared group state. Keep\n// one stable public handle while letting peek() observe either source synchronously, before\n// signal subscribers run in the next microtask.\nclass CombinedClosed implements GetPromise<Error | null> {\n\t#preferred: Once<Error | null>;\n\t#source: Once<Error | null>;\n\t#sourceCleanReady: () => boolean;\n\t#value = new Once<Error | null>();\n\t#dispose?: Dispose;\n\n\tconstructor(preferred: Once<Error | null>, source: Once<Error | null>, sourceCleanReady: () => boolean) {\n\t\tthis.#preferred = preferred;\n\t\tthis.#source = source;\n\t\tthis.#sourceCleanReady = sourceCleanReady;\n\t\tif (this.#sync()) return;\n\n\t\tconst dispose = [preferred.changed(() => this.#sync()), source.changed(() => this.#sync())];\n\t\tthis.#dispose = () => {\n\t\t\tfor (const close of dispose) close();\n\t\t};\n\t}\n\n\t#sync(): boolean {\n\t\tif (this.#value.peek() !== undefined) return true;\n\t\tconst preferred = this.#preferred.peek();\n\t\tconst source = this.#source.peek();\n\t\tconst value =\n\t\t\tpreferred !== undefined\n\t\t\t\t? preferred\n\t\t\t\t: source instanceof Error || this.#sourceCleanReady()\n\t\t\t\t\t? source\n\t\t\t\t\t: undefined;\n\t\tif (value === undefined) return false;\n\n\t\tthis.#value.set(value);\n\t\tthis.#dispose?.();\n\t\tthis.#dispose = undefined;\n\t\treturn true;\n\t}\n\n\trefresh() {\n\t\tthis.#sync();\n\t}\n\n\tpeek(): Error | null | undefined {\n\t\tthis.#sync();\n\t\treturn this.#value.peek();\n\t}\n\n\tchanged(): Promise<Error | null | undefined>;\n\tchanged(fn: (value: Error | null | undefined) => void): Dispose;\n\tchanged(fn?: (value: Error | null | undefined) => void): Promise<Error | null | undefined> | Dispose {\n\t\tthis.#sync();\n\t\treturn fn ? this.#value.changed(fn) : this.#value.changed();\n\t}\n\n\tsubscribe(fn: (value: Error | null | undefined) => void): Dispose {\n\t\tthis.#sync();\n\t\treturn this.#value.subscribe(fn);\n\t}\n\n\t// biome-ignore lint/suspicious/noThenProperty: CombinedClosed is intentionally awaitable.\n\tthen<R1 = Error | null, R2 = never>(\n\t\tonFulfilled?: ((value: Error | null) => R1 | PromiseLike<R1>) | null,\n\t\tonRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null,\n\t): PromiseLike<R1 | R2> {\n\t\tthis.#sync();\n\t\treturn this.#value.then(onFulfilled, onRejected);\n\t}\n}\n\n/**\n * The read side of an ordered stream of frames within a track.\n *\n * Created internally: obtain one from {@link Producer.consume} or a track subscriber's\n * group reads.\n *\n * @public\n */\nexport class Consumer {\n\t/** Sequence number of this group within its track. */\n\treadonly sequence: number;\n\n\t#state: GroupState;\n\t#expiry?: { expired: () => boolean; changed: readonly Getter<unknown>[] };\n\t// Sticky verdicts, set once. `#ended` is a drained group the budget gave up on,\n\t// which is indistinguishable from one that ended: nothing was lost, so it reads as\n\t// the end of the group. `#terminal` is a failure, including a budget that gave up\n\t// while content was still unread.\n\t#ended = false;\n\t#terminal?: Error;\n\t#verdict = new Once<Error | null>();\n\t#closed?: CombinedClosed;\n\t#pendingFrames = 0;\n\n\tprivate constructor(state: GroupState) {\n\t\tthis.#state = state;\n\t\tthis.sequence = state.sequence;\n\t}\n\n\t/**\n\t * Settles when this consumer reaches a terminal state: `null` after a clean close has no\n\t * unread or in-flight frames, or the terminal {@link Error}.\n\t * Peek it synchronously (`undefined` while open), observe it reactively, or `await` it.\n\t */\n\tget closed(): GetPromise<Error | null> {\n\t\tthis.#closed ??= new CombinedClosed(\n\t\t\tthis.#verdict,\n\t\t\tthis.#state.closed,\n\t\t\t() => this.#state.frames.peek().length === 0 && this.#pendingFrames === 0,\n\t\t);\n\t\treturn this.#closed;\n\t}\n\n\tstatic {\n\t\tmakeConsumer = (state) => new Consumer(state);\n\t\thooks.groupTimestamp = (group) => group.#state.timestamp;\n\t\thooks.groupLatest = (group) => group.#state.latest;\n\t\thooks.expireGroup = (group, expiry) => {\n\t\t\tgroup.#expiry = expiry;\n\t\t};\n\t\thooks.guardGroup = (group, operation) => group.#guard(operation);\n\t\thooks.readGroupFrame = (group, from) => group.#readFramePosition(true, from);\n\t\thooks.evictGroup = (group) => {\n\t\t\tgroup.#evict();\n\t\t};\n\t}\n\n\t// Evaluate the drift budget for a read that has nothing buffered and is about to\n\t// wait. A group with frames in hand is always drained: the budget bounds a group\n\t// that has stalled while the live edge moved on, not a reader slower than the wire.\n\t// Returns true if a verdict was just reached, so the caller re-checks.\n\t//\n\t// `unread` is for a caller that still holds content the reader has not seen (a\n\t// publisher part-way through writing a frame): giving up there is a truncation, so\n\t// it fails rather than ending.\n\t#expire(unread = false): boolean {\n\t\tif (this.#terminal || this.#ended) return false;\n\t\tif (this.#state.closed.peek() instanceof Error) return false;\n\t\tif (!this.#expiry?.expired()) return false;\n\n\t\tif (unread) {\n\t\t\tthis.#terminal = new Error(\"group exceeded the subscription max age budget\");\n\t\t} else {\n\t\t\tthis.#ended = true;\n\t\t}\n\t\tif (this.#verdict.peek() === undefined) this.#verdict.set(this.#terminal ?? null);\n\t\treturn true;\n\t}\n\n\t// Takes a thunk rather than a started promise, so a group already past its budget\n\t// never begins the write: an abandoned write would reject later with no handler.\n\t#guard<T>(operation: () => Promise<T>): Promise<T> {\n\t\tthis.#expire(true);\n\t\tif (this.#terminal) return Promise.reject(this.#terminal);\n\t\tconst expiry = this.#expiry;\n\t\tif (!expiry) return operation();\n\n\t\treturn new Promise<T>((resolve, reject) => {\n\t\t\tlet settled = false;\n\t\t\tconst disposes: Dispose[] = [];\n\t\t\tconst finish = (fn: () => void) => {\n\t\t\t\tif (settled) return;\n\t\t\t\tsettled = true;\n\t\t\t\tfor (const dispose of disposes) dispose();\n\t\t\t\tfn();\n\t\t\t};\n\t\t\tconst check = () => {\n\t\t\t\tthis.#expire(true);\n\t\t\t\tif (this.#terminal) {\n\t\t\t\t\tconst error = this.#terminal;\n\t\t\t\t\tfinish(() => reject(error));\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tfor (const changed of expiry.changed) disposes.push(changed.subscribe(check));\n\t\t\toperation().then(\n\t\t\t\t(value) => finish(() => resolve(value)),\n\t\t\t\t(error: unknown) => finish(() => reject(error)),\n\t\t\t);\n\t\t\tcheck();\n\t\t});\n\t}\n\n\t#evict() {\n\t\tconst frames = this.#state.frames.peek();\n\t\tif (frames.length > 0) {\n\t\t\t// Unread content is going away either way. If the budget had already given up\n\t\t\t// on this group that is the more specific reason, so ask it first; otherwise\n\t\t\t// the reader simply lagged behind the cache.\n\t\t\tthis.#expire(true);\n\t\t\tif (!this.#terminal && !this.#ended) {\n\t\t\t\tthis.#terminal = new TooFarBehind();\n\t\t\t\tif (this.#verdict.peek() === undefined) this.#verdict.set(this.#terminal);\n\t\t\t}\n\t\t}\n\t\tif (frames.length > 0) {\n\t\t\tthis.#state.start += frames.length;\n\t\t}\n\t\tthis.#state.cacheBytes = 0;\n\t\tthis.#state.frames.set([]);\n\t}\n\n\tasync #changed(): Promise<void> {\n\t\tif (!this.#expiry) {\n\t\t\tawait Signal.race(this.#state.frames, this.#state.closed);\n\t\t\treturn;\n\t\t}\n\t\tawait Signal.race(this.#state.frames, this.#state.closed, ...this.#expiry.changed);\n\t}\n\n\t#readBufferedFrame(pending = false): ReadGroupFrame | undefined {\n\t\tconst frames = this.#state.frames.peek();\n\t\tconst buffered = frames.shift();\n\t\tif (!buffered) return undefined;\n\n\t\tconst sequence = this.#state.start++;\n\t\tif (pending) this.#pendingFrames++;\n\t\tlet completed = false;\n\t\treturn {\n\t\t\tsequence,\n\t\t\tframe: buffered,\n\t\t\tcomplete: () => {\n\t\t\t\tif (completed) return;\n\t\t\t\tcompleted = true;\n\t\t\t\tif (pending) this.#pendingFrames--;\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t},\n\t\t};\n\t}\n\n\t/** True once no further frames can be read: the group has closed and every buffered frame is read. */\n\tget done(): boolean {\n\t\treturn (\n\t\t\tthis.#terminal !== undefined ||\n\t\t\tthis.#ended ||\n\t\t\t(this.#state.frames.peek().length === 0 && this.#state.closed.peek() !== undefined)\n\t\t);\n\t}\n\n\t/** True once the group has been closed, regardless of whether buffered frames remain unread. Synchronous complement to the {@link closed} promise. */\n\tget isClosed(): boolean {\n\t\treturn this.#terminal !== undefined || this.#ended || this.#state.closed.peek() !== undefined;\n\t}\n\n\t/**\n\t * How many frames the group has held, including any already read.\n\t *\n\t * It is also the next frame's sequence number, so `frameCount - 1` names the newest\n\t * frame written so far. A publisher snapshots it to resolve the track's live edge.\n\t */\n\tget frameCount(): number {\n\t\treturn this.#state.total.peek();\n\t}\n\n\t/**\n\t * Reads the next already-buffered frame without blocking.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t *\n\t * Returns `undefined` when nothing is buffered right now. That is not by itself\n\t * end-of-group: check {@link done} to tell \"no frame buffered yet\" from \"finished\".\n\t */\n\ttryReadFrame(): Frame | undefined {\n\t\tif (this.#terminal || this.#ended) return undefined;\n\t\tconst read = this.#readBufferedFrame();\n\t\tread?.complete();\n\t\treturn read?.frame;\n\t}\n\n\t/** Like {@link tryReadFrame} but also reports the frame's sequence number within the group. */\n\ttryReadFrameSequence(): ({ sequence: number } & Frame) | undefined {\n\t\tif (this.#terminal || this.#ended) return undefined;\n\t\tconst read = this.#readBufferedFrame();\n\t\tif (!read) return undefined;\n\t\tread.complete();\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Resolves once {@link readFrame} would not block. */\n\tasync readable(): Promise<void> {\n\t\tfor (;;) {\n\t\t\tif (this.#terminal || this.#ended) return;\n\t\t\tif (this.#state.frames.peek().length > 0) return;\n\t\t\tif (this.#state.closed.peek() !== undefined) {\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (this.#expire()) return;\n\t\t\tawait this.#changed();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame from the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrame(): Promise<Frame | undefined> {\n\t\treturn (await this.#readFramePosition())?.frame;\n\t}\n\n\tasync #readFramePosition(pending = false, from = 0): Promise<ReadGroupFrame | undefined> {\n\t\tfor (;;) {\n\t\t\tif (this.#terminal) throw this.#terminal;\n\t\t\tif (this.#ended) return;\n\n\t\t\tconst read = this.#readBufferedFrame(pending);\n\t\t\tif (read) {\n\t\t\t\tif (read.sequence < from) {\n\t\t\t\t\tread.complete();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!pending) read.complete();\n\t\t\t\treturn read;\n\t\t\t}\n\n\t\t\tconst closed = this.#state.closed.peek();\n\t\t\tif (closed instanceof Error) throw closed;\n\t\t\tif (closed !== undefined) {\n\t\t\t\tthis.#closed?.refresh();\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Nothing buffered and the group is still open: this wait is the stall the\n\t\t\t// drift budget bounds, and the only place it applies.\n\t\t\tif (this.#expire()) continue;\n\t\t\tawait this.#changed();\n\t\t}\n\t}\n\n\t/**\n\t * Reads the next frame along with its sequence number within the group.\n\t * Treat the returned frame bytes as read-only; they are shared with other consumers.\n\t */\n\tasync readFrameSequence(options?: ReadOptions): Promise<({ sequence: number } & Frame) | undefined> {\n\t\tconst read = await this.#readFramePosition(false, options?.from ?? 0);\n\t\tif (!read) return undefined;\n\t\treturn { sequence: read.sequence, payload: read.frame.payload, timestamp: read.frame.timestamp };\n\t}\n\n\t/** Reads the next frame and decodes its payload as a UTF-8 string. */\n\tasync readString(): Promise<string | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? new TextDecoder().decode(frame.payload) : undefined;\n\t}\n\n\t/** Reads the next frame and parses its payload as JSON. */\n\tasync readJson(): Promise<unknown | undefined> {\n\t\tconst frame = await this.readString();\n\t\treturn frame ? JSON.parse(frame) : undefined;\n\t}\n\n\t/** Reads the next frame and decodes its payload as a one-byte boolean. */\n\tasync readBool(): Promise<boolean | undefined> {\n\t\tconst frame = await this.readFrame();\n\t\treturn frame ? frame.payload[0] === 1 : undefined;\n\t}\n\n\t/** Closes the group, optionally with an error to abort readers. Idempotent. */\n\tclose(abort?: Error) {\n\t\tif (this.#state.closed.peek() !== undefined) return; // already closed\n\t\tthis.#state.closed.set(abort ?? null);\n\t}\n}\n"]}
package/hop.d.ts CHANGED
@@ -50,6 +50,14 @@ export declare const MAX_HOPS = 32;
50
50
  * bundles. Mirrors `Hop::random` in rs/moq-net.
51
51
  */
52
52
  export declare function randomHop(): Hop;
53
+ /**
54
+ * Name an unknown original publisher: put `stamp`, the receiving connection's own random id,
55
+ * in front of a chain that starts with 0, and turn an empty chain into `[stamp, 0]`. A
56
+ * publisher that reconnects then reads downstream as a new first hop, while the 0 after the
57
+ * stamp keeps the route ranked as anonymous. `undefined` if the chain is full or already holds
58
+ * `stamp`. Mirrors `Hops::stamp` in rs/moq-net.
59
+ */
60
+ export declare function stampHops(hops: readonly Hop[], stamp: Hop): Hop[] | undefined;
53
61
  /**
54
62
  * What pulling content via a route costs, in two magnitudes accumulated together
55
63
  * and compared in that order: lower {@link Cost.warm} wins, and {@link Cost.cold}
package/hop.d.ts.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hop.d.ts","sourceRoot":"","sources":["../src/hop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAE9B;;;;;;;;;;GAUG;AACH,eAAO,MAAM,SAAS,2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C,EAAE,KAAK,GAAG,SAAS,GAAG,OAAO,CAS/E"}
package/hop.js CHANGED
@@ -60,6 +60,22 @@ export function randomHop() {
60
60
  // Guard against the (astronomically unlikely) zero draw.
61
61
  return HopSchema.parse(raw === 0n ? 1n : raw);
62
62
  }
63
+ /**
64
+ * Name an unknown original publisher: put `stamp`, the receiving connection's own random id,
65
+ * in front of a chain that starts with 0, and turn an empty chain into `[stamp, 0]`. A
66
+ * publisher that reconnects then reads downstream as a new first hop, while the 0 after the
67
+ * stamp keeps the route ranked as anonymous. `undefined` if the chain is full or already holds
68
+ * `stamp`. Mirrors `Hops::stamp` in rs/moq-net.
69
+ */
70
+ export function stampHops(hops, stamp) {
71
+ if (hops.length === 0)
72
+ return [stamp, UNKNOWN_HOP];
73
+ if (hops[0] !== UNKNOWN_HOP)
74
+ return [...hops];
75
+ if (hops.length >= MAX_HOPS || hops.includes(stamp))
76
+ return undefined;
77
+ return [stamp, ...hops];
78
+ }
63
79
  /** Constructors for {@link Cost}. */
64
80
  export const Cost = {
65
81
  /** A free path in both magnitudes: what a live publisher seeds. */
package/hop.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hop.js","sourceRoot":"","sources":["../src/hop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAE9B;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC;KACxB,MAAM,EAAE;KACR,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,IAAI,KAAK,GAAG,EAAE,IAAI,GAAG,EAAE,2CAA2C,CAAC,CAAC;KACzG,KAAK,CAAC,KAAK,CAAC,CAAC;AAIf;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAQ,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,CAAC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AAE,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC;IAC7D,CAAC;CACD,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,KAAY;IACvC,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACzC,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,WAAW,CAAC,CAAoB,EAAE,CAAoB;IACrE,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3B,OAAO,CACN,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI;QAC3B,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI;QAC3B,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM;QAC/B,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC3C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Endpoint identity within a hop chain, shared by both wire protocols.\n *\n * moq-lite carries these natively on every announcement; moq-transport carries them\n * via the MoQ Cluster extension (see `ietf/cluster.ts`). Mirrors `Hop` in\n * `rs/moq-net`.\n *\n * @module\n */\nimport * as z from \"zod/mini\";\n\n/**\n * One relay's identity in a broadcast's hop chain, encoded as a 62-bit varint on the wire.\n *\n * Names a *hop*, not an {@link !Origin | Origin} routing table: this is the id a relay\n * stamps into a chain as an announcement passes through, so a receiver can spot its own\n * id and reject a loop. The SETUP parameter that carries it session-wide is `Hop` too.\n *\n * The {@link HopSchema} validates any incoming value and brands it so the type system\n * enforces \"only validated ids flow into hop chains.\" Internal code that synthesizes one\n * (e.g. {@link randomHop}) uses `HopSchema.parse(...)` to brand a raw bigint.\n */\nexport const HopSchema = z\n\t.bigint()\n\t.check(z.refine((value) => value >= 0n && value < 1n << 62n, \"Hop must be a non-negative 62-bit integer\"))\n\t.brand(\"Hop\");\n\nexport type Hop = z.infer<typeof HopSchema>;\n\n/**\n * The reserved id 0, meaning \"no identity\".\n *\n * It stands in for an endpoint that never declared one, and any number of endpoints can\n * be 0, so it identifies nothing: it is never a loop, never a publisher two chains have\n * in common, and never excluded from an advertisement. A chain that holds a 0 anywhere\n * is anonymous for route selection.\n */\nexport const UNKNOWN_HOP: Hop = HopSchema.parse(0n);\n\n/**\n * Maximum length of a hop chain. Must match `MAX_HOPS` in Rust's `model/origin.rs`.\n *\n * Broadcasts with longer chains are rejected, which bounds loop detection and rejects\n * pathological announcements across clusters with unbounded forwarding.\n */\nexport const MAX_HOPS = 32;\n\n/**\n * Generate a fresh hop with a random non-zero id.\n *\n * `crypto.getRandomValues` is overkill for best-effort loop detection, but\n * used for slightly better distribution than `Math.random` at negligible cost.\n *\n * TEMPORARY: the wire format allows 62 bits, but older `@moq/lite` JS clients\n * decode `AnnounceInterest.exclude_hop` as a u53 (number) and throw on anything\n * > 2^53-1. To keep those clients alive against fresh peers, we cap the random\n * id at 53 bits. Restore to 62 bits once the u62 fix has propagated to deployed\n * bundles. Mirrors `Hop::random` in rs/moq-net.\n */\nexport function randomHop(): Hop {\n\tconst buf = new BigUint64Array(1);\n\tcrypto.getRandomValues(buf);\n\t// Mask to 53 bits.\n\tconst raw = buf[0] & 0x1f_ffff_ffff_ffffn;\n\t// Guard against the (astronomically unlikely) zero draw.\n\treturn HopSchema.parse(raw === 0n ? 1n : raw);\n}\n\n/**\n * What pulling content via a route costs, in two magnitudes accumulated together\n * and compared in that order: lower {@link Cost.warm} wins, and {@link Cost.cold}\n * breaks the tie.\n *\n * Both price the same path against different cache states. `warm` is what one more\n * subscription would cost the mesh right now, so it collapses to zero at any relay\n * already carrying the broadcast. `cold` prices the identical path as if nothing were\n * cached, so it keeps flowing through a warm relay unchanged and still says which of\n * two warm relays sits closer to the publisher.\n */\nexport interface Cost {\n\t/** The cost as the mesh stands today, discounted to zero at every carrying relay. */\n\twarm: bigint;\n\t/** The same path with every warm discount removed. */\n\tcold: bigint;\n}\n\n/** Constructors for {@link Cost}. */\nexport const Cost = {\n\t/** A free path in both magnitudes: what a live publisher seeds. */\n\tzero: { warm: 0n, cold: 0n } as Cost,\n};\n\n/**\n * The path a route took through the mesh and what using it costs.\n *\n * The metadata half of an advertisement: an origin `dynamic()` pairs it with the\n * pattern it covers, a broadcast `announce()` with the broadcast's exact path, and\n * an announce event carries it so consumers can read it back.\n */\nexport interface Route {\n\t/** The chain of hops the route has traversed, oldest first. */\n\thops: Hop[];\n\t/** What pulling content via this route costs; lower wins. */\n\tcost: Cost;\n}\n\n/** Constructors and helpers for {@link Route}. */\nexport const Route = {\n\t/** An empty hop chain at zero cost: what a publisher seeds for a live broadcast. */\n\tdefault: { hops: [], cost: Cost.zero } as Route,\n\n\t/** Normalize a partial route, treating a bare bigint cost as both magnitudes alike. */\n\tnormalize(route: Route | { hops?: readonly Hop[]; cost?: Cost | bigint } = {}): Route {\n\t\tconst hops = route.hops ? [...route.hops] : [];\n\t\tconst cost = route.cost;\n\t\tif (cost === undefined) return { hops, cost: Cost.zero };\n\t\tif (typeof cost === \"bigint\") return { hops, cost: { warm: cost, cold: cost } };\n\t\treturn { hops, cost: { warm: cost.warm, cold: cost.cold } };\n\t},\n};\n\n/**\n * Whether this route passed through an anonymous hop (id 0) at any depth.\n *\n * An empty chain is a local announcement, not the anonymous mark. Ingress fills a\n * received empty list with {@link UNKNOWN_HOP} before yielding it.\n */\nexport function isAnonymous(route: Route): boolean {\n\treturn route.hops.includes(UNKNOWN_HOP);\n}\n\n/** Whether two routes name the same hop chain and cost. */\nexport function routesEqual(a: Route | undefined, b: Route | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\treturn (\n\t\ta.cost.warm === b.cost.warm &&\n\t\ta.cost.cold === b.cost.cold &&\n\t\ta.hops.length === b.hops.length &&\n\t\ta.hops.every((hop, i) => hop === b.hops[i])\n\t);\n}\n"]}
1
+ {"version":3,"file":"hop.js","sourceRoot":"","sources":["../src/hop.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,CAAC,MAAM,UAAU,CAAC;AAE9B;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,CAAC;KACxB,MAAM,EAAE;KACR,KAAK,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,IAAI,KAAK,GAAG,EAAE,IAAI,GAAG,EAAE,2CAA2C,CAAC,CAAC;KACzG,KAAK,CAAC,KAAK,CAAC,CAAC;AAIf;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,WAAW,GAAQ,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;AAEpD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,EAAE,CAAC;AAE3B;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,SAAS;IACxB,MAAM,GAAG,GAAG,IAAI,cAAc,CAAC,CAAC,CAAC,CAAC;IAClC,MAAM,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAC5B,mBAAmB;IACnB,MAAM,GAAG,GAAG,GAAG,CAAC,CAAC,CAAC,GAAG,iBAAoB,CAAC;IAC1C,yDAAyD;IACzD,OAAO,SAAS,CAAC,KAAK,CAAC,GAAG,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC;AAC/C,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,SAAS,CAAC,IAAoB,EAAE,KAAU;IACzD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,CAAC,KAAK,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;;;;;GAKG;AACH,MAAM,UAAU,WAAW,CAAC,KAAY;IACvC,OAAO,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC;AACzC,CAAC;AAED,2DAA2D;AAC3D,MAAM,UAAU,WAAW,CAAC,CAAoB,EAAE,CAAoB;IACrE,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACzB,IAAI,CAAC,CAAC,IAAI,CAAC,CAAC;QAAE,OAAO,KAAK,CAAC;IAC3B,OAAO,CACN,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI;QAC3B,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,CAAC,CAAC,IAAI,CAAC,IAAI;QAC3B,CAAC,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM;QAC/B,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,CAAC,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAC3C,CAAC;AACH,CAAC","sourcesContent":["/**\n * Endpoint identity within a hop chain, shared by both wire protocols.\n *\n * moq-lite carries these natively on every announcement; moq-transport carries them\n * via the MoQ Cluster extension (see `ietf/cluster.ts`). Mirrors `Hop` in\n * `rs/moq-net`.\n *\n * @module\n */\nimport * as z from \"zod/mini\";\n\n/**\n * One relay's identity in a broadcast's hop chain, encoded as a 62-bit varint on the wire.\n *\n * Names a *hop*, not an {@link !Origin | Origin} routing table: this is the id a relay\n * stamps into a chain as an announcement passes through, so a receiver can spot its own\n * id and reject a loop. The SETUP parameter that carries it session-wide is `Hop` too.\n *\n * The {@link HopSchema} validates any incoming value and brands it so the type system\n * enforces \"only validated ids flow into hop chains.\" Internal code that synthesizes one\n * (e.g. {@link randomHop}) uses `HopSchema.parse(...)` to brand a raw bigint.\n */\nexport const HopSchema = z\n\t.bigint()\n\t.check(z.refine((value) => value >= 0n && value < 1n << 62n, \"Hop must be a non-negative 62-bit integer\"))\n\t.brand(\"Hop\");\n\nexport type Hop = z.infer<typeof HopSchema>;\n\n/**\n * The reserved id 0, meaning \"no identity\".\n *\n * It stands in for an endpoint that never declared one, and any number of endpoints can\n * be 0, so it identifies nothing: it is never a loop, never a publisher two chains have\n * in common, and never excluded from an advertisement. A chain that holds a 0 anywhere\n * is anonymous for route selection.\n */\nexport const UNKNOWN_HOP: Hop = HopSchema.parse(0n);\n\n/**\n * Maximum length of a hop chain. Must match `MAX_HOPS` in Rust's `model/origin.rs`.\n *\n * Broadcasts with longer chains are rejected, which bounds loop detection and rejects\n * pathological announcements across clusters with unbounded forwarding.\n */\nexport const MAX_HOPS = 32;\n\n/**\n * Generate a fresh hop with a random non-zero id.\n *\n * `crypto.getRandomValues` is overkill for best-effort loop detection, but\n * used for slightly better distribution than `Math.random` at negligible cost.\n *\n * TEMPORARY: the wire format allows 62 bits, but older `@moq/lite` JS clients\n * decode `AnnounceInterest.exclude_hop` as a u53 (number) and throw on anything\n * > 2^53-1. To keep those clients alive against fresh peers, we cap the random\n * id at 53 bits. Restore to 62 bits once the u62 fix has propagated to deployed\n * bundles. Mirrors `Hop::random` in rs/moq-net.\n */\nexport function randomHop(): Hop {\n\tconst buf = new BigUint64Array(1);\n\tcrypto.getRandomValues(buf);\n\t// Mask to 53 bits.\n\tconst raw = buf[0] & 0x1f_ffff_ffff_ffffn;\n\t// Guard against the (astronomically unlikely) zero draw.\n\treturn HopSchema.parse(raw === 0n ? 1n : raw);\n}\n\n/**\n * Name an unknown original publisher: put `stamp`, the receiving connection's own random id,\n * in front of a chain that starts with 0, and turn an empty chain into `[stamp, 0]`. A\n * publisher that reconnects then reads downstream as a new first hop, while the 0 after the\n * stamp keeps the route ranked as anonymous. `undefined` if the chain is full or already holds\n * `stamp`. Mirrors `Hops::stamp` in rs/moq-net.\n */\nexport function stampHops(hops: readonly Hop[], stamp: Hop): Hop[] | undefined {\n\tif (hops.length === 0) return [stamp, UNKNOWN_HOP];\n\tif (hops[0] !== UNKNOWN_HOP) return [...hops];\n\tif (hops.length >= MAX_HOPS || hops.includes(stamp)) return undefined;\n\treturn [stamp, ...hops];\n}\n\n/**\n * What pulling content via a route costs, in two magnitudes accumulated together\n * and compared in that order: lower {@link Cost.warm} wins, and {@link Cost.cold}\n * breaks the tie.\n *\n * Both price the same path against different cache states. `warm` is what one more\n * subscription would cost the mesh right now, so it collapses to zero at any relay\n * already carrying the broadcast. `cold` prices the identical path as if nothing were\n * cached, so it keeps flowing through a warm relay unchanged and still says which of\n * two warm relays sits closer to the publisher.\n */\nexport interface Cost {\n\t/** The cost as the mesh stands today, discounted to zero at every carrying relay. */\n\twarm: bigint;\n\t/** The same path with every warm discount removed. */\n\tcold: bigint;\n}\n\n/** Constructors for {@link Cost}. */\nexport const Cost = {\n\t/** A free path in both magnitudes: what a live publisher seeds. */\n\tzero: { warm: 0n, cold: 0n } as Cost,\n};\n\n/**\n * The path a route took through the mesh and what using it costs.\n *\n * The metadata half of an advertisement: an origin `dynamic()` pairs it with the\n * pattern it covers, a broadcast `announce()` with the broadcast's exact path, and\n * an announce event carries it so consumers can read it back.\n */\nexport interface Route {\n\t/** The chain of hops the route has traversed, oldest first. */\n\thops: Hop[];\n\t/** What pulling content via this route costs; lower wins. */\n\tcost: Cost;\n}\n\n/** Constructors and helpers for {@link Route}. */\nexport const Route = {\n\t/** An empty hop chain at zero cost: what a publisher seeds for a live broadcast. */\n\tdefault: { hops: [], cost: Cost.zero } as Route,\n\n\t/** Normalize a partial route, treating a bare bigint cost as both magnitudes alike. */\n\tnormalize(route: Route | { hops?: readonly Hop[]; cost?: Cost | bigint } = {}): Route {\n\t\tconst hops = route.hops ? [...route.hops] : [];\n\t\tconst cost = route.cost;\n\t\tif (cost === undefined) return { hops, cost: Cost.zero };\n\t\tif (typeof cost === \"bigint\") return { hops, cost: { warm: cost, cold: cost } };\n\t\treturn { hops, cost: { warm: cost.warm, cold: cost.cold } };\n\t},\n};\n\n/**\n * Whether this route passed through an anonymous hop (id 0) at any depth.\n *\n * An empty chain is a local announcement, not the anonymous mark. Ingress fills a\n * received empty list with {@link UNKNOWN_HOP} before yielding it.\n */\nexport function isAnonymous(route: Route): boolean {\n\treturn route.hops.includes(UNKNOWN_HOP);\n}\n\n/** Whether two routes name the same hop chain and cost. */\nexport function routesEqual(a: Route | undefined, b: Route | undefined): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\treturn (\n\t\ta.cost.warm === b.cost.warm &&\n\t\ta.cost.cold === b.cost.cold &&\n\t\ta.hops.length === b.hops.length &&\n\t\ta.hops.every((hop, i) => hop === b.hops[i])\n\t);\n}\n"]}
package/ietf/adapter.d.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { Once } from "@moq/signals";
2
+ import type { Drain } from "../connection/goaway";
1
3
  import { Stream } from "../stream";
2
4
  import { type IetfVersion } from "./version";
3
5
  /**
@@ -36,6 +38,8 @@ export declare class NativeSession implements Session {
36
38
  export declare class ControlStreamAdapter implements Session {
37
39
  #private;
38
40
  readonly version: IetfVersion;
41
+ /** The peer's GOAWAY, which draft-14 to -16 carry on the shared control stream. */
42
+ readonly goaway: Once<Drain>;
39
43
  constructor(quic: WebTransport, controlStream: Stream, version: IetfVersion, maxRequestId: bigint, client: boolean);
40
44
  /**
41
45
  * Accept the next incoming virtual bidi stream.
@@ -1 +1 @@
1
- {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/ietf/adapter.ts"],"names":[],"mappings":"AAEA,OAAO,EAAU,MAAM,EAAe,MAAM,cAAc,CAAC;AAG3D,OAAO,EAAE,KAAK,WAAW,EAAW,MAAM,cAAc,CAAC;AAEzD;;;GAGG;AACH,MAAM,WAAW,OAAO;IACvB,MAAM,IAAI,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACnC,YAAY,CAAC,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IACjC,QAAQ,IAAI,OAAO,CA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M,EAAE,OAAO,EAWf;IAED;;;OAGG;IACG,QAAQ,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAS5C;IAED;;;;;OAKG;IACH,MAAM,IAAI,MAAM,CAoDf;IAED;;OAEG;IACG,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAEpC;IAED;;OAEG;IACG,aAAa,IAAI,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAYjD;IAED;;;OAGG;IACG,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,CAkEzB;IAqaD;;;OAGG;IACH,KAAK,CAAC,GAAG,CAAC,EAAE,KAAK,QA8BhB;CACD"}
package/ietf/adapter.js CHANGED
@@ -1,8 +1,10 @@
1
1
  /* @ts-self-types="./adapter.d.ts" */
2
+ import { Once } from "@moq/signals";
2
3
  import { Mutex } from "async-mutex";
3
4
  import { error, ProtocolViolation } from "../error.js";
4
5
  import { Reader, Stream } from "../stream.js";
5
6
  import * as Varint from "../varint.js";
7
+ import { GoAway } from "./goaway.js";
6
8
  import * as Namespace from "./namespace.js";
7
9
  import { Version } from "./version.js";
8
10
  /**
@@ -62,6 +64,8 @@ export class ControlStreamAdapter {
62
64
  #writer;
63
65
  #writeMutex = new Mutex();
64
66
  version;
67
+ /** The peer's GOAWAY, which draft-14 to -16 carry on the shared control stream. */
68
+ goaway = new Once();
65
69
  // Virtual streams keyed by requestId
66
70
  #streams = new Map();
67
71
  // Namespace → requestId reverse lookups for v14/v15 namespace-keyed messages.
@@ -88,6 +92,8 @@ export class ControlStreamAdapter {
88
92
  #maxRequestId;
89
93
  #maxRequestIdResolves = [];
90
94
  #closed = false;
95
+ // Whether this side opened the session. Only a server may name a redirect.
96
+ #client;
91
97
  constructor(quic, controlStream, version, maxRequestId, client) {
92
98
  this.#quic = quic;
93
99
  this.#reader = controlStream.reader;
@@ -97,6 +103,7 @@ export class ControlStreamAdapter {
97
103
  this.version = version;
98
104
  this.#maxRequestId = maxRequestId;
99
105
  this.#requestId = client ? 0n : 1n;
106
+ this.#client = client;
100
107
  }
101
108
  /**
102
109
  * Accept the next incoming virtual bidi stream.
@@ -161,9 +168,7 @@ export class ControlStreamAdapter {
161
168
  }
162
169
  },
163
170
  });
164
- const stream = new Stream({ readable, writable: sendWritable });
165
- stream.reader.version = this.version;
166
- stream.writer.version = this.version;
171
+ const stream = new Stream({ readable, writable: sendWritable, version: this.version });
167
172
  return stream;
168
173
  }
169
174
  /**
@@ -212,8 +217,16 @@ export class ControlStreamAdapter {
212
217
  const body = await this.#reader.read(size);
213
218
  const classified = await this.#classify(typeId, body);
214
219
  if (classified.route === Route.GoAway) {
215
- console.warn("received GOAWAY on control stream");
216
- return;
220
+ // The session keeps serving: a GOAWAY asks us to migrate, not to stop reading.
221
+ const msg = await GoAway.decodeBody(body, this.version);
222
+ if (this.goaway.peek() !== undefined)
223
+ throw new ProtocolViolation("duplicate GOAWAY");
224
+ // A client may leave, but only the server may name where to go.
225
+ if (!this.#client && msg.newSessionUri !== "") {
226
+ throw new ProtocolViolation("client GOAWAY must not name a redirect");
227
+ }
228
+ this.goaway.set(msg.drain());
229
+ continue;
217
230
  }
218
231
  const { route, requestId } = classified;
219
232
  switch (route) {
@@ -281,9 +294,7 @@ export class ControlStreamAdapter {
281
294
  },
282
295
  });
283
296
  const sendWritable = this.#createSendWritable();
284
- const stream = new Stream({ readable, writable: sendWritable });
285
- stream.reader.version = this.version;
286
- stream.writer.version = this.version;
297
+ const stream = new Stream({ readable, writable: sendWritable, version: this.version });
287
298
  this.#streams.set(requestId, { controller });
288
299
  // Push initial message bytes so the dispatcher can read typeId + decode
289
300
  controller.enqueue(this.#encodeRaw(typeId, size, body));