@webtransport-bun/webtransport 0.2.0 → 0.2.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.
package/dist/index.js ADDED
@@ -0,0 +1,1367 @@
1
+ /**
2
+ * @packageDocumentation
3
+ * @module @webtransport-bun/webtransport
4
+ *
5
+ * Production-ready WebTransport for Bun, backed by napi-rs + wtransport (Rust).
6
+ * Supports in-process server, client (Node API and W3C-style facade), datagrams, and streams.
7
+ */
8
+ // Re-export stream symbols and helpers
9
+ export { WT_RESET, WT_STOP_SENDING } from "./streams.js";
10
+ import { BidiStream, RecvStream, SendStream, WT_RESET, WT_STOP_SENDING, } from "./streams.js";
11
+ /**
12
+ * Stable error codes. Use with {@link WebTransportError.code} for programmatic handling.
13
+ * @see WebTransportError
14
+ */
15
+ export { E_TLS, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, E_SESSION_IDLE_TIMEOUT, E_STREAM_RESET, E_STOP_SENDING, E_QUEUE_FULL, E_BACKPRESSURE_TIMEOUT, E_LIMIT_EXCEEDED, E_RATE_LIMITED, E_INTERNAL, WebTransportError, } from "./errors.js";
16
+ import { E_INTERNAL, E_HANDSHAKE_TIMEOUT, E_SESSION_CLOSED, WebTransportError, } from "./errors.js";
17
+ const E_CODE_RE = /E_[A-Z_]+/g;
18
+ /**
19
+ * Maps known validation/connect failures to browser-style DOMException names.
20
+ * Returns undefined for unknown cases; E_* code is always preserved.
21
+ * No broad catch-all: unknown errors remain explicit.
22
+ */
23
+ function normalizeToBrowserName(code, message) {
24
+ if (message.includes("serverCertificateHashes cannot be used with allowPooling=true")) {
25
+ return "NotSupportedError";
26
+ }
27
+ if (message.includes("serverCertificateHashes must be an array")) {
28
+ return "TypeError";
29
+ }
30
+ if (message.includes("allowPooling must be a boolean") ||
31
+ message.includes("requireUnreliable must be a boolean")) {
32
+ return "TypeError";
33
+ }
34
+ if (message.includes("congestionControl must be") ||
35
+ message.includes("datagramsReadableType must be")) {
36
+ return "TypeError";
37
+ }
38
+ if (message.includes("E_HANDSHAKE_TIMEOUT")) {
39
+ return "TimeoutError";
40
+ }
41
+ if (message.includes("E_SESSION_CLOSED") ||
42
+ message.includes("E_SESSION_IDLE_TIMEOUT")) {
43
+ return "InvalidStateError";
44
+ }
45
+ return undefined;
46
+ }
47
+ function toWebTransportError(err, strictW3CErrors) {
48
+ const msg = err instanceof Error ? err.message : String(err);
49
+ const match = msg.match(E_CODE_RE);
50
+ const code = match ? match[0] : E_INTERNAL;
51
+ const browserName = strictW3CErrors === true ? normalizeToBrowserName(code, msg) : undefined;
52
+ return new WebTransportError(code, msg, browserName ? { browserName } : undefined);
53
+ }
54
+ /** Default limit values from AGENTS.md */
55
+ export const DEFAULT_LIMITS = {
56
+ maxSessions: 2000,
57
+ maxHandshakesInFlight: 200,
58
+ maxStreamsPerSessionBidi: 200,
59
+ maxStreamsPerSessionUni: 200,
60
+ maxStreamsGlobal: 50_000,
61
+ maxDatagramSize: 1200,
62
+ maxQueuedBytesGlobal: 512 * 1024 * 1024, // 512 MiB
63
+ maxQueuedBytesPerSession: 2 * 1024 * 1024, // 2 MiB
64
+ maxQueuedBytesPerStream: 256 * 1024, // 256 KiB
65
+ backpressureTimeoutMs: 5000,
66
+ handshakeTimeoutMs: 10_000,
67
+ idleTimeoutMs: 60_000,
68
+ };
69
+ /** Default rate-limit values from AGENTS.md */
70
+ export const DEFAULT_RATE_LIMITS = {
71
+ handshakesPerSec: 20,
72
+ handshakesBurst: 40,
73
+ handshakesBurstPerPrefix: 100,
74
+ streamsPerSec: 200,
75
+ streamsBurst: 400,
76
+ datagramsPerSec: 2000,
77
+ datagramsBurst: 5000,
78
+ };
79
+ function normalizeCloseInfo(info, fallback) {
80
+ return {
81
+ code: info?.code ?? fallback?.code ?? 0,
82
+ reason: info?.reason ?? fallback?.reason ?? "",
83
+ };
84
+ }
85
+ /** W3C-style send group object used by sendOrder/sendGroup options. */
86
+ export class WebTransportSendGroup {
87
+ #transport;
88
+ #id;
89
+ constructor(transport, id) {
90
+ this.#transport = transport;
91
+ this.#id = id;
92
+ }
93
+ _getTransport() {
94
+ return this.#transport;
95
+ }
96
+ _getId() {
97
+ return this.#id;
98
+ }
99
+ async getStats() {
100
+ return this.#transport._getSendGroupStats(this.#id);
101
+ }
102
+ }
103
+ /** Prometheus metric name prefix. Override via env WEBTRANSPORT_METRICS_PREFIX. */
104
+ export const METRICS_PREFIX = process.env.WEBTRANSPORT_METRICS_PREFIX ?? "webtransport_";
105
+ function shouldSuppressInsecureSkipVerifyWarning() {
106
+ const v = process.env.WEBTRANSPORT_SUPPRESS_INSECURE_SKIP_VERIFY_WARN;
107
+ return v === "1" || v === "true" || v === "yes";
108
+ }
109
+ function escapePromLabelValue(v) {
110
+ return String(v)
111
+ .replace(/\\/g, "\\\\")
112
+ .replace(/\n/g, "\\n")
113
+ .replace(/"/g, '\\"');
114
+ }
115
+ function sanitizePromLabelName(k) {
116
+ const safe = k.replace(/[^a-zA-Z0-9_]/g, "_");
117
+ return /^[a-zA-Z_]/.test(safe) ? safe : `_${safe}`;
118
+ }
119
+ /**
120
+ * Convert MetricsSnapshot to Prometheus exposition format (text).
121
+ * Gauges: sessions_active, handshakes_in_flight, streams_active, session_tasks_active, stream_tasks_active, queued_bytes_global.
122
+ * Counters: datagrams_in, datagrams_out, datagrams_dropped, backpressure_wait_total, backpressure_timeout_total, rate_limited_total, limit_exceeded_total.
123
+ *
124
+ * @example
125
+ * ```ts
126
+ * const snapshot = server.metricsSnapshot();
127
+ * const text = metricsToPrometheus(snapshot, { serverId: "main" });
128
+ * response.end(text); // Content-Type: text/plain; version=0.0.4
129
+ * ```
130
+ */
131
+ export function metricsToPrometheus(m, labels) {
132
+ const baseLabels = labels
133
+ ? Object.entries(labels)
134
+ .map(([k, v]) => `${sanitizePromLabelName(k)}="${escapePromLabelValue(v)}"`)
135
+ .join(",")
136
+ : "";
137
+ const metricLabels = baseLabels ? `{${baseLabels}}` : "";
138
+ const p = METRICS_PREFIX;
139
+ const lines = [
140
+ `# HELP ${p}sessions_active Current open sessions`,
141
+ `# TYPE ${p}sessions_active gauge`,
142
+ `${p}sessions_active${metricLabels} ${m.sessionsActive}`,
143
+ `# HELP ${p}handshakes_in_flight Handshakes in progress`,
144
+ `# TYPE ${p}handshakes_in_flight gauge`,
145
+ `${p}handshakes_in_flight${metricLabels} ${m.handshakesInFlight}`,
146
+ `# HELP ${p}streams_active Active streams`,
147
+ `# TYPE ${p}streams_active gauge`,
148
+ `${p}streams_active${metricLabels} ${m.streamsActive}`,
149
+ `# HELP ${p}session_tasks_active Internal session tasks`,
150
+ `# TYPE ${p}session_tasks_active gauge`,
151
+ `${p}session_tasks_active${metricLabels} ${m.sessionTasksActive}`,
152
+ `# HELP ${p}stream_tasks_active Internal stream tasks`,
153
+ `# TYPE ${p}stream_tasks_active gauge`,
154
+ `${p}stream_tasks_active${metricLabels} ${m.streamTasksActive}`,
155
+ `# HELP ${p}queued_bytes_global Bytes queued globally`,
156
+ `# TYPE ${p}queued_bytes_global gauge`,
157
+ `${p}queued_bytes_global${metricLabels} ${m.queuedBytesGlobal}`,
158
+ `# HELP ${p}datagrams_in Datagrams received`,
159
+ `# TYPE ${p}datagrams_in counter`,
160
+ `${p}datagrams_in${metricLabels} ${m.datagramsIn}`,
161
+ `# HELP ${p}datagrams_out Datagrams sent`,
162
+ `# TYPE ${p}datagrams_out counter`,
163
+ `${p}datagrams_out${metricLabels} ${m.datagramsOut}`,
164
+ `# HELP ${p}datagrams_dropped Datagrams dropped`,
165
+ `# TYPE ${p}datagrams_dropped counter`,
166
+ `${p}datagrams_dropped${metricLabels} ${m.datagramsDropped}`,
167
+ `# HELP ${p}backpressure_wait_total Times senders waited on backpressure`,
168
+ `# TYPE ${p}backpressure_wait_total counter`,
169
+ `${p}backpressure_wait_total${metricLabels} ${m.backpressureWaitCount}`,
170
+ `# HELP ${p}backpressure_timeout_total Times backpressure timeout fired`,
171
+ `# TYPE ${p}backpressure_timeout_total counter`,
172
+ `${p}backpressure_timeout_total${metricLabels} ${m.backpressureTimeoutCount}`,
173
+ `# HELP ${p}rate_limited_total Sessions rejected by rate limit`,
174
+ `# TYPE ${p}rate_limited_total counter`,
175
+ `${p}rate_limited_total${metricLabels} ${m.rateLimitedCount}`,
176
+ `# HELP ${p}limit_exceeded_total Sessions rejected (limits)`,
177
+ `# TYPE ${p}limit_exceeded_total counter`,
178
+ `${p}limit_exceeded_total${metricLabels} ${m.limitExceededCount}`,
179
+ ];
180
+ function emitHistogram(name, h) {
181
+ if (!h)
182
+ return;
183
+ const raw = h;
184
+ const le = (raw.le ?? []);
185
+ const cumulativeCount = (raw.cumulativeCount ??
186
+ raw.cumulative_count ??
187
+ []);
188
+ const count = (raw.count ?? 0);
189
+ const sumSecs = (raw.sumSecs ?? raw.sum_secs ?? 0);
190
+ const bn = `${p}${name}`;
191
+ lines.push(`# HELP ${bn}_seconds Latency histogram (seconds)`);
192
+ lines.push(`# TYPE ${bn}_seconds histogram`);
193
+ for (let i = 0; i < le.length; i++) {
194
+ const v = le[i];
195
+ const leVal = v === Infinity || v === undefined || v >= 1e308 ? "+Inf" : String(v);
196
+ const bucketLabels = baseLabels
197
+ ? `{le="${leVal}",${baseLabels}}`
198
+ : `{le="${leVal}"}`;
199
+ lines.push(`${bn}_seconds_bucket${bucketLabels} ${Math.round(cumulativeCount[i] ?? 0)}`);
200
+ }
201
+ const infBucketLabels = baseLabels
202
+ ? `{le="+Inf",${baseLabels}}`
203
+ : `{le="+Inf"}`;
204
+ lines.push(`${bn}_seconds_bucket${infBucketLabels} ${Math.round(count)}`);
205
+ lines.push(`${bn}_seconds_count${metricLabels} ${Math.round(count)}`);
206
+ lines.push(`${bn}_seconds_sum${metricLabels} ${sumSecs}`);
207
+ }
208
+ const mAny = m;
209
+ emitHistogram("handshake_latency", (mAny.handshakeLatency ?? mAny.handshake_latency));
210
+ emitHistogram("datagram_enqueue_latency", (mAny.datagramEnqueueLatency ?? mAny.datagram_enqueue_latency));
211
+ emitHistogram("stream_open_latency", (mAny.streamOpenLatency ?? mAny.stream_open_latency));
212
+ return lines.join("\n") + "\n";
213
+ }
214
+ // ---------------------------------------------------------------------------
215
+ // Native addon loader
216
+ // ---------------------------------------------------------------------------
217
+ import { createRequire } from "node:module";
218
+ const _require = createRequire(import.meta.url);
219
+ const PLATFORM = process.platform;
220
+ const ARCH = process.arch;
221
+ let native;
222
+ const binaryCandidates = [
223
+ `webtransport-native.${PLATFORM}-${ARCH}.node`,
224
+ `webtransport-native.${PLATFORM}-${ARCH}-gnu.node`,
225
+ `webtransport-native.${PLATFORM}-${ARCH}-musl.node`,
226
+ ];
227
+ const basePaths = ["../../../crates/native", "../prebuilds"];
228
+ for (const base of basePaths) {
229
+ for (const candidate of binaryCandidates) {
230
+ try {
231
+ native = _require(`${base}/${candidate}`);
232
+ break;
233
+ }
234
+ catch {
235
+ continue;
236
+ }
237
+ }
238
+ if (native)
239
+ break;
240
+ }
241
+ // ---------------------------------------------------------------------------
242
+ // Server session implementation
243
+ // ---------------------------------------------------------------------------
244
+ class NativeServerSession {
245
+ #nativeHandle;
246
+ #closedPromise;
247
+ #closed = false;
248
+ #requestedCloseInfo = null;
249
+ #incomingBidiCache = null;
250
+ #incomingUniCache = null;
251
+ constructor(nativeHandle, closedPromise) {
252
+ this.#nativeHandle = nativeHandle;
253
+ this.#closedPromise = closedPromise.then((info) => normalizeCloseInfo(info, this.#requestedCloseInfo ?? undefined));
254
+ this.#closedPromise.then(() => {
255
+ this.#closed = true;
256
+ });
257
+ }
258
+ get id() {
259
+ return this.#nativeHandle.id;
260
+ }
261
+ get peer() {
262
+ return {
263
+ ip: this.#nativeHandle.peerIp,
264
+ port: this.#nativeHandle.peerPort,
265
+ };
266
+ }
267
+ get ready() {
268
+ // Server sessions are already handshake-complete when onSession fires
269
+ return Promise.resolve();
270
+ }
271
+ get closed() {
272
+ return this.#closedPromise;
273
+ }
274
+ close(info) {
275
+ if (!this.#closed) {
276
+ this.#closed = true;
277
+ this.#requestedCloseInfo = normalizeCloseInfo(info);
278
+ this.#nativeHandle.close(info?.code ?? null, info?.reason ?? null);
279
+ }
280
+ }
281
+ async sendDatagram(data) {
282
+ if (this.#closed)
283
+ throw new WebTransportError(E_SESSION_CLOSED);
284
+ try {
285
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
286
+ await this.#nativeHandle.sendDatagram(buf);
287
+ }
288
+ catch (err) {
289
+ throw toWebTransportError(err);
290
+ }
291
+ }
292
+ async *incomingDatagrams() {
293
+ while (!this.#closed) {
294
+ try {
295
+ const datagram = await this.#nativeHandle.readDatagram();
296
+ if (!datagram)
297
+ break;
298
+ yield datagram;
299
+ }
300
+ catch {
301
+ break;
302
+ }
303
+ }
304
+ }
305
+ async createBidirectionalStream() {
306
+ if (this.#closed)
307
+ throw new WebTransportError(E_SESSION_CLOSED);
308
+ try {
309
+ const nativeStream = await this.#nativeHandle.createBidiStream();
310
+ return new BidiStream({
311
+ handleId: nativeStream?.id ?? 0,
312
+ nativeHandle: nativeStream,
313
+ });
314
+ }
315
+ catch (err) {
316
+ throw toWebTransportError(err);
317
+ }
318
+ }
319
+ get incomingBidirectionalStreams() {
320
+ if (!this.#incomingBidiCache) {
321
+ this.#incomingBidiCache = createServerIncomingBidiStreams(this.#nativeHandle, () => this.#closed);
322
+ }
323
+ return this.#incomingBidiCache;
324
+ }
325
+ async createUnidirectionalStream() {
326
+ if (this.#closed)
327
+ throw new WebTransportError(E_SESSION_CLOSED);
328
+ try {
329
+ const nativeStream = await this.#nativeHandle.createUniStream();
330
+ return new SendStream({
331
+ handleId: nativeStream?.id ?? 0,
332
+ nativeHandle: nativeStream,
333
+ });
334
+ }
335
+ catch (err) {
336
+ throw toWebTransportError(err);
337
+ }
338
+ }
339
+ get incomingUnidirectionalStreams() {
340
+ if (!this.#incomingUniCache) {
341
+ this.#incomingUniCache = createServerIncomingUniStreams(this.#nativeHandle, () => this.#closed);
342
+ }
343
+ return this.#incomingUniCache;
344
+ }
345
+ metricsSnapshot() {
346
+ return this.#nativeHandle.metricsSnapshot();
347
+ }
348
+ }
349
+ // ---------------------------------------------------------------------------
350
+ // createServer
351
+ // ---------------------------------------------------------------------------
352
+ /**
353
+ * Create an in-process WebTransport server.
354
+ *
355
+ * @param opts - Server configuration. Requires `port`, `tls` (certPem, keyPem), and `onSession` callback.
356
+ * @returns WebTransportServer with `address`, `close()`, and `metricsSnapshot()`.
357
+ * @throws Error if native addon is not loaded.
358
+ *
359
+ * @example
360
+ * ```ts
361
+ * const server = createServer({
362
+ * port: 4433,
363
+ * tls: { certPem: "...", keyPem: "..." },
364
+ * onSession: async (session) => {
365
+ * for await (const d of session.incomingDatagrams()) {
366
+ * await session.sendDatagram(d);
367
+ * }
368
+ * },
369
+ * });
370
+ * // server.address.port
371
+ * await server.close();
372
+ * ```
373
+ */
374
+ export function createServer(opts) {
375
+ if (!native) {
376
+ throw new Error("Native addon not loaded");
377
+ }
378
+ const certPem = typeof opts.tls.certPem === "string"
379
+ ? opts.tls.certPem
380
+ : new TextDecoder().decode(opts.tls.certPem);
381
+ const keyPem = typeof opts.tls.keyPem === "string"
382
+ ? opts.tls.keyPem
383
+ : new TextDecoder().decode(opts.tls.keyPem);
384
+ const caPem = typeof opts.tls.caPem === "string"
385
+ ? opts.tls.caPem
386
+ : opts.tls.caPem != null
387
+ ? new TextDecoder().decode(opts.tls.caPem)
388
+ : "";
389
+ const limitsJson = JSON.stringify({ ...DEFAULT_LIMITS, ...opts.limits });
390
+ const rateLimitsJson = JSON.stringify({
391
+ ...DEFAULT_RATE_LIMITS,
392
+ ...opts.rateLimits,
393
+ });
394
+ const closedResolvers = new Map();
395
+ let activeOnSessionCallbacks = 0;
396
+ let onSessionDrainResolve = null;
397
+ const logCallback = (logEvents) => {
398
+ if (opts.log) {
399
+ for (const le of logEvents) {
400
+ opts.log({
401
+ level: le.level ?? "info",
402
+ msg: le.msg ?? "",
403
+ sessionId: le.sessionId,
404
+ peerIp: le.peerIp,
405
+ peerPort: le.peerPort,
406
+ });
407
+ }
408
+ }
409
+ };
410
+ const handle = new native.ServerHandle(opts.port, opts.host ?? "0.0.0.0", opts.debug === true, certPem, keyPem, caPem, limitsJson, rateLimitsJson, (events) => {
411
+ for (const evt of events) {
412
+ if (evt.name === "session" &&
413
+ evt.id != null &&
414
+ evt.peerIp != null &&
415
+ evt.peerPort != null) {
416
+ let closedResolve;
417
+ const closedPromise = new Promise((resolve) => {
418
+ closedResolve = resolve;
419
+ });
420
+ closedResolvers.set(evt.id, closedResolve);
421
+ const nativeSession = new native.SessionHandle(evt.id, evt.peerIp, evt.peerPort);
422
+ const session = new NativeServerSession(nativeSession, closedPromise);
423
+ activeOnSessionCallbacks++;
424
+ const maybePromise = opts.onSession(session);
425
+ if (maybePromise && typeof maybePromise.then === "function") {
426
+ maybePromise.then(onSessionCallbackDone, onSessionCallbackDone);
427
+ }
428
+ else {
429
+ onSessionCallbackDone();
430
+ }
431
+ }
432
+ else if (evt.name === "session_closed" && evt.id != null) {
433
+ const resolve = closedResolvers.get(evt.id);
434
+ closedResolvers.delete(evt.id);
435
+ if (resolve)
436
+ resolve({ code: evt.code, reason: evt.reason });
437
+ }
438
+ }
439
+ }, logCallback);
440
+ function onSessionCallbackDone() {
441
+ activeOnSessionCallbacks--;
442
+ if (activeOnSessionCallbacks <= 0 && onSessionDrainResolve) {
443
+ onSessionDrainResolve();
444
+ onSessionDrainResolve = null;
445
+ }
446
+ }
447
+ return {
448
+ address: { host: opts.host ?? "0.0.0.0", port: handle.port },
449
+ close: async () => {
450
+ await handle.close();
451
+ for (const [id, resolve] of closedResolvers) {
452
+ closedResolvers.delete(id);
453
+ resolve({ code: 0, reason: "server closed" });
454
+ }
455
+ if (activeOnSessionCallbacks > 0) {
456
+ await Promise.race([
457
+ new Promise((r) => {
458
+ onSessionDrainResolve = r;
459
+ }),
460
+ new Promise((r) => setTimeout(r, 5000)),
461
+ ]);
462
+ }
463
+ },
464
+ metricsSnapshot: () => handle.metricsSnapshot(),
465
+ };
466
+ }
467
+ // ---------------------------------------------------------------------------
468
+ // Client session implementation
469
+ // ---------------------------------------------------------------------------
470
+ class NativeClientSession {
471
+ #nativeHandle;
472
+ #readyPromise;
473
+ #closedPromise;
474
+ #closed = false;
475
+ #requestedCloseInfo = null;
476
+ #strictW3CErrors;
477
+ constructor(nativeHandle, readyPromise, closedPromise, strictW3CErrors = false) {
478
+ this.#nativeHandle = nativeHandle;
479
+ this.#readyPromise = readyPromise;
480
+ this.#closedPromise = closedPromise.then((info) => normalizeCloseInfo(info, this.#requestedCloseInfo ?? undefined));
481
+ this.#strictW3CErrors = strictW3CErrors;
482
+ this.#closedPromise.then(() => {
483
+ this.#closed = true;
484
+ });
485
+ }
486
+ get id() {
487
+ return this.#nativeHandle.id;
488
+ }
489
+ get peer() {
490
+ return {
491
+ ip: this.#nativeHandle.peerIp,
492
+ port: this.#nativeHandle.peerPort,
493
+ };
494
+ }
495
+ get ready() {
496
+ return this.#readyPromise;
497
+ }
498
+ get closed() {
499
+ return this.#closedPromise;
500
+ }
501
+ close(info) {
502
+ if (!this.#closed) {
503
+ this.#closed = true;
504
+ this.#requestedCloseInfo = normalizeCloseInfo(info);
505
+ this.#nativeHandle.close(info?.code ?? null, info?.reason ?? null);
506
+ }
507
+ }
508
+ async sendDatagram(data) {
509
+ if (this.#closed)
510
+ throw new WebTransportError(E_SESSION_CLOSED);
511
+ try {
512
+ const buf = Buffer.isBuffer(data) ? data : Buffer.from(data);
513
+ await this.#nativeHandle.sendDatagram(buf);
514
+ }
515
+ catch (err) {
516
+ throw toWebTransportError(err, this.#strictW3CErrors);
517
+ }
518
+ }
519
+ async *incomingDatagrams() {
520
+ while (!this.#closed) {
521
+ try {
522
+ const dgram = await this.#nativeHandle.readDatagram();
523
+ if (!dgram)
524
+ break;
525
+ yield dgram;
526
+ }
527
+ catch {
528
+ break;
529
+ }
530
+ }
531
+ }
532
+ async createBidirectionalStream() {
533
+ if (this.#closed)
534
+ throw new WebTransportError(E_SESSION_CLOSED);
535
+ try {
536
+ const nativeStream = await this.#nativeHandle.createBidiStream();
537
+ return new BidiStream({
538
+ handleId: nativeStream?.id ?? 0,
539
+ nativeHandle: nativeStream,
540
+ });
541
+ }
542
+ catch (err) {
543
+ throw toWebTransportError(err, this.#strictW3CErrors);
544
+ }
545
+ }
546
+ async *incomingBidirectionalStreams() {
547
+ while (!this.#closed) {
548
+ try {
549
+ const nativeStream = await this.#nativeHandle.acceptBidiStream();
550
+ if (!nativeStream)
551
+ break;
552
+ yield new BidiStream({
553
+ handleId: nativeStream?.id ?? 0,
554
+ nativeHandle: nativeStream,
555
+ });
556
+ }
557
+ catch {
558
+ break;
559
+ }
560
+ }
561
+ }
562
+ async createUnidirectionalStream() {
563
+ if (this.#closed)
564
+ throw new WebTransportError(E_SESSION_CLOSED);
565
+ try {
566
+ const nativeStream = await this.#nativeHandle.createUniStream();
567
+ return new SendStream({
568
+ handleId: nativeStream?.id ?? 0,
569
+ nativeHandle: nativeStream,
570
+ });
571
+ }
572
+ catch (err) {
573
+ throw toWebTransportError(err, this.#strictW3CErrors);
574
+ }
575
+ }
576
+ async *incomingUnidirectionalStreams() {
577
+ while (!this.#closed) {
578
+ try {
579
+ const nativeStream = await this.#nativeHandle.acceptUniStream();
580
+ if (!nativeStream)
581
+ break;
582
+ yield new RecvStream({
583
+ handleId: nativeStream?.id ?? 0,
584
+ nativeHandle: nativeStream,
585
+ });
586
+ }
587
+ catch {
588
+ break;
589
+ }
590
+ }
591
+ }
592
+ metricsSnapshot() {
593
+ return this.#nativeHandle.metricsSnapshot();
594
+ }
595
+ }
596
+ // ---------------------------------------------------------------------------
597
+ // connect
598
+ // ---------------------------------------------------------------------------
599
+ /**
600
+ * Connect to a WebTransport server (Node API).
601
+ *
602
+ * @param url - WebTransport URL (e.g. `https://host:port/path`).
603
+ * @param opts - Optional TLS, limits, and logging. Limits default per {@link DEFAULT_LIMITS}.
604
+ * Use `tls.insecureSkipVerify: true` only for dev; emits a warning.
605
+ * @returns Promise that resolves to ClientSession when handshake completes.
606
+ * @throws WebTransportError with code `E_HANDSHAKE_TIMEOUT` if handshake exceeds `limits.handshakeTimeoutMs` (default 10s).
607
+ * @throws WebTransportError with code `E_TLS` on TLS failure.
608
+ *
609
+ * @example
610
+ * ```ts
611
+ * const session = await connect("https://127.0.0.1:4433", {
612
+ * tls: { insecureSkipVerify: true },
613
+ * limits: { handshakeTimeoutMs: 5000 },
614
+ * });
615
+ * await session.ready;
616
+ * await session.sendDatagram(new Uint8Array([1, 2, 3]));
617
+ * session.close({ code: 1000, reason: "done" });
618
+ * ```
619
+ */
620
+ export async function connect(url, opts) {
621
+ if (!native) {
622
+ throw new Error("Native addon not loaded");
623
+ }
624
+ if (opts?.tls?.insecureSkipVerify === true &&
625
+ (opts.log !== undefined || !shouldSuppressInsecureSkipVerifyWarning())) {
626
+ const log = opts.log ??
627
+ ((e) => console.warn(`[webtransport] ${e.level}: ${e.msg}`));
628
+ log({
629
+ level: "warn",
630
+ msg: "tls.insecureSkipVerify is enabled — dev only, never use in production",
631
+ });
632
+ }
633
+ const mergedLimits = { ...DEFAULT_LIMITS, ...opts?.limits };
634
+ const tlsOpts = opts?.tls
635
+ ? {
636
+ insecureSkipVerify: opts.tls.insecureSkipVerify ?? false,
637
+ caPem: opts.tls.caPem
638
+ ? typeof opts.tls.caPem === "string"
639
+ ? opts.tls.caPem
640
+ : new TextDecoder().decode(opts.tls.caPem)
641
+ : undefined,
642
+ serverName: opts.tls.serverName,
643
+ }
644
+ : undefined;
645
+ const optsJson = JSON.stringify({
646
+ limits: mergedLimits,
647
+ tls: tlsOpts,
648
+ congestionControl: opts?.congestionControl,
649
+ serverCertificateHashes: opts?.serverCertificateHashes,
650
+ allowPooling: opts?.allowPooling,
651
+ requireUnreliable: opts?.requireUnreliable,
652
+ });
653
+ const handshakeTimeout = mergedLimits.handshakeTimeoutMs;
654
+ const connectPromise = new Promise((resolve, reject) => {
655
+ const closedResolvers = new Map();
656
+ const onClosed = (events) => {
657
+ for (const evt of events) {
658
+ if (evt.name === "session_closed" && evt.id != null) {
659
+ const resolveClosed = closedResolvers.get(evt.id);
660
+ closedResolvers.delete(evt.id);
661
+ if (resolveClosed)
662
+ resolveClosed({ code: evt.code, reason: evt.reason });
663
+ }
664
+ }
665
+ };
666
+ native.connect(url, optsJson, onClosed, (err, handleId) => {
667
+ if (err) {
668
+ reject(toWebTransportError(err, opts?.strictW3CErrors));
669
+ return;
670
+ }
671
+ if (handleId == null) {
672
+ reject(new Error("connect succeeded but no handle id"));
673
+ return;
674
+ }
675
+ const handle = native.takeClientSession(handleId);
676
+ if (!handle) {
677
+ reject(new Error("connect: handle not found in registry"));
678
+ return;
679
+ }
680
+ let closedResolve;
681
+ const closedPromise = new Promise((r) => {
682
+ closedResolve = r;
683
+ });
684
+ closedResolvers.set(handle.id, closedResolve);
685
+ const readyPromise = Promise.resolve();
686
+ resolve(new NativeClientSession(handle, readyPromise, closedPromise, opts?.strictW3CErrors));
687
+ });
688
+ });
689
+ const timeoutPromise = new Promise((_, reject) => {
690
+ setTimeout(() => {
691
+ const msg = `E_HANDSHAKE_TIMEOUT: connect timed out after ${handshakeTimeout}ms`;
692
+ const browserName = opts?.strictW3CErrors === true
693
+ ? (normalizeToBrowserName(E_HANDSHAKE_TIMEOUT, msg) ??
694
+ undefined)
695
+ : undefined;
696
+ reject(new WebTransportError(E_HANDSHAKE_TIMEOUT, msg, browserName ? { browserName } : undefined));
697
+ }, handshakeTimeout);
698
+ });
699
+ return Promise.race([connectPromise, timeoutPromise]);
700
+ }
701
+ /** Client pool metrics (hits, misses, evictions). For tests when allowPooling is used. */
702
+ export function clientPoolMetricsSnapshot() {
703
+ if (!native)
704
+ throw new Error("Native addon not loaded");
705
+ const s = native.clientPoolMetricsSnapshot();
706
+ return {
707
+ hits: s.hits,
708
+ misses: s.misses,
709
+ evictIdle: s.evictIdle ?? s.evict_idle ?? 0,
710
+ evictBroken: s.evictBroken ?? s.evict_broken ?? 0,
711
+ };
712
+ }
713
+ // ---------------------------------------------------------------------------
714
+ // Browser-style WebTransport facade (Phase P1)
715
+ // ---------------------------------------------------------------------------
716
+ function validateServerCertificateHashes(arr) {
717
+ for (const entry of arr) {
718
+ if (entry.algorithm !== "sha-256") {
719
+ throw new WebTransportError(E_INTERNAL, `E_INTERNAL: serverCertificateHashes only supports algorithm "sha-256", got "${entry.algorithm}"`);
720
+ }
721
+ if (entry.value == null ||
722
+ (typeof entry.value === "object" &&
723
+ "byteLength" in entry &&
724
+ entry.byteLength === 0)) {
725
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes entry value must be non-empty BufferSource");
726
+ }
727
+ }
728
+ }
729
+ function bufferSourceToUint8(value) {
730
+ if (value instanceof ArrayBuffer)
731
+ return new Uint8Array(value);
732
+ if (ArrayBuffer.isView(value)) {
733
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength);
734
+ }
735
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes entry value must be BufferSource");
736
+ }
737
+ function bufferSourceToBase64(value) {
738
+ return Buffer.from(bufferSourceToUint8(value)).toString("base64");
739
+ }
740
+ const VALID_CONGESTION = new Set(["default", "throughput", "low-latency"]);
741
+ const VALID_DATAGRAMS_READABLE_TYPE = new Set(["bytes", "default"]);
742
+ function validateClientOptions(opts) {
743
+ if (!opts)
744
+ return;
745
+ if (opts.allowPooling !== undefined &&
746
+ typeof opts.allowPooling !== "boolean") {
747
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: allowPooling must be a boolean");
748
+ }
749
+ if (opts.requireUnreliable !== undefined &&
750
+ typeof opts.requireUnreliable !== "boolean") {
751
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: requireUnreliable must be a boolean");
752
+ }
753
+ if (opts.congestionControl !== undefined &&
754
+ !VALID_CONGESTION.has(opts.congestionControl)) {
755
+ throw new WebTransportError(E_INTERNAL, `E_INTERNAL: congestionControl must be "default", "throughput", or "low-latency", got "${opts.congestionControl}"`);
756
+ }
757
+ if (opts.datagramsReadableType !== undefined &&
758
+ !VALID_DATAGRAMS_READABLE_TYPE.has(opts.datagramsReadableType)) {
759
+ throw new WebTransportError(E_INTERNAL, `E_INTERNAL: datagramsReadableType must be "bytes" or "default", got "${opts.datagramsReadableType}"`);
760
+ }
761
+ if (opts.serverCertificateHashes !== undefined) {
762
+ if (!Array.isArray(opts.serverCertificateHashes)) {
763
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes must be an array");
764
+ }
765
+ if (opts.allowPooling === true) {
766
+ throw new WebTransportError(E_INTERNAL, "E_INTERNAL: serverCertificateHashes cannot be used with allowPooling=true", { browserName: "NotSupportedError" });
767
+ }
768
+ validateServerCertificateHashes(opts.serverCertificateHashes);
769
+ }
770
+ }
771
+ function mapToClientOptions(opts) {
772
+ if (!opts)
773
+ return {};
774
+ validateClientOptions(opts);
775
+ return {
776
+ tls: opts.tls,
777
+ limits: opts.limits,
778
+ congestionControl: opts.congestionControl,
779
+ strictW3CErrors: opts.strictW3CErrors,
780
+ serverCertificateHashes: opts.serverCertificateHashes?.map((entry) => ({
781
+ algorithm: entry.algorithm,
782
+ valueBase64: bufferSourceToBase64(entry.value),
783
+ })),
784
+ allowPooling: opts.allowPooling,
785
+ requireUnreliable: opts.requireUnreliable,
786
+ };
787
+ }
788
+ function toCloseInfo(info) {
789
+ const normalized = normalizeCloseInfo(info);
790
+ return {
791
+ closeCode: normalized.code,
792
+ reason: normalized.reason,
793
+ };
794
+ }
795
+ class SendScheduler {
796
+ #queues = new Map();
797
+ #groupOrder = [];
798
+ #rrIdx = 0;
799
+ #running = false;
800
+ #seq = 0;
801
+ enqueue(policy, run) {
802
+ return new Promise((resolve, reject) => {
803
+ const task = {
804
+ groupId: policy.groupId,
805
+ sendOrder: policy.sendOrder,
806
+ seq: this.#seq++,
807
+ run,
808
+ resolve,
809
+ reject,
810
+ };
811
+ const q = this.#queues.get(policy.groupId) ?? [];
812
+ q.push(task);
813
+ q.sort((a, b) => a.sendOrder - b.sendOrder || a.seq - b.seq);
814
+ this.#queues.set(policy.groupId, q);
815
+ if (!this.#groupOrder.includes(policy.groupId)) {
816
+ this.#groupOrder.push(policy.groupId);
817
+ }
818
+ void this.#drain();
819
+ });
820
+ }
821
+ async #drain() {
822
+ if (this.#running)
823
+ return;
824
+ this.#running = true;
825
+ try {
826
+ while (this.#groupOrder.length > 0) {
827
+ const groupId = this.#nextGroup();
828
+ if (groupId == null)
829
+ break;
830
+ const q = this.#queues.get(groupId);
831
+ if (!q || q.length === 0) {
832
+ this.#removeGroup(groupId);
833
+ continue;
834
+ }
835
+ const task = q.shift();
836
+ if (q.length === 0)
837
+ this.#removeGroup(groupId);
838
+ try {
839
+ await task.run();
840
+ task.resolve();
841
+ }
842
+ catch (err) {
843
+ task.reject(err);
844
+ }
845
+ }
846
+ }
847
+ finally {
848
+ this.#running = false;
849
+ }
850
+ }
851
+ #nextGroup() {
852
+ if (this.#groupOrder.length === 0)
853
+ return null;
854
+ if (this.#rrIdx >= this.#groupOrder.length)
855
+ this.#rrIdx = 0;
856
+ const groupId = this.#groupOrder[this.#rrIdx];
857
+ this.#rrIdx = (this.#rrIdx + 1) % Math.max(1, this.#groupOrder.length);
858
+ return groupId ?? null;
859
+ }
860
+ #removeGroup(groupId) {
861
+ this.#queues.delete(groupId);
862
+ const idx = this.#groupOrder.indexOf(groupId);
863
+ if (idx >= 0)
864
+ this.#groupOrder.splice(idx, 1);
865
+ if (this.#rrIdx > idx && idx >= 0)
866
+ this.#rrIdx--;
867
+ if (this.#rrIdx < 0)
868
+ this.#rrIdx = 0;
869
+ }
870
+ }
871
+ /**
872
+ * Browser-style WebTransport client (W3C facade).
873
+ *
874
+ * Use `new WebTransport(url, options)` to connect, or `toWebTransport(session)` to wrap an existing
875
+ * {@link ClientSession}. Await {@link WebTransport.ready} before using datagrams/streams.
876
+ *
877
+ * Option semantics:
878
+ * - `allowPooling`: when true, endpoint-level pooling; when false, dedicated sessions.
879
+ * - `requireUnreliable` is accepted; runtime transport always supports unreliable delivery.
880
+ *
881
+ * @example
882
+ * ```ts
883
+ * const wt = new WebTransport("https://127.0.0.1:4433", { tls: { insecureSkipVerify: true } });
884
+ * await wt.ready;
885
+ * const { readable, writable } = await wt.createBidirectionalStream();
886
+ * writable.getWriter().write(new Uint8Array([1, 2, 3]));
887
+ * wt.close({ closeCode: 1000, reason: "done" });
888
+ * await wt.closed;
889
+ * ```
890
+ */
891
+ export class WebTransport {
892
+ /** Static: true if runtime supports sessions over exclusively reliable (TCP) connections. Ours uses QUIC (supports unreliable). */
893
+ static supportsReliableOnly = false;
894
+ #sessionPromise;
895
+ #ready;
896
+ #closed;
897
+ #draining;
898
+ #drainingResolve;
899
+ #session = null;
900
+ #state;
901
+ #datagramsCache = null;
902
+ #datagramsReadableType;
903
+ #incomingBidiCache = null;
904
+ #incomingUniCache = null;
905
+ #sendScheduler = new SendScheduler();
906
+ #nextSendGroupId = 1;
907
+ #sendGroupBytesSent = new Map();
908
+ #connStats = {
909
+ bytesSent: 0,
910
+ bytesReceived: 0,
911
+ datagramsOut: 0,
912
+ datagramsIn: 0,
913
+ };
914
+ #congestionControl;
915
+ constructor(urlOrSession, options) {
916
+ if (typeof urlOrSession === "string") {
917
+ this.#datagramsReadableType = options?.datagramsReadableType ?? "default";
918
+ const requestedCongestion = options?.congestionControl ?? "default";
919
+ // Runtime currently supports default algorithm; explicit preference falls back to default.
920
+ this.#congestionControl =
921
+ requestedCongestion === "default" ? "default" : "default";
922
+ const clientOpts = mapToClientOptions(options);
923
+ this.#sessionPromise = connect(urlOrSession, clientOpts);
924
+ this.#state = "connecting";
925
+ this.#ready = this.#sessionPromise.then((s) => {
926
+ this.#session = s;
927
+ if (this.#state !== "draining")
928
+ this.#state = "connected";
929
+ }, (err) => {
930
+ this.#state = "failed";
931
+ throw err;
932
+ });
933
+ this.#closed = this.#sessionPromise.then((s) => s.closed.then((info) => {
934
+ this.#state = "closed";
935
+ return toCloseInfo(info);
936
+ }), () => {
937
+ // Connect failed: closed never rejects (PARITY_MATRIX).
938
+ this.#state = "closed";
939
+ return toCloseInfo({ code: 0, reason: "" });
940
+ });
941
+ }
942
+ else {
943
+ this.#datagramsReadableType = "default";
944
+ this.#congestionControl = "default";
945
+ const s = urlOrSession;
946
+ this.#sessionPromise = Promise.resolve(s);
947
+ this.#session = s;
948
+ this.#state = "connected";
949
+ this.#ready = s.ready;
950
+ this.#closed = s.closed.then((info) => {
951
+ this.#state = "closed";
952
+ return toCloseInfo(info);
953
+ });
954
+ }
955
+ // draining: spec says it resolves when close() is called and closing process has started.
956
+ this.#draining = new Promise((r) => {
957
+ this.#drainingResolve = r;
958
+ });
959
+ }
960
+ /** Resolves when handshake completes. Rejects with WebTransportError on connect failure. */
961
+ get ready() {
962
+ return this.#ready;
963
+ }
964
+ /** Resolves with close info when session closes. Never rejects. */
965
+ get closed() {
966
+ return this.#closed;
967
+ }
968
+ /** Resolves when close() has been called and closing process has started. */
969
+ get draining() {
970
+ return this.#draining;
971
+ }
972
+ /** Effective congestion control mode applied by this runtime. */
973
+ get congestionControl() {
974
+ return this.#congestionControl;
975
+ }
976
+ /** Create a send group used by sendOrder/sendGroup options. */
977
+ createSendGroup() {
978
+ return new WebTransportSendGroup(this, this.#nextSendGroupId++);
979
+ }
980
+ /** Datagram duplex stream (W3C WebTransportDatagramDuplexStream). Throws E_SESSION_CLOSED after close. */
981
+ get datagrams() {
982
+ if (!this.#datagramsCache) {
983
+ this.#datagramsCache = createDatagramStreams(this, this.#datagramsReadableType);
984
+ }
985
+ return this.#datagramsCache;
986
+ }
987
+ /** Incoming bidirectional streams as ReadableStream of { readable, writable }. */
988
+ get incomingBidirectionalStreams() {
989
+ if (!this.#incomingBidiCache) {
990
+ this.#incomingBidiCache = createIncomingBidiStreams(this);
991
+ }
992
+ return this.#incomingBidiCache;
993
+ }
994
+ /** Incoming unidirectional streams as ReadableStream of ReadableStream. */
995
+ get incomingUnidirectionalStreams() {
996
+ if (!this.#incomingUniCache) {
997
+ this.#incomingUniCache = createIncomingUniStreams(this);
998
+ }
999
+ return this.#incomingUniCache;
1000
+ }
1001
+ /**
1002
+ * Create a bidirectional stream (Web Streams).
1003
+ * @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
1004
+ */
1005
+ async createBidirectionalStream(options) {
1006
+ const policy = this._resolveSendPolicy(options);
1007
+ if (this.#state === "draining" ||
1008
+ this.#state === "closed" ||
1009
+ this.#state === "failed") {
1010
+ throw new WebTransportError(E_SESSION_CLOSED);
1011
+ }
1012
+ const s = await this.#sessionPromise;
1013
+ const duplex = await s.createBidirectionalStream();
1014
+ return nodeDuplexToWebBidi(duplex, this.#sendScheduler, policy, (bytes) => {
1015
+ this.#connStats.bytesSent += bytes;
1016
+ this._recordSendGroupBytes(policy.groupId, bytes);
1017
+ }, (bytes) => {
1018
+ this.#connStats.bytesReceived += bytes;
1019
+ });
1020
+ }
1021
+ /**
1022
+ * Create a unidirectional send stream (WritableStream).
1023
+ * @throws WebTransportError E_SESSION_CLOSED if session is closed/draining/failed.
1024
+ */
1025
+ async createUnidirectionalStream(options) {
1026
+ const policy = this._resolveSendPolicy(options);
1027
+ if (this.#state === "draining" ||
1028
+ this.#state === "closed" ||
1029
+ this.#state === "failed") {
1030
+ throw new WebTransportError(E_SESSION_CLOSED);
1031
+ }
1032
+ const s = await this.#sessionPromise;
1033
+ const writable = await s.createUnidirectionalStream();
1034
+ return nodeWritableToWebWritable(writable, this.#sendScheduler, policy, (bytes) => {
1035
+ this.#connStats.bytesSent += bytes;
1036
+ this._recordSendGroupBytes(policy.groupId, bytes);
1037
+ });
1038
+ }
1039
+ /**
1040
+ * Get connection stats (W3C WebTransportConnectionStats).
1041
+ * Maps from session.metricsSnapshot(). Native exposes limited fields; unavailable stats are omitted.
1042
+ * @throws DOMException InvalidStateError if state is "failed"
1043
+ */
1044
+ async getStats() {
1045
+ if (this.#state === "failed") {
1046
+ throw new DOMException("Transport has failed", "InvalidStateError");
1047
+ }
1048
+ await this.#sessionPromise; // Ensure session resolved (throws if failed)
1049
+ return {
1050
+ datagrams: {
1051
+ droppedIncoming: 0,
1052
+ expiredIncoming: 0,
1053
+ expiredOutgoing: 0,
1054
+ lostOutgoing: 0,
1055
+ },
1056
+ bytesSent: this.#connStats.bytesSent,
1057
+ bytesReceived: this.#connStats.bytesReceived,
1058
+ packetsSent: this.#connStats.datagramsOut,
1059
+ packetsReceived: this.#connStats.datagramsIn,
1060
+ estimatedSendRate: null,
1061
+ };
1062
+ }
1063
+ /** Initiate graceful close. Idempotent after first call. */
1064
+ close(info) {
1065
+ this.#drainingResolve(); // Resolves draining as soon as close() is called
1066
+ if (this.#state === "connected" || this.#state === "connecting") {
1067
+ this.#state = "draining";
1068
+ }
1069
+ if (this.#session) {
1070
+ this.#session.close({
1071
+ code: info?.closeCode,
1072
+ reason: info?.reason,
1073
+ });
1074
+ }
1075
+ else {
1076
+ // Still connecting: absorb eventual connect failure to prevent unhandled rejection (S4).
1077
+ this.#ready.catch(() => { });
1078
+ }
1079
+ }
1080
+ /** Internal: session for adapters (not part of spec) */
1081
+ async _getSession() {
1082
+ return this.#sessionPromise;
1083
+ }
1084
+ /** Internal: state for createWritable guard (not part of spec) */
1085
+ _getState() {
1086
+ return this.#state;
1087
+ }
1088
+ _resolveSendPolicy(options) {
1089
+ const sendOrder = options?.sendOrder ?? 0;
1090
+ if (!Number.isInteger(sendOrder)) {
1091
+ throw new TypeError("sendOrder must be an integer");
1092
+ }
1093
+ let groupId = 0;
1094
+ if (options?.sendGroup != null) {
1095
+ if (!(options.sendGroup instanceof WebTransportSendGroup)) {
1096
+ throw new DOMException("sendGroup belongs to another transport", "InvalidStateError");
1097
+ }
1098
+ if (options.sendGroup._getTransport() !== this) {
1099
+ throw new DOMException("sendGroup belongs to another transport", "InvalidStateError");
1100
+ }
1101
+ groupId = options.sendGroup._getId();
1102
+ }
1103
+ return { groupId, sendOrder };
1104
+ }
1105
+ _recordSendGroupBytes(groupId, bytes) {
1106
+ this.#sendGroupBytesSent.set(groupId, (this.#sendGroupBytesSent.get(groupId) ?? 0) + bytes);
1107
+ }
1108
+ async _getSendGroupStats(groupId) {
1109
+ return {
1110
+ bytesSent: this.#sendGroupBytesSent.get(groupId) ?? 0,
1111
+ };
1112
+ }
1113
+ async _sendDatagramWithPolicy(chunk, policy) {
1114
+ await this.#sendScheduler.enqueue(policy, async () => {
1115
+ const s = await this.#sessionPromise;
1116
+ await s.sendDatagram(chunk);
1117
+ this.#connStats.bytesSent += chunk.byteLength;
1118
+ this.#connStats.datagramsOut += 1;
1119
+ this._recordSendGroupBytes(policy.groupId, chunk.byteLength);
1120
+ });
1121
+ }
1122
+ _recordIncomingDatagram(chunk) {
1123
+ this.#connStats.bytesReceived += chunk.byteLength;
1124
+ this.#connStats.datagramsIn += 1;
1125
+ }
1126
+ _recordIncomingStreamBytes(bytes) {
1127
+ this.#connStats.bytesReceived += bytes;
1128
+ }
1129
+ }
1130
+ function createDatagramWritable(wt, policy) {
1131
+ return new WritableStream({
1132
+ async write(chunk) {
1133
+ await wt._sendDatagramWithPolicy(chunk, policy);
1134
+ },
1135
+ });
1136
+ }
1137
+ function createDatagramStreams(wt, readableType) {
1138
+ let iter = null;
1139
+ const getNext = async () => {
1140
+ if (!iter) {
1141
+ const s = await wt._getSession();
1142
+ iter = s.incomingDatagrams()[Symbol.asyncIterator]();
1143
+ }
1144
+ return iter.next();
1145
+ };
1146
+ const pull = async (controller) => {
1147
+ const { done, value } = await getNext();
1148
+ if (done) {
1149
+ controller.close();
1150
+ return;
1151
+ }
1152
+ const chunk = new Uint8Array(value);
1153
+ wt._recordIncomingDatagram(chunk);
1154
+ const byteController = controller;
1155
+ if (readableType === "bytes" &&
1156
+ byteController.byobRequest &&
1157
+ byteController.byobRequest.view) {
1158
+ const view = byteController.byobRequest.view;
1159
+ if (view.byteLength < chunk.length) {
1160
+ throw new RangeError("BYOB buffer smaller than datagram size");
1161
+ }
1162
+ view.set(chunk.subarray(0, chunk.length));
1163
+ byteController.byobRequest.respond(chunk.length);
1164
+ return;
1165
+ }
1166
+ controller.enqueue(chunk);
1167
+ };
1168
+ const readable = readableType === "bytes"
1169
+ ? new ReadableStream({
1170
+ type: "bytes",
1171
+ pull,
1172
+ }, { highWaterMark: 0 })
1173
+ : new ReadableStream({ pull }, { highWaterMark: 0 });
1174
+ const writable = createDatagramWritable(wt, { groupId: 0, sendOrder: 0 });
1175
+ return {
1176
+ readable,
1177
+ writable,
1178
+ createWritable(options) {
1179
+ const state = wt._getState();
1180
+ if (state === "closed" || state === "failed") {
1181
+ throw new DOMException("Transport is closed or failed", "InvalidStateError");
1182
+ }
1183
+ return createDatagramWritable(wt, wt._resolveSendPolicy(options));
1184
+ },
1185
+ get maxDatagramSize() {
1186
+ return DEFAULT_LIMITS.maxDatagramSize;
1187
+ },
1188
+ };
1189
+ }
1190
+ function attachServerBidiControls(duplex, stream) {
1191
+ const withControls = stream;
1192
+ const reset = duplex[WT_RESET];
1193
+ if (typeof reset === "function") {
1194
+ withControls[WT_RESET] = (code) => reset.call(duplex, code);
1195
+ }
1196
+ const stopSending = duplex[WT_STOP_SENDING];
1197
+ if (typeof stopSending === "function") {
1198
+ withControls[WT_STOP_SENDING] = (code) => stopSending.call(duplex, code);
1199
+ }
1200
+ return withControls;
1201
+ }
1202
+ function attachServerRecvControls(readable, stream) {
1203
+ const withControls = stream;
1204
+ const stopSending = readable[WT_STOP_SENDING];
1205
+ if (typeof stopSending === "function") {
1206
+ withControls[WT_STOP_SENDING] = (code) => stopSending.call(readable, code);
1207
+ }
1208
+ return withControls;
1209
+ }
1210
+ function createServerIncomingBidiStreams(nativeHandle, isClosed) {
1211
+ return new ReadableStream({
1212
+ async start(controller) {
1213
+ while (!isClosed()) {
1214
+ try {
1215
+ const nativeStream = await nativeHandle.acceptBidiStream();
1216
+ if (!nativeStream)
1217
+ break;
1218
+ const duplex = new BidiStream({
1219
+ handleId: nativeStream?.id ?? 0,
1220
+ nativeHandle: nativeStream,
1221
+ });
1222
+ controller.enqueue(attachServerBidiControls(duplex, await nodeDuplexToWebBidi(duplex)));
1223
+ }
1224
+ catch {
1225
+ break;
1226
+ }
1227
+ }
1228
+ controller.close();
1229
+ },
1230
+ });
1231
+ }
1232
+ function createServerIncomingUniStreams(nativeHandle, isClosed) {
1233
+ return new ReadableStream({
1234
+ async start(controller) {
1235
+ while (!isClosed()) {
1236
+ try {
1237
+ const nativeStream = await nativeHandle.acceptUniStream();
1238
+ if (!nativeStream)
1239
+ break;
1240
+ const readable = new RecvStream({
1241
+ handleId: nativeStream?.id ?? 0,
1242
+ nativeHandle: nativeStream,
1243
+ });
1244
+ controller.enqueue(attachServerRecvControls(readable, nodeReadableToWebReadable(readable)));
1245
+ }
1246
+ catch {
1247
+ break;
1248
+ }
1249
+ }
1250
+ controller.close();
1251
+ },
1252
+ });
1253
+ }
1254
+ function createIncomingBidiStreams(wt) {
1255
+ return new ReadableStream({
1256
+ async start(controller) {
1257
+ const s = await wt._getSession();
1258
+ for await (const duplex of s.incomingBidirectionalStreams()) {
1259
+ controller.enqueue(await nodeDuplexToWebBidi(duplex, undefined, undefined, undefined, (bytes) => {
1260
+ wt._recordIncomingStreamBytes(bytes);
1261
+ }));
1262
+ }
1263
+ controller.close();
1264
+ },
1265
+ });
1266
+ }
1267
+ function createIncomingUniStreams(wt) {
1268
+ return new ReadableStream({
1269
+ async start(controller) {
1270
+ const s = await wt._getSession();
1271
+ for await (const readable of s.incomingUnidirectionalStreams()) {
1272
+ controller.enqueue(nodeReadableToWebReadable(readable, (bytes) => {
1273
+ wt._recordIncomingStreamBytes(bytes);
1274
+ }));
1275
+ }
1276
+ controller.close();
1277
+ },
1278
+ });
1279
+ }
1280
+ function nodeDuplexToWebBidi(duplex, scheduler, policy, onWriteBytes, onReadBytes) {
1281
+ const readable = nodeReadableToWebReadable(duplex, onReadBytes);
1282
+ const writable = nodeWritableToWebWritable(duplex, scheduler, policy, onWriteBytes);
1283
+ return Promise.resolve({ readable, writable });
1284
+ }
1285
+ /** Extract QUIC application error code from abort/cancel reason. */
1286
+ function extractStreamErrorCode(reason) {
1287
+ if (typeof reason === "number" && Number.isInteger(reason))
1288
+ return reason;
1289
+ const o = reason && typeof reason === "object"
1290
+ ? reason
1291
+ : null;
1292
+ if (o) {
1293
+ const c = (o.streamErrorCode ?? o.code);
1294
+ if (typeof c === "number" && Number.isInteger(c))
1295
+ return c;
1296
+ }
1297
+ return 0;
1298
+ }
1299
+ function nodeReadableToWebReadable(r, onReadBytes) {
1300
+ const stopSendable = r;
1301
+ return new ReadableStream({
1302
+ async start(controller) {
1303
+ for await (const chunk of r) {
1304
+ const bytes = chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
1305
+ if (onReadBytes)
1306
+ onReadBytes(bytes.byteLength);
1307
+ controller.enqueue(bytes);
1308
+ }
1309
+ controller.close();
1310
+ },
1311
+ cancel(reason) {
1312
+ const fn = stopSendable[WT_STOP_SENDING];
1313
+ if (typeof fn === "function")
1314
+ fn.call(r, extractStreamErrorCode(reason));
1315
+ },
1316
+ });
1317
+ }
1318
+ function nodeWritableToWebWritable(w, scheduler, policy, onWriteBytes) {
1319
+ const resettable = w;
1320
+ return new WritableStream({
1321
+ async write(chunk) {
1322
+ const run = () => new Promise((resolve, reject) => {
1323
+ w.write(Buffer.from(chunk), (err) => err ? reject(err) : resolve());
1324
+ });
1325
+ if (scheduler && policy) {
1326
+ await scheduler.enqueue(policy, run);
1327
+ }
1328
+ else {
1329
+ await run();
1330
+ }
1331
+ if (onWriteBytes)
1332
+ onWriteBytes(chunk.byteLength);
1333
+ },
1334
+ close() {
1335
+ return new Promise((resolve, reject) => {
1336
+ w.end((err) => err ? reject(err) : resolve());
1337
+ });
1338
+ },
1339
+ abort(reason) {
1340
+ const fn = resettable[WT_RESET];
1341
+ if (typeof fn === "function")
1342
+ fn.call(w, extractStreamErrorCode(reason));
1343
+ },
1344
+ });
1345
+ }
1346
+ /**
1347
+ * Wrap an existing {@link ClientSession} as a browser-style WebTransport.
1348
+ *
1349
+ * Use when you obtained a session via {@link connect} but want Web Streams and W3C-style API.
1350
+ *
1351
+ * @param session - Connected ClientSession from {@link connect}.
1352
+ * @returns WebTransport with same lifecycle; `ready` resolves immediately if session is connected.
1353
+ *
1354
+ * @example
1355
+ * ```ts
1356
+ * const session = await connect("https://127.0.0.1:4433", { tls: { insecureSkipVerify: true } });
1357
+ * const wt = toWebTransport(session);
1358
+ * await wt.ready;
1359
+ * const writer = wt.datagrams.writable.getWriter();
1360
+ * await writer.write(new Uint8Array([1, 2, 3]));
1361
+ * writer.releaseLock();
1362
+ * session.close();
1363
+ * ```
1364
+ */
1365
+ export function toWebTransport(session) {
1366
+ return new WebTransport(session);
1367
+ }