@avatarsd-llc/libtracer-webtransport 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,64 @@
1
+ # @avatarsd-llc/libtracer-webtransport
2
+
3
+ WebTransport transport for [libtracer](https://github.com/avatarsd-llc/libtracer)
4
+ — a browser `WebTransport` client that carries libtracer TLV frames over **one
5
+ bidirectional stream** with **4-byte u32-LE length-prefix framing**. It is
6
+ **wire-compatible with the C++ `tr::net::webtransport_transport_t`**
7
+ (`core/include/libtracer/transport_webtransport.hpp`, the `libtracer_quic`
8
+ module): a browser connects directly to a node's graph
9
+ ([ADR-0043](../../../../docs/adr/0043-quic-webtransport-optional-module-msquic.md)
10
+ Phase B — the [#92](https://github.com/avatarsd-llc/libtracer/issues/92) /
11
+ [ADR-0031](../../../../docs/adr/0031-direct-browser-to-robot-binding-and-webtransport.md)
12
+ browser↔robot path).
13
+
14
+ WebTransport is the browser-reachable form of QUIC (ADR-0031): TLS 1.3, no TCP
15
+ head-of-line blocking, and the substrate for later datagram/multi-stream modes.
16
+ The framing is the same M6 stream framing the C++ TCP/QUIC transports speak —
17
+ the prefix is *transport* framing, not part of the TLV. The core
18
+ (`@avatarsd-llc/libtracer`) is a `peerDependency`
19
+ ([ADR-0033](../../../../docs/adr/0033-npm-subpackage-monorepo.md)).
20
+
21
+ ## Two entry points
22
+
23
+ ```ts
24
+ // 1) The pure, socket-free length-prefix record codec.
25
+ import { encodeRecord, FrameReassembler } from '@avatarsd-llc/libtracer-webtransport/framing';
26
+
27
+ // 2) The TransportWebTransport client (drives the runtime's WebTransport).
28
+ import { TransportWebTransport } from '@avatarsd-llc/libtracer-webtransport';
29
+ import { encode, TYPE } from '@avatarsd-llc/libtracer';
30
+ ```
31
+
32
+ ## Usage (browser)
33
+
34
+ ```ts
35
+ const transport = new TransportWebTransport('https://robot.local:4433/', {
36
+ // DEV ONLY — pin the self-signed server certificate. Browsers require an
37
+ // ECDSA certificate valid <= 14 days for this path; deployments use a real
38
+ // certificate and omit the option.
39
+ serverCertificateHashes: [{ algorithm: 'sha-256', value: certHashBytes }],
40
+ });
41
+ transport.onFrame((bytes) => console.log('frame', bytes));
42
+ await transport.connect();
43
+ transport.send(encode(myTlv));
44
+ ```
45
+
46
+ Compute the dev hash from the server's PEM:
47
+
48
+ ```sh
49
+ openssl x509 -in cert.pem -outform der | openssl dgst -sha256 -binary | base64
50
+ ```
51
+
52
+ `TransportWebTransport` satisfies the client SDK's `ClientTransport` seam
53
+ structurally (`send` / `onFrame` / `onClose`), exactly like `TransportWs` —
54
+ `new LibtracerClient(transport)` works unchanged.
55
+
56
+ ## Runtimes and testing
57
+
58
+ Node has **no native WebTransport client**, so this package's unit tests run
59
+ against a mocked `WebTransport` (web streams), and the wire itself is proven
60
+ end-to-end in C++ (`core/tests/webtransport_test.cpp` implements the client
61
+ half of the handshake). A real-browser interop harness
62
+ (`test/interop-browser.test.mjs`) drives chrome-headless via puppeteer against
63
+ the C++ `wt_interop_server` echo binary; it skips gracefully unless
64
+ `LIBTRACER_WT_INTEROP_SERVER` is set **and** puppeteer is installed.
@@ -0,0 +1,35 @@
1
+ /** The length prefix: 4 bytes, u32 little-endian. */
2
+ export declare const PREFIX_BYTES = 4;
3
+ /**
4
+ * The largest frame the prefix may announce (16 MiB — the C++ `kMaxFrame`
5
+ * cap). A larger prefix is malformed: the stream has lost framing sync and
6
+ * cannot be trusted again.
7
+ */
8
+ export declare const MAX_FRAME: number;
9
+ /** Thrown by {@link FrameReassembler.push} on a prefix announcing more than
10
+ * {@link MAX_FRAME} bytes — the stream is desynced and must be torn down. */
11
+ export declare class MalformedPrefixError extends Error {
12
+ /** The length the malformed prefix announced. */
13
+ readonly announced: number;
14
+ constructor(announced: number);
15
+ }
16
+ /** Encode one frame as a length-prefixed record: `u32-LE length ++ frame`. */
17
+ export declare function encodeRecord(frame: Uint8Array): Uint8Array;
18
+ /**
19
+ * Reassemble length-prefixed records from arbitrary stream chunks (a QUIC
20
+ * stream delivers reads at transport-chosen boundaries: prefixes split across
21
+ * chunks, records coalesced into one chunk — both are normal).
22
+ *
23
+ * `push(chunk)` returns every COMPLETE frame the chunk finished; partial bytes
24
+ * are buffered for the next push. A zero-length record is a no-op (skipped,
25
+ * matching the C++ reassembler); an oversize prefix throws
26
+ * {@link MalformedPrefixError} — after that the reassembler must be discarded
27
+ * with its stream.
28
+ */
29
+ export declare class FrameReassembler {
30
+ private pending;
31
+ /** Feed one stream chunk; returns the frames it completed (possibly none). */
32
+ push(chunk: Uint8Array): Uint8Array[];
33
+ /** Bytes buffered awaiting the rest of a prefix/body (diagnostics). */
34
+ get buffered(): number;
35
+ }
@@ -0,0 +1,85 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // The stream framing shared by every libtracer byte-stream transport (M6):
4
+ // each libtracer TLV frame travels as `u32-LE length ++ frame bytes`. This
5
+ // module is the pure, socket-free codec — byte-identical to the C++
6
+ // `tcp_transport_t` / `quic_transport_t` / `webtransport_transport_t` framing
7
+ // (the prefix is TRANSPORT framing, not part of the TLV).
8
+ /** The length prefix: 4 bytes, u32 little-endian. */
9
+ export const PREFIX_BYTES = 4;
10
+ /**
11
+ * The largest frame the prefix may announce (16 MiB — the C++ `kMaxFrame`
12
+ * cap). A larger prefix is malformed: the stream has lost framing sync and
13
+ * cannot be trusted again.
14
+ */
15
+ export const MAX_FRAME = 16 * 1024 * 1024;
16
+ /** Thrown by {@link FrameReassembler.push} on a prefix announcing more than
17
+ * {@link MAX_FRAME} bytes — the stream is desynced and must be torn down. */
18
+ export class MalformedPrefixError extends Error {
19
+ constructor(announced) {
20
+ super(`malformed length prefix: ${announced} > MAX_FRAME (${MAX_FRAME})`);
21
+ this.name = 'MalformedPrefixError';
22
+ this.announced = announced;
23
+ }
24
+ }
25
+ /** Encode one frame as a length-prefixed record: `u32-LE length ++ frame`. */
26
+ export function encodeRecord(frame) {
27
+ if (frame.byteLength > MAX_FRAME) {
28
+ throw new RangeError(`frame of ${frame.byteLength} bytes exceeds MAX_FRAME (${MAX_FRAME})`);
29
+ }
30
+ const out = new Uint8Array(PREFIX_BYTES + frame.byteLength);
31
+ new DataView(out.buffer).setUint32(0, frame.byteLength, true);
32
+ out.set(frame, PREFIX_BYTES);
33
+ return out;
34
+ }
35
+ /**
36
+ * Reassemble length-prefixed records from arbitrary stream chunks (a QUIC
37
+ * stream delivers reads at transport-chosen boundaries: prefixes split across
38
+ * chunks, records coalesced into one chunk — both are normal).
39
+ *
40
+ * `push(chunk)` returns every COMPLETE frame the chunk finished; partial bytes
41
+ * are buffered for the next push. A zero-length record is a no-op (skipped,
42
+ * matching the C++ reassembler); an oversize prefix throws
43
+ * {@link MalformedPrefixError} — after that the reassembler must be discarded
44
+ * with its stream.
45
+ */
46
+ export class FrameReassembler {
47
+ constructor() {
48
+ this.pending = new Uint8Array(0);
49
+ }
50
+ /** Feed one stream chunk; returns the frames it completed (possibly none). */
51
+ push(chunk) {
52
+ if (this.pending.byteLength === 0) {
53
+ this.pending = chunk;
54
+ }
55
+ else {
56
+ const merged = new Uint8Array(this.pending.byteLength + chunk.byteLength);
57
+ merged.set(this.pending, 0);
58
+ merged.set(chunk, this.pending.byteLength);
59
+ this.pending = merged;
60
+ }
61
+ const frames = [];
62
+ let off = 0;
63
+ while (this.pending.byteLength - off >= PREFIX_BYTES) {
64
+ const view = new DataView(this.pending.buffer, this.pending.byteOffset + off);
65
+ const len = view.getUint32(0, true);
66
+ if (len > MAX_FRAME) {
67
+ this.pending = new Uint8Array(0);
68
+ throw new MalformedPrefixError(len);
69
+ }
70
+ if (this.pending.byteLength - off - PREFIX_BYTES < len)
71
+ break; // await the body
72
+ if (len > 0) {
73
+ // Copy out so callers own their bytes independent of the buffer.
74
+ frames.push(this.pending.slice(off + PREFIX_BYTES, off + PREFIX_BYTES + len));
75
+ }
76
+ off += PREFIX_BYTES + len;
77
+ }
78
+ this.pending = off === 0 ? this.pending : this.pending.slice(off);
79
+ return frames;
80
+ }
81
+ /** Bytes buffered awaiting the rest of a prefix/body (diagnostics). */
82
+ get buffered() {
83
+ return this.pending.byteLength;
84
+ }
85
+ }
@@ -0,0 +1,4 @@
1
+ export declare const TRANSPORT: "webtransport";
2
+ export { PREFIX_BYTES, MAX_FRAME, MalformedPrefixError, encodeRecord, FrameReassembler, } from './framing.js';
3
+ export { TransportWebTransport } from './transport.js';
4
+ export type { FrameReceiver, CloseHandler, WebTransportHash, WebTransportInit, StreamReaderLike, StreamWriterLike, WebTransportBidiLike, WebTransportLike, WebTransportCtor, TransportWebTransportOptions, } from './transport.js';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // @avatarsd-llc/libtracer-webtransport — WebTransport transport for libtracer
4
+ // (ADR-0043 Phase B, the #92 browser->robot path recorded in ADR-0031).
5
+ //
6
+ // A transport is a vertex behind a swappable seam (ADR-0027); WebTransport is
7
+ // the browser-reachable form of QUIC (ADR-0031 ranks it above plain QUIC for
8
+ // the browser and above WebSocket for streams). This package carries libtracer
9
+ // TLV frames over ONE WebTransport bidirectional stream with 4-byte u32-LE
10
+ // length-prefix framing, wire-compatible with the C++
11
+ // `tr::net::webtransport_transport_t` (the libtracer_quic module).
12
+ //
13
+ // Two entry points:
14
+ // - the `framing` subpath: the pure, socket-free length-prefix record codec
15
+ // (shared with the C++ TCP/QUIC/WebTransport stream framing); and
16
+ // - this barrel: the `TransportWebTransport` client plus a re-export.
17
+ // The core (`@avatarsd-llc/libtracer`) is a peerDependency (ADR-0033).
18
+ export const TRANSPORT = 'webtransport';
19
+ export { PREFIX_BYTES, MAX_FRAME, MalformedPrefixError, encodeRecord, FrameReassembler, } from './framing.js';
20
+ export { TransportWebTransport } from './transport.js';
@@ -0,0 +1,124 @@
1
+ /** A received libtracer frame: the payload of one complete length-prefixed record. */
2
+ export type FrameReceiver = (bytes: Uint8Array) => void;
3
+ /** Invoked once when an OPEN session closes/errors, with the cause when known. */
4
+ export type CloseHandler = (cause?: Error) => void;
5
+ /** One entry of `serverCertificateHashes` (the WebCrypto dev-trust pattern). */
6
+ export interface WebTransportHash {
7
+ /** The digest algorithm; browsers accept `"sha-256"`. */
8
+ algorithm: string;
9
+ /** The digest of the server certificate's DER bytes. */
10
+ value: ArrayBuffer | ArrayBufferView;
11
+ }
12
+ /** The constructor options subset this transport forwards to `WebTransport`. */
13
+ export interface WebTransportInit {
14
+ serverCertificateHashes?: WebTransportHash[];
15
+ }
16
+ /** The minimal reader surface of a `ReadableStream<Uint8Array>`. */
17
+ export interface StreamReaderLike {
18
+ read(): Promise<{
19
+ done: boolean;
20
+ value?: Uint8Array;
21
+ }>;
22
+ cancel(reason?: unknown): Promise<unknown> | void;
23
+ }
24
+ /** The minimal writer surface of a `WritableStream<Uint8Array>`. */
25
+ export interface StreamWriterLike {
26
+ write(chunk: Uint8Array): Promise<void>;
27
+ close(): Promise<void>;
28
+ }
29
+ /** The minimal bidirectional-stream surface this transport relies on. */
30
+ export interface WebTransportBidiLike {
31
+ readable: {
32
+ getReader(): StreamReaderLike;
33
+ };
34
+ writable: {
35
+ getWriter(): StreamWriterLike;
36
+ };
37
+ }
38
+ /** The minimal `WebTransport` surface this transport relies on. */
39
+ export interface WebTransportLike {
40
+ ready: Promise<unknown>;
41
+ closed: Promise<unknown>;
42
+ close(closeInfo?: {
43
+ closeCode?: number;
44
+ reason?: string;
45
+ }): void;
46
+ createBidirectionalStream(): Promise<WebTransportBidiLike>;
47
+ }
48
+ /** Constructs a {@link WebTransportLike} for an `https://` URL. */
49
+ export type WebTransportCtor = new (url: string, options?: WebTransportInit) => WebTransportLike;
50
+ /** Options for {@link TransportWebTransport}. */
51
+ export interface TransportWebTransportOptions {
52
+ /**
53
+ * The WebTransport implementation to dial with. Defaults to the runtime
54
+ * global `WebTransport` (browsers; Node has no native client — use the
55
+ * mocked implementation in tests, or run the browser interop harness).
56
+ */
57
+ WebTransport?: WebTransportCtor;
58
+ /**
59
+ * Dev-time certificate pinning: the SHA-256 hash(es) of the server's DER
60
+ * certificate (`openssl x509 -in cert.pem -outform der | openssl dgst
61
+ * -sha256`). Browsers require an ECDSA certificate valid <= 14 days for
62
+ * this path. Omit in deployment (real certificate).
63
+ */
64
+ serverCertificateHashes?: WebTransportHash[];
65
+ }
66
+ /**
67
+ * A WebTransport-backed libtracer transport client.
68
+ *
69
+ * Lifecycle: construct with an `https://host:port/` URL, `await connect()`
70
+ * (session handshake + the bidirectional frame stream), then `send()` TLV
71
+ * bytes and receive inbound TLVs via {@link onFrame}. Satisfies the client
72
+ * SDK's `ClientTransport` seam structurally (send / onFrame / onClose),
73
+ * exactly like `TransportWs`.
74
+ */
75
+ export declare class TransportWebTransport {
76
+ private readonly url;
77
+ private readonly ctor;
78
+ private readonly hashes;
79
+ private wt;
80
+ private writer;
81
+ private receiver;
82
+ private closeHandler;
83
+ private closeNotified;
84
+ /**
85
+ * @param url The `https://host:port/path` WebTransport endpoint to dial.
86
+ * @param options Transport options; see {@link TransportWebTransportOptions}.
87
+ */
88
+ constructor(url: string, options?: TransportWebTransportOptions);
89
+ /**
90
+ * Register (or clear) the inbound-frame receiver. Mirrors the C++
91
+ * `set_receiver`: invoked once per complete length-prefixed record with that
92
+ * record's frame bytes.
93
+ */
94
+ onFrame(receiver: FrameReceiver | null): void;
95
+ /**
96
+ * Register (or clear) the connection-closed notifier (the `ClientTransport`
97
+ * seam's optional close hook). Invoked at most once per session, when an
98
+ * OPEN session closes — remotely, on error, or via {@link close}.
99
+ */
100
+ onClose(handler: CloseHandler | null): void;
101
+ /** Fire the close notifier exactly once for the current session. */
102
+ private notifyClose;
103
+ /** True once the session and its frame stream are up and not yet closed. */
104
+ get connected(): boolean;
105
+ /**
106
+ * Establish the WebTransport session (HTTP/3 extended CONNECT) and open the
107
+ * ONE bidirectional frame stream.
108
+ *
109
+ * @param deadlineMs Reject if the session is not ready within this many
110
+ * milliseconds (default 5000). Uses events, never a sleep.
111
+ * @returns A promise that resolves when frames can flow.
112
+ */
113
+ connect(deadlineMs?: number): Promise<void>;
114
+ /** Pump the frame stream through the reassembler until it ends. */
115
+ private readLoop;
116
+ /**
117
+ * Send one complete libtracer TLV as one length-prefixed record on the frame
118
+ * stream. Throws if not connected; a transmit failure surfaces through the
119
+ * session's close notifier (the underlying write is asynchronous).
120
+ */
121
+ send(frame: Uint8Array): void;
122
+ /** Close the session. Resolves once the session has fully closed. */
123
+ close(): Promise<void>;
124
+ }
@@ -0,0 +1,194 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: Copyright 2026 avatarsd LLC
3
+ // TransportWebTransport — the browser WebTransport transport for libtracer
4
+ // (ADR-0043 Phase B / ADR-0031: the browser-facing low-latency form of QUIC).
5
+ //
6
+ // It mirrors the seam of the C++ `tr::net::webtransport_transport_t`
7
+ // (core/src/transport_webtransport.cpp) from the DIAL side: the runtime's
8
+ // `WebTransport` performs the HTTP/3 extended-CONNECT session handshake, then
9
+ // this transport opens ONE bidirectional stream (`createBidirectionalStream`)
10
+ // as the frame channel and carries each libtracer TLV as a `u32-LE length ++
11
+ // frame` record (./framing.ts) — the identical stream framing the C++ TCP,
12
+ // QUIC and WebTransport transports speak, so a browser interoperates with a
13
+ // C++ `webtransport_transport_t` listener directly.
14
+ //
15
+ // Dev-time trust uses the standard WebTransport pattern: pass the SHA-256 hash
16
+ // of the server's certificate via `serverCertificateHashes` (the certificate
17
+ // must be ECDSA and valid <= 14 days — a browser rule, not ours). Deployments
18
+ // use a real certificate and omit the option.
19
+ import { FrameReassembler, encodeRecord } from './framing.js';
20
+ /**
21
+ * A WebTransport-backed libtracer transport client.
22
+ *
23
+ * Lifecycle: construct with an `https://host:port/` URL, `await connect()`
24
+ * (session handshake + the bidirectional frame stream), then `send()` TLV
25
+ * bytes and receive inbound TLVs via {@link onFrame}. Satisfies the client
26
+ * SDK's `ClientTransport` seam structurally (send / onFrame / onClose),
27
+ * exactly like `TransportWs`.
28
+ */
29
+ export class TransportWebTransport {
30
+ /**
31
+ * @param url The `https://host:port/path` WebTransport endpoint to dial.
32
+ * @param options Transport options; see {@link TransportWebTransportOptions}.
33
+ */
34
+ constructor(url, options = {}) {
35
+ this.wt = null;
36
+ this.writer = null;
37
+ this.receiver = null;
38
+ this.closeHandler = null;
39
+ this.closeNotified = false;
40
+ const ctor = options.WebTransport ?? globalThis.WebTransport;
41
+ if (!ctor) {
42
+ throw new Error('No WebTransport implementation available: run in a browser (or pass ' +
43
+ 'options.WebTransport). Node has no native WebTransport client.');
44
+ }
45
+ this.url = url;
46
+ this.ctor = ctor;
47
+ this.hashes = options.serverCertificateHashes;
48
+ }
49
+ /**
50
+ * Register (or clear) the inbound-frame receiver. Mirrors the C++
51
+ * `set_receiver`: invoked once per complete length-prefixed record with that
52
+ * record's frame bytes.
53
+ */
54
+ onFrame(receiver) {
55
+ this.receiver = receiver;
56
+ }
57
+ /**
58
+ * Register (or clear) the connection-closed notifier (the `ClientTransport`
59
+ * seam's optional close hook). Invoked at most once per session, when an
60
+ * OPEN session closes — remotely, on error, or via {@link close}.
61
+ */
62
+ onClose(handler) {
63
+ this.closeHandler = handler;
64
+ }
65
+ /** Fire the close notifier exactly once for the current session. */
66
+ notifyClose(cause) {
67
+ if (this.closeNotified)
68
+ return;
69
+ this.closeNotified = true;
70
+ if (this.closeHandler)
71
+ this.closeHandler(cause);
72
+ }
73
+ /** True once the session and its frame stream are up and not yet closed. */
74
+ get connected() {
75
+ return this.wt !== null && this.writer !== null;
76
+ }
77
+ /**
78
+ * Establish the WebTransport session (HTTP/3 extended CONNECT) and open the
79
+ * ONE bidirectional frame stream.
80
+ *
81
+ * @param deadlineMs Reject if the session is not ready within this many
82
+ * milliseconds (default 5000). Uses events, never a sleep.
83
+ * @returns A promise that resolves when frames can flow.
84
+ */
85
+ async connect(deadlineMs = 5000) {
86
+ const init = {};
87
+ if (this.hashes)
88
+ init.serverCertificateHashes = this.hashes;
89
+ const wt = new this.ctor(this.url, init);
90
+ let timer;
91
+ const deadline = new Promise((_, reject) => {
92
+ timer = setTimeout(() => {
93
+ try {
94
+ wt.close();
95
+ }
96
+ catch {
97
+ /* ignore */
98
+ }
99
+ reject(new Error(`TransportWebTransport.connect timed out after ${deadlineMs}ms`));
100
+ }, deadlineMs);
101
+ });
102
+ try {
103
+ await Promise.race([wt.ready, deadline]);
104
+ const stream = await Promise.race([wt.createBidirectionalStream(), deadline]);
105
+ this.writer = stream.writable.getWriter();
106
+ this.wt = wt;
107
+ this.closeNotified = false; // arm the close notifier for this session
108
+ // The session-closed watcher: resolves on clean close, rejects on error.
109
+ wt.closed.then(() => {
110
+ this.wt = null;
111
+ this.writer = null;
112
+ this.notifyClose();
113
+ }, (err) => {
114
+ this.wt = null;
115
+ this.writer = null;
116
+ this.notifyClose(err instanceof Error ? err : new Error(String(err)));
117
+ });
118
+ // The read loop: reassemble length-prefixed records off the frame stream.
119
+ void this.readLoop(stream.readable.getReader());
120
+ }
121
+ catch (err) {
122
+ throw err instanceof Error
123
+ ? err
124
+ : new Error(`TransportWebTransport.connect failed: ${String(err)}`);
125
+ }
126
+ finally {
127
+ clearTimeout(timer);
128
+ }
129
+ }
130
+ /** Pump the frame stream through the reassembler until it ends. */
131
+ async readLoop(reader) {
132
+ const reassembler = new FrameReassembler();
133
+ try {
134
+ for (;;) {
135
+ const { done, value } = await reader.read();
136
+ if (done)
137
+ break;
138
+ if (!value)
139
+ continue;
140
+ // A malformed prefix throws here — the stream is desynced (see below).
141
+ const frames = reassembler.push(value);
142
+ for (const frame of frames) {
143
+ if (this.receiver)
144
+ this.receiver(frame);
145
+ }
146
+ }
147
+ }
148
+ catch (err) {
149
+ // Desynced framing or a stream error: the session is unusable.
150
+ try {
151
+ this.wt?.close();
152
+ }
153
+ catch {
154
+ /* ignore */
155
+ }
156
+ this.notifyClose(err instanceof Error ? err : new Error(String(err)));
157
+ }
158
+ }
159
+ /**
160
+ * Send one complete libtracer TLV as one length-prefixed record on the frame
161
+ * stream. Throws if not connected; a transmit failure surfaces through the
162
+ * session's close notifier (the underlying write is asynchronous).
163
+ */
164
+ send(frame) {
165
+ if (!this.writer)
166
+ throw new Error('TransportWebTransport.send called before connect()');
167
+ // Backpressure is delegated to the stream's internal queue; a rejected
168
+ // write means the session died — the closed watcher notifies.
169
+ void this.writer.write(encodeRecord(frame)).catch(() => {
170
+ /* surfaced via wt.closed */
171
+ });
172
+ }
173
+ /** Close the session. Resolves once the session has fully closed. */
174
+ async close() {
175
+ const wt = this.wt;
176
+ if (!wt)
177
+ return;
178
+ this.wt = null;
179
+ this.writer = null;
180
+ try {
181
+ wt.close();
182
+ }
183
+ catch {
184
+ /* ignore */
185
+ }
186
+ try {
187
+ await wt.closed;
188
+ }
189
+ catch {
190
+ /* a close-triggered rejection is still a completed close */
191
+ }
192
+ this.notifyClose();
193
+ }
194
+ }
package/package.json ADDED
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "@avatarsd-llc/libtracer-webtransport",
3
+ "version": "0.3.0",
4
+ "description": "WebTransport transport for libtracer (ADR-0043 Phase B) — a browser WebTransport client that carries libtracer TLV frames over ONE bidirectional stream with 4-byte u32-LE length-prefix framing, wire-compatible with the C++ tr::net::webtransport_transport_t (the libtracer_quic module). The core (@avatarsd-llc/libtracer) is a peerDependency. See docs/adr/0033-npm-subpackage-monorepo.md.",
5
+ "author": "avatarsd LLC",
6
+ "license": "Apache-2.0",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/avatarsd-llc/libtracer.git",
10
+ "directory": "bindings/typescript/packages/transport-webtransport"
11
+ },
12
+ "homepage": "https://github.com/avatarsd-llc/libtracer#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/avatarsd-llc/libtracer/issues"
15
+ },
16
+ "keywords": ["protocol", "iot", "graph", "tlv", "webtransport", "http3", "quic", "transport"],
17
+ "type": "module",
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "sideEffects": false,
22
+ "main": "dist/index.js",
23
+ "types": "dist/index.d.ts",
24
+ "exports": {
25
+ ".": {
26
+ "types": "./dist/index.d.ts",
27
+ "default": "./dist/index.js"
28
+ },
29
+ "./framing": {
30
+ "types": "./dist/framing.d.ts",
31
+ "default": "./dist/framing.js"
32
+ },
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": ["dist", "README.md", "LICENSE"],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "peerDependencies": {
40
+ "@avatarsd-llc/libtracer": ">=0.3.0 <0.4.0"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc",
44
+ "test": "node --test test/*.test.mjs",
45
+ "prepublishOnly": "npm run build"
46
+ },
47
+ "devDependencies": {
48
+ "@avatarsd-llc/libtracer": "*",
49
+ "@types/node": "^20.0.0",
50
+ "typescript": "^5.4.0"
51
+ }
52
+ }