@managebetcodes/sdk 0.0.0-stage → 1.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Manage Bet Codes
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,75 @@
1
- # Temporary Holding Version
1
+ # Manage Bet Codes TypeScript SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official Node.js SDK for the [Manage Bet Codes API v1](https://api.managebetcodes.app/v1).
4
+
5
+ It requires Node.js 18 or later. Use it only on a server, serverless function, or worker. Do not put an API key in browser code.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @managebetcodes/sdk
11
+ ```
12
+
13
+ ## Command line
14
+
15
+ The package installs an `mbc` command with the same client.
16
+
17
+ ```bash
18
+ export MBC_API_KEY=mbc_live_your_key
19
+ mbc convert 7B9A2F --from sportybet --to 1xng
20
+ mbc view 7B9A2F --bookmaker sportybet
21
+ mbc usage
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { Client } from "@managebetcodes/sdk";
28
+
29
+ const client = new Client(process.env.MBC_API_KEY!);
30
+ const result = await client.convert("7B9A2F", "sportybet", "1xng");
31
+
32
+ console.log(result);
33
+ ```
34
+
35
+ Create API keys and see all API actions at [Manage Bet Codes Developers](https://managebetcodes.app/developers).
36
+
37
+ ## Errors and retries
38
+
39
+ The client sends `X-API-Key` on every request. It creates an `Idempotency-Key` for every POST request unless you provide one.
40
+
41
+ It retries HTTP 429, 502, 503, and 504 responses. It respects the `Retry-After` header. Errors are instances of `AuthenticationError`, `QuotaError`, `RateLimitError`, `ValidationError`, or `APIError`.
42
+
43
+ ```ts
44
+ import { Client, RateLimitError } from "@managebetcodes/sdk";
45
+
46
+ const client = new Client(process.env.MBC_API_KEY!, { timeout: 30, maxRetries: 3 });
47
+
48
+ try {
49
+ await client.view("7B9A2F", "sportybet");
50
+ } catch (error) {
51
+ if (error instanceof RateLimitError) {
52
+ console.log(`Retry after ${error.retryAfter ?? "the stated"} seconds.`);
53
+ }
54
+ throw error;
55
+ }
56
+ ```
57
+
58
+ ## Webhooks
59
+
60
+ Verify the signature against the raw request body before parsing JSON.
61
+
62
+ ```ts
63
+ import { verifyWebhook } from "@managebetcodes/sdk";
64
+
65
+ const rawBody = new Uint8Array(await request.arrayBuffer());
66
+ const valid = verifyWebhook(process.env.MBC_WEBHOOK_SECRET!, rawBody, request.headers.get("x-mbc-signature") ?? "");
67
+
68
+ if (!valid) {
69
+ throw new Error("Invalid webhook signature");
70
+ }
71
+ ```
72
+
73
+ ## Documentation
74
+
75
+ See the [API reference](https://api.managebetcodes.app/v1/docs) and the [TypeScript SDK guide](https://managebetcodes.app/developers/sdk/typescript).
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ /** The `mbc` command: convert and view codes from a terminal. */
3
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,166 @@
1
+ #!/usr/bin/env node
2
+ /** The `mbc` command: convert and view codes from a terminal. */
3
+ import { APIError } from "./errors.js";
4
+ import { BASE_URL, Client, VERSION } from "./client.js";
5
+ const HELP = `mbc - Manage Bet Codes API v1
6
+
7
+ Usage:
8
+ mbc [options] <command> [args]
9
+
10
+ Commands:
11
+ convert CODE --from BOOK --to TARGET[,TARGET] Convert a code
12
+ view CODE --bookmaker BOOK View a slip as text
13
+ capabilities Show the API manifest
14
+ usage Show plan, credits, and limits
15
+
16
+ Options:
17
+ --api-key KEY API key (or set MBC_API_KEY; not needed for capabilities)
18
+ --base-url URL API base URL (or set MBC_BASE_URL)
19
+ --help, -h Show this help
20
+ --version, -v Show the version
21
+ `;
22
+ class UsageError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "UsageError";
26
+ }
27
+ }
28
+ const VALUE_FLAGS = new Set(["--api-key", "--base-url", "--from", "--to", "--bookmaker"]);
29
+ function parse(argv) {
30
+ const positionals = [];
31
+ const options = new Map();
32
+ let index = 0;
33
+ while (index < argv.length) {
34
+ const token = argv[index];
35
+ if (token === undefined) {
36
+ break;
37
+ }
38
+ if (token.startsWith("--")) {
39
+ const equals = token.indexOf("=");
40
+ const name = equals === -1 ? token : token.slice(0, equals);
41
+ const inline = equals === -1 ? undefined : token.slice(equals + 1);
42
+ if (VALUE_FLAGS.has(name)) {
43
+ const next = argv[index + 1];
44
+ const value = inline ?? next;
45
+ if (value === undefined || (inline === undefined && value.startsWith("--"))) {
46
+ throw new UsageError(`Option ${name} needs a value. Run mbc --help.`);
47
+ }
48
+ const list = options.get(name) ?? [];
49
+ list.push(value);
50
+ options.set(name, list);
51
+ index += inline === undefined ? 2 : 1;
52
+ }
53
+ else {
54
+ const list = options.get(name) ?? [];
55
+ list.push("true");
56
+ options.set(name, list);
57
+ index += 1;
58
+ }
59
+ }
60
+ else {
61
+ positionals.push(token);
62
+ index += 1;
63
+ }
64
+ }
65
+ return { positionals, options };
66
+ }
67
+ function one(options, name) {
68
+ return options.get(name)?.[0];
69
+ }
70
+ function makeClient(options, env) {
71
+ const apiKey = one(options, "--api-key") ?? env["MBC_API_KEY"] ?? "";
72
+ if (!apiKey) {
73
+ throw new UsageError("Set --api-key or MBC_API_KEY. Keys start with mbc_live_.");
74
+ }
75
+ const baseUrl = one(options, "--base-url") ?? env["MBC_BASE_URL"] ?? BASE_URL;
76
+ return new Client(apiKey, { baseUrl });
77
+ }
78
+ function splitTargets(raw) {
79
+ return raw
80
+ .flatMap((value) => value.split(","))
81
+ .map((value) => value.trim())
82
+ .filter((value) => value.length > 0);
83
+ }
84
+ async function run(argv, env) {
85
+ if (argv.includes("--help") || argv.includes("-h")) {
86
+ console.log(HELP);
87
+ return 0;
88
+ }
89
+ if (argv.includes("--version") || argv.includes("-v")) {
90
+ console.log(VERSION);
91
+ return 0;
92
+ }
93
+ const { positionals, options } = parse(argv);
94
+ const command = positionals[0];
95
+ const args = positionals.slice(1);
96
+ if (command === undefined || command === "help") {
97
+ console.log(HELP);
98
+ return 0;
99
+ }
100
+ if (command !== "convert" && command !== "view" && command !== "capabilities" && command !== "usage") {
101
+ throw new UsageError(`Unknown command ${command}. Run mbc --help.`);
102
+ }
103
+ if (command === "capabilities") {
104
+ // The manifest endpoint is public, so it needs no API key.
105
+ const baseUrl = (one(options, "--base-url") ?? env["MBC_BASE_URL"] ?? BASE_URL).replace(/\/+$/, "");
106
+ const response = await fetch(`${baseUrl}/capabilities`, {
107
+ headers: { Accept: "application/json" },
108
+ });
109
+ if (!response.ok) {
110
+ throw new APIError(`The API returned HTTP ${response.status}.`, {
111
+ status: response.status,
112
+ code: `http_${response.status}`,
113
+ });
114
+ }
115
+ console.log(JSON.stringify(await response.json(), null, 2));
116
+ return 0;
117
+ }
118
+ const client = makeClient(options, env);
119
+ if (command === "convert") {
120
+ const code = args[0];
121
+ const from = one(options, "--from");
122
+ const targets = splitTargets(options.get("--to") ?? []);
123
+ if (!code || !from || targets.length === 0) {
124
+ throw new UsageError("Usage: mbc convert CODE --from BOOK --to TARGET[,TARGET]");
125
+ }
126
+ const single = targets.length === 1 ? targets[0] : undefined;
127
+ const result = single === undefined
128
+ ? await client.convert(code, from, targets)
129
+ : await client.convert(code, from, single);
130
+ console.log(JSON.stringify(result, null, 2));
131
+ return 0;
132
+ }
133
+ if (command === "view") {
134
+ const code = args[0];
135
+ const bookmaker = one(options, "--bookmaker");
136
+ if (!code || !bookmaker) {
137
+ throw new UsageError("Usage: mbc view CODE --bookmaker BOOK");
138
+ }
139
+ console.log(JSON.stringify(await client.view(code, bookmaker), null, 2));
140
+ return 0;
141
+ }
142
+ if (command === "usage") {
143
+ console.log(JSON.stringify(await client.usage(), null, 2));
144
+ return 0;
145
+ }
146
+ throw new UsageError(`Unknown command ${command}. Run mbc --help.`);
147
+ }
148
+ function main() {
149
+ run(process.argv.slice(2), process.env).then((code) => {
150
+ process.exitCode = code;
151
+ }, (error) => {
152
+ if (error instanceof UsageError) {
153
+ console.error(`mbc: ${error.message}`);
154
+ process.exitCode = 2;
155
+ }
156
+ else if (error instanceof APIError) {
157
+ console.error(`mbc: ${error.toString()}`);
158
+ process.exitCode = 1;
159
+ }
160
+ else {
161
+ console.error(`mbc: ${error instanceof Error ? error.message : String(error)}`);
162
+ process.exitCode = 1;
163
+ }
164
+ });
165
+ }
166
+ main();
@@ -0,0 +1,109 @@
1
+ export declare const VERSION = "1.0.2";
2
+ export declare const BASE_URL = "https://api.managebetcodes.app/v1";
3
+ export type QueryValue = string | number | boolean | string[] | null | undefined;
4
+ export type Query = Record<string, QueryValue>;
5
+ export interface EventMarketsQuery extends Query {
6
+ bookmaker?: string;
7
+ view?: "canonical" | "all";
8
+ market?: string | string[];
9
+ q?: string;
10
+ names_only?: boolean;
11
+ }
12
+ export type APIResponse = Record<string, any>;
13
+ export interface ClientOptions {
14
+ baseUrl?: string;
15
+ timeout?: number;
16
+ maxRetries?: number;
17
+ }
18
+ export interface RequestOptions {
19
+ idempotencyKey?: string;
20
+ }
21
+ export declare class Client {
22
+ readonly baseUrl: string;
23
+ private readonly apiKey;
24
+ private readonly timeoutMs;
25
+ private readonly maxRetries;
26
+ constructor(apiKey: string, options?: ClientOptions);
27
+ convert(code: string, source: string, target: string | string[], options?: RequestOptions): Promise<APIResponse>;
28
+ convertToAll(code: string, source: string, options?: RequestOptions & {
29
+ to?: string | string[];
30
+ includeCard?: boolean;
31
+ }): Promise<APIResponse>;
32
+ convertBulk(codes: Array<{
33
+ code: string;
34
+ from: string;
35
+ }>, options?: RequestOptions & {
36
+ to?: string | string[];
37
+ includeCard?: boolean;
38
+ }): Promise<APIResponse>;
39
+ view(code: string, bookmaker: string): Promise<APIResponse>;
40
+ viewImage(code: string, bookmaker: string): Promise<Uint8Array>;
41
+ split(code: string, bookmaker: string, options?: RequestOptions & {
42
+ count?: number;
43
+ pattern?: "equal" | "by_batches" | "target_odds" | "custom" | "alternate" | "blocks";
44
+ order?: "mixed" | "by_start_time" | "slip" | "kickoff";
45
+ targetOdds?: number;
46
+ counts?: number[];
47
+ }): Promise<APIResponse>;
48
+ merge(pairs: Array<Record<string, string>>, options?: RequestOptions & {
49
+ target?: string;
50
+ }): Promise<APIResponse>;
51
+ book(bookmaker: string, options?: RequestOptions & {
52
+ planId?: string;
53
+ picks?: Array<Record<string, unknown>>;
54
+ to?: string[];
55
+ strict?: boolean;
56
+ acceptOddsChange?: boolean;
57
+ }): Promise<APIResponse>;
58
+ eventsSearch(bookmaker: string, queries: Array<Record<string, unknown>>, options?: RequestOptions & {
59
+ sport?: string;
60
+ includeMarkets?: boolean;
61
+ marketFilter?: string[];
62
+ includeUnbookable?: boolean;
63
+ detail?: "compact" | "full" | "agent";
64
+ }): Promise<APIResponse>;
65
+ events(query?: Query): Promise<APIResponse>;
66
+ /**
67
+ * List the markets of one event. Pass `market` as a string or an array;
68
+ * an array sends one `market=` parameter for each name, so one call reads
69
+ * several markets and the response lists absent names in `not_found`.
70
+ */
71
+ eventMarkets(eventId: string, query?: EventMarketsQuery): Promise<APIResponse>;
72
+ resolve(bookmaker: string, picks: Array<Record<string, unknown>>, options?: RequestOptions & {
73
+ strict?: boolean;
74
+ acceptOddsChange?: boolean;
75
+ detail?: "compact" | "full" | "agent";
76
+ }): Promise<APIResponse>;
77
+ markets(): Promise<APIResponse>;
78
+ bookmakers(): Promise<APIResponse>;
79
+ errors(): Promise<APIResponse>;
80
+ books(query?: Query): Promise<APIResponse>;
81
+ bookGet(bookId: string): Promise<APIResponse>;
82
+ capabilities(): Promise<APIResponse>;
83
+ usage(): Promise<APIResponse>;
84
+ history(query?: Query): Promise<APIResponse>;
85
+ historyGet(rowId: string): Promise<APIResponse>;
86
+ webhooksCreate(url: string, options?: RequestOptions & {
87
+ events?: string[];
88
+ }): Promise<APIResponse>;
89
+ webhooks(): Promise<APIResponse>;
90
+ webhookDelete(webhookId: string): Promise<APIResponse>;
91
+ webhookTest(webhookId: string, options?: RequestOptions): Promise<APIResponse>;
92
+ jobsCreate(payload: Record<string, unknown>, options?: RequestOptions): Promise<APIResponse>;
93
+ job(jobId: string): Promise<APIResponse>;
94
+ jobs(query?: Query): Promise<APIResponse>;
95
+ cancelJob(jobId: string): Promise<APIResponse>;
96
+ trackStart(code: string, bookmaker: string, options?: RequestOptions & {
97
+ mode?: "ticket" | "game";
98
+ label?: string;
99
+ webhookUrl?: string;
100
+ }): Promise<APIResponse>;
101
+ track(trackId: string): Promise<APIResponse>;
102
+ tracks(query?: Query): Promise<APIResponse>;
103
+ stopTrack(trackId: string): Promise<APIResponse>;
104
+ private get;
105
+ private post;
106
+ private request;
107
+ private send;
108
+ private toError;
109
+ }
package/dist/client.js ADDED
@@ -0,0 +1,324 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { APIError, errorFromResponse } from "./errors.js";
3
+ export const VERSION = "1.0.2";
4
+ export const BASE_URL = "https://api.managebetcodes.app/v1";
5
+ const RETRY_STATUSES = new Set([429, 502, 503, 504]);
6
+ const NON_RETRYABLE_CODES = new Set([
7
+ "api_quota_exhausted",
8
+ "plan_quota_exhausted",
9
+ "search_quota_exhausted",
10
+ ]);
11
+ const MAX_BACKOFF_MS = 30_000;
12
+ function compact(value) {
13
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
14
+ }
15
+ function sleep(milliseconds) {
16
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
17
+ }
18
+ function retryAfterSeconds(value) {
19
+ if (!value) {
20
+ return undefined;
21
+ }
22
+ const cap = MAX_BACKOFF_MS / 1000;
23
+ const seconds = Number(value);
24
+ if (Number.isFinite(seconds)) {
25
+ return Math.min(Math.max(0, seconds), cap);
26
+ }
27
+ const when = Date.parse(value);
28
+ if (Number.isNaN(when)) {
29
+ return undefined;
30
+ }
31
+ return Math.min(Math.max(0, (when - Date.now()) / 1000), cap);
32
+ }
33
+ function backoffMilliseconds(attempt) {
34
+ return Math.min(500 * 2 ** attempt, MAX_BACKOFF_MS);
35
+ }
36
+ export class Client {
37
+ baseUrl;
38
+ apiKey;
39
+ timeoutMs;
40
+ maxRetries;
41
+ constructor(apiKey, options = {}) {
42
+ if (!apiKey) {
43
+ throw new Error("apiKey is required");
44
+ }
45
+ if (options.maxRetries !== undefined && options.maxRetries < 0) {
46
+ throw new Error("maxRetries must be zero or more");
47
+ }
48
+ this.apiKey = apiKey;
49
+ this.baseUrl = (options.baseUrl ?? BASE_URL).replace(/\/+$/, "");
50
+ this.timeoutMs = (options.timeout ?? 30) * 1000;
51
+ this.maxRetries = options.maxRetries ?? 3;
52
+ }
53
+ convert(code, source, target, options = {}) {
54
+ return this.post("/convert", { code, from: source, to: target }, options.idempotencyKey);
55
+ }
56
+ convertToAll(code, source, options = {}) {
57
+ return this.post("/convert/all", compact({
58
+ code,
59
+ from: source,
60
+ to: options.to,
61
+ include_card: options.includeCard,
62
+ }), options.idempotencyKey);
63
+ }
64
+ convertBulk(codes, options = {}) {
65
+ return this.post("/convert/bulk", compact({
66
+ codes,
67
+ to: options.to,
68
+ include_card: options.includeCard,
69
+ }), options.idempotencyKey);
70
+ }
71
+ view(code, bookmaker) {
72
+ return this.get("/view", { code, bookmaker });
73
+ }
74
+ async viewImage(code, bookmaker) {
75
+ const response = await this.send("GET", "/view/image", {
76
+ query: { code, bookmaker },
77
+ accept: "image/png",
78
+ });
79
+ return new Uint8Array(await response.arrayBuffer());
80
+ }
81
+ split(code, bookmaker, options = {}) {
82
+ return this.post("/split", compact({
83
+ code,
84
+ bookmaker,
85
+ count: options.count ?? 2,
86
+ pattern: options.pattern ?? "equal",
87
+ order: options.order ?? "mixed",
88
+ target_odds: options.targetOdds,
89
+ counts: options.counts,
90
+ }), options.idempotencyKey);
91
+ }
92
+ merge(pairs, options = {}) {
93
+ return this.post("/merge", compact({ pairs, target: options.target }), options.idempotencyKey);
94
+ }
95
+ book(bookmaker, options = {}) {
96
+ return this.post("/book", compact({
97
+ bookmaker,
98
+ plan_id: options.planId,
99
+ picks: options.picks,
100
+ to: options.to,
101
+ strict: options.strict,
102
+ accept_odds_change: options.acceptOddsChange,
103
+ }), options.idempotencyKey);
104
+ }
105
+ eventsSearch(bookmaker, queries, options = {}) {
106
+ return this.post("/events/search", compact({
107
+ bookmaker,
108
+ queries,
109
+ sport: options.sport,
110
+ include_markets: options.includeMarkets,
111
+ market_filter: options.marketFilter,
112
+ include_unbookable: options.includeUnbookable,
113
+ detail: options.detail,
114
+ }), options.idempotencyKey);
115
+ }
116
+ events(query = {}) {
117
+ return this.get("/events", query);
118
+ }
119
+ /**
120
+ * List the markets of one event. Pass `market` as a string or an array;
121
+ * an array sends one `market=` parameter for each name, so one call reads
122
+ * several markets and the response lists absent names in `not_found`.
123
+ */
124
+ eventMarkets(eventId, query = {}) {
125
+ return this.get(`/events/${encodeURIComponent(eventId)}/markets`, query);
126
+ }
127
+ resolve(bookmaker, picks, options = {}) {
128
+ return this.post("/resolve", compact({
129
+ bookmaker,
130
+ picks,
131
+ strict: options.strict,
132
+ accept_odds_change: options.acceptOddsChange,
133
+ detail: options.detail,
134
+ }), options.idempotencyKey);
135
+ }
136
+ markets() {
137
+ return this.get("/markets");
138
+ }
139
+ bookmakers() {
140
+ return this.get("/bookmakers");
141
+ }
142
+ errors() {
143
+ return this.get("/errors");
144
+ }
145
+ books(query = {}) {
146
+ return this.get("/books", query);
147
+ }
148
+ bookGet(bookId) {
149
+ return this.get(`/books/${encodeURIComponent(bookId)}`);
150
+ }
151
+ capabilities() {
152
+ return this.get("/capabilities");
153
+ }
154
+ usage() {
155
+ return this.get("/usage");
156
+ }
157
+ history(query = {}) {
158
+ return this.get("/history", query);
159
+ }
160
+ historyGet(rowId) {
161
+ return this.get(`/history/${encodeURIComponent(rowId)}`);
162
+ }
163
+ webhooksCreate(url, options = {}) {
164
+ return this.post("/webhooks", compact({ url, events: options.events }), options.idempotencyKey);
165
+ }
166
+ webhooks() {
167
+ return this.get("/webhooks");
168
+ }
169
+ webhookDelete(webhookId) {
170
+ return this.request("DELETE", `/webhooks/${encodeURIComponent(webhookId)}`);
171
+ }
172
+ webhookTest(webhookId, options = {}) {
173
+ return this.post(`/webhooks/${encodeURIComponent(webhookId)}/test`, {}, options.idempotencyKey);
174
+ }
175
+ jobsCreate(payload, options = {}) {
176
+ return this.post("/jobs", payload, options.idempotencyKey);
177
+ }
178
+ job(jobId) {
179
+ return this.get(`/jobs/${encodeURIComponent(jobId)}`);
180
+ }
181
+ jobs(query = {}) {
182
+ return this.get("/jobs", query);
183
+ }
184
+ cancelJob(jobId) {
185
+ return this.request("DELETE", `/jobs/${encodeURIComponent(jobId)}`);
186
+ }
187
+ trackStart(code, bookmaker, options = {}) {
188
+ return this.post("/track", compact({
189
+ code,
190
+ bookmaker,
191
+ mode: options.mode,
192
+ label: options.label,
193
+ webhook_url: options.webhookUrl,
194
+ }), options.idempotencyKey);
195
+ }
196
+ track(trackId) {
197
+ return this.get(`/track/${encodeURIComponent(trackId)}`);
198
+ }
199
+ tracks(query = {}) {
200
+ return this.get("/tracks", query);
201
+ }
202
+ stopTrack(trackId) {
203
+ return this.request("DELETE", `/track/${encodeURIComponent(trackId)}`);
204
+ }
205
+ get(path, query) {
206
+ return this.request("GET", path, { query });
207
+ }
208
+ post(path, body, idempotencyKey) {
209
+ return this.request("POST", path, { body, idempotencyKey });
210
+ }
211
+ async request(method, path, options = {}) {
212
+ const response = await this.send(method, path, options);
213
+ if (response.status === 204) {
214
+ return undefined;
215
+ }
216
+ const text = await response.text();
217
+ if (!text) {
218
+ return {};
219
+ }
220
+ try {
221
+ return JSON.parse(text);
222
+ }
223
+ catch {
224
+ throw new APIError("The API returned a response that is not JSON.", {
225
+ status: response.status,
226
+ code: "invalid_json",
227
+ });
228
+ }
229
+ }
230
+ async send(method, path, options = {}) {
231
+ const url = new URL(this.baseUrl + path);
232
+ for (const [key, value] of Object.entries(options.query ?? {})) {
233
+ if (value === undefined || value === null || value === "") {
234
+ continue;
235
+ }
236
+ if (Array.isArray(value)) {
237
+ for (const item of value) {
238
+ url.searchParams.append(key, String(item));
239
+ }
240
+ continue;
241
+ }
242
+ url.searchParams.set(key, String(value));
243
+ }
244
+ const headers = {
245
+ "X-API-Key": this.apiKey,
246
+ Accept: options.accept ?? "application/json",
247
+ "User-Agent": `managebetcodes-node/${VERSION}`,
248
+ };
249
+ let payload;
250
+ if (options.body !== undefined) {
251
+ payload = JSON.stringify(options.body);
252
+ headers["Content-Type"] = "application/json";
253
+ }
254
+ const idempotencyKey = method === "POST" ? (options.idempotencyKey ?? `sdk_${randomUUID()}`) : undefined;
255
+ if (idempotencyKey) {
256
+ headers["Idempotency-Key"] = idempotencyKey;
257
+ }
258
+ for (let attempt = 0;; attempt += 1) {
259
+ const controller = new AbortController();
260
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
261
+ let response;
262
+ try {
263
+ response = await fetch(url, {
264
+ method,
265
+ headers,
266
+ body: payload,
267
+ signal: controller.signal,
268
+ });
269
+ }
270
+ catch (error) {
271
+ if (error instanceof Error && error.name === "AbortError") {
272
+ throw new APIError("The request timed out.", { code: "timeout" });
273
+ }
274
+ throw new APIError(`The request to the API failed: ${String(error)}`, {
275
+ code: "network_error",
276
+ });
277
+ }
278
+ finally {
279
+ clearTimeout(timer);
280
+ }
281
+ if (RETRY_STATUSES.has(response.status) && attempt < this.maxRetries) {
282
+ let payload = null;
283
+ if (response.status === 429) {
284
+ try {
285
+ payload = await response.clone().json();
286
+ }
287
+ catch {
288
+ payload = null;
289
+ }
290
+ const code = payload && typeof payload === "object" && "error" in payload
291
+ ? payload.error?.code
292
+ : undefined;
293
+ if (typeof code === "string" && NON_RETRYABLE_CODES.has(code)) {
294
+ throw await this.toError(response, payload);
295
+ }
296
+ }
297
+ const retryAfter = retryAfterSeconds(response.headers.get("retry-after"));
298
+ const delay = retryAfter === undefined ? backoffMilliseconds(attempt) : retryAfter * 1000;
299
+ await response.body?.cancel();
300
+ await sleep(delay);
301
+ continue;
302
+ }
303
+ if (response.ok) {
304
+ return response;
305
+ }
306
+ throw await this.toError(response);
307
+ }
308
+ }
309
+ async toError(response, payload) {
310
+ if (payload === undefined) {
311
+ const text = await response.text();
312
+ payload = null;
313
+ if (text) {
314
+ try {
315
+ payload = JSON.parse(text);
316
+ }
317
+ catch {
318
+ payload = null;
319
+ }
320
+ }
321
+ }
322
+ return errorFromResponse(response.status, payload, retryAfterSeconds(response.headers.get("retry-after")));
323
+ }
324
+ }
@@ -0,0 +1,32 @@
1
+ export interface APIErrorOptions {
2
+ status?: number;
3
+ code?: string;
4
+ requestId?: string;
5
+ docs?: string;
6
+ details?: unknown;
7
+ }
8
+ export declare class APIError extends Error {
9
+ readonly status: number;
10
+ readonly code: string;
11
+ readonly requestId?: string;
12
+ readonly docs?: string;
13
+ readonly details?: unknown;
14
+ constructor(message: string, options?: APIErrorOptions);
15
+ toString(): string;
16
+ }
17
+ export declare class AuthenticationError extends APIError {
18
+ constructor(message: string, options?: APIErrorOptions);
19
+ }
20
+ export declare class QuotaError extends APIError {
21
+ constructor(message: string, options?: APIErrorOptions);
22
+ }
23
+ export declare class RateLimitError extends APIError {
24
+ readonly retryAfter?: number;
25
+ constructor(message: string, options?: APIErrorOptions & {
26
+ retryAfter?: number;
27
+ });
28
+ }
29
+ export declare class ValidationError extends APIError {
30
+ constructor(message: string, options?: APIErrorOptions);
31
+ }
32
+ export declare function errorFromResponse(status: number, payload: unknown, retryAfter?: number): APIError;
package/dist/errors.js ADDED
@@ -0,0 +1,84 @@
1
+ export class APIError extends Error {
2
+ status;
3
+ code;
4
+ requestId;
5
+ docs;
6
+ details;
7
+ constructor(message, options = {}) {
8
+ super(message);
9
+ this.name = "APIError";
10
+ this.status = options.status ?? 0;
11
+ this.code = options.code ?? "api_error";
12
+ this.requestId = options.requestId;
13
+ this.docs = options.docs;
14
+ this.details = options.details;
15
+ }
16
+ toString() {
17
+ return this.status > 0 ? `HTTP ${this.status} [${this.code}]: ${this.message}` : this.message;
18
+ }
19
+ }
20
+ export class AuthenticationError extends APIError {
21
+ constructor(message, options = {}) {
22
+ super(message, options);
23
+ this.name = "AuthenticationError";
24
+ }
25
+ }
26
+ export class QuotaError extends APIError {
27
+ constructor(message, options = {}) {
28
+ super(message, options);
29
+ this.name = "QuotaError";
30
+ }
31
+ }
32
+ export class RateLimitError extends APIError {
33
+ retryAfter;
34
+ constructor(message, options = {}) {
35
+ const { retryAfter, ...rest } = options;
36
+ super(message, rest);
37
+ this.name = "RateLimitError";
38
+ this.retryAfter = retryAfter;
39
+ }
40
+ }
41
+ export class ValidationError extends APIError {
42
+ constructor(message, options = {}) {
43
+ super(message, options);
44
+ this.name = "ValidationError";
45
+ }
46
+ }
47
+ const QUOTA_CODES = new Set([
48
+ "api_quota_exhausted",
49
+ "plan_quota_exhausted",
50
+ "search_quota_exhausted",
51
+ ]);
52
+ function isRecord(value) {
53
+ return typeof value === "object" && value !== null;
54
+ }
55
+ export function errorFromResponse(status, payload, retryAfter) {
56
+ let envelope = {};
57
+ if (isRecord(payload) && isRecord(payload.error)) {
58
+ envelope = payload.error;
59
+ }
60
+ const code = typeof envelope.code === "string" ? envelope.code : `http_${status}`;
61
+ const message = typeof envelope.message === "string"
62
+ ? envelope.message
63
+ : `The API returned HTTP ${status}.`;
64
+ const options = {
65
+ status,
66
+ code,
67
+ requestId: typeof envelope.request_id === "string" ? envelope.request_id : undefined,
68
+ docs: typeof envelope.docs === "string" ? envelope.docs : undefined,
69
+ details: envelope.details,
70
+ };
71
+ if (status === 401 || status === 403) {
72
+ return new AuthenticationError(message, options);
73
+ }
74
+ if (status === 429 && QUOTA_CODES.has(code)) {
75
+ return new QuotaError(message, options);
76
+ }
77
+ if (status === 429) {
78
+ return new RateLimitError(message, { ...options, retryAfter });
79
+ }
80
+ if (status === 400 || status === 422) {
81
+ return new ValidationError(message, options);
82
+ }
83
+ return new APIError(message, options);
84
+ }
@@ -0,0 +1,4 @@
1
+ export { Client, BASE_URL, VERSION } from "./client.js";
2
+ export type { APIResponse, ClientOptions, Query, QueryValue, RequestOptions, } from "./client.js";
3
+ export { APIError, AuthenticationError, QuotaError, RateLimitError, ValidationError, } from "./errors.js";
4
+ export { verifyWebhook } from "./webhooks.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { Client, BASE_URL, VERSION } from "./client.js";
2
+ export { APIError, AuthenticationError, QuotaError, RateLimitError, ValidationError, } from "./errors.js";
3
+ export { verifyWebhook } from "./webhooks.js";
@@ -0,0 +1,2 @@
1
+ /** Return true when the signature matches the raw request body. */
2
+ export declare function verifyWebhook(secret: string, body: Uint8Array | ArrayBuffer | string, signature: string): boolean;
@@ -0,0 +1,30 @@
1
+ import { createHmac } from "node:crypto";
2
+ const encoder = new TextEncoder();
3
+ const PREFIX = "sha256=";
4
+ function safeEqual(left, right) {
5
+ if (left.length !== right.length) {
6
+ return false;
7
+ }
8
+ let difference = 0;
9
+ for (let index = 0; index < left.length; index += 1) {
10
+ difference |= left.charCodeAt(index) ^ right.charCodeAt(index);
11
+ }
12
+ return difference === 0;
13
+ }
14
+ /** Return true when the signature matches the raw request body. */
15
+ export function verifyWebhook(secret, body, signature) {
16
+ if (!secret || !signature || !signature.trim()) {
17
+ return false;
18
+ }
19
+ const bytes = typeof body === "string"
20
+ ? encoder.encode(body)
21
+ : body instanceof Uint8Array
22
+ ? body
23
+ : new Uint8Array(body);
24
+ const expected = createHmac("sha256", secret).update(bytes).digest("hex");
25
+ let provided = signature.trim();
26
+ if (provided.toLowerCase().startsWith(PREFIX)) {
27
+ provided = provided.slice(PREFIX.length);
28
+ }
29
+ return safeEqual(expected, provided.toLowerCase());
30
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@managebetcodes/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.2",
4
+ "description": "Official TypeScript SDK for the Manage Bet Codes public API v1",
5
+ "license": "MIT",
6
+ "author": "Manage Bet Codes",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/kayceepeece/Viewbetbot.git",
10
+ "directory": "sdk/typescript"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/kayceepeece/Viewbetbot/issues"
14
+ },
15
+ "homepage": "https://managebetcodes.app/developers/sdk/typescript",
16
+ "type": "module",
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ "exports": {
20
+ ".": {
21
+ "types": "./dist/index.d.ts",
22
+ "import": "./dist/index.js"
23
+ }
24
+ },
25
+ "bin": {
26
+ "mbc": "./dist/cli.js"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md"
31
+ ],
32
+ "sideEffects": false,
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "engines": {
37
+ "node": ">=18"
38
+ },
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.json",
41
+ "test": "npm run build && node --test test/client.test.mjs",
42
+ "test:contract": "node --test test/openapi-contract.test.mjs",
43
+ "verify": "npm run test && npm run test:contract && npm pack --dry-run",
44
+ "prepack": "npm run build",
45
+ "prepublishOnly": "npm run test && npm run test:contract"
46
+ },
47
+ "keywords": [
48
+ "betting",
49
+ "bet-codes",
50
+ "sportybet",
51
+ "1xbet",
52
+ "managebetcodes"
53
+ ],
54
+ "devDependencies": {
55
+ "typescript": "^5.4.0"
56
+ }
57
+ }