odds-api-io 1.3.1 → 1.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +330 -245
  2. package/dist/cjs/client.d.ts +278 -0
  3. package/dist/cjs/client.js +536 -292
  4. package/dist/cjs/client.js.map +1 -1
  5. package/dist/cjs/errors.d.ts +63 -0
  6. package/dist/cjs/errors.js +54 -36
  7. package/dist/cjs/errors.js.map +1 -1
  8. package/dist/cjs/helpers.d.ts +5 -0
  9. package/dist/cjs/helpers.js +13 -0
  10. package/dist/cjs/helpers.js.map +1 -0
  11. package/dist/cjs/index.d.ts +15 -0
  12. package/dist/cjs/index.js +15 -3
  13. package/dist/cjs/index.js.map +1 -1
  14. package/dist/cjs/package.json +1 -0
  15. package/dist/cjs/types.d.ts +770 -0
  16. package/dist/cjs/types.js +4 -1
  17. package/dist/cjs/types.js.map +1 -1
  18. package/dist/cjs/version.d.ts +1 -0
  19. package/dist/cjs/version.js +5 -0
  20. package/dist/cjs/version.js.map +1 -0
  21. package/dist/cjs/websocket.d.ts +210 -0
  22. package/dist/cjs/websocket.js +405 -0
  23. package/dist/cjs/websocket.js.map +1 -0
  24. package/dist/esm/client.d.ts +278 -0
  25. package/dist/esm/client.js +537 -293
  26. package/dist/esm/client.js.map +1 -1
  27. package/dist/esm/errors.d.ts +63 -0
  28. package/dist/esm/errors.js +49 -34
  29. package/dist/esm/errors.js.map +1 -1
  30. package/dist/esm/helpers.d.ts +5 -0
  31. package/dist/esm/helpers.js +9 -0
  32. package/dist/esm/helpers.js.map +1 -0
  33. package/dist/esm/index.d.ts +15 -0
  34. package/dist/esm/index.js +5 -2
  35. package/dist/esm/index.js.map +1 -1
  36. package/dist/esm/package.json +1 -0
  37. package/dist/esm/types.d.ts +770 -0
  38. package/dist/esm/types.js +4 -1
  39. package/dist/esm/types.js.map +1 -1
  40. package/dist/esm/version.d.ts +1 -0
  41. package/dist/esm/version.js +2 -0
  42. package/dist/esm/version.js.map +1 -0
  43. package/dist/esm/websocket.d.ts +210 -0
  44. package/dist/esm/websocket.js +367 -0
  45. package/dist/esm/websocket.js.map +1 -0
  46. package/dist/types/client.d.ts +155 -195
  47. package/dist/types/client.d.ts.map +1 -1
  48. package/dist/types/errors.d.ts +48 -24
  49. package/dist/types/errors.d.ts.map +1 -1
  50. package/dist/types/helpers.d.ts +6 -0
  51. package/dist/types/helpers.d.ts.map +1 -0
  52. package/dist/types/index.d.ts +8 -3
  53. package/dist/types/index.d.ts.map +1 -1
  54. package/dist/types/types.d.ts +659 -187
  55. package/dist/types/types.d.ts.map +1 -1
  56. package/dist/types/version.d.ts +2 -0
  57. package/dist/types/version.d.ts.map +1 -0
  58. package/dist/types/websocket.d.ts +211 -0
  59. package/dist/types/websocket.d.ts.map +1 -0
  60. package/package.json +46 -16
@@ -2,477 +2,721 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.OddsAPIClient = void 0;
4
4
  const errors_js_1 = require("./errors.js");
5
- const DEFAULT_BASE_URL = 'https://api2.odds-api.io/v3';
5
+ const version_js_1 = require("./version.js");
6
+ const DEFAULT_BASE_URL = 'https://api.odds-api.io/v3';
6
7
  const DEFAULT_TIMEOUT = 10000;
8
+ const DEFAULT_MAX_RETRIES = 2;
9
+ const DEFAULT_MAX_RETRY_DELAY = 10000;
10
+ const HISTORICAL_SPAN_MS = 31 * 24 * 60 * 60 * 1000;
11
+ const SETTLEMENT_BATCH = 50;
12
+ function joinList(value) {
13
+ if (value === undefined || value === null)
14
+ return undefined;
15
+ return typeof value === 'string' ? value : value.join(',');
16
+ }
17
+ function splitList(value) {
18
+ const parts = typeof value === 'string' ? value.split(',') : value.map(String);
19
+ return parts.map((p) => p.trim()).filter(Boolean);
20
+ }
21
+ function numberHeader(headers, name) {
22
+ const raw = headers.get(name);
23
+ if (raw === null || raw.trim() === '')
24
+ return null;
25
+ const n = Number(raw);
26
+ return Number.isFinite(n) ? n : null;
27
+ }
28
+ function parseRateLimit(headers) {
29
+ const limit = numberHeader(headers, 'x-ratelimit-limit');
30
+ const remaining = numberHeader(headers, 'x-ratelimit-remaining');
31
+ const resetRaw = headers.get('x-ratelimit-reset');
32
+ if (limit === null && remaining === null && !resetRaw)
33
+ return undefined;
34
+ const reset = resetRaw ? new Date(resetRaw) : null;
35
+ return { limit, remaining, reset: reset && !isNaN(reset.getTime()) ? reset : null };
36
+ }
37
+ function retryAfterSeconds(headers, rateLimit) {
38
+ const header = headers.get('retry-after');
39
+ if (header) {
40
+ const secs = Number(header);
41
+ if (Number.isFinite(secs))
42
+ return Math.max(0, secs);
43
+ const date = Date.parse(header);
44
+ if (!isNaN(date))
45
+ return Math.max(0, Math.ceil((date - Date.now()) / 1000));
46
+ }
47
+ if (rateLimit?.remaining === 0 && rateLimit.reset) {
48
+ return Math.max(0, Math.ceil((rateLimit.reset.getTime() - Date.now()) / 1000));
49
+ }
50
+ return undefined;
51
+ }
52
+ function sleep(ms, signal) {
53
+ return new Promise((resolve) => {
54
+ if (signal?.aborted)
55
+ return resolve();
56
+ const timer = setTimeout(done, ms);
57
+ function done() {
58
+ clearTimeout(timer);
59
+ signal?.removeEventListener('abort', done);
60
+ resolve();
61
+ }
62
+ signal?.addEventListener('abort', done, { once: true });
63
+ });
64
+ }
7
65
  /**
8
- * Official Node.js client for Odds-API.io
66
+ * Official Node.js client for Odds-API.io.
9
67
  *
10
68
  * @example
11
69
  * ```typescript
12
70
  * import { OddsAPIClient } from 'odds-api-io';
13
71
  *
14
- * const client = new OddsAPIClient({ apiKey: 'your-api-key' });
72
+ * const client = new OddsAPIClient({ apiKey: process.env.ODDS_API_KEY! });
15
73
  * const sports = await client.getSports();
16
74
  * ```
17
75
  */
18
76
  class OddsAPIClient {
19
77
  constructor(config) {
20
78
  this.apiKey = config.apiKey;
21
- this.baseUrl = config.baseUrl || DEFAULT_BASE_URL;
22
- this.timeout = config.timeout || DEFAULT_TIMEOUT;
79
+ this.baseUrl = (config.baseUrl || DEFAULT_BASE_URL).replace(/\/+$/, '');
80
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT;
81
+ this.maxRetries = Math.max(0, config.maxRetries ?? DEFAULT_MAX_RETRIES);
82
+ this.maxRetryDelay = config.maxRetryDelay ?? DEFAULT_MAX_RETRY_DELAY;
83
+ this.fetchImpl = config.fetch;
23
84
  }
24
- /**
25
- * Make a GET request to the API
26
- */
27
- async request(path, params = {}, requiresAuth = false) {
85
+ buildUrl(path, query = {}, auth = true) {
28
86
  const url = new URL(`${this.baseUrl}/${path}`);
29
- // Add query parameters
30
- if (requiresAuth) {
31
- params.apiKey = this.apiKey;
87
+ for (const [key, value] of Object.entries(query)) {
88
+ if (value === undefined || value === null)
89
+ continue;
90
+ const str = Array.isArray(value) ? value.join(',') : String(value);
91
+ url.searchParams.set(key, str);
32
92
  }
33
- Object.entries(params).forEach(([key, value]) => {
34
- if (value !== undefined && value !== null) {
35
- url.searchParams.append(key, String(value));
36
- }
37
- });
38
- const controller = new AbortController();
39
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
40
- try {
41
- const response = await fetch(url.toString(), {
42
- method: 'GET',
43
- signal: controller.signal,
44
- headers: {
45
- 'User-Agent': 'odds-api-io-node-sdk/1.0.0',
46
- },
47
- });
48
- clearTimeout(timeoutId);
49
- if (!response.ok) {
50
- await this.handleErrorResponse(response);
93
+ if (auth)
94
+ url.searchParams.set('apiKey', this.apiKey);
95
+ return url;
96
+ }
97
+ async send(path, options = {}) {
98
+ const method = options.method ?? 'GET';
99
+ const url = this.buildUrl(path, options.query, options.auth ?? true);
100
+ const retries = method === 'PUT' ? 0 : this.maxRetries;
101
+ const doFetch = this.fetchImpl ?? globalThis.fetch;
102
+ for (let attempt = 0;; attempt++) {
103
+ const controller = new AbortController();
104
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
105
+ let response;
106
+ try {
107
+ const headers = { 'User-Agent': `odds-api-io-node/${version_js_1.VERSION}` };
108
+ let body;
109
+ if (options.body !== undefined) {
110
+ headers['Content-Type'] = 'application/json';
111
+ body = JSON.stringify(options.body);
112
+ }
113
+ response = await doFetch(url.toString(), { method, headers, body, signal: controller.signal });
51
114
  }
52
- return (await response.json());
53
- }
54
- catch (error) {
55
- clearTimeout(timeoutId);
56
- if (error.name === 'AbortError') {
57
- throw new errors_js_1.TimeoutError(`Request timeout after ${this.timeout}ms`);
115
+ catch (error) {
116
+ clearTimeout(timeoutId);
117
+ const err = error?.name === 'AbortError'
118
+ ? new errors_js_1.TimeoutError(`Request timeout after ${this.timeout}ms`)
119
+ : new errors_js_1.NetworkError(`Network request failed: ${error?.message ?? error}`);
120
+ if (attempt < retries) {
121
+ await sleep(this.backoff(attempt));
122
+ continue;
123
+ }
124
+ throw err;
58
125
  }
59
- if (error instanceof errors_js_1.OddsAPIError) {
126
+ try {
127
+ const rateLimit = parseRateLimit(response.headers);
128
+ if (rateLimit)
129
+ this.lastRateLimit = rateLimit;
130
+ if (response.ok) {
131
+ const data = options.raw ? await response.arrayBuffer() : await response.json();
132
+ return { data: data, headers: response.headers };
133
+ }
134
+ const error = await this.toError(response, rateLimit);
135
+ const wait = this.retryDelay(error, attempt);
136
+ if (attempt < retries && wait !== null) {
137
+ await sleep(wait);
138
+ continue;
139
+ }
60
140
  throw error;
61
141
  }
62
- throw new errors_js_1.NetworkError(`Network request failed: ${error.message}`);
63
- }
64
- }
65
- /**
66
- * Make a PUT request to the API
67
- */
68
- async requestPut(path, params = {}, requiresAuth = false) {
69
- const url = new URL(`${this.baseUrl}/${path}`);
70
- // Add query parameters
71
- if (requiresAuth) {
72
- params.apiKey = this.apiKey;
73
- }
74
- Object.entries(params).forEach(([key, value]) => {
75
- if (value !== undefined && value !== null) {
76
- url.searchParams.append(key, String(value));
142
+ catch (error) {
143
+ if (error instanceof errors_js_1.OddsAPIError)
144
+ throw error;
145
+ if (error?.name === 'AbortError')
146
+ throw new errors_js_1.TimeoutError(`Request timeout after ${this.timeout}ms`);
147
+ throw new errors_js_1.NetworkError(`Failed to read response: ${error?.message ?? error}`);
77
148
  }
78
- });
79
- const controller = new AbortController();
80
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
81
- try {
82
- const response = await fetch(url.toString(), {
83
- method: 'PUT',
84
- signal: controller.signal,
85
- headers: {
86
- 'User-Agent': 'odds-api-io-node-sdk/1.0.0',
87
- },
88
- });
89
- clearTimeout(timeoutId);
90
- if (!response.ok) {
91
- await this.handleErrorResponse(response);
149
+ finally {
150
+ clearTimeout(timeoutId);
92
151
  }
93
- return (await response.json());
94
152
  }
95
- catch (error) {
96
- clearTimeout(timeoutId);
97
- if (error.name === 'AbortError') {
98
- throw new errors_js_1.TimeoutError(`Request timeout after ${this.timeout}ms`);
99
- }
100
- if (error instanceof errors_js_1.OddsAPIError) {
101
- throw error;
102
- }
103
- throw new errors_js_1.NetworkError(`Network request failed: ${error.message}`);
153
+ }
154
+ backoff(attempt) {
155
+ const base = Math.min(this.maxRetryDelay, 500 * 2 ** attempt);
156
+ return Math.round(base * (0.75 + Math.random() * 0.25));
157
+ }
158
+ retryDelay(error, attempt) {
159
+ if (error instanceof errors_js_1.RateLimitError) {
160
+ if (error.retryAfter === undefined)
161
+ return null;
162
+ const ms = error.retryAfter * 1000;
163
+ return ms <= this.maxRetryDelay ? ms : null;
164
+ }
165
+ if (error instanceof errors_js_1.ServerError && [500, 502, 503, 504].includes(error.status ?? 0)) {
166
+ return error.retryAfter !== undefined
167
+ ? Math.min(error.retryAfter * 1000, this.maxRetryDelay)
168
+ : this.backoff(attempt);
104
169
  }
170
+ return null;
105
171
  }
106
- /**
107
- * Handle error responses from the API
108
- */
109
- async handleErrorResponse(response) {
172
+ async toError(response, rateLimit) {
110
173
  const status = response.status;
111
- let errorMessage;
174
+ let body = '';
112
175
  try {
113
- const errorBody = await response.text();
114
- errorMessage = errorBody || response.statusText;
176
+ body = await response.text();
115
177
  }
116
178
  catch {
117
- errorMessage = response.statusText;
179
+ body = '';
180
+ }
181
+ let message = body.trim() || response.statusText || `HTTP ${status}`;
182
+ try {
183
+ const parsed = JSON.parse(body);
184
+ if (parsed && typeof parsed.error === 'string')
185
+ message = parsed.error;
186
+ else if (parsed && typeof parsed.message === 'string')
187
+ message = parsed.message;
118
188
  }
189
+ catch {
190
+ // not JSON: keep the raw text
191
+ }
192
+ const details = { status, body, rateLimit };
119
193
  switch (status) {
194
+ case 400:
195
+ return new errors_js_1.BadRequestError(message, details);
120
196
  case 401:
121
- throw new errors_js_1.InvalidAPIKeyError('Invalid API key');
122
- case 429:
123
- throw new errors_js_1.RateLimitExceededError('Rate limit exceeded - please wait before retrying');
197
+ return new errors_js_1.InvalidAPIKeyError(message, details);
198
+ case 403:
199
+ return new errors_js_1.ForbiddenError(message, details);
124
200
  case 404:
125
- throw new errors_js_1.NotFoundError('Resource not found');
201
+ return new errors_js_1.NotFoundError(message, details);
202
+ case 429:
203
+ return new errors_js_1.RateLimitError(message, {
204
+ ...details,
205
+ retryAfter: retryAfterSeconds(response.headers, rateLimit),
206
+ });
126
207
  default:
127
- throw new errors_js_1.OddsAPIError(`API error ${status}: ${errorMessage}`);
208
+ if (status >= 500) {
209
+ return new errors_js_1.ServerError(message, { ...details, retryAfter: retryAfterSeconds(response.headers) });
210
+ }
211
+ return new errors_js_1.OddsAPIError(message, details);
128
212
  }
129
213
  }
214
+ async get(path, query, auth = true) {
215
+ return (await this.send(path, { query, auth })).data;
216
+ }
130
217
  // ============================================================================
131
- // SPORTS & LEAGUES
218
+ // SPORTS, LEAGUES, MARKETS
132
219
  // ============================================================================
133
- /**
134
- * Get all available sports
135
- *
136
- * @returns List of available sports
137
- *
138
- * @example
139
- * ```typescript
140
- * const sports = await client.getSports();
141
- * console.log(`Found ${sports.length} sports`);
142
- * ```
143
- */
220
+ /** All sports. No API key needed. */
144
221
  async getSports() {
145
- return this.request('sports');
222
+ return this.get('sports', undefined, false);
146
223
  }
147
224
  /**
148
- * Get leagues for a specific sport
149
- *
150
- * @param sport - Sport identifier (e.g., 'basketball', 'football')
151
- * @returns List of leagues
225
+ * Leagues for a sport.
152
226
  *
153
227
  * @example
154
228
  * ```typescript
155
- * const leagues = await client.getLeagues('basketball');
229
+ * const leagues = await client.getLeagues('football');
156
230
  * ```
157
231
  */
158
- async getLeagues(sport) {
159
- return this.request('leagues', { sport }, true);
232
+ async getLeagues(sport, options = {}) {
233
+ return this.get('leagues', { sport, all: options.all });
234
+ }
235
+ async getMarkets(sport) {
236
+ return this.get('markets', { sport }, false);
160
237
  }
161
238
  // ============================================================================
162
239
  // EVENTS
163
240
  // ============================================================================
164
241
  /**
165
- * Get events with optional filters
166
- *
167
- * @param params - Event filter parameters
168
- * @returns List of events
242
+ * Events for a sport. Without `to` the window is the next 14 days; each
243
+ * response is capped at 5000 events (see `iterateEvents`).
169
244
  *
170
245
  * @example
171
246
  * ```typescript
172
- * const events = await client.getEvents({
173
- * sport: 'basketball',
174
- * league: 'usa-nba'
175
- * });
247
+ * const events = await client.getEvents({ sport: 'football', league: 'england-premier-league', status: 'pending,live' });
176
248
  * ```
177
249
  */
178
250
  async getEvents(params) {
179
- return this.request('events', params, true);
251
+ return this.get('events', { ...params, status: joinList(params.status) });
180
252
  }
181
253
  /**
182
- * Get a specific event by ID
183
- *
184
- * @param eventId - Event ID
185
- * @returns Event details
254
+ * Every event matching the filters, paging with limit and skip.
186
255
  *
187
256
  * @example
188
257
  * ```typescript
189
- * const event = await client.getEventById('62924717');
258
+ * for await (const event of client.iterateEvents({ sport: 'football', to: '2027-01-01T00:00:00Z' })) {
259
+ * console.log(event.home, event.away);
260
+ * }
190
261
  * ```
191
262
  */
263
+ async *iterateEvents(params, options = {}) {
264
+ const pageSize = options.pageSize ?? params.limit ?? 1000;
265
+ let skip = params.skip ?? 0;
266
+ for (let page = 0; options.maxPages === undefined || page < options.maxPages; page++) {
267
+ const events = await this.getEvents({ ...params, limit: pageSize, skip });
268
+ yield* events;
269
+ if (events.length < pageSize)
270
+ return;
271
+ skip += events.length;
272
+ }
273
+ }
274
+ /** One event by id. */
192
275
  async getEventById(eventId) {
193
- return this.request(`events/${eventId}`, {}, true);
276
+ return this.get(`events/${encodeURIComponent(String(eventId))}`);
194
277
  }
195
- /**
196
- * Get currently live events for a sport
197
- *
198
- * @param sport - Sport identifier
199
- * @returns List of live events
200
- *
201
- * @example
202
- * ```typescript
203
- * const liveEvents = await client.getLiveEvents('basketball');
204
- * ```
205
- */
278
+ /** Live events, optionally for one sport. Live events carry `clock`. */
206
279
  async getLiveEvents(sport) {
207
- return this.request('events/live', { sport }, true);
280
+ return this.get('events/live', { sport });
208
281
  }
209
282
  /**
210
- * Search for events by keyword
211
- *
212
- * @param query - Search query
213
- * @returns List of matching events
283
+ * Search events by team or league name (min 3 characters, up to 10 results).
214
284
  *
215
285
  * @example
216
286
  * ```typescript
217
- * const events = await client.searchEvents('Lakers');
287
+ * const live = await client.searchEvents('Liverpool', { status: 'live' });
218
288
  * ```
219
289
  */
220
- async searchEvents(query) {
221
- return this.request('events/search', { query }, true);
290
+ async searchEvents(query, options = {}) {
291
+ return this.get('events/search', { query, status: options.status });
222
292
  }
223
293
  // ============================================================================
224
294
  // HISTORICAL
225
295
  // ============================================================================
226
296
  /**
227
- * Get finished historical events within a date range
228
- *
229
- * @param params - Historical event filter parameters
230
- * @returns List of historical events
297
+ * Finished events for one league. The span from `from` to `to` is at most 31
298
+ * days; use `iterateHistoricalEvents` for longer ranges.
299
+ */
300
+ async getHistoricalEvents(params) {
301
+ return this.get('historical/events', { ...params });
302
+ }
303
+ /** Finished events for one league over any range, fetched in 31-day windows. */
304
+ async *iterateHistoricalEvents(params) {
305
+ const start = Date.parse(params.from);
306
+ const end = Date.parse(params.to);
307
+ if (isNaN(start) || isNaN(end))
308
+ throw new errors_js_1.BadRequestError('from and to must be RFC 3339 dates');
309
+ const seen = new Set();
310
+ for (let windowStart = start; windowStart < end; windowStart += HISTORICAL_SPAN_MS) {
311
+ const windowEnd = Math.min(windowStart + HISTORICAL_SPAN_MS, end);
312
+ const events = await this.getHistoricalEvents({
313
+ ...params,
314
+ from: new Date(windowStart).toISOString().replace(/\.\d{3}Z$/, 'Z'),
315
+ to: new Date(windowEnd).toISOString().replace(/\.\d{3}Z$/, 'Z'),
316
+ });
317
+ for (const event of events) {
318
+ if (seen.has(event.id))
319
+ continue;
320
+ seen.add(event.id);
321
+ yield event;
322
+ }
323
+ }
324
+ }
325
+ /** Search finished events by team name, across leagues (31-day span, default the last 31 days). */
326
+ async searchHistoricalEvents(params) {
327
+ return this.get('historical/events/search', { ...params });
328
+ }
329
+ /**
330
+ * Odds for a finished event, in the `/odds` shape.
231
331
  *
232
332
  * @example
233
333
  * ```typescript
234
- * const events = await client.getHistoricalEvents({
235
- * sport: 'football',
236
- * league: 'england-premier-league',
237
- * from: '2026-01-01T00:00:00Z',
238
- * to: '2026-01-31T23:59:59Z'
239
- * });
334
+ * const odds = await client.getHistoricalOdds({ eventId: 67697888, bookmakers: ['Bet365', 'SingBet'], markets: ['ML'] });
240
335
  * ```
241
336
  */
242
- async getHistoricalEvents(params) {
243
- return this.request('historical/events', params, true);
337
+ async getHistoricalOdds(params) {
338
+ return this.get('historical/odds', {
339
+ ...params,
340
+ bookmakers: joinList(params.bookmakers),
341
+ markets: joinList(params.markets),
342
+ });
244
343
  }
245
344
  /**
246
- * Get closing odds for a historical event
247
- *
248
- * @param params - Historical odds query parameters
249
- * @returns Historical event odds data
345
+ * Closing odds for every settled event across up to 10 leagues (paid plans).
346
+ * Up to 366 days per call, 100 events per page (see `iterateClosingLines`).
250
347
  *
251
348
  * @example
252
349
  * ```typescript
253
- * const odds = await client.getHistoricalOdds({
254
- * eventId: '67697888',
255
- * bookmakers: 'singbet,bet365'
350
+ * const lines = await client.getClosingLines({
351
+ * sport: 'football',
352
+ * leagues: ['england-premier-league'],
353
+ * from: '2026-08-01T00:00:00Z',
354
+ * to: '2026-10-31T23:59:59Z',
355
+ * markets: ['ML', 'Totals'],
356
+ * bookmakers: ['Bet365'],
256
357
  * });
257
358
  * ```
258
359
  */
259
- async getHistoricalOdds(params) {
260
- return this.request('historical/odds', params, true);
360
+ async getClosingLines(params) {
361
+ return this.get('historical/closing-lines', {
362
+ ...params,
363
+ leagues: joinList(params.leagues),
364
+ markets: joinList(params.markets),
365
+ bookmakers: joinList(params.bookmakers),
366
+ });
367
+ }
368
+ /** Every closing line matching the filters, paging with limit and skip. */
369
+ async *iterateClosingLines(params, options = {}) {
370
+ const pageSize = Math.min(options.pageSize ?? params.limit ?? 100, 100);
371
+ let skip = params.skip ?? 0;
372
+ for (let page = 0; options.maxPages === undefined || page < options.maxPages; page++) {
373
+ const events = await this.getClosingLines({ ...params, limit: pageSize, skip });
374
+ yield* events;
375
+ if (events.length < pageSize)
376
+ return;
377
+ skip += events.length;
378
+ }
261
379
  }
262
380
  // ============================================================================
263
381
  // ODDS
264
382
  // ============================================================================
265
383
  /**
266
- * Get odds for a specific event
267
- *
268
- * @param params - Odds query parameters
269
- * @returns Event odds data
384
+ * Odds for one event. Pass `markets` to keep the response small.
270
385
  *
271
386
  * @example
272
387
  * ```typescript
273
- * const odds = await client.getEventOdds({
274
- * eventId: '62924717',
275
- * bookmakers: 'singbet,bet365'
276
- * });
388
+ * const odds = await client.getEventOdds({ eventId: 62924717, bookmakers: ['Bet365', 'SingBet'], markets: ['ML', 'Totals'] });
389
+ * const ml = odds.bookmakers['Bet365']?.find((m) => m.name === 'ML');
277
390
  * ```
278
391
  */
279
392
  async getEventOdds(params) {
280
- return this.request('odds', params, true);
393
+ return this.get('odds', {
394
+ ...params,
395
+ bookmakers: joinList(params.bookmakers),
396
+ markets: joinList(params.markets),
397
+ });
398
+ }
399
+ /** Odds for up to 10 events in one request. */
400
+ async getOddsForMultipleEvents(params) {
401
+ return this.get('odds/multi', this.multiOddsQuery(params));
281
402
  }
282
403
  /**
283
- * Track odds movements for an event
284
- *
285
- * @param params - Odds movement parameters
286
- * @returns Historical odds movements
404
+ * Odds for up to 10 events plus the WebSocket sequence at that moment.
405
+ * Rebuild state from `data`, then connect or reconnect with `lastSeq: seq`.
406
+ */
407
+ async getOddsSnapshot(params) {
408
+ const { data, headers } = await this.send('odds/multi', {
409
+ query: this.multiOddsQuery({ ...params, includeSeq: true }),
410
+ });
411
+ return { data, seq: numberHeader(headers, 'x-oddsapi-seq') };
412
+ }
413
+ multiOddsQuery(params) {
414
+ return {
415
+ ...params,
416
+ eventIds: joinList(params.eventIds),
417
+ bookmakers: joinList(params.bookmakers),
418
+ markets: joinList(params.markets),
419
+ };
420
+ }
421
+ /**
422
+ * Price history for one market at one bookmaker (prematch only).
287
423
  *
288
424
  * @example
289
425
  * ```typescript
290
- * const movements = await client.getOddsMovement({
291
- * eventId: '62924717',
292
- * bookmaker: 'singbet',
293
- * market: 'moneyline'
294
- * });
426
+ * const history = await client.getOddsMovement({ eventId: 62924717, bookmaker: 'Bet365', market: 'ML' });
295
427
  * ```
296
428
  */
297
429
  async getOddsMovement(params) {
298
- return this.request('odds/movements', params, true);
430
+ return this.get('odds/movements', { ...params });
299
431
  }
300
432
  /**
301
- * Get odds for multiple events at once
302
- *
303
- * @param params - Multi-event odds parameters
304
- * @returns Array of event odds
305
- *
306
- * @example
307
- * ```typescript
308
- * const odds = await client.getOddsForMultipleEvents({
309
- * eventIds: '12345,67890',
310
- * bookmakers: 'singbet,bet365'
311
- * });
312
- * ```
433
+ * Market groups changed since `since` for one bookmaker and sport. The result
434
+ * is a delta: merge it into what you hold, keyed by event and market.
435
+ * See `pollUpdatedOdds` for a loop that follows X-Next-Since.
313
436
  */
314
- async getOddsForMultipleEvents(params) {
315
- return this.request('odds/multi', params, true);
437
+ async getUpdatedOddsSince(params) {
438
+ return (await this.getUpdatedOddsSinceWithMeta(params)).data;
439
+ }
440
+ /** Like `getUpdatedOddsSince`, plus the X-Next-Since, X-Server-Time and X-Unknown-Markets headers. */
441
+ async getUpdatedOddsSinceWithMeta(params) {
442
+ const { data, headers } = await this.send('odds/updated', {
443
+ query: { ...params, markets: joinList(params.markets) },
444
+ });
445
+ const unknown = headers.get('x-unknown-markets');
446
+ return {
447
+ data,
448
+ nextSince: numberHeader(headers, 'x-next-since'),
449
+ serverTime: numberHeader(headers, 'x-server-time'),
450
+ unknownMarkets: unknown ? splitList(unknown) : [],
451
+ };
316
452
  }
317
453
  /**
318
- * Get odds updated since a given timestamp
319
- *
320
- * @param params - Updated odds parameters
321
- * @returns Array of updated event odds
454
+ * Polls `/odds/updated`, passing each X-Next-Since as the next `since`.
455
+ * A page cut short by `limit` is followed up at once.
322
456
  *
323
457
  * @example
324
458
  * ```typescript
325
- * const updatedOdds = await client.getUpdatedOddsSince({
326
- * since: Math.floor(Date.now() / 1000) - 20, // seconds, at most 90 old
327
- * bookmaker: 'Bet365',
328
- * sport: 'football',
329
- * markets: 'ML,Spread,Totals', // required from 15 October 2026
330
- * });
459
+ * const controller = new AbortController();
460
+ * for await (const batch of client.pollUpdatedOdds({ bookmaker: 'Bet365', sport: 'football', markets: ['ML'], signal: controller.signal })) {
461
+ * for (const event of batch.data) merge(event);
462
+ * }
331
463
  * ```
332
464
  */
333
- async getUpdatedOddsSince(params) {
334
- return this.request('odds/updated', params, true);
465
+ async *pollUpdatedOdds(params) {
466
+ const { intervalMs = 10000, signal, since: firstSince, ...query } = params;
467
+ let since = firstSince ?? Math.floor(Date.now() / 1000) - 20;
468
+ while (!signal?.aborted) {
469
+ const result = await this.getUpdatedOddsSinceWithMeta({ ...query, since });
470
+ yield result;
471
+ since = result.nextSince ?? (result.serverTime ?? Math.floor(Date.now() / 1000)) - 10;
472
+ const truncated = query.limit !== undefined && result.data.length >= query.limit;
473
+ if (!truncated)
474
+ await sleep(intervalMs, signal);
475
+ }
476
+ }
477
+ /**
478
+ * Best, average, median, worst and fair price per market line across
479
+ * bookmakers (Growth plans and above; lower plans get `demo: true`).
480
+ */
481
+ async getOddsSummary(params) {
482
+ return this.get('odds/summary', this.summaryQuery(params));
483
+ }
484
+ /** `getOddsSummary` for up to 10 events in one request. */
485
+ async getOddsSummaryMulti(params) {
486
+ return this.get('odds/summary/multi', {
487
+ ...this.summaryQuery(params),
488
+ eventIds: joinList(params.eventIds),
489
+ });
490
+ }
491
+ summaryQuery(params) {
492
+ return {
493
+ ...params,
494
+ markets: joinList(params.markets),
495
+ bookmakers: joinList(params.bookmakers),
496
+ };
335
497
  }
336
498
  // ============================================================================
337
499
  // PARTICIPANTS
338
500
  // ============================================================================
339
- /**
340
- * Get participants (teams/players) for a sport
341
- *
342
- * @param params - Participant query parameters
343
- * @returns List of participants
344
- *
345
- * @example
346
- * ```typescript
347
- * const participants = await client.getParticipants({
348
- * sport: 'basketball',
349
- * search: 'Warriors'
350
- * });
351
- * ```
352
- */
501
+ /** Teams and players for a sport. */
353
502
  async getParticipants(params) {
354
- return this.request('participants', params, true);
503
+ return this.get('participants', { ...params });
504
+ }
505
+ /** One participant by id. */
506
+ async getParticipantById(participantId) {
507
+ return this.get(`participants/${encodeURIComponent(String(participantId))}`);
355
508
  }
356
509
  /**
357
- * Get a specific participant by ID
358
- *
359
- * @param participantId - Participant ID
360
- * @returns Participant details
361
- *
362
- * @example
363
- * ```typescript
364
- * const participant = await client.getParticipantById(3428);
365
- * ```
510
+ * URL of a participant's PNG logo (use `homeId`/`awayId` from events).
511
+ * The URL carries your API key, so only hand it to a browser you trust;
512
+ * otherwise proxy it with `getParticipantLogo`.
366
513
  */
367
- async getParticipantById(participantId) {
368
- return this.request(`participants/${participantId}`, {}, true);
514
+ getParticipantLogoUrl(participantId) {
515
+ return this.buildUrl(`participants/${encodeURIComponent(String(participantId))}/logo`).toString();
516
+ }
517
+ /** A participant's logo as PNG bytes. Throws NotFoundError when there is none. */
518
+ async getParticipantLogo(participantId) {
519
+ const { data } = await this.send(`participants/${encodeURIComponent(String(participantId))}/logo`, { raw: true });
520
+ return data;
369
521
  }
370
522
  // ============================================================================
371
523
  // BOOKMAKERS
372
524
  // ============================================================================
525
+ /** All bookmakers with their current status. No API key needed. */
526
+ async getBookmakers() {
527
+ return this.get('bookmakers', undefined, false);
528
+ }
529
+ /** The bookmakers selected on your key. */
530
+ async getSelectedBookmakers() {
531
+ return this.get('bookmakers/selected');
532
+ }
533
+ /** Add bookmakers to your selection. */
534
+ async selectBookmakers(bookmakers) {
535
+ const { data } = await this.send('bookmakers/selected/select', {
536
+ method: 'PUT',
537
+ query: { bookmakers: joinList(bookmakers) },
538
+ });
539
+ return data;
540
+ }
541
+ /** Clear your selection. Allowed once every 12 hours. */
542
+ async clearSelectedBookmakers() {
543
+ const { data } = await this.send('bookmakers/selected/clear', { method: 'PUT' });
544
+ return data;
545
+ }
546
+ // ============================================================================
547
+ // BETTING ANALYSIS
548
+ // ============================================================================
373
549
  /**
374
- * Get all available bookmakers
375
- *
376
- * @returns List of bookmakers
550
+ * Price gaps across your bookmakers where the best prices imply under 100%
551
+ * (prematch only, refreshed every few seconds). Prices move and limits
552
+ * apply, so check every leg before acting.
377
553
  *
378
554
  * @example
379
555
  * ```typescript
380
- * const bookmakers = await client.getBookmakers();
556
+ * const arbs = await client.getArbitrageBets({ bookmakers: ['Bet365', 'SingBet'], sport: 'football', minProfit: 1 });
381
557
  * ```
382
558
  */
383
- async getBookmakers() {
384
- return this.request('bookmakers');
559
+ async getArbitrageBets(params) {
560
+ return this.get('arbitrage-bets', {
561
+ ...params,
562
+ bookmakers: joinList(params.bookmakers),
563
+ markets: joinList(params.markets),
564
+ });
565
+ }
566
+ /** Prices above a fair-odds estimate at one bookmaker. */
567
+ async getValueBets(params) {
568
+ return this.get('value-bets', { ...params });
385
569
  }
386
570
  /**
387
- * Get your selected bookmakers
388
- *
389
- * @returns List of selected bookmakers
571
+ * Dropping odds from sharp bookmakers (paid plans).
390
572
  *
391
573
  * @example
392
574
  * ```typescript
393
- * const selected = await client.getSelectedBookmakers();
575
+ * const drops = await client.getDroppingOdds({ sport: 'football', markets: ['ML'], minDrop: 10 });
394
576
  * ```
395
577
  */
396
- async getSelectedBookmakers() {
397
- return this.request('bookmakers/selected', {}, true);
578
+ async getDroppingOdds(params = {}) {
579
+ return (await this.getDroppingOddsPage(params)).data;
580
+ }
581
+ /** Like `getDroppingOdds`, plus the pagination headers. */
582
+ async getDroppingOddsPage(params = {}) {
583
+ const { market, ...rest } = params;
584
+ const { data, headers } = await this.send('dropping-odds', {
585
+ query: {
586
+ ...rest,
587
+ leagues: joinList(rest.leagues),
588
+ markets: joinList(rest.markets) ?? market,
589
+ },
590
+ });
591
+ return {
592
+ data,
593
+ total: numberHeader(headers, 'x-total-count'),
594
+ page: numberHeader(headers, 'x-page'),
595
+ perPage: numberHeader(headers, 'x-per-page'),
596
+ updatedAt: numberHeader(headers, 'x-updated-at'),
597
+ };
598
+ }
599
+ /** Every dropping-odds entry matching the filters, page by page. */
600
+ async *iterateDroppingOdds(params = {}, options = {}) {
601
+ const limit = options.pageSize ?? params.limit ?? 200;
602
+ let page = params.page ?? 1;
603
+ let seen = 0;
604
+ for (let n = 0; options.maxPages === undefined || n < options.maxPages; n++, page++) {
605
+ const result = await this.getDroppingOddsPage({ ...params, limit, page });
606
+ yield* result.data;
607
+ seen += result.data.length;
608
+ if (result.data.length < limit)
609
+ return;
610
+ if (result.total !== null && seen >= result.total)
611
+ return;
612
+ }
398
613
  }
614
+ // ============================================================================
615
+ // SETTLEMENT
616
+ // ============================================================================
399
617
  /**
400
- * Select specific bookmakers for your account
401
- *
402
- * @param bookmakers - Comma-separated bookmaker IDs
403
- * @returns Success response
618
+ * Settlement records (status, final flag, final scores) for events (paid plans).
619
+ * More than 50 ids are split into several requests.
404
620
  *
405
621
  * @example
406
622
  * ```typescript
407
- * await client.selectBookmakers('singbet,bet365');
623
+ * const { settlements, notFound } = await client.getSettlements([74919888, 73101436]);
408
624
  * ```
409
625
  */
410
- async selectBookmakers(bookmakers) {
411
- return this.requestPut('bookmakers/selected/select', { bookmakers }, true);
626
+ async getSettlements(eventIds) {
627
+ const ids = splitList(eventIds);
628
+ const result = { settlements: [], notFound: [] };
629
+ for (let i = 0; i < ids.length || i === 0; i += SETTLEMENT_BATCH) {
630
+ const page = await this.get('settlements', {
631
+ eventIds: ids.slice(i, i + SETTLEMENT_BATCH).join(','),
632
+ });
633
+ result.settlements.push(...(page.settlements ?? []));
634
+ result.notFound.push(...(page.notFound ?? []));
635
+ }
636
+ return result;
412
637
  }
413
638
  /**
414
- * Clear your selected bookmakers
415
- *
416
- * @returns Success response
639
+ * Grade bet selections against final results (paid plans). Returns one grade
640
+ * per selection, in order. More than 50 selections are sent in batches.
641
+ * Re-send selections that are not `final`, at most once a minute.
417
642
  *
418
643
  * @example
419
644
  * ```typescript
420
- * await client.clearSelectedBookmakers();
645
+ * const { grades } = await client.gradeBets([
646
+ * { ref: 'bet-1', eventId: 74919888, market: 'Spread', hdp: -0.75, side: 'home' },
647
+ * ]);
421
648
  * ```
422
649
  */
423
- async clearSelectedBookmakers() {
424
- return this.requestPut('bookmakers/selected/clear', {}, true);
650
+ async gradeBets(selections) {
651
+ const grades = [];
652
+ for (let i = 0; i < selections.length || i === 0; i += SETTLEMENT_BATCH) {
653
+ const { data } = await this.send('settlements/grade', {
654
+ method: 'POST',
655
+ body: { selections: selections.slice(i, i + SETTLEMENT_BATCH) },
656
+ });
657
+ grades.push(...(data.grades ?? []));
658
+ }
659
+ return { grades };
660
+ }
661
+ /** Same as `gradeBets` (the API operation is called GradeSelections). */
662
+ async gradeSelections(selections) {
663
+ return this.gradeBets(selections);
425
664
  }
426
665
  // ============================================================================
427
- // BETTING ANALYSIS
666
+ // OUTRIGHTS (paid add-on; a key without it gets ForbiddenError)
428
667
  // ============================================================================
429
668
  /**
430
- * Find arbitrage betting opportunities
431
- *
432
- * @param params - Arbitrage bet parameters
433
- * @returns List of arbitrage opportunities
669
+ * Tournaments for a sport (golf today), sorted by date.
434
670
  *
435
671
  * @example
436
672
  * ```typescript
437
- * const arbs = await client.getArbitrageBets({
438
- * bookmakers: 'singbet,bet365',
439
- * limit: 10,
440
- * includeEventDetails: true
441
- * });
673
+ * const tournaments = await client.getOutrights({ sport: 'golf', league: 'pga-tour' });
442
674
  * ```
443
675
  */
444
- async getArbitrageBets(params) {
445
- return this.request('arbitrage-bets', params, true);
676
+ async getOutrights(params) {
677
+ return this.get('outrights', { ...params, status: joinList(params.status) });
446
678
  }
447
679
  /**
448
- * Find value betting opportunities
449
- *
450
- * @param params - Value bet parameters
451
- * @returns List of value bets
680
+ * Prices for one tournament: Winner, Top 5/10/20, the "(Incl. Ties)"
681
+ * variants and Make Cut, per bookmaker.
452
682
  *
453
683
  * @example
454
684
  * ```typescript
455
- * const valueBets = await client.getValueBets({
456
- * bookmaker: 'singbet',
457
- * includeEventDetails: true
458
- * });
685
+ * const odds = await client.getOutrightOdds({ id: 1001, bookmakers: ['DraftKings', 'Betfair Exchange'] });
459
686
  * ```
460
687
  */
461
- async getValueBets(params) {
462
- return this.request('value-bets', params, true);
688
+ async getOutrightOdds(params) {
689
+ return this.get('outrights/odds', { ...params, bookmakers: joinList(params.bookmakers) });
690
+ }
691
+ /** Final positions and winners per market for one tournament. */
692
+ async getOutrightResults(id) {
693
+ return this.get('outrights/results', { id });
463
694
  }
695
+ // ============================================================================
696
+ // MAPPINGS
697
+ // ============================================================================
464
698
  /**
465
- * Get dropping odds from sharp bookmakers.
466
- * @example
467
- * const drops = await client.getDroppingOdds({
468
- * sport: 'football',
469
- * market: 'ML',
470
- * minDrop: 10,
471
- * includeEventDetails: true
472
- * });
699
+ * A bookmaker's own event, market and outcome ids for our events (paid plans).
700
+ * Without eventId(s), marketId(s) or outcomeId it is a bulk sync with a cursor.
473
701
  */
474
- async getDroppingOdds(params = {}) {
475
- return this.request('dropping-odds', params, true);
702
+ async getMappings(params) {
703
+ return this.get('mappings', {
704
+ ...params,
705
+ eventIds: joinList(params.eventIds),
706
+ marketIds: joinList(params.marketIds),
707
+ });
708
+ }
709
+ /** Every mapping row, following `nextCursor` until it is null. */
710
+ async *iterateMappings(params, options = {}) {
711
+ let cursor = params.cursor;
712
+ const limit = options.pageSize ?? params.limit;
713
+ for (let n = 0; options.maxPages === undefined || n < options.maxPages; n++) {
714
+ const page = await this.getMappings({ ...params, limit, cursor });
715
+ yield* page.data;
716
+ if (!page.nextCursor)
717
+ return;
718
+ cursor = page.nextCursor;
719
+ }
476
720
  }
477
721
  }
478
722
  exports.OddsAPIClient = OddsAPIClient;