@agg-build/sdk 4.17.4 → 4.19.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.
- package/README.md +6 -0
- package/dist/agg-websocket-CE7v1_-O.d.mts +4358 -0
- package/dist/agg-websocket-CE7v1_-O.d.ts +4358 -0
- package/dist/browser.d.mts +69 -0
- package/dist/browser.d.ts +69 -0
- package/dist/browser.js +2049 -0
- package/dist/browser.mjs +804 -0
- package/dist/chunk-QXBVA5TW.mjs +2073 -0
- package/dist/chunk-VD5UTAVD.mjs +158 -0
- package/dist/index.d.mts +439 -4244
- package/dist/index.d.ts +439 -4244
- package/dist/index.js +744 -125
- package/dist/index.mjs +283 -1763
- package/dist/market-data.d.mts +7 -0
- package/dist/market-data.d.ts +7 -0
- package/dist/market-data.js +1776 -0
- package/dist/market-data.mjs +352 -0
- package/dist/server.d.mts +16 -2
- package/dist/server.d.ts +16 -2
- package/package.json +27 -1
package/dist/browser.js
ADDED
|
@@ -0,0 +1,2049 @@
|
|
|
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
|
+
}
|
|
2025
|
+
};
|
|
2026
|
+
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
|
+
*/
|