@xdcobra/react-native-grpc 1.1.0 → 2.0.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.
Files changed (114) hide show
  1. package/LICENSE.md +22 -22
  2. package/README.md +302 -284
  3. package/android/build.gradle +31 -127
  4. package/android/src/main/AndroidManifest.xml +3 -3
  5. package/android/src/main/java/com/reactnativegrpc/GrpcMarshaller.java +27 -27
  6. package/android/src/main/java/com/reactnativegrpc/GrpcModule.java +730 -730
  7. package/android/src/main/java/com/reactnativegrpc/GrpcPackage.java +27 -27
  8. package/android/src/main/java/com/reactnativegrpc/SpkiPinTrustManager.java +101 -101
  9. package/android/src/main/java/com/reactnativegrpc/TrustManagers.java +51 -51
  10. package/ios/Grpc.h +22 -22
  11. package/ios/Grpc.m +627 -625
  12. package/ios/SpkiPinning.h +22 -22
  13. package/ios/SpkiPinning.m +162 -114
  14. package/lib/commonjs/bidi-streaming.js.map +1 -1
  15. package/lib/commonjs/channel.js +9 -9
  16. package/lib/commonjs/channel.js.map +1 -1
  17. package/lib/commonjs/client-streaming.js +3 -3
  18. package/lib/commonjs/client-streaming.js.map +1 -1
  19. package/lib/commonjs/client.js +24 -24
  20. package/lib/commonjs/client.js.map +1 -1
  21. package/lib/commonjs/create-client.js +5 -5
  22. package/lib/commonjs/create-client.js.map +1 -1
  23. package/lib/commonjs/errors.js.map +1 -1
  24. package/lib/commonjs/index.js.map +1 -1
  25. package/lib/commonjs/interceptors.js +3 -3
  26. package/lib/commonjs/interceptors.js.map +1 -1
  27. package/lib/commonjs/native.js.map +1 -1
  28. package/lib/commonjs/retry.js.map +1 -1
  29. package/lib/commonjs/server-streaming.js.map +1 -1
  30. package/lib/commonjs/status.js.map +1 -1
  31. package/lib/commonjs/types.js +5 -5
  32. package/lib/commonjs/types.js.map +1 -1
  33. package/lib/commonjs/unary.js.map +1 -1
  34. package/lib/module/bidi-streaming.js.map +1 -1
  35. package/lib/module/channel.js +9 -9
  36. package/lib/module/channel.js.map +1 -1
  37. package/lib/module/client-streaming.js +3 -3
  38. package/lib/module/client-streaming.js.map +1 -1
  39. package/lib/module/client.js +24 -24
  40. package/lib/module/client.js.map +1 -1
  41. package/lib/module/create-client.js +5 -5
  42. package/lib/module/create-client.js.map +1 -1
  43. package/lib/module/errors.js.map +1 -1
  44. package/lib/module/index.js.map +1 -1
  45. package/lib/module/interceptors.js +3 -3
  46. package/lib/module/interceptors.js.map +1 -1
  47. package/lib/module/native.js.map +1 -1
  48. package/lib/module/retry.js.map +1 -1
  49. package/lib/module/server-streaming.js.map +1 -1
  50. package/lib/module/status.js.map +1 -1
  51. package/lib/module/types.js +5 -5
  52. package/lib/module/types.js.map +1 -1
  53. package/lib/module/unary.js.map +1 -1
  54. package/lib/typescript/src/bidi-streaming.d.ts.map +1 -0
  55. package/lib/typescript/src/channel.d.ts.map +1 -0
  56. package/lib/typescript/src/client-streaming.d.ts.map +1 -0
  57. package/lib/typescript/src/client.d.ts.map +1 -0
  58. package/lib/typescript/src/create-client.d.ts.map +1 -0
  59. package/lib/typescript/src/errors.d.ts.map +1 -0
  60. package/lib/typescript/src/index.d.ts.map +1 -0
  61. package/lib/typescript/src/interceptors.d.ts.map +1 -0
  62. package/lib/typescript/src/native.d.ts.map +1 -0
  63. package/lib/typescript/src/retry.d.ts.map +1 -0
  64. package/lib/typescript/src/server-streaming.d.ts.map +1 -0
  65. package/lib/typescript/src/status.d.ts.map +1 -0
  66. package/lib/typescript/src/types.d.ts.map +1 -0
  67. package/lib/typescript/src/unary.d.ts.map +1 -0
  68. package/lib/typescript/test/app/App.d.ts +3 -0
  69. package/lib/typescript/test/app/App.d.ts.map +1 -0
  70. package/package.json +209 -210
  71. package/react-native-grpc.podspec +33 -29
  72. package/src/bidi-streaming.ts +78 -78
  73. package/src/channel.ts +110 -110
  74. package/src/client-streaming.ts +106 -106
  75. package/src/client.ts +1046 -1046
  76. package/src/create-client.ts +391 -391
  77. package/src/errors.ts +11 -11
  78. package/src/index.ts +28 -28
  79. package/src/interceptors.ts +167 -167
  80. package/src/native.ts +99 -99
  81. package/src/retry.ts +208 -208
  82. package/src/server-streaming.ts +105 -105
  83. package/src/status.ts +50 -50
  84. package/src/types.ts +171 -171
  85. package/src/unary.ts +71 -71
  86. package/android/gradle.properties +0 -4
  87. package/lib/typescript/bidi-streaming.d.ts.map +0 -1
  88. package/lib/typescript/channel.d.ts.map +0 -1
  89. package/lib/typescript/client-streaming.d.ts.map +0 -1
  90. package/lib/typescript/client.d.ts.map +0 -1
  91. package/lib/typescript/create-client.d.ts.map +0 -1
  92. package/lib/typescript/errors.d.ts.map +0 -1
  93. package/lib/typescript/index.d.ts.map +0 -1
  94. package/lib/typescript/interceptors.d.ts.map +0 -1
  95. package/lib/typescript/native.d.ts.map +0 -1
  96. package/lib/typescript/retry.d.ts.map +0 -1
  97. package/lib/typescript/server-streaming.d.ts.map +0 -1
  98. package/lib/typescript/status.d.ts.map +0 -1
  99. package/lib/typescript/types.d.ts.map +0 -1
  100. package/lib/typescript/unary.d.ts.map +0 -1
  101. /package/lib/typescript/{bidi-streaming.d.ts → src/bidi-streaming.d.ts} +0 -0
  102. /package/lib/typescript/{channel.d.ts → src/channel.d.ts} +0 -0
  103. /package/lib/typescript/{client-streaming.d.ts → src/client-streaming.d.ts} +0 -0
  104. /package/lib/typescript/{client.d.ts → src/client.d.ts} +0 -0
  105. /package/lib/typescript/{create-client.d.ts → src/create-client.d.ts} +0 -0
  106. /package/lib/typescript/{errors.d.ts → src/errors.d.ts} +0 -0
  107. /package/lib/typescript/{index.d.ts → src/index.d.ts} +0 -0
  108. /package/lib/typescript/{interceptors.d.ts → src/interceptors.d.ts} +0 -0
  109. /package/lib/typescript/{native.d.ts → src/native.d.ts} +0 -0
  110. /package/lib/typescript/{retry.d.ts → src/retry.d.ts} +0 -0
  111. /package/lib/typescript/{server-streaming.d.ts → src/server-streaming.d.ts} +0 -0
  112. /package/lib/typescript/{status.d.ts → src/status.d.ts} +0 -0
  113. /package/lib/typescript/{types.d.ts → src/types.d.ts} +0 -0
  114. /package/lib/typescript/{unary.d.ts → src/unary.d.ts} +0 -0
package/LICENSE.md CHANGED
@@ -1,22 +1,22 @@
1
-
2
- The MIT License (MIT)
3
-
4
- Copyright (c) 2021 Mitchell Kutchuk
5
-
6
- Permission is hereby granted, free of charge, to any person obtaining a copy
7
- of this software and associated documentation files (the "Software"), to deal
8
- in the Software without restriction, including without limitation the rights
9
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
- copies of the Software, and to permit persons to whom the Software is
11
- furnished to do so, subject to the following conditions:
12
-
13
- The above copyright notice and this permission notice shall be included in all
14
- copies or substantial portions of the Software.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
- SOFTWARE.
1
+
2
+ The MIT License (MIT)
3
+
4
+ Copyright (c) 2021 Mitchell Kutchuk
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md CHANGED
@@ -1,284 +1,302 @@
1
- # @xdcobra/react-native-grpc
2
-
3
- Fork of [`@krishnafkh/react-native-grpc`](https://github.com/krishnafkh/react-native-grpc)
4
- (itself based on [Mitch528/react-native-grpc](https://github.com/Mitch528/react-native-grpc)).
5
-
6
- ## Changes vs upstream
7
-
8
- - Builds and runs with React Native New Architecture (Native Module interop)
9
- - Android `namespace 'com.reactnativegrpc'` (no `package` in AndroidManifest)
10
- - `minSdkVersion` 24
11
- - Per-call deadline via `setCallDeadlineSeconds` (default 120s) and per-RPC `options.deadlineSeconds`
12
- - Client streaming via `GrpcClient.clientStreamCall`
13
- - Bidirectional streaming via `GrpcClient.bidiStreamCall`
14
- - TLS options via `GrpcClient.setTlsOptions` (custom CA, mTLS, hostname override, SPKI pins)
15
- - Multiple concurrent channels via `createChannel` / `GrpcChannel` (immutable per-channel config)
16
- - Interceptors via `createChannel({ interceptors })` / `GrpcClient.setInterceptors` (auth, logging, remapping)
17
- - Unary retry / hedging via `createChannel({ retry | hedging })` / `GrpcClient.setRetryPolicy` / `setHedgingPolicy` ([gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)-style)
18
- - Typed clients via Protobuf-ES `createClient` (Buf + `protoc-gen-es`)
19
-
20
- ## Installation
21
-
22
- ```sh
23
- npm install @xdcobra/react-native-grpc
24
- # Typed clients (optional peer):
25
- npm install @bufbuild/protobuf
26
- # or
27
- npm install git+https://github.com/XDcobra/react-native-grpc.git
28
- ```
29
-
30
- ## Usage
31
-
32
- ```ts
33
- import { GrpcClient, GrpcMetadata } from '@xdcobra/react-native-grpc';
34
-
35
- GrpcClient.setHost('api.example.com:443');
36
- GrpcClient.setInsecure(false); // TLS (system / gRPC default roots)
37
- GrpcClient.setCallDeadlineSeconds(120); // global default
38
- GrpcClient.initGrpcChannel();
39
-
40
- // Plaintext (dev only)
41
- // GrpcClient.setInsecure(true);
42
-
43
- // Custom CA and/or mTLS and/or dial-by-IP hostname override
44
- // (each setTlsOptions call replaces the previous TLS config)
45
- GrpcClient.setTlsOptions({
46
- rootCertsPem: caPem, // optional (required on iOS when using spkiSha256Pins)
47
- certificateChainPem: clientCertPem, // mTLS (with privateKeyPem)
48
- privateKeyPem: clientKeyPem,
49
- hostNameOverride: 'api.example.com', // optional
50
- spkiSha256Pins: ['sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='],
51
- });
52
- GrpcClient.initGrpcChannel();
53
-
54
- const { response } = await GrpcClient.unaryCall(
55
- '/package.Service/Method',
56
- requestBytes,
57
- headers,
58
- { deadlineSeconds: 60 } // optional per-RPC override
59
- );
60
-
61
- // Client streaming: many request chunks, one response
62
- const stream = GrpcClient.clientStreamCall('/package.Service/Upload', headers);
63
- await stream.requests.send(chunk1);
64
- await stream.requests.send(chunk2);
65
- await stream.requests.complete();
66
- const { response: uploadResponse } = await stream;
67
-
68
- // Bidirectional streaming: interleaved requests and responses
69
- const bidi = GrpcClient.bidiStreamCall('/package.Service/Chat', headers, {
70
- deadlineSeconds: 60,
71
- });
72
- bidi.responses.on('data', (chunk) => {
73
- /* handle server message */
74
- });
75
- await bidi.requests.send(chunk1);
76
- await bidi.requests.send(chunk2);
77
- await bidi.requests.complete(); // half-close outbound
78
- const done = await bidi; // resolves on trailers
79
- ```
80
-
81
- ### Typed clients (Buf + createClient)
82
-
83
- Generate messages **and** `GenService` schemas with Buf + `@bufbuild/protoc-gen-es` (no custom plugin). Then call `createClient(service, GrpcClient | channel)`.
84
-
85
- ```yaml
86
- # buf.gen.yaml
87
- version: v2
88
- plugins:
89
- - local: protoc-gen-es
90
- out: src/gen
91
- opt: target=ts
92
- ```
93
-
94
- ```sh
95
- npm i @bufbuild/protobuf
96
- npm i -D @bufbuild/buf @bufbuild/protoc-gen-es
97
- npx buf generate
98
- ```
99
-
100
- ```ts
101
- import { create } from '@bufbuild/protobuf';
102
- import { createClient, GrpcClient } from '@xdcobra/react-native-grpc';
103
- import { ExampleRequestSchema, Examples } from './gen/example_pb';
104
-
105
- GrpcClient.setHost('api.example.com:443');
106
- GrpcClient.initGrpcChannel();
107
-
108
- const client = createClient(Examples, GrpcClient);
109
- // or: createClient(Examples, createChannel({ host: '...' }))
110
-
111
- const res = await client.sendExampleMessage(
112
- create(ExampleRequestSchema, { message: 'Ada' }),
113
- { authorization: 'Bearer …' },
114
- { deadlineSeconds: 30 }
115
- );
116
- ```
117
-
118
- | `methodKind` | Client shape |
119
- |---|---|
120
- | `unary` | `Promise<O>` |
121
- | `server_streaming` | async iterable + `.responses` / `.cancel()` |
122
- | `client_streaming` | `{ send(I), complete(), response: Promise<O> }` |
123
- | `bidi_streaming` | `{ send(I), complete(), responses }` (+ async iterable) |
124
-
125
- Path form: `/${service.typeName}/${MethodName}` (protobuf RPC name). Raw `unaryCall` / stream APIs remain for BYO bytes.
126
-
127
- Subpath import (optional): `import { createClient } from '@xdcobra/react-native-grpc/create-client'`.
128
-
129
- ### Multiple channels / hosts
130
-
131
- Prefer `createChannel` when talking to more than one host (or when you want immutable per-channel TLS/deadline config). The singleton `GrpcClient` path above remains supported for single-host apps.
132
-
133
- `createChannel` exposes the same RPC methods as `GrpcClient` (`unaryCall`, `serverStreamCall`, `clientStreamCall`, `bidiStreamCall`). Channel options (`host`, `insecure`, `tls`, deadline, keepalive, compression, response size) are set **once** in the config — there are no `setHost` / `setTlsOptions` mutators on the returned channel; reconfigure by creating a new channel.
134
-
135
- ```ts
136
- import { createChannel } from '@xdcobra/react-native-grpc';
137
-
138
- const primary = createChannel({
139
- host: 'api.example.com:443',
140
- insecure: false,
141
- callDeadlineSeconds: 120,
142
- tls: {
143
- rootCertsPem: caPem, // optional (required on iOS when using spkiSha256Pins)
144
- certificateChainPem: clientCertPem, // mTLS (with privateKeyPem)
145
- privateKeyPem: clientKeyPem,
146
- hostNameOverride: 'api.example.com', // optional
147
- spkiSha256Pins: ['sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='],
148
- },
149
- // optional:
150
- // responseSizeLimit: 4 * 1024 * 1024,
151
- // compression: { enable: true, compressorName: 'gzip' },
152
- // keepAlive: { enable: true, keepAliveTime: 30, keepAliveTimeOut: 10 },
153
- });
154
-
155
- const staging = createChannel({
156
- host: '10.0.2.2:50051',
157
- insecure: true, // plaintext; `tls` is ignored
158
- });
159
-
160
- await primary.unaryCall('/package.Service/Method', requestBytes);
161
- await staging.unaryCall('/package.Service/Method', requestBytes);
162
-
163
- primary.close();
164
- staging.close();
165
- ```
166
-
167
- `tls` uses the same `GrpcTlsOptions` fields as `GrpcClient.setTlsOptions` (see TLS matrix below). `close()` does not affect the singleton default channel.
168
-
169
- ### Interceptors
170
-
171
- `createChannel` accepts the same interceptor hooks as `GrpcClient.setInterceptors` (replace semantics on the singleton). Outbound hooks run index 0→n; inbound hooks run n→0 (onion). Throw from `onStart` to abort before the native call. Per-RPC extras: `options.interceptors` (appended after channel interceptors).
172
-
173
- ```ts
174
- import { createChannel, GrpcClient, GrpcInterceptor } from '@xdcobra/react-native-grpc';
175
-
176
- const auth: GrpcInterceptor = {
177
- onStart(start) {
178
- return {
179
- ...start,
180
- headers: {
181
- ...start.headers,
182
- authorization: 'Bearer <token>',
183
- },
184
- };
185
- },
186
- };
187
-
188
- // Multi-host / preferred
189
- const channel = createChannel({
190
- host: 'api.example.com:443',
191
- interceptors: [auth],
192
- });
193
-
194
- // Singleton
195
- GrpcClient.setInterceptors([auth]);
196
-
197
- await channel.unaryCall('/package.Service/Method', requestBytes, {}, {
198
- interceptors: [
199
- {
200
- onError(error) {
201
- // remap or log
202
- return error;
203
- },
204
- },
205
- ],
206
- });
207
- ```
208
-
209
- Hooks: `onStart`, `onSendMessage`, `onHeaders`, `onMessage`, `onTrailers`, `onError`.
210
-
211
- ### Retry / hedging (unary only)
212
-
213
- [gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)-inspired client policies for **unary** RPCs. Retry and hedging are mutually exclusive. Streams ignore these policies. Without a policy there is no automatic retry.
214
-
215
- ```ts
216
- import {
217
- createChannel,
218
- GrpcClient,
219
- GrpcStatusCode,
220
- } from '@xdcobra/react-native-grpc';
221
-
222
- const retry = {
223
- maxAttempts: 4, // clamped to max 5
224
- initialBackoff: '0.1s',
225
- maxBackoff: '1s',
226
- backoffMultiplier: 2,
227
- retryableStatusCodes: ['UNAVAILABLE', GrpcStatusCode.RESOURCE_EXHAUSTED],
228
- };
229
-
230
- // Preferred multi-host path
231
- const channel = createChannel({
232
- host: 'api.example.com:443',
233
- retry,
234
- });
235
-
236
- // Singleton
237
- GrpcClient.setRetryPolicy(retry);
238
- // GrpcClient.setHedgingPolicy({ maxAttempts: 3, hedgingDelay: '0.5s', nonFatalStatusCodes: ['UNAVAILABLE'] });
239
-
240
- await channel.unaryCall('/package.Service/Method', requestBytes, {}, {
241
- retry: false, // disable for this call
242
- });
243
- ```
244
-
245
- Hedging sends parallel attempts (first success wins; siblings are cancelled). Call deadline applies across the whole retry/hedge chain.
246
-
247
- Unary, server streaming, client streaming, and bidirectional streaming. Protobuf encode/decode is BYO (e.g. `@bufbuild/protobuf`) or via `createClient`.
248
-
249
- ### TLS matrix
250
-
251
- | Mode | How |
252
- |------|-----|
253
- | Plaintext | `setInsecure(true)` |
254
- | Public CA (e.g. Let's Encrypt) | `setInsecure(false)`, no `setTlsOptions` |
255
- | Custom / private CA | `rootCertsPem` |
256
- | mTLS | `certificateChainPem` + `privateKeyPem` (both required) |
257
- | Dial IP, cert for DNS name | `hostNameOverride` |
258
- | SPKI pin (SHA-256) | `spkiSha256Pins: ['base64…']` (optional `sha256/` prefix) |
259
-
260
- PEM values are strings (load from app assets/bundle yourself). On the singleton path, call `setTlsOptions` before `initGrpcChannel()`. With `createChannel`, pass the same fields under `tls` in the config.
261
-
262
- **SPKI pins:** at least one cert in the server chain must match. On **Android**, pins work with the system trust store and/or `rootCertsPem`. On **iOS** (gRPC ObjC has no handshake SPKI hook), set `rootCertsPem` to the pinned leaf/intermediate PEM as well. Pins are checked against that PEM at config time, then used as trust roots.
263
-
264
- Generate a pin (OpenSSL):
265
-
266
- ```sh
267
- openssl x509 -in leaf.pem -pubkey -noout \
268
- | openssl pkey -pubin -outform DER \
269
- | openssl dgst -sha256 -binary \
270
- | openssl enc -base64
271
- ```
272
-
273
- ## TODOs
274
-
275
- Gaps vs a full gRPC client (not yet supported or not exposed):
276
-
277
- - **Retry / hedging — remaining**: DNS/service-config JSON; retry throttling ([gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)); stream retry / transparent retry after first response message; native `enableRetry` / C-core service config (JS unary policies are implemented)
278
- - **Cross-platform connection events**: Android-only (`onConnectionStateChange`, `enterIdle`, …)
279
- - **Codegen — advanced**: no custom `protoc` plugin; Buf + `createClient` covers the typed path (raw bytes remain available)
280
-
281
-
282
- ## License
283
-
284
- MIT (same as upstream).
1
+ # @xdcobra/react-native-grpc
2
+
3
+ [![npm downloads](https://img.shields.io/npm/dm/@xdcobra/react-native-grpc.svg)](https://www.npmjs.com/package/@xdcobra/react-native-grpc)
4
+ [![Android](https://img.shields.io/badge/platform-Android-3DDC84?logo=android&logoColor=white)](https://developer.android.com)
5
+ [![iOS](https://img.shields.io/badge/platform-iOS-000000?logo=apple&logoColor=white)](https://developer.apple.com/ios)
6
+
7
+ Fork of [`@krishnafkh/react-native-grpc`](https://github.com/krishnafkh/react-native-grpc)
8
+ (itself based on [Mitch528/react-native-grpc](https://github.com/Mitch528/react-native-grpc)).
9
+
10
+ ## Changes vs upstream
11
+
12
+ - Builds and runs with React Native New Architecture (Native Module interop)
13
+ - Android `namespace 'com.reactnativegrpc'` (no `package` in AndroidManifest)
14
+ - `minSdkVersion` 24
15
+ - Per-call deadline via `setCallDeadlineSeconds` (default 120s) and per-RPC `options.deadlineSeconds`
16
+ - Client streaming via `GrpcClient.clientStreamCall`
17
+ - Bidirectional streaming via `GrpcClient.bidiStreamCall`
18
+ - TLS options via `GrpcClient.setTlsOptions` (custom CA, mTLS, hostname override, SPKI pins)
19
+ - Multiple concurrent channels via `createChannel` / `GrpcChannel` (immutable per-channel config)
20
+ - Interceptors via `createChannel({ interceptors })` / `GrpcClient.setInterceptors` (auth, logging, remapping)
21
+ - Unary retry / hedging via `createChannel({ retry | hedging })` / `GrpcClient.setRetryPolicy` / `setHedgingPolicy` ([gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)-style)
22
+ - Typed clients via Protobuf-ES `createClient` (Buf + `protoc-gen-es`)
23
+
24
+ ## Compatibility
25
+
26
+ | | Minimum |
27
+ |---|---|
28
+ | React Native | 0.76 |
29
+ | iOS | 15.1 (the minimum of React Native 0.76+) |
30
+ | Android `minSdkVersion` | 24 |
31
+
32
+ The native modules are classic bridge modules and run under the New Architecture through React Native's interop layer.
33
+
34
+ **iOS gRPC pod:** `gRPC` is limited to `>= 1.84.1, < 1.85.0`. `gRPC-Core 1.85.0` pulls `abseil 1.20260526.0`, whose CocoaPods spec compiles the Windows-only `time_zone_name_win.cc` and fails with `'windows.h' file not found`. The limit will be lifted once this is fixed upstream.
35
+
36
+ **Xcode 27:** its supported deployment target range starts at iOS 15, but the `abseil` pod still declares iOS 12.0, so building any app that uses the `gRPC` pod fails in `abseil-xcprivacy`. This comes from the `abseil` pod, not from this package.
37
+
38
+ ## Installation
39
+
40
+ ```sh
41
+ npm install @xdcobra/react-native-grpc
42
+ # Typed clients (optional peer):
43
+ npm install @bufbuild/protobuf
44
+ # or
45
+ npm install git+https://github.com/XDcobra/react-native-grpc.git
46
+ ```
47
+
48
+ ## Usage
49
+
50
+ ```ts
51
+ import { GrpcClient, GrpcMetadata } from '@xdcobra/react-native-grpc';
52
+
53
+ GrpcClient.setHost('api.example.com:443');
54
+ GrpcClient.setInsecure(false); // TLS (system / gRPC default roots)
55
+ GrpcClient.setCallDeadlineSeconds(120); // global default
56
+ GrpcClient.initGrpcChannel();
57
+
58
+ // Plaintext (dev only)
59
+ // GrpcClient.setInsecure(true);
60
+
61
+ // Custom CA and/or mTLS and/or dial-by-IP hostname override
62
+ // (each setTlsOptions call replaces the previous TLS config)
63
+ GrpcClient.setTlsOptions({
64
+ rootCertsPem: caPem, // optional (required on iOS when using spkiSha256Pins)
65
+ certificateChainPem: clientCertPem, // mTLS (with privateKeyPem)
66
+ privateKeyPem: clientKeyPem,
67
+ hostNameOverride: 'api.example.com', // optional
68
+ spkiSha256Pins: ['sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='],
69
+ });
70
+ GrpcClient.initGrpcChannel();
71
+
72
+ const { response } = await GrpcClient.unaryCall(
73
+ '/package.Service/Method',
74
+ requestBytes,
75
+ headers,
76
+ { deadlineSeconds: 60 } // optional per-RPC override
77
+ );
78
+
79
+ // Client streaming: many request chunks, one response
80
+ const stream = GrpcClient.clientStreamCall('/package.Service/Upload', headers);
81
+ await stream.requests.send(chunk1);
82
+ await stream.requests.send(chunk2);
83
+ await stream.requests.complete();
84
+ const { response: uploadResponse } = await stream;
85
+
86
+ // Bidirectional streaming: interleaved requests and responses
87
+ const bidi = GrpcClient.bidiStreamCall('/package.Service/Chat', headers, {
88
+ deadlineSeconds: 60,
89
+ });
90
+ bidi.responses.on('data', (chunk) => {
91
+ /* handle server message */
92
+ });
93
+ await bidi.requests.send(chunk1);
94
+ await bidi.requests.send(chunk2);
95
+ await bidi.requests.complete(); // half-close outbound
96
+ const done = await bidi; // resolves on trailers
97
+ ```
98
+
99
+ ### Typed clients (Buf + createClient)
100
+
101
+ Generate messages **and** `GenService` schemas with Buf + `@bufbuild/protoc-gen-es` (no custom plugin). Then call `createClient(service, GrpcClient | channel)`.
102
+
103
+ ```yaml
104
+ # buf.gen.yaml
105
+ version: v2
106
+ plugins:
107
+ - local: protoc-gen-es
108
+ out: src/gen
109
+ opt: target=ts
110
+ ```
111
+
112
+ ```sh
113
+ npm i @bufbuild/protobuf
114
+ npm i -D @bufbuild/buf @bufbuild/protoc-gen-es
115
+ npx buf generate
116
+ ```
117
+
118
+ ```ts
119
+ import { create } from '@bufbuild/protobuf';
120
+ import { createClient, GrpcClient } from '@xdcobra/react-native-grpc';
121
+ import { ExampleRequestSchema, Examples } from './gen/example_pb';
122
+
123
+ GrpcClient.setHost('api.example.com:443');
124
+ GrpcClient.initGrpcChannel();
125
+
126
+ const client = createClient(Examples, GrpcClient);
127
+ // or: createClient(Examples, createChannel({ host: '...' }))
128
+
129
+ const res = await client.sendExampleMessage(
130
+ create(ExampleRequestSchema, { message: 'Ada' }),
131
+ { authorization: 'Bearer …' },
132
+ { deadlineSeconds: 30 }
133
+ );
134
+ ```
135
+
136
+ | `methodKind` | Client shape |
137
+ |---|---|
138
+ | `unary` | `Promise<O>` |
139
+ | `server_streaming` | async iterable + `.responses` / `.cancel()` |
140
+ | `client_streaming` | `{ send(I), complete(), response: Promise<O> }` |
141
+ | `bidi_streaming` | `{ send(I), complete(), responses }` (+ async iterable) |
142
+
143
+ Path form: `/${service.typeName}/${MethodName}` (protobuf RPC name). Raw `unaryCall` / stream APIs remain for BYO bytes.
144
+
145
+ Subpath import (optional): `import { createClient } from '@xdcobra/react-native-grpc/create-client'`.
146
+
147
+ ### Multiple channels / hosts
148
+
149
+ Prefer `createChannel` when talking to more than one host (or when you want immutable per-channel TLS/deadline config). The singleton `GrpcClient` path above remains supported for single-host apps.
150
+
151
+ `createChannel` exposes the same RPC methods as `GrpcClient` (`unaryCall`, `serverStreamCall`, `clientStreamCall`, `bidiStreamCall`). Channel options (`host`, `insecure`, `tls`, deadline, keepalive, compression, response size) are set **once** in the config — there are no `setHost` / `setTlsOptions` mutators on the returned channel; reconfigure by creating a new channel.
152
+
153
+ ```ts
154
+ import { createChannel } from '@xdcobra/react-native-grpc';
155
+
156
+ const primary = createChannel({
157
+ host: 'api.example.com:443',
158
+ insecure: false,
159
+ callDeadlineSeconds: 120,
160
+ tls: {
161
+ rootCertsPem: caPem, // optional (required on iOS when using spkiSha256Pins)
162
+ certificateChainPem: clientCertPem, // mTLS (with privateKeyPem)
163
+ privateKeyPem: clientKeyPem,
164
+ hostNameOverride: 'api.example.com', // optional
165
+ spkiSha256Pins: ['sha256/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='],
166
+ },
167
+ // optional:
168
+ // responseSizeLimit: 4 * 1024 * 1024,
169
+ // compression: { enable: true, compressorName: 'gzip' },
170
+ // keepAlive: { enable: true, keepAliveTime: 30, keepAliveTimeOut: 10 },
171
+ });
172
+
173
+ const staging = createChannel({
174
+ host: '10.0.2.2:50051',
175
+ insecure: true, // plaintext; `tls` is ignored
176
+ });
177
+
178
+ await primary.unaryCall('/package.Service/Method', requestBytes);
179
+ await staging.unaryCall('/package.Service/Method', requestBytes);
180
+
181
+ primary.close();
182
+ staging.close();
183
+ ```
184
+
185
+ `tls` uses the same `GrpcTlsOptions` fields as `GrpcClient.setTlsOptions` (see TLS matrix below). `close()` does not affect the singleton default channel.
186
+
187
+ ### Interceptors
188
+
189
+ `createChannel` accepts the same interceptor hooks as `GrpcClient.setInterceptors` (replace semantics on the singleton). Outbound hooks run index 0→n; inbound hooks run n→0 (onion). Throw from `onStart` to abort before the native call. Per-RPC extras: `options.interceptors` (appended after channel interceptors).
190
+
191
+ ```ts
192
+ import { createChannel, GrpcClient, GrpcInterceptor } from '@xdcobra/react-native-grpc';
193
+
194
+ const auth: GrpcInterceptor = {
195
+ onStart(start) {
196
+ return {
197
+ ...start,
198
+ headers: {
199
+ ...start.headers,
200
+ authorization: 'Bearer <token>',
201
+ },
202
+ };
203
+ },
204
+ };
205
+
206
+ // Multi-host / preferred
207
+ const channel = createChannel({
208
+ host: 'api.example.com:443',
209
+ interceptors: [auth],
210
+ });
211
+
212
+ // Singleton
213
+ GrpcClient.setInterceptors([auth]);
214
+
215
+ await channel.unaryCall('/package.Service/Method', requestBytes, {}, {
216
+ interceptors: [
217
+ {
218
+ onError(error) {
219
+ // remap or log
220
+ return error;
221
+ },
222
+ },
223
+ ],
224
+ });
225
+ ```
226
+
227
+ Hooks: `onStart`, `onSendMessage`, `onHeaders`, `onMessage`, `onTrailers`, `onError`.
228
+
229
+ ### Retry / hedging (unary only)
230
+
231
+ [gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)-inspired client policies for **unary** RPCs. Retry and hedging are mutually exclusive. Streams ignore these policies. Without a policy there is no automatic retry.
232
+
233
+ ```ts
234
+ import {
235
+ createChannel,
236
+ GrpcClient,
237
+ GrpcStatusCode,
238
+ } from '@xdcobra/react-native-grpc';
239
+
240
+ const retry = {
241
+ maxAttempts: 4, // clamped to max 5
242
+ initialBackoff: '0.1s',
243
+ maxBackoff: '1s',
244
+ backoffMultiplier: 2,
245
+ retryableStatusCodes: ['UNAVAILABLE', GrpcStatusCode.RESOURCE_EXHAUSTED],
246
+ };
247
+
248
+ // Preferred multi-host path
249
+ const channel = createChannel({
250
+ host: 'api.example.com:443',
251
+ retry,
252
+ });
253
+
254
+ // Singleton
255
+ GrpcClient.setRetryPolicy(retry);
256
+ // GrpcClient.setHedgingPolicy({ maxAttempts: 3, hedgingDelay: '0.5s', nonFatalStatusCodes: ['UNAVAILABLE'] });
257
+
258
+ await channel.unaryCall('/package.Service/Method', requestBytes, {}, {
259
+ retry: false, // disable for this call
260
+ });
261
+ ```
262
+
263
+ Hedging sends parallel attempts (first success wins; siblings are cancelled). Call deadline applies across the whole retry/hedge chain.
264
+
265
+ Unary, server streaming, client streaming, and bidirectional streaming. Protobuf encode/decode is BYO (e.g. `@bufbuild/protobuf`) or via `createClient`.
266
+
267
+ ### TLS matrix
268
+
269
+ | Mode | How |
270
+ |------|-----|
271
+ | Plaintext | `setInsecure(true)` |
272
+ | Public CA (e.g. Let's Encrypt) | `setInsecure(false)`, no `setTlsOptions` |
273
+ | Custom / private CA | `rootCertsPem` |
274
+ | mTLS | `certificateChainPem` + `privateKeyPem` (both required) |
275
+ | Dial IP, cert for DNS name | `hostNameOverride` |
276
+ | SPKI pin (SHA-256) | `spkiSha256Pins: ['base64…']` (optional `sha256/` prefix) |
277
+
278
+ PEM values are strings (load from app assets/bundle yourself). On the singleton path, call `setTlsOptions` before `initGrpcChannel()`. With `createChannel`, pass the same fields under `tls` in the config.
279
+
280
+ **SPKI pins:** at least one cert in the server chain must match. On **Android**, pins work with the system trust store and/or `rootCertsPem`. On **iOS** (gRPC ObjC has no handshake SPKI hook), set `rootCertsPem` to the pinned leaf/intermediate PEM as well. Pins are checked against that PEM at config time, then used as trust roots.
281
+
282
+ Generate a pin (OpenSSL):
283
+
284
+ ```sh
285
+ openssl x509 -in leaf.pem -pubkey -noout \
286
+ | openssl pkey -pubin -outform DER \
287
+ | openssl dgst -sha256 -binary \
288
+ | openssl enc -base64
289
+ ```
290
+
291
+ ## TODOs
292
+
293
+ Gaps vs a full gRPC client (not yet supported or not exposed):
294
+
295
+ - **Retry / hedging — remaining**: DNS/service-config JSON; retry throttling ([gRFC A6](https://github.com/grpc/proposal/blob/master/A6-client-retries.md)); stream retry / transparent retry after first response message; native `enableRetry` / C-core service config (JS unary policies are implemented)
296
+ - **Cross-platform connection events**: Android-only (`onConnectionStateChange`, `enterIdle`, …)
297
+ - **Codegen — advanced**: no custom `protoc` plugin; Buf + `createClient` covers the typed path (raw bytes remain available)
298
+
299
+
300
+ ## License
301
+
302
+ MIT (same as upstream).