@dxos/rpc 0.8.4-main.dedc0f3 → 0.8.4-main.e00bdcdb52

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.
@@ -1,957 +0,0 @@
1
- import { createRequire } from 'node:module';const require = createRequire(import.meta.url);
2
-
3
- // src/errors.ts
4
- import { StackTrace } from "@dxos/debug";
5
- import { decodeError } from "@dxos/protocols";
6
- var decodeRpcError = (err, rpcMethod) => decodeError(err, {
7
- appendStack: `
8
- at RPC ${rpcMethod}
9
- ` + new StackTrace().getStack(1)
10
- });
11
-
12
- // src/rpc.ts
13
- import { Trigger, asyncTimeout, synchronized } from "@dxos/async";
14
- import { Stream } from "@dxos/codec-protobuf";
15
- import { StackTrace as StackTrace2 } from "@dxos/debug";
16
- import { invariant } from "@dxos/invariant";
17
- import { log } from "@dxos/log";
18
- import { RpcClosedError, RpcNotOpenError, encodeError } from "@dxos/protocols";
19
- import { schema } from "@dxos/protocols/proto";
20
- import { exponentialBackoffInterval } from "@dxos/util";
21
- function _define_property(obj, key, value) {
22
- if (key in obj) {
23
- Object.defineProperty(obj, key, {
24
- value,
25
- enumerable: true,
26
- configurable: true,
27
- writable: true
28
- });
29
- } else {
30
- obj[key] = value;
31
- }
32
- return obj;
33
- }
34
- function _ts_decorate(decorators, target, key, desc) {
35
- var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
36
- if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
37
- else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
38
- return c > 3 && r && Object.defineProperty(target, key, r), r;
39
- }
40
- var __dxlog_file = "/__w/dxos/dxos/packages/core/mesh/rpc/src/rpc.ts";
41
- var DEFAULT_TIMEOUT = 3e3;
42
- var BYE_SEND_TIMEOUT = 2e3;
43
- var DEBUG_CALLS = true;
44
- var CLOSE_TIMEOUT = 3e3;
45
- var PendingRpcRequest = class {
46
- constructor(resolve, reject, stream) {
47
- _define_property(this, "resolve", void 0);
48
- _define_property(this, "reject", void 0);
49
- _define_property(this, "stream", void 0);
50
- this.resolve = resolve;
51
- this.reject = reject;
52
- this.stream = stream;
53
- }
54
- };
55
- var RpcMessageCodec;
56
- var getRpcMessageCodec = () => RpcMessageCodec ?? (RpcMessageCodec = schema.getCodecForType("dxos.rpc.RpcMessage"));
57
- var RpcPeer = class {
58
- /**
59
- * Open the peer. Required before making any calls.
60
- *
61
- * Will block before the other peer calls `open`.
62
- */
63
- async open() {
64
- if (this._state !== "INITIAL") {
65
- return;
66
- }
67
- this._unsubscribeFromPort = this._params.port.subscribe(async (msg) => {
68
- try {
69
- await this._receive(msg);
70
- } catch (err) {
71
- log.catch(err, void 0, {
72
- F: __dxlog_file,
73
- L: 156,
74
- S: this,
75
- C: (f, a) => f(...a)
76
- });
77
- }
78
- });
79
- this._state = "OPENING";
80
- if (this._params.noHandshake) {
81
- this._state = "OPENED";
82
- this._remoteOpenTrigger.wake();
83
- return;
84
- }
85
- log("sending open message", {
86
- state: this._state
87
- }, {
88
- F: __dxlog_file,
89
- L: 168,
90
- S: this,
91
- C: (f, a) => f(...a)
92
- });
93
- await this._sendMessage({
94
- open: true
95
- });
96
- if (this._state !== "OPENING") {
97
- return;
98
- }
99
- this._clearOpenInterval = exponentialBackoffInterval(() => {
100
- void this._sendMessage({
101
- open: true
102
- }).catch((err) => log.warn(err, void 0, {
103
- F: __dxlog_file,
104
- L: 177,
105
- S: this,
106
- C: (f, a) => f(...a)
107
- }));
108
- }, 50);
109
- await Promise.race([
110
- this._remoteOpenTrigger.wait(),
111
- this._closingTrigger.wait()
112
- ]);
113
- this._clearOpenInterval?.();
114
- if (this._state !== "OPENED") {
115
- return;
116
- }
117
- log("resending open message", {
118
- state: this._state
119
- }, {
120
- F: __dxlog_file,
121
- L: 191,
122
- S: this,
123
- C: (f, a) => f(...a)
124
- });
125
- await this._sendMessage({
126
- openAck: true
127
- });
128
- }
129
- /**
130
- * Close the peer.
131
- * Stop taking or making requests.
132
- * Will wait for confirmation from the other side.
133
- * Any responses for RPC calls made before close will be delivered.
134
- */
135
- async close({ timeout = CLOSE_TIMEOUT } = {}) {
136
- if (this._state === "CLOSED") {
137
- return;
138
- }
139
- this._abortRequests();
140
- if (this._state === "OPENED" && !this._params.noHandshake) {
141
- try {
142
- this._state = "CLOSING";
143
- await this._sendMessage({
144
- bye: {}
145
- }, BYE_SEND_TIMEOUT);
146
- } catch (err) {
147
- log("error closing peer, sending bye", {
148
- err
149
- }, {
150
- F: __dxlog_file,
151
- L: 213,
152
- S: this,
153
- C: (f, a) => f(...a)
154
- });
155
- }
156
- try {
157
- log("closing waiting on bye", void 0, {
158
- F: __dxlog_file,
159
- L: 216,
160
- S: this,
161
- C: (f, a) => f(...a)
162
- });
163
- await this._byeTrigger.wait({
164
- timeout
165
- });
166
- } catch (err) {
167
- log("error closing peer", {
168
- err
169
- }, {
170
- F: __dxlog_file,
171
- L: 219,
172
- S: this,
173
- C: (f, a) => f(...a)
174
- });
175
- return;
176
- }
177
- }
178
- this._disposeAndClose();
179
- }
180
- /**
181
- * Dispose the connection without waiting for the other side.
182
- */
183
- async abort() {
184
- if (this._state === "CLOSED") {
185
- return;
186
- }
187
- this._abortRequests();
188
- this._disposeAndClose();
189
- }
190
- _abortRequests() {
191
- this._clearOpenInterval?.();
192
- this._closingTrigger.wake();
193
- for (const req of this._outgoingRequests.values()) {
194
- req.reject(new RpcClosedError());
195
- }
196
- this._outgoingRequests.clear();
197
- }
198
- _disposeAndClose() {
199
- this._unsubscribeFromPort?.();
200
- this._unsubscribeFromPort = void 0;
201
- this._clearOpenInterval?.();
202
- this._state = "CLOSED";
203
- }
204
- /**
205
- * Handle incoming message. Should be called as the result of other peer's `send` callback.
206
- */
207
- async _receive(msg) {
208
- const decoded = getRpcMessageCodec().decode(msg, {
209
- preserveAny: true
210
- });
211
- DEBUG_CALLS && log("received message", {
212
- type: Object.keys(decoded)[0]
213
- }, {
214
- F: __dxlog_file,
215
- L: 263,
216
- S: this,
217
- C: (f, a) => f(...a)
218
- });
219
- if (decoded.request) {
220
- if (this._state !== "OPENED" && this._state !== "OPENING") {
221
- log("received request while closed", void 0, {
222
- F: __dxlog_file,
223
- L: 267,
224
- S: this,
225
- C: (f, a) => f(...a)
226
- });
227
- await this._sendMessage({
228
- response: {
229
- id: decoded.request.id,
230
- error: encodeError(new RpcClosedError())
231
- }
232
- });
233
- return;
234
- }
235
- const req = decoded.request;
236
- if (req.stream) {
237
- log("stream request", {
238
- method: req.method
239
- }, {
240
- F: __dxlog_file,
241
- L: 279,
242
- S: this,
243
- C: (f, a) => f(...a)
244
- });
245
- this._callStreamHandler(req, (response) => {
246
- log("sending stream response", {
247
- method: req.method,
248
- response: response.payload?.type_url,
249
- error: response.error,
250
- close: response.close
251
- }, {
252
- F: __dxlog_file,
253
- L: 281,
254
- S: this,
255
- C: (f, a) => f(...a)
256
- });
257
- void this._sendMessage({
258
- response
259
- }).catch((err) => {
260
- log.warn("failed during close", err, {
261
- F: __dxlog_file,
262
- L: 289,
263
- S: this,
264
- C: (f, a) => f(...a)
265
- });
266
- });
267
- });
268
- } else {
269
- DEBUG_CALLS && log("requesting...", {
270
- method: req.method
271
- }, {
272
- F: __dxlog_file,
273
- L: 293,
274
- S: this,
275
- C: (f, a) => f(...a)
276
- });
277
- const response = await this._callHandler(req);
278
- DEBUG_CALLS && log("sending response", {
279
- method: req.method,
280
- response: response.payload?.type_url,
281
- error: response.error
282
- }, {
283
- F: __dxlog_file,
284
- L: 296,
285
- S: this,
286
- C: (f, a) => f(...a)
287
- });
288
- await this._sendMessage({
289
- response
290
- });
291
- }
292
- } else if (decoded.response) {
293
- if (this._state !== "OPENED") {
294
- log("received response while closed", void 0, {
295
- F: __dxlog_file,
296
- L: 305,
297
- S: this,
298
- C: (f, a) => f(...a)
299
- });
300
- return;
301
- }
302
- const responseId = decoded.response.id;
303
- invariant(typeof responseId === "number", void 0, {
304
- F: __dxlog_file,
305
- L: 310,
306
- S: this,
307
- A: [
308
- "typeof responseId === 'number'",
309
- ""
310
- ]
311
- });
312
- if (!this._outgoingRequests.has(responseId)) {
313
- log("received response with invalid id", {
314
- responseId
315
- }, {
316
- F: __dxlog_file,
317
- L: 312,
318
- S: this,
319
- C: (f, a) => f(...a)
320
- });
321
- return;
322
- }
323
- const item = this._outgoingRequests.get(responseId);
324
- if (!item.stream) {
325
- this._outgoingRequests.delete(responseId);
326
- }
327
- DEBUG_CALLS && log("response", {
328
- type_url: decoded.response.payload?.type_url
329
- }, {
330
- F: __dxlog_file,
331
- L: 322,
332
- S: this,
333
- C: (f, a) => f(...a)
334
- });
335
- item.resolve(decoded.response);
336
- } else if (decoded.open) {
337
- log("received open message", {
338
- state: this._state
339
- }, {
340
- F: __dxlog_file,
341
- L: 325,
342
- S: this,
343
- C: (f, a) => f(...a)
344
- });
345
- if (this._params.noHandshake) {
346
- return;
347
- }
348
- await this._sendMessage({
349
- openAck: true
350
- });
351
- } else if (decoded.openAck) {
352
- log("received openAck message", {
353
- state: this._state
354
- }, {
355
- F: __dxlog_file,
356
- L: 332,
357
- S: this,
358
- C: (f, a) => f(...a)
359
- });
360
- if (this._params.noHandshake) {
361
- return;
362
- }
363
- this._state = "OPENED";
364
- this._remoteOpenTrigger.wake();
365
- } else if (decoded.streamClose) {
366
- if (this._state !== "OPENED") {
367
- log("received stream close while closed", void 0, {
368
- F: __dxlog_file,
369
- L: 341,
370
- S: this,
371
- C: (f, a) => f(...a)
372
- });
373
- return;
374
- }
375
- log("received stream close", {
376
- id: decoded.streamClose.id
377
- }, {
378
- F: __dxlog_file,
379
- L: 345,
380
- S: this,
381
- C: (f, a) => f(...a)
382
- });
383
- invariant(typeof decoded.streamClose.id === "number", void 0, {
384
- F: __dxlog_file,
385
- L: 346,
386
- S: this,
387
- A: [
388
- "typeof decoded.streamClose.id === 'number'",
389
- ""
390
- ]
391
- });
392
- const stream = this._localStreams.get(decoded.streamClose.id);
393
- if (!stream) {
394
- log("no local stream", {
395
- id: decoded.streamClose.id
396
- }, {
397
- F: __dxlog_file,
398
- L: 349,
399
- S: this,
400
- C: (f, a) => f(...a)
401
- });
402
- return;
403
- }
404
- this._localStreams.delete(decoded.streamClose.id);
405
- await stream.close();
406
- } else if (decoded.bye) {
407
- this._byeTrigger.wake();
408
- if (this._state !== "CLOSING" && this._state !== "CLOSED") {
409
- log("replying to bye", void 0, {
410
- F: __dxlog_file,
411
- L: 359,
412
- S: this,
413
- C: (f, a) => f(...a)
414
- });
415
- this._state = "CLOSING";
416
- await this._sendMessage({
417
- bye: {}
418
- });
419
- this._abortRequests();
420
- this._disposeAndClose();
421
- }
422
- } else {
423
- log.error("received malformed message", {
424
- msg
425
- }, {
426
- F: __dxlog_file,
427
- L: 367,
428
- S: this,
429
- C: (f, a) => f(...a)
430
- });
431
- throw new Error("Malformed message.");
432
- }
433
- }
434
- /**
435
- * Make RPC call. Will trigger a handler on the other side.
436
- * Peer should be open before making this call.
437
- */
438
- async call(method, request, options) {
439
- DEBUG_CALLS && log("calling...", {
440
- method
441
- }, {
442
- F: __dxlog_file,
443
- L: 377,
444
- S: this,
445
- C: (f, a) => f(...a)
446
- });
447
- throwIfNotOpen(this._state);
448
- let response;
449
- try {
450
- const id = this._nextId++;
451
- const responseReceived = new Promise((resolve, reject) => {
452
- this._outgoingRequests.set(id, new PendingRpcRequest(resolve, reject, false));
453
- });
454
- const sending = this._sendMessage({
455
- request: {
456
- id,
457
- method,
458
- payload: request,
459
- stream: false
460
- }
461
- });
462
- const timeout = options?.timeout ?? this._params.timeout;
463
- const waiting = timeout === 0 ? responseReceived : asyncTimeout(responseReceived, timeout ?? DEFAULT_TIMEOUT);
464
- await Promise.race([
465
- sending,
466
- waiting
467
- ]);
468
- response = await waiting;
469
- invariant(response.id === id, void 0, {
470
- F: __dxlog_file,
471
- L: 405,
472
- S: this,
473
- A: [
474
- "response.id === id",
475
- ""
476
- ]
477
- });
478
- } catch (err) {
479
- if (err instanceof RpcClosedError) {
480
- const error = new RpcClosedError();
481
- error.stack += `
482
-
483
- info: RPC client was closed at:
484
- ${err.stack?.split("\n").slice(1).join("\n")}`;
485
- throw error;
486
- }
487
- throw err;
488
- }
489
- if (response.payload) {
490
- return response.payload;
491
- } else if (response.error) {
492
- throw decodeRpcError(response.error, method);
493
- } else {
494
- throw new Error("Malformed response.");
495
- }
496
- }
497
- /**
498
- * Make RPC call with a streaming response.
499
- * Will trigger a handler on the other side.
500
- * Peer should be open before making this call.
501
- */
502
- callStream(method, request, options) {
503
- throwIfNotOpen(this._state);
504
- const id = this._nextId++;
505
- return new Stream(({ ready, next, close }) => {
506
- const onResponse = (response) => {
507
- if (response.streamReady) {
508
- ready();
509
- } else if (response.close) {
510
- close();
511
- } else if (response.error) {
512
- close(decodeRpcError(response.error, method));
513
- } else if (response.payload) {
514
- next(response.payload);
515
- } else {
516
- throw new Error("Malformed response.");
517
- }
518
- };
519
- const stack = new StackTrace2();
520
- const closeStream = (err) => {
521
- if (!err) {
522
- close();
523
- } else {
524
- err.stack += `
525
-
526
- Error happened in the stream at:
527
- ${stack.getStack()}`;
528
- close(err);
529
- }
530
- };
531
- this._outgoingRequests.set(id, new PendingRpcRequest(onResponse, closeStream, true));
532
- this._sendMessage({
533
- request: {
534
- id,
535
- method,
536
- payload: request,
537
- stream: true
538
- }
539
- }).catch((err) => {
540
- close(err);
541
- });
542
- return () => {
543
- this._sendMessage({
544
- streamClose: {
545
- id
546
- }
547
- }).catch((err) => {
548
- log.catch(err, void 0, {
549
- F: __dxlog_file,
550
- L: 478,
551
- S: this,
552
- C: (f, a) => f(...a)
553
- });
554
- });
555
- this._outgoingRequests.delete(id);
556
- };
557
- });
558
- }
559
- async _sendMessage(message, timeout) {
560
- DEBUG_CALLS && log("sending message", {
561
- type: Object.keys(message)[0]
562
- }, {
563
- F: __dxlog_file,
564
- L: 486,
565
- S: this,
566
- C: (f, a) => f(...a)
567
- });
568
- await this._params.port.send(getRpcMessageCodec().encode(message, {
569
- preserveAny: true
570
- }), timeout);
571
- }
572
- async _callHandler(req) {
573
- try {
574
- invariant(typeof req.id === "number", void 0, {
575
- F: __dxlog_file,
576
- L: 492,
577
- S: this,
578
- A: [
579
- "typeof req.id === 'number'",
580
- ""
581
- ]
582
- });
583
- invariant(req.payload, void 0, {
584
- F: __dxlog_file,
585
- L: 493,
586
- S: this,
587
- A: [
588
- "req.payload",
589
- ""
590
- ]
591
- });
592
- invariant(req.method, void 0, {
593
- F: __dxlog_file,
594
- L: 494,
595
- S: this,
596
- A: [
597
- "req.method",
598
- ""
599
- ]
600
- });
601
- const response = await this._params.callHandler(req.method, req.payload, this._params.handlerRpcOptions);
602
- return {
603
- id: req.id,
604
- payload: response
605
- };
606
- } catch (err) {
607
- return {
608
- id: req.id,
609
- error: encodeError(err)
610
- };
611
- }
612
- }
613
- _callStreamHandler(req, callback) {
614
- try {
615
- invariant(this._params.streamHandler, "Requests with streaming responses are not supported.", {
616
- F: __dxlog_file,
617
- L: 511,
618
- S: this,
619
- A: [
620
- "this._params.streamHandler",
621
- "'Requests with streaming responses are not supported.'"
622
- ]
623
- });
624
- invariant(typeof req.id === "number", void 0, {
625
- F: __dxlog_file,
626
- L: 512,
627
- S: this,
628
- A: [
629
- "typeof req.id === 'number'",
630
- ""
631
- ]
632
- });
633
- invariant(req.payload, void 0, {
634
- F: __dxlog_file,
635
- L: 513,
636
- S: this,
637
- A: [
638
- "req.payload",
639
- ""
640
- ]
641
- });
642
- invariant(req.method, void 0, {
643
- F: __dxlog_file,
644
- L: 514,
645
- S: this,
646
- A: [
647
- "req.method",
648
- ""
649
- ]
650
- });
651
- const responseStream = this._params.streamHandler(req.method, req.payload, this._params.handlerRpcOptions);
652
- responseStream.onReady(() => {
653
- callback({
654
- id: req.id,
655
- streamReady: true
656
- });
657
- });
658
- responseStream.subscribe((msg) => {
659
- callback({
660
- id: req.id,
661
- payload: msg
662
- });
663
- }, (error) => {
664
- if (error) {
665
- callback({
666
- id: req.id,
667
- error: encodeError(error)
668
- });
669
- } else {
670
- callback({
671
- id: req.id,
672
- close: true
673
- });
674
- }
675
- });
676
- this._localStreams.set(req.id, responseStream);
677
- } catch (err) {
678
- callback({
679
- id: req.id,
680
- error: encodeError(err)
681
- });
682
- }
683
- }
684
- constructor(params) {
685
- _define_property(this, "_params", void 0);
686
- _define_property(this, "_outgoingRequests", /* @__PURE__ */ new Map());
687
- _define_property(this, "_localStreams", /* @__PURE__ */ new Map());
688
- _define_property(this, "_remoteOpenTrigger", new Trigger());
689
- _define_property(this, "_closingTrigger", new Trigger());
690
- _define_property(this, "_byeTrigger", new Trigger());
691
- _define_property(this, "_nextId", 0);
692
- _define_property(this, "_state", "INITIAL");
693
- _define_property(this, "_unsubscribeFromPort", void 0);
694
- _define_property(this, "_clearOpenInterval", void 0);
695
- this._params = {
696
- timeout: void 0,
697
- streamHandler: void 0,
698
- noHandshake: false,
699
- ...params
700
- };
701
- }
702
- };
703
- _ts_decorate([
704
- synchronized
705
- ], RpcPeer.prototype, "open", null);
706
- var throwIfNotOpen = (state) => {
707
- switch (state) {
708
- case "OPENED": {
709
- return;
710
- }
711
- case "INITIAL": {
712
- throw new RpcNotOpenError();
713
- }
714
- case "CLOSED": {
715
- throw new RpcClosedError();
716
- }
717
- }
718
- };
719
-
720
- // src/service.ts
721
- import { invariant as invariant2 } from "@dxos/invariant";
722
- function _define_property2(obj, key, value) {
723
- if (key in obj) {
724
- Object.defineProperty(obj, key, {
725
- value,
726
- enumerable: true,
727
- configurable: true,
728
- writable: true
729
- });
730
- } else {
731
- obj[key] = value;
732
- }
733
- return obj;
734
- }
735
- var __dxlog_file2 = "/__w/dxos/dxos/packages/core/mesh/rpc/src/service.ts";
736
- var createServiceBundle = (services) => services;
737
- var ProtoRpcPeer = class {
738
- async open() {
739
- await this._peer.open();
740
- }
741
- async close() {
742
- await this._peer.close();
743
- }
744
- async abort() {
745
- await this._peer.abort();
746
- }
747
- constructor(rpc, _peer) {
748
- _define_property2(this, "rpc", void 0);
749
- _define_property2(this, "_peer", void 0);
750
- this.rpc = rpc;
751
- this._peer = _peer;
752
- }
753
- };
754
- var createProtoRpcPeer = ({ requested, exposed, handlers, encodingOptions, ...rest }) => {
755
- const exposedRpcs = {};
756
- if (exposed) {
757
- invariant2(handlers, void 0, {
758
- F: __dxlog_file2,
759
- L: 93,
760
- S: void 0,
761
- A: [
762
- "handlers",
763
- ""
764
- ]
765
- });
766
- for (const serviceName of Object.keys(exposed)) {
767
- const serviceFqn = exposed[serviceName].serviceProto.fullName.slice(1);
768
- const serviceProvider = handlers[serviceName];
769
- exposedRpcs[serviceFqn] = exposed[serviceName].createServer(serviceProvider, encodingOptions);
770
- }
771
- }
772
- const peer = new RpcPeer({
773
- ...rest,
774
- callHandler: (method, request, options) => {
775
- const [serviceName, methodName] = parseMethodName(method);
776
- if (!exposedRpcs[serviceName]) {
777
- throw new Error(`Service not supported: ${serviceName}`);
778
- }
779
- return exposedRpcs[serviceName].call(methodName, request, options);
780
- },
781
- streamHandler: (method, request, options) => {
782
- const [serviceName, methodName] = parseMethodName(method);
783
- if (!exposedRpcs[serviceName]) {
784
- throw new Error(`Service not supported: ${serviceName}`);
785
- }
786
- return exposedRpcs[serviceName].callStream(methodName, request, options);
787
- }
788
- });
789
- const requestedRpcs = {};
790
- if (requested) {
791
- for (const serviceName of Object.keys(requested)) {
792
- const serviceFqn = requested[serviceName].serviceProto.fullName.slice(1);
793
- requestedRpcs[serviceName] = requested[serviceName].createClient({
794
- call: (method, req, options) => peer.call(`${serviceFqn}.${method}`, req, options),
795
- callStream: (method, req, options) => peer.callStream(`${serviceFqn}.${method}`, req, options)
796
- }, encodingOptions);
797
- }
798
- }
799
- return new ProtoRpcPeer(requestedRpcs, peer);
800
- };
801
- var parseMethodName = (method) => {
802
- const separator = method.lastIndexOf(".");
803
- const serviceName = method.slice(0, separator);
804
- const methodName = method.slice(separator + 1);
805
- if (serviceName.length === 0 || methodName.length === 0) {
806
- throw new Error(`Invalid method: ${method}`);
807
- }
808
- return [
809
- serviceName,
810
- methodName
811
- ];
812
- };
813
- var createRpcClient = (serviceDef, options) => {
814
- const peer = new RpcPeer({
815
- ...options,
816
- callHandler: () => {
817
- throw new Error("Requests to client are not supported.");
818
- }
819
- });
820
- const client = serviceDef.createClient({
821
- call: peer.call.bind(peer),
822
- callStream: peer.callStream.bind(peer)
823
- });
824
- return new ProtoRpcPeer(client, peer);
825
- };
826
- var createRpcServer = ({ service, handlers, ...rest }) => {
827
- const server = service.createServer(handlers);
828
- return new RpcPeer({
829
- ...rest,
830
- callHandler: server.call.bind(server),
831
- streamHandler: server.callStream.bind(server)
832
- });
833
- };
834
- var createBundledRpcClient = (descriptors, options) => {
835
- return createProtoRpcPeer({
836
- requested: descriptors,
837
- ...options
838
- });
839
- };
840
- var createBundledRpcServer = ({ services, handlers, ...rest }) => {
841
- const rpc = {};
842
- for (const serviceName of Object.keys(services)) {
843
- const serviceFqn = services[serviceName].serviceProto.fullName.slice(1);
844
- rpc[serviceFqn] = services[serviceName].createServer(handlers[serviceName]);
845
- }
846
- return new RpcPeer({
847
- ...rest,
848
- callHandler: (method, request) => {
849
- const [serviceName, methodName] = parseMethodName(method);
850
- if (!rpc[serviceName]) {
851
- throw new Error(`Service not supported: ${serviceName}`);
852
- }
853
- return rpc[serviceName].call(methodName, request);
854
- },
855
- streamHandler: (method, request) => {
856
- const [serviceName, methodName] = parseMethodName(method);
857
- if (!rpc[serviceName]) {
858
- throw new Error(`Service not supported: ${serviceName}`);
859
- }
860
- return rpc[serviceName].callStream(methodName, request);
861
- }
862
- });
863
- };
864
-
865
- // src/testing.ts
866
- import { isNode } from "@dxos/util";
867
- var createLinkedPorts = ({ delay } = {}) => {
868
- let port1Received;
869
- let port2Received;
870
- const send = (handler, msg) => {
871
- if (delay) {
872
- setTimeout(() => handler?.(msg), delay);
873
- } else {
874
- void handler?.(msg);
875
- }
876
- };
877
- const port1 = {
878
- send: (msg) => send(port2Received, msg),
879
- subscribe: (cb) => {
880
- port1Received = cb;
881
- }
882
- };
883
- const port2 = {
884
- send: (msg) => send(port1Received, msg),
885
- subscribe: (cb) => {
886
- port2Received = cb;
887
- }
888
- };
889
- return [
890
- port1,
891
- port2
892
- ];
893
- };
894
- var encodeMessage = (msg) => isNode() ? Buffer.from(msg) : new TextEncoder().encode(msg);
895
-
896
- // src/trace.ts
897
- import { Event } from "@dxos/async";
898
- import { MessageTrace } from "@dxos/protocols/proto/dxos/rpc";
899
- function _define_property3(obj, key, value) {
900
- if (key in obj) {
901
- Object.defineProperty(obj, key, {
902
- value,
903
- enumerable: true,
904
- configurable: true,
905
- writable: true
906
- });
907
- } else {
908
- obj[key] = value;
909
- }
910
- return obj;
911
- }
912
- var PortTracer = class {
913
- get port() {
914
- return this._port;
915
- }
916
- constructor(_wrappedPort) {
917
- _define_property3(this, "_wrappedPort", void 0);
918
- _define_property3(this, "message", void 0);
919
- _define_property3(this, "_port", void 0);
920
- this._wrappedPort = _wrappedPort;
921
- this.message = new Event();
922
- this._port = {
923
- send: (msg) => {
924
- this.message.emit({
925
- direction: MessageTrace.Direction.OUTGOING,
926
- data: msg
927
- });
928
- return this._wrappedPort.send(msg);
929
- },
930
- subscribe: (cb) => {
931
- return this._wrappedPort.subscribe((msg) => {
932
- this.message.emit({
933
- direction: MessageTrace.Direction.INCOMING,
934
- data: msg
935
- });
936
- cb(msg);
937
- });
938
- }
939
- };
940
- }
941
- };
942
- export {
943
- PortTracer,
944
- ProtoRpcPeer,
945
- RpcPeer,
946
- createBundledRpcClient,
947
- createBundledRpcServer,
948
- createLinkedPorts,
949
- createProtoRpcPeer,
950
- createRpcClient,
951
- createRpcServer,
952
- createServiceBundle,
953
- decodeRpcError,
954
- encodeMessage,
955
- parseMethodName
956
- };
957
- //# sourceMappingURL=index.mjs.map