@stxapp/stx-typescript 0.9.0-alpha.1 → 0.9.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,13 +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
1
  // src/geo.ts
12
2
  var IP_NOT_ALLOWED = /from this IP address (\S+?) is disallowed/i;
13
3
  function geoRejection(message) {
@@ -68,6 +58,16 @@ var STXInvalidTokenException = class extends STXAuthenticationException {
68
58
  };
69
59
  var STXInsufficientScopeException = class extends STXForbiddenException {
70
60
  };
61
+ var STXTermsRequiredException = class extends STXForbiddenException {
62
+ /** The STX page where the member accepts the terms, when the answer names it. */
63
+ termsUrl;
64
+ constructor(message, opts = {}) {
65
+ super(message, opts);
66
+ this.termsUrl = opts.termsUrl;
67
+ }
68
+ };
69
+ var STXIPNotAllowedException = class extends STXForbiddenException {
70
+ };
71
71
  var STXNotFoundException = class extends STXAPIException {
72
72
  };
73
73
  var STXRejectedException = class extends STXAPIException {
@@ -114,6 +114,87 @@ var STXChannelException = class extends STXException {
114
114
  };
115
115
  var STXTimeoutException = class extends STXChannelException {
116
116
  };
117
+ var NOT_AVAILABLE = /* @__PURE__ */ Symbol.for("@stxapp/stx-typescript.notAvailable");
118
+ var FEATURE_PHRASES = {
119
+ oauth: "OAuth is",
120
+ "oauth.member": "Member sign-in with OAuth is",
121
+ "oauth.app": "App tokens are",
122
+ connect: "Sign in with STX is",
123
+ "terms.stx_page": "Accepting terms on an STX page is",
124
+ "markets.create": "Creating markets is",
125
+ market_types: "Market types are",
126
+ event_players: "Event players are",
127
+ leaderboard: "The leaderboard is",
128
+ combos: "Combos are"
129
+ };
130
+ function notAvailableMessage(feature, host) {
131
+ const phrase = feature.startsWith("scope:") ? `The ${feature.slice("scope:".length)} scope is` : FEATURE_PHRASES[feature] ?? `${feature} is`;
132
+ return `${phrase} not available on ${host} yet.`;
133
+ }
134
+ var STXNotAvailableException = class _STXNotAvailableException extends STXAPIException {
135
+ /** The feature id, e.g. `"combos"`. */
136
+ feature;
137
+ /** The exchange host that lacks it, e.g. `"demo.stxapp.ca"`. */
138
+ host;
139
+ constructor(feature, host, opts = {}) {
140
+ super(opts.message ?? notAvailableMessage(feature, host), opts);
141
+ this.feature = feature;
142
+ this.host = host;
143
+ markNotAvailable(this);
144
+ }
145
+ // `this` is the class on the right of `instanceof`: a subclass keeps the
146
+ // ordinary check, only the base class also accepts marked exceptions.
147
+ static [Symbol.hasInstance](value) {
148
+ const cls = this;
149
+ if (Function.prototype[Symbol.hasInstance].call(cls, value)) return true;
150
+ return cls === _STXNotAvailableException && typeof value === "object" && value !== null && value[NOT_AVAILABLE] === true;
151
+ }
152
+ };
153
+ function markNotAvailable(err) {
154
+ Object.defineProperty(err, NOT_AVAILABLE, { value: true, enumerable: false });
155
+ }
156
+ var STXCombosUnavailableException = class extends STXChannelException {
157
+ feature = "combos";
158
+ /** The exchange host that lacks combos. */
159
+ host;
160
+ constructor(message, opts = {}) {
161
+ super(message, opts);
162
+ this.host = opts.host ?? "";
163
+ markNotAvailable(this);
164
+ }
165
+ };
166
+ function isMissingRoute(err) {
167
+ if (!(err instanceof STXNotFoundException)) return false;
168
+ const body = err.body;
169
+ return !!body && typeof body === "object" && body.error === "not_found" && Object.keys(body).length === 1;
170
+ }
171
+ function isEdgeBlock(status, text) {
172
+ if (status !== 403) return false;
173
+ try {
174
+ JSON.parse(text);
175
+ return false;
176
+ } catch {
177
+ return true;
178
+ }
179
+ }
180
+ var STXComboRefusedException = class extends STXChannelException {
181
+ command;
182
+ code;
183
+ detail;
184
+ constructor(message, opts) {
185
+ super(message, opts);
186
+ this.command = opts.command;
187
+ this.code = opts.code;
188
+ this.detail = opts.detail;
189
+ }
190
+ };
191
+ var STXComboPriceMovedException = class extends STXComboRefusedException {
192
+ best;
193
+ constructor(message, opts) {
194
+ super(message, opts);
195
+ this.best = opts.best;
196
+ }
197
+ };
117
198
  function errorForStatus(statusCode, body, opts) {
118
199
  let message;
119
200
  if (body && typeof body === "object" && typeof body.error === "string") {
@@ -130,6 +211,16 @@ function errorForStatus(statusCode, body, opts) {
130
211
  case 401:
131
212
  return bearerError(opts.wwwAuthenticate) === "invalid_token" ? new STXInvalidTokenException(message, base) : new STXAuthenticationException(message, base);
132
213
  case 403: {
214
+ const fields = body && typeof body === "object" ? body : {};
215
+ if (fields.error === "ip_not_allowed") {
216
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
217
+ return new STXIPNotAllowedException(description, base);
218
+ }
219
+ if (fields.error === "terms_required") {
220
+ const description = typeof fields.error_description === "string" ? fields.error_description : message;
221
+ const termsUrl = typeof fields.terms_url === "string" ? fields.terms_url : void 0;
222
+ return new STXTermsRequiredException(description, { ...base, termsUrl });
223
+ }
133
224
  if (bearerError(opts.wwwAuthenticate) === "insufficient_scope" || /insufficient scope/i.test(message)) {
134
225
  return new STXInsufficientScopeException(message, {
135
226
  ...base,
@@ -168,6 +259,147 @@ function insufficientScopes(header, body) {
168
259
  return raw ? raw.split(/\s+/).filter(Boolean) : [];
169
260
  }
170
261
 
262
+ // src/capabilities.ts
263
+ var FEATURES = [
264
+ "oauth",
265
+ "oauth.member",
266
+ "oauth.app",
267
+ "connect",
268
+ "terms.stx_page",
269
+ "markets.create",
270
+ "market_types",
271
+ "event_players",
272
+ "leaderboard",
273
+ "combos"
274
+ ];
275
+ var MEMBER_SCOPES = [
276
+ "profile.read",
277
+ "balance.read",
278
+ "portfolio.read",
279
+ "orders.read",
280
+ "transfers.read",
281
+ "orders.write"
282
+ ];
283
+ var Capabilities = class {
284
+ /** The exchange host, e.g. `"demo.stxapp.io"`. */
285
+ host;
286
+ /** `GET /api_version`, e.g. `"3.3.196-rnd.9"`, or null when it did not answer. */
287
+ apiVersion;
288
+ /** When the checks ran. */
289
+ checkedAt;
290
+ /** The scopes the exchange's OAuth discovery document lists; empty without OAuth. */
291
+ scopesSupported;
292
+ /** Every feature and whether the exchange has it. */
293
+ features;
294
+ constructor(init) {
295
+ this.host = init.host;
296
+ this.apiVersion = init.apiVersion;
297
+ this.checkedAt = init.checkedAt;
298
+ this.scopesSupported = init.scopesSupported;
299
+ this.features = init.features;
300
+ }
301
+ /** True only when the exchange is known to have `feature`. */
302
+ has(feature) {
303
+ return this.features[feature] === true;
304
+ }
305
+ /**
306
+ * Throw `STXNotAvailableException` unless the exchange is known to have
307
+ * `feature`. A feature that could not be checked (`null`) does not throw:
308
+ * the call itself will say.
309
+ */
310
+ require(feature) {
311
+ if (this.features[feature] === false) throw new STXNotAvailableException(feature, this.host);
312
+ }
313
+ toJSON() {
314
+ return {
315
+ host: this.host,
316
+ apiVersion: this.apiVersion,
317
+ checkedAt: this.checkedAt.toISOString(),
318
+ scopesSupported: this.scopesSupported,
319
+ features: this.features
320
+ };
321
+ }
322
+ };
323
+ var NOBODY = "00000000-0000-0000-0000-000000000000";
324
+ function json(answer) {
325
+ if (!answer) return null;
326
+ try {
327
+ const parsed = JSON.parse(answer.text);
328
+ return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
329
+ } catch {
330
+ return null;
331
+ }
332
+ }
333
+ function strings(value) {
334
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
335
+ }
336
+ function missingRoute(answer) {
337
+ if (!answer || answer.status !== 404) return false;
338
+ const body = json(answer);
339
+ return !!body && body.error === "not_found" && Object.keys(body).length === 1;
340
+ }
341
+ function oauthMetadataFrom(answer) {
342
+ if (!answer) return null;
343
+ const body = json(answer);
344
+ if (answer.status === 404) return false;
345
+ if (answer.status === 403 && !body) return false;
346
+ if (answer.status !== 200 || !body) return null;
347
+ if (typeof body.issuer !== "string" || typeof body.authorization_endpoint !== "string" || typeof body.token_endpoint !== "string") {
348
+ return null;
349
+ }
350
+ return body;
351
+ }
352
+ async function discoverCapabilities(probes) {
353
+ const swallow = (p) => p ? p.catch(() => null) : Promise.resolve(null);
354
+ const [version, discovery, types, players, board, combos] = await Promise.all([
355
+ swallow(probes.get("/api_version")),
356
+ swallow(probes.get("/.well-known/oauth-authorization-server")),
357
+ swallow(probes.signedGet("/api/v1/types")),
358
+ swallow(probes.signedGet(`/api/v1/events/${NOBODY}/players`)),
359
+ swallow(probes.signedGet("/api/v1/leaderboard?limit=1")),
360
+ swallow(probes.joinReason(`rfq:${NOBODY}`))
361
+ ]);
362
+ const apiVersion = json(version)?.api_version;
363
+ const meta = oauthMetadataFrom(discovery);
364
+ const scopes = meta ? strings(meta.scopes_supported) : [];
365
+ const grants = meta ? strings(meta.grant_types_supported) : [];
366
+ const fromMeta = (decide) => meta === null ? null : meta === false ? false : decide();
367
+ const oauth = fromMeta(() => true);
368
+ const member = fromMeta(() => grants.includes("authorization_code") && scopes.some((s) => MEMBER_SCOPES.includes(s)));
369
+ const app = fromMeta(() => grants.includes("client_credentials"));
370
+ const features = {
371
+ oauth,
372
+ "oauth.member": member,
373
+ "oauth.app": app,
374
+ connect: fromMeta(() => scopes.includes("openid")),
375
+ "terms.stx_page": fromMeta(() => member === true && !scopes.includes("terms.write")),
376
+ "markets.create": fromMeta(() => app === true && scopes.includes("markets.write")),
377
+ market_types: types === null ? null : types.status >= 200 && types.status < 300 ? true : missingRoute(types) ? false : null,
378
+ // A 404 about the event (not about the route) means the route is there.
379
+ event_players: players === null ? null : missingRoute(players) ? false : players.status === 404 || players.status < 300 ? true : null,
380
+ // Switched off answers 404 too ("Leaderboard is not enabled").
381
+ leaderboard: board === null ? null : board.status >= 200 && board.status < 300 ? true : board.status === 404 ? false : null,
382
+ combos: combos === null ? null : combos !== "unmatched topic"
383
+ };
384
+ return new Capabilities({
385
+ host: probes.host,
386
+ apiVersion: typeof apiVersion === "string" ? apiVersion : null,
387
+ checkedAt: /* @__PURE__ */ new Date(),
388
+ scopesSupported: scopes,
389
+ features
390
+ });
391
+ }
392
+
393
+ // src/enums.ts
394
+ var Region = {
395
+ US: "us",
396
+ ONTARIO: "ontario"
397
+ };
398
+ var Environment = {
399
+ PRODUCTION: "production",
400
+ DEMO: "demo"
401
+ };
402
+
171
403
  // src/config.ts
172
404
  var Environments = {
173
405
  /** United States demo. Shared by every integrator. No real money. */
@@ -641,16 +873,24 @@ function isValidLine(line) {
641
873
  return typeof line === "number" && Number.isFinite(line) && line > 0 && line * 2 % 2 === 1;
642
874
  }
643
875
  function marketEntry(m) {
644
- return Object.fromEntries(Object.entries(m).map(([k, v]) => [k.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`), v]));
876
+ return { rule: m.rule ?? "player_stat_line", player_id: m.playerId, stat: m.stat, line: m.line };
645
877
  }
646
- function toCreateMarketResult(raw, index) {
647
- return { ...raw, index, market_id: raw.market_id ?? null, reason: raw.reason ?? null };
878
+ function toCreateMarketResult(raw, m, index) {
879
+ const market = marketEntry(m);
880
+ switch (raw.status) {
881
+ case "created":
882
+ case "exists":
883
+ return { index, status: raw.status, market_id: String(raw.market_id), reason: null, market };
884
+ case "valid":
885
+ return { index, status: "valid", market_id: null, reason: null, market };
886
+ default:
887
+ return rejected(m, index, raw.reason ?? "not_created");
888
+ }
648
889
  }
649
- function rejected(index, reason) {
650
- return { index, status: "rejected", market_id: null, reason };
890
+ function rejected(m, index, reason) {
891
+ return { index, status: "rejected", market_id: null, reason, market: marketEntry(m) };
651
892
  }
652
893
  function checkMarket(m, players) {
653
- if (m.rule !== "player_stat_line") return { market: m };
654
894
  if (!isValidLine(m.line)) return { reason: "invalid_line" };
655
895
  const stat = players.stats.find((s) => String(s.stat).toUpperCase() === String(m.stat).toUpperCase());
656
896
  if (!stat) return { reason: "unsupported_stat" };
@@ -969,7 +1209,7 @@ function credentialsFromSettings(keyId, privateKey, signer) {
969
1209
  }
970
1210
 
971
1211
  // src/version.ts
972
- var VERSION = "0.9.0-alpha.1";
1212
+ var VERSION = "0.9.0";
973
1213
  var USER_AGENT = `stx-typescript/${VERSION}`;
974
1214
  var ASYNC_DISPOSE = Symbol.asyncDispose ?? /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
975
1215
 
@@ -1156,6 +1396,303 @@ var AccountView = class {
1156
1396
  }
1157
1397
  };
1158
1398
 
1399
+ // src/combos.ts
1400
+ var COMBO_PLAYER_CHANNEL = "rfq";
1401
+ var COMBO_MAKER_CHANNEL = "combo_quote";
1402
+ var UNAVAILABLE_REASON = "unmatched topic";
1403
+ var ACCEPT_TIMEOUT_MS = 35e3;
1404
+ var HISTORY_SIZE = 1e3;
1405
+ var PLAYER_EVENTS = /* @__PURE__ */ new Set(["best_quote", "placed", "negotiation_closed"]);
1406
+ var MAKER_EVENTS = /* @__PURE__ */ new Set([
1407
+ "rfq_opened",
1408
+ "rfq_closed",
1409
+ "quote_accepted",
1410
+ "placed",
1411
+ "negotiation_closed"
1412
+ ]);
1413
+ function comboRefusal(command, topic, response, host = "") {
1414
+ const reply = response && typeof response === "object" ? response : {};
1415
+ const reason = typeof reply.reason === "string" ? reply.reason : void 0;
1416
+ if (reason === UNAVAILABLE_REASON) {
1417
+ return new STXCombosUnavailableException(notAvailableMessage("combos", host || "this exchange"), {
1418
+ topic,
1419
+ reply: response,
1420
+ host
1421
+ });
1422
+ }
1423
+ if (reason === void 0) {
1424
+ return new STXComboRefusedException(`${command} on ${topic} failed: ${JSON.stringify(response)}`, {
1425
+ topic,
1426
+ reply: response,
1427
+ command,
1428
+ code: ""
1429
+ });
1430
+ }
1431
+ let code = reason;
1432
+ let detail;
1433
+ if (reason.startsWith("player_refused:")) {
1434
+ code = "player_refused";
1435
+ detail = reason.slice("player_refused:".length);
1436
+ }
1437
+ const message = `${command} on ${topic} refused: ${reason}`;
1438
+ if (code === "price_moved") {
1439
+ return new STXComboPriceMovedException(message, {
1440
+ topic,
1441
+ reply: response,
1442
+ command,
1443
+ code,
1444
+ best: {
1445
+ quote_id: reply.quote_id ?? null,
1446
+ amount: reply.amount ?? null,
1447
+ expires_at: reply.expires_at ?? null
1448
+ }
1449
+ });
1450
+ }
1451
+ return new STXComboRefusedException(message, { topic, reply: response, command, code, detail });
1452
+ }
1453
+ function comboJoinError(err, host = "") {
1454
+ if (err instanceof STXChannelException && !(err instanceof STXCombosUnavailableException) && err.reply !== void 0) {
1455
+ if (err.constructor !== STXChannelException) return err;
1456
+ return comboRefusal("phx_join", err.topic, err.reply, host);
1457
+ }
1458
+ return err;
1459
+ }
1460
+ async function comboJoinPayload(geo) {
1461
+ const packet = await resolveGeoLocation(geo);
1462
+ return packet === void 0 ? {} : { geo_location: packet };
1463
+ }
1464
+ function money(name, value) {
1465
+ if (typeof value !== "string") {
1466
+ throw new TypeError(`${name} must be a decimal string such as "250.00", got ${typeof value}`);
1467
+ }
1468
+ return value;
1469
+ }
1470
+ var ComboSession = class {
1471
+ /** The underlying channel. Its `reply` is the latest join reply. */
1472
+ channel;
1473
+ #onEvent;
1474
+ #history = [];
1475
+ #waiters = [];
1476
+ #events;
1477
+ /** @internal */
1478
+ constructor(channel, events, onEvent) {
1479
+ this.channel = channel;
1480
+ this.#events = events;
1481
+ this.#onEvent = onEvent;
1482
+ }
1483
+ /** Your account's pseudonym for counterparties, from the join reply. */
1484
+ get externalId() {
1485
+ return this.channel.reply.external_id ?? "";
1486
+ }
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
+ /** @internal */
1492
+ _typed(msg) {
1493
+ if (!this.#events.has(msg.event) || !msg.payload || typeof msg.payload !== "object") return void 0;
1494
+ return { event: msg.event, payload: msg.payload };
1495
+ }
1496
+ /** @internal Called for every message on the channel, before it is queued. */
1497
+ async _receive(msg) {
1498
+ const event = this._typed(msg);
1499
+ if (!event) return;
1500
+ this.#history.push(event);
1501
+ if (this.#history.length > HISTORY_SIZE) this.#history.shift();
1502
+ for (const w of [...this.#waiters]) {
1503
+ if (w.match(event)) {
1504
+ this.#waiters = this.#waiters.filter((x) => x !== w);
1505
+ w.resolve(event);
1506
+ }
1507
+ }
1508
+ if (this.#onEvent) await this.#onEvent(event);
1509
+ }
1510
+ /** The events received so far (the latest 1000), oldest first. */
1511
+ get events() {
1512
+ return [...this.#history];
1513
+ }
1514
+ /**
1515
+ * The next event, in arrival order. Rejects with `STXTimeoutException` when
1516
+ * none arrives within `timeoutMs`, and with `STXChannelException` once the
1517
+ * channel is closed. Use either this or `for await`, not both.
1518
+ */
1519
+ async next(timeoutMs) {
1520
+ for (; ; ) {
1521
+ const event = this._typed(await this.channel.next(timeoutMs));
1522
+ if (event) return event;
1523
+ }
1524
+ }
1525
+ async *[Symbol.asyncIterator]() {
1526
+ for await (const msg of this.channel) {
1527
+ const event = this._typed(msg);
1528
+ if (event) yield event;
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Resolve with the first event named `event` (or one of several) for
1533
+ * `rfqId`, looking first at events already received. Unlike `next()`, it
1534
+ * takes nothing from the queue. Rejects with `STXTimeoutException` after
1535
+ * `timeoutMs` (default 10000).
1536
+ *
1537
+ * @param event An event name, or several.
1538
+ * @param opts.rfqId Only events for this request.
1539
+ * @param opts.quoteId Only events for this quote (maker events).
1540
+ * @param opts.timeoutMs Milliseconds to wait. Default 10000.
1541
+ */
1542
+ waitFor(event, opts = {}) {
1543
+ const names = typeof event === "string" ? [event] : event;
1544
+ 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);
1545
+ const seen = this.#history.find(match);
1546
+ if (seen) return Promise.resolve(seen);
1547
+ const timeoutMs = opts.timeoutMs ?? 1e4;
1548
+ return new Promise((resolve, reject) => {
1549
+ const waiter = {
1550
+ match,
1551
+ resolve: (e) => {
1552
+ clearTimeout(timer);
1553
+ resolve(e);
1554
+ }
1555
+ };
1556
+ const timer = setTimeout(() => {
1557
+ this.#waiters = this.#waiters.filter((w) => w !== waiter);
1558
+ reject(
1559
+ new STXTimeoutException(`No ${names.join(" or ")} on ${this.channel.topic} within ${timeoutMs} ms`, {
1560
+ topic: this.channel.topic
1561
+ })
1562
+ );
1563
+ }, timeoutMs);
1564
+ this.#waiters.push(waiter);
1565
+ });
1566
+ }
1567
+ /**
1568
+ * Leave the topic. Requests opened and quotes placed on this channel end
1569
+ * (`cancelled`), as on any close, and delivery on this channel stops when
1570
+ * `leave()` resolves: the exchange's `negotiation_closed` for those requests
1571
+ * arrives after the channel has closed and is not passed to `onEvent` or to
1572
+ * an iterator. Treat every request still open here as cancelled once
1573
+ * `leave()` resolves. To see each request's own close first, `cancel()` it
1574
+ * and wait for its `negotiation_closed` before leaving. Other connections of
1575
+ * the same member still receive the close.
1576
+ */
1577
+ leave() {
1578
+ return this.channel.leave();
1579
+ }
1580
+ /** @internal Send a command and map a refusal to the combo exceptions. */
1581
+ async _command(command, payload, timeoutMs) {
1582
+ try {
1583
+ return await this.channel.push(command, payload, timeoutMs);
1584
+ } catch (err) {
1585
+ if (err instanceof STXChannelException && err.constructor === STXChannelException && err.reply !== void 0) {
1586
+ throw comboRefusal(command, this.channel.topic, err.reply);
1587
+ }
1588
+ throw err;
1589
+ }
1590
+ }
1591
+ };
1592
+ var ComboPlayer = class extends ComboSession {
1593
+ /** @internal */
1594
+ constructor(channel, onEvent) {
1595
+ super(channel, PLAYER_EVENTS, onEvent);
1596
+ }
1597
+ /**
1598
+ * `request_quote`: ask makers to quote on these legs for a stake. `amount`
1599
+ * is the stake as a decimal string in whole cents, e.g. `"250.00"`. Makers
1600
+ * quote what you win; quotes arrive as `best_quote` events.
1601
+ *
1602
+ * @param legs Two or more `open` markets and the outcome the combination needs of each.
1603
+ * @param amount The stake in dollars, e.g. `"250.00"`.
1604
+ */
1605
+ requestQuote(legs, amount2) {
1606
+ return this._command("request_quote", {
1607
+ legs: legs.map((leg) => ({ market_id: leg.marketId, outcome: leg.outcome })),
1608
+ amount: money("amount", amount2)
1609
+ });
1610
+ }
1611
+ /**
1612
+ * `cash_out`: ask makers to quote for what you hold of a combination, by the
1613
+ * `market_id` from `placed`. The exchange sets the size.
1614
+ *
1615
+ * @param marketId The combination's market id.
1616
+ */
1617
+ cashOut(marketId) {
1618
+ return this._command("cash_out", { market_id: marketId });
1619
+ }
1620
+ /**
1621
+ * `accept`: bind the request at `amount` or more, normally the amount
1622
+ * `best_quote` showed. The best live quote binds whoever made it, so the
1623
+ * placement can be better than `amount`. Waits up to 35 s.
1624
+ *
1625
+ * Throws `STXComboPriceMovedException` (with the live `best`) when nothing
1626
+ * at least as good is live; the request stays open and you can accept again.
1627
+ * The reply says what was placed; fills arrive on `fills`.
1628
+ *
1629
+ * @param rfqId The request.
1630
+ * @param quoteId The quote you saw, normally from `best_quote`.
1631
+ * @param amount The least amount you take, e.g. `"1750.00"`.
1632
+ */
1633
+ accept(rfqId, quoteId, amount2) {
1634
+ return this._command(
1635
+ "accept",
1636
+ { rfq_id: rfqId, quote_id: quoteId, amount: money("amount", amount2) },
1637
+ ACCEPT_TIMEOUT_MS
1638
+ );
1639
+ }
1640
+ /**
1641
+ * `cancel`: end the request and drop every quote on it.
1642
+ *
1643
+ * @param rfqId The request.
1644
+ */
1645
+ cancel(rfqId) {
1646
+ return this._command("cancel", { rfq_id: rfqId });
1647
+ }
1648
+ /**
1649
+ * `snapshot`: the request now, with the live best quote. Not delayed like `best_quote` events.
1650
+ *
1651
+ * @param rfqId The request.
1652
+ */
1653
+ snapshot(rfqId) {
1654
+ return this._command("snapshot", { rfq_id: rfqId });
1655
+ }
1656
+ };
1657
+ var ComboMaker = class extends ComboSession {
1658
+ /** @internal */
1659
+ constructor(channel, onEvent) {
1660
+ super(channel, MAKER_EVENTS, onEvent);
1661
+ }
1662
+ /**
1663
+ * `quote`: offer `amount` on a request. On a buy it is what the player wins;
1664
+ * on a cash out, what you pay for the whole size. Price it against the
1665
+ * request's `max_price` and `tick_size`. `expiresInMs` (a positive integer)
1666
+ * counts from receipt; the quote ends no later than its request.
1667
+ * `clientOrderId` (at most 255 bytes) is copied onto your order if it binds.
1668
+ *
1669
+ * @param rfqId The request, from `rfq_opened`.
1670
+ * @param amount In dollars, e.g. `"1750.00"`.
1671
+ * @param expiresInMs How long the quote stands, in milliseconds.
1672
+ * @param opts.clientOrderId Copied onto your order if the quote binds.
1673
+ */
1674
+ quote(rfqId, amount2, expiresInMs, opts = {}) {
1675
+ const payload = {
1676
+ rfq_id: rfqId,
1677
+ amount: money("amount", amount2),
1678
+ expires_in_ms: expiresInMs
1679
+ };
1680
+ if (opts.clientOrderId !== void 0) payload.client_order_id = opts.clientOrderId;
1681
+ return this._command("quote", payload);
1682
+ }
1683
+ /**
1684
+ * `withdraw_quote`: remove one of your quotes.
1685
+ *
1686
+ * @param rfqId The request.
1687
+ * @param quoteId Your quote, from the `quote()` reply.
1688
+ */
1689
+ withdrawQuote(rfqId, quoteId) {
1690
+ return this._command("withdraw_quote", { rfq_id: rfqId, quote_id: quoteId });
1691
+ }
1692
+ };
1693
+ var COMBO_CHANNELS = /* @__PURE__ */ new Set([COMBO_PLAYER_CHANNEL, COMBO_MAKER_CHANNEL]);
1694
+ var COMBOS_UNAVAILABLE_REASON = UNAVAILABLE_REASON;
1695
+
1159
1696
  // src/money.ts
1160
1697
  var PRICE_FIELDS = ["price", "last_traded_price", "max_price"];
1161
1698
  var QUANTITY_FIELDS = ["total_volume", "volume_24h", "open_interest"];
@@ -1409,6 +1946,15 @@ function ids(value) {
1409
1946
  return typeof value === "string" ? [value] : [...value];
1410
1947
  }
1411
1948
  var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
1949
+ var GATED_OPERATIONS = {
1950
+ types_get: "market_types",
1951
+ events__id_players_get: "event_players",
1952
+ markets_post: "markets.create",
1953
+ leaderboard_get: "leaderboard",
1954
+ leaderboard_me_get: "leaderboard",
1955
+ me_profile_patch: "leaderboard"
1956
+ };
1957
+ var LEADERBOARD_OFF = "Leaderboard is not enabled";
1412
1958
  var STX = class _STX {
1413
1959
  baseUrl;
1414
1960
  socketUrl;
@@ -1424,6 +1970,7 @@ var STX = class _STX {
1424
1970
  onResponse;
1425
1971
  #fetch;
1426
1972
  #me;
1973
+ #capabilities;
1427
1974
  /** Test hook: how retries wait. */
1428
1975
  _sleep = sleep;
1429
1976
  constructor(opts = {}) {
@@ -1477,6 +2024,74 @@ var STX = class _STX {
1477
2024
  toString() {
1478
2025
  return `STX(baseUrl=${JSON.stringify(this.baseUrl)}, keyId=${JSON.stringify(this.credentials?.keyId ?? null)})`;
1479
2026
  }
2027
+ /** The exchange host, e.g. `"demo.stxapp.io"`: the name `STXNotAvailableException` and `capabilities()` report. */
2028
+ get host() {
2029
+ return new URL(this.baseUrl).host;
2030
+ }
2031
+ // ------------------------------------------------------------------
2032
+ // Capabilities
2033
+ // ------------------------------------------------------------------
2034
+ /**
2035
+ * Which features this exchange has, from what it publishes: its OAuth
2036
+ * discovery document, `/api_version`, a signed GET of the routes that not
2037
+ * every exchange has yet, and a join of a combos topic nobody owns. Nothing
2038
+ * is created or changed. Checked once per client and cached; pass
2039
+ * `{ refresh: true }` to check again.
2040
+ *
2041
+ * const caps = await stx.capabilities();
2042
+ * caps.features.combos; // false on demo.stxapp.ca
2043
+ * caps.require("combos"); // throws STXNotAvailableException there
2044
+ *
2045
+ * Each feature is `true`, `false`, or `null` when it could not be checked
2046
+ * (no credentials for a signed check, or no answer). A missing feature never
2047
+ * throws here; the call that needs it throws `STXNotAvailableException`.
2048
+ */
2049
+ capabilities(opts = {}) {
2050
+ if (opts.refresh || !this.#capabilities) {
2051
+ const run = discoverCapabilities({
2052
+ host: this.host,
2053
+ get: (path) => this.#rawGet(path, false),
2054
+ signedGet: (path) => this.auth ? this.#rawGet(path, true) : null,
2055
+ joinReason: (topic) => this.#joinReason(topic)
2056
+ });
2057
+ this.#capabilities = run;
2058
+ run.catch(() => {
2059
+ if (this.#capabilities === run) this.#capabilities = void 0;
2060
+ });
2061
+ }
2062
+ return this.#capabilities;
2063
+ }
2064
+ async #rawGet(path, signed) {
2065
+ const headers = { "User-Agent": USER_AGENT, Accept: "application/json" };
2066
+ if (signed && this.auth) Object.assign(headers, await this.auth.authHeaders({ method: "GET", path }));
2067
+ const controller = new AbortController();
2068
+ const timer = setTimeout(() => controller.abort(), Math.min(this.timeoutMs, 15e3));
2069
+ try {
2070
+ const res = await this.#fetch(this.baseUrl + path, { method: "GET", headers, signal: controller.signal });
2071
+ return { status: res.status, text: await res.text() };
2072
+ } catch {
2073
+ return null;
2074
+ } finally {
2075
+ clearTimeout(timer);
2076
+ }
2077
+ }
2078
+ async #joinReason(topic) {
2079
+ if (!this.auth) return null;
2080
+ const ws = this.websocket({ reconnect: false, joinTimeoutMs: 8e3 });
2081
+ try {
2082
+ const channel = await ws.join(topic);
2083
+ await channel.leave().catch(() => {
2084
+ });
2085
+ return "ok";
2086
+ } catch (err) {
2087
+ if (err instanceof STXTimeoutException) return null;
2088
+ if (err instanceof STXChannelException) return err.reason ?? null;
2089
+ return null;
2090
+ } finally {
2091
+ await ws.close().catch(() => {
2092
+ });
2093
+ }
2094
+ }
1480
2095
  /** Nothing to release (fetch pools connections itself); present so `await using` and explicit cleanup work. */
1481
2096
  async close() {
1482
2097
  }
@@ -1575,7 +2190,22 @@ var STX = class _STX {
1575
2190
  }
1576
2191
  }
1577
2192
  async #call(operationId, args = {}) {
1578
- return this.#send(buildRequest(operationId, args));
2193
+ try {
2194
+ return await this.#send(buildRequest(operationId, args));
2195
+ } catch (err) {
2196
+ const feature = GATED_OPERATIONS[operationId];
2197
+ const off = feature === "leaderboard" && err instanceof STXNotFoundException && err.body?.error === LEADERBOARD_OFF;
2198
+ if (feature && (isMissingRoute(err) || off)) {
2199
+ throw new STXNotAvailableException(feature, this.host, {
2200
+ statusCode: err.statusCode,
2201
+ body: err.body,
2202
+ method: err.method,
2203
+ path: err.path,
2204
+ cause: err
2205
+ });
2206
+ }
2207
+ throw err;
2208
+ }
1579
2209
  }
1580
2210
  async #one(operationId, args = {}) {
1581
2211
  const body = await this.#call(operationId, args);
@@ -1727,16 +2357,18 @@ var STX = class _STX {
1727
2357
  * which STX grants, from an address on the client's IP allow-list (it
1728
2358
  * applies to every call that client makes).
1729
2359
  *
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).
2360
+ * Returns one result per market, in order: `created` or `exists` (both with
2361
+ * `market_id`), `valid` with `dryRun`, or `rejected` with a `reason`. Each
2362
+ * result's `index` is its position in `markets`, and `market` is that market
2363
+ * as requested. A rejected market is a
2364
+ * result, not an error, and resending is safe: a market that is already
2365
+ * listed comes back `exists`. A refused request throws (`403` without
2366
+ * `markets.write`, `404` unknown event, `422` event not open).
1736
2367
  *
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.
2368
+ * Each `line` must be a positive number ending in `.5`, e.g. `18.5`. More
2369
+ * than `MAX_MARKETS_PER_REQUEST` markets throws `TypeError` before any
2370
+ * request. `dryRun` runs every check and creates nothing. `validate` also
2371
+ * needs the `events` scope.
1740
2372
  */
1741
2373
  async createMarkets(eventId, markets, opts = {}) {
1742
2374
  if (markets.length < 1 || markets.length > MAX_MARKETS_PER_REQUEST) {
@@ -1749,24 +2381,20 @@ var STX = class _STX {
1749
2381
  send = send.flatMap(({ m, i }) => {
1750
2382
  const checked = checkMarket(m, players);
1751
2383
  if ("market" in checked) return [{ m: checked.market, i }];
1752
- results[i] = rejected(i, checked.reason);
2384
+ results[i] = rejected(m, i, checked.reason);
1753
2385
  return [];
1754
2386
  });
1755
2387
  }
1756
2388
  if (send.length) {
1757
- const body = {
1758
- event_id: eventId,
1759
- ...opts.dryRun ? { dry_run: true } : {},
1760
- markets: send.map(({ m }) => marketEntry(m))
1761
- };
2389
+ const body = { event_id: eventId, markets: send.map(({ m }) => marketEntry(m)) };
2390
+ if (opts.dryRun) body.dry_run = true;
1762
2391
  const raw = await this.#one("markets_post", { body });
1763
2392
  (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);
2393
+ const slot = send[typeof r.index === "number" ? r.index : k];
2394
+ if (slot) results[slot.i] = toCreateMarketResult(r, slot.m, slot.i);
1767
2395
  });
1768
2396
  }
1769
- return Array.from(results, (r, i) => r ?? rejected(i, "not_created"));
2397
+ return results.map((r, i) => r ?? rejected(markets[i], i, "not_created"));
1770
2398
  }
1771
2399
  // ------------------------------------------------------------------
1772
2400
  // Orders
@@ -1798,7 +2426,7 @@ var STX = class _STX {
1798
2426
  *
1799
2427
  * `action` is `"buy"` or `"sell"`; `orderType` is `"limit"` or `"market"`.
1800
2428
  * `price` (dollars, required for a limit order) and `quantity` (contracts)
1801
- * are decimal strings, e.g. `{ price: "0.56", quantity: "2" }`. Numbers are
2429
+ * are decimal strings, e.g. `{ price: "0.58", quantity: "100" }`. Numbers are
1802
2430
  * refused client-side.
1803
2431
  *
1804
2432
  * The exchange validates the order: a bad price step or a fractional
@@ -1994,9 +2622,41 @@ var STX = class _STX {
1994
2622
  return this.#iterate("portfolio_loyalty_get", { limit: query.limit });
1995
2623
  }
1996
2624
  // ------------------------------------------------------------------
2625
+ // Leaderboard and public profile
2626
+ // ------------------------------------------------------------------
2627
+ /**
2628
+ * `GET /api/v1/leaderboard`: ranked members for a period, sport and metric.
2629
+ * Rows carry a public handle and avatar, never an account id. Throws
2630
+ * `STXNotAvailableException` (feature `leaderboard`) where the exchange does
2631
+ * not have the leaderboard.
2632
+ */
2633
+ leaderboard(query = {}) {
2634
+ const { period, category, metric, limit } = query;
2635
+ return this.#one("leaderboard_get", { query: { period, category, metric, limit } });
2636
+ }
2637
+ /** `GET /api/v1/leaderboard/me`: your own standing, including your rank outside the list. */
2638
+ leaderboardMe(query = {}) {
2639
+ return this.#one("leaderboard_me_get", { query: { period: query.period, category: query.category } });
2640
+ }
2641
+ /**
2642
+ * `PATCH /api/v1/me/profile`: change your public handle, avatar or
2643
+ * leaderboard opt-in. Resolves to the updated `me`.
2644
+ */
2645
+ async updateProfile(update) {
2646
+ this.#me = await this.#one("me_profile_patch", { body: update });
2647
+ return this.#me;
2648
+ }
2649
+ // ------------------------------------------------------------------
1997
2650
  // Terms
1998
2651
  // ------------------------------------------------------------------
1999
- /** `POST /api/v1/tnc/accept`: accept the current terms. Resolves to the server's message. */
2652
+ /**
2653
+ * `POST /api/v1/tnc/accept`: accept the current terms for your own account,
2654
+ * with your own API key. Resolves to the server's message.
2655
+ *
2656
+ * An app cannot accept the terms for a member: called with a member's OAuth
2657
+ * access token, the exchange answers 403 `terms_not_delegable`
2658
+ * (`STXForbiddenException`). The member accepts on an STX page instead.
2659
+ */
2000
2660
  async acceptTerms(deviceId, opts = {}) {
2001
2661
  const body = {
2002
2662
  device_id: deviceId,
@@ -2110,6 +2770,7 @@ var MessageQueue = class {
2110
2770
  });
2111
2771
  }
2112
2772
  };
2773
+ var UNPINGED_CHANNELS = /* @__PURE__ */ new Set(["market", "rfq", "combo_quote"]);
2113
2774
  var Channel = class {
2114
2775
  /** The wire topic, e.g. `orders:<user_id>`. */
2115
2776
  topic;
@@ -2128,6 +2789,8 @@ var Channel = class {
2128
2789
  joinRef = null;
2129
2790
  joined = false;
2130
2791
  closed = false;
2792
+ /** @internal Runs before every (re)join, e.g. to refresh a geolocation packet in `joinPayload`. */
2793
+ _beforeJoin;
2131
2794
  #ws;
2132
2795
  #queue;
2133
2796
  #snapshotWaiters = [];
@@ -2583,6 +3246,63 @@ var STXWebSocket = class {
2583
3246
  return this.#joinAccount("user_info", {}, opts.onMessage);
2584
3247
  }
2585
3248
  // ------------------------------------------------------------------
3249
+ // Combos
3250
+ // ------------------------------------------------------------------
3251
+ /**
3252
+ * Join `rfq:{user_id}` and return a `ComboPlayer`: request quotes on a
3253
+ * combination, cash one out, accept, cancel and read a request.
3254
+ *
3255
+ * Available on US demo.
3256
+ * Where combos are not available, rejects with
3257
+ * `STXCombosUnavailableException`. Other join refusals (a read-only key, an
3258
+ * account that may not trade) reject with `STXComboRefusedException`.
3259
+ */
3260
+ async comboPlayer(opts = {}) {
3261
+ let player;
3262
+ const early = [];
3263
+ const channel = await this.#joinCombo(COMBO_PLAYER_CHANNEL, opts, async (msg) => {
3264
+ if (player) await player._receive(msg);
3265
+ else early.push(msg);
3266
+ });
3267
+ player = new ComboPlayer(channel, opts.onEvent);
3268
+ for (const msg of early) await player._receive(msg);
3269
+ return player;
3270
+ }
3271
+ /**
3272
+ * Join `combo_quote:{user_id}` and return a `ComboMaker`: receive every
3273
+ * request opened from now on (`rfq_opened`), quote and withdraw quotes.
3274
+ *
3275
+ * Available on US demo.
3276
+ * Where combos are not available, rejects with
3277
+ * `STXCombosUnavailableException`.
3278
+ */
3279
+ async comboMaker(opts = {}) {
3280
+ let maker;
3281
+ const early = [];
3282
+ const channel = await this.#joinCombo(COMBO_MAKER_CHANNEL, opts, async (msg) => {
3283
+ if (maker) await maker._receive(msg);
3284
+ else early.push(msg);
3285
+ });
3286
+ maker = new ComboMaker(channel, opts.onEvent);
3287
+ for (const msg of early) await maker._receive(msg);
3288
+ return maker;
3289
+ }
3290
+ async #joinCombo(name, opts, onMessage) {
3291
+ let channel;
3292
+ try {
3293
+ channel = await this.#joinAccount(name, await comboJoinPayload(opts.geoLocation), onMessage);
3294
+ } catch (err) {
3295
+ throw comboJoinError(err, new URL(this.rest.baseUrl).host);
3296
+ }
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
+ }
3305
+ // ------------------------------------------------------------------
2586
3306
  // Generic join
2587
3307
  // ------------------------------------------------------------------
2588
3308
  /**
@@ -2594,8 +3314,9 @@ var STXWebSocket = class {
2594
3314
  const existing = this.channels.get(topic);
2595
3315
  if (existing && !existing.closed) throw new STXChannelException(`Already joined ${topic}`, { topic });
2596
3316
  await this.connect();
3317
+ const name = topic.split(":", 1)[0];
2597
3318
  const channel = new Channel(this, topic, payload, onMessage, {
2598
- pingIntervalMs: opts.pingIntervalMs === void 0 ? this.channelPingIntervalMs : opts.pingIntervalMs,
3319
+ pingIntervalMs: opts.pingIntervalMs !== void 0 ? opts.pingIntervalMs : UNPINGED_CHANNELS.has(name) ? null : this.channelPingIntervalMs,
2599
3320
  queueSize: this.queueSize
2600
3321
  });
2601
3322
  this.channels.set(topic, channel);
@@ -2620,6 +3341,7 @@ var STXWebSocket = class {
2620
3341
  const ref = this.#nextRef();
2621
3342
  channel.joinRef = ref;
2622
3343
  channel._resetForRejoin();
3344
+ if (channel._beforeJoin) await channel._beforeJoin();
2623
3345
  const reply = await this._request(channel.topic, "phx_join", channel.joinPayload, ref, void 0, ref);
2624
3346
  channel.reply = reply && typeof reply === "object" && !Array.isArray(reply) ? reply : { response: reply };
2625
3347
  if (channel.name === "market") channel.reply = convertMarketChannelPayload(channel.reply);
@@ -2826,7 +3548,7 @@ var STXWebSocket = class {
2826
3548
  } catch (err) {
2827
3549
  this.logger.error(`rejoin ${channel.topic} failed: ${err.message}`);
2828
3550
  const reply = err instanceof STXChannelException ? err.reply : void 0;
2829
- if (reply?.reason === "unauthorized") {
3551
+ if (reply?.reason === "unauthorized" || reply?.reason === COMBOS_UNAVAILABLE_REASON && COMBO_CHANNELS.has(channel.name)) {
2830
3552
  channel._close();
2831
3553
  return;
2832
3554
  }
@@ -2948,8 +3670,6 @@ function dropUndefined(payload) {
2948
3670
  }
2949
3671
 
2950
3672
  export {
2951
- Region,
2952
- Environment,
2953
3673
  geoRejection,
2954
3674
  STXException,
2955
3675
  STXConfigException,
@@ -2959,6 +3679,8 @@ export {
2959
3679
  STXForbiddenException,
2960
3680
  STXInvalidTokenException,
2961
3681
  STXInsufficientScopeException,
3682
+ STXTermsRequiredException,
3683
+ STXIPNotAllowedException,
2962
3684
  STXNotFoundException,
2963
3685
  STXRejectedException,
2964
3686
  STXGeoLocationException,
@@ -2967,7 +3689,17 @@ export {
2967
3689
  STXTransportException,
2968
3690
  STXChannelException,
2969
3691
  STXTimeoutException,
3692
+ notAvailableMessage,
3693
+ STXNotAvailableException,
3694
+ STXCombosUnavailableException,
3695
+ isEdgeBlock,
3696
+ STXComboRefusedException,
3697
+ STXComboPriceMovedException,
2970
3698
  errorForStatus,
3699
+ FEATURES,
3700
+ Capabilities,
3701
+ Region,
3702
+ Environment,
2971
3703
  Environments,
2972
3704
  HOSTS,
2973
3705
  environmentNamed,
@@ -2995,6 +3727,8 @@ export {
2995
3727
  USER_AGENT,
2996
3728
  TERMINAL_ORDER_STATUSES,
2997
3729
  AccountView,
3730
+ ComboPlayer,
3731
+ ComboMaker,
2998
3732
  centsToDollars,
2999
3733
  toDollarString,
3000
3734
  toQuantity,
@@ -3010,4 +3744,4 @@ export {
3010
3744
  orderBody,
3011
3745
  STX
3012
3746
  };
3013
- //# sourceMappingURL=chunk-4CSBA2YV.js.map
3747
+ //# sourceMappingURL=chunk-46XK6VDD.js.map