@agg-build/sdk 4.25.0 → 4.27.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.
Files changed (42) hide show
  1. package/dist/agg-websocket-BstVWtLA.d.mts +6004 -0
  2. package/dist/agg-websocket-BstVWtLA.d.mts.map +1 -0
  3. package/dist/agg-websocket-BstVWtLA.d.ts +6004 -0
  4. package/dist/agg-websocket-BstVWtLA.d.ts.map +1 -0
  5. package/dist/agg-websocket-CK2iXfti.mjs +1427 -0
  6. package/dist/agg-websocket-CK2iXfti.mjs.map +1 -0
  7. package/dist/agg-websocket-DJbIfxKb.js +1478 -0
  8. package/dist/browser.d.mts +67 -66
  9. package/dist/browser.d.mts.map +1 -0
  10. package/dist/browser.d.ts +67 -66
  11. package/dist/browser.d.ts.map +1 -0
  12. package/dist/browser.js +720 -2047
  13. package/dist/browser.mjs +423 -799
  14. package/dist/browser.mjs.map +1 -0
  15. package/dist/candle-builder-BNewIe9K.mjs +148 -0
  16. package/dist/candle-builder-BNewIe9K.mjs.map +1 -0
  17. package/dist/candle-builder-BULYdxB4.js +151 -0
  18. package/dist/index.d.mts +2 -1342
  19. package/dist/index.d.ts +2 -1342
  20. package/dist/index.js +2794 -4656
  21. package/dist/index.mjs +2788 -2486
  22. package/dist/index.mjs.map +1 -0
  23. package/dist/market-data.d.mts +6 -6
  24. package/dist/market-data.d.mts.map +1 -0
  25. package/dist/market-data.d.ts +6 -6
  26. package/dist/market-data.d.ts.map +1 -0
  27. package/dist/market-data.js +314 -1774
  28. package/dist/market-data.mjs +314 -350
  29. package/dist/market-data.mjs.map +1 -0
  30. package/dist/server.d.mts +235 -234
  31. package/dist/server.d.mts.map +1 -0
  32. package/dist/server.d.ts +235 -234
  33. package/dist/server.d.ts.map +1 -0
  34. package/dist/server.js +168 -296
  35. package/dist/server.mjs +163 -234
  36. package/dist/server.mjs.map +1 -0
  37. package/package.json +4 -4
  38. package/dist/agg-websocket-Bxt9PzTz.d.mts +0 -4479
  39. package/dist/agg-websocket-Bxt9PzTz.d.ts +0 -4479
  40. package/dist/chunk-QXBVA5TW.mjs +0 -2073
  41. package/dist/chunk-VD5UTAVD.mjs +0 -158
  42. package/dist/chunk-WNQUEZJF.mjs +0 -58
package/dist/browser.js CHANGED
@@ -1,2049 +1,722 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __defProps = Object.defineProperties;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
6
- var __getOwnPropNames = Object.getOwnPropertyNames;
7
- var __getOwnPropSymbols = Object.getOwnPropertySymbols;
8
- var __hasOwnProp = Object.prototype.hasOwnProperty;
9
- var __propIsEnum = Object.prototype.propertyIsEnumerable;
10
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
- var __spreadValues = (a, b) => {
12
- for (var prop in b || (b = {}))
13
- if (__hasOwnProp.call(b, prop))
14
- __defNormalProp(a, prop, b[prop]);
15
- if (__getOwnPropSymbols)
16
- for (var prop of __getOwnPropSymbols(b)) {
17
- if (__propIsEnum.call(b, prop))
18
- __defNormalProp(a, prop, b[prop]);
19
- }
20
- return a;
21
- };
22
- var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
23
- var __objRest = (source, exclude) => {
24
- var target = {};
25
- for (var prop in source)
26
- if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
27
- target[prop] = source[prop];
28
- if (source != null && __getOwnPropSymbols)
29
- for (var prop of __getOwnPropSymbols(source)) {
30
- if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
31
- target[prop] = source[prop];
32
- }
33
- return target;
34
- };
35
- var __export = (target, all) => {
36
- for (var name in all)
37
- __defProp(target, name, { get: all[name], enumerable: true });
38
- };
39
- var __copyProps = (to, from, except, desc) => {
40
- if (from && typeof from === "object" || typeof from === "function") {
41
- for (let key of __getOwnPropNames(from))
42
- if (!__hasOwnProp.call(to, key) && key !== except)
43
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
44
- }
45
- return to;
46
- };
47
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
48
- var __async = (__this, __arguments, generator) => {
49
- return new Promise((resolve, reject) => {
50
- var fulfilled = (value) => {
51
- try {
52
- step(generator.next(value));
53
- } catch (e) {
54
- reject(e);
55
- }
56
- };
57
- var rejected = (value) => {
58
- try {
59
- step(generator.throw(value));
60
- } catch (e) {
61
- reject(e);
62
- }
63
- };
64
- var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
65
- step((generator = generator.apply(__this, __arguments)).next());
66
- });
67
- };
68
-
69
- // src/browser.ts
70
- var browser_exports = {};
71
- __export(browser_exports, {
72
- WorkerAggWebSocket: () => WorkerAggWebSocket,
73
- createWorkerWebSocket: () => createWorkerWebSocket
74
- });
75
- module.exports = __toCommonJS(browser_exports);
76
-
77
- // ../../node_modules/.pnpm/comlink@4.4.2/node_modules/comlink/dist/esm/comlink.mjs
78
- var proxyMarker = /* @__PURE__ */ Symbol("Comlink.proxy");
79
- var createEndpoint = /* @__PURE__ */ Symbol("Comlink.endpoint");
80
- var releaseProxy = /* @__PURE__ */ Symbol("Comlink.releaseProxy");
81
- var finalizer = /* @__PURE__ */ Symbol("Comlink.finalizer");
82
- var throwMarker = /* @__PURE__ */ Symbol("Comlink.thrown");
83
- var isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
84
- var proxyTransferHandler = {
85
- canHandle: (val) => isObject(val) && val[proxyMarker],
86
- serialize(obj) {
87
- const { port1, port2 } = new MessageChannel();
88
- expose(obj, port1);
89
- return [port2, [port2]];
90
- },
91
- deserialize(port) {
92
- port.start();
93
- return wrap(port);
94
- }
95
- };
96
- var throwTransferHandler = {
97
- canHandle: (value) => isObject(value) && throwMarker in value,
98
- serialize({ value }) {
99
- let serialized;
100
- if (value instanceof Error) {
101
- serialized = {
102
- isError: true,
103
- value: {
104
- message: value.message,
105
- name: value.name,
106
- stack: value.stack
107
- }
108
- };
109
- } else {
110
- serialized = { isError: false, value };
111
- }
112
- return [serialized, []];
113
- },
114
- deserialize(serialized) {
115
- if (serialized.isError) {
116
- throw Object.assign(new Error(serialized.value.message), serialized.value);
117
- }
118
- throw serialized.value;
119
- }
120
- };
121
- var transferHandlers = /* @__PURE__ */ new Map([
122
- ["proxy", proxyTransferHandler],
123
- ["throw", throwTransferHandler]
124
- ]);
125
- function isAllowedOrigin(allowedOrigins, origin) {
126
- for (const allowedOrigin of allowedOrigins) {
127
- if (origin === allowedOrigin || allowedOrigin === "*") {
128
- return true;
129
- }
130
- if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) {
131
- return true;
132
- }
133
- }
134
- return false;
135
- }
136
- function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
137
- ep.addEventListener("message", function callback(ev) {
138
- if (!ev || !ev.data) {
139
- return;
140
- }
141
- if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
142
- console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
143
- return;
144
- }
145
- const { id, type, path } = Object.assign({ path: [] }, ev.data);
146
- const argumentList = (ev.data.argumentList || []).map(fromWireValue);
147
- let returnValue;
148
- try {
149
- const parent = path.slice(0, -1).reduce((obj2, prop) => obj2[prop], obj);
150
- const rawValue = path.reduce((obj2, prop) => obj2[prop], obj);
151
- switch (type) {
152
- case "GET":
153
- {
154
- returnValue = rawValue;
155
- }
156
- break;
157
- case "SET":
158
- {
159
- parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
160
- returnValue = true;
161
- }
162
- break;
163
- case "APPLY":
164
- {
165
- returnValue = rawValue.apply(parent, argumentList);
166
- }
167
- break;
168
- case "CONSTRUCT":
169
- {
170
- const value = new rawValue(...argumentList);
171
- returnValue = proxy(value);
172
- }
173
- break;
174
- case "ENDPOINT":
175
- {
176
- const { port1, port2 } = new MessageChannel();
177
- expose(obj, port2);
178
- returnValue = transfer(port1, [port1]);
179
- }
180
- break;
181
- case "RELEASE":
182
- {
183
- returnValue = void 0;
184
- }
185
- break;
186
- default:
187
- return;
188
- }
189
- } catch (value) {
190
- returnValue = { value, [throwMarker]: 0 };
191
- }
192
- Promise.resolve(returnValue).catch((value) => {
193
- return { value, [throwMarker]: 0 };
194
- }).then((returnValue2) => {
195
- const [wireValue, transferables] = toWireValue(returnValue2);
196
- ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
197
- if (type === "RELEASE") {
198
- ep.removeEventListener("message", callback);
199
- closeEndPoint(ep);
200
- if (finalizer in obj && typeof obj[finalizer] === "function") {
201
- obj[finalizer]();
202
- }
203
- }
204
- }).catch((error) => {
205
- const [wireValue, transferables] = toWireValue({
206
- value: new TypeError("Unserializable return value"),
207
- [throwMarker]: 0
208
- });
209
- ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
210
- });
211
- });
212
- if (ep.start) {
213
- ep.start();
214
- }
215
- }
216
- function isMessagePort(endpoint) {
217
- return endpoint.constructor.name === "MessagePort";
218
- }
219
- function closeEndPoint(endpoint) {
220
- if (isMessagePort(endpoint))
221
- endpoint.close();
222
- }
223
- function wrap(ep, target) {
224
- const pendingListeners = /* @__PURE__ */ new Map();
225
- ep.addEventListener("message", function handleMessage(ev) {
226
- const { data } = ev;
227
- if (!data || !data.id) {
228
- return;
229
- }
230
- const resolver = pendingListeners.get(data.id);
231
- if (!resolver) {
232
- return;
233
- }
234
- try {
235
- resolver(data);
236
- } finally {
237
- pendingListeners.delete(data.id);
238
- }
239
- });
240
- return createProxy(ep, pendingListeners, [], target);
241
- }
242
- function throwIfProxyReleased(isReleased) {
243
- if (isReleased) {
244
- throw new Error("Proxy has been released and is not useable");
245
- }
246
- }
247
- function releaseEndpoint(ep) {
248
- return requestResponseMessage(ep, /* @__PURE__ */ new Map(), {
249
- type: "RELEASE"
250
- }).then(() => {
251
- closeEndPoint(ep);
252
- });
253
- }
254
- var proxyCounter = /* @__PURE__ */ new WeakMap();
255
- var proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((ep) => {
256
- const newCount = (proxyCounter.get(ep) || 0) - 1;
257
- proxyCounter.set(ep, newCount);
258
- if (newCount === 0) {
259
- releaseEndpoint(ep);
260
- }
261
- });
262
- function registerProxy(proxy2, ep) {
263
- const newCount = (proxyCounter.get(ep) || 0) + 1;
264
- proxyCounter.set(ep, newCount);
265
- if (proxyFinalizers) {
266
- proxyFinalizers.register(proxy2, ep, proxy2);
267
- }
268
- }
269
- function unregisterProxy(proxy2) {
270
- if (proxyFinalizers) {
271
- proxyFinalizers.unregister(proxy2);
272
- }
273
- }
274
- function createProxy(ep, pendingListeners, path = [], target = function() {
275
- }) {
276
- let isProxyReleased = false;
277
- const proxy2 = new Proxy(target, {
278
- get(_target, prop) {
279
- throwIfProxyReleased(isProxyReleased);
280
- if (prop === releaseProxy) {
281
- return () => {
282
- unregisterProxy(proxy2);
283
- releaseEndpoint(ep);
284
- pendingListeners.clear();
285
- isProxyReleased = true;
286
- };
287
- }
288
- if (prop === "then") {
289
- if (path.length === 0) {
290
- return { then: () => proxy2 };
291
- }
292
- const r = requestResponseMessage(ep, pendingListeners, {
293
- type: "GET",
294
- path: path.map((p) => p.toString())
295
- }).then(fromWireValue);
296
- return r.then.bind(r);
297
- }
298
- return createProxy(ep, pendingListeners, [...path, prop]);
299
- },
300
- set(_target, prop, rawValue) {
301
- throwIfProxyReleased(isProxyReleased);
302
- const [value, transferables] = toWireValue(rawValue);
303
- return requestResponseMessage(ep, pendingListeners, {
304
- type: "SET",
305
- path: [...path, prop].map((p) => p.toString()),
306
- value
307
- }, transferables).then(fromWireValue);
308
- },
309
- apply(_target, _thisArg, rawArgumentList) {
310
- throwIfProxyReleased(isProxyReleased);
311
- const last = path[path.length - 1];
312
- if (last === createEndpoint) {
313
- return requestResponseMessage(ep, pendingListeners, {
314
- type: "ENDPOINT"
315
- }).then(fromWireValue);
316
- }
317
- if (last === "bind") {
318
- return createProxy(ep, pendingListeners, path.slice(0, -1));
319
- }
320
- const [argumentList, transferables] = processArguments(rawArgumentList);
321
- return requestResponseMessage(ep, pendingListeners, {
322
- type: "APPLY",
323
- path: path.map((p) => p.toString()),
324
- argumentList
325
- }, transferables).then(fromWireValue);
326
- },
327
- construct(_target, rawArgumentList) {
328
- throwIfProxyReleased(isProxyReleased);
329
- const [argumentList, transferables] = processArguments(rawArgumentList);
330
- return requestResponseMessage(ep, pendingListeners, {
331
- type: "CONSTRUCT",
332
- path: path.map((p) => p.toString()),
333
- argumentList
334
- }, transferables).then(fromWireValue);
335
- }
336
- });
337
- registerProxy(proxy2, ep);
338
- return proxy2;
339
- }
340
- function myFlat(arr) {
341
- return Array.prototype.concat.apply([], arr);
342
- }
343
- function processArguments(argumentList) {
344
- const processed = argumentList.map(toWireValue);
345
- return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
346
- }
347
- var transferCache = /* @__PURE__ */ new WeakMap();
348
- function transfer(obj, transfers) {
349
- transferCache.set(obj, transfers);
350
- return obj;
351
- }
352
- function proxy(obj) {
353
- return Object.assign(obj, { [proxyMarker]: true });
354
- }
355
- function toWireValue(value) {
356
- for (const [name, handler] of transferHandlers) {
357
- if (handler.canHandle(value)) {
358
- const [serializedValue, transferables] = handler.serialize(value);
359
- return [
360
- {
361
- type: "HANDLER",
362
- name,
363
- value: serializedValue
364
- },
365
- transferables
366
- ];
367
- }
368
- }
369
- return [
370
- {
371
- type: "RAW",
372
- value
373
- },
374
- transferCache.get(value) || []
375
- ];
376
- }
377
- function fromWireValue(value) {
378
- switch (value.type) {
379
- case "HANDLER":
380
- return transferHandlers.get(value.name).deserialize(value.value);
381
- case "RAW":
382
- return value.value;
383
- }
384
- }
385
- function requestResponseMessage(ep, pendingListeners, msg, transfers) {
386
- return new Promise((resolve) => {
387
- const id = generateUUID();
388
- pendingListeners.set(id, resolve);
389
- if (ep.start) {
390
- ep.start();
391
- }
392
- ep.postMessage(Object.assign({ id }, msg), transfers);
393
- });
394
- }
395
- function generateUUID() {
396
- return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
397
- }
398
-
399
- // src/market-data/history-decoder.ts
400
- function decodeChartHistory(payload) {
401
- if (payload.length > 1048576) throw new Error("Chart history exceeds decode budget");
402
- const body = JSON.parse(payload);
403
- if (!body || !Array.isArray(body.data) || body.data.length > 5e3 || typeof body.venueMarketOutcomeId !== "string" || typeof body.venue !== "string" || !["1m", "5m", "1h", "1d"].includes(body.resolution) || !body.meta)
404
- throw new Error("Invalid chart history response");
405
- const price = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
406
- for (const bar of body.data) {
407
- if (!Number.isSafeInteger(bar.t) || bar.t < 0 || ![bar.o, bar.h, bar.l, bar.c].every(price) || bar.l > Math.min(bar.o, bar.c) || bar.h < Math.max(bar.o, bar.c) || bar.v !== null && (!Number.isFinite(bar.v) || bar.v < 0) || bar.mean !== void 0 && !price(bar.mean))
408
- throw new Error("Invalid chart history candle");
409
- }
410
- const data = [...body.data].sort((a, b) => a.t - b.t);
411
- if (data.some((bar, index) => index > 0 && data[index - 1].t === bar.t))
412
- throw new Error("Duplicate chart history timestamp");
413
- return __spreadProps(__spreadValues({}, body), { data });
414
- }
415
-
416
- // src/market-data/validate.ts
417
- var object = (value) => !!value && typeof value === "object" && !Array.isArray(value);
418
- var finite = (value) => typeof value === "number" && Number.isFinite(value);
419
- var nullable = (value) => value === null || finite(value);
420
- var levels = (value, attributed) => Array.isArray(value) && value.length <= 1e4 && value.every(
421
- (level) => Array.isArray(level) && finite(level[0]) && level[0] >= 0 && finite(level[1]) && level[1] >= 0 && (!attributed || object(level[2]) && Object.values(level[2]).every((size) => finite(size) && size >= 0))
422
- );
423
- function validMarketFrame(frame) {
424
- if (typeof frame.outcomeId !== "string" || !frame.outcomeId || !finite(frame.timestamp) || frame.timestamp < 0)
425
- return false;
426
- if (frame.type === "trade")
427
- return finite(frame.price) && frame.price >= 0 && finite(frame.size) && frame.size >= 0 && typeof frame.venue === "string" && (frame.side === "buy" || frame.side === "sell");
428
- if (!Number.isSafeInteger(frame.seq) || frame.seq < 0 || !Number.isInteger(frame.checksum) || frame.checksum < 0 || frame.checksum > 4294967295 || !nullable(frame.midpoint) || !nullable(frame.spread) || !object(frame.venues))
429
- return false;
430
- for (const info of Object.values(frame.venues))
431
- if (!object(info) || !nullable(info.bestBid) || !nullable(info.bestAsk)) return false;
432
- const snapshot = frame.type === "orderbook_snapshot";
433
- if (!levels(frame[snapshot ? "bids" : "bidChanges"], true) || !levels(frame[snapshot ? "asks" : "askChanges"], true))
434
- return false;
435
- const books = frame[snapshot ? "venueOrderbooks" : "venueDeltaBooks"];
436
- return object(books) && Object.values(books).every(
437
- (book) => object(book) && levels(book[snapshot ? "bids" : "bidChanges"], false) && levels(book[snapshot ? "asks" : "askChanges"], false)
438
- );
439
- }
440
-
441
- // src/market-history.ts
442
- function readBoundedBody(response, signal) {
443
- return __async(this, null, function* () {
444
- var _a, _b;
445
- if (!response.body) throw new Error("Missing history body");
446
- const reader = response.body.getReader();
447
- const chunks = [];
448
- let size = 0;
449
- const abort = () => {
450
- void reader.cancel(signal.reason).catch(() => void 0);
451
- };
452
- signal.addEventListener("abort", abort, { once: true });
453
- try {
454
- while (true) {
455
- if (signal.aborted) throw (_a = signal.reason) != null ? _a : new Error("History request aborted");
456
- const { done, value } = yield reader.read();
457
- if (signal.aborted) throw (_b = signal.reason) != null ? _b : new Error("History request aborted");
458
- if (done) break;
459
- size += value.byteLength;
460
- if (size > 262144) {
461
- yield reader.cancel();
462
- throw new Error("Oversized history object");
463
- }
464
- chunks.push(value);
465
- }
466
- const bytes = new Uint8Array(size);
467
- let offset = 0;
468
- for (const chunk of chunks) {
469
- bytes.set(chunk, offset);
470
- offset += chunk.byteLength;
471
- }
472
- return bytes;
473
- } finally {
474
- signal.removeEventListener("abort", abort);
475
- reader.releaseLock();
476
- }
477
- });
478
- }
479
- function loadImmutableHistory(_0) {
480
- return __async(this, arguments, function* ({
481
- manifest,
482
- fetch: fetcher = globalThis.fetch,
483
- signal,
484
- digest
485
- }) {
486
- if (manifest.version !== 1 || !["venue-ohlcv-v1", "polymarket-price-samples-v1", "kalshi-ohlcv-quote-fallback-v2"].includes(
487
- manifest.semantics
488
- ) || manifest.chunks.length > 8 || manifest.chunks.reduce((n, c) => n + c.points, 0) > 4096 || !manifest.meta.complete) {
489
- throw new Error("History manifest is incomplete or unsupported");
490
- }
491
- const hash = digest != null ? digest : ((bytes) => __async(null, null, function* () {
492
- var _a;
493
- if (!((_a = globalThis.crypto) == null ? void 0 : _a.subtle))
494
- throw new Error(
495
- "History integrity requires WebCrypto or an injected SHA-256 implementation"
496
- );
497
- const value = yield globalThis.crypto.subtle.digest("SHA-256", bytes);
498
- return Array.from(new Uint8Array(value), (b) => b.toString(16).padStart(2, "0")).join("");
499
- }));
500
- const results = new Array(manifest.chunks.length);
501
- let next = 0;
502
- const controller = new AbortController();
503
- const deadline = setTimeout(
504
- () => controller.abort(new Error("History download budget exhausted")),
505
- 2e3
506
- );
507
- const abort = () => controller.abort(signal == null ? void 0 : signal.reason);
508
- signal == null ? void 0 : signal.addEventListener("abort", abort, { once: true });
509
- if (signal == null ? void 0 : signal.aborted) abort();
510
- try {
511
- yield Promise.all(
512
- Array.from({ length: Math.min(2, manifest.chunks.length) }, () => __async(null, null, function* () {
513
- var _a;
514
- while (next < manifest.chunks.length) {
515
- if (controller.signal.aborted)
516
- throw (_a = controller.signal.reason) != null ? _a : new Error("History request aborted");
517
- const index = next++;
518
- const chunk = manifest.chunks[index];
519
- if (chunk.points < 0 || chunk.points > 512 || chunk.from >= chunk.to || new URL(chunk.url).protocol !== "https:")
520
- throw new Error("Invalid history reference");
521
- const response = yield fetcher(chunk.url, {
522
- signal: controller.signal,
523
- credentials: "omit"
524
- });
525
- if (!response.ok) throw new Error(`History download failed (${response.status})`);
526
- if (Number(response.headers.get("content-length")) > 262144)
527
- throw new Error("Oversized history object");
528
- const bytes = yield readBoundedBody(response, controller.signal);
529
- if (bytes.byteLength > 262144 || (yield hash(bytes)) !== chunk.sha256)
530
- throw new Error("History integrity mismatch");
531
- const object2 = JSON.parse(new TextDecoder().decode(bytes));
532
- if (object2.version !== 1 || object2.venueMarketOutcomeId !== manifest.venueMarketOutcomeId || object2.venue !== manifest.venue || object2.resolution !== manifest.resolution || object2.semantics !== manifest.semantics || object2.from !== chunk.from || object2.to !== chunk.to || !Array.isArray(object2.data) || object2.data.length !== chunk.points) {
533
- throw new Error("History identity mismatch");
534
- }
535
- let previous = -Infinity;
536
- for (const bar of object2.data) {
537
- if (!Number.isSafeInteger(bar.t) || bar.t <= previous || bar.t < chunk.from || bar.t >= chunk.to || ![bar.o, bar.h, bar.l, bar.c].every((v) => Number.isFinite(v) && v >= 0 && v <= 1) || bar.l > Math.min(bar.o, bar.c) || bar.h < Math.max(bar.o, bar.c) || bar.v !== null && (!Number.isFinite(bar.v) || bar.v < 0) || bar.mean !== void 0 && (!Number.isFinite(bar.mean) || bar.mean < 0 || bar.mean > 1))
538
- throw new Error("Invalid history candle");
539
- previous = bar.t;
540
- }
541
- results[index] = object2.data;
542
- }
543
- }))
544
- );
545
- const bars = results.flat().filter((b) => b.t >= manifest.from && b.t < manifest.to).sort((a, b) => a.t - b.t);
546
- if (bars.some((b, i) => i > 0 && bars[i - 1].t === b.t))
547
- throw new Error("Overlapping history chunks");
548
- return bars;
549
- } catch (error) {
550
- controller.abort(error);
551
- throw error;
552
- } finally {
553
- clearTimeout(deadline);
554
- signal == null ? void 0 : signal.removeEventListener("abort", abort);
555
- }
556
- });
557
- }
558
-
559
- // ../common/src/orderbook-checksum.ts
560
- function orderbookCrc32(value) {
561
- let crc = 4294967295;
562
- for (let i = 0; i < value.length; i++) {
563
- crc ^= value.charCodeAt(i);
564
- for (let bit = 0; bit < 8; bit++) crc = crc >>> 1 ^ (crc & 1 ? 3988292384 : 0);
565
- }
566
- return (crc ^ 4294967295) >>> 0;
567
- }
568
- function projectedOrderbookChecksum(book) {
569
- let result = 0;
570
- for (const level of book.bids) result ^= orderbookCrc32(`B${level.price}:${level.size}`);
571
- for (const level of book.asks) result ^= orderbookCrc32(`A${level.price}:${level.size}`);
572
- return result >>> 0;
573
- }
574
-
575
- // src/orderbook-utils.ts
576
- var PRICE_KEY_SCALE = 1e9;
577
- function computeChecksum(book) {
578
- return projectedOrderbookChecksum(book);
579
- }
580
- function attributedToLevel(wire) {
581
- return { price: wire[0], size: wire[1], venues: __spreadValues({}, wire[2]) };
582
- }
583
- function venueLevelToLevel(wire) {
584
- return { price: wire[0], size: wire[1] };
585
- }
586
- function convertVenueBooks(raw) {
587
- const result = {};
588
- for (const [venue, book] of Object.entries(raw)) {
589
- result[venue] = {
590
- bids: book.bids.map(venueLevelToLevel),
591
- asks: book.asks.map(venueLevelToLevel)
592
- };
593
- }
594
- return result;
595
- }
596
- function snapshotToOrderbook(snapshot) {
597
- return {
598
- marketId: snapshot.outcomeId,
599
- outcomeId: snapshot.outcomeId,
600
- bids: snapshot.bids.map(attributedToLevel),
601
- asks: snapshot.asks.map(attributedToLevel),
602
- venueOrderbooks: convertVenueBooks(snapshot.venueOrderbooks),
603
- venues: __spreadValues({}, snapshot.venues),
604
- midpoint: snapshot.midpoint,
605
- spread: snapshot.spread,
606
- seq: snapshot.seq,
607
- checksum: snapshot.checksum,
608
- timestamp: snapshot.timestamp
609
- };
610
- }
611
- function toPriceKey(price) {
612
- return String(Math.round(price * PRICE_KEY_SCALE));
613
- }
614
- function mergeVenueLevelChanges(primary, fallback) {
615
- if (!(primary == null ? void 0 : primary.length)) return fallback ? [...fallback] : [];
616
- if (!(fallback == null ? void 0 : fallback.length)) return [...primary];
617
- const changesByPrice = /* @__PURE__ */ new Map();
618
- for (const change of fallback) {
619
- changesByPrice.set(toPriceKey(change[0]), change);
620
- }
621
- for (const change of primary) {
622
- changesByPrice.set(toPriceKey(change[0]), change);
623
- }
624
- return [...changesByPrice.values()];
625
- }
626
- function deriveVenueChangesFromAttributedChanges(previousLevels, changes) {
627
- var _a, _b;
628
- const previousLevelsByPrice = new Map(
629
- previousLevels.map((level) => [toPriceKey(level.price), level])
630
- );
631
- const venueChanges = {};
632
- for (const [price, size, nextVenuesRaw] of changes) {
633
- const key = toPriceKey(price);
634
- const previousLevel = previousLevelsByPrice.get(key);
635
- const previousVenues = (_a = previousLevel == null ? void 0 : previousLevel.venues) != null ? _a : {};
636
- const nextVenues = nextVenuesRaw != null ? nextVenuesRaw : {};
637
- const affectedVenues = /* @__PURE__ */ new Set([...Object.keys(previousVenues), ...Object.keys(nextVenues)]);
638
- for (const venue of affectedVenues) {
639
- const nextSize = Number((_b = nextVenues[venue]) != null ? _b : 0);
640
- if (!Number.isFinite(nextSize)) continue;
641
- if (!venueChanges[venue]) {
642
- venueChanges[venue] = [];
643
- }
644
- venueChanges[venue].push([price, nextSize]);
645
- }
646
- if (size === 0) {
647
- previousLevelsByPrice.delete(key);
648
- continue;
649
- }
650
- previousLevelsByPrice.set(key, {
651
- price,
652
- size,
653
- venues: __spreadValues({}, nextVenues)
654
- });
655
- }
656
- return venueChanges;
657
- }
658
- var IndexedOrderbook = class {
659
- constructor(state) {
660
- this.venueBooks = /* @__PURE__ */ new Map();
661
- this.bids = new Map(state.bids.map((level) => [toPriceKey(level.price), level]));
662
- this.asks = new Map(state.asks.map((level) => [toPriceKey(level.price), level]));
663
- for (const [venue, book] of Object.entries(state.venueOrderbooks)) {
664
- this.venueBooks.set(venue, {
665
- bids: new Map(book.bids.map((level) => [toPriceKey(level.price), level])),
666
- asks: new Map(book.asks.map((level) => [toPriceKey(level.price), level]))
667
- });
668
- }
669
- const _a = state, { bids: _bids, asks: _asks, venueOrderbooks: _venueBooks } = _a, metadata = __objRest(_a, ["bids", "asks", "venueOrderbooks"]);
670
- this.metadata = metadata;
671
- this.cached = state;
672
- this.checksumValue = computeChecksum(state);
673
- }
674
- get seq() {
675
- return this.metadata.seq;
676
- }
677
- get checksum() {
678
- return this.checksumValue;
679
- }
680
- /** Verify before committing, including duplicate-price changes within a frame. */
681
- apply(delta) {
682
- var _a;
683
- let checksum = this.checksumValue;
684
- for (const [levels2, changes, side] of [
685
- [this.bids, delta.bidChanges, "B"],
686
- [this.asks, delta.askChanges, "A"]
687
- ]) {
688
- const changed = /* @__PURE__ */ new Map();
689
- for (const [price, size, venues] of changes) {
690
- const key = toPriceKey(price);
691
- const previous = changed.has(key) ? changed.get(key) : levels2.get(key);
692
- if (previous) checksum ^= orderbookCrc32(`${side}${previous.price}:${previous.size}`);
693
- if (size !== 0) checksum ^= orderbookCrc32(`${side}${price}:${size}`);
694
- changed.set(key, size === 0 ? void 0 : { price, size, venues: __spreadValues({}, venues) });
695
- }
696
- }
697
- checksum >>>= 0;
698
- if (checksum !== delta.checksum) return checksum;
699
- const previousBids = delta.bidChanges.flatMap(
700
- ([price]) => {
701
- var _a2;
702
- return (_a2 = this.bids.get(toPriceKey(price))) != null ? _a2 : [];
703
- }
704
- );
705
- const previousAsks = delta.askChanges.flatMap(
706
- ([price]) => {
707
- var _a2;
708
- return (_a2 = this.asks.get(toPriceKey(price))) != null ? _a2 : [];
709
- }
710
- );
711
- const impliedBids = deriveVenueChangesFromAttributedChanges(previousBids, delta.bidChanges);
712
- const impliedAsks = deriveVenueChangesFromAttributedChanges(previousAsks, delta.askChanges);
713
- for (const venue of /* @__PURE__ */ new Set([
714
- ...Object.keys(delta.venueDeltaBooks),
715
- ...Object.keys(impliedBids),
716
- ...Object.keys(impliedAsks)
717
- ])) {
718
- let book = this.venueBooks.get(venue);
719
- if (!book) {
720
- book = { bids: /* @__PURE__ */ new Map(), asks: /* @__PURE__ */ new Map() };
721
- this.venueBooks.set(venue, book);
722
- }
723
- const explicit = delta.venueDeltaBooks[venue];
724
- for (const [levels2, changes] of [
725
- [book.bids, mergeVenueLevelChanges(explicit == null ? void 0 : explicit.bidChanges, impliedBids[venue])],
726
- [book.asks, mergeVenueLevelChanges(explicit == null ? void 0 : explicit.askChanges, impliedAsks[venue])]
727
- ]) {
728
- for (const [price, size] of changes) {
729
- if (size === 0) levels2.delete(toPriceKey(price));
730
- else levels2.set(toPriceKey(price), { price, size });
731
- }
732
- }
733
- }
734
- for (const [levels2, changes] of [
735
- [this.bids, delta.bidChanges],
736
- [this.asks, delta.askChanges]
737
- ]) {
738
- for (const [price, size, venues] of changes) {
739
- if (size === 0) levels2.delete(toPriceKey(price));
740
- else levels2.set(toPriceKey(price), { price, size, venues: __spreadValues({}, venues) });
741
- }
742
- }
743
- this.metadata = __spreadProps(__spreadValues({}, this.metadata), {
744
- outcomeId: (_a = this.metadata.outcomeId) != null ? _a : delta.outcomeId,
745
- venues: __spreadValues(__spreadValues({}, this.metadata.venues), delta.venues),
746
- midpoint: delta.midpoint,
747
- spread: delta.spread,
748
- seq: delta.seq,
749
- checksum: delta.checksum,
750
- timestamp: delta.timestamp
751
- });
752
- this.checksumValue = checksum;
753
- this.cached = null;
754
- return checksum;
755
- }
756
- view() {
757
- if (this.cached) return this.cached;
758
- const bids = (levels2) => [...levels2.values()].sort((a, b) => b.price - a.price);
759
- const asks = (levels2) => [...levels2.values()].sort((a, b) => a.price - b.price);
760
- this.cached = __spreadProps(__spreadValues({}, this.metadata), {
761
- bids: bids(this.bids),
762
- asks: asks(this.asks),
763
- venueOrderbooks: Object.fromEntries(
764
- [...this.venueBooks].map(([venue, book]) => [
765
- venue,
766
- { bids: bids(book.bids), asks: asks(book.asks) }
767
- ])
768
- )
769
- });
770
- return this.cached;
771
- }
772
- };
773
-
774
- // src/agg-websocket.ts
775
- var RECONNECT_BASE_MS = 1e3;
776
- var RECONNECT_MAX_MS = 3e4;
777
- var STALE_TIMEOUT_MS = 45e3;
778
- var ORDERBOOK_DEBUG_TOP_LEVELS = 5;
779
- var AggWebSocket = class {
780
- constructor(options) {
781
- this.ws = null;
782
- // ── Subscription tracking ──
783
- this.subs = /* @__PURE__ */ new Map();
784
- this.pendingSubs = /* @__PURE__ */ new Set();
785
- this.pendingTradeSubs = /* @__PURE__ */ new Set();
786
- this.pendingResnapshots = /* @__PURE__ */ new Set();
787
- // ── Post-connect batching (coalesces same-tick sub/unsub calls into one frame) ──
788
- this.pendingFlushSubs = /* @__PURE__ */ new Set();
789
- this.pendingFlushUnsubs = /* @__PURE__ */ new Set();
790
- this.pendingFlushTradeSubs = /* @__PURE__ */ new Set();
791
- this.pendingFlushTradeUnsubs = /* @__PURE__ */ new Set();
792
- this.pendingFlushArbSubs = /* @__PURE__ */ new Set();
793
- this.pendingFlushArbUnsubs = /* @__PURE__ */ new Set();
794
- this.flushScheduled = false;
795
- // ── Arb subscriptions ──
796
- this.arbSubs = /* @__PURE__ */ new Map();
797
- this.arbFeedCbs = /* @__PURE__ */ new Set();
798
- /** Latest arb market update per marketId (last-value-wins, loss-tolerant). */
799
- this.latestArb = /* @__PURE__ */ new Map();
800
- // ── Orderbook state per market ──
801
- this.books = /* @__PURE__ */ new Map();
802
- /** Markets currently resyncing (awaiting snapshot after seq gap / checksum mismatch). */
803
- this.resyncing = /* @__PURE__ */ new Set();
804
- // ── Connection state ──
805
- this.connecting = false;
806
- this._connected = false;
807
- this.reconnectAttempts = 0;
808
- this.reconnectTimer = null;
809
- this.staleTimer = null;
810
- this.lastMessageTime = 0;
811
- this.destroyed = false;
812
- this.historyControllers = /* @__PURE__ */ new Set();
813
- var _a, _b, _c;
814
- this.deferBookViews = (_a = options.deferBookViews) != null ? _a : false;
815
- this.url = options.url;
816
- this.callbacks = (_b = options.callbacks) != null ? _b : {};
817
- this.initialToken = options.initialToken;
818
- this.enableLogs = (_c = options.enableLogs) != null ? _c : false;
819
- }
820
- // ── Public API ──
821
- get connected() {
822
- return this._connected;
823
- }
824
- /** Decode dynamic authenticated REST bytes in the same processing environment as live data. */
825
- decodeHistory(payload) {
826
- return __async(this, null, function* () {
827
- return decodeChartHistory(payload);
828
- });
829
- }
830
- /** Immutable history decoder. Browser adapters execute this inside their Worker. */
831
- loadHistory(manifest, options) {
832
- return __async(this, null, function* () {
833
- var _a, _b, _c;
834
- if (this.destroyed) throw new Error("Market-data client disposed");
835
- const controller = new AbortController();
836
- const abort = () => {
837
- var _a2;
838
- return controller.abort((_a2 = options == null ? void 0 : options.signal) == null ? void 0 : _a2.reason);
839
- };
840
- (_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.addEventListener("abort", abort, { once: true });
841
- if ((_b = options == null ? void 0 : options.signal) == null ? void 0 : _b.aborted) abort();
842
- this.historyControllers.add(controller);
843
- try {
844
- controller.signal.throwIfAborted();
845
- const result = yield loadImmutableHistory({ manifest, signal: controller.signal });
846
- controller.signal.throwIfAborted();
847
- return result;
848
- } finally {
849
- this.historyControllers.delete(controller);
850
- (_c = options == null ? void 0 : options.signal) == null ? void 0 : _c.removeEventListener("abort", abort);
851
- }
852
- });
853
- }
854
- /** Optional framework-independent host diagnostics, cleared on disposal. */
855
- setHostDiagnostics(provider) {
856
- this.hostDiagnostics = provider;
857
- }
858
- /** On-demand ownership diagnostics; contains no credentials or user/account data. */
859
- getDiagnostics() {
860
- var _a;
861
- return {
862
- connected: this.connected,
863
- host: (_a = this.hostDiagnostics) == null ? void 0 : _a.call(this),
864
- transport: this.destroyed ? "disposed" : "direct",
865
- orderbookOutcomeIds: this.activeOrderbookMarkets(),
866
- tradeOutcomeIds: this.activeTradeMarkets(),
867
- arbMarketIds: this.activeArbMarkets(),
868
- arbFeedSubscribers: this.arbFeedCbs.size,
869
- cachedBooks: this.books.size,
870
- cachedArb: this.latestArb.size,
871
- resyncingBooks: this.resyncing.size,
872
- pendingResnapshots: this.pendingResnapshots.size,
873
- pendingHistoryRequests: this.historyControllers.size
874
- };
875
- }
876
- /** Get the current orderbook state for an outcome (or null if no snapshot received yet). */
877
- getBook(outcomeId) {
878
- var _a, _b;
879
- return (_b = (_a = this.books.get(outcomeId)) == null ? void 0 : _a.view()) != null ? _b : null;
880
- }
881
- /** Whether an outcome is currently resyncing (waiting for fresh snapshot). */
882
- isResyncing(outcomeId) {
883
- return this.resyncing.has(outcomeId);
884
- }
885
- /** Get the latest arb update for a market (or null if none received yet). */
886
- getArb(marketId) {
887
- var _a;
888
- return (_a = this.latestArb.get(marketId)) != null ? _a : null;
889
- }
890
- /**
891
- * Subscribe to per-market arb updates for a given marketId.
892
- * Ref-counted: multiple callers for the same marketId share one server subscription.
893
- * Returns an unsubscribe function.
894
- */
895
- subscribeArb(marketId, cb) {
896
- let entry = this.arbSubs.get(marketId);
897
- if (!entry) {
898
- entry = { refCount: 0, cbs: /* @__PURE__ */ new Set() };
899
- this.arbSubs.set(marketId, entry);
900
- this.ensureConnected();
901
- if (this._connected) {
902
- this.pendingFlushArbUnsubs.delete(marketId);
903
- this.pendingFlushArbSubs.add(marketId);
904
- this.scheduleFlush();
905
- }
906
- }
907
- entry.cbs.add(cb);
908
- entry.refCount++;
909
- return () => {
910
- const e = this.arbSubs.get(marketId);
911
- if (!e) return;
912
- e.cbs.delete(cb);
913
- e.refCount--;
914
- if (e.refCount <= 0) {
915
- this.arbSubs.delete(marketId);
916
- if (this._connected) {
917
- if (this.pendingFlushArbSubs.has(marketId)) {
918
- this.pendingFlushArbSubs.delete(marketId);
919
- } else {
920
- this.pendingFlushArbUnsubs.add(marketId);
921
- this.scheduleFlush();
922
- }
923
- }
924
- }
925
- };
926
- }
927
- /**
928
- * Subscribe to the global arb-feed batches.
929
- * Only one server subscription is maintained regardless of how many callers.
930
- * Returns an unsubscribe function.
931
- */
932
- subscribeArbFeed(cb) {
933
- const wasEmpty = this.arbFeedCbs.size === 0;
934
- this.arbFeedCbs.add(cb);
935
- if (wasEmpty) {
936
- this.ensureConnected();
937
- if (this._connected) {
938
- this.send({ action: "subscribe", channel: "arb-feed" });
939
- }
940
- }
941
- return () => {
942
- this.arbFeedCbs.delete(cb);
943
- if (this.arbFeedCbs.size === 0 && this._connected) {
944
- this.send({ action: "unsubscribe", channel: "arb-feed" });
945
- }
946
- };
947
- }
948
- /**
949
- * Subscribe to a feed by outcome ID.
950
- * @param outcomeId The venueMarketOutcomeId to subscribe to.
951
- * @param channel "orderbook" (default) or "trades".
952
- * Returns an unsubscribe function (ref-counted).
953
- */
954
- subscribe(outcomeId, channel = "orderbook") {
955
- if (channel === "trades") {
956
- return this._subscribeTrades(outcomeId);
957
- }
958
- let sub = this.subs.get(outcomeId);
959
- if (!sub) {
960
- sub = { refCount: 0, tradeRefs: 0 };
961
- this.subs.set(outcomeId, sub);
962
- }
963
- if (sub.refCount === 0) {
964
- this.pendingSubs.add(outcomeId);
965
- this.ensureConnected();
966
- if (this._connected) {
967
- this.pendingFlushUnsubs.delete(outcomeId);
968
- this.pendingFlushSubs.add(outcomeId);
969
- this.pendingSubs.delete(outcomeId);
970
- this.scheduleFlush();
971
- }
972
- }
973
- sub.refCount++;
974
- let released = false;
975
- return () => {
976
- if (released) return;
977
- released = true;
978
- const s = this.subs.get(outcomeId);
979
- if (!s) return;
980
- s.refCount--;
981
- if (s.refCount <= 0) {
982
- s.refCount = 0;
983
- if (s.tradeRefs <= 0) {
984
- this.subs.delete(outcomeId);
985
- this.books.delete(outcomeId);
986
- }
987
- this.resyncing.delete(outcomeId);
988
- if (this._connected) {
989
- if (this.pendingFlushSubs.has(outcomeId)) {
990
- this.pendingFlushSubs.delete(outcomeId);
991
- } else {
992
- this.pendingFlushUnsubs.add(outcomeId);
993
- this.scheduleFlush();
994
- }
995
- }
996
- this.pendingSubs.delete(outcomeId);
997
- this.pendingResnapshots.delete(outcomeId);
998
- }
999
- };
1000
- }
1001
- /**
1002
- * Subscribe to an outcome's trade feed.
1003
- * @deprecated Use `subscribe(outcomeId, "trades")` instead.
1004
- * Returns an unsubscribe function.
1005
- */
1006
- subscribeTrades(outcomeId) {
1007
- return this._subscribeTrades(outcomeId);
1008
- }
1009
- _subscribeTrades(outcomeId) {
1010
- let sub = this.subs.get(outcomeId);
1011
- if (!sub) {
1012
- sub = { refCount: 0, tradeRefs: 0 };
1013
- this.subs.set(outcomeId, sub);
1014
- }
1015
- if (sub.tradeRefs === 0) {
1016
- this.pendingTradeSubs.add(outcomeId);
1017
- this.ensureConnected();
1018
- if (this._connected) {
1019
- this.pendingFlushTradeUnsubs.delete(outcomeId);
1020
- this.pendingFlushTradeSubs.add(outcomeId);
1021
- this.pendingTradeSubs.delete(outcomeId);
1022
- this.scheduleFlush();
1023
- }
1024
- }
1025
- sub.tradeRefs++;
1026
- let released = false;
1027
- return () => {
1028
- if (released) return;
1029
- released = true;
1030
- const s = this.subs.get(outcomeId);
1031
- if (!s) return;
1032
- s.tradeRefs--;
1033
- if (s.tradeRefs <= 0) {
1034
- s.tradeRefs = 0;
1035
- if (this._connected) {
1036
- if (this.pendingFlushTradeSubs.has(outcomeId)) {
1037
- this.pendingFlushTradeSubs.delete(outcomeId);
1038
- } else {
1039
- this.pendingFlushTradeUnsubs.add(outcomeId);
1040
- this.scheduleFlush();
1041
- }
1042
- }
1043
- this.pendingTradeSubs.delete(outcomeId);
1044
- this.pendingResnapshots.delete(outcomeId);
1045
- if (s.refCount <= 0) {
1046
- this.subs.delete(outcomeId);
1047
- this.books.delete(outcomeId);
1048
- this.resyncing.delete(outcomeId);
1049
- }
1050
- }
1051
- };
1052
- }
1053
- /** Send a JWT to authenticate (or re-authenticate) the connection. */
1054
- authenticate(token) {
1055
- if (this._connected) {
1056
- this.send({ action: "authenticate", token });
1057
- }
1058
- }
1059
- /** Request a fresh snapshot for one or more subscribed outcomes. */
1060
- resnapshot(outcomeIdOrIds) {
1061
- const outcomeIds = Array.isArray(outcomeIdOrIds) ? outcomeIdOrIds : [outcomeIdOrIds];
1062
- outcomeIds.forEach((outcomeId) => {
1063
- this.requestResnapshot(outcomeId, true);
1064
- });
1065
- }
1066
- /** Connect (idempotent). Called automatically on first subscribe. */
1067
- connect() {
1068
- this.ensureConnected();
1069
- }
1070
- /** Disconnect and clean up. Reusable — call connect() to reconnect. */
1071
- disconnect() {
1072
- var _a, _b;
1073
- this.cancelReconnect();
1074
- this.cancelStaleTimer();
1075
- this._connected = false;
1076
- this.connecting = false;
1077
- if (this.ws) {
1078
- this.ws.onclose = null;
1079
- this.ws.close();
1080
- this.ws = null;
1081
- }
1082
- (_b = (_a = this.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, false);
1083
- }
1084
- /** Permanently destroy. Cannot reconnect after this. */
1085
- destroy() {
1086
- this.destroyed = true;
1087
- for (const controller of this.historyControllers)
1088
- controller.abort(new Error("Market-data client disposed"));
1089
- this.historyControllers.clear();
1090
- this.disconnect();
1091
- this.hostDiagnostics = void 0;
1092
- this.callbacks = {};
1093
- this.subs.clear();
1094
- this.books.clear();
1095
- this.resyncing.clear();
1096
- this.pendingSubs.clear();
1097
- this.pendingTradeSubs.clear();
1098
- this.pendingResnapshots.clear();
1099
- this.pendingFlushSubs.clear();
1100
- this.pendingFlushUnsubs.clear();
1101
- this.pendingFlushTradeSubs.clear();
1102
- this.pendingFlushTradeUnsubs.clear();
1103
- this.arbSubs.clear();
1104
- this.arbFeedCbs.clear();
1105
- this.latestArb.clear();
1106
- this.pendingFlushArbSubs.clear();
1107
- this.pendingFlushArbUnsubs.clear();
1108
- this.flushScheduled = false;
1109
- }
1110
- /** Update callbacks (e.g., after React re-render). */
1111
- setCallbacks(callbacks) {
1112
- this.callbacks = callbacks;
1113
- }
1114
- // ── Connection management ──
1115
- ensureConnected() {
1116
- var _a;
1117
- if (this.destroyed) return;
1118
- if (((_a = this.ws) == null ? void 0 : _a.readyState) === WebSocket.OPEN || this.connecting) return;
1119
- this.doConnect();
1120
- }
1121
- doConnect() {
1122
- if (this.destroyed) return;
1123
- this.connecting = true;
1124
- const ws = new WebSocket(this.url);
1125
- this.ws = ws;
1126
- ws.onopen = () => {
1127
- if (this.destroyed || this.ws !== ws) return;
1128
- this.connecting = false;
1129
- this.reconnectAttempts = 0;
1130
- this.resetStaleTimer();
1131
- if (this.initialToken) {
1132
- this.send({ action: "authenticate", token: this.initialToken });
1133
- }
1134
- };
1135
- ws.onmessage = (event) => {
1136
- var _a, _b;
1137
- if (this.destroyed || this.ws !== ws) return;
1138
- this.lastMessageTime = Date.now();
1139
- (_b = (_a = this.callbacks).onFrameReceived) == null ? void 0 : _b.call(_a, this.lastMessageTime);
1140
- this.resetStaleTimer();
1141
- try {
1142
- const raw = JSON.parse(event.data);
1143
- this.handleMessage(raw);
1144
- } catch (e) {
1145
- }
1146
- };
1147
- ws.onclose = () => {
1148
- var _a, _b;
1149
- this.ws = null;
1150
- this.connecting = false;
1151
- const wasConnected = this._connected;
1152
- this._connected = false;
1153
- this.cancelStaleTimer();
1154
- if (wasConnected) {
1155
- (_b = (_a = this.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, false);
1156
- }
1157
- if (!this.destroyed && (this.subs.size > 0 || this.arbSubs.size > 0 || this.arbFeedCbs.size > 0)) {
1158
- this.scheduleReconnect();
1159
- }
1160
- };
1161
- ws.onerror = () => {
1162
- };
1163
- }
1164
- scheduleReconnect() {
1165
- this.cancelReconnect();
1166
- const delay = Math.min(
1167
- RECONNECT_BASE_MS * Math.pow(2, this.reconnectAttempts),
1168
- RECONNECT_MAX_MS
1169
- );
1170
- this.reconnectAttempts++;
1171
- this.emitDiagnostic({ type: "reconnect", attempt: this.reconnectAttempts, delayMs: delay });
1172
- this.reconnectTimer = setTimeout(() => {
1173
- this.reconnectTimer = null;
1174
- this.doConnect();
1175
- }, delay);
1176
- }
1177
- cancelReconnect() {
1178
- if (this.reconnectTimer) {
1179
- clearTimeout(this.reconnectTimer);
1180
- this.reconnectTimer = null;
1181
- }
1182
- }
1183
- // ── Staleness detection ──
1184
- resetStaleTimer() {
1185
- this.cancelStaleTimer();
1186
- this.staleTimer = setTimeout(() => {
1187
- const age = Date.now() - this.lastMessageTime;
1188
- this.emitDiagnostic({ type: "stale_connection", lastMessageAge: age });
1189
- if (this.ws) {
1190
- this.ws.close();
1191
- }
1192
- }, STALE_TIMEOUT_MS);
1193
- }
1194
- cancelStaleTimer() {
1195
- if (this.staleTimer) {
1196
- clearTimeout(this.staleTimer);
1197
- this.staleTimer = null;
1198
- }
1199
- }
1200
- // ── Message handling ──
1201
- handleMessage(raw) {
1202
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
1203
- const type = raw.type;
1204
- if (["orderbook_snapshot", "orderbook_delta", "trade"].includes(type) && !validMarketFrame(raw)) {
1205
- (_b = (_a = this.callbacks).onError) == null ? void 0 : _b.call(_a, { type: "error", message: "Invalid market-data frame" });
1206
- if (typeof raw.outcomeId === "string" && this.subs.has(raw.outcomeId))
1207
- this.requestResnapshot(raw.outcomeId);
1208
- return;
1209
- }
1210
- switch (type) {
1211
- case "orderbook_snapshot":
1212
- this.handleSnapshot(raw);
1213
- break;
1214
- case "orderbook_delta":
1215
- this.handleDelta(raw);
1216
- break;
1217
- case "trade":
1218
- this.handleTrade(raw);
1219
- break;
1220
- case "heartbeat":
1221
- this.handleHeartbeat(raw);
1222
- break;
1223
- case "subscribed":
1224
- (_d = (_c = this.callbacks).onSubscribed) == null ? void 0 : _d.call(_c, raw);
1225
- break;
1226
- case "unsubscribed":
1227
- (_f = (_e = this.callbacks).onUnsubscribed) == null ? void 0 : _f.call(_e, raw);
1228
- break;
1229
- case "connected":
1230
- this.handleConnected(raw);
1231
- break;
1232
- case "authenticated":
1233
- (_h = (_g = this.callbacks).onAuthenticated) == null ? void 0 : _h.call(_g, raw);
1234
- break;
1235
- case "market_resolved":
1236
- this.handleMarketResolved(raw);
1237
- break;
1238
- case "error":
1239
- (_j = (_i = this.callbacks).onError) == null ? void 0 : _j.call(_i, raw);
1240
- break;
1241
- case "order_submitted":
1242
- this.handleOrderSubmitted(raw);
1243
- break;
1244
- case "balance_update":
1245
- this.handleBalanceUpdate(raw);
1246
- break;
1247
- case "order_event":
1248
- (_l = (_k = this.callbacks).onOrderEvent) == null ? void 0 : _l.call(_k, raw);
1249
- break;
1250
- case "redeem_event":
1251
- this.handleRedeemEvent(raw);
1252
- break;
1253
- case "withdrawal_lifecycle":
1254
- (_n = (_m = this.callbacks).onWithdrawalLifecycle) == null ? void 0 : _n.call(_m, raw);
1255
- break;
1256
- case "arb_market_update": {
1257
- const arbMsg = raw;
1258
- this.latestArb.set(arbMsg.marketId, arbMsg);
1259
- const arbEntry = this.arbSubs.get(arbMsg.marketId);
1260
- if (arbEntry) {
1261
- for (const cb of arbEntry.cbs) cb(arbMsg);
1262
- }
1263
- (_p = (_o = this.callbacks).onArbMarket) == null ? void 0 : _p.call(_o, arbMsg);
1264
- break;
1265
- }
1266
- case "arb_feed_batch": {
1267
- const feedMsg = raw;
1268
- for (const cb of this.arbFeedCbs) cb(feedMsg);
1269
- (_r = (_q = this.callbacks).onArbFeed) == null ? void 0 : _r.call(_q, feedMsg);
1270
- break;
1271
- }
1272
- }
1273
- }
1274
- /**
1275
- * Server confirmed the connection — gateway has validated our appId and is
1276
- * ready to accept subscriptions. Now flush all pending subs.
1277
- */
1278
- handleConnected(msg) {
1279
- var _a, _b, _c, _d;
1280
- this._connected = true;
1281
- (_b = (_a = this.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, true);
1282
- (_d = (_c = this.callbacks).onConnected) == null ? void 0 : _d.call(_c, msg);
1283
- const orderbookSet = new Set(this.activeOrderbookMarkets());
1284
- this.pendingSubs.forEach((id) => orderbookSet.add(id));
1285
- this.pendingFlushSubs.forEach((id) => orderbookSet.add(id));
1286
- const orderbookIds = Array.from(orderbookSet);
1287
- if (orderbookIds.length > 0) {
1288
- this.sendSubscribe(orderbookIds);
1289
- }
1290
- this.pendingSubs.clear();
1291
- this.pendingFlushSubs.clear();
1292
- this.pendingFlushUnsubs.clear();
1293
- const tradeSet = new Set(this.activeTradeMarkets());
1294
- this.pendingTradeSubs.forEach((id) => tradeSet.add(id));
1295
- this.pendingFlushTradeSubs.forEach((id) => tradeSet.add(id));
1296
- const tradeIds = Array.from(tradeSet);
1297
- if (tradeIds.length > 0) {
1298
- this.send({ action: "subscribe", channel: "trades", outcomeIds: tradeIds });
1299
- }
1300
- this.pendingTradeSubs.clear();
1301
- this.pendingFlushTradeSubs.clear();
1302
- this.pendingFlushTradeUnsubs.clear();
1303
- const resnapshotIds = Array.from(this.pendingResnapshots);
1304
- if (resnapshotIds.length > 0) {
1305
- this.send({ action: "resnapshot", channel: "orderbook", outcomeIds: resnapshotIds });
1306
- }
1307
- this.pendingResnapshots.clear();
1308
- const arbSet = new Set(this.activeArbMarkets());
1309
- this.pendingFlushArbSubs.forEach((id) => arbSet.add(id));
1310
- const arbIds = Array.from(arbSet);
1311
- if (arbIds.length > 0) {
1312
- this.send({ action: "subscribe", channel: "arb", marketIds: arbIds });
1313
- }
1314
- this.pendingFlushArbSubs.clear();
1315
- this.pendingFlushArbUnsubs.clear();
1316
- if (this.arbFeedCbs.size > 0) {
1317
- this.send({ action: "subscribe", channel: "arb-feed" });
1318
- }
1319
- }
1320
- handleSnapshot(raw) {
1321
- var _a, _b, _c, _d;
1322
- if (!this.subs.has(raw.outcomeId)) return;
1323
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1324
- const book = snapshotToOrderbook(msg);
1325
- this.books.set(msg.outcomeId, new IndexedOrderbook(book));
1326
- this.resyncing.delete(msg.outcomeId);
1327
- this.pendingResnapshots.delete(msg.outcomeId);
1328
- this.debugOrderbook("snapshot_applied", {
1329
- outcomeId: msg.outcomeId,
1330
- seq: msg.seq,
1331
- checksum: msg.checksum,
1332
- bidsTop: this.summarizeTopLevels(book.bids),
1333
- asksTop: this.summarizeTopLevels(book.asks)
1334
- });
1335
- (_b = (_a = this.callbacks).onBookTick) == null ? void 0 : _b.call(_a, msg.outcomeId, {
1336
- midpoint: msg.midpoint,
1337
- timestamp: msg.timestamp,
1338
- source: "snapshot"
1339
- });
1340
- if (!this.deferBookViews) (_d = (_c = this.callbacks).onSnapshot) == null ? void 0 : _d.call(_c, msg.outcomeId, book);
1341
- }
1342
- handleDelta(raw) {
1343
- var _a, _b, _c, _d;
1344
- if (!this.subs.has(raw.outcomeId)) return;
1345
- const outcomeId = raw.outcomeId;
1346
- const current = this.books.get(outcomeId);
1347
- if (!current) {
1348
- this.debugOrderbook("delta_missing_snapshot", { outcomeId, seq: raw.seq });
1349
- this.requestResnapshot(outcomeId);
1350
- return;
1351
- }
1352
- if (raw.seq <= current.seq) {
1353
- this.debugOrderbook("delta_stale_ignored", {
1354
- outcomeId,
1355
- currentSeq: current.seq,
1356
- receivedSeq: raw.seq
1357
- });
1358
- return;
1359
- }
1360
- if (raw.seq > current.seq + 1) {
1361
- this.debugOrderbook("delta_seq_gap", {
1362
- outcomeId,
1363
- expectedSeq: current.seq + 1,
1364
- receivedSeq: raw.seq
1365
- });
1366
- this.emitDiagnostic({
1367
- type: "seq_gap",
1368
- marketId: outcomeId,
1369
- outcomeId,
1370
- expected: current.seq + 1,
1371
- received: raw.seq
1372
- });
1373
- this.requestResnapshot(outcomeId);
1374
- return;
1375
- }
1376
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1377
- const computed = current.apply(msg);
1378
- if (computed !== msg.checksum) {
1379
- this.debugOrderbook("delta_checksum_mismatch", {
1380
- outcomeId,
1381
- seq: msg.seq,
1382
- expected: msg.checksum,
1383
- computed
1384
- });
1385
- this.emitDiagnostic({
1386
- type: "checksum_mismatch",
1387
- marketId: outcomeId,
1388
- outcomeId,
1389
- expected: msg.checksum,
1390
- computed
1391
- });
1392
- this.requestResnapshot(outcomeId);
1393
- return;
1394
- }
1395
- (_b = (_a = this.callbacks).onBookTick) == null ? void 0 : _b.call(_a, outcomeId, {
1396
- midpoint: msg.midpoint,
1397
- timestamp: msg.timestamp,
1398
- source: "delta"
1399
- });
1400
- if (!this.deferBookViews) (_d = (_c = this.callbacks).onDelta) == null ? void 0 : _d.call(_c, outcomeId, current.view());
1401
- }
1402
- handleTrade(raw) {
1403
- var _a, _b;
1404
- if (!this.subs.has(raw.outcomeId)) return;
1405
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1406
- (_b = (_a = this.callbacks).onTrade) == null ? void 0 : _b.call(_a, msg);
1407
- }
1408
- handleHeartbeat(raw) {
1409
- var _a, _b;
1410
- const msg = __spreadProps(__spreadValues({}, raw), { ts: raw.ts / 1e3 });
1411
- (_b = (_a = this.callbacks).onHeartbeat) == null ? void 0 : _b.call(_a, msg);
1412
- }
1413
- handleMarketResolved(raw) {
1414
- var _a, _b;
1415
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1416
- this.books.delete(msg.outcomeId);
1417
- this.pendingResnapshots.delete(msg.outcomeId);
1418
- this.resyncing.delete(msg.outcomeId);
1419
- (_b = (_a = this.callbacks).onMarketResolved) == null ? void 0 : _b.call(_a, msg);
1420
- }
1421
- handleOrderSubmitted(raw) {
1422
- var _a, _b;
1423
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1424
- (_b = (_a = this.callbacks).onOrderSubmitted) == null ? void 0 : _b.call(_a, msg);
1425
- }
1426
- handleBalanceUpdate(raw) {
1427
- var _a, _b;
1428
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1429
- (_b = (_a = this.callbacks).onBalanceUpdate) == null ? void 0 : _b.call(_a, msg);
1430
- }
1431
- handleRedeemEvent(raw) {
1432
- var _a, _b;
1433
- const msg = __spreadProps(__spreadValues({}, raw), { timestamp: raw.timestamp / 1e3 });
1434
- (_b = (_a = this.callbacks).onRedeemEvent) == null ? void 0 : _b.call(_a, msg);
1435
- }
1436
- // ── Resnapshot ──
1437
- requestResnapshot(outcomeId, force = false) {
1438
- if (this.resyncing.has(outcomeId) && !force) return;
1439
- this.resyncing.add(outcomeId);
1440
- if (this._connected) {
1441
- this.send({ action: "resnapshot", channel: "orderbook", outcomeIds: [outcomeId] });
1442
- this.pendingResnapshots.delete(outcomeId);
1443
- return;
1444
- }
1445
- this.pendingResnapshots.add(outcomeId);
1446
- this.ensureConnected();
1447
- }
1448
- // ── Helpers ──
1449
- /**
1450
- * Schedule a microtask that flushes queued subscribe/unsubscribe frames.
1451
- * Coalesces multiple same-tick sub/unsub calls into at most one frame per
1452
- * channel+action pair.
1453
- */
1454
- scheduleFlush() {
1455
- if (this.flushScheduled) return;
1456
- this.flushScheduled = true;
1457
- queueMicrotask(() => {
1458
- this.flushScheduled = false;
1459
- if (!this._connected) {
1460
- this.pendingFlushSubs.clear();
1461
- this.pendingFlushUnsubs.clear();
1462
- this.pendingFlushTradeSubs.clear();
1463
- this.pendingFlushTradeUnsubs.clear();
1464
- this.pendingFlushArbSubs.clear();
1465
- this.pendingFlushArbUnsubs.clear();
1466
- return;
1467
- }
1468
- this.flushPending();
1469
- });
1470
- }
1471
- flushPending() {
1472
- for (const id of [...this.pendingFlushSubs]) {
1473
- if (this.pendingFlushUnsubs.has(id)) {
1474
- this.pendingFlushSubs.delete(id);
1475
- this.pendingFlushUnsubs.delete(id);
1476
- }
1477
- }
1478
- if (this.pendingFlushSubs.size > 0) {
1479
- this.sendSubscribe(Array.from(this.pendingFlushSubs));
1480
- this.pendingFlushSubs.clear();
1481
- }
1482
- if (this.pendingFlushUnsubs.size > 0) {
1483
- this.send({
1484
- action: "unsubscribe",
1485
- channel: "orderbook",
1486
- outcomeIds: Array.from(this.pendingFlushUnsubs)
1487
- });
1488
- this.pendingFlushUnsubs.clear();
1489
- }
1490
- for (const id of [...this.pendingFlushTradeSubs]) {
1491
- if (this.pendingFlushTradeUnsubs.has(id)) {
1492
- this.pendingFlushTradeSubs.delete(id);
1493
- this.pendingFlushTradeUnsubs.delete(id);
1494
- }
1495
- }
1496
- if (this.pendingFlushTradeSubs.size > 0) {
1497
- this.send({
1498
- action: "subscribe",
1499
- channel: "trades",
1500
- outcomeIds: Array.from(this.pendingFlushTradeSubs)
1501
- });
1502
- this.pendingFlushTradeSubs.clear();
1503
- }
1504
- if (this.pendingFlushTradeUnsubs.size > 0) {
1505
- this.send({
1506
- action: "unsubscribe",
1507
- channel: "trades",
1508
- outcomeIds: Array.from(this.pendingFlushTradeUnsubs)
1509
- });
1510
- this.pendingFlushTradeUnsubs.clear();
1511
- }
1512
- for (const id of [...this.pendingFlushArbSubs]) {
1513
- if (this.pendingFlushArbUnsubs.has(id)) {
1514
- this.pendingFlushArbSubs.delete(id);
1515
- this.pendingFlushArbUnsubs.delete(id);
1516
- }
1517
- }
1518
- if (this.pendingFlushArbSubs.size > 0) {
1519
- this.send({
1520
- action: "subscribe",
1521
- channel: "arb",
1522
- marketIds: Array.from(this.pendingFlushArbSubs)
1523
- });
1524
- this.pendingFlushArbSubs.clear();
1525
- }
1526
- if (this.pendingFlushArbUnsubs.size > 0) {
1527
- this.send({
1528
- action: "unsubscribe",
1529
- channel: "arb",
1530
- marketIds: Array.from(this.pendingFlushArbUnsubs)
1531
- });
1532
- this.pendingFlushArbUnsubs.clear();
1533
- }
1534
- }
1535
- sendSubscribe(outcomeIds) {
1536
- this.send({ action: "subscribe", channel: "orderbook", outcomeIds });
1537
- }
1538
- send(msg) {
1539
- var _a;
1540
- if (((_a = this.ws) == null ? void 0 : _a.readyState) === WebSocket.OPEN) {
1541
- this.ws.send(JSON.stringify(msg));
1542
- }
1543
- }
1544
- activeOrderbookMarkets() {
1545
- const markets = [];
1546
- this.subs.forEach((sub, id) => {
1547
- if (sub.refCount > 0) markets.push(id);
1548
- });
1549
- return markets;
1550
- }
1551
- activeTradeMarkets() {
1552
- const markets = [];
1553
- this.subs.forEach((sub, id) => {
1554
- if (sub.tradeRefs > 0) markets.push(id);
1555
- });
1556
- return markets;
1557
- }
1558
- activeArbMarkets() {
1559
- return Array.from(this.arbSubs.keys());
1560
- }
1561
- emitDiagnostic(event) {
1562
- var _a, _b;
1563
- (_b = (_a = this.callbacks).onDiagnostics) == null ? void 0 : _b.call(_a, event);
1564
- }
1565
- summarizeTopLevels(levels2) {
1566
- return levels2.slice(0, ORDERBOOK_DEBUG_TOP_LEVELS).map((level) => ({ price: level.price, size: level.size }));
1567
- }
1568
- debugOrderbook(event, payload) {
1569
- if (!this.isOrderbookDebugEnabled()) return;
1570
- console.debug(`[AggWebSocket][orderbook] ${event}`, payload);
1571
- }
1572
- isOrderbookDebugEnabled() {
1573
- return this.enableLogs;
1574
- }
1575
- };
1576
-
1577
- // src/market-data/worker-adapter.ts
1578
- var WorkerAggWebSocket = class extends AggWebSocket {
1579
- constructor(config, factory) {
1580
- var _a, _b;
1581
- super(config);
1582
- this.config = config;
1583
- this.endpointListeners = /* @__PURE__ */ new Map();
1584
- this.historyOperations = 0;
1585
- this.currentBooks = /* @__PURE__ */ new Map();
1586
- this.recovering = /* @__PURE__ */ new Set();
1587
- this.diagnosticRevisions = /* @__PURE__ */ new Map();
1588
- this.deliveredRevisions = /* @__PURE__ */ new Map();
1589
- this.resolvedRevisions = /* @__PURE__ */ new Map();
1590
- this.refs = /* @__PURE__ */ new Map();
1591
- this.arbListeners = /* @__PURE__ */ new Map();
1592
- this.feedListeners = /* @__PURE__ */ new Set();
1593
- this.latest = /* @__PURE__ */ new Map();
1594
- this.generation = 0;
1595
- this.online = false;
1596
- this.stopped = false;
1597
- this.queued = false;
1598
- this.historyFailures = /* @__PURE__ */ new Set();
1599
- this.fallback = null;
1600
- this.fallbackUnsubs = /* @__PURE__ */ new Map();
1601
- this.historyGeneration = 0;
1602
- this.visibility = () => {
1603
- if (document.visibilityState === "visible")
1604
- this.resnapshot(
1605
- [...this.refs.values()].filter((entry) => entry.sub.channel === "orderbook").map((entry) => entry.sub.id)
1606
- );
1607
- };
1608
- this.fail = () => {
1609
- var _a, _b, _c;
1610
- if (this.stopped || this.fallback) return;
1611
- this.releaseWorker();
1612
- this.currentBooks.clear();
1613
- this.latest.clear();
1614
- this.recovering.clear();
1615
- this.diagnosticRevisions.clear();
1616
- this.deliveredRevisions.clear();
1617
- this.resolvedRevisions.clear();
1618
- this.online = false;
1619
- (_b = (_a = this.handlers).onConnectionStateChange) == null ? void 0 : _b.call(_a, false);
1620
- this.fallback = new AggWebSocket(__spreadProps(__spreadValues({}, this.config), { callbacks: this.fallbackCallbacks() }));
1621
- for (const reject of this.historyFailures) reject(new Error("Market-data worker failed"));
1622
- this.historyFailures.clear();
1623
- (_c = this.resolveFailure) == null ? void 0 : _c.call(this);
1624
- this.syncFallback();
1625
- };
1626
- if (((_a = config.callbacks) == null ? void 0 : _a.onTrade) && !config.callbacks.onMarketView)
1627
- throw new Error(
1628
- "Raw trade callbacks require AggWebSocket; Worker views require onMarketView opt-in"
1629
- );
1630
- this.handlers = (_b = config.callbacks) != null ? _b : {};
1631
- this.worker = factory();
1632
- const worker = this.worker;
1633
- const endpoint = {
1634
- postMessage: worker.postMessage.bind(worker),
1635
- addEventListener: (type, listener) => {
1636
- this.endpointListeners.set(listener, type);
1637
- worker.addEventListener(type, listener);
1638
- },
1639
- removeEventListener: (type, listener) => {
1640
- this.endpointListeners.delete(listener);
1641
- worker.removeEventListener(type, listener);
1642
- }
1643
- };
1644
- this.remote = wrap(endpoint);
1645
- this.worker.addEventListener("error", this.fail);
1646
- this.worker.addEventListener("messageerror", this.fail);
1647
- const _c = config, { callbacks: _callbacks } = _c, options = __objRest(_c, ["callbacks"]);
1648
- const startup = this.remote.start(
1649
- options,
1650
- proxy((event) => {
1651
- if (!this.fallback) this.event(event.name, event.args, event.revision);
1652
- })
1653
- ).then(() => {
1654
- if (this.stopped || this.fallback || !this.remote) return;
1655
- return this.remote.observeViews(
1656
- proxy((batch) => {
1657
- var _a2, _b2, _c2, _d, _e, _f, _g, _h, _i, _j;
1658
- if (batch.generation < this.generation || this.stopped || this.fallback) return;
1659
- for (const view of batch.views) {
1660
- if (!this.refs.has(`orderbook:${view.outcomeId}`) && !this.refs.has(`trades:${view.outcomeId}`))
1661
- continue;
1662
- if (((_a2 = this.resolvedRevisions.get(view.outcomeId)) != null ? _a2 : -1) >= view.revision) continue;
1663
- const integrity = ((_b2 = this.diagnosticRevisions.get(view.outcomeId)) != null ? _b2 : -1) > view.revision ? "resyncing" : view.integrity;
1664
- this.deliveredRevisions.set(view.outcomeId, view.revision);
1665
- (_d = (_c2 = this.handlers).onMarketView) == null ? void 0 : _d.call(_c2, __spreadProps(__spreadValues({}, view), { integrity }));
1666
- if (view.book) {
1667
- this.currentBooks.set(view.outcomeId, view.book);
1668
- if (integrity === "ok") {
1669
- this.recovering.delete(view.outcomeId);
1670
- this.diagnosticRevisions.delete(view.outcomeId);
1671
- } else this.recovering.add(view.outcomeId);
1672
- if (view.snapshot) (_f = (_e = this.handlers).onSnapshot) == null ? void 0 : _f.call(_e, view.outcomeId, view.book);
1673
- else (_h = (_g = this.handlers).onDelta) == null ? void 0 : _h.call(_g, view.outcomeId, view.book);
1674
- }
1675
- for (const trade of [...view.trades].reverse()) (_j = (_i = this.handlers).onTrade) == null ? void 0 : _j.call(_i, trade);
1676
- }
1677
- })
1678
- );
1679
- }).catch(this.fail);
1680
- const failed = new Promise((resolve) => {
1681
- this.resolveFailure = resolve;
1682
- });
1683
- this.ready = Promise.race([startup, failed]);
1684
- const startupTimeout = setTimeout(this.fail, 3e3);
1685
- void this.ready.then(() => clearTimeout(startupTimeout));
1686
- if (typeof document !== "undefined")
1687
- document.addEventListener("visibilitychange", this.visibility);
1688
- }
1689
- get processesCandles() {
1690
- return !this.fallback;
1691
- }
1692
- decodeHistory(payload) {
1693
- return __async(this, null, function* () {
1694
- this.historyOperations++;
1695
- try {
1696
- return yield this.decodeHistoryRequest(payload);
1697
- } finally {
1698
- this.historyOperations--;
1699
- }
1700
- });
1701
- }
1702
- decodeHistoryRequest(payload) {
1703
- return __async(this, null, function* () {
1704
- if (this.stopped) throw new Error("Market-data worker disposed");
1705
- yield this.ready;
1706
- if (this.stopped) throw new Error("Market-data worker disposed");
1707
- if (this.fallback) return this.fallback.decodeHistory(payload);
1708
- const remote = this.remote;
1709
- if (!remote) throw new Error("Market-data worker unavailable");
1710
- let rejectFailure;
1711
- const failed = new Promise((_resolve, reject) => {
1712
- rejectFailure = reject;
1713
- this.historyFailures.add(reject);
1714
- });
1715
- try {
1716
- return yield Promise.race([remote.decodeHistory(payload), failed]);
1717
- } finally {
1718
- this.historyFailures.delete(rejectFailure);
1719
- }
1720
- });
1721
- }
1722
- loadHistory(manifest, options) {
1723
- return __async(this, null, function* () {
1724
- this.historyOperations++;
1725
- try {
1726
- return yield this.loadHistoryRequest(manifest, options);
1727
- } finally {
1728
- this.historyOperations--;
1729
- }
1730
- });
1731
- }
1732
- loadHistoryRequest(manifest, options) {
1733
- return __async(this, null, function* () {
1734
- var _a, _b, _c, _d, _e;
1735
- if (this.stopped) throw new Error("Market-data worker disposed");
1736
- if (this.fallback) return this.fallback.loadHistory(manifest, options);
1737
- const generation = ++this.historyGeneration;
1738
- const key = `${manifest.venueMarketOutcomeId}:${manifest.resolution}:${manifest.from}:${manifest.to}`;
1739
- (_a = options == null ? void 0 : options.signal) == null ? void 0 : _a.throwIfAborted();
1740
- yield this.ready;
1741
- if (this.stopped) throw new Error("Market-data worker disposed");
1742
- (_b = options == null ? void 0 : options.signal) == null ? void 0 : _b.throwIfAborted();
1743
- const fallbackAfterStartup = this.fallback;
1744
- if (fallbackAfterStartup) return fallbackAfterStartup.loadHistory(manifest, options);
1745
- const remote = this.remote;
1746
- if (!remote) throw new Error("Market-data worker unavailable");
1747
- let rejectFailure;
1748
- const failed = new Promise((_resolve, reject) => {
1749
- rejectFailure = reject;
1750
- this.historyFailures.add(reject);
1751
- });
1752
- const abort = () => {
1753
- var _a2;
1754
- void ((_a2 = this.remote) == null ? void 0 : _a2.cancelHistoryRange(key, generation));
1755
- };
1756
- (_c = options == null ? void 0 : options.signal) == null ? void 0 : _c.addEventListener("abort", abort, { once: true });
1757
- try {
1758
- const result = yield Promise.race([
1759
- remote.loadImmutableRange(key, generation, manifest),
1760
- failed
1761
- ]);
1762
- (_d = options == null ? void 0 : options.signal) == null ? void 0 : _d.throwIfAborted();
1763
- return result;
1764
- } finally {
1765
- (_e = options == null ? void 0 : options.signal) == null ? void 0 : _e.removeEventListener("abort", abort);
1766
- this.historyFailures.delete(rejectFailure);
1767
- }
1768
- });
1769
- }
1770
- setHostDiagnostics(provider) {
1771
- this.hostProvider = provider;
1772
- }
1773
- getDiagnostics() {
1774
- var _a, _b;
1775
- const subscriptions = [...this.refs.values()].map((entry) => entry.sub);
1776
- return this.fallback ? __spreadProps(__spreadValues({}, this.fallback.getDiagnostics()), {
1777
- host: (_a = this.hostProvider) == null ? void 0 : _a.call(this),
1778
- pendingHistoryRequests: this.historyOperations,
1779
- workerAttached: false,
1780
- bridgeListeners: this.endpointListeners.size
1781
- }) : {
1782
- connected: this.connected,
1783
- host: (_b = this.hostProvider) == null ? void 0 : _b.call(this),
1784
- transport: this.stopped ? "disposed" : "worker",
1785
- orderbookOutcomeIds: subscriptions.filter((sub) => sub.channel === "orderbook").map((sub) => sub.id),
1786
- tradeOutcomeIds: subscriptions.filter((sub) => sub.channel === "trades").map((sub) => sub.id),
1787
- arbMarketIds: [...this.arbListeners.keys()],
1788
- arbFeedSubscribers: this.feedListeners.size,
1789
- cachedBooks: this.currentBooks.size,
1790
- cachedArb: this.latest.size,
1791
- resyncingBooks: this.recovering.size,
1792
- pendingResnapshots: 0,
1793
- pendingHistoryRequests: this.historyOperations,
1794
- workerAttached: this.worker !== null,
1795
- bridgeListeners: this.endpointListeners.size
1796
- };
1797
- }
1798
- getWorkerDiagnostics() {
1799
- return __async(this, null, function* () {
1800
- yield this.ready;
1801
- const remote = this.remote;
1802
- if (this.stopped || !remote || this.fallback) return null;
1803
- let rejectFailure;
1804
- const failed = new Promise((_resolve, reject) => {
1805
- rejectFailure = reject;
1806
- this.historyFailures.add(reject);
1807
- });
1808
- try {
1809
- return yield Promise.race([remote.getMeasurements(), failed]);
1810
- } catch (e) {
1811
- return null;
1812
- } finally {
1813
- this.historyFailures.delete(rejectFailure);
1814
- }
1815
- });
1816
- }
1817
- get connected() {
1818
- var _a, _b;
1819
- return !this.stopped && ((_b = (_a = this.fallback) == null ? void 0 : _a.connected) != null ? _b : this.online);
1820
- }
1821
- getBook(id) {
1822
- var _a, _b, _c;
1823
- return (_c = (_b = (_a = this.fallback) == null ? void 0 : _a.getBook(id)) != null ? _b : this.currentBooks.get(id)) != null ? _c : null;
1824
- }
1825
- isResyncing(id) {
1826
- var _a, _b;
1827
- return (_b = (_a = this.fallback) == null ? void 0 : _a.isResyncing(id)) != null ? _b : this.recovering.has(id);
1828
- }
1829
- getArb(id) {
1830
- var _a, _b, _c;
1831
- return (_c = (_b = (_a = this.fallback) == null ? void 0 : _a.getArb(id)) != null ? _b : this.latest.get(id)) != null ? _c : null;
1832
- }
1833
- subscribe(id, channel = "orderbook") {
1834
- return this.ref({ id, channel });
1835
- }
1836
- subscribeTrades(id) {
1837
- return this.subscribe(id, "trades");
1838
- }
1839
- subscribeArb(id, cb) {
1840
- var _a;
1841
- const listeners = (_a = this.arbListeners.get(id)) != null ? _a : /* @__PURE__ */ new Set();
1842
- listeners.add(cb);
1843
- this.arbListeners.set(id, listeners);
1844
- const unsubscribe = this.ref({ id, channel: "arb" });
1845
- return () => {
1846
- unsubscribe();
1847
- listeners.delete(cb);
1848
- if (!listeners.size) this.arbListeners.delete(id);
1849
- };
1850
- }
1851
- subscribeArbFeed(cb) {
1852
- this.feedListeners.add(cb);
1853
- const unsubscribe = this.ref({ id: "*", channel: "arb-feed" });
1854
- return () => {
1855
- unsubscribe();
1856
- this.feedListeners.delete(cb);
1857
- };
1858
- }
1859
- setCallbacks(callbacks) {
1860
- var _a;
1861
- this.handlers = callbacks;
1862
- if (callbacks.onTrade && !callbacks.onMarketView && !this.fallback) this.fail();
1863
- (_a = this.fallback) == null ? void 0 : _a.setCallbacks(this.fallbackCallbacks());
1864
- }
1865
- authenticate(token) {
1866
- this.config.initialToken = token;
1867
- this.run((engine) => engine.authenticate(token));
1868
- }
1869
- connect() {
1870
- this.run((engine) => engine.connect());
1871
- }
1872
- disconnect() {
1873
- this.run((engine) => engine.disconnect());
1874
- }
1875
- resnapshot(id) {
1876
- const ids = Array.isArray(id) ? id : [id];
1877
- this.run((engine) => engine.resnapshot(ids));
1878
- }
1879
- destroy() {
1880
- var _a, _b;
1881
- if (this.stopped) return;
1882
- this.stopped = true;
1883
- this.online = false;
1884
- (_a = this.resolveFailure) == null ? void 0 : _a.call(this);
1885
- for (const reject of this.historyFailures) reject(new Error("Market-data worker disposed"));
1886
- this.historyFailures.clear();
1887
- this.refs.clear();
1888
- this.currentBooks.clear();
1889
- this.latest.clear();
1890
- this.arbListeners.clear();
1891
- this.feedListeners.clear();
1892
- this.recovering.clear();
1893
- this.diagnosticRevisions.clear();
1894
- this.deliveredRevisions.clear();
1895
- this.resolvedRevisions.clear();
1896
- (_b = this.fallback) == null ? void 0 : _b.destroy();
1897
- this.fallbackUnsubs.clear();
1898
- this.hostProvider = void 0;
1899
- this.handlers = {};
1900
- if (typeof document !== "undefined")
1901
- document.removeEventListener("visibilitychange", this.visibility);
1902
- this.releaseWorker();
1903
- }
1904
- releaseWorker() {
1905
- const worker = this.worker;
1906
- const remote = this.remote;
1907
- this.remote = null;
1908
- this.worker = null;
1909
- if (remote) remote[releaseProxy]();
1910
- if (!worker) return;
1911
- for (const [listener, type] of this.endpointListeners)
1912
- worker.removeEventListener(type, listener);
1913
- this.endpointListeners.clear();
1914
- worker.removeEventListener("error", this.fail);
1915
- worker.removeEventListener("messageerror", this.fail);
1916
- worker.terminate();
1917
- }
1918
- event(name, args, revision = 0) {
1919
- var _a, _b, _c, _d;
1920
- if (this.stopped) return;
1921
- if (name === "onConnectionStateChange") this.online = args[0];
1922
- if (name === "onDiagnostics") {
1923
- const diagnostic = args[0];
1924
- if (diagnostic.outcomeId && revision < ((_a = this.deliveredRevisions.get(diagnostic.outcomeId)) != null ? _a : -1))
1925
- return;
1926
- if (diagnostic.outcomeId && (this.refs.has(`orderbook:${diagnostic.outcomeId}`) || this.refs.has(`trades:${diagnostic.outcomeId}`)) && ["seq_gap", "checksum_mismatch"].includes(diagnostic.type)) {
1927
- this.recovering.add(diagnostic.outcomeId);
1928
- this.diagnosticRevisions.set(diagnostic.outcomeId, revision);
1929
- }
1930
- }
1931
- if (name === "onMarketResolved") {
1932
- const id = args[0].outcomeId;
1933
- if (this.refs.has(`orderbook:${id}`) || this.refs.has(`trades:${id}`))
1934
- this.resolvedRevisions.set(id, revision);
1935
- this.currentBooks.delete(id);
1936
- }
1937
- if (name === "onArbMarket") {
1938
- const msg = args[0];
1939
- this.latest.set(msg.marketId, msg);
1940
- for (const cb of (_b = this.arbListeners.get(msg.marketId)) != null ? _b : []) cb(msg);
1941
- }
1942
- if (name === "onArbFeed") for (const cb of this.feedListeners) cb(args[0]);
1943
- (_d = (_c = this.handlers)[name]) == null ? void 0 : _d.call(_c, ...args);
1944
- }
1945
- ref(sub) {
1946
- var _a;
1947
- const key = `${sub.channel}:${sub.id}`;
1948
- const entry = (_a = this.refs.get(key)) != null ? _a : { sub, count: 0 };
1949
- entry.count++;
1950
- this.refs.set(key, entry);
1951
- this.sync();
1952
- let released = false;
1953
- return () => {
1954
- if (released) return;
1955
- released = true;
1956
- if (--entry.count === 0) {
1957
- this.refs.delete(key);
1958
- if (sub.channel === "orderbook") this.recovering.delete(sub.id);
1959
- if (!this.refs.has(`orderbook:${sub.id}`) && !this.refs.has(`trades:${sub.id}`)) {
1960
- this.currentBooks.delete(sub.id);
1961
- this.recovering.delete(sub.id);
1962
- this.diagnosticRevisions.delete(sub.id);
1963
- this.deliveredRevisions.delete(sub.id);
1964
- this.resolvedRevisions.delete(sub.id);
1965
- }
1966
- }
1967
- this.sync();
1968
- };
1969
- }
1970
- sync() {
1971
- if (this.queued || this.stopped) return;
1972
- this.queued = true;
1973
- queueMicrotask(() => {
1974
- this.queued = false;
1975
- if (this.stopped) return;
1976
- if (this.fallback) {
1977
- this.syncFallback();
1978
- return;
1979
- }
1980
- const generation = ++this.generation;
1981
- const subscriptions = [...this.refs.values()].map((entry) => entry.sub);
1982
- void this.ready.then(() => {
1983
- var _a;
1984
- if (!this.stopped && !this.fallback)
1985
- return (_a = this.remote) == null ? void 0 : _a.setSubscriptions(subscriptions, generation);
1986
- }).catch(this.fail);
1987
- });
1988
- }
1989
- run(action) {
1990
- if (this.stopped) return;
1991
- if (this.fallback) {
1992
- action(this.fallback);
1993
- return;
1994
- }
1995
- void this.ready.then(() => {
1996
- var _a;
1997
- if (this.stopped) return;
1998
- const engine = (_a = this.fallback) != null ? _a : this.remote;
1999
- if (engine) return action(engine);
2000
- }).catch(this.fail);
2001
- }
2002
- fallbackCallbacks() {
2003
- return __spreadProps(__spreadValues({}, this.handlers), {
2004
- onArbMarket: (msg) => this.event("onArbMarket", [msg]),
2005
- onArbFeed: (msg) => this.event("onArbFeed", [msg])
2006
- });
2007
- }
2008
- syncFallback() {
2009
- for (const [key, unsubscribe] of this.fallbackUnsubs) {
2010
- if (!this.refs.has(key)) {
2011
- unsubscribe();
2012
- this.fallbackUnsubs.delete(key);
2013
- }
2014
- }
2015
- for (const [key, { sub }] of this.refs) {
2016
- if (this.fallbackUnsubs.has(key)) continue;
2017
- this.fallbackUnsubs.set(
2018
- key,
2019
- sub.channel === "arb" ? this.fallback.subscribeArb(sub.id, () => {
2020
- }) : sub.channel === "arb-feed" ? this.fallback.subscribeArbFeed(() => {
2021
- }) : this.fallback.subscribe(sub.id, sub.channel)
2022
- );
2023
- }
2024
- }
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
4
+ //#endregion
5
+ const require_agg_websocket = require("./agg-websocket-DJbIfxKb.js");
6
+ /**
7
+ * @license
8
+ * Copyright 2019 Google LLC
9
+ * SPDX-License-Identifier: Apache-2.0
10
+ */
11
+ //#endregion
12
+ //#region src/market-data/worker-adapter.ts
13
+ var import_comlink = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
14
+ (function(global, factory) {
15
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.Comlink = {}));
16
+ })(exports, (function(exports$1) {
17
+ "use strict";
18
+ const proxyMarker = Symbol("Comlink.proxy");
19
+ const createEndpoint = Symbol("Comlink.endpoint");
20
+ const releaseProxy = Symbol("Comlink.releaseProxy");
21
+ const finalizer = Symbol("Comlink.finalizer");
22
+ const throwMarker = Symbol("Comlink.thrown");
23
+ const isObject = (val) => typeof val === "object" && val !== null || typeof val === "function";
24
+ /**
25
+ * Allows customizing the serialization of certain values.
26
+ */
27
+ const transferHandlers = /* @__PURE__ */ new Map([["proxy", {
28
+ canHandle: (val) => isObject(val) && val[proxyMarker],
29
+ serialize(obj) {
30
+ const { port1, port2 } = new MessageChannel();
31
+ expose(obj, port1);
32
+ return [port2, [port2]];
33
+ },
34
+ deserialize(port) {
35
+ port.start();
36
+ return wrap(port);
37
+ }
38
+ }], ["throw", {
39
+ canHandle: (value) => isObject(value) && throwMarker in value,
40
+ serialize({ value }) {
41
+ let serialized;
42
+ if (value instanceof Error) serialized = {
43
+ isError: true,
44
+ value: {
45
+ message: value.message,
46
+ name: value.name,
47
+ stack: value.stack
48
+ }
49
+ };
50
+ else serialized = {
51
+ isError: false,
52
+ value
53
+ };
54
+ return [serialized, []];
55
+ },
56
+ deserialize(serialized) {
57
+ if (serialized.isError) throw Object.assign(new Error(serialized.value.message), serialized.value);
58
+ throw serialized.value;
59
+ }
60
+ }]]);
61
+ function isAllowedOrigin(allowedOrigins, origin) {
62
+ for (const allowedOrigin of allowedOrigins) {
63
+ if (origin === allowedOrigin || allowedOrigin === "*") return true;
64
+ if (allowedOrigin instanceof RegExp && allowedOrigin.test(origin)) return true;
65
+ }
66
+ return false;
67
+ }
68
+ function expose(obj, ep = globalThis, allowedOrigins = ["*"]) {
69
+ ep.addEventListener("message", function callback(ev) {
70
+ if (!ev || !ev.data) return;
71
+ if (!isAllowedOrigin(allowedOrigins, ev.origin)) {
72
+ console.warn(`Invalid origin '${ev.origin}' for comlink proxy`);
73
+ return;
74
+ }
75
+ const { id, type, path } = Object.assign({ path: [] }, ev.data);
76
+ const argumentList = (ev.data.argumentList || []).map(fromWireValue);
77
+ let returnValue;
78
+ try {
79
+ const parent = path.slice(0, -1).reduce((obj, prop) => obj[prop], obj);
80
+ const rawValue = path.reduce((obj, prop) => obj[prop], obj);
81
+ switch (type) {
82
+ case "GET":
83
+ returnValue = rawValue;
84
+ break;
85
+ case "SET":
86
+ parent[path.slice(-1)[0]] = fromWireValue(ev.data.value);
87
+ returnValue = true;
88
+ break;
89
+ case "APPLY":
90
+ returnValue = rawValue.apply(parent, argumentList);
91
+ break;
92
+ case "CONSTRUCT":
93
+ returnValue = proxy(new rawValue(...argumentList));
94
+ break;
95
+ case "ENDPOINT":
96
+ {
97
+ const { port1, port2 } = new MessageChannel();
98
+ expose(obj, port2);
99
+ returnValue = transfer(port1, [port1]);
100
+ }
101
+ break;
102
+ case "RELEASE":
103
+ returnValue = void 0;
104
+ break;
105
+ default: return;
106
+ }
107
+ } catch (value) {
108
+ returnValue = {
109
+ value,
110
+ [throwMarker]: 0
111
+ };
112
+ }
113
+ Promise.resolve(returnValue).catch((value) => {
114
+ return {
115
+ value,
116
+ [throwMarker]: 0
117
+ };
118
+ }).then((returnValue) => {
119
+ const [wireValue, transferables] = toWireValue(returnValue);
120
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
121
+ if (type === "RELEASE") {
122
+ ep.removeEventListener("message", callback);
123
+ closeEndPoint(ep);
124
+ if (finalizer in obj && typeof obj[finalizer] === "function") obj[finalizer]();
125
+ }
126
+ }).catch((error) => {
127
+ const [wireValue, transferables] = toWireValue({
128
+ value: /* @__PURE__ */ new TypeError("Unserializable return value"),
129
+ [throwMarker]: 0
130
+ });
131
+ ep.postMessage(Object.assign(Object.assign({}, wireValue), { id }), transferables);
132
+ });
133
+ });
134
+ if (ep.start) ep.start();
135
+ }
136
+ function isMessagePort(endpoint) {
137
+ return endpoint.constructor.name === "MessagePort";
138
+ }
139
+ function closeEndPoint(endpoint) {
140
+ if (isMessagePort(endpoint)) endpoint.close();
141
+ }
142
+ function wrap(ep, target) {
143
+ const pendingListeners = /* @__PURE__ */ new Map();
144
+ ep.addEventListener("message", function handleMessage(ev) {
145
+ const { data } = ev;
146
+ if (!data || !data.id) return;
147
+ const resolver = pendingListeners.get(data.id);
148
+ if (!resolver) return;
149
+ try {
150
+ resolver(data);
151
+ } finally {
152
+ pendingListeners.delete(data.id);
153
+ }
154
+ });
155
+ return createProxy(ep, pendingListeners, [], target);
156
+ }
157
+ function throwIfProxyReleased(isReleased) {
158
+ if (isReleased) throw new Error("Proxy has been released and is not useable");
159
+ }
160
+ function releaseEndpoint(ep) {
161
+ return requestResponseMessage(ep, /* @__PURE__ */ new Map(), { type: "RELEASE" }).then(() => {
162
+ closeEndPoint(ep);
163
+ });
164
+ }
165
+ const proxyCounter = /* @__PURE__ */ new WeakMap();
166
+ const proxyFinalizers = "FinalizationRegistry" in globalThis && new FinalizationRegistry((ep) => {
167
+ const newCount = (proxyCounter.get(ep) || 0) - 1;
168
+ proxyCounter.set(ep, newCount);
169
+ if (newCount === 0) releaseEndpoint(ep);
170
+ });
171
+ function registerProxy(proxy, ep) {
172
+ const newCount = (proxyCounter.get(ep) || 0) + 1;
173
+ proxyCounter.set(ep, newCount);
174
+ if (proxyFinalizers) proxyFinalizers.register(proxy, ep, proxy);
175
+ }
176
+ function unregisterProxy(proxy) {
177
+ if (proxyFinalizers) proxyFinalizers.unregister(proxy);
178
+ }
179
+ function createProxy(ep, pendingListeners, path = [], target = function() {}) {
180
+ let isProxyReleased = false;
181
+ const proxy = new Proxy(target, {
182
+ get(_target, prop) {
183
+ throwIfProxyReleased(isProxyReleased);
184
+ if (prop === releaseProxy) return () => {
185
+ unregisterProxy(proxy);
186
+ releaseEndpoint(ep);
187
+ pendingListeners.clear();
188
+ isProxyReleased = true;
189
+ };
190
+ if (prop === "then") {
191
+ if (path.length === 0) return { then: () => proxy };
192
+ const r = requestResponseMessage(ep, pendingListeners, {
193
+ type: "GET",
194
+ path: path.map((p) => p.toString())
195
+ }).then(fromWireValue);
196
+ return r.then.bind(r);
197
+ }
198
+ return createProxy(ep, pendingListeners, [...path, prop]);
199
+ },
200
+ set(_target, prop, rawValue) {
201
+ throwIfProxyReleased(isProxyReleased);
202
+ const [value, transferables] = toWireValue(rawValue);
203
+ return requestResponseMessage(ep, pendingListeners, {
204
+ type: "SET",
205
+ path: [...path, prop].map((p) => p.toString()),
206
+ value
207
+ }, transferables).then(fromWireValue);
208
+ },
209
+ apply(_target, _thisArg, rawArgumentList) {
210
+ throwIfProxyReleased(isProxyReleased);
211
+ const last = path[path.length - 1];
212
+ if (last === createEndpoint) return requestResponseMessage(ep, pendingListeners, { type: "ENDPOINT" }).then(fromWireValue);
213
+ if (last === "bind") return createProxy(ep, pendingListeners, path.slice(0, -1));
214
+ const [argumentList, transferables] = processArguments(rawArgumentList);
215
+ return requestResponseMessage(ep, pendingListeners, {
216
+ type: "APPLY",
217
+ path: path.map((p) => p.toString()),
218
+ argumentList
219
+ }, transferables).then(fromWireValue);
220
+ },
221
+ construct(_target, rawArgumentList) {
222
+ throwIfProxyReleased(isProxyReleased);
223
+ const [argumentList, transferables] = processArguments(rawArgumentList);
224
+ return requestResponseMessage(ep, pendingListeners, {
225
+ type: "CONSTRUCT",
226
+ path: path.map((p) => p.toString()),
227
+ argumentList
228
+ }, transferables).then(fromWireValue);
229
+ }
230
+ });
231
+ registerProxy(proxy, ep);
232
+ return proxy;
233
+ }
234
+ function myFlat(arr) {
235
+ return Array.prototype.concat.apply([], arr);
236
+ }
237
+ function processArguments(argumentList) {
238
+ const processed = argumentList.map(toWireValue);
239
+ return [processed.map((v) => v[0]), myFlat(processed.map((v) => v[1]))];
240
+ }
241
+ const transferCache = /* @__PURE__ */ new WeakMap();
242
+ function transfer(obj, transfers) {
243
+ transferCache.set(obj, transfers);
244
+ return obj;
245
+ }
246
+ function proxy(obj) {
247
+ return Object.assign(obj, { [proxyMarker]: true });
248
+ }
249
+ function windowEndpoint(w, context = globalThis, targetOrigin = "*") {
250
+ return {
251
+ postMessage: (msg, transferables) => w.postMessage(msg, targetOrigin, transferables),
252
+ addEventListener: context.addEventListener.bind(context),
253
+ removeEventListener: context.removeEventListener.bind(context)
254
+ };
255
+ }
256
+ function toWireValue(value) {
257
+ for (const [name, handler] of transferHandlers) if (handler.canHandle(value)) {
258
+ const [serializedValue, transferables] = handler.serialize(value);
259
+ return [{
260
+ type: "HANDLER",
261
+ name,
262
+ value: serializedValue
263
+ }, transferables];
264
+ }
265
+ return [{
266
+ type: "RAW",
267
+ value
268
+ }, transferCache.get(value) || []];
269
+ }
270
+ function fromWireValue(value) {
271
+ switch (value.type) {
272
+ case "HANDLER": return transferHandlers.get(value.name).deserialize(value.value);
273
+ case "RAW": return value.value;
274
+ }
275
+ }
276
+ function requestResponseMessage(ep, pendingListeners, msg, transfers) {
277
+ return new Promise((resolve) => {
278
+ const id = generateUUID();
279
+ pendingListeners.set(id, resolve);
280
+ if (ep.start) ep.start();
281
+ ep.postMessage(Object.assign({ id }, msg), transfers);
282
+ });
283
+ }
284
+ function generateUUID() {
285
+ return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
286
+ }
287
+ exports$1.createEndpoint = createEndpoint;
288
+ exports$1.expose = expose;
289
+ exports$1.finalizer = finalizer;
290
+ exports$1.proxy = proxy;
291
+ exports$1.proxyMarker = proxyMarker;
292
+ exports$1.releaseProxy = releaseProxy;
293
+ exports$1.transfer = transfer;
294
+ exports$1.transferHandlers = transferHandlers;
295
+ exports$1.windowEndpoint = windowEndpoint;
296
+ exports$1.wrap = wrap;
297
+ }));
298
+ })))();
299
+ var WorkerAggWebSocket = class extends require_agg_websocket.AggWebSocket {
300
+ get processesCandles() {
301
+ return !this.fallback;
302
+ }
303
+ constructor(config, factory) {
304
+ super(config);
305
+ this.config = config;
306
+ this.endpointListeners = /* @__PURE__ */ new Map();
307
+ this.historyOperations = 0;
308
+ this.currentBooks = /* @__PURE__ */ new Map();
309
+ this.recovering = /* @__PURE__ */ new Set();
310
+ this.diagnosticRevisions = /* @__PURE__ */ new Map();
311
+ this.deliveredRevisions = /* @__PURE__ */ new Map();
312
+ this.resolvedRevisions = /* @__PURE__ */ new Map();
313
+ this.refs = /* @__PURE__ */ new Map();
314
+ this.arbListeners = /* @__PURE__ */ new Map();
315
+ this.feedListeners = /* @__PURE__ */ new Set();
316
+ this.latest = /* @__PURE__ */ new Map();
317
+ this.generation = 0;
318
+ this.online = false;
319
+ this.stopped = false;
320
+ this.queued = false;
321
+ this.historyFailures = /* @__PURE__ */ new Set();
322
+ this.fallback = null;
323
+ this.fallbackUnsubs = /* @__PURE__ */ new Map();
324
+ this.historyGeneration = 0;
325
+ this.visibility = () => {
326
+ if (document.visibilityState === "visible") this.resnapshot([...this.refs.values()].filter((entry) => entry.sub.channel === "orderbook").map((entry) => entry.sub.id));
327
+ };
328
+ this.fail = () => {
329
+ if (this.stopped || this.fallback) return;
330
+ this.releaseWorker();
331
+ this.currentBooks.clear();
332
+ this.latest.clear();
333
+ this.recovering.clear();
334
+ this.diagnosticRevisions.clear();
335
+ this.deliveredRevisions.clear();
336
+ this.resolvedRevisions.clear();
337
+ this.online = false;
338
+ this.handlers.onConnectionStateChange?.(false);
339
+ this.fallback = new require_agg_websocket.AggWebSocket({
340
+ ...this.config,
341
+ callbacks: this.fallbackCallbacks()
342
+ });
343
+ for (const reject of this.historyFailures) reject(/* @__PURE__ */ new Error("Market-data worker failed"));
344
+ this.historyFailures.clear();
345
+ this.resolveFailure?.();
346
+ this.syncFallback();
347
+ };
348
+ if (config.callbacks?.onTrade && !config.callbacks.onMarketView) throw new Error("Raw trade callbacks require AggWebSocket; Worker views require onMarketView opt-in");
349
+ this.handlers = config.callbacks ?? {};
350
+ this.worker = factory();
351
+ const worker = this.worker;
352
+ const endpoint = {
353
+ postMessage: worker.postMessage.bind(worker),
354
+ addEventListener: (type, listener) => {
355
+ this.endpointListeners.set(listener, type);
356
+ worker.addEventListener(type, listener);
357
+ },
358
+ removeEventListener: (type, listener) => {
359
+ this.endpointListeners.delete(listener);
360
+ worker.removeEventListener(type, listener);
361
+ }
362
+ };
363
+ this.remote = (0, import_comlink.wrap)(endpoint);
364
+ this.worker.addEventListener("error", this.fail);
365
+ this.worker.addEventListener("messageerror", this.fail);
366
+ const { callbacks: _callbacks, ...options } = config;
367
+ const startup = this.remote.start(options, (0, import_comlink.proxy)((event) => {
368
+ if (!this.fallback) this.event(event.name, event.args, event.revision);
369
+ })).then(() => {
370
+ if (this.stopped || this.fallback || !this.remote) return;
371
+ return this.remote.observeViews((0, import_comlink.proxy)((batch) => {
372
+ if (batch.generation < this.generation || this.stopped || this.fallback) return;
373
+ for (const view of batch.views) {
374
+ if (!this.refs.has(`orderbook:${view.outcomeId}`) && !this.refs.has(`trades:${view.outcomeId}`)) continue;
375
+ if ((this.resolvedRevisions.get(view.outcomeId) ?? -1) >= view.revision) continue;
376
+ const integrity = (this.diagnosticRevisions.get(view.outcomeId) ?? -1) > view.revision ? "resyncing" : view.integrity;
377
+ this.deliveredRevisions.set(view.outcomeId, view.revision);
378
+ this.handlers.onMarketView?.({
379
+ ...view,
380
+ integrity
381
+ });
382
+ if (view.book) {
383
+ this.currentBooks.set(view.outcomeId, view.book);
384
+ if (integrity === "ok") {
385
+ this.recovering.delete(view.outcomeId);
386
+ this.diagnosticRevisions.delete(view.outcomeId);
387
+ } else this.recovering.add(view.outcomeId);
388
+ if (view.snapshot) this.handlers.onSnapshot?.(view.outcomeId, view.book);
389
+ else this.handlers.onDelta?.(view.outcomeId, view.book);
390
+ }
391
+ for (const trade of [...view.trades].reverse()) this.handlers.onTrade?.(trade);
392
+ }
393
+ }));
394
+ }).catch(this.fail);
395
+ const failed = new Promise((resolve) => {
396
+ this.resolveFailure = resolve;
397
+ });
398
+ this.ready = Promise.race([startup, failed]);
399
+ const startupTimeout = setTimeout(this.fail, 3e3);
400
+ this.ready.then(() => clearTimeout(startupTimeout));
401
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.visibility);
402
+ }
403
+ async decodeHistory(payload) {
404
+ this.historyOperations++;
405
+ try {
406
+ return await this.decodeHistoryRequest(payload);
407
+ } finally {
408
+ this.historyOperations--;
409
+ }
410
+ }
411
+ async decodeHistoryRequest(payload) {
412
+ if (this.stopped) throw new Error("Market-data worker disposed");
413
+ await this.ready;
414
+ if (this.stopped) throw new Error("Market-data worker disposed");
415
+ if (this.fallback) return this.fallback.decodeHistory(payload);
416
+ const remote = this.remote;
417
+ if (!remote) throw new Error("Market-data worker unavailable");
418
+ let rejectFailure;
419
+ const failed = new Promise((_resolve, reject) => {
420
+ rejectFailure = reject;
421
+ this.historyFailures.add(reject);
422
+ });
423
+ try {
424
+ return await Promise.race([remote.decodeHistory(payload), failed]);
425
+ } finally {
426
+ this.historyFailures.delete(rejectFailure);
427
+ }
428
+ }
429
+ async loadHistory(manifest, options) {
430
+ this.historyOperations++;
431
+ try {
432
+ return await this.loadHistoryRequest(manifest, options);
433
+ } finally {
434
+ this.historyOperations--;
435
+ }
436
+ }
437
+ async loadHistoryRequest(manifest, options) {
438
+ if (this.stopped) throw new Error("Market-data worker disposed");
439
+ if (this.fallback) return this.fallback.loadHistory(manifest, options);
440
+ const generation = ++this.historyGeneration;
441
+ const key = `${manifest.venueMarketOutcomeId}:${manifest.resolution}:${manifest.from}:${manifest.to}`;
442
+ options?.signal?.throwIfAborted();
443
+ await this.ready;
444
+ if (this.stopped) throw new Error("Market-data worker disposed");
445
+ options?.signal?.throwIfAborted();
446
+ const fallbackAfterStartup = this.fallback;
447
+ if (fallbackAfterStartup) return fallbackAfterStartup.loadHistory(manifest, options);
448
+ const remote = this.remote;
449
+ if (!remote) throw new Error("Market-data worker unavailable");
450
+ let rejectFailure;
451
+ const failed = new Promise((_resolve, reject) => {
452
+ rejectFailure = reject;
453
+ this.historyFailures.add(reject);
454
+ });
455
+ const abort = () => {
456
+ this.remote?.cancelHistoryRange(key, generation);
457
+ };
458
+ options?.signal?.addEventListener("abort", abort, { once: true });
459
+ try {
460
+ const result = await Promise.race([remote.loadImmutableRange(key, generation, manifest), failed]);
461
+ options?.signal?.throwIfAborted();
462
+ return result;
463
+ } finally {
464
+ options?.signal?.removeEventListener("abort", abort);
465
+ this.historyFailures.delete(rejectFailure);
466
+ }
467
+ }
468
+ setHostDiagnostics(provider) {
469
+ this.hostProvider = provider;
470
+ }
471
+ getDiagnostics() {
472
+ const subscriptions = [...this.refs.values()].map((entry) => entry.sub);
473
+ return this.fallback ? {
474
+ ...this.fallback.getDiagnostics(),
475
+ host: this.hostProvider?.(),
476
+ pendingHistoryRequests: this.historyOperations,
477
+ workerAttached: false,
478
+ bridgeListeners: this.endpointListeners.size
479
+ } : {
480
+ connected: this.connected,
481
+ host: this.hostProvider?.(),
482
+ transport: this.stopped ? "disposed" : "worker",
483
+ orderbookOutcomeIds: subscriptions.filter((sub) => sub.channel === "orderbook").map((sub) => sub.id),
484
+ tradeOutcomeIds: subscriptions.filter((sub) => sub.channel === "trades").map((sub) => sub.id),
485
+ arbMarketIds: [...this.arbListeners.keys()],
486
+ arbFeedSubscribers: this.feedListeners.size,
487
+ cachedBooks: this.currentBooks.size,
488
+ cachedArb: this.latest.size,
489
+ resyncingBooks: this.recovering.size,
490
+ pendingResnapshots: 0,
491
+ pendingHistoryRequests: this.historyOperations,
492
+ workerAttached: this.worker !== null,
493
+ bridgeListeners: this.endpointListeners.size
494
+ };
495
+ }
496
+ async getWorkerDiagnostics() {
497
+ await this.ready;
498
+ const remote = this.remote;
499
+ if (this.stopped || !remote || this.fallback) return null;
500
+ let rejectFailure;
501
+ const failed = new Promise((_resolve, reject) => {
502
+ rejectFailure = reject;
503
+ this.historyFailures.add(reject);
504
+ });
505
+ try {
506
+ return await Promise.race([remote.getMeasurements(), failed]);
507
+ } catch {
508
+ return null;
509
+ } finally {
510
+ this.historyFailures.delete(rejectFailure);
511
+ }
512
+ }
513
+ get connected() {
514
+ return !this.stopped && (this.fallback?.connected ?? this.online);
515
+ }
516
+ getBook(id) {
517
+ return this.fallback?.getBook(id) ?? this.currentBooks.get(id) ?? null;
518
+ }
519
+ isResyncing(id) {
520
+ return this.fallback?.isResyncing(id) ?? this.recovering.has(id);
521
+ }
522
+ getArb(id) {
523
+ return this.fallback?.getArb(id) ?? this.latest.get(id) ?? null;
524
+ }
525
+ subscribe(id, channel = "orderbook") {
526
+ return this.ref({
527
+ id,
528
+ channel
529
+ });
530
+ }
531
+ subscribeTrades(id) {
532
+ return this.subscribe(id, "trades");
533
+ }
534
+ subscribeArb(id, cb) {
535
+ const listeners = this.arbListeners.get(id) ?? /* @__PURE__ */ new Set();
536
+ listeners.add(cb);
537
+ this.arbListeners.set(id, listeners);
538
+ const unsubscribe = this.ref({
539
+ id,
540
+ channel: "arb"
541
+ });
542
+ return () => {
543
+ unsubscribe();
544
+ listeners.delete(cb);
545
+ if (!listeners.size) this.arbListeners.delete(id);
546
+ };
547
+ }
548
+ subscribeArbFeed(cb) {
549
+ this.feedListeners.add(cb);
550
+ const unsubscribe = this.ref({
551
+ id: "*",
552
+ channel: "arb-feed"
553
+ });
554
+ return () => {
555
+ unsubscribe();
556
+ this.feedListeners.delete(cb);
557
+ };
558
+ }
559
+ setCallbacks(callbacks) {
560
+ this.handlers = callbacks;
561
+ if (callbacks.onTrade && !callbacks.onMarketView && !this.fallback) this.fail();
562
+ this.fallback?.setCallbacks(this.fallbackCallbacks());
563
+ }
564
+ authenticate(token) {
565
+ this.config.initialToken = token;
566
+ this.run((engine) => engine.authenticate(token));
567
+ }
568
+ connect() {
569
+ this.run((engine) => engine.connect());
570
+ }
571
+ disconnect() {
572
+ this.run((engine) => engine.disconnect());
573
+ }
574
+ resnapshot(id) {
575
+ const ids = Array.isArray(id) ? id : [id];
576
+ this.run((engine) => engine.resnapshot(ids));
577
+ }
578
+ destroy() {
579
+ if (this.stopped) return;
580
+ this.stopped = true;
581
+ this.online = false;
582
+ this.resolveFailure?.();
583
+ for (const reject of this.historyFailures) reject(/* @__PURE__ */ new Error("Market-data worker disposed"));
584
+ this.historyFailures.clear();
585
+ this.refs.clear();
586
+ this.currentBooks.clear();
587
+ this.latest.clear();
588
+ this.arbListeners.clear();
589
+ this.feedListeners.clear();
590
+ this.recovering.clear();
591
+ this.diagnosticRevisions.clear();
592
+ this.deliveredRevisions.clear();
593
+ this.resolvedRevisions.clear();
594
+ this.fallback?.destroy();
595
+ this.fallbackUnsubs.clear();
596
+ this.hostProvider = void 0;
597
+ this.handlers = {};
598
+ if (typeof document !== "undefined") document.removeEventListener("visibilitychange", this.visibility);
599
+ this.releaseWorker();
600
+ }
601
+ releaseWorker() {
602
+ const worker = this.worker;
603
+ const remote = this.remote;
604
+ this.remote = null;
605
+ this.worker = null;
606
+ if (remote) remote[import_comlink.releaseProxy]();
607
+ if (!worker) return;
608
+ for (const [listener, type] of this.endpointListeners) worker.removeEventListener(type, listener);
609
+ this.endpointListeners.clear();
610
+ worker.removeEventListener("error", this.fail);
611
+ worker.removeEventListener("messageerror", this.fail);
612
+ worker.terminate();
613
+ }
614
+ event(name, args, revision = 0) {
615
+ if (this.stopped) return;
616
+ if (name === "onConnectionStateChange") this.online = args[0];
617
+ if (name === "onDiagnostics") {
618
+ const diagnostic = args[0];
619
+ if (diagnostic.outcomeId && revision < (this.deliveredRevisions.get(diagnostic.outcomeId) ?? -1)) return;
620
+ if (diagnostic.outcomeId && (this.refs.has(`orderbook:${diagnostic.outcomeId}`) || this.refs.has(`trades:${diagnostic.outcomeId}`)) && ["seq_gap", "checksum_mismatch"].includes(diagnostic.type)) {
621
+ this.recovering.add(diagnostic.outcomeId);
622
+ this.diagnosticRevisions.set(diagnostic.outcomeId, revision);
623
+ }
624
+ }
625
+ if (name === "onMarketResolved") {
626
+ const id = args[0].outcomeId;
627
+ if (this.refs.has(`orderbook:${id}`) || this.refs.has(`trades:${id}`)) this.resolvedRevisions.set(id, revision);
628
+ this.currentBooks.delete(id);
629
+ }
630
+ if (name === "onArbMarket") {
631
+ const msg = args[0];
632
+ this.latest.set(msg.marketId, msg);
633
+ for (const cb of this.arbListeners.get(msg.marketId) ?? []) cb(msg);
634
+ }
635
+ if (name === "onArbFeed") for (const cb of this.feedListeners) cb(args[0]);
636
+ this.handlers[name]?.(...args);
637
+ }
638
+ ref(sub) {
639
+ const key = `${sub.channel}:${sub.id}`;
640
+ const entry = this.refs.get(key) ?? {
641
+ sub,
642
+ count: 0
643
+ };
644
+ entry.count++;
645
+ this.refs.set(key, entry);
646
+ this.sync();
647
+ let released = false;
648
+ return () => {
649
+ if (released) return;
650
+ released = true;
651
+ if (--entry.count === 0) {
652
+ this.refs.delete(key);
653
+ if (sub.channel === "orderbook") this.recovering.delete(sub.id);
654
+ if (!this.refs.has(`orderbook:${sub.id}`) && !this.refs.has(`trades:${sub.id}`)) {
655
+ this.currentBooks.delete(sub.id);
656
+ this.recovering.delete(sub.id);
657
+ this.diagnosticRevisions.delete(sub.id);
658
+ this.deliveredRevisions.delete(sub.id);
659
+ this.resolvedRevisions.delete(sub.id);
660
+ }
661
+ }
662
+ this.sync();
663
+ };
664
+ }
665
+ sync() {
666
+ if (this.queued || this.stopped) return;
667
+ this.queued = true;
668
+ queueMicrotask(() => {
669
+ this.queued = false;
670
+ if (this.stopped) return;
671
+ if (this.fallback) {
672
+ this.syncFallback();
673
+ return;
674
+ }
675
+ const generation = ++this.generation;
676
+ const subscriptions = [...this.refs.values()].map((entry) => entry.sub);
677
+ this.ready.then(() => {
678
+ if (!this.stopped && !this.fallback) return this.remote?.setSubscriptions(subscriptions, generation);
679
+ }).catch(this.fail);
680
+ });
681
+ }
682
+ run(action) {
683
+ if (this.stopped) return;
684
+ if (this.fallback) {
685
+ action(this.fallback);
686
+ return;
687
+ }
688
+ this.ready.then(() => {
689
+ if (this.stopped) return;
690
+ const engine = this.fallback ?? this.remote;
691
+ if (engine) return action(engine);
692
+ }).catch(this.fail);
693
+ }
694
+ fallbackCallbacks() {
695
+ return {
696
+ ...this.handlers,
697
+ onArbMarket: (msg) => this.event("onArbMarket", [msg]),
698
+ onArbFeed: (msg) => this.event("onArbFeed", [msg])
699
+ };
700
+ }
701
+ syncFallback() {
702
+ for (const [key, unsubscribe] of this.fallbackUnsubs) if (!this.refs.has(key)) {
703
+ unsubscribe();
704
+ this.fallbackUnsubs.delete(key);
705
+ }
706
+ for (const [key, { sub }] of this.refs) {
707
+ if (this.fallbackUnsubs.has(key)) continue;
708
+ this.fallbackUnsubs.set(key, sub.channel === "arb" ? this.fallback.subscribeArb(sub.id, () => {}) : sub.channel === "arb-feed" ? this.fallback.subscribeArbFeed(() => {}) : this.fallback.subscribe(sub.id, sub.channel));
709
+ }
710
+ }
2025
711
  };
2026
712
  function createWorkerWebSocket(options, factory) {
2027
- var _a;
2028
- if (((_a = options.callbacks) == null ? void 0 : _a.onTrade) && !options.callbacks.onMarketView)
2029
- return new AggWebSocket(options);
2030
- try {
2031
- return new WorkerAggWebSocket(options, factory);
2032
- } catch (e) {
2033
- return new AggWebSocket(options);
2034
- }
2035
- }
2036
- // Annotate the CommonJS export names for ESM import in node:
2037
- 0 && (module.exports = {
2038
- WorkerAggWebSocket,
2039
- createWorkerWebSocket
2040
- });
2041
- /*! Bundled license information:
2042
-
2043
- comlink/dist/esm/comlink.mjs:
2044
- (**
2045
- * @license
2046
- * Copyright 2019 Google LLC
2047
- * SPDX-License-Identifier: Apache-2.0
2048
- *)
2049
- */
713
+ if (options.callbacks?.onTrade && !options.callbacks.onMarketView) return new require_agg_websocket.AggWebSocket(options);
714
+ try {
715
+ return new WorkerAggWebSocket(options, factory);
716
+ } catch {
717
+ return new require_agg_websocket.AggWebSocket(options);
718
+ }
719
+ }
720
+ //#endregion
721
+ exports.WorkerAggWebSocket = WorkerAggWebSocket;
722
+ exports.createWorkerWebSocket = createWorkerWebSocket;