@stxapp/stx-typescript 0.9.0-alpha.1 → 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.
@@ -1,38 +1,3 @@
1
- // src/enums.ts
2
- var Region = {
3
- US: "us",
4
- ONTARIO: "ontario"
5
- };
6
- var Environment = {
7
- PRODUCTION: "production",
8
- DEMO: "demo"
9
- };
10
-
11
- // src/geo.ts
12
- var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
13
- function geoRejection(message) {
14
- const ip = IP_NOT_ALLOWED.exec(message);
15
- if (ip) return { reason: "ip_not_allowed", ipAddress: ip[1] };
16
- if (/geo location check was not done by this user|unknown user in geocomply/i.test(message)) {
17
- return { reason: "packet_other_user" };
18
- }
19
- if (/IP address doesn't match geo location/i.test(message)) {
20
- return { reason: "packet_ip_mismatch" };
21
- }
22
- if (/geo ?location package is invalid|geocomply location response|unable to find expected tag/i.test(message)) {
23
- return { reason: "packet_invalid" };
24
- }
25
- if (/invalid geo ?location|geo[- ]?(location|fenc)/i.test(message)) {
26
- return { reason: "location_not_allowed" };
27
- }
28
- return void 0;
29
- }
30
- async function resolveGeoLocation(provider) {
31
- if (provider === void 0 || provider === null) return void 0;
32
- const value = typeof provider === "function" ? await provider() : provider;
33
- return value === null || value === void 0 || value === "" ? void 0 : value;
34
- }
35
-
36
1
  // src/exceptions.ts
37
2
  var STXException = class extends Error {
38
3
  statusCode;
@@ -68,19 +33,20 @@ var STXInvalidTokenException = class extends STXAuthenticationException {
68
33
  };
69
34
  var STXInsufficientScopeException = class extends STXForbiddenException {
70
35
  };
36
+ var STXTermsRequiredException = class extends STXForbiddenException {
37
+ /** The STX page where the member accepts the terms, when the answer names it. */
38
+ termsUrl;
39
+ constructor(message, opts = {}) {
40
+ super(message, opts);
41
+ this.termsUrl = opts.termsUrl;
42
+ }
43
+ };
44
+ var STXIPNotAllowedException = class extends STXForbiddenException {
45
+ };
71
46
  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 = {}) {
@@ -114,6 +80,88 @@ var STXChannelException = class extends STXException {
114
80
  };
115
81
  var STXTimeoutException = class extends STXChannelException {
116
82
  };
83
+ var NOT_AVAILABLE = /* @__PURE__ */ Symbol.for("@stxapp/stx-typescript.notAvailable");
84
+ var FEATURE_PHRASES = {
85
+ oauth: "OAuth is",
86
+ "oauth.member": "Member sign-in with OAuth is",
87
+ "oauth.app": "App tokens are",
88
+ connect: "Sign in with STX is",
89
+ "terms.stx_page": "Accepting terms on an STX page is",
90
+ "markets.create": "Creating markets is",
91
+ market_types: "Market types are",
92
+ event_players: "Event players are",
93
+ leaderboard: "The leaderboard is",
94
+ loyalty: "The loyalty program is",
95
+ combos: "Combos are"
96
+ };
97
+ function notAvailableMessage(feature, host) {
98
+ const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : FEATURE_PHRASES[feature] ?? `${feature} is`;
99
+ return `${phrase} not available on ${host} yet.`;
100
+ }
101
+ var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
102
+ /** The feature id, e.g. `"combos"`. */
103
+ feature;
104
+ /** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
105
+ host;
106
+ constructor(feature, host, opts = {}) {
107
+ super(opts.message ?? notAvailableMessage(feature, host), opts);
108
+ this.feature = feature;
109
+ this.host = host;
110
+ markNotAvailable(this);
111
+ }
112
+ // `this` is the class on the right of `instanceof`: a subclass keeps the
113
+ // ordinary check, only the base class also accepts marked exceptions.
114
+ static [Symbol.hasInstance](value) {
115
+ const cls = this;
116
+ if (Function.prototype[Symbol.hasInstance].call(cls, value)) return true;
117
+ return cls === _STXNotAvailableException && typeof value === "object" && value !== null && value[NOT_AVAILABLE] === true;
118
+ }
119
+ };
120
+ function markNotAvailable(err) {
121
+ Object.defineProperty(err, NOT_AVAILABLE, { value: true, enumerable: false });
122
+ }
123
+ var STXCombosUnavailableException = class extends STXChannelException {
124
+ feature = "combos";
125
+ /** The exchange host that lacks combos. */
126
+ host;
127
+ constructor(message, opts = {}) {
128
+ super(message, opts);
129
+ this.host = opts.host ?? "";
130
+ markNotAvailable(this);
131
+ }
132
+ };
133
+ function isMissingRoute(err) {
134
+ if (!(err instanceof STXNotFoundException)) return false;
135
+ const body = err.body;
136
+ return !!body && typeof body === "object" && body.error === "not_found" && Object.keys(body).length === 1;
137
+ }
138
+ function isEdgeBlock(status, text) {
139
+ if (status !== 403) return false;
140
+ try {
141
+ JSON.parse(text);
142
+ return false;
143
+ } catch {
144
+ return true;
145
+ }
146
+ }
147
+ var STXComboRefusedException = class extends STXChannelException {
148
+ command;
149
+ code;
150
+ detail;
151
+ constructor(message, opts) {
152
+ super(message, opts);
153
+ this.command = opts.command;
154
+ this.code = opts.code;
155
+ this.detail = opts.detail;
156
+ }
157
+ };
158
+ var STXComboPriceMovedException = class extends STXComboRefusedException {
159
+ best;
160
+ constructor(message, opts) {
161
+ super(message, opts);
162
+ this.best = opts.best;
163
+ }
164
+ };
117
165
  function errorForStatus(statusCode, body, opts) {
118
166
  let message;
119
167
  if (body && typeof body === "object" && typeof body.error === "string") {
@@ -130,6 +178,16 @@ function errorForStatus(statusCode, body, opts) {
130
178
  case 401:
131
179
  return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
132
180
  case 403: {
181
+ const fields = body && typeof body === "object" ? body : {};
182
+ if (fields.error === "ip_not_allowed") {
183
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
184
+ return new STXIPNotAllowedException(description, base);
185
+ }
186
+ if (fields.error === "terms_required") {
187
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
188
+ const termsUrl = typeof fields.terms_url === "string" ? fields.terms_url : void 0;
189
+ return new STXTermsRequiredException(description, { ...base, termsUrl });
190
+ }
133
191
  if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
134
192
  return new STXInsufficientScopeException(message, {
135
193
  ...base,
@@ -140,10 +198,8 @@ function errorForStatus(statusCode, body, opts) {
140
198
  }
141
199
  case 404:
142
200
  return new STXNotFoundException(message, base);
143
- case 422: {
144
- const geo = geoRejection(message);
145
- return geo ? new STXGeoLocationException(message, geo, base) : new STXRejectedException(message, base);
146
- }
201
+ case 422:
202
+ return new STXRejectedException(message, base);
147
203
  case 429:
148
204
  return new STXRateLimitException(message, { ...base, retryAfter: parseRetryAfter(opts.retryAfter) });
149
205
  default:
@@ -168,6 +224,151 @@ function insufficientScopes(header, body) {
168
224
  return raw ? raw.split(/\s+/).filter(Boolean) : [];
169
225
  }
170
226
 
227
+ // src/capabilities.ts
228
+ var FEATURES = [
229
+ "oauth",
230
+ "oauth.member",
231
+ "oauth.app",
232
+ "connect",
233
+ "terms.stx_page",
234
+ "markets.create",
235
+ "market_types",
236
+ "event_players",
237
+ "leaderboard",
238
+ "loyalty",
239
+ "combos"
240
+ ];
241
+ var MEMBER_SCOPES = [
242
+ "profile.read",
243
+ "balance.read",
244
+ "portfolio.read",
245
+ "orders.read",
246
+ "transfers.read",
247
+ "orders.write"
248
+ ];
249
+ var Capabilities = class {
250
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
251
+ host;
252
+ /** `GET /api_version`, e.g. `"3.3.196-rnd.9"`, or null when it did not answer. */
253
+ apiVersion;
254
+ /** When the checks ran. */
255
+ checkedAt;
256
+ /** The scopes the exchange's OAuth discovery document lists; empty without OAuth. */
257
+ scopesSupported;
258
+ /** Every feature and whether the exchange has it. */
259
+ features;
260
+ constructor(init) {
261
+ this.host = init.host;
262
+ this.apiVersion = init.apiVersion;
263
+ this.checkedAt = init.checkedAt;
264
+ this.scopesSupported = init.scopesSupported;
265
+ this.features = init.features;
266
+ }
267
+ /** True only when the exchange is known to have `feature`. */
268
+ has(feature) {
269
+ return this.features[feature] === true;
270
+ }
271
+ /**
272
+ * Throw `STXNotAvailableException` unless the exchange is known to have
273
+ * `feature`. A feature that could not be checked (`null`) does not throw:
274
+ * the call itself will say.
275
+ */
276
+ require(feature) {
277
+ if (this.features[feature] === false) throw new STXNotAvailableException(feature, this.host);
278
+ }
279
+ toJSON() {
280
+ return {
281
+ host: this.host,
282
+ apiVersion: this.apiVersion,
283
+ checkedAt: this.checkedAt.toISOString(),
284
+ scopesSupported: this.scopesSupported,
285
+ features: this.features
286
+ };
287
+ }
288
+ };
289
+ var NOBODY = "00000000-0000-0000-0000-000000000000";
290
+ function json(answer) {
291
+ if (!answer) return null;
292
+ try {
293
+ const parsed = JSON.parse(answer.text);
294
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
295
+ } catch {
296
+ return null;
297
+ }
298
+ }
299
+ function strings(value) {
300
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
301
+ }
302
+ function missingRoute(answer) {
303
+ if (!answer || answer.status !== 404) return false;
304
+ const body = json(answer);
305
+ return !!body && body.error === "not_found" && Object.keys(body).length === 1;
306
+ }
307
+ function oauthMetadataFrom(answer) {
308
+ if (!answer) return null;
309
+ const body = json(answer);
310
+ if (answer.status === 404) return false;
311
+ if (answer.status === 403 && !body) return false;
312
+ if (answer.status !== 200 || !body) return null;
313
+ if (typeof body.issuer !== "string" || typeof body.authorization_endpoint !== "string" || typeof body.token_endpoint !== "string") {
314
+ return null;
315
+ }
316
+ return body;
317
+ }
318
+ async function discoverCapabilities(probes) {
319
+ const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
320
+ const [version, discovery, types, players, board, loyalty, combos] = await Promise.all([
321
+ swallow(probes.get("/api_version")),
322
+ swallow(probes.get("/.well-known/oauth-authorization-server")),
323
+ swallow(probes.signedGet("/api/v1/types")),
324
+ swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
325
+ swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
326
+ swallow(probes.signedGet("/api/v1/portfolio/loyalty?limit=1")),
327
+ swallow(probes.joinReason(`rfq:${NOBODY}`))
328
+ ]);
329
+ const apiVersion = json(version)?.api_version;
330
+ const meta = oauthMetadataFrom(discovery);
331
+ const scopes = meta ? strings(meta.scopes_supported) : [];
332
+ const grants = meta ? strings(meta.grant_types_supported) : [];
333
+ const fromMeta = (decide) => meta === null ? null : meta === false ? false : decide();
334
+ const oauth = fromMeta(() => true);
335
+ const member = fromMeta(() => grants.includes("authorization_code") && scopes.some((s) => MEMBER_SCOPES.includes(s)));
336
+ const app = fromMeta(() => grants.includes("client_credentials"));
337
+ const features = {
338
+ oauth,
339
+ "oauth.member": member,
340
+ "oauth.app": app,
341
+ connect: fromMeta(() => scopes.includes("openid")),
342
+ "terms.stx_page": fromMeta(() => member === true && !scopes.includes("terms.write")),
343
+ "markets.create": fromMeta(() => app === true && scopes.includes("markets.write")),
344
+ market_types: types === null ? null : types.status >= 200 && types.status < 300 ? true : missingRoute(types) ? false : null,
345
+ // A 404 about the event (not about the route) means the route is there.
346
+ event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
347
+ // Switched off answers 404 too ("Leaderboard is not enabled").
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,
351
+ combos: combos === null ? null : combos !== "unmatched topic"
352
+ };
353
+ return new Capabilities({
354
+ host: probes.host,
355
+ apiVersion: typeof apiVersion === "string" ? apiVersion : null,
356
+ checkedAt: /* @__PURE__ */ new Date(),
357
+ scopesSupported: scopes,
358
+ features
359
+ });
360
+ }
361
+
362
+ // src/enums.ts
363
+ var Region = {
364
+ US: "us",
365
+ ONTARIO: "ontario"
366
+ };
367
+ var Environment = {
368
+ PRODUCTION: "production",
369
+ DEMO: "demo"
370
+ };
371
+
171
372
  // src/config.ts
172
373
  var Environments = {
173
374
  /** United States demo. Shared by every integrator. No real money. */
@@ -641,16 +842,24 @@ function isValidLine(line) {
641
842
  return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
642
843
  }
643
844
  function marketEntry(m) {
644
- return Object.fromEntries(Object.entries(m).map(([k, v]) => [k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`), v]));
845
+ return { rule: m.rule ?? "player_stat_line", player_id: m.playerId, stat: m.stat, line: m.line };
645
846
  }
646
- function toCreateMarketResult(raw, index) {
647
- return { ...raw, index, market_id: raw.market_id ?? null, reason: raw.reason ?? null };
847
+ function toCreateMarketResult(raw, m, index) {
848
+ const market = marketEntry(m);
849
+ switch (raw.status) {
850
+ case "created":
851
+ case "exists":
852
+ return { index, status: raw.status, market_id: String(raw.market_id), reason: null, market };
853
+ case "valid":
854
+ return { index, status: "valid", market_id: null, reason: null, market };
855
+ default:
856
+ return rejected(m, index, raw.reason ?? "not_created");
857
+ }
648
858
  }
649
- function rejected(index, reason) {
650
- return { index, status: "rejected", market_id: null, reason };
859
+ function rejected(m, index, reason) {
860
+ return { index, status: "rejected", market_id: null, reason, market: marketEntry(m) };
651
861
  }
652
862
  function checkMarket(m, players) {
653
- if (m.rule !== "player_stat_line") return { market: m };
654
863
  if (!isValidLine(m.line)) return { reason: "invalid_line" };
655
864
  const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
656
865
  if (!stat) return { reason: "unsupported_stat" };
@@ -969,7 +1178,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
969
1178
  }
970
1179
 
971
1180
  // src/version.ts
972
- var VERSION = "0.9.0-alpha.1";
1181
+ var VERSION = "0.10.0";
973
1182
  var USER_AGENT = `stx-typescript/${VERSION}`;
974
1183
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
975
1184
 
@@ -1156,6 +1365,295 @@ var AccountView = class {
1156
1365
  }
1157
1366
  };
1158
1367
 
1368
+ // src/combos.ts
1369
+ var COMBO_PLAYER_CHANNEL = "rfq";
1370
+ var COMBO_MAKER_CHANNEL = "combo_quote";
1371
+ var UNAVAILABLE_REASON = "unmatched topic";
1372
+ var ACCEPT_TIMEOUT_MS = 35e3;
1373
+ var HISTORY_SIZE = 1e3;
1374
+ var PLAYER_EVENTS = /* @__PURE__ */ new Set(["best_quote", "placed", "negotiation_closed"]);
1375
+ var MAKER_EVENTS = /* @__PURE__ */ new Set([
1376
+ "rfq_opened",
1377
+ "rfq_closed",
1378
+ "quote_accepted",
1379
+ "placed",
1380
+ "negotiation_closed"
1381
+ ]);
1382
+ function comboRefusal(command, topic, response, host = "") {
1383
+ const reply = response && typeof response === "object" ? response : {};
1384
+ const reason = typeof reply.reason === "string" ? reply.reason : void 0;
1385
+ if (reason === UNAVAILABLE_REASON) {
1386
+ return new STXCombosUnavailableException(notAvailableMessage("combos", host || "this exchange"), {
1387
+ topic,
1388
+ reply: response,
1389
+ host
1390
+ });
1391
+ }
1392
+ if (reason === void 0) {
1393
+ return new STXComboRefusedException(`${command} on ${topic} failed: ${JSON.stringify(response)}`, {
1394
+ topic,
1395
+ reply: response,
1396
+ command,
1397
+ code: ""
1398
+ });
1399
+ }
1400
+ let code = reason;
1401
+ let detail;
1402
+ if (reason.startsWith("player_refused:")) {
1403
+ code = "player_refused";
1404
+ detail = reason.slice("player_refused:".length);
1405
+ }
1406
+ const message = `${command} on ${topic} refused: ${reason}`;
1407
+ if (code === "price_moved") {
1408
+ return new STXComboPriceMovedException(message, {
1409
+ topic,
1410
+ reply: response,
1411
+ command,
1412
+ code,
1413
+ best: {
1414
+ quote_id: reply.quote_id ?? null,
1415
+ amount: reply.amount ?? null,
1416
+ expires_at: reply.expires_at ?? null
1417
+ }
1418
+ });
1419
+ }
1420
+ return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
1421
+ }
1422
+ function comboJoinError(err, host = "") {
1423
+ if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
1424
+ if (err.constructor !== STXChannelException) return err;
1425
+ return comboRefusal("phx_join", err.topic, err.reply, host);
1426
+ }
1427
+ return err;
1428
+ }
1429
+ function money(name, value) {
1430
+ if (typeof value !== "string") {
1431
+ throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
1432
+ }
1433
+ return value;
1434
+ }
1435
+ var ComboSession = class {
1436
+ /** The underlying channel. Its `reply` is the latest join reply. */
1437
+ channel;
1438
+ #onEvent;
1439
+ #history = [];
1440
+ #waiters = [];
1441
+ #events;
1442
+ /** @internal */
1443
+ constructor(channel, events, onEvent) {
1444
+ this.channel = channel;
1445
+ this.#events = events;
1446
+ this.#onEvent = onEvent;
1447
+ }
1448
+ /** Your account's pseudonym for counterparties, from the join reply. */
1449
+ get externalId() {
1450
+ return this.channel.reply.external_id ?? "";
1451
+ }
1452
+ /** @internal */
1453
+ _typed(msg) {
1454
+ if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
1455
+ return { event: msg.event, payload: msg.payload };
1456
+ }
1457
+ /** @internal Called for every message on the channel, before it is queued. */
1458
+ async _receive(msg) {
1459
+ const event = this._typed(msg);
1460
+ if (!event) return;
1461
+ this.#history.push(event);
1462
+ if (this.#history.length > HISTORY_SIZE) this.#history.shift();
1463
+ for (const w of [...this.#waiters]) {
1464
+ if (w.match(event)) {
1465
+ this.#waiters = this.#waiters.filter((x) => x !== w);
1466
+ w.resolve(event);
1467
+ }
1468
+ }
1469
+ if (this.#onEvent) await this.#onEvent(event);
1470
+ }
1471
+ /** The events received so far (the latest 1000), oldest first. */
1472
+ get events() {
1473
+ return [...this.#history];
1474
+ }
1475
+ /**
1476
+ * The next event, in arrival order. Rejects with `STXTimeoutException` when
1477
+ * none arrives within `timeoutMs`, and with `STXChannelException` once the
1478
+ * channel is closed. Use either this or `for await`, not both.
1479
+ */
1480
+ async next(timeoutMs) {
1481
+ for (; ; ) {
1482
+ const event = this._typed(await this.channel.next(timeoutMs));
1483
+ if (event) return event;
1484
+ }
1485
+ }
1486
+ async *[Symbol.asyncIterator]() {
1487
+ for await (const msg of this.channel) {
1488
+ const event = this._typed(msg);
1489
+ if (event) yield event;
1490
+ }
1491
+ }
1492
+ /**
1493
+ * Resolve with the first event named `event` (or one of several) for
1494
+ * `rfqId`, looking first at events already received. Unlike `next()`, it
1495
+ * takes nothing from the queue. Rejects with `STXTimeoutException` after
1496
+ * `timeoutMs` (default 10000).
1497
+ *
1498
+ * @param event An event name, or several.
1499
+ * @param opts.rfqId Only events for this request.
1500
+ * @param opts.quoteId Only events for this quote (maker events).
1501
+ * @param opts.timeoutMs Milliseconds to wait. Default 10000.
1502
+ */
1503
+ waitFor(event, opts = {}) {
1504
+ const names = typeof event === "string" ? [event] : event;
1505
+ const match = (e) => names.includes(e.event) && (opts.rfqId === void 0 || e.payload.rfq_id === opts.rfqId) && (opts.quoteId === void 0 || e.payload.quote_id === opts.quoteId);
1506
+ const seen = this.#history.find(match);
1507
+ if (seen) return Promise.resolve(seen);
1508
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1509
+ return new Promise((resolve, reject) => {
1510
+ const waiter = {
1511
+ match,
1512
+ resolve: (e) => {
1513
+ clearTimeout(timer);
1514
+ resolve(e);
1515
+ }
1516
+ };
1517
+ const timer = setTimeout(() => {
1518
+ this.#waiters = this.#waiters.filter((w) => w !== waiter);
1519
+ reject(
1520
+ new STXTimeoutException(`No ${names.join(" or ")} on ${this.channel.topic} within ${timeoutMs} ms`, {
1521
+ topic: this.channel.topic
1522
+ })
1523
+ );
1524
+ }, timeoutMs);
1525
+ this.#waiters.push(waiter);
1526
+ });
1527
+ }
1528
+ /**
1529
+ * Leave the topic. Requests opened and quotes placed on this channel end
1530
+ * (`cancelled`), as on any close, and delivery on this channel stops when
1531
+ * `leave()` resolves: the exchange's `negotiation_closed` for those requests
1532
+ * arrives after the channel has closed and is not passed to `onEvent` or to
1533
+ * an iterator. Treat every request still open here as cancelled once
1534
+ * `leave()` resolves. To see each request's own close first, `cancel()` it
1535
+ * and wait for its `negotiation_closed` before leaving. Other connections of
1536
+ * the same member still receive the close.
1537
+ */
1538
+ leave() {
1539
+ return this.channel.leave();
1540
+ }
1541
+ /** @internal Send a command and map a refusal to the combo exceptions. */
1542
+ async _command(command, payload, timeoutMs) {
1543
+ try {
1544
+ return await this.channel.push(command, payload, timeoutMs);
1545
+ } catch (err) {
1546
+ if (err instanceof STXChannelException && err.constructor === STXChannelException && err.reply !== void 0) {
1547
+ throw comboRefusal(command, this.channel.topic, err.reply);
1548
+ }
1549
+ throw err;
1550
+ }
1551
+ }
1552
+ };
1553
+ var ComboPlayer = class extends ComboSession {
1554
+ /** @internal */
1555
+ constructor(channel, onEvent) {
1556
+ super(channel, PLAYER_EVENTS, onEvent);
1557
+ }
1558
+ /**
1559
+ * `request_quote`: ask makers to quote on these legs for a stake. `amount`
1560
+ * is the stake as a decimal string in whole cents, e.g. `"250.00"`. Makers
1561
+ * quote what you win; quotes arrive as `best_quote` events.
1562
+ *
1563
+ * @param legs Two or more `open` markets and the outcome the combination needs of each.
1564
+ * @param amount The stake in dollars, e.g. `"250.00"`.
1565
+ */
1566
+ requestQuote(legs, amount2) {
1567
+ return this._command("request_quote", {
1568
+ legs: legs.map((leg) => ({ market_id: leg.marketId, outcome: leg.outcome })),
1569
+ amount: money("amount", amount2)
1570
+ });
1571
+ }
1572
+ /**
1573
+ * `cash_out`: ask makers to quote for what you hold of a combination, by the
1574
+ * `market_id` from `placed`. The exchange sets the size.
1575
+ *
1576
+ * @param marketId The combination's market id.
1577
+ */
1578
+ cashOut(marketId) {
1579
+ return this._command("cash_out", { market_id: marketId });
1580
+ }
1581
+ /**
1582
+ * `accept`: bind the request at `amount` or more, normally the amount
1583
+ * `best_quote` showed. The best live quote binds whoever made it, so the
1584
+ * placement can be better than `amount`. Waits up to 35 s.
1585
+ *
1586
+ * Throws `STXComboPriceMovedException` (with the live `best`) when nothing
1587
+ * at least as good is live; the request stays open and you can accept again.
1588
+ * The reply says what was placed; fills arrive on `fills`.
1589
+ *
1590
+ * @param rfqId The request.
1591
+ * @param quoteId The quote you saw, normally from `best_quote`.
1592
+ * @param amount The least amount you take, e.g. `"1750.00"`.
1593
+ */
1594
+ accept(rfqId, quoteId, amount2) {
1595
+ return this._command(
1596
+ "accept",
1597
+ { rfq_id: rfqId, quote_id: quoteId, amount: money("amount", amount2) },
1598
+ ACCEPT_TIMEOUT_MS
1599
+ );
1600
+ }
1601
+ /**
1602
+ * `cancel`: end the request and drop every quote on it.
1603
+ *
1604
+ * @param rfqId The request.
1605
+ */
1606
+ cancel(rfqId) {
1607
+ return this._command("cancel", { rfq_id: rfqId });
1608
+ }
1609
+ /**
1610
+ * `snapshot`: the request now, with the live best quote. Not delayed like `best_quote` events.
1611
+ *
1612
+ * @param rfqId The request.
1613
+ */
1614
+ snapshot(rfqId) {
1615
+ return this._command("snapshot", { rfq_id: rfqId });
1616
+ }
1617
+ };
1618
+ var ComboMaker = class extends ComboSession {
1619
+ /** @internal */
1620
+ constructor(channel, onEvent) {
1621
+ super(channel, MAKER_EVENTS, onEvent);
1622
+ }
1623
+ /**
1624
+ * `quote`: offer `amount` on a request. On a buy it is what the player wins;
1625
+ * on a cash out, what you pay for the whole size. Price it against the
1626
+ * request's `max_price` and `tick_size`. `expiresInMs` (a positive integer)
1627
+ * counts from receipt; the quote ends no later than its request.
1628
+ * `clientOrderId` (at most 255 bytes) is copied onto your order if it binds.
1629
+ *
1630
+ * @param rfqId The request, from `rfq_opened`.
1631
+ * @param amount In dollars, e.g. `"1750.00"`.
1632
+ * @param expiresInMs How long the quote stands, in milliseconds.
1633
+ * @param opts.clientOrderId Copied onto your order if the quote binds.
1634
+ */
1635
+ quote(rfqId, amount2, expiresInMs, opts = {}) {
1636
+ const payload = {
1637
+ rfq_id: rfqId,
1638
+ amount: money("amount", amount2),
1639
+ expires_in_ms: expiresInMs
1640
+ };
1641
+ if (opts.clientOrderId !== void 0) payload.client_order_id = opts.clientOrderId;
1642
+ return this._command("quote", payload);
1643
+ }
1644
+ /**
1645
+ * `withdraw_quote`: remove one of your quotes.
1646
+ *
1647
+ * @param rfqId The request.
1648
+ * @param quoteId Your quote, from the `quote()` reply.
1649
+ */
1650
+ withdrawQuote(rfqId, quoteId) {
1651
+ return this._command("withdraw_quote", { rfq_id: rfqId, quote_id: quoteId });
1652
+ }
1653
+ };
1654
+ var COMBO_CHANNELS = /* @__PURE__ */ new Set([COMBO_PLAYER_CHANNEL, COMBO_MAKER_CHANNEL]);
1655
+ var COMBOS_UNAVAILABLE_REASON = UNAVAILABLE_REASON;
1656
+
1159
1657
  // src/money.ts
1160
1658
  var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
1161
1659
  var QUANTITY_FIELDS = ["total_volume", "volume_24h", "open_interest"];
@@ -1409,6 +1907,19 @@ function ids(value) {
1409
1907
  return typeof value === "string" ? [value] : [...value];
1410
1908
  }
1411
1909
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1910
+ var GATED_OPERATIONS = {
1911
+ types_get: "market_types",
1912
+ events__id_players_get: "event_players",
1913
+ markets_post: "markets.create",
1914
+ leaderboard_get: "leaderboard",
1915
+ leaderboard_me_get: "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"
1922
+ };
1412
1923
  var STX = class _STX {
1413
1924
  baseUrl;
1414
1925
  socketUrl;
@@ -1420,10 +1931,10 @@ var STX = class _STX {
1420
1931
  verifyTls;
1421
1932
  retry;
1422
1933
  timeoutMs;
1423
- geoLocation;
1424
1934
  onResponse;
1425
1935
  #fetch;
1426
1936
  #me;
1937
+ #capabilities;
1427
1938
  /** Test hook: how retries wait. */
1428
1939
  _sleep = sleep;
1429
1940
  constructor(opts = {}) {
@@ -1461,7 +1972,6 @@ var STX = class _STX {
1461
1972
  this.verifyTls = settings.verifyTls;
1462
1973
  this.retry = opts.retry ?? new RetryPolicy();
1463
1974
  this.timeoutMs = opts.timeoutMs ?? 3e4;
1464
- this.geoLocation = opts.geoLocation;
1465
1975
  this.onResponse = opts.onResponse;
1466
1976
  const fetchImpl = opts.fetch ?? globalThis.fetch;
1467
1977
  if (typeof fetchImpl !== "function") {
@@ -1477,6 +1987,74 @@ var STX = class _STX {
1477
1987
  toString() {
1478
1988
  return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(this.credentials?.keyId ?? null)})`;
1479
1989
  }
1990
+ /** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
1991
+ get host() {
1992
+ return new URL(this.baseUrl).host;
1993
+ }
1994
+ // ------------------------------------------------------------------
1995
+ // Capabilities
1996
+ // ------------------------------------------------------------------
1997
+ /**
1998
+ * Which features this exchange has, from what it publishes: its OAuth
1999
+ * discovery document, `/api_version`, a signed GET of the routes that not
2000
+ * every exchange has yet, and a join of a combos topic nobody owns. Nothing
2001
+ * is created or changed. Checked once per client and cached; pass
2002
+ * `{ refresh: true }` to check again.
2003
+ *
2004
+ * const caps = await stx.capabilities();
2005
+ * caps.features.combos; // false on demo.stxapp.ca
2006
+ * caps.require("combos"); // throws STXNotAvailableException there
2007
+ *
2008
+ * Each feature is `true`, `false`, or `null` when it could not be checked
2009
+ * (no credentials for a signed check, or no answer). A missing feature never
2010
+ * throws here; the call that needs it throws `STXNotAvailableException`.
2011
+ */
2012
+ capabilities(opts = {}) {
2013
+ if (opts.refresh || !this.#capabilities) {
2014
+ const run = discoverCapabilities({
2015
+ host: this.host,
2016
+ get: (path) => this.#rawGet(path, false),
2017
+ signedGet: (path) => this.auth ? this.#rawGet(path, true) : null,
2018
+ joinReason: (topic) => this.#joinReason(topic)
2019
+ });
2020
+ this.#capabilities = run;
2021
+ run.catch(() => {
2022
+ if (this.#capabilities === run) this.#capabilities = void 0;
2023
+ });
2024
+ }
2025
+ return this.#capabilities;
2026
+ }
2027
+ async #rawGet(path, signed) {
2028
+ const headers = { "User-Agent": USER_AGENT, Accept: "application/json" };
2029
+ if (signed && this.auth) Object.assign(headers, await this.auth.authHeaders({ method: "GET", path }));
2030
+ const controller = new AbortController();
2031
+ const timer = setTimeout(() => controller.abort(), Math.min(this.timeoutMs, 15e3));
2032
+ try {
2033
+ const res = await this.#fetch(this.baseUrl + path, { method: "GET", headers, signal: controller.signal });
2034
+ return { status: res.status, text: await res.text() };
2035
+ } catch {
2036
+ return null;
2037
+ } finally {
2038
+ clearTimeout(timer);
2039
+ }
2040
+ }
2041
+ async #joinReason(topic) {
2042
+ if (!this.auth) return null;
2043
+ const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
2044
+ try {
2045
+ const channel = await ws.join(topic);
2046
+ await channel.leave().catch(() => {
2047
+ });
2048
+ return "ok";
2049
+ } catch (err) {
2050
+ if (err instanceof STXTimeoutException) return null;
2051
+ if (err instanceof STXChannelException) return err.reason ?? null;
2052
+ return null;
2053
+ } finally {
2054
+ await ws.close().catch(() => {
2055
+ });
2056
+ }
2057
+ }
1480
2058
  /** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
1481
2059
  async close() {
1482
2060
  }
@@ -1575,7 +2153,22 @@ var STX = class _STX {
1575
2153
  }
1576
2154
  }
1577
2155
  async #call(operationId, args = {}) {
1578
- return this.#send(buildRequest(operationId, args));
2156
+ try {
2157
+ return await this.#send(buildRequest(operationId, args));
2158
+ } catch (err) {
2159
+ const feature = GATED_OPERATIONS[operationId];
2160
+ const off = feature !== void 0 && err instanceof STXNotFoundException && SWITCHED_OFF[feature] !== void 0 && err.body?.error === SWITCHED_OFF[feature];
2161
+ if (feature && (isMissingRoute(err) || off)) {
2162
+ throw new STXNotAvailableException(feature, this.host, {
2163
+ statusCode: err.statusCode,
2164
+ body: err.body,
2165
+ method: err.method,
2166
+ path: err.path,
2167
+ cause: err
2168
+ });
2169
+ }
2170
+ throw err;
2171
+ }
1579
2172
  }
1580
2173
  async #one(operationId, args = {}) {
1581
2174
  const body = await this.#call(operationId, args);
@@ -1599,10 +2192,6 @@ var STX = class _STX {
1599
2192
  q.cursor = page.cursor;
1600
2193
  }
1601
2194
  }
1602
- async #geoBody(body, opts) {
1603
- const packet = opts?.geoLocation !== void 0 ? opts.geoLocation ?? void 0 : await resolveGeoLocation(this.geoLocation);
1604
- return packet === void 0 ? body : { ...body, geo_location: packet };
1605
- }
1606
2195
  // ------------------------------------------------------------------
1607
2196
  // Identity
1608
2197
  // ------------------------------------------------------------------
@@ -1727,16 +2316,18 @@ var STX = class _STX {
1727
2316
  * which STX grants, from an address on the client's IP allow-list (it
1728
2317
  * applies to every call that client makes).
1729
2318
  *
1730
- * Returns one result per market, in the order given, each with its `index`:
1731
- * `created` or `exists` (both with `market_id`), `valid` (a `dryRun` market
1732
- * that would be created), or `rejected` with a `reason`. A rejected market
1733
- * is a result, not an error, and resending is safe: a market that is
1734
- * already listed comes back `exists`. A refused request throws (`403`
1735
- * without `markets.write`, `404` unknown event, `422` event not open).
2319
+ * Returns one result per market, in order: `created` or `exists` (both with
2320
+ * `market_id`), `valid` with `dryRun`, or `rejected` with a `reason`. Each
2321
+ * result's `index` is its position in `markets`, and `market` is that market
2322
+ * as requested. A rejected market is a
2323
+ * result, not an error, and resending is safe: a market that is already
2324
+ * listed comes back `exists`. A refused request throws (`403` without
2325
+ * `markets.write`, `404` unknown event, `422` event not open).
1736
2326
  *
1737
- * `dryRun` runs every check and creates nothing. More than
1738
- * `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any request.
1739
- * `validate` also needs the `events` scope.
2327
+ * Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
2328
+ * than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
2329
+ * request. `dryRun` runs every check and creates nothing. `validate` also
2330
+ * needs the `events` scope.
1740
2331
  */
1741
2332
  async createMarkets(eventId, markets, opts = {}) {
1742
2333
  if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
@@ -1749,24 +2340,20 @@ var STX = class _STX {
1749
2340
  send = send.flatMap(({ m, i }) => {
1750
2341
  const checked = checkMarket(m, players);
1751
2342
  if ("market" in checked) return [{ m: checked.market, i }];
1752
- results[i] = rejected(i, checked.reason);
2343
+ results[i] = rejected(m, i, checked.reason);
1753
2344
  return [];
1754
2345
  });
1755
2346
  }
1756
2347
  if (send.length) {
1757
- const body = {
1758
- event_id: eventId,
1759
- ...opts.dryRun ? { dry_run: true } : {},
1760
- markets: send.map(({ m }) => marketEntry(m))
1761
- };
2348
+ const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
2349
+ if (opts.dryRun) body.dry_run = true;
1762
2350
  const raw = await this.#one("markets_post", { body });
1763
2351
  (raw.markets ?? []).forEach((r, k) => {
1764
- const sent = typeof r.index === "number" ? r.index : k;
1765
- const slot = send[sent];
1766
- if (slot) results[slot.i] = toCreateMarketResult(r, slot.i);
2352
+ const slot = send[typeof r.index === "number" ? r.index : k];
2353
+ if (slot) results[slot.i] = toCreateMarketResult(r, slot.m, slot.i);
1767
2354
  });
1768
2355
  }
1769
- return Array.from(results, (r, i) => r ?? rejected(i, "not_created"));
2356
+ return results.map((r, i) => r ?? rejected(markets[i], i, "not_created"));
1770
2357
  }
1771
2358
  // ------------------------------------------------------------------
1772
2359
  // Orders
@@ -1798,88 +2385,46 @@ var STX = class _STX {
1798
2385
  *
1799
2386
  * `action` is `"buy"` or `"sell"`; `orderType` is `"limit"` or `"market"`.
1800
2387
  * `price` (dollars, required for a limit order) and `quantity` (contracts)
1801
- * are decimal strings, e.g. `{ price: "0.56", quantity: "2" }`. Numbers are
2388
+ * are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
1802
2389
  * refused client-side.
1803
2390
  *
1804
2391
  * The exchange validates the order: a bad price step or a fractional
1805
2392
  * quantity throws `STXValidationException` (400) or `STXRejectedException`
1806
- * (422) with the API's message; a geo-fencing refusal throws
1807
- * `STXGeoLocationException`.
2393
+ * (422) with the API's message. An order from outside the region is also
2394
+ * an `STXRejectedException`.
1808
2395
  *
1809
2396
  * A POST is never retried after a 5xx or a dropped connection; pass
1810
2397
  * `clientOrderId` so you can look the order up if that happens.
1811
2398
  */
1812
2399
  async placeOrder(marketId, action, orderType, opts) {
1813
- const { geoLocation, ...fields } = opts ?? {};
1814
- const body = orderBody(marketId, action, orderType, fields);
1815
- 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 });
1816
2402
  }
1817
2403
  /**
1818
- * `POST /api/v1/orders/batched`: place several orders in one call. One geo
1819
- * check covers the batch. Returns one result per order, in order; a
1820
- * rejected order has `errors` instead of `order` and does not stop the
1821
- * 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.
1822
2407
  */
1823
- async placeOrders(orders, opts) {
2408
+ async placeOrders(orders) {
1824
2409
  const body = { orders: orders.map(normalizeOrder) };
1825
- const raw = await this.#list("orders_batched_post", { body: await this.#geoBody(body, opts) });
2410
+ const raw = await this.#list("orders_batched_post", { body });
1826
2411
  return raw.map(toBatchOrderResult);
1827
2412
  }
1828
2413
  /**
1829
2414
  * `DELETE /api/v1/orders/{order_id}`: request a cancel. A cancel is a
1830
2415
  * request: a fill already in flight can still land.
1831
2416
  */
1832
- async cancelOrder(orderId, opts) {
1833
- const geo = await this.#geoBody({}, opts);
1834
- return this.#one("orders__order_id_delete", {
1835
- pathParams: { order_id: orderId },
1836
- body: "geo_location" in geo ? geo : void 0
1837
- });
2417
+ async cancelOrder(orderId) {
2418
+ return this.#one("orders__order_id_delete", { pathParams: { order_id: orderId } });
1838
2419
  }
1839
2420
  /** `DELETE /api/v1/orders/batched`: cancel the named orders. */
1840
- async cancelOrders(orderIds, opts) {
2421
+ async cancelOrders(orderIds) {
1841
2422
  const body = { orders: orderIds.map((id) => ({ order_id: id })) };
1842
- return this.#list("orders_batched_delete", { body: await this.#geoBody(body, opts) });
2423
+ return this.#list("orders_batched_delete", { body });
1843
2424
  }
1844
2425
  /** `DELETE /api/v1/orders/all`: cancel everything resting on the account. */
1845
- async cancelAllOrders(opts) {
1846
- const geo = await this.#geoBody({}, opts);
1847
- return this.#list("orders_all_delete", { body: "geo_location" in geo ? geo : void 0 });
1848
- }
1849
- // ------------------------------------------------------------------
1850
- // Geo-fencing
1851
- // ------------------------------------------------------------------
1852
- /**
1853
- * Ask the exchange whether this machine may trade right now, without
1854
- * placing or cancelling anything.
1855
- *
1856
- * Sends `DELETE /api/v1/orders/00000000-0000-0000-0000-000000000000` (an
1857
- * order id that cannot exist) with the geolocation packet, if one is
1858
- * configured. The exchange runs its geo check before it looks the order
1859
- * up, so a 404 means the check passed, and a geo 422 means it did not. On
1860
- * an exchange without geo-fencing it always passes.
1861
- *
1862
- * Needs a `read_write` key (the probe is a write route). The exchange
1863
- * records a failed check in its geolocation log exactly as it would a real
1864
- * order from the same place, and may raise a compliance alert, so call it
1865
- * once at start-up, not in a loop.
1866
- */
1867
- async geoCheck(opts) {
1868
- const geo = await this.#geoBody({}, opts);
1869
- const sentPacket = "geo_location" in geo;
1870
- try {
1871
- await this.#one("orders__order_id_delete", {
1872
- pathParams: { order_id: "00000000-0000-0000-0000-000000000000" },
1873
- body: sentPacket ? geo : void 0
1874
- });
1875
- return { allowed: true, sentPacket };
1876
- } catch (err) {
1877
- if (err instanceof STXNotFoundException) return { allowed: true, sentPacket };
1878
- if (err instanceof STXGeoLocationException) {
1879
- return { allowed: false, reason: err.reason, message: err.message, ipAddress: err.ipAddress, sentPacket };
1880
- }
1881
- throw err;
1882
- }
2426
+ async cancelAllOrders() {
2427
+ return this.#list("orders_all_delete");
1883
2428
  }
1884
2429
  // ------------------------------------------------------------------
1885
2430
  // Fills, positions, balance
@@ -1985,18 +2530,54 @@ var STX = class _STX {
1985
2530
  iterFees(query = {}) {
1986
2531
  return this.#iterate("portfolio_fees_get", { limit: query.limit });
1987
2532
  }
1988
- /** `GET /api/v1/portfolio/loyalty`: loyalty entries. */
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
+ */
1989
2538
  loyalty(query = {}) {
1990
2539
  return this.#page("portfolio_loyalty_get", { limit: query.limit, cursor: query.cursor });
1991
2540
  }
1992
- /** Every loyalty entry, following the cursor. */
2541
+ /** Every loyalty entry, following the cursor. Throws like `loyalty()`. */
1993
2542
  iterLoyalty(query = {}) {
1994
2543
  return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
1995
2544
  }
1996
2545
  // ------------------------------------------------------------------
2546
+ // Leaderboard and public profile
2547
+ // ------------------------------------------------------------------
2548
+ /**
2549
+ * `GET /api/v1/leaderboard`: ranked members for a period, sport and metric.
2550
+ * Rows carry a public handle and avatar, never an account id. Throws
2551
+ * `STXNotAvailableException` (feature `leaderboard`) where the exchange does
2552
+ * not have the leaderboard.
2553
+ */
2554
+ leaderboard(query = {}) {
2555
+ const { period, category, metric, limit } = query;
2556
+ return this.#one("leaderboard_get", { query: { period, category, metric, limit } });
2557
+ }
2558
+ /** `GET /api/v1/leaderboard/me`: your own standing, including your rank outside the list. */
2559
+ leaderboardMe(query = {}) {
2560
+ return this.#one("leaderboard_me_get", { query: { period: query.period, category: query.category } });
2561
+ }
2562
+ /**
2563
+ * `PATCH /api/v1/me/profile`: change your public handle, avatar or
2564
+ * leaderboard opt-in. Resolves to the updated `me`.
2565
+ */
2566
+ async updateProfile(update) {
2567
+ this.#me = await this.#one("me_profile_patch", { body: update });
2568
+ return this.#me;
2569
+ }
2570
+ // ------------------------------------------------------------------
1997
2571
  // Terms
1998
2572
  // ------------------------------------------------------------------
1999
- /** `POST /api/v1/tnc/accept`: accept the current terms. Resolves to the server's message. */
2573
+ /**
2574
+ * `POST /api/v1/tnc/accept`: accept the current terms for your own account,
2575
+ * with your own API key. Resolves to the server's message.
2576
+ *
2577
+ * An app cannot accept the terms for a member: called with a member's OAuth
2578
+ * access token, the exchange answers 403 `terms_not_delegable`
2579
+ * (`STXForbiddenException`). The member accepts on an STX page instead.
2580
+ */
2000
2581
  async acceptTerms(deviceId, opts = {}) {
2001
2582
  const body = {
2002
2583
  device_id: deviceId,
@@ -2092,6 +2673,12 @@ var MessageQueue = class {
2092
2673
  this.#items.push(msg);
2093
2674
  return dropped;
2094
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
+ }
2095
2682
  get(timeoutMs) {
2096
2683
  if (this.#items.length) return Promise.resolve(this.#items.shift());
2097
2684
  return new Promise((resolve, reject) => {
@@ -2110,6 +2697,7 @@ var MessageQueue = class {
2110
2697
  });
2111
2698
  }
2112
2699
  };
2700
+ var UNPINGED_CHANNELS = /* @__PURE__ */ new Set(["market", "rfq", "combo_quote"]);
2113
2701
  var Channel = class {
2114
2702
  /** The wire topic, e.g. `orders:<user_id>`. */
2115
2703
  topic;
@@ -2132,6 +2720,19 @@ var Channel = class {
2132
2720
  #queue;
2133
2721
  #snapshotWaiters = [];
2134
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;
2135
2736
  constructor(ws, topic, joinPayload, onMessage, opts) {
2136
2737
  this.#ws = ws;
2137
2738
  this.topic = topic;
@@ -2299,9 +2900,10 @@ var Channel = class {
2299
2900
  let interval = this.pingIntervalMs;
2300
2901
  const granted = this.reply?.ping_timeout;
2301
2902
  if (typeof granted === "number" && this.joinPayload.cancel_on_disconnect) {
2302
- const cod = granted * 0.6;
2903
+ const cod = granted / 3;
2303
2904
  interval = interval === null ? cod : Math.min(interval, cod);
2304
2905
  }
2906
+ this._pingEveryMs = interval || null;
2305
2907
  if (interval) {
2306
2908
  const every = interval;
2307
2909
  this.#pingTimer = setInterval(() => {
@@ -2321,9 +2923,17 @@ var Channel = class {
2321
2923
  /** @internal */
2322
2924
  _resetForRejoin() {
2323
2925
  this.joined = false;
2926
+ this._restoredConnection = 0;
2324
2927
  this.snapshots = {};
2325
2928
  this._stopPinger();
2326
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
+ }
2327
2937
  /** @internal */
2328
2938
  _close() {
2329
2939
  this.closed = true;
@@ -2357,15 +2967,19 @@ var STXWebSocket = class {
2357
2967
  channels = /* @__PURE__ */ new Map();
2358
2968
  /** Successful reconnects so far. */
2359
2969
  reconnects = 0;
2970
+ /** Channels rejoined after the server closed or errored them while the socket stayed up. */
2971
+ channelRejoins = 0;
2360
2972
  #userId;
2361
2973
  #conn;
2362
2974
  #ref = 0;
2975
+ #connection = 0;
2363
2976
  #pending = /* @__PURE__ */ new Map();
2364
2977
  #heartbeat;
2365
2978
  #pendingHeartbeat = null;
2366
2979
  #closed = false;
2367
2980
  #connecting;
2368
2981
  #reconnecting = false;
2982
+ #reconnectDone = Promise.resolve();
2369
2983
  #closedWaiters = [];
2370
2984
  // Frames are handled one at a time, in arrival order: each waits for the
2371
2985
  // previous one's handler to finish.
@@ -2415,6 +3029,11 @@ var STXWebSocket = class {
2415
3029
  async connect() {
2416
3030
  if (this.#closed) throw new STXTransportException("This STXWebSocket is closed; create a new one.");
2417
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
+ }
2418
3037
  if (!this.#connecting) {
2419
3038
  this.#connecting = this.#openAuthenticated().finally(() => {
2420
3039
  this.#connecting = void 0;
@@ -2534,7 +3153,7 @@ var STXWebSocket = class {
2534
3153
  * `cancelOnDisconnect: true` arms cancel-on-disconnect for orders placed
2535
3154
  * with `cancelOnDisconnect: true`. `pingTimeout` is in milliseconds,
2536
3155
  * clamped by the server to 5000 to 20000; the granted value is in
2537
- * `channel.reply.ping_timeout` and the SDK pings at 60% of it for as long
3156
+ * `channel.reply.ping_timeout` and the SDK pings at a third of it for as long
2538
3157
  * as the channel is joined.
2539
3158
  */
2540
3159
  orders(opts = {}) {
@@ -2583,6 +3202,53 @@ var STXWebSocket = class {
2583
3202
  return this.#joinAccount("user_info", {}, opts.onMessage);
2584
3203
  }
2585
3204
  // ------------------------------------------------------------------
3205
+ // Combos
3206
+ // ------------------------------------------------------------------
3207
+ /**
3208
+ * Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
3209
+ * combination, cash one out, accept, cancel and read a request.
3210
+ *
3211
+ * Where combos are not available, rejects with
3212
+ * `STXCombosUnavailableException`. Other join refusals (a read-only key, an
3213
+ * account that may not trade) reject with `STXComboRefusedException`.
3214
+ */
3215
+ async comboPlayer(opts = {}) {
3216
+ let player;
3217
+ const early = [];
3218
+ const channel = await this.#joinCombo(COMBO_PLAYER_CHANNEL, opts, async (msg) => {
3219
+ if (player) await player._receive(msg);
3220
+ else early.push(msg);
3221
+ });
3222
+ player = new ComboPlayer(channel, opts.onEvent);
3223
+ for (const msg of early) await player._receive(msg);
3224
+ return player;
3225
+ }
3226
+ /**
3227
+ * Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
3228
+ * request opened from now on (`rfq_opened`), quote and withdraw quotes.
3229
+ *
3230
+ * Where combos are not available, rejects with
3231
+ * `STXCombosUnavailableException`.
3232
+ */
3233
+ async comboMaker(opts = {}) {
3234
+ let maker;
3235
+ const early = [];
3236
+ const channel = await this.#joinCombo(COMBO_MAKER_CHANNEL, opts, async (msg) => {
3237
+ if (maker) await maker._receive(msg);
3238
+ else early.push(msg);
3239
+ });
3240
+ maker = new ComboMaker(channel, opts.onEvent);
3241
+ for (const msg of early) await maker._receive(msg);
3242
+ return maker;
3243
+ }
3244
+ async #joinCombo(name, opts, onMessage) {
3245
+ try {
3246
+ return await this.#joinAccount(name, {}, onMessage);
3247
+ } catch (err) {
3248
+ throw comboJoinError(err, new URL(this.rest.baseUrl).host);
3249
+ }
3250
+ }
3251
+ // ------------------------------------------------------------------
2586
3252
  // Generic join
2587
3253
  // ------------------------------------------------------------------
2588
3254
  /**
@@ -2591,11 +3257,16 @@ var STXWebSocket = class {
2591
3257
  * `market_ids_required` or `unauthorized`) if the join is refused.
2592
3258
  */
2593
3259
  async join(topic, payload = {}, onMessage, opts = {}) {
2594
- const existing = this.channels.get(topic);
2595
- if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
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();
2596
3265
  await this.connect();
3266
+ already();
3267
+ const name = topic.split(":", 1)[0];
2597
3268
  const channel = new Channel(this, topic, payload, onMessage, {
2598
- pingIntervalMs: opts.pingIntervalMs === void 0 ? this.channelPingIntervalMs : opts.pingIntervalMs,
3269
+ pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
2599
3270
  queueSize: this.queueSize
2600
3271
  });
2601
3272
  this.channels.set(topic, channel);
@@ -2616,16 +3287,56 @@ var STXWebSocket = class {
2616
3287
  }
2617
3288
  return this.join(`${name}:${await this.userId()}`, payload, onMessage);
2618
3289
  }
2619
- async #join(channel) {
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) {
2620
3312
  const ref = this.#nextRef();
2621
3313
  channel.joinRef = ref;
2622
3314
  channel._resetForRejoin();
3315
+ channel._endedJoin = null;
2623
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
+ }
2624
3322
  channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
2625
3323
  if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
3324
+ channel._joinedConnection = connection;
2626
3325
  channel.joined = true;
2627
- if (channel.watches.length) await channel.push("watch", [...channel.watches]);
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
+ }
2628
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);
2629
3340
  }
2630
3341
  /** @internal */
2631
3342
  async _leave(channel) {
@@ -2680,6 +3391,8 @@ var STXWebSocket = class {
2680
3391
  };
2681
3392
  const onUnexpected = (_req, res) => {
2682
3393
  cleanup();
3394
+ conn.on("error", () => {
3395
+ });
2683
3396
  conn.terminate();
2684
3397
  const reason = res.headers?.["x-stx-error"];
2685
3398
  reject(
@@ -2706,6 +3419,7 @@ var STXWebSocket = class {
2706
3419
  conn.on("message", (data) => this.#onFrame(data.toString()));
2707
3420
  conn.on("close", () => this.#onConnClose(conn));
2708
3421
  this.#conn = conn;
3422
+ this.#connection += 1;
2709
3423
  this.#pendingHeartbeat = null;
2710
3424
  this.#startHeartbeat();
2711
3425
  this.logger.debug(`connected to ${this.url}`);
@@ -2789,15 +3503,29 @@ var STXWebSocket = class {
2789
3503
  }
2790
3504
  const channel = this.channels.get(topic);
2791
3505
  if (!channel) return;
2792
- if (joinRef !== null && joinRef !== void 0 && channel.joinRef !== null && String(joinRef) !== channel.joinRef) {
2793
- return;
2794
- }
2795
3506
  if (event === "phx_error" || event === "phx_close") {
2796
- if (!channel.closed && !this.#closed) {
2797
- this.logger.warn(`${topic}: server sent ${event}; rejoining`);
2798
- channel._resetForRejoin();
2799
- void this.#rejoinLater(channel);
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;
3515
+ }
3516
+ for (const pending of [...this.#pending.values()]) {
3517
+ if (pending.topic === channel.topic) pending.reject(joinInterrupted(channel, event));
2800
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) {
2801
3529
  return;
2802
3530
  }
2803
3531
  if (channel.name === "markets") payload = convertMarketsFrame(payload);
@@ -2815,18 +3543,26 @@ var STXWebSocket = class {
2815
3543
  )
2816
3544
  );
2817
3545
  }
2818
- async #rejoinLater(channel) {
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) {
2819
3552
  let attempt = 1;
2820
3553
  while (!channel.closed && !this.#closed) {
2821
3554
  await sleep2(this.reconnectPolicy.delayMs(attempt));
2822
3555
  if (!this.connected) return;
2823
3556
  try {
2824
- 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
+ }
2825
3561
  return;
2826
3562
  } catch (err) {
2827
3563
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
2828
3564
  const reply = err instanceof STXChannelException ? err.reply : void 0;
2829
- if (reply?.reason === "unauthorized") {
3565
+ if (reply?.reason === "unauthorized" || reply?.reason === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
2830
3566
  channel._close();
2831
3567
  return;
2832
3568
  }
@@ -2871,6 +3607,8 @@ var STXWebSocket = class {
2871
3607
  }
2872
3608
  async #reconnectLoop() {
2873
3609
  this.#reconnecting = true;
3610
+ let finished;
3611
+ this.#reconnectDone = new Promise((r) => finished = r);
2874
3612
  let ok = false;
2875
3613
  try {
2876
3614
  let attempt = 1;
@@ -2892,13 +3630,13 @@ var STXWebSocket = class {
2892
3630
  } catch (err) {
2893
3631
  if (!(err instanceof STXChannelException)) throw err;
2894
3632
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}; retrying`);
2895
- void this.#rejoinLater(channel);
3633
+ void this.#rejoinLater(channel, false);
2896
3634
  }
2897
3635
  }
2898
3636
  this.reconnects += 1;
2899
3637
  this.logger.info(`reconnected (${this.reconnects})`);
2900
3638
  ok = true;
2901
- if (this.onReconnect) await this.onReconnect();
3639
+ void this.#raiseReconnect();
2902
3640
  return;
2903
3641
  } catch (err) {
2904
3642
  this.#closeConn();
@@ -2914,12 +3652,21 @@ var STXWebSocket = class {
2914
3652
  }
2915
3653
  } finally {
2916
3654
  this.#reconnecting = false;
3655
+ finished();
2917
3656
  if (ok && !this.#closed && !this.connected) {
2918
3657
  for (const channel of this.channels.values()) channel._resetForRejoin();
2919
3658
  void this.#reconnectLoop();
2920
3659
  }
2921
3660
  }
2922
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
+ }
2923
3670
  #failAuth(err) {
2924
3671
  this.error = err;
2925
3672
  this.#shutdownAfterDrop();
@@ -2941,6 +3688,12 @@ var STXWebSocket = class {
2941
3688
  for (const w of waiters) w();
2942
3689
  }
2943
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
+ }
2944
3697
  function dropUndefined(payload) {
2945
3698
  return Object.fromEntries(
2946
3699
  Object.entries(payload).filter(([, v]) => v !== void 0).map(([k, v]) => [k, Array.isArray(v) ? [...v] : v])
@@ -2948,9 +3701,6 @@ function dropUndefined(payload) {
2948
3701
  }
2949
3702
 
2950
3703
  export {
2951
- Region,
2952
- Environment,
2953
- geoRejection,
2954
3704
  STXException,
2955
3705
  STXConfigException,
2956
3706
  STXAPIException,
@@ -2959,15 +3709,26 @@ export {
2959
3709
  STXForbiddenException,
2960
3710
  STXInvalidTokenException,
2961
3711
  STXInsufficientScopeException,
3712
+ STXTermsRequiredException,
3713
+ STXIPNotAllowedException,
2962
3714
  STXNotFoundException,
2963
3715
  STXRejectedException,
2964
- STXGeoLocationException,
2965
3716
  STXRateLimitException,
2966
3717
  STXServerException,
2967
3718
  STXTransportException,
2968
3719
  STXChannelException,
2969
3720
  STXTimeoutException,
3721
+ notAvailableMessage,
3722
+ STXNotAvailableException,
3723
+ STXCombosUnavailableException,
3724
+ isEdgeBlock,
3725
+ STXComboRefusedException,
3726
+ STXComboPriceMovedException,
2970
3727
  errorForStatus,
3728
+ FEATURES,
3729
+ Capabilities,
3730
+ Region,
3731
+ Environment,
2971
3732
  Environments,
2972
3733
  HOSTS,
2973
3734
  environmentNamed,
@@ -2995,6 +3756,8 @@ export {
2995
3756
  USER_AGENT,
2996
3757
  TERMINAL_ORDER_STATUSES,
2997
3758
  AccountView,
3759
+ ComboPlayer,
3760
+ ComboMaker,
2998
3761
  centsToDollars,
2999
3762
  toDollarString,
3000
3763
  toQuantity,
@@ -3010,4 +3773,4 @@ export {
3010
3773
  orderBody,
3011
3774
  STX
3012
3775
  };
3013
- //# sourceMappingURL=chunk-4CSBA2YV.js.map
3776
+ //# sourceMappingURL=chunk-FTZCBXT7.js.map