-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathThirdPartyNotices.txt
More file actions
3859 lines (3034 loc) · 174 KB
/
ThirdPartyNotices.txt
File metadata and controls
3859 lines (3034 loc) · 174 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
GitLens
THIRD-PARTY SOFTWARE NOTICES AND INFORMATION
This project incorporates components from the projects listed below.
1. @eamodio/supertalk-core version 0.0.6 (https://github.com/eamodio/supertalk)
2. @eamodio/supertalk-signals version 0.0.6 (https://github.com/eamodio/supertalk)
3. @eamodio/supertalk version 0.0.7 (https://github.com/eamodio/supertalk)
4. @gitlens/ai version 0.0.1 (undefined)
5. @gitlens/git-cli version 0.0.1 (undefined)
6. @gitlens/git-github version 0.0.1 (undefined)
7. @gitlens/git version 0.0.1 (undefined)
8. @lit-labs/signals version 0.2.0 (https://github.com/lit/lit)
9. @lit-labs/virtualizer version 2.1.1 (https://github.com/lit/lit)
10. @lit/context version 1.1.6 (https://github.com/lit/lit)
11. @lit/react version 1.0.8 (https://github.com/lit/lit)
12. @lit/task version 1.0.3 (https://github.com/lit/lit)
13. @octokit/graphql version 9.0.3 (https://github.com/octokit/graphql.js)
14. @octokit/request-error version 7.1.0 (https://github.com/octokit/request-error.js)
15. @octokit/request version 10.0.8 (https://github.com/octokit/request.js)
16. @octokit/types version 16.0.0 (https://github.com/octokit/types.ts)
17. @opentelemetry/api version 1.9.1 (https://github.com/open-telemetry/opentelemetry-js)
18. @opentelemetry/exporter-trace-otlp-http version 0.215.0 (https://github.com/open-telemetry/opentelemetry-js)
19. @opentelemetry/resources version 2.7.0 (https://github.com/open-telemetry/opentelemetry-js)
20. @opentelemetry/sdk-trace-base version 2.7.0 (https://github.com/open-telemetry/opentelemetry-js)
21. @opentelemetry/semantic-conventions version 1.40.0 (https://github.com/open-telemetry/opentelemetry-js)
22. @shoelace-style/shoelace version 2.20.1 (https://github.com/shoelace-style/shoelace)
23. @vscode/codicons version 0.0.45 (https://github.com/microsoft/vscode-codicons)
24. billboard.js version 3.18.0 (https://github.com/naver/billboard.js)
25. diff2html version 3.4.56 (https://github.com/rtfpessoa/diff2html)
26. dragula version 3.7.3 (https://github.com/bevacqua/dragula)
27. driver.js version 1.4.0 (https://github.com/kamranahmedse/driver.js)
28. fflate version 0.8.2 (https://github.com/101arrowz/fflate)
29. ignore version 7.0.5 (https://github.com/kaelzhang/node-ignore)
30. lit version 3.3.2 (https://github.com/lit/lit)
31. marked version 18.0.2 (https://github.com/markedjs/marked)
32. microsoft/vscode (https://github.com/microsoft/vscode)
33. os-browserify version 0.3.0 (https://github.com/CoderPuppy/os-browserify)
34. path-browserify version 1.0.1 (https://github.com/browserify/path-browserify)
35. react-dom version 19.2.5 (https://github.com/facebook/react)
36. react version 19.2.5 (https://github.com/facebook/react)
37. signal-polyfill version 0.2.2 (https://github.com/proposal-signals/signal-polyfill)
38. signal-utils version 0.21.1 (https://github.com/proposal-signals/signal-utils)
39. slug version 11.0.1 (https://github.com/Trott/slug)
40. sortablejs version 1.15.7 (https://github.com/SortableJS/Sortable)
41. vscode-uri version 3.1.0 (https://github.com/microsoft/vscode-uri)
%% @eamodio/supertalk-core NOTICES AND INFORMATION BEGIN HERE
=========================================
# @supertalk/core
[](https://github.com/eamodio/supertalk/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@eamodio/supertalk-core)
[](https://opensource.org/licenses/MIT)
> [!WARNING]
> This is a pre-release package under active development. APIs may change without
> notice between versions.
A type-safe, unified communication library for Web Workers, Iframes, and Node.js
worker threads.
## Overview
**Supertalk turns workers' low-level message passing into a high-level,
type-safe RPC layer—so you can call methods, pass callbacks, and await promises
as if they were local.**
Supertalk is built to be a joy to use and deploy:
- **Type-safe:** Your IDE knows exactly what's proxied vs cloned
- **Ergonomic:** Callbacks, promises, and classes just work
- **Bidirectional:** The same types and patterns work in both directions
- **Fast & small:** ~2.4 kB brotli-compressed, zero dependencies
- **Composable & extendable:** Non-global configuration, nested objects,
services are just classes, composable transport handlers
- **Standard modules:** Some people call them "ESM". We don't publish CJS.
- **Modern JavaScript:** Published as ES2024, targeting current browsers and
Node.js 20+
## Installation
```bash
npm install @supertalk/core
```
## Quick Start
`worker.ts` (exposed side):
```ts
import {expose} from '@supertalk/core';
const service = {
add(a: number, b: number): number {
return a + b;
},
async fetchData(url: string): Promise<string> {
const res = await fetch(url);
return res.text();
},
};
expose(service, self);
```
`main.ts` (wrapped side):
```ts
import {wrap} from '@supertalk/core';
const worker = new Worker('./worker.ts');
const remote = await wrap<typeof service>(worker);
// Methods become async
const result = await remote.add(1, 2); // 3
```
## Core Features
### Automatic proxying of functions and promises
Functions and promises passed as **top-level arguments or return values** are
always proxied:
```ts
// Exposed side
const service = {
forEach(items: number[], callback: (item: number) => void) {
for (const item of items) {
callback(item); // Calls back to wrapped side
}
},
};
```
```ts
// Wrapped side
await remote.forEach([1, 2, 3], (item) => {
console.log(item); // Runs locally
});
```
All functions are transformed into promise-returning async functions on the
wrapped side. Proxies are released from memory when they're no longer in use by
the wrapped side.
### Object proxying with `proxy()`
Objects are cloned by default. This works well for immutable data objects, but
not for all cases. The `proxy()` function marks an object as needing to be
proxied instead of cloned.
**Use `proxy()` when returning:**
1. **Mutable objects** — The remote side should see updates
2. **Large graphs** — Avoid cloning expensive data structures
3. **Class instances with methods** — Preserve the prototype API
`worker.ts`:
```ts
import {expose, proxy} from '@supertalk/core';
export class Widget {
count = 42;
sayHello() {
return 'hello';
}
}
expose(
{
createWidget() {
return proxy(new Widget()); // Explicitly proxied
},
},
self,
);
```
`main.ts`:
```ts
const service = await wrap(worker);
const widget = await service.createWidget();
// The proxy provides async access to properties and methods
const count = await widget.count;
const hello = await widget.sayHello();
```
### Opaque Handles with `handle()`
When you need to pass a reference without exposing any remote interface, use
`handle()`. Handles are opaque tokens — they can be passed around and back, but
provide no way to access properties or methods remotely.
```ts
import {expose, handle, getHandleValue} from '@supertalk/core';
class Session {
constructor(public id: string) {}
}
const service = {
createSession(id: string) {
return handle(new Session(id)); // Opaque handle
},
getSessionId(session: Handle<Session>) {
// Extract the value on the owning side
return getHandleValue(session).id;
},
};
```
```ts
// Client side
const session = await remote.createSession('abc'); // Handle<Session>
// session is opaque — no property access
const id = await remote.getSessionId(session); // Pass it back
```
### Extracting Values from Proxies and Handles
Both `proxy()` and `handle()` create wrappers that work the same on both sides.
On the side that created the proxy/handle, you can extract the underlying value:
```ts
import {proxy, getProxyValue, handle, getHandleValue} from '@supertalk/core';
const service = {
// Return a proxied widget
createWidget() {
return proxy(new Widget());
},
// Accept a proxy and extract its value
updateWidget(widget: AsyncProxy<Widget>) {
const w = getProxyValue(widget); // Only works on owning side
w.refresh();
},
// Same pattern works for handles
processSession(session: Handle<Session>) {
const s = getHandleValue(session);
return s.data;
},
};
```
### Nested Objects & Proxies
Supertalk supports two modes for handling nested values:
- **Shallow mode** (default): Maximum performance, only top-level function
arguments and return values are proxied. Nested functions/promises fail with
`DataCloneError`.
- **Nested mode** (`nestedProxies: true`): Full payload traversal. Functions and
promises anywhere in the graph are auto-proxied.
```ts
// On exposed side
expose(service, self, {nestedProxies: true});
const service = {
getData() {
return {
process: (x) => x * 2, // auto-proxied (function)
widget: proxy(new Widget()), // explicitly proxied (class)
};
},
};
// On wrapped side
const remote = await wrap<typeof service>(worker, {nestedProxies: true});
const data = await remote.getData();
await data.process(5); // 10
```
### Transferables with `transfer()`
Use `transfer()` to mark values like `ArrayBuffer`, `MessagePort`, or streams to
be transferred rather than cloned.
```ts
import {transfer} from '@supertalk/core';
const service = {
getBuffer(): ArrayBuffer {
const buf = new ArrayBuffer(1024);
return transfer(buf); // Zero-copy transfer
},
};
```
### Value Handling Reference
When values cross the communication boundary:
| Value Type | Shallow Mode | Nested Mode |
| ------------------------------------------------ | -------------- | -------------- |
| Primitives | ✅ Cloned | ✅ Cloned |
| Plain objects `{...}` | ✅ Cloned | ✅ Cloned |
| Arrays | ✅ Cloned | ✅ Cloned |
| Functions (top-level) | 🛜 Proxied | 🛜 Proxied |
| Functions (nested) | ❌ Error | 🛜 Proxied |
| Promises (top-level return) | 🛜 Proxied | 🛜 Proxied |
| Promises (nested) | ❌ Error | 🛜 Proxied |
| `proxy()` wrapped values (top-level) | 🛜 Proxied | 🛜 Proxied |
| `proxy()` wrapped values (nested) | ❌ Error | 🛜 Proxied |
| `handle()` wrapped values (top-level) | 🔒 Handle | 🔒 Handle |
| `handle()` wrapped values (nested) | ❌ Error | 🔒 Handle |
| `transfer()` wrapped values (top-level) | 📦 Transferred | 📦 Transferred |
| `transfer()` wrapped values (nested) | ❌ Error | 📦 Transferred |
| Class instances & objects with custom prototypes | ⚠️ Cloned\* | ⚠️ Cloned\* |
| Other structured cloneable objects | ✅ Cloned | ✅ Cloned |
\* _Class instances are cloned via structured clone (losing methods) unless
wrapped in `proxy()`._
## API Reference
### Core Functions
#### `expose(target, endpoint, options?)`
Exposes an object or function to the other side.
- `target`: The service object or function to expose.
- `endpoint`: The `Worker`, `MessagePort`, `Window`, or compatible interface.
- `options`: Connection options (see below).
#### `wrap<T>(endpoint, options?)`
Connects to an exposed service and returns a proxy.
- `endpoint`: The `Worker`, `MessagePort`, `Window`, or compatible interface.
- `options`: Connection options (see below).
- Returns: `Promise<Remote<T>>`
#### `proxy(value)`
Marks an object to be proxied rather than cloned. Returns an `AsyncProxy<T>`
that provides async access on both sides. Use this for:
- Class instances with methods
- Mutable objects that should be shared
- Large objects to avoid cloning costs
#### `handle(value)`
Marks an object as an opaque handle. Returns a `Handle<T>` that can be passed
around but provides no remote interface. Use this for:
- Session tokens or identifiers
- References to expensive objects
- Graph nodes where you don't want to expose internals
#### `getProxyValue(proxy)` / `getHandleValue(handle)`
Extracts the underlying value from an `AsyncProxy` or `Handle`. Only works on
the side that created the proxy/handle — throws `TypeError` on the remote side.
#### `transfer(value, transferables?)`
Marks a value to be transferred (zero-copy) rather than cloned.
- `value`: The value to send (e.g. `ArrayBuffer`, `MessagePort`).
- `transferables`: Optional array of transferables. If omitted, `value` is assumed to be the transferable.
### Options
```ts
interface Options {
/** Enable nested proxy handling (default: false) */
nestedProxies?: boolean;
/**
* Enable debug mode for better error messages.
* Throws NonCloneableError with the exact path for nested functions,
* promises, proxy() markers, and transfer() markers that would fail
* without nestedProxies: true.
*/
debug?: boolean;
/** Custom handlers for serializing/deserializing specific types */
handlers?: Array<Handler>;
}
```
### Handlers
Handlers provide pluggable serialization for custom types or streams.
**Stream Handler Example:**
```ts
import {streamHandler} from '@supertalk/core/handlers/streams.js';
expose(service, self, {handlers: [streamHandler]});
const remote = await wrap<typeof service>(worker, {handlers: [streamHandler]});
```
**Custom Handlers:**
Handlers let you control how specific types are serialized. Each handler implements:
- `wireType` — Unique identifier (e.g., `'app:my-type'`)
- `canHandle(value)` — Returns `true` if this handler should process the value
- `toWire(value, ctx)` — Serialize the value, using `ctx.toWire()` for nested values
- `fromWire(wire, ctx)` — Deserialize, using `ctx.fromWire()` for nested values
```ts
import {WIRE_TYPE, type Handler} from '@supertalk/core';
// Handler that clones Maps by converting to/from arrays
const mapHandler: Handler<Map<unknown, unknown>, {entries: unknown[]}> = {
wireType: 'app:map',
canHandle: (v): v is Map<unknown, unknown> => v instanceof Map,
toWire(map, ctx) {
return {
[WIRE_TYPE]: 'app:map',
entries: [...map.entries()].map(([k, v]) => [
ctx.toWire(k),
ctx.toWire(v),
]),
};
},
fromWire(wire, ctx) {
return new Map(
wire.entries.map(([k, v]) => [ctx.fromWire(k), ctx.fromWire(v)]),
);
},
};
```
**Subscription Handlers:**
For handlers that need to send updates outside of RPC calls (like signals or observables), the handler lifecycle provides messaging support:
- `connect(ctx)` — Called when attached; provides `ctx.sendMessage()` for sending updates
- `onMessage(payload)` — Called when a message arrives for this handler's wireType
- `disconnect()` — Called when the connection closes; clean up resources
See [@supertalk/signals](../signals) for a complete example.
### TypeScript Types
#### `Remote<T>`
The primary type for service proxies returned by `wrap()`. Transforms all
methods to async and properties to `Promise<T>`.
```ts
const remote = await wrap<MyService>(worker);
// remote has type Remote<MyService>
```
#### `AsyncProxy<T>`
The unified proxy type returned by `proxy()`. Works the same on both sides of a
connection — the remote side gets async access to properties and methods, while
the owning side can extract the underlying value with `getProxyValue()`.
```ts
// Service returns an AsyncProxy
createWidget(): AsyncProxy<Widget> {
return proxy(new Widget());
}
// Client receives the same type
const widget = await remote.createWidget(); // AsyncProxy<Widget>
await widget.name; // Property access is async
await widget.activate(); // Method calls are async
```
#### `Handle<T>`
An opaque reference type returned by `handle()`. Provides no remote interface —
useful for session tokens, expensive objects, or graph nodes that shouldn't
expose their internals.
```ts
// Service returns a Handle
createSession(): Handle<Session> {
return handle(new Session());
}
// Client can only pass it back
const session = await remote.createSession(); // Handle<Session>
// session.foo — not allowed, handles are opaque
await remote.useSession(session); // Pass it back
```
## Advanced Usage
### Debugging
Debugging `DataCloneError` can be tricky. Supertalk provides a `debug` option
that traverses your data before sending and throws a `NonCloneableError` with
the exact path to the problematic value.
```ts
const remote = await wrap<Service>(endpoint, {debug: true});
```
### Memory Management
Proxied objects are tracked with registries on both sides.
- **Source side**: Holds strong references until released.
- **Consumer side**: Holds weak references; when GC'd, notifies source to
release.
### Node.js Worker Threads
For Node.js `worker_threads`, use the `nodeEndpoint` adapter to convert the
Node-style event API (`on`/`off`) to the browser-style API
(`addEventListener`/`removeEventListener`).
**main.ts:**
```ts
import {wrap} from '@supertalk/core';
import {nodeEndpoint} from '@supertalk/core/node.js';
import {Worker} from 'node:worker_threads';
const worker = new Worker('./worker.js');
const remote = await wrap<MyService>(nodeEndpoint(worker));
const result = await remote.add(1, 2);
worker.terminate();
```
**worker.ts:**
```ts
import {expose} from '@supertalk/core';
import {parentPort} from 'node:worker_threads';
const service = {
add(a: number, b: number) {
return a + b;
},
};
// parentPort is a MessagePort which has addEventListener/removeEventListener
expose(service, parentPort!);
```
## Benchmarks
Supertalk vs Comlink vs Supertalk with `nestedProxies: true`, measured in
ops/sec (higher is better). Node.js `worker_threads` with `MessageChannel`.
| Benchmark | Supertalk | Comlink | ST vs Comlink | Supertalk w/ <br> nestedProxies | nested vs <br> shallow |
| ---------------------------- | --------: | ------: | ------------: | ------------------------------: | ---------------------: |
| Simple String Echo | 168,597 | 94,543 | 1.78x | 173,684 | 1.03x |
| Multiple Arguments (4 nums) | 163,503 | 84,546 | 1.93x | 163,420 | 1x |
| Large Object (~10KB) | 26,257 | 23,714 | 1.11x | 12,886 | 0.49x |
| Large Array (10,000 items) | 313 | 309 | 1.01x | 163 | 0.52x |
| Callback (proxy function) | 3,742 | 3,469 | 1.08x | 3,607 | 0.96x |
| Multiple Callbacks (3 funcs) | 1,748 | 1,576 | 1.11x | 1,856 | 1.06x |
| Rapid Sequential (20x burst) | 190,164 | 103,191 | 1.84x | 179,378 | 0.94x |
**Notes:**
- Supertalk appears to have lower per-call and per-object overhead, which makes
it faster in the multiple call and multiple argument cases, and similar in the
one large object or array cases.
- For simple calls and bursts, Supertalk is ~1.8-1.9x faster than Comlink
- `nestedProxies` mode adds traversal overhead for large payloads. The
performance impact ranges from negligible for small objects to 2x slower for
large graphs and arrays.
- Run the benchmarks with: `npm run bench -w @supertalk/core`
## Background
### Why Supertalk?
Workers are great for offloading work, but the raw `postMessage` API is
difficult:
- No built-in request/response (one-way only)
- No error propagation
- No functions or promises (DataCloneError)
- Manual lifetime management
- Manual transfer lists
Supertalk handles all of this: RPC layer, transparent proxying, automatic
lifetime management, and deep traversal.
### Comparison to Comlink
Supertalk is inspired by Comlink but differs in key ways:
- **Automatic proxying:** Functions/promises are auto-proxied.
- **Nested support:** `nestedProxies` mode allows proxies anywhere in the
payload.
- **Debug mode:** Reports exactly where non-serializable values are.
- **Symmetric:** Both ends use the same `Connection` class.
- **No MessagePorts:** Uses the worker/window directly, making it lighter.
## License
MIT
=========================================
END OF @eamodio/supertalk-core NOTICES AND INFORMATION
%% @eamodio/supertalk-signals NOTICES AND INFORMATION BEGIN HERE
=========================================
# @supertalk/signals
[](https://github.com/eamodio/supertalk/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@eamodio/supertalk-signals)
[](https://opensource.org/licenses/MIT)
> [!WARNING]
> This is a pre-release package under active development. APIs may change without
> notice between versions.
TC39 Signals integration for Supertalk. Synchronize reactive state across
workers with automatic batched updates.
## Features
- **Reactive across boundaries:** Signals on the sender side become
`RemoteSignal`s on the receiver that trigger local effects
- **Synchronous reads:** Initial values are available immediately via `get()`
- **Batched updates:** Multiple signal changes are coalesced into a single
message
- **Lazy watching:** Source signals are only watched when the receiver observes
reactively, respecting `[Signal.subtle.watched]` callbacks
- **Works with `Signal.State` and `Signal.Computed`**
- **Modern JavaScript:** Published as ES2024, targeting current browsers and
Node.js 20+
## Installation
```bash
npm install @supertalk/signals signal-polyfill
```
> **Note:** This package requires `signal-polyfill` for the TC39 Signals API.
## Quick Start
**worker.ts** (exposed side):
```ts
import {expose} from '@supertalk/core';
import {Signal} from 'signal-polyfill';
import {SignalHandler} from '@supertalk/signals';
const count = new Signal.State(0);
const doubled = new Signal.Computed(() => count.get() * 2);
const service = {
getCount: () => count,
getDoubled: () => doubled,
increment: () => count.set(count.get() + 1),
};
expose(service, self, {handlers: [new SignalHandler()]});
```
**main.ts** (wrapped side):
```ts
import {wrap} from '@supertalk/core';
import {Signal} from 'signal-polyfill';
import {SignalHandler} from '@supertalk/signals';
const worker = new Worker('./worker.ts');
const remote = await wrap<typeof service>(worker, {
handlers: [new SignalHandler()],
});
// Get the remote signal (initial value available synchronously)
const count = await remote.getCount();
console.log(count.get()); // 0
// Set up reactive observation with a Watcher
const watcher = new Signal.subtle.Watcher(() => {
// Handle updates
});
const quadrupled = new Signal.Computed(() => count.get() * 4);
watcher.watch(quadrupled);
quadrupled.get(); // Establish the subscription chain
// Mutate on worker side
await remote.increment();
// After microtask, updates propagate (because watcher is watching quadrupled)
console.log(count.get()); // 1
console.log(quadrupled.get()); // 4
```
## API
### `SignalHandler`
Coordinates signal synchronization across a connection. Create one per endpoint.
```ts
const signalHandler = new SignalHandler(options);
// Options:
interface SignalHandlerOptions {
/**
* Whether to automatically watch signals when sent (default: false).
*
* - false: Lazy watching. Signals are only watched when the receiver
* observes them reactively. Respects [Signal.subtle.watched] callbacks.
*
* - true: Eager watching. Signals are watched immediately when sent.
* Updates always flow regardless of whether receiver is observing.
*/
autoWatch?: boolean;
}
```
#### Lazy vs Eager Watching
By default (`autoWatch: false`), signals are watched lazily:
```ts
// Sender has a signal with a watched callback
const data = new Signal.State(initialData, {
[Signal.subtle.watched]: () => startExpensiveDataFetch(),
[Signal.subtle.unwatched]: () => stopExpensiveDataFetch(),
});
// Sending the signal does NOT trigger the watched callback
const remoteData = await remote.getData();
// Only when something observes the RemoteSignal reactively...
const computed = new Signal.Computed(() => remoteData.get());
// ...does the sender start watching (and the callback fires)
```
Use `autoWatch: true` when you want updates to always flow:
```ts
const signalHandler = new SignalHandler({autoWatch: true});
```
### `RemoteSignal<T>`
A read-only signal that receives updates from the sender side. You don't create
these directly—they're returned when you access a signal property on a remote
service.
```ts
const count = await remote.getCount(); // RemoteSignal<number>
count.get(); // Read current value (reactive)
count.set(42); // Throws! RemoteSignals are read-only
```
RemoteSignals integrate with the TC39 Signals reactivity system:
```ts
import {Signal} from 'signal-polyfill';
// Local computeds can depend on remote signals
const doubled = new Signal.Computed(() => count.get() * 2);
// Effects track remote signals too
const watcher = new Signal.subtle.Watcher(() => {
console.log('count changed!');
});
watcher.watch(new Signal.Computed(() => count.get()));
```
## How It Works
1. When a `Signal.State` or `Signal.Computed` is sent across the boundary, the
`SignalHandler` assigns it an ID and sends the current value
2. The receiver creates a `RemoteSignal` with that initial value
3. When something observes the `RemoteSignal` reactively, a watch message is
sent to the sender
4. The sender starts monitoring the signal for changes via a `Watcher`
5. When signals change, updates are batched via `queueMicrotask` and sent as a
single message
6. When the receiver stops observing, an unwatch message is sent and the sender
stops monitoring
With `autoWatch: true`, steps 3-4 happen immediately when the signal is sent.
## Limitations
- **One-way sync:** Signals flow from sender to receiver. `RemoteSignal`s are
read-only.
- **Requires handler on both sides:** Both `expose()` and `wrap()` need a
`SignalHandler` in their handlers array.
- **Lazy watching requires reactive observation:** With the default
`autoWatch: false`, calling `.get()` outside a reactive context (computed,
effect, watcher) won't trigger updates. Use `autoWatch: true` if you need
updates without reactive observation.
=========================================
END OF @eamodio/supertalk-signals NOTICES AND INFORMATION
%% @eamodio/supertalk NOTICES AND INFORMATION BEGIN HERE
=========================================
# Supertalk
[](https://github.com/eamodio/supertalk/actions/workflows/ci.yml)
[](https://www.npmjs.com/package/@eamodio/supertalk)
[](https://opensource.org/licenses/MIT)
> [!WARNING]
> This is a pre-release package under active development. APIs may change without
> notice between versions.
A type-safe, unified communication library for Web Workers, Iframes, and Node.js
worker threads.
**Supertalk turns workers' low-level message passing into a high-level,
type-safe RPC layer—so you can call methods, pass callbacks, and await promises
as if they were local.**
Supertalk is built to be a joy to use and deploy:
- **Type-safe:** Your IDE knows exactly what's proxied vs cloned
- **Ergonomic:** Callbacks, promises, and classes just work
- **Bidirectional:** The same types and patterns work in both directions
- **Fast & small:** ~2.4 kB brotli-compressed, zero dependencies
- **Composable & extendable:** Non-global configuration, nested objects,
services are just classes, composable transport handlers
- **Standard modules:** ESM-only, no CommonJS
- **Modern JavaScript:** Published as ES2024, targeting current browsers and
Node.js 20+
## Installation
```bash
npm install supertalk
```
This package re-exports `@supertalk/core`. As additional packages are added to
the Supertalk ecosystem, they may be included here as well.
## Quick Start
**worker.ts** (exposed side):
```ts
import {expose} from 'supertalk';
const service = {
add(a: number, b: number): number {
return a + b;
},
async fetchData(url: string): Promise<string> {
const res = await fetch(url);
return res.text();
},
};
expose(service, self);
```
**main.ts** (wrapped side):
```ts
import {wrap} from 'supertalk';
const worker = new Worker('./worker.ts');
const remote = await wrap<typeof service>(worker);
// Methods become async
const result = await remote.add(1, 2); // 3
```
## Core Concepts
### Requests and Responses
Most cross-worker communication follows a request/response pattern, but
`postMessage()` only sends one-way messages. Matching responses to requests is
left as an exercise to the developer. Supertalk builds a request/response
protocol on top of `postMessage()`, so you can call methods and await results
naturally.
### Clones vs Proxies
`postMessage()` copies payloads via the structured clone algorithm, which only
supports a limited set of types. Functions are completely unsupported, and class
instances lose their prototypes—so things like Promises don't survive the trip.
Supertalk addresses this by _proxying_ values that can't be cloned. A proxied
object stays on its original side; the other side gets a lightweight proxy that
forwards calls back. This is how functions, promises, and class instances work
across the message boundary.
### Shallow vs Deep Proxying
By default, Supertalk only proxies objects passed directly to or returned from
method calls. This keeps messages fast. If you need proxies nested anywhere in a
payload, set `nestedProxies: true` to traverse the full object graph.
## Core Features
### Automatic proxying of functions and promises
Functions and promises passed as **top-level arguments or return values** are
always proxied:
```ts
// Exposed side
const service = {
forEach(items: number[], callback: (item: number) => void) {
for (const item of items) {
callback(item); // Calls back to wrapped side
}
},
};
```
```ts
// Wrapped side
await remote.forEach([1, 2, 3], (item) => {
console.log(item); // Runs locally
});
```
All functions are transformed into promise-returning async functions on the
wrapped side. Proxies are released from memory when they're no longer in use by
the wrapped side.
### Object proxying with `proxy()`
Objects are cloned by default. This works well for immutable data objects, but
not for all cases. The `proxy()` function marks an object as needing to be
proxied instead of cloned.
**Use `proxy()` when returning:**
1. **Mutable objects** — The remote side should see updates
2. **Large graphs** — Avoid cloning expensive data structures
3. **Class instances with methods** — Preserve the prototype API
`worker.ts`:
```ts
import {expose, proxy} from 'supertalk';
export class Widget {
count = 42;
sayHello() {
return 'hello';
}
}
expose(
{
createWidget() {
return proxy(new Widget()); // Explicitly proxied
},
},
self,
);
```
`main.ts`:
```ts
const service = await wrap(worker);
const widget = await service.createWidget();
// The proxy provides async access to properties and methods
const count = await widget.count;
const hello = await widget.sayHello();
```
### Opaque Handles with `handle()`
When you need to pass a reference without exposing any remote interface, use
`handle()`. Handles are opaque tokens — they can be passed around and back, but
provide no way to access properties or methods remotely.
```ts
import {expose, handle, getHandleValue, type Handle} from 'supertalk';
class Session {
constructor(public id: string) {}
}
const service = {
createSession(id: string) {
return handle(new Session(id)); // Opaque handle
},
getSessionId(session: Handle<Session>) {
// Extract the value on the owning side
return getHandleValue(session).id;
},