@1kbgz/transports 0.6.0 → 0.8.0

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,708 @@
1
+ // src/ts/bridge.ts
2
+ function toValue(v) {
3
+ if (v === null || v === void 0) return "Null";
4
+ if (typeof v === "boolean") return { Bool: v };
5
+ if (typeof v === "number")
6
+ return Number.isInteger(v) ? { Int: v } : { Float: v };
7
+ if (typeof v === "string") return { Str: v };
8
+ if (Array.isArray(v)) return { List: v.map(toValue) };
9
+ if (typeof v === "object") {
10
+ const m = {};
11
+ for (const [k, x] of Object.entries(v)) m[k] = toValue(x);
12
+ return { Map: m };
13
+ }
14
+ throw new TypeError(`unsupported value for transports: ${typeof v}`);
15
+ }
16
+ function fromValue(value) {
17
+ if (value === "Null") return null;
18
+ const [tag, inner] = Object.entries(value)[0];
19
+ switch (tag) {
20
+ case "Bool":
21
+ case "Int":
22
+ case "Float":
23
+ case "Str":
24
+ case "Submodel":
25
+ return inner;
26
+ case "List":
27
+ return inner.map(fromValue);
28
+ case "Map": {
29
+ const o = {};
30
+ for (const [k, x] of Object.entries(inner))
31
+ o[k] = fromValue(x);
32
+ return o;
33
+ }
34
+ default:
35
+ throw new Error(`unrecognized tagged value: ${JSON.stringify(value)}`);
36
+ }
37
+ }
38
+
39
+ // src/ts/codecs.ts
40
+ var registry = /* @__PURE__ */ new Map();
41
+ function codecFor(contentType) {
42
+ return registry.get(contentType);
43
+ }
44
+
45
+ // dist/pkg/transports.js
46
+ var Store = class {
47
+ __destroy_into_raw() {
48
+ const ptr = this.__wbg_ptr;
49
+ this.__wbg_ptr = 0;
50
+ StoreFinalization.unregister(this);
51
+ return ptr;
52
+ }
53
+ free() {
54
+ const ptr = this.__destroy_into_raw();
55
+ wasm.__wbg_store_free(ptr, 0);
56
+ }
57
+ /**
58
+ * Apply a JSON patch to a mirrored model; returns whether the id was known.
59
+ * @param {bigint} id
60
+ * @param {string} patch_json
61
+ * @returns {boolean}
62
+ */
63
+ apply(id, patch_json) {
64
+ const ptr0 = passStringToWasm0(patch_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
65
+ const len0 = WASM_VECTOR_LEN;
66
+ const ret = wasm.store_apply(this.__wbg_ptr, id, ptr0, len0);
67
+ if (ret[2]) {
68
+ throw takeFromExternrefTable0(ret[1]);
69
+ }
70
+ return ret[0] !== 0;
71
+ }
72
+ /**
73
+ * Host a model from its JSON; returns the assigned id.
74
+ * @param {string} type_name
75
+ * @param {string} value_json
76
+ * @returns {bigint}
77
+ */
78
+ host(type_name, value_json) {
79
+ const ptr0 = passStringToWasm0(type_name, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
80
+ const len0 = WASM_VECTOR_LEN;
81
+ const ptr1 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
82
+ const len1 = WASM_VECTOR_LEN;
83
+ const ret = wasm.store_host(this.__wbg_ptr, ptr0, len0, ptr1, len1);
84
+ if (ret[2]) {
85
+ throw takeFromExternrefTable0(ret[1]);
86
+ }
87
+ return BigInt.asUintN(64, ret[0]);
88
+ }
89
+ /**
90
+ * Replace a hosted model from JSON; returns the JSON patch (or `undefined` if id unknown).
91
+ * @param {bigint} id
92
+ * @param {string} value_json
93
+ * @returns {string | undefined}
94
+ */
95
+ mutate(id, value_json) {
96
+ const ptr0 = passStringToWasm0(value_json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
97
+ const len0 = WASM_VECTOR_LEN;
98
+ const ret = wasm.store_mutate(this.__wbg_ptr, id, ptr0, len0);
99
+ if (ret[3]) {
100
+ throw takeFromExternrefTable0(ret[2]);
101
+ }
102
+ let v2;
103
+ if (ret[0] !== 0) {
104
+ v2 = getStringFromWasm0(ret[0], ret[1]).slice();
105
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
106
+ }
107
+ return v2;
108
+ }
109
+ constructor() {
110
+ const ret = wasm.store_new();
111
+ this.__wbg_ptr = ret;
112
+ StoreFinalization.register(this, this.__wbg_ptr, this);
113
+ return this;
114
+ }
115
+ /**
116
+ * `{"type_name":..,"rev":..,"value":..}` for a hosted model, or `undefined`.
117
+ * @param {bigint} id
118
+ * @returns {string | undefined}
119
+ */
120
+ snapshot(id) {
121
+ const ret = wasm.store_snapshot(this.__wbg_ptr, id);
122
+ let v1;
123
+ if (ret[0] !== 0) {
124
+ v1 = getStringFromWasm0(ret[0], ret[1]).slice();
125
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
126
+ }
127
+ return v1;
128
+ }
129
+ };
130
+ if (Symbol.dispose) Store.prototype[Symbol.dispose] = Store.prototype.free;
131
+ function cbor_to_json(data) {
132
+ let deferred3_0;
133
+ let deferred3_1;
134
+ try {
135
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
136
+ const len0 = WASM_VECTOR_LEN;
137
+ const ret = wasm.cbor_to_json(ptr0, len0);
138
+ var ptr2 = ret[0];
139
+ var len2 = ret[1];
140
+ if (ret[3]) {
141
+ ptr2 = 0;
142
+ len2 = 0;
143
+ throw takeFromExternrefTable0(ret[2]);
144
+ }
145
+ deferred3_0 = ptr2;
146
+ deferred3_1 = len2;
147
+ return getStringFromWasm0(ptr2, len2);
148
+ } finally {
149
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
150
+ }
151
+ }
152
+ function diff(old, _new) {
153
+ let deferred4_0;
154
+ let deferred4_1;
155
+ try {
156
+ const ptr0 = passStringToWasm0(old, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
157
+ const len0 = WASM_VECTOR_LEN;
158
+ const ptr1 = passStringToWasm0(_new, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
159
+ const len1 = WASM_VECTOR_LEN;
160
+ const ret = wasm.diff(ptr0, len0, ptr1, len1);
161
+ var ptr3 = ret[0];
162
+ var len3 = ret[1];
163
+ if (ret[3]) {
164
+ ptr3 = 0;
165
+ len3 = 0;
166
+ throw takeFromExternrefTable0(ret[2]);
167
+ }
168
+ deferred4_0 = ptr3;
169
+ deferred4_1 = len3;
170
+ return getStringFromWasm0(ptr3, len3);
171
+ } finally {
172
+ wasm.__wbindgen_free(deferred4_0, deferred4_1, 1);
173
+ }
174
+ }
175
+ function json_to_cbor(json) {
176
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
177
+ const len0 = WASM_VECTOR_LEN;
178
+ const ret = wasm.json_to_cbor(ptr0, len0);
179
+ if (ret[3]) {
180
+ throw takeFromExternrefTable0(ret[2]);
181
+ }
182
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
183
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
184
+ return v2;
185
+ }
186
+ function json_to_msgpack(json) {
187
+ const ptr0 = passStringToWasm0(json, wasm.__wbindgen_malloc, wasm.__wbindgen_realloc);
188
+ const len0 = WASM_VECTOR_LEN;
189
+ const ret = wasm.json_to_msgpack(ptr0, len0);
190
+ if (ret[3]) {
191
+ throw takeFromExternrefTable0(ret[2]);
192
+ }
193
+ var v2 = getArrayU8FromWasm0(ret[0], ret[1]).slice();
194
+ wasm.__wbindgen_free(ret[0], ret[1] * 1, 1);
195
+ return v2;
196
+ }
197
+ function msgpack_to_json(data) {
198
+ let deferred3_0;
199
+ let deferred3_1;
200
+ try {
201
+ const ptr0 = passArray8ToWasm0(data, wasm.__wbindgen_malloc);
202
+ const len0 = WASM_VECTOR_LEN;
203
+ const ret = wasm.msgpack_to_json(ptr0, len0);
204
+ var ptr2 = ret[0];
205
+ var len2 = ret[1];
206
+ if (ret[3]) {
207
+ ptr2 = 0;
208
+ len2 = 0;
209
+ throw takeFromExternrefTable0(ret[2]);
210
+ }
211
+ deferred3_0 = ptr2;
212
+ deferred3_1 = len2;
213
+ return getStringFromWasm0(ptr2, len2);
214
+ } finally {
215
+ wasm.__wbindgen_free(deferred3_0, deferred3_1, 1);
216
+ }
217
+ }
218
+ var StoreFinalization = typeof FinalizationRegistry === "undefined" ? { register: () => {
219
+ }, unregister: () => {
220
+ } } : new FinalizationRegistry((ptr) => wasm.__wbg_store_free(ptr, 1));
221
+ function getArrayU8FromWasm0(ptr, len) {
222
+ ptr = ptr >>> 0;
223
+ return getUint8ArrayMemory0().subarray(ptr / 1, ptr / 1 + len);
224
+ }
225
+ function getStringFromWasm0(ptr, len) {
226
+ return decodeText(ptr >>> 0, len);
227
+ }
228
+ var cachedUint8ArrayMemory0 = null;
229
+ function getUint8ArrayMemory0() {
230
+ if (cachedUint8ArrayMemory0 === null || cachedUint8ArrayMemory0.byteLength === 0) {
231
+ cachedUint8ArrayMemory0 = new Uint8Array(wasm.memory.buffer);
232
+ }
233
+ return cachedUint8ArrayMemory0;
234
+ }
235
+ function passArray8ToWasm0(arg, malloc) {
236
+ const ptr = malloc(arg.length * 1, 1) >>> 0;
237
+ getUint8ArrayMemory0().set(arg, ptr / 1);
238
+ WASM_VECTOR_LEN = arg.length;
239
+ return ptr;
240
+ }
241
+ function passStringToWasm0(arg, malloc, realloc) {
242
+ if (realloc === void 0) {
243
+ const buf = cachedTextEncoder.encode(arg);
244
+ const ptr2 = malloc(buf.length, 1) >>> 0;
245
+ getUint8ArrayMemory0().subarray(ptr2, ptr2 + buf.length).set(buf);
246
+ WASM_VECTOR_LEN = buf.length;
247
+ return ptr2;
248
+ }
249
+ let len = arg.length;
250
+ let ptr = malloc(len, 1) >>> 0;
251
+ const mem = getUint8ArrayMemory0();
252
+ let offset = 0;
253
+ for (; offset < len; offset++) {
254
+ const code = arg.charCodeAt(offset);
255
+ if (code > 127) break;
256
+ mem[ptr + offset] = code;
257
+ }
258
+ if (offset !== len) {
259
+ if (offset !== 0) {
260
+ arg = arg.slice(offset);
261
+ }
262
+ ptr = realloc(ptr, len, len = offset + arg.length * 3, 1) >>> 0;
263
+ const view = getUint8ArrayMemory0().subarray(ptr + offset, ptr + len);
264
+ const ret = cachedTextEncoder.encodeInto(arg, view);
265
+ offset += ret.written;
266
+ ptr = realloc(ptr, len, offset, 1) >>> 0;
267
+ }
268
+ WASM_VECTOR_LEN = offset;
269
+ return ptr;
270
+ }
271
+ function takeFromExternrefTable0(idx) {
272
+ const value = wasm.__wbindgen_externrefs.get(idx);
273
+ wasm.__externref_table_dealloc(idx);
274
+ return value;
275
+ }
276
+ var cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
277
+ cachedTextDecoder.decode();
278
+ var MAX_SAFARI_DECODE_BYTES = 2146435072;
279
+ var numBytesDecoded = 0;
280
+ function decodeText(ptr, len) {
281
+ numBytesDecoded += len;
282
+ if (numBytesDecoded >= MAX_SAFARI_DECODE_BYTES) {
283
+ cachedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true, fatal: true });
284
+ cachedTextDecoder.decode();
285
+ numBytesDecoded = len;
286
+ }
287
+ return cachedTextDecoder.decode(getUint8ArrayMemory0().subarray(ptr, ptr + len));
288
+ }
289
+ var cachedTextEncoder = new TextEncoder();
290
+ if (!("encodeInto" in cachedTextEncoder)) {
291
+ cachedTextEncoder.encodeInto = function(arg, view) {
292
+ const buf = cachedTextEncoder.encode(arg);
293
+ view.set(buf);
294
+ return {
295
+ read: arg.length,
296
+ written: buf.length
297
+ };
298
+ };
299
+ }
300
+ var WASM_VECTOR_LEN = 0;
301
+ var wasm;
302
+
303
+ // src/ts/index.ts
304
+ var diff2 = (oldModel, newModel) => diff(oldModel, newModel);
305
+ var jsonToMsgpack = (json) => json_to_msgpack(json);
306
+ var msgpackToJson = (bytes) => msgpack_to_json(bytes);
307
+ var jsonToCbor = (json) => json_to_cbor(json);
308
+ var cborToJson = (bytes) => cbor_to_json(bytes);
309
+
310
+ // src/ts/client.ts
311
+ function mapValue(value) {
312
+ if (value && typeof value === "object" && "Map" in value && value.Map && typeof value.Map === "object" && !Array.isArray(value.Map))
313
+ return value.Map;
314
+ throw new Error("patch path expected a map");
315
+ }
316
+ function listValue(value) {
317
+ if (value && typeof value === "object" && "List" in value && Array.isArray(value.List))
318
+ return value.List;
319
+ throw new Error("patch path expected a list");
320
+ }
321
+ function validIndex(index) {
322
+ return Number.isSafeInteger(index) && index >= 0;
323
+ }
324
+ function updateAt(value, path, update) {
325
+ if (!path.length) return update(value);
326
+ const [segment, ...rest] = path;
327
+ if ("Key" in segment) {
328
+ const map = mapValue(value);
329
+ if (rest.length && !Object.prototype.hasOwnProperty.call(map, segment.Key))
330
+ throw new Error(
331
+ `patch path key ${JSON.stringify(segment.Key)} not found`
332
+ );
333
+ return {
334
+ Map: {
335
+ ...map,
336
+ [segment.Key]: updateAt(map[segment.Key], rest, update)
337
+ }
338
+ };
339
+ }
340
+ const list = listValue(value);
341
+ if (!validIndex(segment.Index) || segment.Index >= list.length)
342
+ throw new Error(
343
+ `patch path index ${segment.Index} out of bounds (len ${list.length})`
344
+ );
345
+ const next = [...list];
346
+ next[segment.Index] = updateAt(next[segment.Index], rest, update);
347
+ return { List: next };
348
+ }
349
+ function applyOp(value, op) {
350
+ if ("Set" in op) return updateAt(value, op.Set.path, () => op.Set.value);
351
+ if ("Remove" in op) {
352
+ const { path } = op.Remove;
353
+ const segment = path[path.length - 1];
354
+ if (!segment || !("Key" in segment))
355
+ throw new Error("remove path must end in a map key");
356
+ return updateAt(value, path.slice(0, -1), (container) => {
357
+ const map = { ...mapValue(container) };
358
+ delete map[segment.Key];
359
+ return { Map: map };
360
+ });
361
+ }
362
+ if ("Insert" in op) {
363
+ const { path, index, value: inserted } = op.Insert;
364
+ return updateAt(value, path, (container) => {
365
+ const list = listValue(container);
366
+ if (!validIndex(index) || index > list.length)
367
+ throw new Error(
368
+ `insert index ${index} out of bounds (len ${list.length})`
369
+ );
370
+ const next = [...list];
371
+ next.splice(index, 0, inserted);
372
+ return { List: next };
373
+ });
374
+ }
375
+ if ("RemoveAt" in op) {
376
+ const { path, index } = op.RemoveAt;
377
+ return updateAt(value, path, (container) => {
378
+ const list = listValue(container);
379
+ if (!validIndex(index) || index >= list.length)
380
+ throw new Error(
381
+ `remove index ${index} out of bounds (len ${list.length})`
382
+ );
383
+ const next = [...list];
384
+ next.splice(index, 1);
385
+ return { List: next };
386
+ });
387
+ }
388
+ if ("Move" in op) {
389
+ const { path, from, to } = op.Move;
390
+ return updateAt(value, path, (container) => {
391
+ const list = listValue(container);
392
+ if (!validIndex(from) || from >= list.length)
393
+ throw new Error(
394
+ `move source index ${from} out of bounds (len ${list.length})`
395
+ );
396
+ if (!validIndex(to) || to >= list.length)
397
+ throw new Error(
398
+ `move destination index ${to} out of bounds (len ${list.length})`
399
+ );
400
+ if (from === to) return container;
401
+ const next = [...list];
402
+ const [moved] = next.splice(from, 1);
403
+ next.splice(to, 0, moved);
404
+ return { List: next };
405
+ });
406
+ }
407
+ if ("Reorder" in op) {
408
+ const { path, order } = op.Reorder;
409
+ return updateAt(value, path, (container) => {
410
+ const list = listValue(container);
411
+ if (!Array.isArray(order))
412
+ throw new Error("reorder order must be an array");
413
+ if (order.length !== list.length)
414
+ throw new Error(
415
+ `reorder length ${order.length} does not match list length ${list.length}`
416
+ );
417
+ const seen = /* @__PURE__ */ new Set();
418
+ for (const index of order) {
419
+ if (!validIndex(index) || index >= list.length)
420
+ throw new Error(
421
+ `reorder index ${index} out of bounds (len ${list.length})`
422
+ );
423
+ if (seen.has(index))
424
+ throw new Error(`reorder index ${index} is duplicated`);
425
+ seen.add(index);
426
+ }
427
+ if (order.every((old, current) => old === current))
428
+ return container;
429
+ return { List: order.map((index) => list[index]) };
430
+ });
431
+ }
432
+ throw new Error("unknown patch op");
433
+ }
434
+ function applyPatch(value, patch) {
435
+ let next = value;
436
+ for (const op of patch.ops) next = applyOp(next, op);
437
+ return next;
438
+ }
439
+ var Client = class {
440
+ constructor(codec = "json") {
441
+ this.codec = codec;
442
+ }
443
+ codec;
444
+ values = /* @__PURE__ */ new Map();
445
+ revs = /* @__PURE__ */ new Map();
446
+ changeListeners = [];
447
+ rejectListeners = [];
448
+ /** Register a listener fired when the server refuses a proposed edit, with the decoded `reject`
449
+ * frame (model id, the server's current rev, and the validation error). The mirror itself reverts
450
+ * via the authoritative snapshot the server sends alongside. Returns an unsubscribe function.
451
+ */
452
+ onReject(listener) {
453
+ this.rejectListeners.push(listener);
454
+ return () => {
455
+ const i = this.rejectListeners.indexOf(listener);
456
+ if (i >= 0) this.rejectListeners.splice(i, 1);
457
+ };
458
+ }
459
+ /** Register a listener fired after each accepted snapshot or patch — the same `ReceiveChange`
460
+ * `recv` returns — so `connect`/`run`/`connectSSE` consumers get path-level changes without
461
+ * managing the socket themselves. Not fired for ignored frames (stale revision, unknown message
462
+ * type). Returns an unsubscribe function. A listener exception propagates to the `recv` caller;
463
+ * the mirror has already updated by then.
464
+ */
465
+ onChange(listener) {
466
+ this.changeListeners.push(listener);
467
+ return () => {
468
+ const i = this.changeListeners.indexOf(listener);
469
+ if (i >= 0) this.changeListeners.splice(i, 1);
470
+ };
471
+ }
472
+ accepted(change) {
473
+ for (const listener of [...this.changeListeners]) listener(change);
474
+ return change;
475
+ }
476
+ /** Apply an inbound snapshot or patch frame to the mirror.
477
+ *
478
+ * Decodes by the client's codec: a registered custom codec, else built-in JSON (text) / msgpack
479
+ * (binary). Returns the accepted change so reactive adapters can update only its paths; returns
480
+ * `undefined` for a patch whose revision was already applied, and for an unrecognized message
481
+ * type — ignored, not an error, so a newer server can add message types without breaking older
482
+ * clients. The returned change and values from `value()` share immutable branches with the
483
+ * mirror; consumers must not mutate them. Invalid frames throw without changing the mirror or its
484
+ * accepted revision.
485
+ */
486
+ recv(data) {
487
+ const custom = codecFor(this.codec);
488
+ let msg;
489
+ if (custom) {
490
+ msg = custom.decode(data);
491
+ } else if (typeof data === "string") {
492
+ msg = JSON.parse(data);
493
+ } else {
494
+ msg = JSON.parse(
495
+ this.codec === "cbor" ? cborToJson(data) : msgpackToJson(data)
496
+ );
497
+ }
498
+ if (msg.t === "snapshot") {
499
+ this.values.set(msg.id, msg.value);
500
+ this.revs.set(msg.id, msg.rev);
501
+ return this.accepted({ t: "snapshot", id: msg.id, rev: msg.rev });
502
+ } else if (msg.t === "patch") {
503
+ const seen = this.revs.get(msg.id);
504
+ if (seen !== void 0 && msg.patch.rev <= seen) return void 0;
505
+ const current = this.values.get(msg.id);
506
+ if (current === void 0)
507
+ throw new Error(`patch received before snapshot for model ${msg.id}`);
508
+ this.values.set(msg.id, applyPatch(current, msg.patch));
509
+ this.revs.set(msg.id, msg.patch.rev);
510
+ return this.accepted(msg);
511
+ } else if (msg.t === "reject") {
512
+ for (const listener of [...this.rejectListeners]) listener(msg);
513
+ return void 0;
514
+ }
515
+ return void 0;
516
+ }
517
+ /** The current mirrored core `Value` of a model. */
518
+ value(id) {
519
+ return this.values.get(id);
520
+ }
521
+ ids() {
522
+ return [...this.values.keys()];
523
+ }
524
+ /** Propose an edit to a mirrored model; returns the patch frame to send (encoded in this codec).
525
+ *
526
+ * Server-authoritative: the local mirror updates when the server echoes the authoritative patch
527
+ * back via `recv`, not optimistically.
528
+ */
529
+ edit(id, value) {
530
+ const patch = JSON.parse(
531
+ diff2(JSON.stringify(this.values.get(id)), JSON.stringify(value))
532
+ );
533
+ const msg = { t: "patch", id, patch };
534
+ const custom = codecFor(this.codec);
535
+ if (custom) return custom.encode(msg);
536
+ const s = JSON.stringify(msg);
537
+ if (this.codec === "msgpack") return jsonToMsgpack(s);
538
+ if (this.codec === "cbor") return jsonToCbor(s);
539
+ return s;
540
+ }
541
+ /** Connect to a transports server and mirror it. Returns the `WebSocket`.
542
+ *
543
+ * On a reconnect (this client already mirrors models) it appends `?since=` with its last-seen rev per
544
+ * model, so the server replays only the delta instead of re-sending each whole model.
545
+ */
546
+ connect(url) {
547
+ const sep = url.includes("?") ? "&" : "?";
548
+ let params = `codec=${this.codec}`;
549
+ if (this.revs.size) {
550
+ const since = encodeURIComponent(
551
+ JSON.stringify(Object.fromEntries(this.revs))
552
+ );
553
+ params += `&since=${since}`;
554
+ }
555
+ const ws = new WebSocket(`${url}${sep}${params}`);
556
+ ws.binaryType = "arraybuffer";
557
+ ws.addEventListener("message", (e) => {
558
+ const data = e.data;
559
+ this.recv(
560
+ typeof data === "string" ? data : new Uint8Array(data)
561
+ );
562
+ });
563
+ return ws;
564
+ }
565
+ /** Connect and mirror, **reconnecting** whenever the socket drops — so the client survives a server
566
+ * restart or a refresh. `authority` decides reconciliation on each (re)connect:
567
+ *
568
+ * - `"server"` (default): the server is canonical; the client adopts its state (resuming via `?since=`
569
+ * when it can, else a fresh snapshot) — the "refetch on refresh" behavior.
570
+ * - `"client"`: the client is canonical; after the server's snapshot it pushes its last-known state
571
+ * back as an edit, rectifying a server that came back stale/empty (merges under a CRDT, else
572
+ * overwrites).
573
+ *
574
+ * `onMessage` fires after each applied frame (e.g. to re-render). Returns `{ stop() }`.
575
+ */
576
+ run(url, opts = {}) {
577
+ const { authority = "server", retry = 1e3, onMessage } = opts;
578
+ let stopped = false;
579
+ const loop = () => {
580
+ if (stopped) return;
581
+ const pre = authority === "client" ? new Map(this.values) : null;
582
+ const pushed = /* @__PURE__ */ new Set();
583
+ const ws = this.connect(url);
584
+ ws.addEventListener("message", () => {
585
+ onMessage?.();
586
+ if (pre) {
587
+ for (const id of this.values.keys()) {
588
+ if (!pushed.has(id) && pre.has(id)) {
589
+ ws.send(
590
+ this.edit(id, pre.get(id))
591
+ );
592
+ pushed.add(id);
593
+ }
594
+ }
595
+ }
596
+ });
597
+ ws.addEventListener("close", () => {
598
+ if (!stopped) setTimeout(loop, retry);
599
+ });
600
+ ws.addEventListener("error", () => {
601
+ try {
602
+ ws.close();
603
+ } catch {
604
+ }
605
+ });
606
+ };
607
+ loop();
608
+ return {
609
+ stop() {
610
+ stopped = true;
611
+ }
612
+ };
613
+ }
614
+ /** Mirror a server over Server-Sent Events (receive-only, JSON). Returns the `EventSource`. */
615
+ connectSSE(url) {
616
+ const es = new EventSource(url);
617
+ es.addEventListener(
618
+ "message",
619
+ (e) => this.recv(e.data)
620
+ );
621
+ return es;
622
+ }
623
+ };
624
+
625
+ // src/ts/widget.ts
626
+ var clients = /* @__PURE__ */ new WeakMap();
627
+ function clientFor(model) {
628
+ let client = clients.get(model);
629
+ if (!client) {
630
+ const created = new Client();
631
+ clients.set(model, created);
632
+ model.on("msg:custom", (content) => {
633
+ const wire = content?.wire;
634
+ if (wire !== void 0) created.recv(wire);
635
+ });
636
+ model.send({ ready: true });
637
+ client = created;
638
+ }
639
+ return client;
640
+ }
641
+ function sendEdit(model, id, path, value) {
642
+ const segments = path.map(
643
+ (p) => typeof p === "number" ? { Index: p } : { Key: p }
644
+ );
645
+ const patch = {
646
+ rev: 0,
647
+ // a proposal's rev is ignored; the server owns rev
648
+ ops: [{ Set: { path: segments, value: toValue(value) } }]
649
+ };
650
+ model.send({ wire: JSON.stringify({ t: "patch", id, patch }) });
651
+ }
652
+ var widget_default = {
653
+ initialize({ model }) {
654
+ clientFor(model);
655
+ },
656
+ render({ model, el }) {
657
+ const client = clientFor(model);
658
+ const container = document.createElement("div");
659
+ const error = document.createElement("div");
660
+ error.setAttribute(
661
+ "style",
662
+ "color: #b91c1c; font-size: 0.85em; min-height: 1em;"
663
+ );
664
+ el.appendChild(container);
665
+ el.appendChild(error);
666
+ const views = /* @__PURE__ */ new Map();
667
+ const update = (id) => {
668
+ let pre = views.get(id);
669
+ if (!pre) {
670
+ pre = document.createElement("pre");
671
+ pre.setAttribute("style", "margin: 0.25em 0;");
672
+ views.set(id, pre);
673
+ container.appendChild(pre);
674
+ }
675
+ pre.textContent = JSON.stringify(
676
+ fromValue(client.value(id)),
677
+ null,
678
+ 2
679
+ );
680
+ };
681
+ for (const id of client.ids()) update(id);
682
+ const offChange = client.onChange((change) => {
683
+ error.textContent = "";
684
+ update(change.id);
685
+ el.dispatchEvent(
686
+ new CustomEvent("transports-change", { detail: change, bubbles: true })
687
+ );
688
+ });
689
+ const offReject = client.onReject((reject) => {
690
+ error.textContent = `rejected: ${reject.error}`;
691
+ el.dispatchEvent(
692
+ new CustomEvent("transports-reject", { detail: reject, bubbles: true })
693
+ );
694
+ });
695
+ el.transports = {
696
+ client,
697
+ edit: (id, path, value) => sendEdit(model, id, path, value)
698
+ };
699
+ return () => {
700
+ offChange();
701
+ offReject();
702
+ };
703
+ }
704
+ };
705
+ export {
706
+ widget_default as default
707
+ };
708
+ //# sourceMappingURL=widget.js.map