@ufcalendar/sdk 0.2.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  // src/version.ts
2
- var VERSION = "0.2.1";
2
+ var VERSION = "0.6.0";
3
3
 
4
4
  // src/client.ts
5
5
  var DEFAULT_BASE_URL = "https://api.ufcalendar.com/v1";
6
+ var LIVE_WS_URL = "wss://live.ufcalendar.com/v1";
6
7
  var DEFAULT_TIMEOUT_MS = 3e4;
7
8
  var FightAPIError = class extends Error {
8
9
  status;
@@ -145,40 +146,211 @@ var FightAPI = class {
145
146
  return (await this.#request("GET", "plans", { open: true })).data;
146
147
  }
147
148
  /* ---------------------------------------------------------------- orgs */
148
- /** Launch orgs with capability flags (stats / rounds / rankings / broadcasts / predictions). */
149
+ /** Launch orgs with capability flags (stats / rounds / rankings / broadcasts / predictions / scorecards / odds). */
149
150
  orgs() {
150
151
  return this.get("orgs");
151
152
  }
152
153
  org(slug) {
153
154
  return this.get(`orgs/${encodeURIComponent(slug)}`);
154
155
  }
156
+ /**
157
+ * One weight class in one promotion: its rankings board (null where the
158
+ * promotion publishes none), upcoming bouts at that weight, the latest
159
+ * results and the roster by recency. `division` is a slug, e.g.
160
+ * `lightweight` or `womens-strawweight`.
161
+ */
162
+ orgDivision(org, division) {
163
+ return this.get(`orgs/${encodeURIComponent(org)}/divisions/${encodeURIComponent(division)}`);
164
+ }
155
165
  /* -------------------------------------------------------------- events */
156
166
  /**
157
167
  * Schedule + results. Bare call = the upcoming calendar, soonest first.
158
168
  * `status: 'completed'` (or `order: 'desc'`) browses the archive
159
- * newest-first. `from` / `to` are `YYYY-MM-DD`.
169
+ * newest-first; `status: 'upcoming'` = every card not yet over (announced,
170
+ * scheduled or live). `from` / `to` are `YYYY-MM-DD`.
160
171
  */
161
172
  events(opts = {}) {
162
- const { limit, ...params } = opts;
163
- return this.#paginate("events", params, { limit });
173
+ const { limit, isTitleCard, isPpv, include, ...params } = opts;
174
+ return this.#paginate("events", {
175
+ ...params,
176
+ is_title_card: isTitleCard,
177
+ is_ppv: isPpv,
178
+ include: include?.length ? include.join(",") : void 0
179
+ }, { limit });
164
180
  }
165
- /** One event with its full fight card, venue and broadcasts. */
166
- event(idOrSlug) {
167
- return this.get(`events/${encodeURIComponent(String(idOrSlug))}`);
181
+ /**
182
+ * One event with its full fight card, venue and broadcasts.
183
+ * `include: ['eta']` adds an estimated start time to every bout;
184
+ * `include: ['odds']` adds each bout's current consensus line (the closing line once settled) (null when
185
+ * unpriced). Pass both as `['eta', 'odds']`.
186
+ */
187
+ event(idOrSlug, opts = {}) {
188
+ return this.get(
189
+ `events/${encodeURIComponent(String(idOrSlug))}`,
190
+ opts.include?.length ? { include: opts.include.join(",") } : void 0
191
+ );
192
+ }
193
+ /**
194
+ * Who airs one event, per country: the promotion's rights deals for the
195
+ * event's series merged with the event's own listings. `country` (ISO-2)
196
+ * narrows to that market plus worldwide.
197
+ */
198
+ eventWatch(idOrSlug, opts = {}) {
199
+ return this.get(`events/${encodeURIComponent(String(idOrSlug))}/watch`, opts);
200
+ }
201
+ /**
202
+ * The talking points of one card as of its start: title fights and
203
+ * eliminators, the closest bout (UFCalendar model, else Power Index — not
204
+ * betting advice), rematches and trilogy deciders, streaks, debuts and
205
+ * returns, ranked fighters, nations, tallest / longest reach, the fastest
206
+ * career finish.
207
+ */
208
+ eventStorylines(idOrSlug) {
209
+ return this.get(`events/${encodeURIComponent(String(idOrSlug))}/storylines`);
210
+ }
211
+ /**
212
+ * How the UFCalendar community is picking each bout on one card: picks per
213
+ * corner, the total and `pct_a`, in card order. Crowd sentiment from our
214
+ * own pick'em game, not a market and not a forecast.
215
+ */
216
+ eventPickem(idOrSlug) {
217
+ return this.get(`events/${encodeURIComponent(String(idOrSlug))}/pickem`);
218
+ }
219
+ /**
220
+ * The UFCalendar consensus odds for every non-cancelled bout on one card, in
221
+ * card order: `consensus`, `opening`, `closing` (settled bouts), `movement`
222
+ * and `points`. Unpriced bouts stay on the list with nulls and `points: 0`;
223
+ * `lastMeta.priced` / `lastMeta.unpriced` count both. Information only, not
224
+ * betting advice.
225
+ */
226
+ eventOdds(idOrSlug) {
227
+ return this.get(`events/${encodeURIComponent(String(idOrSlug))}/odds`);
168
228
  }
169
229
  /** Card-change diff log (fight added/removed, opponent swapped, date moved, profile merged). */
170
230
  eventChanges(idOrSlug) {
171
231
  return this.get(`events/${encodeURIComponent(String(idOrSlug))}/changes`);
172
232
  }
173
- /** Latest real-time LiveState snapshot on fight night (Business+), or null
174
- * when nothing is being streamed. The WebSocket at wss://live.ufcalendar.com/v1
175
- * pushes the same document as it changes. */
233
+ /**
234
+ * The card-change feed across every event, newest first (default: the last
235
+ * 90 days) — the `card.changed` webhook's audit trail, for callers that
236
+ * poll. `since` is `YYYY-MM-DD` or an ISO-8601 datetime.
237
+ */
238
+ changes(opts = {}) {
239
+ const { limit, ...params } = opts;
240
+ return this.#paginate("changes", params, { limit });
241
+ }
242
+ /** Latest real-time LiveState snapshot on fight night (Pro plans and up), or
243
+ * null when nothing is being streamed. The WebSocket at
244
+ * wss://live.ufcalendar.com/v1 pushes the same document as it changes — see
245
+ * `subscribeLive()`. */
176
246
  eventLive(idOrSlug) {
177
247
  return this.get(`events/${encodeURIComponent(String(idOrSlug))}/live`);
178
248
  }
249
+ /**
250
+ * Subscribe to the live WebSocket and receive every frame (Pro plans and up).
251
+ *
252
+ * The UFC live API: opens `wss://live.ufcalendar.com/v1?key=…`, sends
253
+ * `{"action":"subscribe","event":<slug>}` and calls `onFrame` with each
254
+ * `LiveFrame` — round, running clock, unofficial in-fight statistics and the
255
+ * action timeline, the same `LiveState` `eventLive()` returns.
256
+ *
257
+ * ```ts
258
+ * const stop = api.subscribeLive('ufc-331', (f) => console.log(f.type), { until: 'final' });
259
+ * ```
260
+ *
261
+ * Uses the global `WebSocket` (browser, Node >= 22) unless you inject one
262
+ * (`ws` on older Node). A dropped socket reconnects and re-subscribes ONCE.
263
+ *
264
+ * @returns an unsubscribe function — call it to close the socket for good.
265
+ */
266
+ subscribeLive(event, onFrame, opts = {}) {
267
+ const Impl = opts.WebSocketImpl ?? globalThis.WebSocket;
268
+ if (!Impl) {
269
+ throw new Error(
270
+ "subscribeLive() needs a WebSocket: use Node >= 22 (or a browser), or pass { WebSocketImpl } \u2014 e.g. `import WebSocket from 'ws'`."
271
+ );
272
+ }
273
+ if (!this.apiKey) {
274
+ throw new Error(
275
+ "No API key. The live stream authenticates with ?key=. Keys (and the free 1-day trial) live at https://www.ufcalendar.com/account/api"
276
+ );
277
+ }
278
+ const url = `${LIVE_WS_URL}?key=${encodeURIComponent(this.apiKey)}`;
279
+ let done = false;
280
+ let reconnects = 0;
281
+ let sock = null;
282
+ const open = () => {
283
+ const ws = new Impl(url);
284
+ sock = ws;
285
+ ws.onopen = () => {
286
+ try {
287
+ ws.send(JSON.stringify({ action: "subscribe", event }));
288
+ } catch {
289
+ }
290
+ };
291
+ ws.onmessage = (ev) => {
292
+ let frame;
293
+ try {
294
+ frame = JSON.parse(typeof ev.data === "string" ? ev.data : String(ev.data));
295
+ } catch {
296
+ return;
297
+ }
298
+ if (!frame || typeof frame !== "object") return;
299
+ onFrame(frame);
300
+ if (opts.until === "final" && frame.type === "fight.final") {
301
+ done = true;
302
+ try {
303
+ ws.close();
304
+ } catch {
305
+ }
306
+ }
307
+ };
308
+ ws.onclose = () => {
309
+ if (done || reconnects >= 1) return;
310
+ reconnects += 1;
311
+ open();
312
+ };
313
+ };
314
+ open();
315
+ return () => {
316
+ done = true;
317
+ try {
318
+ sock?.close();
319
+ } catch {
320
+ }
321
+ };
322
+ }
179
323
  /* -------------------------------------------------------------- fights */
180
- fight(fightId) {
181
- return this.get(`fights/${encodeURIComponent(String(fightId))}`);
324
+ /** One bout with its result. `include: ['odds']` adds the current consensus line (the closing line once the bout is settled). */
325
+ fight(fightId, opts = {}) {
326
+ return this.get(
327
+ `fights/${encodeURIComponent(String(fightId))}`,
328
+ opts.include?.length ? { include: opts.include.join(",") } : void 0
329
+ );
330
+ }
331
+ /**
332
+ * The UFCalendar consensus line for one bout: `consensus` (latest point; the closing line once settled),
333
+ * `opening`, `closing` (the last point at or before the event start,
334
+ * settled bouts only), `movement` (opening → consensus in implied-probability
335
+ * points on corner a) and `sources` on every point (how many sportsbooks
336
+ * backed it; book identities are never exposed). An unpriced bout resolves
337
+ * with null blocks and `points: 0`. Information only, not betting advice.
338
+ */
339
+ fightOdds(fightId) {
340
+ return this.get(`fights/${encodeURIComponent(String(fightId))}/odds`);
341
+ }
342
+ /**
343
+ * Every consensus point for one bout, oldest first (Pro plans and up; a
344
+ * lower plan throws `FightAPIError` 403 `tier_required`). A point is stored
345
+ * only when the consensus moves. `from` / `to` are inclusive `YYYY-MM-DD`.
346
+ */
347
+ fightOddsHistory(fightId, opts = {}) {
348
+ const { limit, ...params } = opts;
349
+ return this.#paginate(
350
+ `fights/${encodeURIComponent(String(fightId))}/odds/history`,
351
+ params,
352
+ { limit }
353
+ );
182
354
  }
183
355
  /** Per-fight totals for both corners. */
184
356
  fightStats(fightId) {
@@ -201,6 +373,22 @@ var FightAPI = class {
201
373
  fightScorecards(fightId) {
202
374
  return this.get(`fights/${encodeURIComponent(String(fightId))}/scorecards`);
203
375
  }
376
+ /**
377
+ * Completed bouts, filtered — newest first unless `order: 'oldest'`. At
378
+ * least one narrowing filter is required (`titleOnly`, `method`,
379
+ * `division`, `fighter`, `winner`, `from`, `to`, `mainEventsOnly`); the
380
+ * server serves 25 rows a page and at most 10 pages.
381
+ */
382
+ findFights(opts = {}) {
383
+ const { limit, titleOnly, mainEventsOnly, fighter, winner, ...rest } = opts;
384
+ return this.#paginate("fights/search", {
385
+ ...rest,
386
+ title_only: titleOnly,
387
+ main_events_only: mainEventsOnly,
388
+ fighter: fighter === void 0 ? void 0 : String(fighter),
389
+ winner: winner === void 0 ? void 0 : String(winner)
390
+ }, { limit });
391
+ }
204
392
  /* -------------------------------------------------------------- judges */
205
393
  /**
206
394
  * Every official who has scored a launch-org bout, busiest first. Rates
@@ -213,7 +401,18 @@ var FightAPI = class {
213
401
  judge(judgeId) {
214
402
  return this.get(`judges/${encodeURIComponent(String(judgeId))}`);
215
403
  }
216
- /** Every card this judge has turned in, newest first. */
404
+ /**
405
+ * Split and majority decisions, newest first, with every judge's card and
406
+ * the dissenting judges named. Commission records only.
407
+ */
408
+ splitDecisions(opts = {}) {
409
+ const { limit, ...params } = opts;
410
+ return this.#paginate("scorecards/splits", params, { limit });
411
+ }
412
+ /**
413
+ * Every card this judge has turned in, newest first, with `lone_dissent`,
414
+ * `split` and the `colleagues`' totals on each row.
415
+ */
217
416
  judgeScorecards(judgeId, opts = {}) {
218
417
  return this.#paginate(
219
418
  `judges/${encodeURIComponent(String(judgeId))}/scorecards`,
@@ -226,27 +425,53 @@ var FightAPI = class {
226
425
  const { limit, ...params } = opts;
227
426
  return this.#paginate("fighters", params, { limit });
228
427
  }
229
- /** Bio, records, career stats, Power Index and CC-licensed images. */
230
- fighter(idOrSlug) {
231
- return this.get(`fighters/${encodeURIComponent(String(idOrSlug))}`);
428
+ /**
429
+ * Bio, records, career stats, Power Index, CC-licensed images, `next_fight`
430
+ * and `last_fight`. `include: ['bonuses']` adds the UFC bonus ledger;
431
+ * `include: ['credentials']` adds grappling and wrestling pedigree, gyms and
432
+ * coaches (every row with `sources` and a `confidence` grade).
433
+ */
434
+ fighter(idOrSlug, opts = {}) {
435
+ return this.get(
436
+ `fighters/${encodeURIComponent(String(idOrSlug))}`,
437
+ opts.include?.length ? { include: opts.include.join(",") } : void 0
438
+ );
232
439
  }
233
440
  /** Complete multi-promotion career timeline. */
234
441
  fighterHistory(idOrSlug) {
235
442
  return this.get(`fighters/${encodeURIComponent(String(idOrSlug))}/history`);
236
443
  }
237
- /** Career statistics, one source-stamped row per scope (`pro-mma`, `ufc-only` …). */
444
+ /** Raw career stat rows, one source-stamped row per scope (`pro-mma`, `ufc-only` …).
445
+ * For the readable split use `fighter().records` / `fighter().stats`. */
238
446
  fighterStats(idOrSlug) {
239
447
  return this.get(`fighters/${encodeURIComponent(String(idOrSlug))}/stats`);
240
448
  }
241
- /** Every official ranking row the fighter ever held, newest first. */
242
- fighterRankings(idOrSlug) {
243
- return this.get(`fighters/${encodeURIComponent(String(idOrSlug))}/rankings`);
449
+ /** Every ranking row the fighter ever held, newest first, across every board
450
+ * (`board` is `official` / `meta`; `is_champion` when rank 0). The endpoint is
451
+ * cursor-paginated since 2026-09-24 — this walks every page so the array is
452
+ * complete (a long career is 900+ rows). */
453
+ async fighterRankings(idOrSlug) {
454
+ const out = [];
455
+ for await (const row of this.#paginate(
456
+ `fighters/${encodeURIComponent(String(idOrSlug))}/rankings`,
457
+ { limit: 500 }
458
+ )) out.push(row);
459
+ return out;
244
460
  }
245
461
  fighterPowerIndex(idOrSlug) {
246
462
  return this.get(
247
463
  `fighters/${encodeURIComponent(String(idOrSlug))}/power-index`
248
464
  );
249
465
  }
466
+ /**
467
+ * Two fighters side by side (slugs or ids): bios with age, career stats,
468
+ * strike mix, win streaks, previous meetings, common opponents, the booked
469
+ * bout between them, the UFCalendar model prediction for it (UFC; not
470
+ * betting advice) and Power Index ratings.
471
+ */
472
+ compare(a, b) {
473
+ return this.get("compare", { a: String(a), b: String(b) });
474
+ }
250
475
  /* ------------------------------------------------------------ rankings */
251
476
  /**
252
477
  * Official board, point-in-time. `date: 'YYYY-MM-DD'` returns the board
@@ -261,30 +486,123 @@ var FightAPI = class {
261
486
  opts
262
487
  );
263
488
  }
264
- /** Current champions across every launch org. */
265
- champions() {
266
- return this.get("champions");
489
+ /** Current champions across every launch org, or one `org` / `division`. */
490
+ champions(opts = {}) {
491
+ return this.get("champions", opts);
492
+ }
493
+ /**
494
+ * UFCalendar Power Index board. `view: 'movers'` = biggest risers over
495
+ * `days` (default 365), `view: 'peaks'` = all-time peak ratings;
496
+ * `division` narrows any view.
497
+ */
498
+ powerIndex(org = "ufc", opts = {}) {
499
+ return this.get(`power-index/${encodeURIComponent(org)}`, {
500
+ view: opts.view,
501
+ division: opts.division,
502
+ days: opts.days,
503
+ limit: opts.limit
504
+ });
505
+ }
506
+ /* ---------------------------------------------------------- matchmaker */
507
+ /**
508
+ * UFCalendar's matchmaker: the fights worth making in one MMA promotion,
509
+ * scored 0–100, across the roster or for one `division` (`lastMeta.divisions`
510
+ * lists the valid ones). Not a list of bookings; computed without the
511
+ * site's Fight DNA factor.
512
+ */
513
+ matchmaker(org = "ufc", opts = {}) {
514
+ return this.get(`matchmaker/${encodeURIComponent(org)}`, {
515
+ division: opts.division,
516
+ limit: opts.limit
517
+ });
267
518
  }
268
- /** UFCalendar Power Index board. */
269
- powerIndex(org = "ufc") {
270
- return this.get(`power-index/${encodeURIComponent(org)}`);
519
+ /**
520
+ * Who one fighter (slug or id) should fight next: the best-scored
521
+ * opponents with the Power Index win probability for each, plus the bout
522
+ * already booked (`booked_next`).
523
+ */
524
+ whosNext(fighter, opts = {}) {
525
+ return this.get(`matchmaker/next/${encodeURIComponent(String(fighter))}`, { limit: opts.limit });
526
+ }
527
+ /* --------------------------------------------------------------- stats */
528
+ /**
529
+ * One Record Book leaderboard for one promotion (`metric` e.g. `wins`,
530
+ * `fastest_knockout`, `finish_rate`). Narrow with `division` (slug),
531
+ * `country` (ISO-2) or `population: 'active'` — not `country` and
532
+ * `active` together. `lastMeta.metric` names the unit and what
533
+ * `value_secondary` means.
534
+ */
535
+ leaderboard(org, metric, opts = {}) {
536
+ return this.get("stats/leaders", { org, metric, ...opts });
537
+ }
538
+ /**
539
+ * Every leaderboard's top rows (`top`, default 10, max 25) for one
540
+ * promotion, grouped by category.
541
+ */
542
+ recordBook(org, opts = {}) {
543
+ return this.get("stats/record-book", { org, ...opts });
544
+ }
545
+ /**
546
+ * One calendar year in numbers for one promotion, or every covered
547
+ * promotion when `org` is omitted: events, title fights, finish methods,
548
+ * divisions, fastest finishes, upsets, Power Index climbers, busiest
549
+ * fighters, host countries and the most-used judges.
550
+ */
551
+ yearStats(year, opts = {}) {
552
+ return this.get(`stats/years/${encodeURIComponent(String(year))}`, opts);
271
553
  }
272
554
  /* ---------------------------------------------------------------- misc */
273
- /** Model win probabilities for upcoming UFC bouts. */
274
- predictionsUpcoming() {
275
- return this.get("predictions/upcoming");
555
+ /** Model win probabilities for upcoming UFC bouts; `event` narrows to one card. */
556
+ predictionsUpcoming(opts = {}) {
557
+ return this.get(
558
+ "predictions/upcoming",
559
+ opts.event !== void 0 ? { event: String(opts.event) } : void 0
560
+ );
276
561
  }
277
- /** Who airs the promotion, per ISO-2 country. */
562
+ /**
563
+ * Who airs the promotion, per ISO-2 country — the org-wide deals, or a UFC
564
+ * sub-series grid with `series: 'dwcs' | 'rtufc'`.
565
+ */
278
566
  broadcastRights(org = "ufc", opts = {}) {
279
567
  return this.get(`broadcast-rights/${encodeURIComponent(org)}`, opts);
280
568
  }
569
+ /**
570
+ * Venues that hosted a covered promotion, alphabetical. `q` (2+ chars)
571
+ * matches name or city; `country` is an ISO-2 code or an English name.
572
+ */
573
+ venues(opts = {}) {
574
+ const { limit, ...params } = opts;
575
+ return this.#paginate("venues", params, { limit });
576
+ }
281
577
  venue(venueId) {
282
578
  return this.get(`venues/${encodeURIComponent(String(venueId))}`);
283
579
  }
580
+ /** Every covered event at one venue, newest first (`order: 'asc'` reverses). */
581
+ venueEvents(venueId, opts = {}) {
582
+ const { limit, ...params } = opts;
583
+ return this.#paginate(`venues/${encodeURIComponent(String(venueId))}/events`, params, { limit });
584
+ }
284
585
  /** Typeahead across fighters and events. */
285
586
  search(q) {
286
587
  return this.get("search", { q });
287
588
  }
589
+ /**
590
+ * UFCalendar's own editorial archive, newest first. `q` (2+ chars) matches
591
+ * title, summary or a tag; `tag` is exact; `locale` is one of the 13 site
592
+ * languages (English fallback).
593
+ */
594
+ articles(opts = {}) {
595
+ const { limit, ...params } = opts;
596
+ return this.#paginate("articles", params, { limit });
597
+ }
598
+ /**
599
+ * One article: full Markdown `body_md` (client widgets removed), author,
600
+ * tags, `published_at`; `served_locale` names the language
601
+ * delivered.
602
+ */
603
+ article(slug, opts = {}) {
604
+ return this.get(`articles/${encodeURIComponent(slug)}`, opts);
605
+ }
288
606
  /** Your key's month-to-date quota usage. */
289
607
  usage() {
290
608
  return this.get("usage");
@@ -312,8 +630,10 @@ var FightAPI = class {
312
630
  }
313
631
  /**
314
632
  * Register a signed webhook (Pro and up). `events` ⊆ `event.announced`,
315
- * `fight.result`, `card.changed`, `event.completed`. The signing secret is
316
- * returned ONCE, in this response.
633
+ * `fight.result`, `card.changed`, `event.completed`, `odds.moved` (the
634
+ * consensus line on an upcoming bout moved 5+ implied-probability points or
635
+ * the favourite flipped). The signing secret is returned ONCE, in this
636
+ * response.
317
637
  */
318
638
  async createWebhookEndpoint(url, events) {
319
639
  const body = { url };
@@ -334,6 +654,7 @@ export {
334
654
  DEFAULT_BASE_URL,
335
655
  FightAPI,
336
656
  FightAPIError,
657
+ LIVE_WS_URL,
337
658
  VERSION
338
659
  };
339
660
  //# sourceMappingURL=index.js.map