@crdt-sync/core 0.1.2 → 0.2.1

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.
@@ -0,0 +1,233 @@
1
+ /**
2
+ * TypeScript interface matching the Wasm-bindgen-generated `WasmStateStore`.
3
+ *
4
+ * In production, import the real `WasmStateStore` from the compiled Wasm
5
+ * package (e.g. `import { WasmStateStore } from './crdt_sync.js'`).
6
+ * In tests the interface can be satisfied by any mock object.
7
+ */
8
+ interface WasmStateStore {
9
+ /** Write a JSON-encoded value to the named LWW register. Returns the Envelope JSON. */
10
+ set_register(key: string, value_json: string): string;
11
+ /** Read the current value of a named LWW register as a JSON string, or `undefined`. */
12
+ get_register(key: string): string | undefined;
13
+ /** Apply a remote Envelope (serialised as JSON) to this store. */
14
+ apply_envelope(envelope_json: string): void;
15
+ }
16
+ /**
17
+ * Payload delivered to every `onUpdate` listener when a property is written
18
+ * through the proxy.
19
+ */
20
+ interface UpdateEvent {
21
+ /** Dot-separated key path that was updated (e.g. `"robot.speed"`). */
22
+ key: string;
23
+ /** The new JavaScript value. */
24
+ value: unknown;
25
+ /**
26
+ * The CRDT Envelope returned by `WasmStateStore.set_register`, serialised
27
+ * as a JSON string. Broadcast this to peer nodes via `apply_envelope`.
28
+ */
29
+ envelope: string;
30
+ }
31
+ /** Callback type for `onUpdate` listeners. */
32
+ type UpdateHandler = (event: UpdateEvent) => void;
33
+ /**
34
+ * A TypeScript proxy wrapper around `WasmStateStore` that gives frontend
35
+ * developers a **magical, object-oriented** experience.
36
+ *
37
+ * ## How it works
38
+ *
39
+ * 1. **JS `Proxy` interception** – accessing a nested path on `state` returns
40
+ * another `Proxy`. Assigning a value anywhere in the tree intercepts the
41
+ * write and forwards it to the underlying Wasm store via
42
+ * `set_register(dotPath, JSON.stringify(value))`.
43
+ *
44
+ * 2. **Wasm call** – the interceptor immediately calls
45
+ * `WasmStateStore.set_register()` so the CRDT operation is recorded and
46
+ * returns an `Envelope` JSON string ready for broadcasting.
47
+ *
48
+ * 3. **Event emitter** – every write fires all `onUpdate` listeners with the
49
+ * full `UpdateEvent` (key, value, envelope), enabling React / Vue and other
50
+ * UI frameworks to react to state changes.
51
+ *
52
+ * ## Usage
53
+ *
54
+ * ```ts
55
+ * import init, { WasmStateStore } from './crdt_sync.js';
56
+ * import { CrdtStateProxy } from './CrdtStateProxy.js';
57
+ *
58
+ * await init();
59
+ * const store = new WasmStateStore('node-1');
60
+ * const proxy = new CrdtStateProxy(store);
61
+ *
62
+ * // Register a listener (e.g. trigger a React re-render).
63
+ * const unsubscribe = proxy.onUpdate(({ key, value, envelope }) => {
64
+ * console.log(`${key} =`, value);
65
+ * broadcast(envelope); // send to peers
66
+ * });
67
+ *
68
+ * // Write through the proxy — the interceptor handles everything.
69
+ * proxy.state.speed = 100;
70
+ * proxy.state.robot.x = 42;
71
+ *
72
+ * // Clean up when done.
73
+ * unsubscribe();
74
+ * ```
75
+ */
76
+ declare class CrdtStateProxy {
77
+ private readonly _store;
78
+ private readonly _handlers;
79
+ private readonly _state;
80
+ /**
81
+ * Create a new `CrdtStateProxy` backed by the given `WasmStateStore`.
82
+ *
83
+ * @param store - The Wasm state store instance to proxy.
84
+ */
85
+ constructor(store: WasmStateStore);
86
+ /**
87
+ * The proxied state object.
88
+ *
89
+ * Assigning any property (or nested property) on this object will
90
+ * automatically call `WasmStateStore.set_register` and fire `onUpdate`
91
+ * listeners.
92
+ *
93
+ * ```ts
94
+ * proxy.state.speed = 100; // key: "speed"
95
+ * proxy.state.robot.speed = 100; // key: "robot.speed"
96
+ * ```
97
+ */
98
+ get state(): Record<string, unknown>;
99
+ /**
100
+ * Register a listener that is called whenever a property is written through
101
+ * `proxy.state`.
102
+ *
103
+ * @param handler - Callback receiving an `UpdateEvent`.
104
+ * @returns An unsubscribe function — call it to remove the listener.
105
+ */
106
+ onUpdate(handler: UpdateHandler): () => void;
107
+ /**
108
+ * Recursively build a `Proxy` for the given dot-path `prefix`.
109
+ *
110
+ * - **`get` trap**: returns a child proxy for the nested path so that deep
111
+ * assignments like `proxy.state.robot.speed = 100` work correctly.
112
+ * - **`set` trap**: serialises the value, calls `set_register`, and fires
113
+ * all `onUpdate` listeners.
114
+ */
115
+ private _makeProxy;
116
+ /** Dispatch an `UpdateEvent` to all registered handlers. */
117
+ private _emit;
118
+ }
119
+
120
+ /**
121
+ * Minimal subset of the browser `WebSocket` API used by `WebSocketManager`.
122
+ *
123
+ * The real browser `WebSocket` satisfies this interface out-of-the-box.
124
+ * In tests, a plain mock object can be used instead.
125
+ */
126
+ interface WebSocketLike {
127
+ /** Current connection state (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED). */
128
+ readonly readyState: number;
129
+ /** Send a UTF-8 string frame to the server. */
130
+ send(data: string): void;
131
+ /** Initiate the closing handshake. */
132
+ close(): void;
133
+ /** Fired when a message frame is received. */
134
+ onmessage: ((event: {
135
+ data: string;
136
+ }) => void) | null;
137
+ /** Fired when the connection is established. */
138
+ onopen: ((event: unknown) => void) | null;
139
+ /** Fired when the connection is closed. */
140
+ onclose: ((event: unknown) => void) | null;
141
+ /** Fired when an error occurs. */
142
+ onerror: ((event: unknown) => void) | null;
143
+ }
144
+ /**
145
+ * Bridges a `CrdtStateProxy` to a WebSocket connection so that every CRDT
146
+ * operation produced locally is broadcast to peers, and every envelope
147
+ * received from a peer is applied to the local store.
148
+ *
149
+ * ## Data flow
150
+ *
151
+ * ```
152
+ * Local write
153
+ * → CrdtStateProxy.onUpdate (envelope collected in _pendingEnvelopes)
154
+ * → requestAnimationFrame / setTimeout schedules a batch flush
155
+ * → WebSocket.send(JSON.stringify(envelopes)) // one payload per frame
156
+ *
157
+ * Incoming message (single envelope or JSON array of envelopes)
158
+ * → WebSocket.onmessage
159
+ * → WasmStateStore.apply_envelope() // merge into local store
160
+ * ```
161
+ *
162
+ * ## Throttling / batching
163
+ *
164
+ * Multiple proxy writes that occur within the same JavaScript task (e.g. a
165
+ * 60 FPS game loop) are collected in `_pendingEnvelopes` and sent as a single
166
+ * JSON array payload on the next animation frame (browser) or the next
167
+ * `setTimeout(fn, 0)` tick (Node.js / non-browser environments). This keeps
168
+ * network traffic proportional to frame rate rather than to the raw mutation
169
+ * rate.
170
+ *
171
+ * ## Usage
172
+ *
173
+ * ```ts
174
+ * import init, { WasmStateStore } from './crdt_sync.js';
175
+ * import { CrdtStateProxy, WebSocketManager } from './index.js';
176
+ *
177
+ * await init();
178
+ * const store = new WasmStateStore('node-1');
179
+ * const proxy = new CrdtStateProxy(store);
180
+ * const manager = new WebSocketManager(store, proxy, new WebSocket('wss://example.com/sync'));
181
+ *
182
+ * // Writes are automatically batched and broadcast to peers.
183
+ * proxy.state.robot = { x: 10, y: 20 };
184
+ *
185
+ * // Clean up.
186
+ * manager.disconnect();
187
+ * ```
188
+ */
189
+ declare class WebSocketManager {
190
+ private readonly _store;
191
+ private readonly _proxy;
192
+ private readonly _ws;
193
+ private _unsubscribe;
194
+ /** Envelopes collected in the current frame, waiting for the batch flush. */
195
+ private _pendingEnvelopes;
196
+ /** Cancels the currently scheduled batch flush (rAF or setTimeout handle). */
197
+ private _cancelFlush;
198
+ /** Envelopes queued while the socket is not open, flushed on reconnection. */
199
+ private _offlineQueue;
200
+ /**
201
+ * Create a `WebSocketManager` and attach it to the given WebSocket.
202
+ *
203
+ * @param store - The Wasm state store. Incoming peer envelopes will be
204
+ * applied to this store via `apply_envelope`.
205
+ * @param proxy - The CRDT state proxy. Outgoing envelopes produced by
206
+ * `set_register` calls will be read from the proxy's `onUpdate` events.
207
+ * @param ws - An open or connecting WebSocket (or any `WebSocketLike` object).
208
+ */
209
+ constructor(store: WasmStateStore, proxy: CrdtStateProxy, ws: WebSocketLike);
210
+ private _attach;
211
+ /**
212
+ * Schedule a single batch flush for the current frame. Subsequent calls
213
+ * before the flush fires are no-ops (only one flush is ever outstanding).
214
+ *
215
+ * Uses `requestAnimationFrame` when available (browser, ~60 FPS cadence),
216
+ * falling back to `setTimeout(fn, 0)` in non-browser environments.
217
+ */
218
+ private _scheduleBatchFlush;
219
+ /**
220
+ * Send all pending envelopes as a single JSON-array payload, or move them
221
+ * to the offline queue if the socket is not currently open.
222
+ */
223
+ private _flushBatch;
224
+ /**
225
+ * Unsubscribe from proxy updates, discard any buffered envelopes, and close
226
+ * the WebSocket connection.
227
+ *
228
+ * Safe to call more than once.
229
+ */
230
+ disconnect(): void;
231
+ }
232
+
233
+ export { CrdtStateProxy, type UpdateEvent, type UpdateHandler, type WasmStateStore, type WebSocketLike, WebSocketManager };
package/dist/index.d.ts CHANGED
@@ -1,5 +1,233 @@
1
- export { CrdtStateProxy } from './CrdtStateProxy.js';
2
- export type { WasmStateStore, UpdateEvent, UpdateHandler } from './CrdtStateProxy.js';
3
- export { WebSocketManager } from './WebSocketManager.js';
4
- export type { WebSocketLike } from './WebSocketManager.js';
5
- //# sourceMappingURL=index.d.ts.map
1
+ /**
2
+ * TypeScript interface matching the Wasm-bindgen-generated `WasmStateStore`.
3
+ *
4
+ * In production, import the real `WasmStateStore` from the compiled Wasm
5
+ * package (e.g. `import { WasmStateStore } from './crdt_sync.js'`).
6
+ * In tests the interface can be satisfied by any mock object.
7
+ */
8
+ interface WasmStateStore {
9
+ /** Write a JSON-encoded value to the named LWW register. Returns the Envelope JSON. */
10
+ set_register(key: string, value_json: string): string;
11
+ /** Read the current value of a named LWW register as a JSON string, or `undefined`. */
12
+ get_register(key: string): string | undefined;
13
+ /** Apply a remote Envelope (serialised as JSON) to this store. */
14
+ apply_envelope(envelope_json: string): void;
15
+ }
16
+ /**
17
+ * Payload delivered to every `onUpdate` listener when a property is written
18
+ * through the proxy.
19
+ */
20
+ interface UpdateEvent {
21
+ /** Dot-separated key path that was updated (e.g. `"robot.speed"`). */
22
+ key: string;
23
+ /** The new JavaScript value. */
24
+ value: unknown;
25
+ /**
26
+ * The CRDT Envelope returned by `WasmStateStore.set_register`, serialised
27
+ * as a JSON string. Broadcast this to peer nodes via `apply_envelope`.
28
+ */
29
+ envelope: string;
30
+ }
31
+ /** Callback type for `onUpdate` listeners. */
32
+ type UpdateHandler = (event: UpdateEvent) => void;
33
+ /**
34
+ * A TypeScript proxy wrapper around `WasmStateStore` that gives frontend
35
+ * developers a **magical, object-oriented** experience.
36
+ *
37
+ * ## How it works
38
+ *
39
+ * 1. **JS `Proxy` interception** – accessing a nested path on `state` returns
40
+ * another `Proxy`. Assigning a value anywhere in the tree intercepts the
41
+ * write and forwards it to the underlying Wasm store via
42
+ * `set_register(dotPath, JSON.stringify(value))`.
43
+ *
44
+ * 2. **Wasm call** – the interceptor immediately calls
45
+ * `WasmStateStore.set_register()` so the CRDT operation is recorded and
46
+ * returns an `Envelope` JSON string ready for broadcasting.
47
+ *
48
+ * 3. **Event emitter** – every write fires all `onUpdate` listeners with the
49
+ * full `UpdateEvent` (key, value, envelope), enabling React / Vue and other
50
+ * UI frameworks to react to state changes.
51
+ *
52
+ * ## Usage
53
+ *
54
+ * ```ts
55
+ * import init, { WasmStateStore } from './crdt_sync.js';
56
+ * import { CrdtStateProxy } from './CrdtStateProxy.js';
57
+ *
58
+ * await init();
59
+ * const store = new WasmStateStore('node-1');
60
+ * const proxy = new CrdtStateProxy(store);
61
+ *
62
+ * // Register a listener (e.g. trigger a React re-render).
63
+ * const unsubscribe = proxy.onUpdate(({ key, value, envelope }) => {
64
+ * console.log(`${key} =`, value);
65
+ * broadcast(envelope); // send to peers
66
+ * });
67
+ *
68
+ * // Write through the proxy — the interceptor handles everything.
69
+ * proxy.state.speed = 100;
70
+ * proxy.state.robot.x = 42;
71
+ *
72
+ * // Clean up when done.
73
+ * unsubscribe();
74
+ * ```
75
+ */
76
+ declare class CrdtStateProxy {
77
+ private readonly _store;
78
+ private readonly _handlers;
79
+ private readonly _state;
80
+ /**
81
+ * Create a new `CrdtStateProxy` backed by the given `WasmStateStore`.
82
+ *
83
+ * @param store - The Wasm state store instance to proxy.
84
+ */
85
+ constructor(store: WasmStateStore);
86
+ /**
87
+ * The proxied state object.
88
+ *
89
+ * Assigning any property (or nested property) on this object will
90
+ * automatically call `WasmStateStore.set_register` and fire `onUpdate`
91
+ * listeners.
92
+ *
93
+ * ```ts
94
+ * proxy.state.speed = 100; // key: "speed"
95
+ * proxy.state.robot.speed = 100; // key: "robot.speed"
96
+ * ```
97
+ */
98
+ get state(): Record<string, unknown>;
99
+ /**
100
+ * Register a listener that is called whenever a property is written through
101
+ * `proxy.state`.
102
+ *
103
+ * @param handler - Callback receiving an `UpdateEvent`.
104
+ * @returns An unsubscribe function — call it to remove the listener.
105
+ */
106
+ onUpdate(handler: UpdateHandler): () => void;
107
+ /**
108
+ * Recursively build a `Proxy` for the given dot-path `prefix`.
109
+ *
110
+ * - **`get` trap**: returns a child proxy for the nested path so that deep
111
+ * assignments like `proxy.state.robot.speed = 100` work correctly.
112
+ * - **`set` trap**: serialises the value, calls `set_register`, and fires
113
+ * all `onUpdate` listeners.
114
+ */
115
+ private _makeProxy;
116
+ /** Dispatch an `UpdateEvent` to all registered handlers. */
117
+ private _emit;
118
+ }
119
+
120
+ /**
121
+ * Minimal subset of the browser `WebSocket` API used by `WebSocketManager`.
122
+ *
123
+ * The real browser `WebSocket` satisfies this interface out-of-the-box.
124
+ * In tests, a plain mock object can be used instead.
125
+ */
126
+ interface WebSocketLike {
127
+ /** Current connection state (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED). */
128
+ readonly readyState: number;
129
+ /** Send a UTF-8 string frame to the server. */
130
+ send(data: string): void;
131
+ /** Initiate the closing handshake. */
132
+ close(): void;
133
+ /** Fired when a message frame is received. */
134
+ onmessage: ((event: {
135
+ data: string;
136
+ }) => void) | null;
137
+ /** Fired when the connection is established. */
138
+ onopen: ((event: unknown) => void) | null;
139
+ /** Fired when the connection is closed. */
140
+ onclose: ((event: unknown) => void) | null;
141
+ /** Fired when an error occurs. */
142
+ onerror: ((event: unknown) => void) | null;
143
+ }
144
+ /**
145
+ * Bridges a `CrdtStateProxy` to a WebSocket connection so that every CRDT
146
+ * operation produced locally is broadcast to peers, and every envelope
147
+ * received from a peer is applied to the local store.
148
+ *
149
+ * ## Data flow
150
+ *
151
+ * ```
152
+ * Local write
153
+ * → CrdtStateProxy.onUpdate (envelope collected in _pendingEnvelopes)
154
+ * → requestAnimationFrame / setTimeout schedules a batch flush
155
+ * → WebSocket.send(JSON.stringify(envelopes)) // one payload per frame
156
+ *
157
+ * Incoming message (single envelope or JSON array of envelopes)
158
+ * → WebSocket.onmessage
159
+ * → WasmStateStore.apply_envelope() // merge into local store
160
+ * ```
161
+ *
162
+ * ## Throttling / batching
163
+ *
164
+ * Multiple proxy writes that occur within the same JavaScript task (e.g. a
165
+ * 60 FPS game loop) are collected in `_pendingEnvelopes` and sent as a single
166
+ * JSON array payload on the next animation frame (browser) or the next
167
+ * `setTimeout(fn, 0)` tick (Node.js / non-browser environments). This keeps
168
+ * network traffic proportional to frame rate rather than to the raw mutation
169
+ * rate.
170
+ *
171
+ * ## Usage
172
+ *
173
+ * ```ts
174
+ * import init, { WasmStateStore } from './crdt_sync.js';
175
+ * import { CrdtStateProxy, WebSocketManager } from './index.js';
176
+ *
177
+ * await init();
178
+ * const store = new WasmStateStore('node-1');
179
+ * const proxy = new CrdtStateProxy(store);
180
+ * const manager = new WebSocketManager(store, proxy, new WebSocket('wss://example.com/sync'));
181
+ *
182
+ * // Writes are automatically batched and broadcast to peers.
183
+ * proxy.state.robot = { x: 10, y: 20 };
184
+ *
185
+ * // Clean up.
186
+ * manager.disconnect();
187
+ * ```
188
+ */
189
+ declare class WebSocketManager {
190
+ private readonly _store;
191
+ private readonly _proxy;
192
+ private readonly _ws;
193
+ private _unsubscribe;
194
+ /** Envelopes collected in the current frame, waiting for the batch flush. */
195
+ private _pendingEnvelopes;
196
+ /** Cancels the currently scheduled batch flush (rAF or setTimeout handle). */
197
+ private _cancelFlush;
198
+ /** Envelopes queued while the socket is not open, flushed on reconnection. */
199
+ private _offlineQueue;
200
+ /**
201
+ * Create a `WebSocketManager` and attach it to the given WebSocket.
202
+ *
203
+ * @param store - The Wasm state store. Incoming peer envelopes will be
204
+ * applied to this store via `apply_envelope`.
205
+ * @param proxy - The CRDT state proxy. Outgoing envelopes produced by
206
+ * `set_register` calls will be read from the proxy's `onUpdate` events.
207
+ * @param ws - An open or connecting WebSocket (or any `WebSocketLike` object).
208
+ */
209
+ constructor(store: WasmStateStore, proxy: CrdtStateProxy, ws: WebSocketLike);
210
+ private _attach;
211
+ /**
212
+ * Schedule a single batch flush for the current frame. Subsequent calls
213
+ * before the flush fires are no-ops (only one flush is ever outstanding).
214
+ *
215
+ * Uses `requestAnimationFrame` when available (browser, ~60 FPS cadence),
216
+ * falling back to `setTimeout(fn, 0)` in non-browser environments.
217
+ */
218
+ private _scheduleBatchFlush;
219
+ /**
220
+ * Send all pending envelopes as a single JSON-array payload, or move them
221
+ * to the offline queue if the socket is not currently open.
222
+ */
223
+ private _flushBatch;
224
+ /**
225
+ * Unsubscribe from proxy updates, discard any buffered envelopes, and close
226
+ * the WebSocket connection.
227
+ *
228
+ * Safe to call more than once.
229
+ */
230
+ disconnect(): void;
231
+ }
232
+
233
+ export { CrdtStateProxy, type UpdateEvent, type UpdateHandler, type WasmStateStore, type WebSocketLike, WebSocketManager };
package/dist/index.js CHANGED
@@ -1,8 +1,222 @@
1
1
  "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.WebSocketManager = exports.CrdtStateProxy = void 0;
4
- var CrdtStateProxy_js_1 = require("./CrdtStateProxy.js");
5
- Object.defineProperty(exports, "CrdtStateProxy", { enumerable: true, get: function () { return CrdtStateProxy_js_1.CrdtStateProxy; } });
6
- var WebSocketManager_js_1 = require("./WebSocketManager.js");
7
- Object.defineProperty(exports, "WebSocketManager", { enumerable: true, get: function () { return WebSocketManager_js_1.WebSocketManager; } });
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ CrdtStateProxy: () => CrdtStateProxy,
24
+ WebSocketManager: () => WebSocketManager
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+
28
+ // src/CrdtStateProxy.ts
29
+ var CrdtStateProxy = class {
30
+ /**
31
+ * Create a new `CrdtStateProxy` backed by the given `WasmStateStore`.
32
+ *
33
+ * @param store - The Wasm state store instance to proxy.
34
+ */
35
+ constructor(store) {
36
+ this._handlers = /* @__PURE__ */ new Set();
37
+ this._store = store;
38
+ this._state = this._makeProxy("");
39
+ }
40
+ // ── Public API ────────────────────────────────────────────────────────
41
+ /**
42
+ * The proxied state object.
43
+ *
44
+ * Assigning any property (or nested property) on this object will
45
+ * automatically call `WasmStateStore.set_register` and fire `onUpdate`
46
+ * listeners.
47
+ *
48
+ * ```ts
49
+ * proxy.state.speed = 100; // key: "speed"
50
+ * proxy.state.robot.speed = 100; // key: "robot.speed"
51
+ * ```
52
+ */
53
+ get state() {
54
+ return this._state;
55
+ }
56
+ /**
57
+ * Register a listener that is called whenever a property is written through
58
+ * `proxy.state`.
59
+ *
60
+ * @param handler - Callback receiving an `UpdateEvent`.
61
+ * @returns An unsubscribe function — call it to remove the listener.
62
+ */
63
+ onUpdate(handler) {
64
+ this._handlers.add(handler);
65
+ return () => {
66
+ this._handlers.delete(handler);
67
+ };
68
+ }
69
+ // ── Internal helpers ──────────────────────────────────────────────────
70
+ /**
71
+ * Recursively build a `Proxy` for the given dot-path `prefix`.
72
+ *
73
+ * - **`get` trap**: returns a child proxy for the nested path so that deep
74
+ * assignments like `proxy.state.robot.speed = 100` work correctly.
75
+ * - **`set` trap**: serialises the value, calls `set_register`, and fires
76
+ * all `onUpdate` listeners.
77
+ */
78
+ _makeProxy(prefix) {
79
+ const children = {};
80
+ return new Proxy({}, {
81
+ get: (_target, prop) => {
82
+ const key = prefix ? `${prefix}.${prop}` : prop;
83
+ if (!(prop in children)) {
84
+ children[prop] = this._makeProxy(key);
85
+ }
86
+ return children[prop];
87
+ },
88
+ set: (_target, prop, value) => {
89
+ const key = prefix ? `${prefix}.${prop}` : prop;
90
+ const envelope = this._store.set_register(key, JSON.stringify(value));
91
+ this._emit({ key, value, envelope });
92
+ return true;
93
+ }
94
+ });
95
+ }
96
+ /** Dispatch an `UpdateEvent` to all registered handlers. */
97
+ _emit(event) {
98
+ this._handlers.forEach((handler) => handler(event));
99
+ }
100
+ };
101
+
102
+ // src/WebSocketManager.ts
103
+ var WebSocketManager = class {
104
+ /**
105
+ * Create a `WebSocketManager` and attach it to the given WebSocket.
106
+ *
107
+ * @param store - The Wasm state store. Incoming peer envelopes will be
108
+ * applied to this store via `apply_envelope`.
109
+ * @param proxy - The CRDT state proxy. Outgoing envelopes produced by
110
+ * `set_register` calls will be read from the proxy's `onUpdate` events.
111
+ * @param ws - An open or connecting WebSocket (or any `WebSocketLike` object).
112
+ */
113
+ constructor(store, proxy, ws) {
114
+ this._unsubscribe = null;
115
+ /** Envelopes collected in the current frame, waiting for the batch flush. */
116
+ this._pendingEnvelopes = [];
117
+ /** Cancels the currently scheduled batch flush (rAF or setTimeout handle). */
118
+ this._cancelFlush = null;
119
+ /** Envelopes queued while the socket is not open, flushed on reconnection. */
120
+ this._offlineQueue = [];
121
+ this._store = store;
122
+ this._proxy = proxy;
123
+ this._ws = ws;
124
+ this._attach();
125
+ }
126
+ // ── Internal setup ────────────────────────────────────────────────────
127
+ _attach() {
128
+ const ws = this._ws;
129
+ this._unsubscribe = this._proxy.onUpdate(({ envelope }) => {
130
+ this._pendingEnvelopes.push(envelope);
131
+ this._scheduleBatchFlush();
132
+ });
133
+ ws.onopen = () => {
134
+ this._cancelFlush?.();
135
+ this._cancelFlush = null;
136
+ const offline = this._offlineQueue;
137
+ const pending = this._pendingEnvelopes;
138
+ this._offlineQueue = [];
139
+ this._pendingEnvelopes = [];
140
+ const batch = [...offline, ...pending];
141
+ if (batch.length > 0) {
142
+ ws.send(JSON.stringify(batch));
143
+ }
144
+ };
145
+ ws.onmessage = (event) => {
146
+ let parsed;
147
+ try {
148
+ parsed = JSON.parse(event.data);
149
+ } catch {
150
+ parsed = null;
151
+ }
152
+ if (Array.isArray(parsed)) {
153
+ for (const env of parsed) {
154
+ this._store.apply_envelope(env);
155
+ }
156
+ } else {
157
+ this._store.apply_envelope(event.data);
158
+ }
159
+ };
160
+ ws.onclose = () => {
161
+ };
162
+ ws.onerror = () => {
163
+ };
164
+ }
165
+ /**
166
+ * Schedule a single batch flush for the current frame. Subsequent calls
167
+ * before the flush fires are no-ops (only one flush is ever outstanding).
168
+ *
169
+ * Uses `requestAnimationFrame` when available (browser, ~60 FPS cadence),
170
+ * falling back to `setTimeout(fn, 0)` in non-browser environments.
171
+ */
172
+ _scheduleBatchFlush() {
173
+ if (this._cancelFlush !== null) return;
174
+ const doFlush = () => {
175
+ this._cancelFlush = null;
176
+ this._flushBatch();
177
+ };
178
+ if (typeof requestAnimationFrame === "function") {
179
+ const id = requestAnimationFrame(doFlush);
180
+ this._cancelFlush = () => cancelAnimationFrame(id);
181
+ } else {
182
+ const id = setTimeout(doFlush, 0);
183
+ this._cancelFlush = () => clearTimeout(id);
184
+ }
185
+ }
186
+ /**
187
+ * Send all pending envelopes as a single JSON-array payload, or move them
188
+ * to the offline queue if the socket is not currently open.
189
+ */
190
+ _flushBatch() {
191
+ const envelopes = this._pendingEnvelopes.splice(0);
192
+ if (envelopes.length === 0) return;
193
+ const ws = this._ws;
194
+ if (ws.readyState === 1) {
195
+ ws.send(JSON.stringify(envelopes));
196
+ } else {
197
+ this._offlineQueue.push(...envelopes);
198
+ }
199
+ }
200
+ // ── Public API ────────────────────────────────────────────────────────
201
+ /**
202
+ * Unsubscribe from proxy updates, discard any buffered envelopes, and close
203
+ * the WebSocket connection.
204
+ *
205
+ * Safe to call more than once.
206
+ */
207
+ disconnect() {
208
+ this._unsubscribe?.();
209
+ this._unsubscribe = null;
210
+ this._cancelFlush?.();
211
+ this._cancelFlush = null;
212
+ this._pendingEnvelopes = [];
213
+ this._offlineQueue = [];
214
+ this._ws.close();
215
+ }
216
+ };
217
+ // Annotate the CommonJS export names for ESM import in node:
218
+ 0 && (module.exports = {
219
+ CrdtStateProxy,
220
+ WebSocketManager
221
+ });
8
222
  //# sourceMappingURL=index.js.map