grpc-dc 0.32.5 → 0.32.6

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/index.js CHANGED
@@ -26,6 +26,10 @@ export { createGrpcDcBridge, createGrpcDcServerBridge } from "./src/wasm_bridge.
26
26
  // modules (node:dgram via webrtc/js/direct.js) and this index
27
27
  // is also loaded in browsers. Import it directly:
28
28
  // import { directClientEndpoint } from "grpc-dc/webrtc_direct";
29
+ // The generated HTTP/2 client transport (src/http2.js, calls
30
+ // official gRPC servers directly) is Node-only for the same
31
+ // reason (node:http2). Import it directly:
32
+ // import { http2Channel } from "grpc-dc/http2";
29
33
 
30
34
  import { Channel } from "./src/channel.js";
31
35
  import { Endpoint } from "./src/endpoint.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grpc-dc",
3
- "version": "0.32.5",
3
+ "version": "0.32.6",
4
4
  "description": "gRPC in the browser over WebRTC DataChannels: dependency-free generated gRPC clients & servers for JavaScript — no grpc-web proxy, no external runtime",
5
5
  "keywords": [
6
6
  "grpc",
@@ -28,7 +28,8 @@
28
28
  "default": "./index.js"
29
29
  },
30
30
  "./wire_gen.js": "./wire_gen.js",
31
- "./webrtc_direct": "./src/webrtc_direct.js"
31
+ "./webrtc_direct": "./src/webrtc_direct.js",
32
+ "./http2": "./src/http2.js"
32
33
  },
33
34
  "bin": {
34
35
  "protoc-gen-grpc-dc-js": "plugin/protoc-gen-grpc-dc-js.mjs",
@@ -488,6 +488,10 @@ function concatBytes(a, b) {
488
488
  return out;
489
489
  }
490
490
 
491
+ function putRaw(out, bytes) {
492
+ for (let i = 0; i < bytes.length; i++) out.push(bytes[i]);
493
+ }
494
+
491
495
  function putTag(out, num, wire) {
492
496
  out.push(...varintBytes((BigInt(num) << 3n) | BigInt(wire)));
493
497
  }
@@ -500,7 +504,8 @@ function putVarintField(out, num, value) {
500
504
 
501
505
  function putBytesField(out, num, payload) {
502
506
  putTag(out, num, 2);
503
- out.push(...varintBytes(payload.length), ...payload);
507
+ putRaw(out, varintBytes(payload.length));
508
+ putRaw(out, payload);
504
509
  }
505
510
 
506
511
  function putStringField(out, num, value) {
@@ -768,7 +773,7 @@ function pbMessageClass(model, msg) {
768
773
  const dec = msg.fields.map((f) => pbDecodeCase(model, f)).join('');
769
774
  return 'export class ' + name + ' {\n'
770
775
  + ' constructor({ ' + params + ' } = {}) {\n' + assigns + ' this.unknownFields = new Uint8Array(0);\n }\n'
771
- + ' static encode(msg) {\n const out = [];\n' + enc + ' out.push(...msg.unknownFields);\n return new Uint8Array(out);\n }\n'
776
+ + ' static encode(msg) {\n const out = [];\n' + enc + ' putRaw(out, msg.unknownFields);\n return new Uint8Array(out);\n }\n'
772
777
  + ' static decode(bytes) {\n const msg = new ' + name + '();\n'
773
778
  + ' const reader = new Reader(bytes);\n let f;\n'
774
779
  + ' while ((f = reader.field()) !== null) {\n const [num, wire, value, raw] = f;\n switch (num) {\n'
@@ -1433,7 +1438,11 @@ function gpMessage(model, msg) {
1433
1438
  + '\treturn out\n}\n\n'
1434
1439
  + 'func (m *' + name + ') UnmarshalDC(data []byte) error {\n'
1435
1440
  + '\tm.UnknownFields = nil\n'
1436
- + '\tr := &pbReader{buf: data}\n\tfor {\n\t\tnum, _, value, raw, done, err := r.field()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif done {\n\t\t\treturn nil\n\t\t}\n\t\tswitch num {\n'
1441
+ + '\tr := &pbReader{buf: data}\n\tfor {\n'
1442
+ + (msg.fields.length === 0
1443
+ ? '\t\tnum, _, _, raw, done, err := r.field()\n'
1444
+ : '\t\tnum, _, value, raw, done, err := r.field()\n')
1445
+ + '\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif done {\n\t\t\treturn nil\n\t\t}\n\t\tswitch num {\n'
1437
1446
  + msg.fields.map((f) => gpDecodeCase(model, f)).join('')
1438
1447
  + '\t\tdefault:\n\t\t\tm.UnknownFields = append(m.UnknownFields, raw...)\n'
1439
1448
  + '\t\t}\n\t}\n}\n\n';
@@ -1514,7 +1523,9 @@ function emitGoFile(model, params) {
1514
1523
  content: '// @generated by protoc-gen-grpc-dc-go. DO NOT EDIT.\n'
1515
1524
  + '// source: ' + model.name + '\n\n'
1516
1525
  + 'package ' + goPackage(model, params) + '\n\n'
1517
- + 'import (\n\t"context"\n\n\tgrpcdc "grpcdc"\n)\n\n'
1526
+ + (model.services.length === 0
1527
+ ? ''
1528
+ : 'import (\n\t"context"\n\n\tgrpcdc "grpcdc"\n)\n\n')
1518
1529
  + model.services.map(goService).join(''),
1519
1530
  };
1520
1531
  const pb = emitGoPbFile(model, params);
package/src/codec.js CHANGED
@@ -18,6 +18,10 @@ export class StatusError extends Error {
18
18
  super(`${StatusName[code] ?? `CODE_${code}`}: ${message}`);
19
19
  this.name = "StatusError";
20
20
  this.code = code;
21
+ // The raw status message for the wire: Error.message carries
22
+ // a "NAME: " display prefix that must not leak into status
23
+ // frames (peers would see it doubled).
24
+ this.statusMessage = message;
21
25
  }
22
26
  static ok() {
23
27
  return new StatusError(StatusCode.OK, "");
@@ -106,7 +110,7 @@ export function parseTimeout(text) {
106
110
  }
107
111
 
108
112
  export function statusFrame(frameType, streamId, status) {
109
- const body = JSON.stringify({ code: status.code, message: status.message ?? "" });
113
+ const body = JSON.stringify({ code: status.code, message: status.statusMessage ?? status.message ?? "" });
110
114
  return encodeFrame(frameType, streamId, textEncoder.encode(body));
111
115
  }
112
116
 
package/src/http2.js ADDED
@@ -0,0 +1,119 @@
1
+ // @generated by grpc-dc codegen. DO NOT EDIT.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // HTTP/2 client transport: call official gRPC servers directly.
4
+ //
5
+ // Http2DataChannel is a DataChannel-like adapter over a
6
+ // node:http2 client session: Endpoint/Channel above it speak
7
+ // grpc-dc frames; each frame is translated to HTTP/2 streams
8
+ // and back. The session layer (HPACK, flow control) is Node
9
+ // stdlib; TLS comes from node:http2 connect options (ALPN h2)
10
+ // — only the dial glue is generated. Node only: browsers keep
11
+ // using WebRTC DataChannels.
12
+
13
+ import http2 from "node:http2";
14
+ import { decodeFrame, encodeFrame, FrameType } from "./codec.js";
15
+ import { parseHeaders } from "./codec.js";
16
+ import { Channel } from "./channel.js";
17
+
18
+ export class Http2DataChannel {
19
+ #listeners = new Map();
20
+ #streams = new Map();
21
+ #buffers = new Map();
22
+
23
+ constructor(authority, { secure = false, ...connectOptions } = {}) {
24
+ this.readyState = "open";
25
+ this.bufferedAmount = 0;
26
+ const url = `${secure ? "https" : "http"}://${authority}`;
27
+ this.session = http2.connect(url, connectOptions);
28
+ this.session.on("error", () => {});
29
+ }
30
+
31
+ addEventListener(name, fn) {
32
+ if (!this.#listeners.has(name)) this.#listeners.set(name, []);
33
+ this.#listeners.get(name).push(fn);
34
+ }
35
+
36
+ #emit(bytes) {
37
+ const data = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
38
+ for (const fn of this.#listeners.get("message") ?? []) fn({ data });
39
+ }
40
+
41
+ #emitFrame(type, streamId, payloadText) {
42
+ this.#emit(encodeFrame(type, streamId, new TextEncoder().encode(payloadText)));
43
+ }
44
+
45
+ send(frameBytes) {
46
+ const frame = decodeFrame(frameBytes);
47
+ const id = frame.streamId;
48
+ if (frame.type === FrameType.HEADERS) {
49
+ const head = parseHeaders(frame.payload);
50
+ const metadata = {};
51
+ for (const [k, v] of Object.entries(head.metadata ?? {})) metadata[k.toLowerCase()] = v;
52
+ const stream = this.session.request({
53
+ ":path": head.path,
54
+ ":method": "POST",
55
+ "content-type": "application/grpc",
56
+ te: "trailers",
57
+ ...metadata,
58
+ });
59
+ this.#streams.set(id, stream);
60
+ this.#buffers.set(id, Buffer.alloc(0));
61
+ stream.on("response", (headers, flags) => {
62
+ const meta = {};
63
+ for (const [k, v] of Object.entries(headers)) {
64
+ if (!k.startsWith(":") && k !== "content-type") meta[k] = v;
65
+ }
66
+ const trailersOnly =
67
+ (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) !== 0 && headers["grpc-status"] !== undefined;
68
+ if (trailersOnly) {
69
+ this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
70
+ code: Number(headers["grpc-status"]),
71
+ message: decodeURIComponent(headers["grpc-message"] ?? ""),
72
+ }));
73
+ } else {
74
+ this.#emitFrame(FrameType.HEADERS, id, JSON.stringify({ metadata: meta }));
75
+ }
76
+ });
77
+ stream.on("trailers", (headers) => {
78
+ this.#emitFrame(FrameType.TRAILERS, id, JSON.stringify({
79
+ code: Number(headers["grpc-status"] ?? 2),
80
+ message: decodeURIComponent(headers["grpc-message"] ?? ""),
81
+ }));
82
+ });
83
+ stream.on("data", (chunk) => {
84
+ let buf = Buffer.concat([this.#buffers.get(id), chunk]);
85
+ while (buf.length >= 5) {
86
+ const len = buf.readUInt32BE(1);
87
+ if (buf.length < 5 + len) break;
88
+ this.#emit(encodeFrame(FrameType.DATA, id, new Uint8Array(buf.subarray(5, 5 + len))));
89
+ buf = buf.subarray(5 + len);
90
+ }
91
+ this.#buffers.set(id, buf);
92
+ });
93
+ stream.on("error", () => {
94
+ this.#emitFrame(FrameType.RST, id, JSON.stringify({ code: 8, message: "h2 stream error" }));
95
+ });
96
+ } else if (frame.type === FrameType.DATA) {
97
+ const stream = this.#streams.get(id);
98
+ if (stream) {
99
+ const lpm = Buffer.alloc(5 + frame.payload.length);
100
+ lpm.writeUInt32BE(frame.payload.length, 1);
101
+ Buffer.from(frame.payload).copy(lpm, 5);
102
+ stream.write(lpm);
103
+ }
104
+ } else if (frame.type === FrameType.HALF_CLOSE) {
105
+ this.#streams.get(id)?.end();
106
+ } else if (frame.type === FrameType.RST) {
107
+ this.#streams.get(id)?.close(http2.constants.NGHTTP2_CANCEL);
108
+ }
109
+ }
110
+
111
+ close() {
112
+ this.session.close();
113
+ }
114
+ }
115
+
116
+ /** Channel over HTTP/2 to an official gRPC server. */
117
+ export function http2Channel(authority, options) {
118
+ return new Channel(new Http2DataChannel(authority, options));
119
+ }