@stxapp/stx-typescript 0.9.0 → 0.10.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/CHANGELOG.md +23 -0
- package/dist/{chunk-R77AZ5UH.cjs → chunk-42OCIF3G.cjs} +193 -164
- package/dist/chunk-42OCIF3G.cjs.map +1 -0
- package/dist/{chunk-46XK6VDD.js → chunk-FTZCBXT7.js} +179 -150
- package/dist/chunk-FTZCBXT7.js.map +1 -0
- package/dist/{client-B-MMKiRt.d.ts → client-DJr0UUvB.d.cts} +51 -130
- package/dist/{client-B-MMKiRt.d.cts → client-DJr0UUvB.d.ts} +51 -130
- package/dist/index.cjs +2 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -5
- package/dist/oauth.cjs +30 -30
- package/dist/oauth.d.cts +2 -2
- package/dist/oauth.d.ts +2 -2
- package/dist/oauth.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-46XK6VDD.js.map +0 -1
- package/dist/chunk-R77AZ5UH.cjs.map +0 -1
|
@@ -1,28 +1,3 @@
|
|
|
1
|
-
// src/geo.ts
|
|
2
|
-
var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
|
|
3
|
-
function geoRejection(message) {
|
|
4
|
-
const ip = IP_NOT_ALLOWED.exec(message);
|
|
5
|
-
if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
|
|
6
|
-
if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
|
|
7
|
-
return { reason: "packet_other_user" };
|
|
8
|
-
}
|
|
9
|
-
if (/IP address doesn't match geo location/i.test(message)) {
|
|
10
|
-
return { reason: "packet_ip_mismatch" };
|
|
11
|
-
}
|
|
12
|
-
if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
|
|
13
|
-
return { reason: "packet_invalid" };
|
|
14
|
-
}
|
|
15
|
-
if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
|
|
16
|
-
return { reason: "location_not_allowed" };
|
|
17
|
-
}
|
|
18
|
-
return void 0;
|
|
19
|
-
}
|
|
20
|
-
async function resolveGeoLocation(provider) {
|
|
21
|
-
if (provider === void 0 || provider === null) return void 0;
|
|
22
|
-
const value = typeof provider === "function" ? await provider() : provider;
|
|
23
|
-
return value === null || value === void 0 || value === "" ? void 0 : value;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
1
|
// src/exceptions.ts
|
|
27
2
|
var STXException = class extends Error {
|
|
28
3
|
statusCode;
|
|
@@ -72,15 +47,6 @@ var STXNotFoundException = class extends STXAPIException {
|
|
|
72
47
|
};
|
|
73
48
|
var STXRejectedException = class extends STXAPIException {
|
|
74
49
|
};
|
|
75
|
-
var STXGeoLocationException = class extends STXRejectedException {
|
|
76
|
-
reason;
|
|
77
|
-
ipAddress;
|
|
78
|
-
constructor(message, rejection, opts = {}) {
|
|
79
|
-
super(message, opts);
|
|
80
|
-
this.reason = rejection.reason;
|
|
81
|
-
this.ipAddress = rejection.ipAddress;
|
|
82
|
-
}
|
|
83
|
-
};
|
|
84
50
|
var STXRateLimitException = class extends STXAPIException {
|
|
85
51
|
retryAfter;
|
|
86
52
|
constructor(message, opts = {}) {
|
|
@@ -125,6 +91,7 @@ var FEATURE_PHRASES = {
|
|
|
125
91
|
market_types: "Market types are",
|
|
126
92
|
event_players: "Event players are",
|
|
127
93
|
leaderboard: "The leaderboard is",
|
|
94
|
+
loyalty: "The loyalty program is",
|
|
128
95
|
combos: "Combos are"
|
|
129
96
|
};
|
|
130
97
|
function notAvailableMessage(feature, host) {
|
|
@@ -231,10 +198,8 @@ function errorForStatus(statusCode, body, opts) {
|
|
|
231
198
|
}
|
|
232
199
|
case 404:
|
|
233
200
|
return new STXNotFoundException(message, base);
|
|
234
|
-
case 422:
|
|
235
|
-
|
|
236
|
-
return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
|
|
237
|
-
}
|
|
201
|
+
case 422:
|
|
202
|
+
return new STXRejectedException(message, base);
|
|
238
203
|
case 429:
|
|
239
204
|
return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
|
|
240
205
|
default:
|
|
@@ -270,6 +235,7 @@ var FEATURES = [
|
|
|
270
235
|
"market_types",
|
|
271
236
|
"event_players",
|
|
272
237
|
"leaderboard",
|
|
238
|
+
"loyalty",
|
|
273
239
|
"combos"
|
|
274
240
|
];
|
|
275
241
|
var MEMBER_SCOPES = [
|
|
@@ -351,12 +317,13 @@ function oauthMetadataFrom(answer) {
|
|
|
351
317
|
}
|
|
352
318
|
async function discoverCapabilities(probes) {
|
|
353
319
|
const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
|
|
354
|
-
const [version, discovery, types, players, board, combos] = await Promise.all([
|
|
320
|
+
const [version, discovery, types, players, board, loyalty, combos] = await Promise.all([
|
|
355
321
|
swallow(probes.get("/api_version")),
|
|
356
322
|
swallow(probes.get("/.well-known/oauth-authorization-server")),
|
|
357
323
|
swallow(probes.signedGet("/api/v1/types")),
|
|
358
324
|
swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
|
|
359
325
|
swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
|
|
326
|
+
swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
|
|
360
327
|
swallow(probes.joinReason(`rfq:${NOBODY}`))
|
|
361
328
|
]);
|
|
362
329
|
const apiVersion = json(version)?.api_version;
|
|
@@ -379,6 +346,8 @@ async function discoverCapabilities(probes) {
|
|
|
379
346
|
event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
|
|
380
347
|
// Switched off answers 404 too ("Leaderboard is not enabled").
|
|
381
348
|
leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
|
|
349
|
+
// Switched off answers 404 ("Loyalty program is not enabled").
|
|
350
|
+
loyalty: loyalty === null ? null : loyalty.status >= 200 && loyalty.status < 300 ? true : loyalty.status === 404 ? false : null,
|
|
382
351
|
combos: combos === null ? null : combos !== "unmatched topic"
|
|
383
352
|
};
|
|
384
353
|
return new Capabilities({
|
|
@@ -1209,7 +1178,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
|
|
|
1209
1178
|
}
|
|
1210
1179
|
|
|
1211
1180
|
// src/version.ts
|
|
1212
|
-
var VERSION = "0.
|
|
1181
|
+
var VERSION = "0.10.0";
|
|
1213
1182
|
var USER_AGENT = `stx-typescript/${VERSION}`;
|
|
1214
1183
|
var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
|
|
1215
1184
|
|
|
@@ -1457,10 +1426,6 @@ function comboJoinError(err, host = "") {
|
|
|
1457
1426
|
}
|
|
1458
1427
|
return err;
|
|
1459
1428
|
}
|
|
1460
|
-
async function comboJoinPayload(geo) {
|
|
1461
|
-
const packet = await resolveGeoLocation(geo);
|
|
1462
|
-
return packet === void 0 ? {} : { geo_location: packet };
|
|
1463
|
-
}
|
|
1464
1429
|
function money(name, value) {
|
|
1465
1430
|
if (typeof value !== "string") {
|
|
1466
1431
|
throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
|
|
@@ -1484,10 +1449,6 @@ var ComboSession = class {
|
|
|
1484
1449
|
get externalId() {
|
|
1485
1450
|
return this.channel.reply.external_id ?? "";
|
|
1486
1451
|
}
|
|
1487
|
-
/** When the geolocation packet this join used expires (ISO 8601), or null. Rejoin before it. */
|
|
1488
|
-
get nextGeolocationAt() {
|
|
1489
|
-
return this.channel.reply.next_geolocation_at ?? null;
|
|
1490
|
-
}
|
|
1491
1452
|
/** @internal */
|
|
1492
1453
|
_typed(msg) {
|
|
1493
1454
|
if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
|
|
@@ -1952,9 +1913,13 @@ var GATED_OPERATIONS = {
|
|
|
1952
1913
|
markets_post: "markets.create",
|
|
1953
1914
|
leaderboard_get: "leaderboard",
|
|
1954
1915
|
leaderboard_me_get: "leaderboard",
|
|
1955
|
-
me_profile_patch: "leaderboard"
|
|
1916
|
+
me_profile_patch: "leaderboard",
|
|
1917
|
+
portfolio_loyalty_get: "loyalty"
|
|
1918
|
+
};
|
|
1919
|
+
var SWITCHED_OFF = {
|
|
1920
|
+
leaderboard: "Leaderboard is not enabled",
|
|
1921
|
+
loyalty: "Loyalty program is not enabled"
|
|
1956
1922
|
};
|
|
1957
|
-
var LEADERBOARD_OFF = "Leaderboard is not enabled";
|
|
1958
1923
|
var STX = class _STX {
|
|
1959
1924
|
baseUrl;
|
|
1960
1925
|
socketUrl;
|
|
@@ -1966,7 +1931,6 @@ var STX = class _STX {
|
|
|
1966
1931
|
verifyTls;
|
|
1967
1932
|
retry;
|
|
1968
1933
|
timeoutMs;
|
|
1969
|
-
geoLocation;
|
|
1970
1934
|
onResponse;
|
|
1971
1935
|
#fetch;
|
|
1972
1936
|
#me;
|
|
@@ -2008,7 +1972,6 @@ var STX = class _STX {
|
|
|
2008
1972
|
this.verifyTls = settings.verifyTls;
|
|
2009
1973
|
this.retry = opts.retry ?? new RetryPolicy();
|
|
2010
1974
|
this.timeoutMs = opts.timeoutMs ?? 3e4;
|
|
2011
|
-
this.geoLocation = opts.geoLocation;
|
|
2012
1975
|
this.onResponse = opts.onResponse;
|
|
2013
1976
|
const fetchImpl = opts.fetch ?? globalThis.fetch;
|
|
2014
1977
|
if (typeof fetchImpl !== "function") {
|
|
@@ -2194,7 +2157,7 @@ var STX = class _STX {
|
|
|
2194
2157
|
return await this.#send(buildRequest(operationId, args));
|
|
2195
2158
|
} catch (err) {
|
|
2196
2159
|
const feature = GATED_OPERATIONS[operationId];
|
|
2197
|
-
const off = feature
|
|
2160
|
+
const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && err.body?.error === SWITCHED_OFF[feature];
|
|
2198
2161
|
if (feature && (isMissingRoute(err) || off)) {
|
|
2199
2162
|
throw new STXNotAvailableException(feature, this.host, {
|
|
2200
2163
|
statusCode: err.statusCode,
|
|
@@ -2229,10 +2192,6 @@ var STX = class _STX {
|
|
|
2229
2192
|
q.cursor = page.cursor;
|
|
2230
2193
|
}
|
|
2231
2194
|
}
|
|
2232
|
-
async #geoBody(body, opts) {
|
|
2233
|
-
const packet = opts?.geoLocation !== void 0 ? opts.geoLocation ?? void 0 : await resolveGeoLocation(this.geoLocation);
|
|
2234
|
-
return packet === void 0 ? body : { ...body, geo_location: packet };
|
|
2235
|
-
}
|
|
2236
2195
|
// ------------------------------------------------------------------
|
|
2237
2196
|
// Identity
|
|
2238
2197
|
// ------------------------------------------------------------------
|
|
@@ -2431,83 +2390,41 @@ var STX = class _STX {
|
|
|
2431
2390
|
*
|
|
2432
2391
|
* The exchange validates the order: a bad price step or a fractional
|
|
2433
2392
|
* quantity throws `STXValidationException` (400) or `STXRejectedException`
|
|
2434
|
-
* (422) with the API's message
|
|
2435
|
-
* `
|
|
2393
|
+
* (422) with the API's message. An order from outside the region is also
|
|
2394
|
+
* an `STXRejectedException`.
|
|
2436
2395
|
*
|
|
2437
2396
|
* A POST is never retried after a 5xx or a dropped connection; pass
|
|
2438
2397
|
* `clientOrderId` so you can look the order up if that happens.
|
|
2439
2398
|
*/
|
|
2440
2399
|
async placeOrder(marketId, action, orderType, opts) {
|
|
2441
|
-
const
|
|
2442
|
-
|
|
2443
|
-
return this.#one("orders_post", { body: await this.#geoBody(body, { geoLocation }) });
|
|
2400
|
+
const body = orderBody(marketId, action, orderType, opts ?? {});
|
|
2401
|
+
return this.#one("orders_post", { body });
|
|
2444
2402
|
}
|
|
2445
2403
|
/**
|
|
2446
|
-
* `POST /api/v1/orders/batched`: place several orders in one call.
|
|
2447
|
-
*
|
|
2448
|
-
*
|
|
2449
|
-
* others.
|
|
2404
|
+
* `POST /api/v1/orders/batched`: place several orders in one call. Returns
|
|
2405
|
+
* one result per order, in order; a rejected order has `errors` instead of
|
|
2406
|
+
* `order` and does not stop the others.
|
|
2450
2407
|
*/
|
|
2451
|
-
async placeOrders(orders
|
|
2408
|
+
async placeOrders(orders) {
|
|
2452
2409
|
const body = { orders: orders.map(normalizeOrder) };
|
|
2453
|
-
const raw = await this.#list("orders_batched_post", { body
|
|
2410
|
+
const raw = await this.#list("orders_batched_post", { body });
|
|
2454
2411
|
return raw.map(toBatchOrderResult);
|
|
2455
2412
|
}
|
|
2456
2413
|
/**
|
|
2457
2414
|
* `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
|
|
2458
2415
|
* request: a fill already in flight can still land.
|
|
2459
2416
|
*/
|
|
2460
|
-
async cancelOrder(orderId
|
|
2461
|
-
|
|
2462
|
-
return this.#one("orders__order_id_delete", {
|
|
2463
|
-
pathParams: { order_id: orderId },
|
|
2464
|
-
body: "geo_location" in geo ? geo : void 0
|
|
2465
|
-
});
|
|
2417
|
+
async cancelOrder(orderId) {
|
|
2418
|
+
return this.#one("orders__order_id_delete", { pathParams: { order_id: orderId } });
|
|
2466
2419
|
}
|
|
2467
2420
|
/** `DELETE /api/v1/orders/batched`: cancel the named orders. */
|
|
2468
|
-
async cancelOrders(orderIds
|
|
2421
|
+
async cancelOrders(orderIds) {
|
|
2469
2422
|
const body = { orders: orderIds.map((id) => ({ order_id: id })) };
|
|
2470
|
-
return this.#list("orders_batched_delete", { body
|
|
2423
|
+
return this.#list("orders_batched_delete", { body });
|
|
2471
2424
|
}
|
|
2472
2425
|
/** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
|
|
2473
|
-
async cancelAllOrders(
|
|
2474
|
-
|
|
2475
|
-
return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
|
|
2476
|
-
}
|
|
2477
|
-
// ------------------------------------------------------------------
|
|
2478
|
-
// Geo-fencing
|
|
2479
|
-
// ------------------------------------------------------------------
|
|
2480
|
-
/**
|
|
2481
|
-
* Ask the exchange whether this machine may trade right now, without
|
|
2482
|
-
* placing or cancelling anything.
|
|
2483
|
-
*
|
|
2484
|
-
* Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
|
|
2485
|
-
* order id that cannot exist) with the geolocation packet, if one is
|
|
2486
|
-
* configured. The exchange runs its geo check before it looks the order
|
|
2487
|
-
* up, so a 404 means the check passed, and a geo 422 means it did not. On
|
|
2488
|
-
* an exchange without geo-fencing it always passes.
|
|
2489
|
-
*
|
|
2490
|
-
* Needs a `read_write` key (the probe is a write route). The exchange
|
|
2491
|
-
* records a failed check in its geolocation log exactly as it would a real
|
|
2492
|
-
* order from the same place, and may raise a compliance alert, so call it
|
|
2493
|
-
* once at start-up, not in a loop.
|
|
2494
|
-
*/
|
|
2495
|
-
async geoCheck(opts) {
|
|
2496
|
-
const geo = await this.#geoBody({}, opts);
|
|
2497
|
-
const sentPacket = "geo_location" in geo;
|
|
2498
|
-
try {
|
|
2499
|
-
await this.#one("orders__order_id_delete", {
|
|
2500
|
-
pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
|
|
2501
|
-
body: sentPacket ? geo : void 0
|
|
2502
|
-
});
|
|
2503
|
-
return { allowed: true, sentPacket };
|
|
2504
|
-
} catch (err) {
|
|
2505
|
-
if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
|
|
2506
|
-
if (err instanceof STXGeoLocationException) {
|
|
2507
|
-
return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
|
|
2508
|
-
}
|
|
2509
|
-
throw err;
|
|
2510
|
-
}
|
|
2426
|
+
async cancelAllOrders() {
|
|
2427
|
+
return this.#list("orders_all_delete");
|
|
2511
2428
|
}
|
|
2512
2429
|
// ------------------------------------------------------------------
|
|
2513
2430
|
// Fills, positions, balance
|
|
@@ -2613,11 +2530,15 @@ var STX = class _STX {
|
|
|
2613
2530
|
iterFees(query = {}) {
|
|
2614
2531
|
return this.#iterate("portfolio_fees_get", { limit: query.limit });
|
|
2615
2532
|
}
|
|
2616
|
-
/**
|
|
2533
|
+
/**
|
|
2534
|
+
* `GET /api/v1/portfolio/loyalty`: loyalty entries. Throws
|
|
2535
|
+
* `STXNotAvailableException` (feature `loyalty`) where the exchange has the
|
|
2536
|
+
* loyalty program switched off.
|
|
2537
|
+
*/
|
|
2617
2538
|
loyalty(query = {}) {
|
|
2618
2539
|
return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
|
|
2619
2540
|
}
|
|
2620
|
-
/** Every loyalty entry, following the cursor. */
|
|
2541
|
+
/** Every loyalty entry, following the cursor. Throws like `loyalty()`. */
|
|
2621
2542
|
iterLoyalty(query = {}) {
|
|
2622
2543
|
return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
|
|
2623
2544
|
}
|
|
@@ -2752,6 +2673,12 @@ var MessageQueue = class {
|
|
|
2752
2673
|
this.#items.push(msg);
|
|
2753
2674
|
return dropped;
|
|
2754
2675
|
}
|
|
2676
|
+
/** Queue the end marker behind everything already queued, dropping nothing. */
|
|
2677
|
+
end() {
|
|
2678
|
+
const waiter = this.#waiters.shift();
|
|
2679
|
+
if (waiter) waiter(null);
|
|
2680
|
+
else this.#items.push(null);
|
|
2681
|
+
}
|
|
2755
2682
|
get(timeoutMs) {
|
|
2756
2683
|
if (this.#items.length) return Promise.resolve(this.#items.shift());
|
|
2757
2684
|
return new Promise((resolve, reject) => {
|
|
@@ -2789,12 +2716,23 @@ var Channel = class {
|
|
|
2789
2716
|
joinRef = null;
|
|
2790
2717
|
joined = false;
|
|
2791
2718
|
closed = false;
|
|
2792
|
-
/** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
|
|
2793
|
-
_beforeJoin;
|
|
2794
2719
|
#ws;
|
|
2795
2720
|
#queue;
|
|
2796
2721
|
#snapshotWaiters = [];
|
|
2797
2722
|
#pingTimer;
|
|
2723
|
+
/** @internal Milliseconds between pings while joined; null when none are sent. */
|
|
2724
|
+
_pingEveryMs = null;
|
|
2725
|
+
// One phx_join per topic per connection (Phoenix answers a second join of a
|
|
2726
|
+
// joined topic by closing the first): joins run one after another, and a
|
|
2727
|
+
// join already made on the current connection is not repeated.
|
|
2728
|
+
/** @internal */
|
|
2729
|
+
_joinTail = Promise.resolve();
|
|
2730
|
+
/** @internal */
|
|
2731
|
+
_joinedConnection = 0;
|
|
2732
|
+
/** @internal The connection whose join also restored watches and the pinger. */
|
|
2733
|
+
_restoredConnection = 0;
|
|
2734
|
+
/** @internal A phx_close/phx_error for the join in flight. */
|
|
2735
|
+
_endedJoin = null;
|
|
2798
2736
|
constructor(ws, topic, joinPayload, onMessage, opts) {
|
|
2799
2737
|
this.#ws = ws;
|
|
2800
2738
|
this.topic = topic;
|
|
@@ -2962,9 +2900,10 @@ var Channel = class {
|
|
|
2962
2900
|
let interval = this.pingIntervalMs;
|
|
2963
2901
|
const granted = this.reply?.ping_timeout;
|
|
2964
2902
|
if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
|
|
2965
|
-
const cod = granted
|
|
2903
|
+
const cod = granted / 3;
|
|
2966
2904
|
interval = interval === null ? cod : Math.min(interval, cod);
|
|
2967
2905
|
}
|
|
2906
|
+
this._pingEveryMs = interval || null;
|
|
2968
2907
|
if (interval) {
|
|
2969
2908
|
const every = interval;
|
|
2970
2909
|
this.#pingTimer = setInterval(() => {
|
|
@@ -2984,9 +2923,17 @@ var Channel = class {
|
|
|
2984
2923
|
/** @internal */
|
|
2985
2924
|
_resetForRejoin() {
|
|
2986
2925
|
this.joined = false;
|
|
2926
|
+
this._restoredConnection = 0;
|
|
2987
2927
|
this.snapshots = {};
|
|
2988
2928
|
this._stopPinger();
|
|
2989
2929
|
}
|
|
2930
|
+
/** @internal End the channel after every queued message is read. */
|
|
2931
|
+
_finish() {
|
|
2932
|
+
this.closed = true;
|
|
2933
|
+
this.joined = false;
|
|
2934
|
+
this._stopPinger();
|
|
2935
|
+
this.#queue.end();
|
|
2936
|
+
}
|
|
2990
2937
|
/** @internal */
|
|
2991
2938
|
_close() {
|
|
2992
2939
|
this.closed = true;
|
|
@@ -3020,15 +2967,19 @@ var STXWebSocket = class {
|
|
|
3020
2967
|
channels = /* @__PURE__ */ new Map();
|
|
3021
2968
|
/** Successful reconnects so far. */
|
|
3022
2969
|
reconnects = 0;
|
|
2970
|
+
/** Channels rejoined after the server closed or errored them while the socket stayed up. */
|
|
2971
|
+
channelRejoins = 0;
|
|
3023
2972
|
#userId;
|
|
3024
2973
|
#conn;
|
|
3025
2974
|
#ref = 0;
|
|
2975
|
+
#connection = 0;
|
|
3026
2976
|
#pending = /* @__PURE__ */ new Map();
|
|
3027
2977
|
#heartbeat;
|
|
3028
2978
|
#pendingHeartbeat = null;
|
|
3029
2979
|
#closed = false;
|
|
3030
2980
|
#connecting;
|
|
3031
2981
|
#reconnecting = false;
|
|
2982
|
+
#reconnectDone = Promise.resolve();
|
|
3032
2983
|
#closedWaiters = [];
|
|
3033
2984
|
// Frames are handled one at a time, in arrival order: each waits for the
|
|
3034
2985
|
// previous one's handler to finish.
|
|
@@ -3078,6 +3029,11 @@ var STXWebSocket = class {
|
|
|
3078
3029
|
async connect() {
|
|
3079
3030
|
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
3080
3031
|
if (this.connected) return this;
|
|
3032
|
+
while (this.#reconnecting) {
|
|
3033
|
+
await this.#reconnectDone;
|
|
3034
|
+
if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
|
|
3035
|
+
if (this.connected) return this;
|
|
3036
|
+
}
|
|
3081
3037
|
if (!this.#connecting) {
|
|
3082
3038
|
this.#connecting = this.#openAuthenticated().finally(() => {
|
|
3083
3039
|
this.#connecting = void 0;
|
|
@@ -3197,7 +3153,7 @@ var STXWebSocket = class {
|
|
|
3197
3153
|
* `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
|
|
3198
3154
|
* with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
|
|
3199
3155
|
* clamped by the server to 5000 to 20000; the granted value is in
|
|
3200
|
-
* `channel.reply.ping_timeout` and the SDK pings at
|
|
3156
|
+
* `channel.reply.ping_timeout` and the SDK pings at a third of it for as long
|
|
3201
3157
|
* as the channel is joined.
|
|
3202
3158
|
*/
|
|
3203
3159
|
orders(opts = {}) {
|
|
@@ -3252,7 +3208,6 @@ var STXWebSocket = class {
|
|
|
3252
3208
|
* Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
|
|
3253
3209
|
* combination, cash one out, accept, cancel and read a request.
|
|
3254
3210
|
*
|
|
3255
|
-
* Available on US demo.
|
|
3256
3211
|
* Where combos are not available, rejects with
|
|
3257
3212
|
* `STXCombosUnavailableException`. Other join refusals (a read-only key, an
|
|
3258
3213
|
* account that may not trade) reject with `STXComboRefusedException`.
|
|
@@ -3272,7 +3227,6 @@ var STXWebSocket = class {
|
|
|
3272
3227
|
* Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
|
|
3273
3228
|
* request opened from now on (`rfq_opened`), quote and withdraw quotes.
|
|
3274
3229
|
*
|
|
3275
|
-
* Available on US demo.
|
|
3276
3230
|
* Where combos are not available, rejects with
|
|
3277
3231
|
* `STXCombosUnavailableException`.
|
|
3278
3232
|
*/
|
|
@@ -3288,19 +3242,11 @@ var STXWebSocket = class {
|
|
|
3288
3242
|
return maker;
|
|
3289
3243
|
}
|
|
3290
3244
|
async #joinCombo(name, opts, onMessage) {
|
|
3291
|
-
let channel;
|
|
3292
3245
|
try {
|
|
3293
|
-
|
|
3246
|
+
return await this.#joinAccount(name, {}, onMessage);
|
|
3294
3247
|
} catch (err) {
|
|
3295
3248
|
throw comboJoinError(err, new URL(this.rest.baseUrl).host);
|
|
3296
3249
|
}
|
|
3297
|
-
if (typeof opts.geoLocation === "function") {
|
|
3298
|
-
const geo = opts.geoLocation;
|
|
3299
|
-
channel._beforeJoin = async () => {
|
|
3300
|
-
channel.joinPayload = await comboJoinPayload(geo);
|
|
3301
|
-
};
|
|
3302
|
-
}
|
|
3303
|
-
return channel;
|
|
3304
3250
|
}
|
|
3305
3251
|
// ------------------------------------------------------------------
|
|
3306
3252
|
// Generic join
|
|
@@ -3311,9 +3257,13 @@ var STXWebSocket = class {
|
|
|
3311
3257
|
* `market_ids_required` or `unauthorized`) if the join is refused.
|
|
3312
3258
|
*/
|
|
3313
3259
|
async join(topic, payload = {}, onMessage, opts = {}) {
|
|
3314
|
-
const
|
|
3315
|
-
|
|
3260
|
+
const already = () => {
|
|
3261
|
+
const existing = this.channels.get(topic);
|
|
3262
|
+
if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
|
|
3263
|
+
};
|
|
3264
|
+
already();
|
|
3316
3265
|
await this.connect();
|
|
3266
|
+
already();
|
|
3317
3267
|
const name = topic.split(":", 1)[0];
|
|
3318
3268
|
const channel = new Channel(this, topic, payload, onMessage, {
|
|
3319
3269
|
pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
|
|
@@ -3337,17 +3287,56 @@ var STXWebSocket = class {
|
|
|
3337
3287
|
}
|
|
3338
3288
|
return this.join(`${name}:${await this.userId()}`, payload, onMessage);
|
|
3339
3289
|
}
|
|
3340
|
-
|
|
3290
|
+
/**
|
|
3291
|
+
* Join `channel` on the current connection unless it already is, then
|
|
3292
|
+
* restore its watches and pinger; resolves to whether anything was done.
|
|
3293
|
+
*/
|
|
3294
|
+
#join(channel) {
|
|
3295
|
+
const run = channel._joinTail.then(async () => {
|
|
3296
|
+
const connection = this.#connection;
|
|
3297
|
+
if (channel.closed) return false;
|
|
3298
|
+
if (channel.joined && channel._joinedConnection === connection) {
|
|
3299
|
+
if (channel._restoredConnection === connection) return false;
|
|
3300
|
+
await this.#restore(channel, connection);
|
|
3301
|
+
return true;
|
|
3302
|
+
}
|
|
3303
|
+
await this.#joinNow(channel, connection);
|
|
3304
|
+
await this.#restore(channel, connection);
|
|
3305
|
+
return true;
|
|
3306
|
+
});
|
|
3307
|
+
channel._joinTail = run.catch(() => {
|
|
3308
|
+
});
|
|
3309
|
+
return run;
|
|
3310
|
+
}
|
|
3311
|
+
async #joinNow(channel, connection) {
|
|
3341
3312
|
const ref = this.#nextRef();
|
|
3342
3313
|
channel.joinRef = ref;
|
|
3343
3314
|
channel._resetForRejoin();
|
|
3344
|
-
|
|
3315
|
+
channel._endedJoin = null;
|
|
3345
3316
|
const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
|
|
3317
|
+
const ended = channel._endedJoin;
|
|
3318
|
+
if (ended && ended.joinRef === ref) {
|
|
3319
|
+
channel._endedJoin = null;
|
|
3320
|
+
throw joinInterrupted(channel, ended.event);
|
|
3321
|
+
}
|
|
3346
3322
|
channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
|
|
3347
3323
|
if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
|
|
3324
|
+
channel._joinedConnection = connection;
|
|
3348
3325
|
channel.joined = true;
|
|
3349
|
-
|
|
3326
|
+
}
|
|
3327
|
+
async #restore(channel, connection) {
|
|
3328
|
+
if (channel.watches.length) {
|
|
3329
|
+
await channel.push("watch", [...channel.watches]);
|
|
3330
|
+
if (channel.closed || !channel.joined || channel._joinedConnection !== connection) {
|
|
3331
|
+
throw joinInterrupted(channel, "phx_close");
|
|
3332
|
+
}
|
|
3333
|
+
}
|
|
3350
3334
|
channel._startPinger();
|
|
3335
|
+
channel._restoredConnection = connection;
|
|
3336
|
+
}
|
|
3337
|
+
#finishMarket(channel) {
|
|
3338
|
+
channel._finish();
|
|
3339
|
+
if (this.channels.get(channel.topic) === channel) this.channels.delete(channel.topic);
|
|
3351
3340
|
}
|
|
3352
3341
|
/** @internal */
|
|
3353
3342
|
async _leave(channel) {
|
|
@@ -3402,6 +3391,8 @@ var STXWebSocket = class {
|
|
|
3402
3391
|
};
|
|
3403
3392
|
const onUnexpected = (_req, res) => {
|
|
3404
3393
|
cleanup();
|
|
3394
|
+
conn.on("error", () => {
|
|
3395
|
+
});
|
|
3405
3396
|
conn.terminate();
|
|
3406
3397
|
const reason = res.headers?.["x-stx-error"];
|
|
3407
3398
|
reject(
|
|
@@ -3428,6 +3419,7 @@ var STXWebSocket = class {
|
|
|
3428
3419
|
conn.on("message", (data) => this.#onFrame(data.toString()));
|
|
3429
3420
|
conn.on("close", () => this.#onConnClose(conn));
|
|
3430
3421
|
this.#conn = conn;
|
|
3422
|
+
this.#connection += 1;
|
|
3431
3423
|
this.#pendingHeartbeat = null;
|
|
3432
3424
|
this.#startHeartbeat();
|
|
3433
3425
|
this.logger.debug(`connected to ${this.url}`);
|
|
@@ -3511,15 +3503,29 @@ var STXWebSocket = class {
|
|
|
3511
3503
|
}
|
|
3512
3504
|
const channel = this.channels.get(topic);
|
|
3513
3505
|
if (!channel) return;
|
|
3514
|
-
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
3515
|
-
return;
|
|
3516
|
-
}
|
|
3517
3506
|
if (event === "phx_error" || event === "phx_close") {
|
|
3518
|
-
if (
|
|
3519
|
-
|
|
3520
|
-
|
|
3521
|
-
|
|
3507
|
+
if (joinRef === null || joinRef === void 0 || String(joinRef) !== channel.joinRef) return;
|
|
3508
|
+
if (channel.closed || this.#closed) return;
|
|
3509
|
+
if (!channel.joined) {
|
|
3510
|
+
channel._endedJoin = { joinRef: String(joinRef), event };
|
|
3511
|
+
const pending = this.#pending.get(String(joinRef));
|
|
3512
|
+
if (pending?.event === "phx_join") pending.reject(joinInterrupted(channel, event));
|
|
3513
|
+
if (event === "phx_close" && channel.name === "market") this.#finishMarket(channel);
|
|
3514
|
+
return;
|
|
3522
3515
|
}
|
|
3516
|
+
for (const pending of [...this.#pending.values()]) {
|
|
3517
|
+
if (pending.topic === channel.topic) pending.reject(joinInterrupted(channel, event));
|
|
3518
|
+
}
|
|
3519
|
+
if (event === "phx_close" && channel.name === "market") {
|
|
3520
|
+
this.#finishMarket(channel);
|
|
3521
|
+
return;
|
|
3522
|
+
}
|
|
3523
|
+
this.logger.warn(`${topic}: server sent ${event}; rejoining`);
|
|
3524
|
+
channel._resetForRejoin();
|
|
3525
|
+
void this.#rejoinLater(channel, true);
|
|
3526
|
+
return;
|
|
3527
|
+
}
|
|
3528
|
+
if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
|
|
3523
3529
|
return;
|
|
3524
3530
|
}
|
|
3525
3531
|
if (channel.name === "markets") payload = convertMarketsFrame(payload);
|
|
@@ -3537,13 +3543,21 @@ var STXWebSocket = class {
|
|
|
3537
3543
|
)
|
|
3538
3544
|
);
|
|
3539
3545
|
}
|
|
3540
|
-
|
|
3546
|
+
/**
|
|
3547
|
+
* Rejoin `channel` with backoff. `serverClosed`: the server closed or
|
|
3548
|
+
* errored it while the socket stayed up (counted in `channelRejoins`);
|
|
3549
|
+
* otherwise a rejoin refused during a socket reconnect is being retried.
|
|
3550
|
+
*/
|
|
3551
|
+
async #rejoinLater(channel, serverClosed) {
|
|
3541
3552
|
let attempt = 1;
|
|
3542
3553
|
while (!channel.closed && !this.#closed) {
|
|
3543
3554
|
await sleep2(this.reconnectPolicy.delayMs(attempt));
|
|
3544
3555
|
if (!this.connected) return;
|
|
3545
3556
|
try {
|
|
3546
|
-
await this.#join(channel)
|
|
3557
|
+
if (await this.#join(channel) && channel.joined && !channel.closed) {
|
|
3558
|
+
if (serverClosed) this.channelRejoins += 1;
|
|
3559
|
+
await this.#raiseReconnect();
|
|
3560
|
+
}
|
|
3547
3561
|
return;
|
|
3548
3562
|
} catch (err) {
|
|
3549
3563
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
|
|
@@ -3593,6 +3607,8 @@ var STXWebSocket = class {
|
|
|
3593
3607
|
}
|
|
3594
3608
|
async #reconnectLoop() {
|
|
3595
3609
|
this.#reconnecting = true;
|
|
3610
|
+
let finished;
|
|
3611
|
+
this.#reconnectDone = new Promise((r) => finished = r);
|
|
3596
3612
|
let ok = false;
|
|
3597
3613
|
try {
|
|
3598
3614
|
let attempt = 1;
|
|
@@ -3614,13 +3630,13 @@ var STXWebSocket = class {
|
|
|
3614
3630
|
} catch (err) {
|
|
3615
3631
|
if (!(err instanceof STXChannelException)) throw err;
|
|
3616
3632
|
this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
|
|
3617
|
-
void this.#rejoinLater(channel);
|
|
3633
|
+
void this.#rejoinLater(channel, false);
|
|
3618
3634
|
}
|
|
3619
3635
|
}
|
|
3620
3636
|
this.reconnects += 1;
|
|
3621
3637
|
this.logger.info(`reconnected (${this.reconnects})`);
|
|
3622
3638
|
ok = true;
|
|
3623
|
-
|
|
3639
|
+
void this.#raiseReconnect();
|
|
3624
3640
|
return;
|
|
3625
3641
|
} catch (err) {
|
|
3626
3642
|
this.#closeConn();
|
|
@@ -3636,12 +3652,21 @@ var STXWebSocket = class {
|
|
|
3636
3652
|
}
|
|
3637
3653
|
} finally {
|
|
3638
3654
|
this.#reconnecting = false;
|
|
3655
|
+
finished();
|
|
3639
3656
|
if (ok && !this.#closed && !this.connected) {
|
|
3640
3657
|
for (const channel of this.channels.values()) channel._resetForRejoin();
|
|
3641
3658
|
void this.#reconnectLoop();
|
|
3642
3659
|
}
|
|
3643
3660
|
}
|
|
3644
3661
|
}
|
|
3662
|
+
async #raiseReconnect() {
|
|
3663
|
+
if (!this.onReconnect) return;
|
|
3664
|
+
try {
|
|
3665
|
+
await this.onReconnect();
|
|
3666
|
+
} catch (err) {
|
|
3667
|
+
this.logger.error("onReconnect threw", err);
|
|
3668
|
+
}
|
|
3669
|
+
}
|
|
3645
3670
|
#failAuth(err) {
|
|
3646
3671
|
this.error = err;
|
|
3647
3672
|
this.#shutdownAfterDrop();
|
|
@@ -3663,6 +3688,12 @@ var STXWebSocket = class {
|
|
|
3663
3688
|
for (const w of waiters) w();
|
|
3664
3689
|
}
|
|
3665
3690
|
};
|
|
3691
|
+
function joinInterrupted(channel, event) {
|
|
3692
|
+
return new STXChannelException(`${event} on ${channel.topic} while joining`, {
|
|
3693
|
+
topic: channel.topic,
|
|
3694
|
+
reply: { reason: event }
|
|
3695
|
+
});
|
|
3696
|
+
}
|
|
3666
3697
|
function dropUndefined(payload) {
|
|
3667
3698
|
return Object.fromEntries(
|
|
3668
3699
|
Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
|
|
@@ -3670,7 +3701,6 @@ function dropUndefined(payload) {
|
|
|
3670
3701
|
}
|
|
3671
3702
|
|
|
3672
3703
|
export {
|
|
3673
|
-
geoRejection,
|
|
3674
3704
|
STXException,
|
|
3675
3705
|
STXConfigException,
|
|
3676
3706
|
STXAPIException,
|
|
@@ -3683,7 +3713,6 @@ export {
|
|
|
3683
3713
|
STXIPNotAllowedException,
|
|
3684
3714
|
STXNotFoundException,
|
|
3685
3715
|
STXRejectedException,
|
|
3686
|
-
STXGeoLocationException,
|
|
3687
3716
|
STXRateLimitException,
|
|
3688
3717
|
STXServerException,
|
|
3689
3718
|
STXTransportException,
|
|
@@ -3744,4 +3773,4 @@ export {
|
|
|
3744
3773
|
orderBody,
|
|
3745
3774
|
STX
|
|
3746
3775
|
};
|
|
3747
|
-
//# sourceMappingURL=chunk-
|
|
3776
|
+
//# sourceMappingURL=chunk-FTZCBXT7.js.map
|