@lovebowls/api 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 lovebowls.co.uk
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,161 @@
1
- # Temporary Holding Version
1
+ # @lovebowls/api
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
+ JavaScript SDK for the [lovebowls](https://www.lovebowls.co.uk) Public API: your club's details,
4
+ competitions, fixtures, results and league tables, for a website you build yourself.
5
+
6
+ Zero dependencies. Works in browsers and Node 18+ (it uses the global `fetch`). Written in TypeScript;
7
+ the types are generated from the API's OpenAPI contract.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @lovebowls/api
13
+ ```
14
+
15
+ Or, with no build step, from jsDelivr:
16
+
17
+ ```html
18
+ <script type="module">
19
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.1.0/+esm";
20
+ // or: ".../npm/@lovebowls/api@0.1.0/dist/index.js"
21
+ </script>
22
+ ```
23
+
24
+ ## Example: a plain HTML page
25
+
26
+ ```html
27
+ <ul id="fixtures"></ul>
28
+ <script type="module">
29
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.1.0/+esm";
30
+ const lb = new LovebowlsClient({ apiKey: "lb_pk_..." }); // your publishable key
31
+ const page = await lb.listFixtures("YOUR-CLUB-ID", { limit: 10 });
32
+ for (const f of page.items) {
33
+ const li = document.createElement("li");
34
+ li.textContent = `${f.start.slice(0, 10)} ${f.opponent ?? f.eventName}`;
35
+ document.getElementById("fixtures").append(li);
36
+ }
37
+ </script>
38
+ ```
39
+
40
+ ## Example: Node
41
+
42
+ ```js
43
+ import { LovebowlsClient, LovebowlsApiError } from "@lovebowls/api";
44
+
45
+ const lb = new LovebowlsClient({ apiKey: process.env.LOVEBOWLS_API_KEY });
46
+ try {
47
+ const club = await lb.getClub("YOUR-CLUB-ID");
48
+ console.log(club.name, club.teams.map((t) => t.name));
49
+ } catch (e) {
50
+ if (e instanceof LovebowlsApiError) console.error(e.status, e.code, e.requestId);
51
+ else throw e;
52
+ }
53
+ ```
54
+
55
+ ## The browser rule
56
+
57
+ A **publishable** key (`lb_pk_...`) is meant for browsers: it works only from the origins listed on the
58
+ key, and only for reading. **Never put a server key in a page**: the API refuses it from a browser
59
+ (`server_key_in_browser`), and anyone can read what a page sends. Keep server keys in server code and
60
+ environment variables.
61
+
62
+ ## Client
63
+
64
+ ```ts
65
+ new LovebowlsClient({
66
+ apiKey: "lb_pk_...", // required; sent as X-Api-Key
67
+ baseUrl: "https://api.lovebowls.co.uk/v1", // optional, this is the default
68
+ fetch: customFetch, // optional, default globalThis.fetch
69
+ });
70
+ ```
71
+
72
+ ## Methods
73
+
74
+ Method names are the API's `operationId`s. Every method returns a promise and throws
75
+ `LovebowlsApiError` on failure. Responses are the API's JSON unchanged: dates stay ISO strings.
76
+
77
+ | Method | Returns |
78
+ |---|---|
79
+ | `getClub(clubId)` | `Club`: name, time zone, teams, current season |
80
+ | `listCompetitions(clubId, { kind? })` | `{ items: Competition[] }` (not paged) |
81
+ | `listFixtures(clubId, { from?, to?, competition?, team?, kind?, limit?, cursor? })` | `Page<Fixture>` |
82
+ | `iterateFixtures(clubId, filters?)` | `AsyncIterable<Fixture>`, all pages |
83
+ | `getFixture(clubId, fixtureId)` | `Fixture` |
84
+ | `getLeague(leagueId)` | `League` with its table (leagues have no club id) |
85
+
86
+ Filters:
87
+
88
+ - `from` (inclusive) and `to` (exclusive) take a `Date` or an ISO string. A date-only string such as
89
+ `"2027-04-01"` is sent as is. Give both or neither; with neither you get the club's current season.
90
+ A range may not exceed 400 days.
91
+ - `competition` takes one competition id or an array (sent as a repeated parameter).
92
+ - `team` is a team id from `getClub`; `kind` is `"match"` or `"event"`.
93
+ - `limit` is 1 to 100 (default 50).
94
+
95
+ `listCompetitions` answers with `{ items }` rather than a bare array, as the contract says.
96
+
97
+ ## Paging
98
+
99
+ `listFixtures` returns one page: `{ items, nextCursor }`. `nextCursor` is `null` on the last page;
100
+ otherwise pass it back as `cursor`, with the same filters. `iterateFixtures` does that for you:
101
+
102
+ ```js
103
+ for await (const fixture of lb.iterateFixtures("YOUR-CLUB-ID", {
104
+ from: "2027-04-01",
105
+ to: "2027-10-01",
106
+ competition: ["COMP-ID-1", "COMP-ID-2"],
107
+ })) {
108
+ console.log(fixture.start, fixture.result?.text);
109
+ }
110
+ ```
111
+
112
+ ## Errors
113
+
114
+ Every failure is a `LovebowlsApiError` (an `Error`) with:
115
+
116
+ | Field | Meaning |
117
+ |---|---|
118
+ | `status` | HTTP status; `0` for `network_error` |
119
+ | `code` | stable machine-readable code: branch on this |
120
+ | `title`, `detail` | for people; may change. `detail` may be `null` |
121
+ | `requestId` | quote it when asking for support |
122
+ | `retryAfter` | seconds to wait, from `Retry-After` on 429 and 503; else `null` |
123
+
124
+ `code` is the API's problem code, for example `api_key_invalid`, `origin_not_allowed`,
125
+ `server_key_in_browser`, `club_mismatch`, `feature_not_in_plan`, `invalid_request`, `invalid_cursor`,
126
+ `club_not_found`, `fixture_not_found`, `league_not_found`, `rate_limited`, `upstream_error`
127
+ (safe to retry). The SDK adds two of its own:
128
+
129
+ - `network_error`: no answer (offline, DNS failure, a blocked cross-origin call, an abort);
130
+ - `invalid_response`: an answer that is not what the API sends (a non-JSON body, an error without a
131
+ problem document, or a paging cursor that repeats).
132
+
133
+ The API key is never included in an error message.
134
+
135
+ ```js
136
+ try {
137
+ await lb.getFixture(clubId, id);
138
+ } catch (e) {
139
+ if (e.code === "fixture_not_found") { /* show "no such fixture" */ }
140
+ else if (e.code === "rate_limited") await new Promise((r) => setTimeout(r, (e.retryAfter ?? 1) * 1000));
141
+ else throw e;
142
+ }
143
+ ```
144
+
145
+ ## Types
146
+
147
+ `Club`, `Competition`, `Fixture`, `Result`, `League`, `LeagueTableRow`, `Page<T>`, `Problem` and
148
+ `FixtureFilters` are exported. They are generated from `openapi.yaml`. The API only adds fields within v1, so
149
+ ignore unknown fields and unknown enum values (a new `kind`, say) as normal.
150
+
151
+ ## Development
152
+
153
+ ```sh
154
+ npm install
155
+ npm run generate # regenerate src/schema.ts from ../openapi.yaml
156
+ npm test # build, then run the tests (fake fetch, no network; fails if types are stale)
157
+ ```
158
+
159
+ ## Licence
160
+
161
+ MIT - see [LICENSE](LICENSE).
package/dist/index.cjs ADDED
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ API_BASE_URL: () => API_BASE_URL,
24
+ LovebowlsApiError: () => LovebowlsApiError,
25
+ LovebowlsClient: () => LovebowlsClient
26
+ });
27
+ module.exports = __toCommonJS(index_exports);
28
+ var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
29
+ var LovebowlsApiError = class _LovebowlsApiError extends Error {
30
+ status;
31
+ code;
32
+ title;
33
+ detail;
34
+ requestId;
35
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
36
+ retryAfter;
37
+ constructor(init) {
38
+ super(init.detail ? `${init.title}: ${init.detail}` : init.title);
39
+ this.name = "LovebowlsApiError";
40
+ this.status = init.status;
41
+ this.code = init.code;
42
+ this.title = init.title;
43
+ this.detail = init.detail ?? null;
44
+ this.requestId = init.requestId ?? null;
45
+ this.retryAfter = init.retryAfter ?? null;
46
+ if (init.cause !== void 0) this.cause = init.cause;
47
+ Object.setPrototypeOf(this, _LovebowlsApiError.prototype);
48
+ }
49
+ };
50
+ function toIso(name, v) {
51
+ if (v instanceof Date) {
52
+ if (Number.isNaN(v.getTime())) throw new TypeError(`${name} is an invalid Date`);
53
+ return v.toISOString();
54
+ }
55
+ return String(v);
56
+ }
57
+ function parseRetryAfter(h) {
58
+ if (!h) return null;
59
+ const s = h.trim();
60
+ if (/^\d+$/.test(s)) return Number(s);
61
+ const t = Date.parse(s);
62
+ return Number.isNaN(t) ? null : Math.max(0, Math.ceil((t - Date.now()) / 1e3));
63
+ }
64
+ function enc(id) {
65
+ return encodeURIComponent(String(id));
66
+ }
67
+ function query(...pairs) {
68
+ const usp = new URLSearchParams();
69
+ for (const [k, v] of pairs) if (v !== void 0) usp.append(k, v);
70
+ const s = usp.toString();
71
+ return s ? `?${s}` : "";
72
+ }
73
+ var LovebowlsClient = class {
74
+ #apiKey;
75
+ #baseUrl;
76
+ #fetch;
77
+ constructor(options) {
78
+ if (!options || typeof options.apiKey !== "string" || !options.apiKey) {
79
+ throw new TypeError("LovebowlsClient: apiKey is required");
80
+ }
81
+ this.#apiKey = options.apiKey;
82
+ this.#baseUrl = (options.baseUrl ?? API_BASE_URL).replace(/\/+$/, "");
83
+ this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
84
+ }
85
+ getClub(clubId) {
86
+ return this.#get(`/clubs/${enc(clubId)}`);
87
+ }
88
+ listCompetitions(clubId, options = {}) {
89
+ return this.#get(`/clubs/${enc(clubId)}/competitions`, query(["kind", options.kind]));
90
+ }
91
+ listFixtures(clubId, options = {}) {
92
+ const comp = options.competition === void 0 ? [] : [].concat(options.competition);
93
+ return this.#get(
94
+ `/clubs/${enc(clubId)}/fixtures`,
95
+ query(
96
+ ["from", options.from === void 0 ? void 0 : toIso("from", options.from)],
97
+ ["to", options.to === void 0 ? void 0 : toIso("to", options.to)],
98
+ ...comp.map((c) => ["competition", c]),
99
+ ["team", options.team],
100
+ ["kind", options.kind],
101
+ ["limit", options.limit === void 0 ? void 0 : String(options.limit)],
102
+ ["cursor", options.cursor]
103
+ )
104
+ );
105
+ }
106
+ /** Every fixture matching the filters, fetching pages (via `nextCursor`) as you iterate. */
107
+ async *iterateFixtures(clubId, filters = {}) {
108
+ let cursor;
109
+ for (; ; ) {
110
+ const page = await this.listFixtures(clubId, { ...filters, cursor });
111
+ for (const item of page.items) yield item;
112
+ const next = page.nextCursor;
113
+ if (next === null || next === void 0) return;
114
+ if (next === cursor) {
115
+ throw new LovebowlsApiError({
116
+ status: 200,
117
+ code: "invalid_response",
118
+ title: "Invalid response",
119
+ detail: "The API returned the same paging cursor twice."
120
+ });
121
+ }
122
+ cursor = next;
123
+ }
124
+ }
125
+ getFixture(clubId, fixtureId) {
126
+ return this.#get(`/clubs/${enc(clubId)}/fixtures/${enc(fixtureId)}`);
127
+ }
128
+ getLeague(leagueId) {
129
+ return this.#get(`/leagues/${enc(leagueId)}`);
130
+ }
131
+ async #get(path, search = "") {
132
+ let res;
133
+ try {
134
+ res = await this.#fetch(this.#baseUrl + path + search, {
135
+ method: "GET",
136
+ headers: { "X-Api-Key": this.#apiKey, Accept: "application/json" }
137
+ });
138
+ } catch (cause) {
139
+ throw new LovebowlsApiError({
140
+ status: 0,
141
+ code: "network_error",
142
+ title: "Network error",
143
+ detail: "The request could not be completed.",
144
+ cause
145
+ });
146
+ }
147
+ const requestId = res.headers.get("X-Request-Id");
148
+ let text = "";
149
+ try {
150
+ text = await res.text();
151
+ } catch (cause) {
152
+ throw new LovebowlsApiError({
153
+ status: res.status,
154
+ code: "network_error",
155
+ title: "Network error",
156
+ detail: "The response could not be read.",
157
+ requestId,
158
+ cause
159
+ });
160
+ }
161
+ let body;
162
+ let parsed = false;
163
+ try {
164
+ body = JSON.parse(text);
165
+ parsed = true;
166
+ } catch {
167
+ }
168
+ if (res.ok) {
169
+ if (!parsed) {
170
+ throw new LovebowlsApiError({
171
+ status: res.status,
172
+ code: "invalid_response",
173
+ title: "Invalid response",
174
+ detail: "The response was not JSON.",
175
+ requestId
176
+ });
177
+ }
178
+ return body;
179
+ }
180
+ const retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
181
+ const p = parsed && body && typeof body === "object" ? body : null;
182
+ if (p && typeof p.code === "string") {
183
+ throw new LovebowlsApiError({
184
+ status: res.status,
185
+ code: p.code,
186
+ title: typeof p.title === "string" ? p.title : res.statusText || "Error",
187
+ detail: typeof p.detail === "string" ? p.detail : null,
188
+ requestId: typeof p.requestId === "string" ? p.requestId : requestId,
189
+ retryAfter
190
+ });
191
+ }
192
+ throw new LovebowlsApiError({
193
+ status: res.status,
194
+ code: "invalid_response",
195
+ title: res.statusText || "Error",
196
+ detail: `The API answered ${res.status} with a body that was not a problem document.`,
197
+ requestId,
198
+ retryAfter
199
+ });
200
+ }
201
+ };
@@ -0,0 +1,95 @@
1
+ /**
2
+ * @lovebowls/api - JavaScript SDK for the lovebowls Public API (contract: ../openapi.yaml).
3
+ * Zero runtime dependencies; works in browsers and Node 18+ (global `fetch`).
4
+ * Types come from ./schema.ts, generated from the contract by `npm run generate`.
5
+ */
6
+ import type { components, operations } from "./schema";
7
+ export declare const API_BASE_URL = "https://api.lovebowls.co.uk/v1";
8
+ type Schemas = components["schemas"];
9
+ export type Club = Schemas["Club"];
10
+ export type Competition = Schemas["Competition"];
11
+ export type CompetitionSummary = Schemas["CompetitionSummary"];
12
+ export type Fixture = Schemas["Fixture"];
13
+ export type FixtureKind = Schemas["FixtureKind"];
14
+ export type Result = Schemas["Result"];
15
+ export type League = Schemas["League"];
16
+ export type LeagueTableRow = Schemas["LeagueTableRow"];
17
+ export type Problem = Schemas["Problem"];
18
+ /** One page of a paged list. `nextCursor` is `null` on the last page. */
19
+ export type Page<T> = Omit<Schemas["Page"], "items"> & {
20
+ items: T[];
21
+ };
22
+ /** What `listCompetitions` returns: not paged, so just the items. */
23
+ export type CompetitionList = {
24
+ items: Competition[];
25
+ };
26
+ /** A date as the SDK accepts it: a `Date`, or an ISO string (a date-only string stays date-only). */
27
+ export type DateInput = Date | string;
28
+ export interface FixtureFilters {
29
+ /** Start of the range, inclusive. Send both `from` and `to`, or neither. */
30
+ from?: DateInput;
31
+ /** End of the range, exclusive. */
32
+ to?: DateInput;
33
+ /** One competition id, or several (sent as a repeated parameter). */
34
+ competition?: string | string[];
35
+ /** A team id from `getClub`. */
36
+ team?: string;
37
+ kind?: FixtureKind;
38
+ }
39
+ export interface ListFixturesOptions extends FixtureFilters {
40
+ /** Items per page, 1 to 100. */
41
+ limit?: number;
42
+ /** The `nextCursor` of the previous page, unchanged, with the same filters. */
43
+ cursor?: string;
44
+ }
45
+ export interface ListCompetitionsOptions {
46
+ kind?: FixtureKind;
47
+ }
48
+ export interface LovebowlsClientOptions {
49
+ /** Your API key (`lb_pk_...` in a browser). Sent as `X-Api-Key`. */
50
+ apiKey: string;
51
+ /** Default `https://api.lovebowls.co.uk/v1`. */
52
+ baseUrl?: string;
53
+ /** Default `globalThis.fetch`. */
54
+ fetch?: typeof fetch;
55
+ }
56
+ export type OperationId = keyof Pick<operations, "getClub" | "listCompetitions" | "listFixtures" | "getFixture" | "getLeague">;
57
+ /**
58
+ * Thrown for every failure. `code` is the gateway's stable problem code (for example
59
+ * `fixture_not_found`, `rate_limited`) or one the SDK raises itself:
60
+ * - `network_error`: the request never got an answer (offline, DNS, CORS, abort);
61
+ * - `invalid_response`: the answer was not what the API sends (non-JSON, wrong shape, a paging loop).
62
+ * `status` is 0 for `network_error`. The API key is never part of the message.
63
+ */
64
+ export declare class LovebowlsApiError extends Error {
65
+ status: number;
66
+ code: string;
67
+ title: string;
68
+ detail: string | null;
69
+ requestId: string | null;
70
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
71
+ retryAfter: number | null;
72
+ constructor(init: {
73
+ status: number;
74
+ code: string;
75
+ title: string;
76
+ detail?: string | null;
77
+ requestId?: string | null;
78
+ retryAfter?: number | null;
79
+ cause?: unknown;
80
+ });
81
+ }
82
+ export declare class LovebowlsClient {
83
+ #private;
84
+ constructor(options: LovebowlsClientOptions);
85
+ getClub(clubId: string): Promise<Club>;
86
+ listCompetitions(clubId: string, options?: ListCompetitionsOptions): Promise<CompetitionList>;
87
+ listFixtures(clubId: string, options?: ListFixturesOptions): Promise<Page<Fixture>>;
88
+ /** Every fixture matching the filters, fetching pages (via `nextCursor`) as you iterate. */
89
+ iterateFixtures(clubId: string, filters?: FixtureFilters & {
90
+ limit?: number;
91
+ }): AsyncIterable<Fixture>;
92
+ getFixture(clubId: string, fixtureId: string): Promise<Fixture>;
93
+ getLeague(leagueId: string): Promise<League>;
94
+ }
95
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,180 @@
1
+ // src/index.ts
2
+ var API_BASE_URL = "https://api.lovebowls.co.uk/v1";
3
+ var LovebowlsApiError = class _LovebowlsApiError extends Error {
4
+ status;
5
+ code;
6
+ title;
7
+ detail;
8
+ requestId;
9
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
10
+ retryAfter;
11
+ constructor(init) {
12
+ super(init.detail ? `${init.title}: ${init.detail}` : init.title);
13
+ this.name = "LovebowlsApiError";
14
+ this.status = init.status;
15
+ this.code = init.code;
16
+ this.title = init.title;
17
+ this.detail = init.detail ?? null;
18
+ this.requestId = init.requestId ?? null;
19
+ this.retryAfter = init.retryAfter ?? null;
20
+ if (init.cause !== void 0) this.cause = init.cause;
21
+ Object.setPrototypeOf(this, _LovebowlsApiError.prototype);
22
+ }
23
+ };
24
+ function toIso(name, v) {
25
+ if (v instanceof Date) {
26
+ if (Number.isNaN(v.getTime())) throw new TypeError(`${name} is an invalid Date`);
27
+ return v.toISOString();
28
+ }
29
+ return String(v);
30
+ }
31
+ function parseRetryAfter(h) {
32
+ if (!h) return null;
33
+ const s = h.trim();
34
+ if (/^\d+$/.test(s)) return Number(s);
35
+ const t = Date.parse(s);
36
+ return Number.isNaN(t) ? null : Math.max(0, Math.ceil((t - Date.now()) / 1e3));
37
+ }
38
+ function enc(id) {
39
+ return encodeURIComponent(String(id));
40
+ }
41
+ function query(...pairs) {
42
+ const usp = new URLSearchParams();
43
+ for (const [k, v] of pairs) if (v !== void 0) usp.append(k, v);
44
+ const s = usp.toString();
45
+ return s ? `?${s}` : "";
46
+ }
47
+ var LovebowlsClient = class {
48
+ #apiKey;
49
+ #baseUrl;
50
+ #fetch;
51
+ constructor(options) {
52
+ if (!options || typeof options.apiKey !== "string" || !options.apiKey) {
53
+ throw new TypeError("LovebowlsClient: apiKey is required");
54
+ }
55
+ this.#apiKey = options.apiKey;
56
+ this.#baseUrl = (options.baseUrl ?? API_BASE_URL).replace(/\/+$/, "");
57
+ this.#fetch = options.fetch ?? ((input, init) => globalThis.fetch(input, init));
58
+ }
59
+ getClub(clubId) {
60
+ return this.#get(`/clubs/${enc(clubId)}`);
61
+ }
62
+ listCompetitions(clubId, options = {}) {
63
+ return this.#get(`/clubs/${enc(clubId)}/competitions`, query(["kind", options.kind]));
64
+ }
65
+ listFixtures(clubId, options = {}) {
66
+ const comp = options.competition === void 0 ? [] : [].concat(options.competition);
67
+ return this.#get(
68
+ `/clubs/${enc(clubId)}/fixtures`,
69
+ query(
70
+ ["from", options.from === void 0 ? void 0 : toIso("from", options.from)],
71
+ ["to", options.to === void 0 ? void 0 : toIso("to", options.to)],
72
+ ...comp.map((c) => ["competition", c]),
73
+ ["team", options.team],
74
+ ["kind", options.kind],
75
+ ["limit", options.limit === void 0 ? void 0 : String(options.limit)],
76
+ ["cursor", options.cursor]
77
+ )
78
+ );
79
+ }
80
+ /** Every fixture matching the filters, fetching pages (via `nextCursor`) as you iterate. */
81
+ async *iterateFixtures(clubId, filters = {}) {
82
+ let cursor;
83
+ for (; ; ) {
84
+ const page = await this.listFixtures(clubId, { ...filters, cursor });
85
+ for (const item of page.items) yield item;
86
+ const next = page.nextCursor;
87
+ if (next === null || next === void 0) return;
88
+ if (next === cursor) {
89
+ throw new LovebowlsApiError({
90
+ status: 200,
91
+ code: "invalid_response",
92
+ title: "Invalid response",
93
+ detail: "The API returned the same paging cursor twice."
94
+ });
95
+ }
96
+ cursor = next;
97
+ }
98
+ }
99
+ getFixture(clubId, fixtureId) {
100
+ return this.#get(`/clubs/${enc(clubId)}/fixtures/${enc(fixtureId)}`);
101
+ }
102
+ getLeague(leagueId) {
103
+ return this.#get(`/leagues/${enc(leagueId)}`);
104
+ }
105
+ async #get(path, search = "") {
106
+ let res;
107
+ try {
108
+ res = await this.#fetch(this.#baseUrl + path + search, {
109
+ method: "GET",
110
+ headers: { "X-Api-Key": this.#apiKey, Accept: "application/json" }
111
+ });
112
+ } catch (cause) {
113
+ throw new LovebowlsApiError({
114
+ status: 0,
115
+ code: "network_error",
116
+ title: "Network error",
117
+ detail: "The request could not be completed.",
118
+ cause
119
+ });
120
+ }
121
+ const requestId = res.headers.get("X-Request-Id");
122
+ let text = "";
123
+ try {
124
+ text = await res.text();
125
+ } catch (cause) {
126
+ throw new LovebowlsApiError({
127
+ status: res.status,
128
+ code: "network_error",
129
+ title: "Network error",
130
+ detail: "The response could not be read.",
131
+ requestId,
132
+ cause
133
+ });
134
+ }
135
+ let body;
136
+ let parsed = false;
137
+ try {
138
+ body = JSON.parse(text);
139
+ parsed = true;
140
+ } catch {
141
+ }
142
+ if (res.ok) {
143
+ if (!parsed) {
144
+ throw new LovebowlsApiError({
145
+ status: res.status,
146
+ code: "invalid_response",
147
+ title: "Invalid response",
148
+ detail: "The response was not JSON.",
149
+ requestId
150
+ });
151
+ }
152
+ return body;
153
+ }
154
+ const retryAfter = parseRetryAfter(res.headers.get("Retry-After"));
155
+ const p = parsed && body && typeof body === "object" ? body : null;
156
+ if (p && typeof p.code === "string") {
157
+ throw new LovebowlsApiError({
158
+ status: res.status,
159
+ code: p.code,
160
+ title: typeof p.title === "string" ? p.title : res.statusText || "Error",
161
+ detail: typeof p.detail === "string" ? p.detail : null,
162
+ requestId: typeof p.requestId === "string" ? p.requestId : requestId,
163
+ retryAfter
164
+ });
165
+ }
166
+ throw new LovebowlsApiError({
167
+ status: res.status,
168
+ code: "invalid_response",
169
+ title: res.statusText || "Error",
170
+ detail: `The API answered ${res.status} with a body that was not a problem document.`,
171
+ requestId,
172
+ retryAfter
173
+ });
174
+ }
175
+ };
176
+ export {
177
+ API_BASE_URL,
178
+ LovebowlsApiError,
179
+ LovebowlsClient
180
+ };