@lesomnus/grpc-dgram 0.0.1

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.
@@ -0,0 +1,876 @@
1
+ import { r as StatusError, s as toStatusError } from "./status-DZwMDWIn.mjs";
2
+ //#region src/limits.ts
3
+ let DropPolicy = /* @__PURE__ */ function(DropPolicy) {
4
+ DropPolicy[DropPolicy["Newest"] = 0] = "Newest";
5
+ DropPolicy[DropPolicy["Oldest"] = 1] = "Oldest";
6
+ return DropPolicy;
7
+ }({});
8
+ function resolveRxConfig(c = {}) {
9
+ return {
10
+ size: c.size !== void 0 && c.size > 0 ? c.size : 32,
11
+ policy: c.policy ?? 0
12
+ };
13
+ }
14
+ function resolveLimits(l = {}) {
15
+ const pos = (v, d) => v !== void 0 && v > 0 ? v : d;
16
+ return {
17
+ maxTombstones: pos(l.maxTombstones, 1024),
18
+ maxTombstoneBytes: pos(l.maxTombstoneBytes, 1 << 20),
19
+ maxDeadPeers: pos(l.maxDeadPeers, 4),
20
+ maxPendingResets: pos(l.maxPendingResets, 1024),
21
+ maxLiveCalls: pos(l.maxLiveCalls, 4096),
22
+ maxRepliesPerRTI: pos(l.maxRepliesPerRTI, 64)
23
+ };
24
+ }
25
+ //#endregion
26
+ //#region src/metadata.ts
27
+ const isBinaryKey = (key) => key.endsWith("-bin");
28
+ function metadataJoin(a, b) {
29
+ if (a === void 0) return b === void 0 ? void 0 : cloneMetadata(b);
30
+ const out = cloneMetadata(a);
31
+ if (b !== void 0) for (const [k, vs] of Object.entries(b)) {
32
+ const cur = out[k];
33
+ out[k] = cur === void 0 ? [...vs] : [...cur, ...vs];
34
+ }
35
+ return out;
36
+ }
37
+ function cloneMetadata(md) {
38
+ const out = {};
39
+ for (const [k, vs] of Object.entries(md)) out[k] = [...vs];
40
+ return out;
41
+ }
42
+ const B64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
43
+ const B64_VALUES = (() => {
44
+ const t = (/* @__PURE__ */ new Int8Array(128)).fill(-1);
45
+ for (let i = 0; i < 64; i++) t[B64_CHARS.charCodeAt(i)] = i;
46
+ return t;
47
+ })();
48
+ function encodeBase64(bytes) {
49
+ const out = [];
50
+ let i = 0;
51
+ for (; i + 2 < bytes.length; i += 3) {
52
+ const n = bytes[i] << 16 | bytes[i + 1] << 8 | bytes[i + 2];
53
+ out.push(B64_CHARS[n >>> 18 & 63] + B64_CHARS[n >>> 12 & 63] + B64_CHARS[n >>> 6 & 63] + B64_CHARS[n & 63]);
54
+ }
55
+ const rem = bytes.length - i;
56
+ if (rem === 1) {
57
+ const n = bytes[i] << 16;
58
+ out.push(`${B64_CHARS[n >>> 18 & 63]}${B64_CHARS[n >>> 12 & 63]}==`);
59
+ } else if (rem === 2) {
60
+ const n = bytes[i] << 16 | bytes[i + 1] << 8;
61
+ out.push(`${B64_CHARS[n >>> 18 & 63]}${B64_CHARS[n >>> 12 & 63]}${B64_CHARS[n >>> 6 & 63]}=`);
62
+ }
63
+ return out.join("");
64
+ }
65
+ function decodeBase64(s) {
66
+ let end = s.length;
67
+ while (end > 0 && s.charCodeAt(end - 1) === 61) end--;
68
+ const pad = s.length - end;
69
+ if (pad > 2 || pad > 0 && s.length % 4 !== 0) throw new Error("drpc: invalid base64: bad padding");
70
+ const rem = end & 3;
71
+ if (rem === 1) throw new Error("drpc: invalid base64: truncated group");
72
+ const full = end >>> 2;
73
+ const out = new Uint8Array(full * 3 + (rem === 0 ? 0 : rem - 1));
74
+ let o = 0;
75
+ let i = 0;
76
+ const six = (p) => {
77
+ const c = s.charCodeAt(p);
78
+ const v = c < 128 ? B64_VALUES[c] : -1;
79
+ if (v < 0) throw new Error(`drpc: invalid base64: illegal character ${JSON.stringify(s[p] ?? "")}`);
80
+ return v;
81
+ };
82
+ for (let g = 0; g < full; g++, i += 4) {
83
+ const n = six(i) << 18 | six(i + 1) << 12 | six(i + 2) << 6 | six(i + 3);
84
+ out[o++] = n >>> 16 & 255;
85
+ out[o++] = n >>> 8 & 255;
86
+ out[o++] = n & 255;
87
+ }
88
+ if (rem === 2) out[o++] = (six(i) << 2 | six(i + 1) >>> 4) & 255;
89
+ else if (rem === 3) {
90
+ const n = six(i) << 12 | six(i + 1) << 6 | six(i + 2);
91
+ out[o++] = n >>> 10 & 255;
92
+ out[o++] = n >>> 2 & 255;
93
+ }
94
+ return out;
95
+ }
96
+ const textEncoder$1 = new TextEncoder();
97
+ const textDecoder$1 = new TextDecoder();
98
+ function encodeMetadataValue(key, value) {
99
+ if (!isBinaryKey(key)) return textEncoder$1.encode(value);
100
+ try {
101
+ return decodeBase64(value);
102
+ } catch (err) {
103
+ throw new StatusError(13, binaryValueMsg(key, err));
104
+ }
105
+ }
106
+ function decodeMetadataValue(key, bytes) {
107
+ return isBinaryKey(key) ? encodeBase64(bytes) : textDecoder$1.decode(bytes);
108
+ }
109
+ function validateMetadata(md) {
110
+ if (md === void 0) return;
111
+ for (const [k, vs] of Object.entries(md)) validateMetadataPair(k, vs);
112
+ }
113
+ function validateMetadataPair(key, values) {
114
+ if (key === "") throw new StatusError(13, "there is an empty key in the header");
115
+ for (let i = 0; i < key.length; i++) {
116
+ const c = key.charCodeAt(i);
117
+ if (!(c >= 97 && c <= 122 || c >= 48 && c <= 57 || c === 46 || c === 45 || c === 95)) throw new StatusError(13, `header key ${JSON.stringify(key)} contains illegal characters not in [0-9a-z-_.]`);
118
+ }
119
+ if (isBinaryKey(key)) {
120
+ for (const v of values) try {
121
+ decodeBase64(v);
122
+ } catch (err) {
123
+ throw new StatusError(13, binaryValueMsg(key, err));
124
+ }
125
+ return;
126
+ }
127
+ for (const v of values) for (let i = 0; i < v.length; i++) {
128
+ const c = v.charCodeAt(i);
129
+ if (c < 32 || c > 126) throw new StatusError(13, `header key ${JSON.stringify(key)} contains value with non-printable ASCII characters`);
130
+ }
131
+ }
132
+ function binaryValueMsg(key, err) {
133
+ const why = err instanceof Error ? err.message : String(err);
134
+ return `header key ${JSON.stringify(key)} carries a binary value that is not base64 (${why})`;
135
+ }
136
+ //#endregion
137
+ //#region src/seam.ts
138
+ function hasTransportInfo(tx) {
139
+ return typeof tx.reliable === "function";
140
+ }
141
+ function hasConnAttacher(tx) {
142
+ return typeof tx.attachConn === "function";
143
+ }
144
+ async function unpack(frames, h, ctx) {
145
+ for (const f of frames) try {
146
+ await h.handle(f, ctx);
147
+ } catch {}
148
+ }
149
+ //#endregion
150
+ //#region src/util.ts
151
+ const noop = () => {};
152
+ function nowMs() {
153
+ return Date.now();
154
+ }
155
+ function nonzeroEpoch() {
156
+ const buf = /* @__PURE__ */ new Uint32Array(1);
157
+ for (;;) {
158
+ globalThis.crypto.getRandomValues(buf);
159
+ if (buf[0] !== 0) return buf[0];
160
+ }
161
+ }
162
+ function unrefTimer(t) {
163
+ t.unref?.();
164
+ }
165
+ var Latch = class {
166
+ tripped = false;
167
+ promise;
168
+ resolve;
169
+ constructor() {
170
+ this.promise = new Promise((res) => {
171
+ this.resolve = res;
172
+ });
173
+ }
174
+ trip() {
175
+ if (this.tripped) return;
176
+ this.tripped = true;
177
+ this.resolve();
178
+ }
179
+ wait() {
180
+ return this.promise;
181
+ }
182
+ };
183
+ function abortListener(signal, fn) {
184
+ signal.addEventListener("abort", fn, { once: true });
185
+ return () => signal.removeEventListener("abort", fn);
186
+ }
187
+ var FrameQueue = class {
188
+ cap;
189
+ dropped = 0;
190
+ buf = [];
191
+ readWaiters = [];
192
+ spaceWaiters = [];
193
+ putTail = Promise.resolve();
194
+ constructor(cap) {
195
+ this.cap = cap;
196
+ }
197
+ get size() {
198
+ return this.buf.length;
199
+ }
200
+ tryTake() {
201
+ const f = this.buf.shift();
202
+ if (f !== void 0) wake(this.spaceWaiters);
203
+ return f;
204
+ }
205
+ tryPut(f) {
206
+ if (this.buf.length >= this.cap) return false;
207
+ this.buf.push(f);
208
+ wake(this.readWaiters);
209
+ return true;
210
+ }
211
+ putDrop(f, policy) {
212
+ if (this.tryPut(f)) return;
213
+ if (policy === 1) {
214
+ if (this.buf.shift() !== void 0) this.dropped++;
215
+ if (this.tryPut(f)) return;
216
+ }
217
+ this.dropped++;
218
+ }
219
+ async putBlocking(f, done, signal) {
220
+ const prev = this.putTail;
221
+ let release = noop;
222
+ this.putTail = new Promise((r) => {
223
+ release = r;
224
+ });
225
+ try {
226
+ await prev;
227
+ for (;;) {
228
+ if (this.tryPut(f)) return true;
229
+ if (done.tripped) return true;
230
+ if (signal?.aborted) return false;
231
+ let dispose = noop;
232
+ const waits = [this.space(), done.wait()];
233
+ if (signal !== void 0) waits.push(new Promise((res) => {
234
+ dispose = abortListener(signal, res);
235
+ }));
236
+ try {
237
+ await Promise.race(waits);
238
+ } finally {
239
+ dispose();
240
+ }
241
+ }
242
+ } finally {
243
+ release();
244
+ }
245
+ }
246
+ readable() {
247
+ if (this.buf.length > 0) return Promise.resolve();
248
+ return new Promise((res) => this.readWaiters.push(res));
249
+ }
250
+ space() {
251
+ return new Promise((res) => this.spaceWaiters.push(res));
252
+ }
253
+ };
254
+ function wake(waiters) {
255
+ if (waiters.length === 0) return;
256
+ const ws = waiters.splice(0);
257
+ for (const w of ws) w();
258
+ }
259
+ var Sweeper = class {
260
+ timer;
261
+ stopped = false;
262
+ kick(intervalMs, sweep, hasWork) {
263
+ if (this.stopped || this.timer !== void 0) return;
264
+ const t = setInterval(() => {
265
+ sweep();
266
+ if (this.timer === t && !hasWork()) {
267
+ clearInterval(t);
268
+ this.timer = void 0;
269
+ }
270
+ }, intervalMs);
271
+ unrefTimer(t);
272
+ this.timer = t;
273
+ }
274
+ stop() {
275
+ this.stopped = true;
276
+ if (this.timer !== void 0) {
277
+ clearInterval(this.timer);
278
+ this.timer = void 0;
279
+ }
280
+ }
281
+ };
282
+ const W_INIT = 32;
283
+ const DEFAULT_STALL_MS = 3e4;
284
+ function reliableRxSize(size, reliable) {
285
+ return reliable && size < 32 ? 32 : size;
286
+ }
287
+ var FlowSender = class {
288
+ on = false;
289
+ observed = false;
290
+ granted = 0;
291
+ sent = 0;
292
+ waiters = [];
293
+ assume(window) {
294
+ if (window <= 0 || this.observed || this.on) return;
295
+ this.on = true;
296
+ this.granted = window;
297
+ }
298
+ observe(window) {
299
+ if (this.observed) return;
300
+ this.observed = true;
301
+ if (window <= 0) this.on = false;
302
+ else {
303
+ this.on = true;
304
+ this.granted = window;
305
+ }
306
+ wake(this.waiters);
307
+ }
308
+ grant(n) {
309
+ if (n <= 0 || !this.on) return;
310
+ this.granted = Math.min(this.granted + n, Number.MAX_SAFE_INTEGER);
311
+ wake(this.waiters);
312
+ }
313
+ undo() {
314
+ if (this.sent > 0) this.sent--;
315
+ wake(this.waiters);
316
+ }
317
+ release() {
318
+ this.on = false;
319
+ wake(this.waiters);
320
+ }
321
+ tryAcquire() {
322
+ if (this.on && this.sent >= this.granted) return false;
323
+ this.sent++;
324
+ return true;
325
+ }
326
+ async acquire(done, stallMs, signal) {
327
+ let timer;
328
+ let dispose = noop;
329
+ let expired = false;
330
+ let bounds;
331
+ try {
332
+ for (;;) {
333
+ if (this.tryAcquire()) return "ok";
334
+ if (done.tripped) return "ended";
335
+ if (signal?.aborted) return "aborted";
336
+ if (expired) return "stalled";
337
+ if (bounds === void 0) {
338
+ bounds = [done.wait()];
339
+ if (stallMs > 0) bounds.push(new Promise((res) => {
340
+ const t = setTimeout(() => {
341
+ expired = true;
342
+ res();
343
+ }, stallMs);
344
+ unrefTimer(t);
345
+ timer = t;
346
+ }));
347
+ if (signal !== void 0) bounds.push(new Promise((res) => {
348
+ dispose = abortListener(signal, res);
349
+ }));
350
+ }
351
+ await Promise.race([this.parked(), ...bounds]);
352
+ }
353
+ } finally {
354
+ if (timer !== void 0) clearTimeout(timer);
355
+ dispose();
356
+ }
357
+ }
358
+ parked() {
359
+ return new Promise((res) => this.waiters.push(res));
360
+ }
361
+ };
362
+ var FlowReceiver = class {
363
+ on = false;
364
+ window = 0;
365
+ pending = 0;
366
+ enable(window) {
367
+ this.on = window > 0;
368
+ this.window = window;
369
+ }
370
+ get active() {
371
+ return this.on;
372
+ }
373
+ consumed(n) {
374
+ if (!this.on || n <= 0) return 0;
375
+ this.pending += n;
376
+ if (this.pending * 2 < this.window) return 0;
377
+ const grant = this.pending;
378
+ this.pending = 0;
379
+ return grant;
380
+ }
381
+ };
382
+ const DEFAULT_MAX_RECV_MSG_SIZE = 4 * 1024 * 1024;
383
+ const DEFAULT_MAX_SEND_MSG_SIZE = 2147483647;
384
+ function sizeOr(v, def) {
385
+ return v === void 0 ? def : v;
386
+ }
387
+ function checkSendSize(n, limit) {
388
+ if (n > limit) throw new StatusError(8, `drpc: trying to send message larger than max (${n} vs. ${limit})`);
389
+ }
390
+ function checkRecvSize(n, limit) {
391
+ if (n > limit) throw new StatusError(8, `drpc: received message larger than max (${n} vs. ${limit})`);
392
+ }
393
+ const rawPayload = (bytes) => ({
394
+ bytes,
395
+ compressed: false
396
+ });
397
+ const FORMATS = {
398
+ gzip: "gzip",
399
+ deflate: "deflate"
400
+ };
401
+ const compressorCache = /* @__PURE__ */ new Map();
402
+ function getCompressor(name) {
403
+ if (name === "") return void 0;
404
+ const hit = compressorCache.get(name);
405
+ if (hit !== void 0 || compressorCache.has(name)) return hit;
406
+ const c = makeCompressor(name);
407
+ compressorCache.set(name, c);
408
+ return c;
409
+ }
410
+ function makeCompressor(name) {
411
+ const format = FORMATS[name];
412
+ if (format === void 0) return void 0;
413
+ if (typeof CompressionStream === "undefined" || typeof DecompressionStream === "undefined") return void 0;
414
+ try {
415
+ new CompressionStream(format);
416
+ new DecompressionStream(format);
417
+ } catch {
418
+ return;
419
+ }
420
+ return new StreamCompressor(format);
421
+ }
422
+ var StreamCompressor = class {
423
+ format;
424
+ constructor(format) {
425
+ this.format = format;
426
+ }
427
+ async compress(data) {
428
+ try {
429
+ return await runTransform(new CompressionStream(this.format), data, Number.MAX_SAFE_INTEGER);
430
+ } catch (err) {
431
+ if (err instanceof StatusError) throw err;
432
+ throw new StatusError(13, `drpc: compressor: ${errMsg(err)}`);
433
+ }
434
+ }
435
+ async decompress(data, maxRecv) {
436
+ const limit = maxRecv > 0 ? maxRecv : DEFAULT_MAX_RECV_MSG_SIZE;
437
+ try {
438
+ return await runTransform(new DecompressionStream(this.format), data, limit);
439
+ } catch (err) {
440
+ if (err instanceof StatusError) throw err;
441
+ throw new StatusError(13, `drpc: decompress: ${errMsg(err)}`);
442
+ }
443
+ }
444
+ };
445
+ async function runTransform(ts, data, limit) {
446
+ const writer = ts.writable.getWriter();
447
+ const reader = ts.readable.getReader();
448
+ let writeErr;
449
+ const written = (async () => {
450
+ await writer.write(data);
451
+ await writer.close();
452
+ })().catch((err) => {
453
+ writeErr = err;
454
+ });
455
+ const chunks = [];
456
+ let total = 0;
457
+ try {
458
+ for (;;) {
459
+ const { done, value } = await reader.read();
460
+ if (done) break;
461
+ if (value === void 0) continue;
462
+ total += value.length;
463
+ if (total > limit) throw new StatusError(8, `drpc: received message after decompression larger than max (> ${limit})`);
464
+ chunks.push(value);
465
+ }
466
+ } catch (err) {
467
+ reader.cancel().catch(noop);
468
+ throw err;
469
+ }
470
+ await written;
471
+ if (writeErr !== void 0) throw writeErr;
472
+ if (chunks.length === 1) return chunks[0];
473
+ const out = new Uint8Array(total);
474
+ let at = 0;
475
+ for (const c of chunks) {
476
+ out.set(c, at);
477
+ at += c.length;
478
+ }
479
+ return out;
480
+ }
481
+ async function compressPayload(comp, payload) {
482
+ if (payload.length === 0) return rawPayload(payload);
483
+ const out = await comp.compress(payload);
484
+ if (out.length >= payload.length) return rawPayload(payload);
485
+ return {
486
+ bytes: out,
487
+ compressed: true
488
+ };
489
+ }
490
+ async function decompressPayload(comp, payload, maxRecv) {
491
+ if (comp === void 0) throw new StatusError(13, "drpc: frame is compressed but the call has no compressor");
492
+ return comp.decompress(payload, maxRecv);
493
+ }
494
+ function errMsg(err) {
495
+ return err instanceof Error ? err.message : String(err);
496
+ }
497
+ //#endregion
498
+ //#region src/wire.ts
499
+ const FlagOpen = 1;
500
+ const FlagClose = 2;
501
+ const FlagReset = 4;
502
+ const FlagPing = 8;
503
+ const FlagWindow = 16;
504
+ const FlagCompressed = 32;
505
+ const SHAPE_MASK = 31;
506
+ function frame(init) {
507
+ return {
508
+ epoch: 0,
509
+ sid: 0,
510
+ seq: 0,
511
+ flags: 0,
512
+ method: "",
513
+ codec: "",
514
+ desc: "",
515
+ peerEpoch: 0,
516
+ window: 0,
517
+ compressor: "",
518
+ ...init
519
+ };
520
+ }
521
+ const isOpen = (f) => (f.flags & 1) !== 0;
522
+ const isClose = (f) => (f.flags & 2) !== 0;
523
+ const isReset = (f) => (f.flags & 4) !== 0;
524
+ const isPing = (f) => (f.flags & 8) !== 0;
525
+ const isWindow = (f) => (f.flags & 16) !== 0;
526
+ const isCompressed = (f) => (f.flags & 32) !== 0;
527
+ const shapeOf = (f) => f.flags & 31;
528
+ const hasUnknownFlags = (f) => (f.flags & -64) !== 0;
529
+ function legalShape(shape) {
530
+ switch (shape) {
531
+ case 0:
532
+ case 1:
533
+ case 2:
534
+ case 3:
535
+ case 4:
536
+ case 8:
537
+ case 16: return true;
538
+ default: return false;
539
+ }
540
+ }
541
+ const isTerminal = (f) => shapeOf(f) === 2 && f.code !== void 0;
542
+ const isHalfClose = (f) => shapeOf(f) === 2 && f.code === void 0;
543
+ const isData = (f) => shapeOf(f) === 0 && f.payload !== void 0;
544
+ const isHeaderFrame = (f) => shapeOf(f) === 0 && f.payload === void 0;
545
+ function frameStatus(f) {
546
+ return new StatusError(f.code ?? 0, f.desc);
547
+ }
548
+ function setFrameError(f, err) {
549
+ const st = toStatusError(err);
550
+ f.code = st.code;
551
+ f.desc = st.desc;
552
+ }
553
+ function resetFor(f) {
554
+ return frame({
555
+ flags: 4,
556
+ epoch: f.epoch,
557
+ sid: f.sid,
558
+ peerEpoch: f.peerEpoch
559
+ });
560
+ }
561
+ const textEncoder = new TextEncoder();
562
+ const textDecoder = new TextDecoder();
563
+ var Writer = class {
564
+ buf = [];
565
+ byte(b) {
566
+ this.buf.push(b & 255);
567
+ }
568
+ varint(v) {
569
+ let n = v >>> 0;
570
+ while (n > 127) {
571
+ this.buf.push(n & 127 | 128);
572
+ n >>>= 7;
573
+ }
574
+ this.buf.push(n);
575
+ }
576
+ varint64(v) {
577
+ let n = BigInt.asUintN(64, v);
578
+ while (n > 127n) {
579
+ this.buf.push(Number(n & 127n) | 128);
580
+ n >>= 7n;
581
+ }
582
+ this.buf.push(Number(n));
583
+ }
584
+ tag(field, wire) {
585
+ this.varint(field << 3 | wire);
586
+ }
587
+ fixed32(field, v) {
588
+ this.tag(field, 5);
589
+ const n = v >>> 0;
590
+ this.buf.push(n & 255, n >>> 8 & 255, n >>> 16 & 255, n >>> 24 & 255);
591
+ }
592
+ bytes(field, v) {
593
+ this.tag(field, 2);
594
+ this.varint(v.length);
595
+ for (let i = 0; i < v.length; i++) this.buf.push(v[i]);
596
+ }
597
+ string(field, v) {
598
+ this.bytes(field, textEncoder.encode(v));
599
+ }
600
+ finish() {
601
+ return Uint8Array.from(this.buf);
602
+ }
603
+ };
604
+ var Reader = class {
605
+ buf;
606
+ pos = 0;
607
+ constructor(buf) {
608
+ this.buf = buf;
609
+ }
610
+ get eof() {
611
+ return this.pos >= this.buf.length;
612
+ }
613
+ next() {
614
+ if (this.pos >= this.buf.length) throw new Error("drpc: malformed frame: truncated");
615
+ return this.buf[this.pos++];
616
+ }
617
+ varint() {
618
+ let out = 0n;
619
+ for (let shift = 0n; shift < 70n; shift += 7n) {
620
+ const b = this.next();
621
+ out |= BigInt(b & 127) << shift;
622
+ if ((b & 128) === 0) return BigInt.asUintN(64, out);
623
+ }
624
+ throw new Error("drpc: malformed frame: varint too long");
625
+ }
626
+ varint32() {
627
+ return Number(this.varint() & 4294967295n);
628
+ }
629
+ fixed32() {
630
+ if (this.pos + 4 > this.buf.length) throw new Error("drpc: malformed frame: truncated");
631
+ const b = this.buf;
632
+ const p = this.pos;
633
+ this.pos += 4;
634
+ return (b[p] | b[p + 1] << 8 | b[p + 2] << 16 | b[p + 3] << 24) >>> 0;
635
+ }
636
+ bytes() {
637
+ const n = this.varint32();
638
+ if (this.pos + n > this.buf.length) throw new Error("drpc: malformed frame: truncated");
639
+ const out = this.buf.subarray(this.pos, this.pos + n);
640
+ this.pos += n;
641
+ return out;
642
+ }
643
+ string() {
644
+ return textDecoder.decode(this.bytes());
645
+ }
646
+ skip(wire) {
647
+ switch (wire) {
648
+ case 0:
649
+ this.varint();
650
+ return;
651
+ case 1:
652
+ if (this.pos + 8 > this.buf.length) throw new Error("drpc: malformed frame: truncated");
653
+ this.pos += 8;
654
+ return;
655
+ case 2:
656
+ this.bytes();
657
+ return;
658
+ case 5:
659
+ this.fixed32();
660
+ return;
661
+ default: throw new Error(`drpc: malformed frame: unsupported wire type ${wire}`);
662
+ }
663
+ }
664
+ };
665
+ function encodeDuration(ms) {
666
+ const w = new Writer();
667
+ const totalNs = BigInt(Math.round(ms * 1e6));
668
+ const seconds = totalNs / 1000000000n;
669
+ const nanos = totalNs % 1000000000n;
670
+ if (seconds !== 0n) {
671
+ w.tag(1, 0);
672
+ w.varint64(seconds);
673
+ }
674
+ if (nanos !== 0n) {
675
+ w.tag(2, 0);
676
+ w.varint64(nanos);
677
+ }
678
+ return w.finish();
679
+ }
680
+ function decodeDuration(data) {
681
+ const r = new Reader(data);
682
+ let seconds = 0n;
683
+ let nanos = 0n;
684
+ while (!r.eof) {
685
+ const tag = r.varint32();
686
+ const field = tag >>> 3;
687
+ const wire = tag & 7;
688
+ if (field === 1 && wire === 0) seconds = BigInt.asIntN(64, r.varint());
689
+ else if (field === 2 && wire === 0) nanos = BigInt.asIntN(32, r.varint());
690
+ else r.skip(wire);
691
+ }
692
+ return Number(seconds) * 1e3 + Number(nanos) / 1e6;
693
+ }
694
+ function encodeAny(a) {
695
+ const w = new Writer();
696
+ if (a.typeUrl !== "") w.string(1, a.typeUrl);
697
+ if (a.value.length > 0) w.bytes(2, a.value);
698
+ return w.finish();
699
+ }
700
+ function decodeAny(data) {
701
+ const r = new Reader(data);
702
+ const a = {
703
+ typeUrl: "",
704
+ value: /* @__PURE__ */ new Uint8Array(0)
705
+ };
706
+ while (!r.eof) {
707
+ const tag = r.varint32();
708
+ const field = tag >>> 3;
709
+ const wire = tag & 7;
710
+ if (field === 1 && wire === 2) a.typeUrl = r.string();
711
+ else if (field === 2 && wire === 2) a.value = r.bytes().slice();
712
+ else r.skip(wire);
713
+ }
714
+ return a;
715
+ }
716
+ function encodeMetadata(md) {
717
+ const w = new Writer();
718
+ for (const key of Object.keys(md).sort()) {
719
+ const entry = new Writer();
720
+ for (const v of md[key]) entry.bytes(1, encodeMetadataValue(key, v));
721
+ const kv = new Writer();
722
+ kv.string(1, key);
723
+ kv.bytes(2, entry.finish());
724
+ w.bytes(1, kv.finish());
725
+ }
726
+ return w.finish();
727
+ }
728
+ function decodeMetadata(data) {
729
+ const md = {};
730
+ const r = new Reader(data);
731
+ while (!r.eof) {
732
+ const tag = r.varint32();
733
+ if (tag >>> 3 === 1 && (tag & 7) === 2) {
734
+ const kv = new Reader(r.bytes());
735
+ let key = "";
736
+ const raw = [];
737
+ while (!kv.eof) {
738
+ const t = kv.varint32();
739
+ if (t >>> 3 === 1 && (t & 7) === 2) key = kv.string();
740
+ else if (t >>> 3 === 2 && (t & 7) === 2) {
741
+ const entry = new Reader(kv.bytes());
742
+ while (!entry.eof) {
743
+ const et = entry.varint32();
744
+ if (et >>> 3 === 1 && (et & 7) === 2) raw.push(entry.bytes());
745
+ else entry.skip(et & 7);
746
+ }
747
+ } else kv.skip(t & 7);
748
+ }
749
+ md[key] = raw.map((b) => decodeMetadataValue(key, b));
750
+ } else r.skip(tag & 7);
751
+ }
752
+ return md;
753
+ }
754
+ function encodeFrame(f) {
755
+ const w = new Writer();
756
+ if (f.epoch !== 0) w.fixed32(1, f.epoch);
757
+ if (f.sid !== 0) w.fixed32(2, f.sid);
758
+ if (f.seq !== 0) w.fixed32(3, f.seq);
759
+ if (f.flags !== 0) {
760
+ w.tag(4, 0);
761
+ w.varint(f.flags);
762
+ }
763
+ if (f.method !== "") w.string(5, f.method);
764
+ if (f.codec !== "") w.string(7, f.codec);
765
+ if (f.timeoutMs !== void 0) w.bytes(8, encodeDuration(f.timeoutMs));
766
+ if (f.payload !== void 0) w.bytes(9, f.payload);
767
+ if (f.code !== void 0) {
768
+ w.tag(10, 0);
769
+ w.varint(f.code);
770
+ }
771
+ if (f.desc !== "") w.string(11, f.desc);
772
+ if (f.header !== void 0) w.bytes(12, encodeMetadata(f.header));
773
+ if (f.trailer !== void 0) w.bytes(13, encodeMetadata(f.trailer));
774
+ if (f.peerEpoch !== 0) w.fixed32(14, f.peerEpoch);
775
+ if (f.window) {
776
+ w.tag(15, 0);
777
+ w.varint(f.window);
778
+ }
779
+ if (f.compressor) w.string(16, f.compressor);
780
+ if (f.details !== void 0) for (const d of f.details) w.bytes(17, encodeAny(d));
781
+ return w.finish();
782
+ }
783
+ function decodeFrame(data) {
784
+ const f = frame();
785
+ const r = new Reader(data);
786
+ while (!r.eof) {
787
+ const tag = r.varint32();
788
+ const field = tag >>> 3;
789
+ const wire = tag & 7;
790
+ switch (field) {
791
+ case 1:
792
+ if (wire !== 5) r.skip(wire);
793
+ else f.epoch = r.fixed32();
794
+ break;
795
+ case 2:
796
+ if (wire !== 5) r.skip(wire);
797
+ else f.sid = r.fixed32();
798
+ break;
799
+ case 3:
800
+ if (wire !== 5) r.skip(wire);
801
+ else f.seq = r.fixed32();
802
+ break;
803
+ case 4:
804
+ if (wire !== 0) r.skip(wire);
805
+ else f.flags = r.varint32();
806
+ break;
807
+ case 5:
808
+ if (wire !== 2) r.skip(wire);
809
+ else f.method = r.string();
810
+ break;
811
+ case 7:
812
+ if (wire !== 2) r.skip(wire);
813
+ else f.codec = r.string();
814
+ break;
815
+ case 8:
816
+ if (wire !== 2) r.skip(wire);
817
+ else f.timeoutMs = decodeDuration(r.bytes());
818
+ break;
819
+ case 9:
820
+ if (wire !== 2) r.skip(wire);
821
+ else f.payload = r.bytes().slice();
822
+ break;
823
+ case 10:
824
+ if (wire !== 0) r.skip(wire);
825
+ else f.code = r.varint32();
826
+ break;
827
+ case 11:
828
+ if (wire !== 2) r.skip(wire);
829
+ else f.desc = r.string();
830
+ break;
831
+ case 12:
832
+ if (wire !== 2) r.skip(wire);
833
+ else f.header = decodeMetadata(r.bytes());
834
+ break;
835
+ case 13:
836
+ if (wire !== 2) r.skip(wire);
837
+ else f.trailer = decodeMetadata(r.bytes());
838
+ break;
839
+ case 14:
840
+ if (wire !== 5) r.skip(wire);
841
+ else f.peerEpoch = r.fixed32();
842
+ break;
843
+ case 15:
844
+ if (wire !== 0) r.skip(wire);
845
+ else f.window = r.varint32();
846
+ break;
847
+ case 16:
848
+ if (wire !== 2) r.skip(wire);
849
+ else f.compressor = r.string();
850
+ break;
851
+ case 17:
852
+ if (wire !== 2) r.skip(wire);
853
+ else (f.details ??= []).push(decodeAny(r.bytes()));
854
+ break;
855
+ default: r.skip(wire);
856
+ }
857
+ }
858
+ return f;
859
+ }
860
+ function encodeEnvelop(frames) {
861
+ const w = new Writer();
862
+ for (const f of frames) w.bytes(1, encodeFrame(f));
863
+ return w.finish();
864
+ }
865
+ function decodeEnvelop(data) {
866
+ const frames = [];
867
+ const r = new Reader(data);
868
+ while (!r.eof) {
869
+ const tag = r.varint32();
870
+ if (tag >>> 3 === 1 && (tag & 7) === 2) frames.push(decodeFrame(r.bytes()));
871
+ else r.skip(tag & 7);
872
+ }
873
+ return frames;
874
+ }
875
+ //#endregion
876
+ export { unpack as $, DEFAULT_MAX_SEND_MSG_SIZE as A, checkSendSize as B, isTerminal as C, setFrameError as D, resetFor as E, Latch as F, noop as G, decompressPayload as H, Sweeper as I, reliableRxSize as J, nowMs as K, W_INIT as L, FlowReceiver as M, FlowSender as N, shapeOf as O, FrameQueue as P, hasTransportInfo as Q, abortListener as R, isReset as S, legalShape as T, getCompressor as U, compressPayload as V, nonzeroEpoch as W, unrefTimer as X, sizeOr as Y, hasConnAttacher as Z, isData as _, FlagReset as a, validateMetadata as at, isOpen as b, decodeEnvelop as c, resolveLimits as ct, encodeFrame as d, cloneMetadata as et, frame as f, isCompressed as g, isClose as h, FlagPing as i, metadataJoin as it, DEFAULT_STALL_MS as j, DEFAULT_MAX_RECV_MSG_SIZE as k, decodeFrame as l, resolveRxConfig as lt, hasUnknownFlags as m, FlagCompressed as n, encodeBase64 as nt, FlagWindow as o, validateMetadataPair as ot, frameStatus as p, rawPayload as q, FlagOpen as r, isBinaryKey as rt, SHAPE_MASK as s, DropPolicy as st, FlagClose as t, decodeBase64 as tt, encodeEnvelop as u, isHalfClose as v, isWindow as w, isPing as x, isHeaderFrame as y, checkRecvSize as z };