@dmarket/p2p-tracker-core 0.1.0-SNAPSHOT.99 → 1.0.1-beta

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 (66) hide show
  1. package/VERSION +14 -0
  2. package/dmarket-p2p-tracker-core-domain.mjs +11510 -4975
  3. package/dmarket-p2p-tracker-core-domain.mjs.map +1 -1
  4. package/kotlin-kotlin-stdlib.mjs +3168 -2664
  5. package/kotlin-kotlin-stdlib.mjs.map +1 -1
  6. package/kotlinx-atomicfu.mjs +13 -13
  7. package/kotlinx-coroutines-core.mjs +2758 -2428
  8. package/kotlinx-coroutines-core.mjs.map +1 -1
  9. package/kotlinx-io-kotlinx-io-bytestring.mjs +44 -44
  10. package/kotlinx-io-kotlinx-io-bytestring.mjs.map +1 -1
  11. package/kotlinx-io-kotlinx-io-core.mjs +517 -497
  12. package/kotlinx-io-kotlinx-io-core.mjs.map +1 -1
  13. package/kotlinx-serialization-kotlinx-serialization-core.mjs +1791 -1790
  14. package/kotlinx-serialization-kotlinx-serialization-core.mjs.map +1 -1
  15. package/kotlinx-serialization-kotlinx-serialization-json.mjs +1586 -1564
  16. package/kotlinx-serialization-kotlinx-serialization-json.mjs.map +1 -1
  17. package/ktor-ktor-client-core.mjs +3047 -3048
  18. package/ktor-ktor-client-core.mjs.map +1 -1
  19. package/ktor-ktor-events.mjs +6 -6
  20. package/ktor-ktor-http-cio.mjs +491 -491
  21. package/ktor-ktor-http.mjs +666 -646
  22. package/ktor-ktor-http.mjs.map +1 -1
  23. package/ktor-ktor-io.mjs +1145 -1059
  24. package/ktor-ktor-io.mjs.map +1 -1
  25. package/ktor-ktor-utils.mjs +794 -786
  26. package/ktor-ktor-utils.mjs.map +1 -1
  27. package/ktor-ktor-websockets.mjs +855 -799
  28. package/ktor-ktor-websockets.mjs.map +1 -1
  29. package/p2p-tracker-core.d.mts +110 -40
  30. package/p2p-tracker-core.mjs +28378 -11117
  31. package/p2p-tracker-core.mjs.map +1 -1
  32. package/package.json +2 -4
  33. package/pkg/README.md +92 -0
  34. package/pkg/client_wasm.d.ts +312 -0
  35. package/pkg/client_wasm.js +1187 -0
  36. package/pkg/client_wasm_bg.wasm +0 -0
  37. package/pkg/client_wasm_bg.wasm.d.ts +32 -0
  38. package/pkg/package.json +19 -0
  39. package/pkg/snippets/web-spawn-05868593a72e2d44/js/spawn.js +73 -0
  40. package/pkg/spawn.js +73 -0
  41. package/transport/README.md +172 -0
  42. package/transport/dist/channel.d.ts +48 -0
  43. package/transport/dist/channel.d.ts.map +1 -0
  44. package/transport/dist/channel.js +150 -0
  45. package/transport/dist/channel.js.map +1 -0
  46. package/transport/dist/index.d.ts +8 -0
  47. package/transport/dist/index.d.ts.map +1 -0
  48. package/transport/dist/index.js +18 -0
  49. package/transport/dist/index.js.map +1 -0
  50. package/transport/dist/prover.d.ts +103 -0
  51. package/transport/dist/prover.d.ts.map +1 -0
  52. package/transport/dist/prover.js +139 -0
  53. package/transport/dist/prover.js.map +1 -0
  54. package/transport/dist/transport.d.ts +31 -0
  55. package/transport/dist/transport.d.ts.map +1 -0
  56. package/transport/dist/transport.js +75 -0
  57. package/transport/dist/transport.js.map +1 -0
  58. package/transport/dist/types.d.ts +162 -0
  59. package/transport/dist/types.d.ts.map +1 -0
  60. package/transport/dist/types.js +21 -0
  61. package/transport/dist/types.js.map +1 -0
  62. package/transport/dist/wasm-compat.d.ts +2 -0
  63. package/transport/dist/wasm-compat.d.ts.map +1 -0
  64. package/transport/dist/wasm-compat.js +15 -0
  65. package/transport/dist/wasm-compat.js.map +1 -0
  66. package/transport/package.json +28 -0
Binary file
@@ -0,0 +1,32 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ export const __wbg_proveoutput_free: (a: number, b: number) => void;
4
+ export const initialize: (a: number, b: number) => any;
5
+ export const present: (a: number, b: number, c: number, d: number, e: number) => [number, number, number, number];
6
+ export const prove: (a: any, b: any, c: any, d: any, e: number) => any;
7
+ export const proveoutput_attestation: (a: number) => [number, number];
8
+ export const proveoutput_response: (a: number) => any;
9
+ export const proveoutput_secrets: (a: number) => [number, number];
10
+ export const __wbg_spawner_free: (a: number, b: number) => void;
11
+ export const __wbg_workerdata_free: (a: number, b: number) => void;
12
+ export const spawner_intoRaw: (a: number) => number;
13
+ export const spawner_run: (a: number, b: number, c: number) => any;
14
+ export const startSpawner: () => any;
15
+ export const web_spawn_recover_spawner: (a: number) => number;
16
+ export const web_spawn_start_worker: (a: number) => void;
17
+ export const ring_core_0_17_14__bn_mul_mont: (a: number, b: number, c: number, d: number, e: number, f: number) => void;
18
+ export const wasm_bindgen_1fa5c626ec3a32f9___convert__closures_____invoke___wasm_bindgen_1fa5c626ec3a32f9___JsValue__core_b7b33017ae0f8bb5___result__Result_____wasm_bindgen_1fa5c626ec3a32f9___JsError___true_: (a: number, b: number, c: any) => [number, number];
19
+ export const wasm_bindgen_1fa5c626ec3a32f9___convert__closures_____invoke___js_sys_27d0ccca2911ffcd___Function_fn_wasm_bindgen_1fa5c626ec3a32f9___JsValue_____wasm_bindgen_1fa5c626ec3a32f9___sys__Undefined___js_sys_27d0ccca2911ffcd___Function_fn_wasm_bindgen_1fa5c626ec3a32f9___JsValue_____wasm_bindgen_1fa5c626ec3a32f9___sys__Undefined_______true_: (a: number, b: number, c: any, d: any) => void;
20
+ export const wasm_bindgen_1fa5c626ec3a32f9___convert__closures_____invoke___wasm_bindgen_1fa5c626ec3a32f9___JsValue______true_: (a: number, b: number, c: any) => void;
21
+ export const wasm_bindgen_1fa5c626ec3a32f9___convert__closures_____invoke___js_sys_27d0ccca2911ffcd___futures__task__wait_async_polyfill__MessageEvent______true_: (a: number, b: number, c: any) => void;
22
+ export const memory: WebAssembly.Memory;
23
+ export const __wbindgen_malloc: (a: number, b: number) => number;
24
+ export const __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
25
+ export const __wbindgen_exn_store: (a: number) => void;
26
+ export const __externref_table_alloc: () => number;
27
+ export const __wbindgen_externrefs: WebAssembly.Table;
28
+ export const __wbindgen_free: (a: number, b: number, c: number) => void;
29
+ export const __wbindgen_destroy_closure: (a: number, b: number) => void;
30
+ export const __externref_table_dealloc: (a: number) => void;
31
+ export const __wbindgen_thread_destroy: (a?: number, b?: number, c?: number) => void;
32
+ export const __wbindgen_start: (a: number) => void;
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "client-wasm",
3
+ "type": "module",
4
+ "description": "Wasm bindings (browser-extension prover) over client-core: initialize()/prove()/present() + JsIo adapter, packaged via wasm-pack.",
5
+ "version": "0.1.0",
6
+ "files": [
7
+ "client_wasm_bg.wasm",
8
+ "client_wasm.js",
9
+ "client_wasm.d.ts",
10
+ "client_wasm_bg.wasm.d.ts",
11
+ "spawn.js",
12
+ "snippets/"
13
+ ],
14
+ "main": "client_wasm.js",
15
+ "types": "client_wasm.d.ts",
16
+ "sideEffects": [
17
+ "./snippets/*"
18
+ ]
19
+ }
@@ -0,0 +1,73 @@
1
+ function registerMessageListener(target, type, callback) {
2
+ const listener = async (event) => {
3
+ const message = event.data;
4
+ if (message && message.type === type) {
5
+ await callback(message.data);
6
+ }
7
+ };
8
+
9
+ target.addEventListener('message', listener);
10
+ }
11
+
12
+ // Register listener for the start spawner message.
13
+ registerMessageListener(self, 'web_spawn_start_spawner', async (data) => {
14
+ const workerUrl = new URL(
15
+ './spawn.js',
16
+ import.meta.url
17
+ );
18
+ const [module, memory, spawnerPtr] = data;
19
+ const pkg = await import('../../../client_wasm.js');
20
+ const exports = await pkg.default({ module, memory });
21
+
22
+ const spawner = pkg.web_spawn_recover_spawner(spawnerPtr);
23
+ postMessage('web_spawn_spawner_ready');
24
+ await spawner.run(workerUrl.toString());
25
+
26
+ exports.__wbindgen_thread_destroy();
27
+
28
+ close();
29
+ });
30
+
31
+ // Register listener for the start worker message.
32
+ registerMessageListener(self, 'web_spawn_start_worker', async (data) => {
33
+ const [module, memory, workerPtr] = data;
34
+
35
+ const pkg = await import('../../../client_wasm.js');
36
+ const exports = await pkg.default({ module, memory });
37
+
38
+ pkg.web_spawn_start_worker(workerPtr);
39
+
40
+ exports.__wbindgen_thread_destroy();
41
+
42
+ close();
43
+ });
44
+
45
+ /// Starts the spawner in a new worker.
46
+ export async function startSpawnerWorker(module, memory, spawner) {
47
+ const workerUrl = new URL(
48
+ './spawn.js',
49
+ import.meta.url
50
+ );
51
+ const worker = new Worker(
52
+ workerUrl,
53
+ {
54
+ name: 'web-spawn-spawner',
55
+ type: 'module'
56
+ }
57
+ );
58
+
59
+ const data = [module, memory, spawner.intoRaw()];
60
+ worker.postMessage({
61
+ type: 'web_spawn_start_spawner',
62
+ data: data
63
+ })
64
+
65
+ await new Promise(resolve => {
66
+ worker.addEventListener('message', function handler(event) {
67
+ if (event.data === 'web_spawn_spawner_ready') {
68
+ worker.removeEventListener('message', handler);
69
+ resolve();
70
+ }
71
+ })
72
+ })
73
+ }
package/pkg/spawn.js ADDED
@@ -0,0 +1,73 @@
1
+ function registerMessageListener(target, type, callback) {
2
+ const listener = async (event) => {
3
+ const message = event.data;
4
+ if (message && message.type === type) {
5
+ await callback(message.data);
6
+ }
7
+ };
8
+
9
+ target.addEventListener('message', listener);
10
+ }
11
+
12
+ // Register listener for the start spawner message.
13
+ registerMessageListener(self, 'web_spawn_start_spawner', async (data) => {
14
+ const workerUrl = new URL(
15
+ './spawn.js',
16
+ import.meta.url
17
+ );
18
+ const [module, memory, spawnerPtr] = data;
19
+ const pkg = await import('../../../client_wasm.js');
20
+ const exports = await pkg.default({ module, memory });
21
+
22
+ const spawner = pkg.web_spawn_recover_spawner(spawnerPtr);
23
+ postMessage('web_spawn_spawner_ready');
24
+ await spawner.run(workerUrl.toString());
25
+
26
+ exports.__wbindgen_thread_destroy();
27
+
28
+ close();
29
+ });
30
+
31
+ // Register listener for the start worker message.
32
+ registerMessageListener(self, 'web_spawn_start_worker', async (data) => {
33
+ const [module, memory, workerPtr] = data;
34
+
35
+ const pkg = await import('../../../client_wasm.js');
36
+ const exports = await pkg.default({ module, memory });
37
+
38
+ pkg.web_spawn_start_worker(workerPtr);
39
+
40
+ exports.__wbindgen_thread_destroy();
41
+
42
+ close();
43
+ });
44
+
45
+ /// Starts the spawner in a new worker.
46
+ export async function startSpawnerWorker(module, memory, spawner) {
47
+ const workerUrl = new URL(
48
+ './spawn.js',
49
+ import.meta.url
50
+ );
51
+ const worker = new Worker(
52
+ workerUrl,
53
+ {
54
+ name: 'web-spawn-spawner',
55
+ type: 'module'
56
+ }
57
+ );
58
+
59
+ const data = [module, memory, spawner.intoRaw()];
60
+ worker.postMessage({
61
+ type: 'web_spawn_start_spawner',
62
+ data: data
63
+ })
64
+
65
+ await new Promise(resolve => {
66
+ worker.addEventListener('message', function handler(event) {
67
+ if (event.data === 'web_spawn_spawner_ready') {
68
+ worker.removeEventListener('message', handler);
69
+ resolve();
70
+ }
71
+ })
72
+ })
73
+ }
@@ -0,0 +1,172 @@
1
+ # client-wasm-transport — transport + pass-through prover façade for the wasm prover
2
+
3
+ The TS companion to the `client-wasm` browser-extension prover. Two layers,
4
+ both **wasm-free at runtime** (the emitted `dist/` contains no import of the
5
+ wasm pkg — a load-bearing invariant, see below):
6
+
7
+ - **Transport** — the two WebSocket `IoChannel`s that [`prove()`](../pkg)
8
+ consumes, mirroring the native `connect_notary` / `connect_proxy` in
9
+ `test-full-e2e/src/ws.rs` (the wasm build can't open raw TCP or use
10
+ tungstenite, so the transport lives here and is injected across the wasm
11
+ boundary).
12
+ - **Prover façade** — `createProver(wasm)`: a pass-through mirror of the wasm
13
+ API (`initialize` / `prove` / `present`, same call shapes) over a
14
+ **caller-injected** pkg module. It owns the setup (the pkg's default
15
+ `init()`, then the rayon-pool `initialize()`, both memoized) and absorbs the
16
+ wire conversions so callers never see the generated bindings' warts.
17
+
18
+ ## What it exports
19
+
20
+ | export | kind | purpose |
21
+ | --- | --- | --- |
22
+ | `createProver(wasm)` | façade | wraps an injected pkg module in the `Prover` surface below |
23
+ | `Prover` | type | `initialize(logging?, threads?)` / `prove(notaryIo, serverIo, config, request, onProgress?)` / `present(attestation, secrets, policy?)` |
24
+ | `ClientWasmModule` | type | the injected-module contract (`import * as wasm from ".../pkg/client_wasm.js"` satisfies it) |
25
+ | `connectNotary(url, token, opts?)` | transport | the notary MPC channel, authenticated by the `Sec-WebSocket-Protocol` bearer subprotocol |
26
+ | `connectProxy(proxyBase, host, port, opts?)` | transport | the target byte pipe, tunnelled `WS → p2p-wss-proxy → TCP` |
27
+ | `WsIoChannel` | transport | the `WebSocket`→`IoChannel` adapter both helpers return |
28
+ | `NOTARY_SUBPROTOCOL` | transport | `"tlsn.notary.v2"` — the notary subprotocol marker |
29
+ | DTO types | types | `IssuanceConfig`, `HttpRequest`/`HttpResponse`, `RevealPolicy`, `BodyReveal`, `RootStore`, `LoggingConfig`, `ProveOutput`, `ProveProgress`/`ProgressCallback`, `IoChannel` |
30
+
31
+ Deliberately **not** exported: the pkg's web-spawn glue (`startSpawner`,
32
+ `web_spawn_*`) and instantiation lifecycle (`default` init / `initSync`) —
33
+ those are called through the pkg's own module identity and are internal to the
34
+ façade's setup.
35
+
36
+ ## Usage
37
+
38
+ ```ts
39
+ import * as wasm from "./pkg/client_wasm.js"; // the loose wasm-pack output — keep EXTERNAL in your bundle
40
+ import { createProver, connectNotary, connectProxy } from "client-wasm-transport";
41
+
42
+ const prover = createProver(wasm);
43
+ // Optional — prove() runs it with defaults if you skip it. Call it yourself to
44
+ // pick logging / thread count (defaults: null logging, hardwareConcurrency ≤ 8).
45
+ await prover.initialize({ level: "Info" }, navigator.hardwareConcurrency);
46
+
47
+ const notaryIo = await connectNotary("wss://notary.example/", bearerToken);
48
+ const serverIo = await connectProxy("wss://proxy.example", "api.example.com", 443);
49
+
50
+ const out = await prover.prove(
51
+ notaryIo,
52
+ serverIo,
53
+ { serverName: "api.example.com" }, // IssuanceConfig (rootStore defaults to Mozilla roots)
54
+ { method: "GET", uri: "/v1/resource" }, // HttpRequest (body may be a Uint8Array)
55
+ (ev) => console.log(`${ev.step} ${Math.round(ev.progress * 100)}% — ${ev.message}`),
56
+ );
57
+ // out.attestation, out.secrets: Uint8Array — persist together
58
+ // out.response: { status, headers, body: Uint8Array } — convenience only
59
+
60
+ // Omitting the policy applies the core default: it redacts the authorization/
61
+ // cookie/user-agent header values but REVEALS the request target (path+query).
62
+ // Pass an explicit policy to withhold a credential-bearing query string:
63
+ const presentation = prover.present(out.attestation, out.secrets, {
64
+ redactRequestHeaderValues: ["authorization", "cookie", "user-agent"],
65
+ revealRequestTarget: false,
66
+ revealResponseHeaders: true,
67
+ revealResponseBody: "all",
68
+ });
69
+ // POST `presentation` (Uint8Array) to your validating backend.
70
+ ```
71
+
72
+ ## Why injection instead of `import ... from "client-wasm"` (load-bearing)
73
+
74
+ This package is **inlined** by its consumer's bundle (the extension's
75
+ offscreen bundle inlines `client-wasm-transport`), while the wasm-pack `pkg/`
76
+ must stay **loose** next to the bundle: its rayon spawner does
77
+ `new Worker(new URL("./spawn.js", import.meta.url))` and fetches the `.wasm`
78
+ via `import.meta.url`, so inlining it 404s the Worker and the `.wasm` — and a
79
+ *bare* `client-wasm` specifier is invisible to the consumer's
80
+ `--external:./pkg/*` glob. Worse, with `"sideEffects": false` a value
81
+ re-export lets tree-shaking silently drop the instantiation chain: a green
82
+ build whose exports throw on first call. Both failure modes were measured in
83
+ the branch journal (entries 20/21).
84
+
85
+ Injection is the shape that avoids all of it: the caller keeps the one pkg
86
+ import (external, at the pkg's real path), so the module's `import.meta.url`
87
+ semantics and single-instance identity are untouched — and because the module
88
+ namespace itself is handed in, the façade can still own `init()` +
89
+ `initialize()` on the caller's behalf.
90
+
91
+ ## What the façade converts (vs. the raw pkg bindings)
92
+
93
+ | raw `pkg/client_wasm.d.ts` | façade |
94
+ | --- | --- |
95
+ | caller must run default `init()` before anything, `initialize()` before `prove()` | `initialize()` does both, memoized; `prove()` auto-initializes with defaults |
96
+ | `HttpRequest.body` / `HttpResponse.body` are `number[]` (tsify's `Vec<u8>`) | `Uint8Array` both ways |
97
+ | `LoggingConfig` fields required-but-nullable; `crate_filters` snake_case | truly optional; camelCase `crateFilters` |
98
+ | `progress_cb?: Function \| null` | typed `(event: ProveProgress) => void` |
99
+ | `prove()` returns a `ProveOutput` class the caller must `free()` / dispose | plain object; the wasm handle is freed by the façade |
100
+
101
+ Passed through **unchanged**: `IssuanceConfig`, `RevealPolicy` (all fields
102
+ required by design — a partial policy is refused rather than silently
103
+ completed), `BodyReveal`, `RootStore`, and `present`'s omitted-policy
104
+ fallback.
105
+
106
+ ## The `IoChannel` contract
107
+
108
+ `WsIoChannel` implements the interface the wasm side expects. The shape is
109
+ declared locally in `src/types.ts` (so this package's `.d.ts` never references
110
+ the unpublished pkg) and **compile-time asserted identical** to the generated
111
+ `../pkg/client_wasm.d.ts` — which is itself generated from the Rust
112
+ `typescript_custom_section` in `../src/io.rs`, the single source of truth —
113
+ by `src/wasm-compat.ts`:
114
+
115
+ ```ts
116
+ interface IoChannel {
117
+ read(): Promise<Uint8Array | null>; // next inbound frame, or null on EOF
118
+ write(data: Uint8Array): Promise<void>;
119
+ close(): Promise<void>;
120
+ }
121
+ ```
122
+
123
+ Semantics (mirroring the native `WsByteStream`): `read()` returns one inbound
124
+ binary frame per call (the Rust adapter buffers leftovers, so frame boundaries
125
+ needn't align with reads); a socket close/error resolves `read()` with `null`
126
+ (EOF → `Ok(0)` in Rust); empty frames are skipped, not treated as EOF;
127
+ `write()` resolves once bytes are queued in the browser send buffer (the
128
+ browser flushes to the wire on its own — the reason the Rust write-completion
129
+ queue in `io.rs` is satisfied immediately here).
130
+
131
+ ### Why two different channels
132
+
133
+ - **Notary** — browsers can't set an `Authorization` header on a WebSocket
134
+ handshake, only subprotocols, so the bearer token rides in
135
+ `Sec-WebSocket-Protocol` as `tlsn.notary.v2, bearer.<token>` (CLIENT_CONTRACT
136
+ §2). `connectNotary` asserts the notary negotiated `tlsn.notary.v2` back (it
137
+ echoes only the marker, never the token) before resolving.
138
+ - **Server (via proxy)** — a browser extension can't open raw TCP, so the target
139
+ connection tunnels through the `p2p-wss-proxy` worker (`dep/cf-workers`; see
140
+ JOURNAL toplevel/06): `connectProxy` opens
141
+ `ws://<proxyBase>/?host=<host>&port=<port>` (no subprotocol/auth) and the
142
+ worker relays bytes to a raw TCP socket. MPC-TLS runs over this pipe.
143
+
144
+ ## Building & typechecking
145
+
146
+ The generated wasm package (`../pkg`) must exist first — `src/wasm-compat.ts`
147
+ asserts this package's locally-declared types against the generated
148
+ `client_wasm.d.ts` (resolved via the `paths` mapping in `tsconfig.json`).
149
+ There is **no runtime dependency** on `../pkg`: every import of it is
150
+ type-only and erased, so the emitted `dist/` imports nothing from it (verify
151
+ with `grep -rE 'from "client-wasm"' dist/` → nothing).
152
+
153
+ ```sh
154
+ ../build.sh # 1. build the wasm pkg (produces ../pkg/client_wasm.d.ts)
155
+ npm install # 2. dev-only (TypeScript); no runtime deps
156
+ npm run typecheck # tsc --noEmit — includes the wasm-compat drift check
157
+ npm run build # emit dist/ (ESM + .d.ts)
158
+ ```
159
+
160
+ ## Running outside a browser (Node)
161
+
162
+ `connect*` use the global `WebSocket` by default. To run under Node (e.g. the
163
+ deferred single-threaded e2e — see [`../RUN_E2E.md`](../RUN_E2E.md)), inject an
164
+ implementation: `connectNotary(url, token, { WebSocketImpl: WsFromNodePackage })`.
165
+
166
+ ## Integrator note (cross-origin isolation)
167
+
168
+ The multi-threaded wasm build uses `SharedArrayBuffer`, so the embedding
169
+ page/extension **must be cross-origin isolated** (COOP: `same-origin` + COEP:
170
+ `require-corp`). Plan the extension/page headers accordingly. A failed
171
+ `initialize()` (e.g. missing those headers) releases the façade's memo, so
172
+ calling it again after fixing the environment retries for real.
@@ -0,0 +1,48 @@
1
+ import type { IoChannel } from "./types.js";
2
+ /**
3
+ * Injectable `WebSocket` constructor. Defaults to the global browser
4
+ * `WebSocket`. Supplying one lets the transport run under a polyfill (e.g. the
5
+ * `ws` package in Node for the deferred single-threaded run — see RUN_E2E.md),
6
+ * without any code change.
7
+ */
8
+ export type WebSocketCtor = {
9
+ new (url: string, protocols?: string | string[]): WebSocket;
10
+ };
11
+ /**
12
+ * Adapts a browser `WebSocket` into the wasm prover's `IoChannel`.
13
+ *
14
+ * ## Byte-stream semantics (mirrors the native `WsByteStream`)
15
+ *
16
+ * - **read()** resolves the next inbound binary frame as a `Uint8Array`, one
17
+ * frame per call. The Rust `JsIoAdapter` buffers any leftover bytes, so frame
18
+ * boundaries need not align with the reader's buffer. When no frame is
19
+ * buffered the returned promise stays pending until one arrives (or EOF).
20
+ * - **EOF** — a socket `close` or `error` resolves `read()` with `null`, which
21
+ * Rust maps to `Ok(0)` (io.rs treats null / empty as EOF). Empty binary
22
+ * frames are *skipped*, not treated as EOF, exactly as `WsByteStream` skips a
23
+ * zero-length payload rather than reporting end-of-stream.
24
+ * - **write()** sends `data` as a binary frame and resolves as soon as the
25
+ * bytes are queued in the browser's send buffer. The browser flushes to the
26
+ * wire on its own — unlike tungstenite, whose userspace buffering forced the
27
+ * native eager-flush fix (`ws.rs`) and the io.rs write-completion queue. That
28
+ * queue is therefore satisfied immediately here (the returned promise is
29
+ * already resolved), which is correct: "send() called" ⇒ "bytes will reach
30
+ * the wire" for a browser `WebSocket`.
31
+ *
32
+ * Invariant kept by the buffering: at most one of `#queue` / `#waiters` is
33
+ * non-empty at any time (read() drains the queue before ever parking a waiter,
34
+ * and onMessage delivers to a waiter only when the queue is empty), so inbound
35
+ * ordering is preserved with no reordering.
36
+ */
37
+ export declare class WsIoChannel implements IoChannel {
38
+ #private;
39
+ constructor(ws: WebSocket);
40
+ /** Resolves once the socket is open; rejects if it fails to open. */
41
+ whenReady(): Promise<void>;
42
+ /** The subprotocol the server selected (`""` until open / if none). */
43
+ get protocol(): string;
44
+ read(): Promise<Uint8Array | null>;
45
+ write(data: Uint8Array): Promise<void>;
46
+ close(): Promise<void>;
47
+ }
48
+ //# sourceMappingURL=channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAE5C;;;;;GAKG;AACH,MAAM,MAAM,aAAa,GAAG;IAC1B,KAAK,GAAG,EAAE,MAAM,EAAE,SAAS,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;CAC7D,CAAC;AAEF;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,qBAAa,WAAY,YAAW,SAAS;;IAW3C,YAAY,EAAE,EAAE,SAAS,EAgCxB;IAED,qEAAqE;IACrE,SAAS,IAAI,OAAO,CAAC,IAAI,CAAC,CAEzB;IAED,uEAAuE;IACvE,IAAI,QAAQ,IAAI,MAAM,CAErB;IAyBD,IAAI,IAAI,OAAO,CAAC,UAAU,GAAG,IAAI,CAAC,CAKjC;IAEK,KAAK,CAAC,IAAI,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAe3C;IAED,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAcrB;CACF"}
@@ -0,0 +1,150 @@
1
+ /**
2
+ * Adapts a browser `WebSocket` into the wasm prover's `IoChannel`.
3
+ *
4
+ * ## Byte-stream semantics (mirrors the native `WsByteStream`)
5
+ *
6
+ * - **read()** resolves the next inbound binary frame as a `Uint8Array`, one
7
+ * frame per call. The Rust `JsIoAdapter` buffers any leftover bytes, so frame
8
+ * boundaries need not align with the reader's buffer. When no frame is
9
+ * buffered the returned promise stays pending until one arrives (or EOF).
10
+ * - **EOF** — a socket `close` or `error` resolves `read()` with `null`, which
11
+ * Rust maps to `Ok(0)` (io.rs treats null / empty as EOF). Empty binary
12
+ * frames are *skipped*, not treated as EOF, exactly as `WsByteStream` skips a
13
+ * zero-length payload rather than reporting end-of-stream.
14
+ * - **write()** sends `data` as a binary frame and resolves as soon as the
15
+ * bytes are queued in the browser's send buffer. The browser flushes to the
16
+ * wire on its own — unlike tungstenite, whose userspace buffering forced the
17
+ * native eager-flush fix (`ws.rs`) and the io.rs write-completion queue. That
18
+ * queue is therefore satisfied immediately here (the returned promise is
19
+ * already resolved), which is correct: "send() called" ⇒ "bytes will reach
20
+ * the wire" for a browser `WebSocket`.
21
+ *
22
+ * Invariant kept by the buffering: at most one of `#queue` / `#waiters` is
23
+ * non-empty at any time (read() drains the queue before ever parking a waiter,
24
+ * and onMessage delivers to a waiter only when the queue is empty), so inbound
25
+ * ordering is preserved with no reordering.
26
+ */
27
+ export class WsIoChannel {
28
+ #ws;
29
+ /** Inbound frames received while no reader was waiting (FIFO). */
30
+ #queue = [];
31
+ /** Parked `read()` resolvers awaiting the next frame (FIFO). */
32
+ #waiters = [];
33
+ /** Resolves on `open`; rejects if the socket errors/closes before opening. */
34
+ #ready;
35
+ /** Set once the socket has closed (or errored) — all further reads are EOF. */
36
+ #closed = false;
37
+ constructor(ws) {
38
+ this.#ws = ws;
39
+ // Must be set before any message arrives so binary frames arrive as
40
+ // ArrayBuffer (not Blob); safe to set synchronously right after construction.
41
+ ws.binaryType = "arraybuffer";
42
+ this.#ready = new Promise((resolve, reject) => {
43
+ if (ws.readyState === WebSocket.OPEN) {
44
+ resolve();
45
+ return;
46
+ }
47
+ ws.addEventListener("open", () => resolve(), { once: true });
48
+ // A failed handshake (bad auth, unreachable proxy, …) fires error/close
49
+ // *before* open — surface it to the awaiter instead of hanging.
50
+ ws.addEventListener("close", (ev) => reject(new Error(`websocket closed before open (code ${ev.code})`)), { once: true });
51
+ ws.addEventListener("error", () => reject(new Error("websocket error before open")), {
52
+ once: true,
53
+ });
54
+ });
55
+ // Swallow the ready rejection here so it never becomes an unhandled
56
+ // rejection; callers observe it via `whenReady()` (and reads see EOF).
57
+ this.#ready.catch(() => { });
58
+ ws.addEventListener("message", (ev) => this.#onMessage(ev));
59
+ ws.addEventListener("close", () => this.#onEof());
60
+ // Browsers emit `error` then `close`; treat either as end-of-stream for
61
+ // readers. `#onEof` is idempotent, so the trailing `close` is a no-op.
62
+ ws.addEventListener("error", () => this.#onEof());
63
+ }
64
+ /** Resolves once the socket is open; rejects if it fails to open. */
65
+ whenReady() {
66
+ return this.#ready;
67
+ }
68
+ /** The subprotocol the server selected (`""` until open / if none). */
69
+ get protocol() {
70
+ return this.#ws.protocol;
71
+ }
72
+ #onMessage(ev) {
73
+ const chunk = toBytes(ev.data);
74
+ // Skip zero-length frames rather than signalling EOF (matches WsByteStream,
75
+ // which loops past an empty payload). An empty read *would* be read as EOF
76
+ // by io.rs, so this guard is load-bearing.
77
+ if (chunk === null || chunk.length === 0)
78
+ return;
79
+ const waiter = this.#waiters.shift();
80
+ if (waiter)
81
+ waiter(chunk);
82
+ else
83
+ this.#queue.push(chunk);
84
+ }
85
+ #onEof() {
86
+ if (this.#closed)
87
+ return;
88
+ this.#closed = true;
89
+ // Wake every parked reader with EOF; buffered frames (if any) were already
90
+ // delivered ahead of any waiter by the queue-first invariant.
91
+ let waiter;
92
+ while ((waiter = this.#waiters.shift()))
93
+ waiter(null);
94
+ }
95
+ // --- IoChannel ---------------------------------------------------------
96
+ read() {
97
+ const buffered = this.#queue.shift();
98
+ if (buffered !== undefined)
99
+ return Promise.resolve(buffered);
100
+ if (this.#closed)
101
+ return Promise.resolve(null);
102
+ return new Promise((resolve) => this.#waiters.push(resolve));
103
+ }
104
+ async write(data) {
105
+ await this.#ready;
106
+ if (this.#closed || this.#ws.readyState !== WebSocket.OPEN) {
107
+ // Fail loud: a silently-dropped write would strand a protocol frame and
108
+ // deadlock the notary (it never replies) — the exact hazard the io.rs
109
+ // write-completion fix guards against on the Rust side.
110
+ throw new Error("cannot write: websocket is not open");
111
+ }
112
+ // Copy into a fresh (non-shared) buffer before sending. `data` may be a view
113
+ // into the wasm linear memory, which in the multi-threaded build is a
114
+ // SharedArrayBuffer — and `WebSocket.send()` rejects SharedArrayBuffer-backed
115
+ // views in some browsers. `slice()` yields a plain-ArrayBuffer copy and also
116
+ // decouples us from however io.rs hands the bytes over. Cost is negligible
117
+ // (protocol frames are small).
118
+ this.#ws.send(data.slice());
119
+ }
120
+ close() {
121
+ if (this.#closed || this.#ws.readyState === WebSocket.CLOSED) {
122
+ this.#onEof();
123
+ return Promise.resolve();
124
+ }
125
+ return new Promise((resolve) => {
126
+ this.#ws.addEventListener("close", () => resolve(), { once: true });
127
+ try {
128
+ this.#ws.close();
129
+ }
130
+ catch {
131
+ // Already closing/closed — resolve; the EOF is handled by #onEof.
132
+ resolve();
133
+ }
134
+ });
135
+ }
136
+ }
137
+ /** Normalise a `MessageEvent.data` to bytes (arraybuffer / text / view). */
138
+ function toBytes(data) {
139
+ if (data instanceof ArrayBuffer)
140
+ return new Uint8Array(data);
141
+ if (ArrayBuffer.isView(data)) {
142
+ const view = data;
143
+ return new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
144
+ }
145
+ if (typeof data === "string")
146
+ return new TextEncoder().encode(data);
147
+ // Blob or unknown — unreachable while binaryType === "arraybuffer".
148
+ return null;
149
+ }
150
+ //# sourceMappingURL=channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.js","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAyBA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAM,OAAO,WAAW;IACb,GAAG,CAAY;IACxB,kEAAkE;IACzD,MAAM,GAAiB,EAAE,CAAC;IACnC,gEAAgE;IACvD,QAAQ,GAA2C,EAAE,CAAC;IAC/D,8EAA8E;IACrE,MAAM,CAAgB;IAC/B,+EAA+E;IAC/E,OAAO,GAAG,KAAK,CAAC;IAEhB,YAAY,EAAa;QACvB,IAAI,CAAC,GAAG,GAAG,EAAE,CAAC;QACd,oEAAoE;QACpE,8EAA8E;QAC9E,EAAE,CAAC,UAAU,GAAG,aAAa,CAAC;QAE9B,IAAI,CAAC,MAAM,GAAG,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YAClD,IAAI,EAAE,CAAC,UAAU,KAAK,SAAS,CAAC,IAAI,EAAE,CAAC;gBACrC,O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O,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;IACpE,oEAAoE;IACpE,OAAO,IAAI,CAAC;AACd,CAAC"}
@@ -0,0 +1,8 @@
1
+ export { WsIoChannel } from "./channel.js";
2
+ export type { WebSocketCtor } from "./channel.js";
3
+ export { NOTARY_SUBPROTOCOL, connectNotary, connectProxy } from "./transport.js";
4
+ export type { ConnectOptions } from "./transport.js";
5
+ export { createProver } from "./prover.js";
6
+ export type { ClientWasmModule, Prover } from "./prover.js";
7
+ export type { BodyReveal, CrateLogFilter, HttpRequest, HttpResponse, IoChannel, IssuanceConfig, LoggingConfig, LoggingLevel, ProgressCallback, ProveOutput, ProveProgress, RevealPolicy, RootStore, RootStorePreset, } from "./types.js";
8
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAeA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AACjF,YAAY,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAErD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,YAAY,EAAE,gBAAgB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;AAE5D,YAAY,EACV,UAAU,EACV,cAAc,EACd,WAAW,EACX,YAAY,EACZ,SAAS,EACT,cAAc,EACd,aAAa,EACb,YAAY,EACZ,gBAAgB,EAChB,WAAW,EACX,aAAa,EACb,YAAY,EACZ,SAAS,EACT,eAAe,GAChB,MAAM,YAAY,CAAC"}
@@ -0,0 +1,18 @@
1
+ // client-wasm-transport — the TS companion to the `client-wasm` wasm prover.
2
+ //
3
+ // Two layers, both wasm-free at runtime (this package emits **no** import of
4
+ // the wasm pkg — load-bearing for the extension bundle, see ./prover.ts):
5
+ //
6
+ // - **Transport** (`connectNotary` / `connectProxy` / `WsIoChannel`): the
7
+ // WebSocket `IoChannel`s `prove()` consumes.
8
+ // - **Prover façade** (`createProver`): a pass-through mirror of the wasm
9
+ // API (`initialize` / `prove` / `present`) over a caller-injected pkg
10
+ // module — owns instantiation + rayon-pool setup and the wire
11
+ // conversions.
12
+ //
13
+ // All DTO types are declared locally in ./types.ts (self-contained d.ts) and
14
+ // compile-time-checked against the generated pkg in ./wasm-compat.ts.
15
+ export { WsIoChannel } from "./channel.js";
16
+ export { NOTARY_SUBPROTOCOL, connectNotary, connectProxy } from "./transport.js";
17
+ export { createProver } from "./prover.js";
18
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,6EAA6E;AAC7E,EAAE;AACF,6EAA6E;AAC7E,0EAA0E;AAC1E,EAAE;AACF,4EAA4E;AAC5E,iDAAiD;AACjD,4EAA4E;AAC5E,0EAA0E;AAC1E,kEAAkE;AAClE,mBAAmB;AACnB,EAAE;AACF,6EAA6E;AAC7E,sEAAsE;AAEtE,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAG3C,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGjF,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC"}