@xapy/orderbook 0.1.24 → 0.1.25

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 (46) hide show
  1. package/README.md +2 -0
  2. package/dist/exchanges/binance/index.d.cts +1 -1
  3. package/dist/exchanges/binance/index.d.ts +1 -1
  4. package/dist/exchanges/bingx/index.d.cts +1 -1
  5. package/dist/exchanges/bingx/index.d.ts +1 -1
  6. package/dist/exchanges/bitget/index.d.cts +1 -1
  7. package/dist/exchanges/bitget/index.d.ts +1 -1
  8. package/dist/exchanges/bybit/index.d.cts +1 -1
  9. package/dist/exchanges/bybit/index.d.ts +1 -1
  10. package/dist/exchanges/coinex/index.d.cts +1 -1
  11. package/dist/exchanges/coinex/index.d.ts +1 -1
  12. package/dist/exchanges/deribit/index.d.cts +1 -1
  13. package/dist/exchanges/deribit/index.d.ts +1 -1
  14. package/dist/exchanges/edgex/index.cjs +648 -0
  15. package/dist/exchanges/edgex/index.cjs.map +1 -0
  16. package/dist/exchanges/edgex/index.d.cts +62 -0
  17. package/dist/exchanges/edgex/index.d.ts +62 -0
  18. package/dist/exchanges/edgex/index.js +642 -0
  19. package/dist/exchanges/edgex/index.js.map +1 -0
  20. package/dist/exchanges/gate/index.d.cts +1 -1
  21. package/dist/exchanges/gate/index.d.ts +1 -1
  22. package/dist/exchanges/grvt/index.d.cts +1 -1
  23. package/dist/exchanges/grvt/index.d.ts +1 -1
  24. package/dist/exchanges/huobi/index.d.cts +1 -1
  25. package/dist/exchanges/huobi/index.d.ts +1 -1
  26. package/dist/exchanges/hyperliquid/index.d.cts +1 -1
  27. package/dist/exchanges/hyperliquid/index.d.ts +1 -1
  28. package/dist/exchanges/kucoin/index.d.cts +1 -1
  29. package/dist/exchanges/kucoin/index.d.ts +1 -1
  30. package/dist/exchanges/lighter/index.cjs +664 -0
  31. package/dist/exchanges/lighter/index.cjs.map +1 -0
  32. package/dist/exchanges/lighter/index.d.cts +58 -0
  33. package/dist/exchanges/lighter/index.d.ts +58 -0
  34. package/dist/exchanges/lighter/index.js +658 -0
  35. package/dist/exchanges/lighter/index.js.map +1 -0
  36. package/dist/exchanges/okx/index.d.cts +1 -1
  37. package/dist/exchanges/okx/index.d.ts +1 -1
  38. package/dist/index.cjs +511 -3
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +4 -2
  41. package/dist/index.d.ts +4 -2
  42. package/dist/index.js +510 -4
  43. package/dist/index.js.map +1 -1
  44. package/dist/{stream-Con47OAp.d.cts → stream-CrvepB6m.d.cts} +1 -1
  45. package/dist/{stream-Con47OAp.d.ts → stream-CrvepB6m.d.ts} +1 -1
  46. package/package.json +24 -2
@@ -0,0 +1,664 @@
1
+ 'use strict';
2
+
3
+ // src/core/symbol.ts
4
+ function parseSymbol(symbol) {
5
+ const [pair, settle] = symbol.split(":");
6
+ const parts = (pair ?? "").split("/");
7
+ const base = parts[0]?.toUpperCase();
8
+ const quote = parts[1]?.toUpperCase();
9
+ if (!base || !quote) {
10
+ throw new Error(
11
+ `invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE" or "BASE/QUOTE:SETTLE"`
12
+ );
13
+ }
14
+ if (settle && settle.toUpperCase() !== quote) {
15
+ throw new Error(
16
+ `unsupported settlement currency in "${symbol}" \u2014 only linear (settle === quote) is supported`
17
+ );
18
+ }
19
+ return {
20
+ base,
21
+ quote,
22
+ market: settle ? "perpetual" : "spot",
23
+ pair: `${base}/${quote}`
24
+ };
25
+ }
26
+
27
+ // src/transport/http.ts
28
+ async function httpJson(req) {
29
+ const url = req.transformUrl ? req.transformUrl(req.url) : req.url;
30
+ const controller = new AbortController();
31
+ const timer = setTimeout(() => controller.abort(), req.timeoutMs ?? 1e4);
32
+ try {
33
+ const res = await fetch(url, {
34
+ method: req.method ?? "GET",
35
+ headers: req.headers,
36
+ body: req.body,
37
+ signal: controller.signal
38
+ });
39
+ if (!res.ok) {
40
+ const text = await res.text().catch(() => "");
41
+ throw new Error(`HTTP ${res.status} ${res.statusText}: ${text.slice(0, 200)}`);
42
+ }
43
+ return await res.json();
44
+ } finally {
45
+ clearTimeout(timer);
46
+ }
47
+ }
48
+
49
+ // src/core/errors.ts
50
+ var ExchangeError = class extends Error {
51
+ constructor(exchange, message, cause) {
52
+ super(
53
+ `[${exchange}] ${message}`,
54
+ cause === void 0 ? void 0 : { cause }
55
+ );
56
+ this.exchange = exchange;
57
+ this.name = "ExchangeError";
58
+ }
59
+ exchange;
60
+ };
61
+
62
+ // src/exchanges/lighter/markets.ts
63
+ var LIGHTER_REST = "https://mainnet.zklighter.elliot.ai";
64
+ var cache = null;
65
+ var inflight = null;
66
+ var key = (name, market) => `${market}:${name.toUpperCase()}`;
67
+ async function fetchMarkets(opts) {
68
+ const res = await httpJson({
69
+ url: `${LIGHTER_REST}/api/v1/orderBooks`,
70
+ timeoutMs: opts.timeoutMs,
71
+ transformUrl: opts.transformUrl
72
+ });
73
+ const rows = res.order_books ?? [];
74
+ if (rows.length === 0) {
75
+ throw new ExchangeError(
76
+ "lighter",
77
+ res.message ? `${res.code}: ${res.message}` : "empty orderBooks response"
78
+ );
79
+ }
80
+ const map = /* @__PURE__ */ new Map();
81
+ for (const row of rows) {
82
+ map.set(key(row.symbol, row.market_type === "spot" ? "spot" : "perpetual"), row);
83
+ }
84
+ return map;
85
+ }
86
+ function loadMarkets(opts) {
87
+ inflight ??= fetchMarkets(opts).then(
88
+ (m) => {
89
+ cache = m;
90
+ inflight = null;
91
+ return m;
92
+ },
93
+ (err) => {
94
+ inflight = null;
95
+ throw err;
96
+ }
97
+ );
98
+ return inflight;
99
+ }
100
+ async function resolveLighterMarket(name, market, opts) {
101
+ const k = key(name, market);
102
+ const hit = cache?.get(k);
103
+ const meta = hit ?? (await loadMarkets(opts)).get(k);
104
+ if (!meta) {
105
+ throw new ExchangeError(
106
+ "lighter",
107
+ `unknown ${market} market "${name}" \u2014 not listed on lighter`
108
+ );
109
+ }
110
+ if (meta.status && meta.status !== "active") {
111
+ throw new ExchangeError(
112
+ "lighter",
113
+ `market "${name}" is ${meta.status} \u2014 no book is published for it`
114
+ );
115
+ }
116
+ return meta;
117
+ }
118
+
119
+ // src/exchanges/lighter/symbols.ts
120
+ function toLighterSymbol(symbol, market) {
121
+ const [base, quote] = symbol.split("/");
122
+ if (!base || !quote) {
123
+ throw new Error(`invalid symbol "${symbol}" \u2014 expected "BASE/QUOTE"`);
124
+ }
125
+ if (quote.toUpperCase() !== "USDC") {
126
+ throw new Error(`lighter only supports USDC-quoted pairs; got "${quote}"`);
127
+ }
128
+ return market === "perpetual" ? base.toUpperCase() : `${base.toUpperCase()}/${quote.toUpperCase()}`;
129
+ }
130
+ function fromLighterSymbol(name) {
131
+ return name.includes("/") ? name.toUpperCase() : `${name.toUpperCase()}/USDC`;
132
+ }
133
+
134
+ // src/exchanges/lighter/rest.ts
135
+ var MAX_ORDERS = 250;
136
+ function usToMs(us) {
137
+ return Number.isFinite(us) && us > 0 ? Math.floor(us / 1e3) : Date.now();
138
+ }
139
+ function aggregate(orders, side, capped) {
140
+ const byPrice = /* @__PURE__ */ new Map();
141
+ for (const o of orders ?? []) {
142
+ const price = Number(o.price);
143
+ const size = Number(o.remaining_base_amount);
144
+ if (!Number.isFinite(price) || !Number.isFinite(size)) continue;
145
+ byPrice.set(price, (byPrice.get(price) ?? 0) + size);
146
+ }
147
+ const levels = [];
148
+ for (const [price, size] of byPrice) levels.push({ price, size });
149
+ levels.sort((a, b) => side === "bid" ? b.price - a.price : a.price - b.price);
150
+ if (capped) levels.pop();
151
+ return levels;
152
+ }
153
+ async function fetchLighterOrderbook(opts) {
154
+ const name = toLighterSymbol(opts.symbol, opts.market);
155
+ const meta = await resolveLighterMarket(name, opts.market, opts);
156
+ const res = await httpJson({
157
+ url: `${LIGHTER_REST}/api/v1/orderBookOrders?market_id=${meta.market_id}&limit=${MAX_ORDERS}`,
158
+ timeoutMs: opts.timeoutMs,
159
+ transformUrl: opts.transformUrl
160
+ });
161
+ if (!res.asks && !res.bids) {
162
+ throw new ExchangeError(
163
+ "lighter",
164
+ res.message ? `${res.code}: ${res.message}` : "empty orderbook response"
165
+ );
166
+ }
167
+ const depth = opts.depth ?? 50;
168
+ const bids = aggregate(res.bids, "bid", res.total_bids === MAX_ORDERS);
169
+ const asks = aggregate(res.asks, "ask", res.total_asks === MAX_ORDERS);
170
+ const timestamp = Date.now();
171
+ return {
172
+ exchange: "lighter",
173
+ symbol: fromLighterSymbol(name),
174
+ market: opts.market,
175
+ bids: bids.slice(0, depth),
176
+ asks: asks.slice(0, depth),
177
+ timestamp,
178
+ // The L3 endpoint publishes no sequence of its own — the WS `nonce` chain
179
+ // is where ordering is enforced.
180
+ sequence: timestamp
181
+ };
182
+ }
183
+
184
+ // src/core/book-merger.ts
185
+ var BookMerger = class {
186
+ bids = /* @__PURE__ */ new Map();
187
+ // price -> size
188
+ asks = /* @__PURE__ */ new Map();
189
+ sequence = -1;
190
+ timestamp = 0;
191
+ hasSnapshot = false;
192
+ apply(event) {
193
+ if (event.kind === "snapshot") {
194
+ this.bids.clear();
195
+ this.asks.clear();
196
+ for (const { price, size } of event.bids) {
197
+ if (size > 0) this.bids.set(price, size);
198
+ }
199
+ for (const { price, size } of event.asks) {
200
+ if (size > 0) this.asks.set(price, size);
201
+ }
202
+ this.sequence = event.sequence;
203
+ this.timestamp = event.timestamp;
204
+ this.hasSnapshot = true;
205
+ return this.emit();
206
+ }
207
+ if (!this.hasSnapshot) {
208
+ return { ok: false, reason: "no-snapshot" };
209
+ }
210
+ if (event.sequence <= this.sequence) {
211
+ return this.emit();
212
+ }
213
+ if (event.prevSequence !== void 0) {
214
+ if (event.prevSequence !== this.sequence) {
215
+ return {
216
+ ok: false,
217
+ reason: "gap",
218
+ expected: this.sequence,
219
+ received: event.prevSequence
220
+ };
221
+ }
222
+ } else if (event.sequence !== this.sequence + 1) {
223
+ return {
224
+ ok: false,
225
+ reason: "gap",
226
+ expected: this.sequence + 1,
227
+ received: event.sequence
228
+ };
229
+ }
230
+ for (const { price, size } of event.bids) {
231
+ if (size === 0) this.bids.delete(price);
232
+ else this.bids.set(price, size);
233
+ }
234
+ for (const { price, size } of event.asks) {
235
+ if (size === 0) this.asks.delete(price);
236
+ else this.asks.set(price, size);
237
+ }
238
+ this.sequence = event.sequence;
239
+ this.timestamp = event.timestamp;
240
+ return this.emit();
241
+ }
242
+ reset() {
243
+ this.bids.clear();
244
+ this.asks.clear();
245
+ this.sequence = -1;
246
+ this.timestamp = 0;
247
+ this.hasSnapshot = false;
248
+ }
249
+ /** Returns true once the merger has a usable book. */
250
+ isReady() {
251
+ return this.hasSnapshot;
252
+ }
253
+ emit() {
254
+ const bids = [];
255
+ for (const [price, size] of this.bids) bids.push({ price, size });
256
+ bids.sort((a, b) => b.price - a.price);
257
+ const asks = [];
258
+ for (const [price, size] of this.asks) asks.push({ price, size });
259
+ asks.sort((a, b) => a.price - b.price);
260
+ return {
261
+ ok: true,
262
+ bids,
263
+ asks,
264
+ sequence: this.sequence,
265
+ timestamp: this.timestamp
266
+ };
267
+ }
268
+ };
269
+
270
+ // src/core/event-emitter.ts
271
+ var TypedEmitter = class {
272
+ listeners = /* @__PURE__ */ new Map();
273
+ on(event, fn) {
274
+ let set = this.listeners.get(event);
275
+ if (!set) {
276
+ set = /* @__PURE__ */ new Set();
277
+ this.listeners.set(event, set);
278
+ }
279
+ set.add(fn);
280
+ return this;
281
+ }
282
+ off(event, fn) {
283
+ this.listeners.get(event)?.delete(fn);
284
+ return this;
285
+ }
286
+ emit(event, ...args) {
287
+ const set = this.listeners.get(event);
288
+ if (!set || set.size === 0) return false;
289
+ for (const fn of set) fn(...args);
290
+ return true;
291
+ }
292
+ removeAllListeners() {
293
+ this.listeners.clear();
294
+ }
295
+ };
296
+
297
+ // src/core/stream.ts
298
+ var OrderbookStream = class extends TypedEmitter {
299
+ constructor(onClose) {
300
+ super();
301
+ this.onClose = onClose;
302
+ }
303
+ onClose;
304
+ closed = false;
305
+ close() {
306
+ if (this.closed) return;
307
+ this.closed = true;
308
+ this.onClose();
309
+ this.removeAllListeners();
310
+ }
311
+ /** Yields each maintained book as it becomes available. */
312
+ async *iter() {
313
+ const queue = [];
314
+ let resolveNext = null;
315
+ let pendingError = null;
316
+ let ended = false;
317
+ const onUpdate = (b) => {
318
+ queue.push(b);
319
+ resolveNext?.();
320
+ };
321
+ const onError = (e) => {
322
+ pendingError = e;
323
+ resolveNext?.();
324
+ };
325
+ const onClose = () => {
326
+ ended = true;
327
+ resolveNext?.();
328
+ };
329
+ this.on("update", onUpdate);
330
+ this.on("error", onError);
331
+ this.on("disconnected", onClose);
332
+ try {
333
+ while (true) {
334
+ if (pendingError) throw pendingError;
335
+ const next = queue.shift();
336
+ if (next) {
337
+ yield next;
338
+ continue;
339
+ }
340
+ if (ended || this.closed) return;
341
+ await new Promise((r) => {
342
+ resolveNext = r;
343
+ });
344
+ resolveNext = null;
345
+ }
346
+ } finally {
347
+ this.off("update", onUpdate);
348
+ this.off("error", onError);
349
+ this.off("disconnected", onClose);
350
+ }
351
+ }
352
+ };
353
+
354
+ // src/core/reconnect.ts
355
+ var Backoff = class _Backoff {
356
+ attempt = 0;
357
+ opts;
358
+ constructor(opts) {
359
+ this.opts = opts;
360
+ }
361
+ static withDefaults(opts = {}) {
362
+ return new _Backoff({
363
+ initialMs: opts.initialMs ?? 500,
364
+ maxMs: opts.maxMs ?? 3e4,
365
+ factor: opts.factor ?? 2,
366
+ jitter: opts.jitter ?? 0.3,
367
+ maxAttempts: opts.maxAttempts ?? 0
368
+ });
369
+ }
370
+ next() {
371
+ if (this.opts.maxAttempts > 0 && this.attempt >= this.opts.maxAttempts) {
372
+ return null;
373
+ }
374
+ this.attempt += 1;
375
+ const base = Math.min(
376
+ this.opts.initialMs * Math.pow(this.opts.factor, this.attempt - 1),
377
+ this.opts.maxMs
378
+ );
379
+ const jitterRange = base * this.opts.jitter;
380
+ const wait = Math.max(0, base + (Math.random() * 2 - 1) * jitterRange);
381
+ return { wait, attempt: this.attempt };
382
+ }
383
+ reset() {
384
+ this.attempt = 0;
385
+ }
386
+ };
387
+ var hasNativeWebSocket = typeof globalThis.WebSocket !== "undefined";
388
+
389
+ // src/transport/ws.ts
390
+ function toError(value, fallback = "unknown error") {
391
+ if (value instanceof Error) {
392
+ return value.message ? value : new Error(`${value.name}: ${fallback}`);
393
+ }
394
+ if (typeof value === "string" && value) return new Error(value);
395
+ return new Error(fallback);
396
+ }
397
+ function normalizeWsError(ev) {
398
+ const detail = ev?.message || (ev?.error instanceof Error ? ev.error.message : void 0) || (typeof ev?.error === "string" ? ev.error : void 0);
399
+ return new Error(detail ? `WebSocket error: ${detail}` : "WebSocket error");
400
+ }
401
+ function describeClose(ev) {
402
+ if (ev?.reason) return ev.reason;
403
+ return ev?.code === void 0 ? "closed" : `closed (code ${ev.code})`;
404
+ }
405
+ var cachedCtor = null;
406
+ async function getWebSocketCtor() {
407
+ if (cachedCtor) return cachedCtor;
408
+ if (hasNativeWebSocket) {
409
+ cachedCtor = globalThis.WebSocket;
410
+ return cachedCtor;
411
+ }
412
+ try {
413
+ const mod = await import('ws');
414
+ const ctor = mod.default ?? mod.WebSocket;
415
+ if (!ctor) throw new Error("missing default export");
416
+ cachedCtor = ctor;
417
+ return cachedCtor;
418
+ } catch (err) {
419
+ throw new Error(
420
+ "WebSocket unavailable; install peer dep `ws` for Node <22. " + (err instanceof Error ? err.message : String(err))
421
+ );
422
+ }
423
+ }
424
+ var WSClient = class extends TypedEmitter {
425
+ constructor(cfg) {
426
+ super();
427
+ this.cfg = cfg;
428
+ this.backoff = Backoff.withDefaults(cfg.reconnect);
429
+ }
430
+ cfg;
431
+ ws = null;
432
+ backoff;
433
+ closed = false;
434
+ pingTimer = null;
435
+ async connect() {
436
+ if (this.closed) return;
437
+ const WS = await getWebSocketCtor();
438
+ const url = typeof this.cfg.url === "function" ? await this.cfg.url() : this.cfg.url;
439
+ const ws = new WS(url);
440
+ ws.binaryType = "arraybuffer";
441
+ this.ws = ws;
442
+ ws.onopen = async () => {
443
+ this.backoff.reset();
444
+ this.startPing();
445
+ this.emit("open");
446
+ try {
447
+ await this.cfg.onOpen?.({
448
+ send: (d) => ws.send(d),
449
+ close: () => this.close()
450
+ });
451
+ } catch (err) {
452
+ this.emit("error", toError(err, "onOpen handler failed"));
453
+ }
454
+ };
455
+ ws.onmessage = (e) => {
456
+ let result;
457
+ try {
458
+ result = this.cfg.onMessage(e.data);
459
+ } catch (err) {
460
+ this.emit("error", toError(err, "onMessage handler failed"));
461
+ return;
462
+ }
463
+ if (result && typeof result.catch === "function") {
464
+ result.catch(
465
+ (err) => this.emit("error", toError(err, "onMessage handler failed"))
466
+ );
467
+ }
468
+ };
469
+ ws.onerror = (e) => {
470
+ this.emit("error", normalizeWsError(e));
471
+ };
472
+ ws.onclose = (e) => {
473
+ this.stopPing();
474
+ const reason = describeClose(e);
475
+ this.emit("close", reason);
476
+ if (!this.closed) this.scheduleReconnect();
477
+ };
478
+ }
479
+ send(data) {
480
+ this.ws?.send(data);
481
+ }
482
+ close() {
483
+ this.closed = true;
484
+ this.stopPing();
485
+ try {
486
+ this.ws?.close();
487
+ } catch {
488
+ }
489
+ }
490
+ startPing() {
491
+ if (!this.cfg.pingIntervalMs || !this.cfg.pingPayload) return;
492
+ this.stopPing();
493
+ this.pingTimer = setInterval(() => {
494
+ try {
495
+ this.ws?.send(this.cfg.pingPayload());
496
+ } catch {
497
+ }
498
+ }, this.cfg.pingIntervalMs);
499
+ }
500
+ stopPing() {
501
+ if (this.pingTimer) {
502
+ clearInterval(this.pingTimer);
503
+ this.pingTimer = null;
504
+ }
505
+ }
506
+ scheduleReconnect() {
507
+ const next = this.backoff.next();
508
+ if (!next) {
509
+ this.emit("error", new Error("max reconnect attempts exceeded"));
510
+ return;
511
+ }
512
+ this.emit("reconnecting", next.attempt, next.wait);
513
+ setTimeout(() => {
514
+ this.connect().catch((e) => this.emit("error", toError(e, "reconnect failed")));
515
+ }, next.wait);
516
+ }
517
+ };
518
+
519
+ // src/exchanges/lighter/ws.ts
520
+ var WS_URL = "wss://mainnet.zklighter.elliot.ai/stream";
521
+ var PING_INTERVAL_MS = 6e4;
522
+ var toLevels = (rows) => (rows ?? []).map((l) => ({ price: Number(l.price), size: Number(l.size) }));
523
+ function streamLighterOrderbook(opts) {
524
+ const name = toLighterSymbol(opts.symbol, opts.market);
525
+ const symbol = fromLighterSymbol(name);
526
+ const marketId = resolveLighterMarket(name, opts.market, opts).then(
527
+ (m) => m.market_id
528
+ );
529
+ marketId.catch(() => {
530
+ });
531
+ const merger = new BookMerger();
532
+ let ws = null;
533
+ let sock = null;
534
+ let channel = null;
535
+ let recovering = false;
536
+ const stream = new OrderbookStream(() => ws?.close());
537
+ const send = (type) => {
538
+ if (channel) sock?.send(JSON.stringify({ type, channel }));
539
+ };
540
+ const emit = (r) => {
541
+ const book = {
542
+ exchange: "lighter",
543
+ symbol,
544
+ market: opts.market,
545
+ bids: r.bids,
546
+ asks: r.asks,
547
+ timestamp: r.timestamp,
548
+ sequence: r.sequence
549
+ };
550
+ stream.emit("update", book);
551
+ };
552
+ const resync = () => {
553
+ if (recovering) return;
554
+ recovering = true;
555
+ merger.reset();
556
+ send("unsubscribe");
557
+ send("subscribe");
558
+ };
559
+ const buildEvent = (msg, snapshot) => {
560
+ const ob = msg.order_book ?? {};
561
+ const bids = toLevels(ob.bids);
562
+ const asks = toLevels(ob.asks);
563
+ const timestamp = msg.timestamp ?? usToMs(ob.last_updated_at);
564
+ const sequence = Number(ob.nonce ?? 0);
565
+ return snapshot ? { kind: "snapshot", bids, asks, sequence, timestamp } : {
566
+ kind: "delta",
567
+ bids,
568
+ asks,
569
+ sequence,
570
+ prevSequence: Number(ob.begin_nonce ?? 0),
571
+ timestamp
572
+ };
573
+ };
574
+ const handleBook = (msg, snapshot) => {
575
+ if (snapshot) recovering = false;
576
+ else if (recovering) return;
577
+ const r = merger.apply(buildEvent(msg, snapshot));
578
+ if (r.ok) {
579
+ emit(r);
580
+ } else if (r.reason === "gap" || r.reason === "no-snapshot") {
581
+ resync();
582
+ }
583
+ };
584
+ const onMessage = (raw) => {
585
+ if (typeof raw !== "string") return;
586
+ let msg;
587
+ try {
588
+ msg = JSON.parse(raw);
589
+ } catch {
590
+ return;
591
+ }
592
+ if (msg.error) {
593
+ stream.emit(
594
+ "error",
595
+ new ExchangeError("lighter", `${msg.error.code}: ${msg.error.message}`)
596
+ );
597
+ return;
598
+ }
599
+ if (!msg.order_book) return;
600
+ if (msg.channel && channel && msg.channel !== channel.replace("/", ":")) {
601
+ return;
602
+ }
603
+ if (msg.type === "subscribed/order_book") handleBook(msg, true);
604
+ else if (msg.type === "update/order_book") handleBook(msg, false);
605
+ };
606
+ ws = new WSClient({
607
+ url: WS_URL,
608
+ onOpen: async (handle) => {
609
+ sock = handle;
610
+ merger.reset();
611
+ recovering = false;
612
+ channel = `order_book/${await marketId}`;
613
+ send("subscribe");
614
+ },
615
+ onMessage,
616
+ pingIntervalMs: PING_INTERVAL_MS,
617
+ pingPayload: () => JSON.stringify({ type: "ping" })
618
+ });
619
+ ws.on("open", () => stream.emit("connected"));
620
+ ws.on("close", (r) => stream.emit("disconnected", r));
621
+ ws.on("reconnecting", (a, w) => stream.emit("reconnecting", a, w));
622
+ ws.on("error", (e) => stream.emit("error", e));
623
+ ws.connect().catch((e) => stream.emit("error", e));
624
+ return stream;
625
+ }
626
+
627
+ // src/exchanges/lighter/index.ts
628
+ var LighterClient = class {
629
+ exchange = "lighter";
630
+ transformUrl;
631
+ timeoutMs;
632
+ constructor(opts = {}) {
633
+ this.transformUrl = opts.transformUrl;
634
+ this.timeoutMs = opts.timeoutMs;
635
+ }
636
+ fetchOrderbook(symbol, opts = {}) {
637
+ const { pair, market } = parseSymbol(symbol);
638
+ return fetchLighterOrderbook({
639
+ symbol: pair,
640
+ market,
641
+ depth: opts.depth,
642
+ timeoutMs: this.timeoutMs,
643
+ transformUrl: this.transformUrl
644
+ });
645
+ }
646
+ streamOrderbook(symbol, opts = {}) {
647
+ const { pair, market } = parseSymbol(symbol);
648
+ return streamLighterOrderbook({
649
+ symbol: pair,
650
+ market,
651
+ depth: opts.depth,
652
+ transformUrl: this.transformUrl,
653
+ timeoutMs: this.timeoutMs
654
+ });
655
+ }
656
+ };
657
+
658
+ exports.LighterClient = LighterClient;
659
+ exports.fetchLighterOrderbook = fetchLighterOrderbook;
660
+ exports.fromLighterSymbol = fromLighterSymbol;
661
+ exports.streamLighterOrderbook = streamLighterOrderbook;
662
+ exports.toLighterSymbol = toLighterSymbol;
663
+ //# sourceMappingURL=index.cjs.map
664
+ //# sourceMappingURL=index.cjs.map