@xconnio/xconn 0.0.0-stage → 0.6.2

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 (54) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/LICENSE +22 -0
  3. package/README.md +281 -2
  4. package/dist/auth.d.ts +51 -0
  5. package/dist/auth.js +57 -0
  6. package/dist/call.d.ts +38 -0
  7. package/dist/call.js +146 -0
  8. package/dist/client.d.ts +21 -0
  9. package/dist/client.js +62 -0
  10. package/dist/constants.d.ts +60 -0
  11. package/dist/constants.js +61 -0
  12. package/dist/crypto.d.ts +9 -0
  13. package/dist/crypto.js +25 -0
  14. package/dist/discovery.d.ts +20 -0
  15. package/dist/discovery.js +25 -0
  16. package/dist/exception.d.ts +12 -0
  17. package/dist/exception.js +28 -0
  18. package/dist/inbox.d.ts +14 -0
  19. package/dist/inbox.js +71 -0
  20. package/dist/index.d.ts +26 -0
  21. package/dist/index.js +15 -0
  22. package/dist/message.d.ts +33 -0
  23. package/dist/message.js +59 -0
  24. package/dist/native.d.ts +6 -0
  25. package/dist/native.js +35 -0
  26. package/dist/package.json +1 -0
  27. package/dist/payload.d.ts +48 -0
  28. package/dist/payload.js +314 -0
  29. package/dist/peer.d.ts +16 -0
  30. package/dist/peer.js +124 -0
  31. package/dist/requests.d.ts +57 -0
  32. package/dist/requests.js +121 -0
  33. package/dist/rpc-streams.d.ts +13 -0
  34. package/dist/rpc-streams.js +31 -0
  35. package/dist/serializers.d.ts +29 -0
  36. package/dist/serializers.js +44 -0
  37. package/dist/session.d.ts +67 -0
  38. package/dist/session.js +528 -0
  39. package/dist/toolchain.txt +3 -0
  40. package/dist/transport.d.ts +47 -0
  41. package/dist/transport.js +201 -0
  42. package/dist/types.d.ts +70 -0
  43. package/dist/types.js +140 -0
  44. package/dist/util.d.ts +2 -0
  45. package/dist/util.js +20 -0
  46. package/dist/wasm/xconn_browser.d.ts +176 -0
  47. package/dist/wasm/xconn_browser.js +1467 -0
  48. package/dist/wasm/xconn_browser_bg.wasm +0 -0
  49. package/dist/wasm/xconn_browser_bg.wasm.d.ts +53 -0
  50. package/dist/webrtc.d.ts +98 -0
  51. package/dist/webrtc.js +712 -0
  52. package/dist/webtransport.d.ts +31 -0
  53. package/dist/webtransport.js +242 -0
  54. package/package.json +48 -4
package/CHANGELOG.md ADDED
@@ -0,0 +1,33 @@
1
+ # Changelog
2
+
3
+ ## 0.6.2
4
+
5
+ ## 0.6.0
6
+
7
+ - Rename the package to `@xconnio/xconn`.
8
+
9
+ ## 0.1.6
10
+
11
+ ## 0.1.5
12
+
13
+ - RPC-associated byte streams over WebTransport and WebRTC, with indexed stream access.
14
+ - Publish the tested npm package from the shared XConn release tag.
15
+
16
+ ## 0.1.2
17
+
18
+ - Allow WebRTC WAMP responses up to 16 MiB and advertise that receive limit
19
+ during negotiation, preventing disconnects on multi-megabyte results.
20
+ - Keep peer send limits and bounded receive assembly enforced.
21
+
22
+ ## 0.1.1
23
+
24
+ - Fix browser ICE candidate signaling arguments being sent as a nested array,
25
+ preventing the backend from receiving trickled candidates for NAT traversal.
26
+
27
+ ## 0.1.0
28
+
29
+ - Initial browser WAMP client backed by the Rust protocol engine.
30
+ - Fluent RPC and publish/subscribe APIs, including progressive calls and results.
31
+ - JSON, CBOR and MessagePack codecs with WAMP authentication and packet crypto.
32
+ - Browser WebRTC and WebTransport connections using browser networking APIs.
33
+ - Bundled WebAssembly and TypeScript declarations; no runtime npm dependencies.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright XConnIO Ltd.
4
+ Copyright 2024-2025 Simple Things Inc.
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,3 +1,282 @@
1
- # Temporary Holding Version
1
+ # XConn browser client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A fluent browser WAMP client backed by Rust/WASM. Rust owns joining,
4
+ authentication, IDs, message layouts/validation and JSON/CBOR/MessagePack.
5
+ TypeScript owns browser WebSocket IO, Promises, request correlation, callbacks,
6
+ cancellation and session lifecycle. There are no npm runtime dependencies.
7
+
8
+ This package provides WebSocket/WSS clients and direct WebRTC/WebTransport
9
+ connections through browser APIs. Tokio, native networking, router algorithms
10
+ and C FFI are not shipped to browsers.
11
+
12
+ ## Use
13
+
14
+ ```js
15
+ import { connectAnonymous, Result } from "@xconnio/xconn";
16
+
17
+ const session = await connectAnonymous("ws://localhost:8080/ws", "realm1");
18
+ try {
19
+ const registration = await session
20
+ .register("com.example.echo", invocation => new Result(invocation.args, invocation.kwargs))
21
+ .execute();
22
+
23
+ const result = await session.call("com.example.echo").arg("hello").execute();
24
+ console.log(result.argString(0));
25
+
26
+ const subscription = await session
27
+ .subscribe("com.example.news", event => console.log(event.argString(0)))
28
+ .execute();
29
+
30
+ await session.publish("com.example.news")
31
+ .arg("Hello").acknowledge().excludeMe(false).execute();
32
+
33
+ await subscription.unsubscribe();
34
+ await registration.unregister();
35
+ } finally {
36
+ await session.close();
37
+ }
38
+ ```
39
+
40
+ `call`, `register`, `subscribe` and `publish` create inert request builders.
41
+ `execute()` sends the operation and returns a Promise. There are no parallel
42
+ `callRequest`/`registerRequest`/`subscribeRequest`/`publishRequest` entry points.
43
+ This is a fresh fluent API, not a drop-in replacement for positional xconn-js
44
+ session methods. Common connect/authentication helpers retain their names.
45
+
46
+ Builders offer `.option(key, value)` / `.options(object)`. Call and publication
47
+ builders also offer `.arg(value)`, `.args(...values)`, `.kwarg(key, value)` and
48
+ `.kwargs(object)`. Register/subscribe offer `.match(value)`, registration adds
49
+ `.invoke(value)`, and publication adds `.acknowledge()` / `.excludeMe(value)`.
50
+
51
+ ```js
52
+ import { Client, JSONSerializer, TicketAuthenticator } from "@xconnio/xconn";
53
+ const client = new Client({
54
+ serializer: new JSONSerializer(),
55
+ authenticator: new TicketAuthenticator("alice", "secret", {}),
56
+ connectTimeout: 20_000,
57
+ closeTimeout: 10_000,
58
+ });
59
+ const session = await client.connect("wss://example.com/ws", "realm1");
60
+ ```
61
+
62
+ Connections initialize WASM automatically. Direct synchronous codecs/auth metadata
63
+ and manually constructed Session objects require `await initializeWasm()` first.
64
+ Full builds default to CBOR; JSON-only builds default to JSON. Keep the generated
65
+ WASM asset beside `dist/wasm/xconn_browser.js`, or supply its URL explicitly to
66
+ `initializeWasm(wasmURL)`. Serve WASM as `application/wasm`. Use WSS on HTTPS pages.
67
+
68
+ The package is modern ESM with TypeScript declarations. Binary codecs preserve
69
+ Uint8Array and 64-bit BigInt values. Node 24's global WebSocket can run the same
70
+ client with WASM initialized explicitly from a file buffer.
71
+
72
+ ## Cancellation and progressive results
73
+
74
+ ```js
75
+ const controller = new AbortController();
76
+ const call = await session.call("com.example.long_task")
77
+ .timeout(30_000)
78
+ .signal(controller.signal)
79
+ .stream();
80
+ try {
81
+ for await (const result of call.results()) {
82
+ console.log(result.args, result.progress);
83
+ }
84
+ } finally {
85
+ await call.close();
86
+ }
87
+ ```
88
+
89
+ Register handlers may use `await invocation.sendProgress(args, kwargs)` when the
90
+ caller requests progressive results. `invocation.signal` observes cancellation.
91
+ Use `.stream({ progressiveInput: true })` to send additional chunks with
92
+ `call.send(args, kwargs)` and close input with `call.finish(args, kwargs)`. Receive
93
+ results concurrently for long producers. Existing callback helpers remain available.
94
+
95
+ Connect timeout defaults to 20 seconds and covers WASM initialization, socket
96
+ connection and authentication. Close timeout defaults to 10 seconds. Calls have
97
+ no implicit local timeout; `.timeout(milliseconds)` adds one. Zero disables the
98
+ corresponding local deadline. WAMP `.option("timeout", value)` is a distinct
99
+ router-side option.
100
+
101
+ Pending requests reject on disconnect. `session.onDisconnect(callback)` runs once;
102
+ `session.onError(callback)` observes asynchronous handler failures. Close is
103
+ idempotent. Custom base sessions extend `BaseSession` and use the raw send/receive
104
+ interface; custom serializers/authenticators retain structural interfaces. The
105
+ WebSocket-specific `WebSocketBaseSession` does not preserve the old peer-based constructor.
106
+
107
+ Invocation, Event and Result expose the same [strict payload accessors](https://github.com/xconnio/xconn/blob/main/docs/payload.md).
108
+ JS `argInt64` / `kwargInt64` return BigInt; typed defaults use names such as
109
+ `argStringOr(0, "fallback")`. See the [cross-language API contract](https://github.com/xconnio/xconn/blob/main/docs/fluent-api.md).
110
+
111
+ ## Build and package
112
+
113
+ Install the browser client from npm:
114
+
115
+ ```sh
116
+ npm install @xconnio/xconn
117
+ ```
118
+
119
+ The package includes JavaScript, TypeScript declarations and the compiled WASM
120
+ binary. Application installs require no Rust toolchain or native SDK downloads.
121
+ Bundlers must preserve or explicitly relocate the WASM asset; pass its URL to
122
+ `initializeWasm(wasmURL)` when configuring a custom asset location.
123
+
124
+ Maintainer builds require Rust,
125
+ wasm32-unknown-unknown, wasm-bindgen-cli 0.2.129, Binaryen wasm-opt and Node 20.11+.
126
+
127
+ ```sh
128
+ rustup target add wasm32-unknown-unknown
129
+ cargo install wasm-bindgen-cli --version 0.2.129 --locked
130
+ npm --prefix bindings/js ci
131
+ npm --prefix bindings/js run build
132
+ mkdir -p target/browser-package
133
+ (cd bindings/js && npm pack --ignore-scripts --pack-destination ../../target/browser-package)
134
+ ```
135
+
136
+ Applications can install the resulting .tgz without Rust, C or native libraries.
137
+ The WASM binary is included and installation has no native build step. Bundlers
138
+ must preserve or explicitly relocate the WASM asset.
139
+
140
+ The build discovers wasm-bindgen/wasm-opt on PATH or in wasm-pack's cache;
141
+ WASM_BINDGEN_BIN / WASM_OPT_BIN override discovery. Use
142
+ `bindings/js/scripts/build.sh json` or `... codecs` for reduced builds. Artifacts
143
+ are in dist/. Serve bindings/js over HTTP and open example.html for a plain-browser
144
+ example against an existing router; the example starts no router itself.
145
+
146
+ ## Validation
147
+
148
+ ```sh
149
+ npm --prefix bindings/js run typecheck
150
+ npm --prefix bindings/js run lint
151
+ npm --prefix bindings/js run format:check
152
+ XCONN_REFERENCE_GO_BIN=/path/to/original-go-reference \
153
+ CHROMIUM_BIN=/path/to/chromium npm --prefix bindings/js test
154
+ ```
155
+
156
+ Node and real Chromium run the same tests against the original Go router:
157
+ authentication across codecs, concurrent/reentrant RPC, PubSub, progressive
158
+ results, cancellation, custom adapters, malformed packets, lifecycle and the
159
+ shared payload parsing matrix. Without the reference only local tests run;
160
+ without Chromium browser tests are skipped. CI requires both and also installs
161
+ and tests the packed package outside the checkout. Chromium tests use an isolated
162
+ profile and --no-sandbox for the local test process.
163
+
164
+ [Size measurements](https://github.com/xconnio/xconn/blob/main/benchmarks/browser-wasm/README.md) include WASM,
165
+ generated glue and all high-level client modules.
166
+
167
+ [Result construction and received values](https://github.com/xconnio/xconn/blob/main/docs/results.md) use one payload
168
+ type for handler replies, progressive results and completed calls.
169
+
170
+ Progressive RPCs use the fluent `stream()` terminal (`Stream()`/`StreamContext()` in Go).
171
+ See the [cross-language streaming API](https://github.com/xconnio/xconn/blob/main/docs/streaming.md) for examples and lifecycle rules.
172
+
173
+ ### Native adapter ownership
174
+
175
+ Built-in serializers and authenticators expose an idempotent `free()` method to
176
+ release their WASM storage immediately. Reusing the adapter allocates fresh native
177
+ storage lazily. A session releases its default serializer on disconnect; connection
178
+ setup releases its default authenticator on success or failure. Supplied adapters
179
+ remain caller-owned, so free them when all connections using them have finished.
180
+
181
+ ## Browser QUIC connectivity through WebTransport
182
+
183
+ ```typescript
184
+ import { WebTransportConnection } from "@xconnio/xconn";
185
+
186
+ const connection = await WebTransportConnection.connect("https://router:443/wamp");
187
+ try {
188
+ const session = await connection.openSession("realm");
189
+ try {
190
+ console.log((await session.call("echo").arg("hello").execute()).args);
191
+ } finally {
192
+ await session.close();
193
+ }
194
+ } finally {
195
+ await connection.close();
196
+ }
197
+ ```
198
+
199
+ Networking uses the browser's native WebTransport API; WAMP joining, codecs and
200
+ RawSocket framing use Rust/WASM. A WebTransport listener is required; arbitrary
201
+ QUIC listeners cannot accept browser connections. Browser certificate validation
202
+ is mandatory. For development certificates, pass the standard
203
+ `serverCertificateHashes` option with SHA-256 hashes obtained through a trusted
204
+ channel. WAMP sessions are independent of sibling byte streams. `openStream()`
205
+ and `acceptStream()` expose `read`, `write`, `writeEof`, and `close`; EOF is
206
+ `undefined`. `connectTimeout` and `signal` bound connection setup.
207
+
208
+ ## Browser WebRTC
209
+
210
+ ```typescript
211
+ import { Client, WebRTCConnection } from "@xconnio/xconn";
212
+
213
+ const signaling = await new Client().connect("wss://router/ws", "realm");
214
+ try {
215
+ const peer = await WebRTCConnection.connect(signaling, "realm", {
216
+ offerProcedure: "offer",
217
+ remoteCandidatesTopic: "to-client",
218
+ localCandidatesTopic: "to-provider",
219
+ });
220
+ try {
221
+ console.log((await peer.call("echo").arg("hello").execute()).args);
222
+ const channel = await peer.connection.openChannel("files");
223
+ try {
224
+ await channel.writeMessage(new TextEncoder().encode("file contents"));
225
+ } finally {
226
+ await channel.close();
227
+ }
228
+ } finally {
229
+ await peer.close();
230
+ await peer.connection.close();
231
+ }
232
+ } finally {
233
+ await signaling.close();
234
+ }
235
+ ```
236
+
237
+ Configure STUN/TURN servers with the standard `iceServers` option.
238
+ Browser APIs own ICE, DTLS and SCTP. Rust/WASM owns WAMP state, signaling JSON,
239
+ serializer negotiation and the same bounded chunk framing used by native Rust.
240
+ The Rust signaling provider's offer/candidate contract is preserved. Early remote
241
+ candidates are buffered and applied in order; the signaling subscription remains
242
+ active for late trickle candidates until the peer connection closes.
243
+
244
+ WebRTC WAMP sessions advertise a 16 MiB receive limit and reject larger assembled
245
+ messages. Outgoing WAMP messages remain bounded by the remote peer's advertised
246
+ limit; chunking does not bypass either limit.
247
+
248
+ `connectTimeout`, `openTimeout`, `handshakeTimeout` and `signal` bound setup.
249
+ Additional sessions use `peer.connection.openSession`. Closing a session leaves
250
+ its connection and sibling channels open. The signaling session remains owned by
251
+ the application. `openChannel` and `acceptChannel` support remote-initiated raw
252
+ channels. `send`/`receive` preserve text and binary packets; `writeMessage` and
253
+ `readMessage` use chunk framing for ordered, reliable channels. Reads accept an
254
+ optional AbortSignal. Do not mix packet and chunk framing on the same channel.
255
+ Incoming and outgoing queues are bounded; large producers should receive
256
+ concurrently and handle explicit queue-limit errors. Close resources explicitly.
257
+
258
+ ## Publishing
259
+
260
+ The `npm release` GitHub Actions workflow builds and tests the packed package,
261
+ including browser WebRTC and WebTransport, before publishing `@xconnio/xconn`.
262
+ Manual runs produce a tested package artifact without publishing.
263
+ To retry publication, rerun the failed jobs from the original tag-push run.
264
+ One-time setup:
265
+
266
+ 1. Create a GitHub environment named `npm` with a required reviewer.
267
+ 2. In the npm package settings, add a GitHub Actions trusted publisher:
268
+ owner `xconnio`, repository `xconn`, workflow `npm-release.yaml`,
269
+ environment `npm`. Allow publishing. No npm token secret is needed.
270
+
271
+ For a release, align the SDK and package versions, then merge the changes and
272
+ push the shared root tag:
273
+
274
+ ```sh
275
+ git tag -a v0.6.0 -m 'XConn 0.6.0'
276
+ git push origin v0.6.0
277
+ ```
278
+
279
+ Approve the `npm` environment deployment after the build succeeds. The publish
280
+ job uploads the tested tarball using npm trusted publishing with provenance.
281
+ The same root tag starts the other XConn releases; see
282
+ [binding distribution](../../docs/releases.md).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,51 @@
1
+ import { type Dictionary, type Message } from "./message.js";
2
+ export interface Challenge extends Message {
3
+ readonly authmethod: string;
4
+ readonly extra: Dictionary;
5
+ }
6
+ export interface Authenticate extends Message {
7
+ readonly signature: string;
8
+ readonly extra: Dictionary;
9
+ }
10
+ export interface ClientAuthenticator {
11
+ /** Release native storage. Built-in adapters recreate it lazily if reused. */
12
+ free?(): void;
13
+ readonly authMethod: string;
14
+ readonly authID: string;
15
+ readonly authExtra: object;
16
+ authenticate(challenge: Challenge): Promise<Authenticate>;
17
+ }
18
+ declare abstract class RustAuthenticator implements ClientAuthenticator {
19
+ readonly authID: string;
20
+ private readonly secret;
21
+ private readonly extra;
22
+ private native?;
23
+ private metadata?;
24
+ abstract readonly authMethod: string;
25
+ constructor(authID: string, secret: string, extra: object | null);
26
+ private get adapter();
27
+ free(): void;
28
+ get authExtra(): object;
29
+ authenticate(challenge: Challenge): Promise<Authenticate>;
30
+ }
31
+ export declare class AnonymousAuthenticator extends RustAuthenticator {
32
+ static readonly TYPE = "anonymous";
33
+ readonly authMethod = "anonymous";
34
+ constructor(authID?: string, extra?: object | null);
35
+ }
36
+ export declare class TicketAuthenticator extends RustAuthenticator {
37
+ static readonly TYPE = "ticket";
38
+ readonly authMethod = "ticket";
39
+ constructor(authID: string, ticket: string, extra?: object | null);
40
+ }
41
+ export declare class WAMPCRAAuthenticator extends RustAuthenticator {
42
+ static readonly TYPE = "wampcra";
43
+ readonly authMethod = "wampcra";
44
+ constructor(authID: string, secret: string, extra?: object | null);
45
+ }
46
+ export declare class CryptoSignAuthenticator extends RustAuthenticator {
47
+ static readonly TYPE = "cryptosign";
48
+ readonly authMethod = "cryptosign";
49
+ constructor(authID: string, key: string, extra?: object | null);
50
+ }
51
+ export {};
package/dist/auth.js ADDED
@@ -0,0 +1,57 @@
1
+ import { getNative, initializeWasm, rustCall } from "./native.js";
2
+ import { WireMessage } from "./message.js";
3
+ class RustAuthenticator {
4
+ authID;
5
+ secret;
6
+ extra;
7
+ native;
8
+ metadata;
9
+ constructor(authID, secret, extra) {
10
+ this.authID = authID;
11
+ this.secret = secret;
12
+ this.extra = extra;
13
+ }
14
+ get adapter() {
15
+ return (this.native ??= rustCall(() => new (getNative().NativeAuthenticator)(this.authMethod, this.authID, this.secret, this.extra ?? {})));
16
+ }
17
+ free() {
18
+ this.native?.free();
19
+ this.native = undefined;
20
+ this.metadata = undefined;
21
+ }
22
+ get authExtra() {
23
+ return (this.metadata ??= rustCall(() => this.adapter.extra()));
24
+ }
25
+ async authenticate(challenge) {
26
+ await initializeWasm();
27
+ return new WireMessage(rustCall(() => this.adapter.authenticate(challenge.marshal())));
28
+ }
29
+ }
30
+ export class AnonymousAuthenticator extends RustAuthenticator {
31
+ static TYPE = "anonymous";
32
+ authMethod = AnonymousAuthenticator.TYPE;
33
+ constructor(authID = "", extra = {}) {
34
+ super(authID, "", extra);
35
+ }
36
+ }
37
+ export class TicketAuthenticator extends RustAuthenticator {
38
+ static TYPE = "ticket";
39
+ authMethod = TicketAuthenticator.TYPE;
40
+ constructor(authID, ticket, extra = {}) {
41
+ super(authID, ticket, extra);
42
+ }
43
+ }
44
+ export class WAMPCRAAuthenticator extends RustAuthenticator {
45
+ static TYPE = "wampcra";
46
+ authMethod = WAMPCRAAuthenticator.TYPE;
47
+ constructor(authID, secret, extra = {}) {
48
+ super(authID, secret, extra);
49
+ }
50
+ }
51
+ export class CryptoSignAuthenticator extends RustAuthenticator {
52
+ static TYPE = "cryptosign";
53
+ authMethod = CryptoSignAuthenticator.TYPE;
54
+ constructor(authID, key, extra = {}) {
55
+ super(authID, key, extra);
56
+ }
57
+ }
package/dist/call.d.ts ADDED
@@ -0,0 +1,38 @@
1
+ import type { Result } from "./types.js";
2
+ import type { Dictionary } from "./message.js";
3
+ export interface StreamOptions {
4
+ progressiveInput?: boolean;
5
+ progressiveResults?: boolean;
6
+ bufferSize?: number;
7
+ }
8
+ export interface CallTransport {
9
+ input: (args: unknown[], kwargs: Dictionary, finish: boolean) => void;
10
+ cancel: (error: unknown) => void;
11
+ }
12
+ /** One owned RPC with independent input and result paths. */
13
+ export declare class Call implements AsyncIterable<Result> {
14
+ private readonly transport;
15
+ private readonly capacity;
16
+ private readonly queue;
17
+ private waiter?;
18
+ private receiving;
19
+ private done;
20
+ private inputFinished;
21
+ private failure;
22
+ private failed;
23
+ constructor(transport: CallTransport, capacity: number, progressiveInput: boolean);
24
+ /** @internal */
25
+ offer(result: Result): void;
26
+ /** @internal */
27
+ complete(result: Result): void;
28
+ /** @internal */
29
+ fail(error: unknown): void;
30
+ receive(): Promise<Result | null>;
31
+ send(args?: unknown[], kwargs?: Dictionary): Promise<void>;
32
+ finish(args?: unknown[], kwargs?: Dictionary): Promise<void>;
33
+ private input;
34
+ cancel(): Promise<void>;
35
+ close(): Promise<void>;
36
+ results(): AsyncIterableIterator<Result>;
37
+ [Symbol.asyncIterator](): AsyncIterableIterator<Result>;
38
+ }
package/dist/call.js ADDED
@@ -0,0 +1,146 @@
1
+ import { ProtocolError } from "./exception.js";
2
+ /** One owned RPC with independent input and result paths. */
3
+ export class Call {
4
+ transport;
5
+ capacity;
6
+ queue = [];
7
+ waiter;
8
+ receiving = false;
9
+ done = false;
10
+ inputFinished;
11
+ failure;
12
+ failed = false;
13
+ constructor(transport, capacity, progressiveInput) {
14
+ this.transport = transport;
15
+ this.capacity = capacity;
16
+ this.inputFinished = !progressiveInput;
17
+ }
18
+ /** @internal */
19
+ offer(result) {
20
+ if (this.done) {
21
+ return;
22
+ }
23
+ if (this.waiter) {
24
+ const waiter = this.waiter;
25
+ this.waiter = undefined;
26
+ waiter.resolve(result);
27
+ }
28
+ else if (this.queue.length < this.capacity) {
29
+ this.queue.push(result);
30
+ }
31
+ else {
32
+ const error = new ProtocolError("call result queue overflow");
33
+ this.fail(error);
34
+ this.transport.cancel(error);
35
+ throw error;
36
+ }
37
+ }
38
+ /** @internal */
39
+ complete(result) {
40
+ if (this.done) {
41
+ return;
42
+ }
43
+ try {
44
+ this.offer(result);
45
+ this.done = true;
46
+ }
47
+ catch {
48
+ /* offer records overflow and cancels correlation */
49
+ }
50
+ }
51
+ /** @internal */
52
+ fail(error) {
53
+ if (this.done) {
54
+ return;
55
+ }
56
+ this.done = true;
57
+ if (this.waiter) {
58
+ const waiter = this.waiter;
59
+ this.waiter = undefined;
60
+ waiter.reject(error);
61
+ }
62
+ else {
63
+ this.failure = error;
64
+ this.failed = true;
65
+ }
66
+ }
67
+ async receive() {
68
+ if (this.receiving) {
69
+ throw new ProtocolError("another receive is already pending");
70
+ }
71
+ this.receiving = true;
72
+ try {
73
+ if (this.queue.length) {
74
+ return this.queue.shift();
75
+ }
76
+ if (this.failed) {
77
+ this.failed = false;
78
+ throw this.failure;
79
+ }
80
+ if (this.done) {
81
+ return null;
82
+ }
83
+ return await new Promise((resolve, reject) => {
84
+ this.waiter = { resolve, reject };
85
+ });
86
+ }
87
+ finally {
88
+ this.receiving = false;
89
+ }
90
+ }
91
+ async send(args = [], kwargs = {}) {
92
+ this.input(args, kwargs, false);
93
+ }
94
+ async finish(args = [], kwargs = {}) {
95
+ this.input(args, kwargs, true);
96
+ }
97
+ input(args, kwargs, finish) {
98
+ if (this.done) {
99
+ throw new ProtocolError("call is finished");
100
+ }
101
+ if (this.inputFinished) {
102
+ throw new ProtocolError("progressive input is disabled or already finished");
103
+ }
104
+ try {
105
+ this.transport.input(args, kwargs, finish);
106
+ }
107
+ catch (error) {
108
+ this.fail(error);
109
+ this.transport.cancel(error);
110
+ throw error;
111
+ }
112
+ if (finish) {
113
+ this.inputFinished = true;
114
+ }
115
+ }
116
+ async cancel() {
117
+ if (this.done) {
118
+ return;
119
+ }
120
+ const error = new DOMException("Call cancelled", "AbortError");
121
+ this.queue.length = 0;
122
+ this.fail(error);
123
+ this.transport.cancel(error);
124
+ }
125
+ async close() {
126
+ await this.cancel();
127
+ }
128
+ results() {
129
+ return {
130
+ next: async () => {
131
+ const result = await this.receive();
132
+ return result === null ? { done: true, value: undefined } : { done: false, value: result };
133
+ },
134
+ return: async () => {
135
+ await this.close();
136
+ return { done: true, value: undefined };
137
+ },
138
+ [Symbol.asyncIterator]() {
139
+ return this;
140
+ },
141
+ };
142
+ }
143
+ [Symbol.asyncIterator]() {
144
+ return this.results();
145
+ }
146
+ }
@@ -0,0 +1,21 @@
1
+ import type { ClientAuthenticator } from "./auth.js";
2
+ import type { Serializer } from "./serializers.js";
3
+ import type { Session } from "./session.js";
4
+ export interface ClientOptions {
5
+ authenticator?: ClientAuthenticator;
6
+ serializer?: Serializer;
7
+ connectTimeout?: number;
8
+ closeTimeout?: number;
9
+ signal?: AbortSignal;
10
+ webSocketFactory?: (uri: string, protocols: string[]) => WebSocket;
11
+ }
12
+ export declare class Client {
13
+ private readonly options;
14
+ constructor(options?: ClientOptions);
15
+ connect(uri: string, realm: string): Promise<Session>;
16
+ }
17
+ export declare function connect(uri: string, realm: string, options?: ClientOptions): Promise<Session>;
18
+ export declare function connectAnonymous(uri: string, realm: string): Promise<Session>;
19
+ export declare function connectTicket(uri: string, realm: string, authid: string, ticket: string): Promise<Session>;
20
+ export declare function connectCRA(uri: string, realm: string, authid: string, secret: string): Promise<Session>;
21
+ export declare function connectCryptosign(uri: string, realm: string, authid: string, key: string): Promise<Session>;