@lovebowls/api 0.0.0-stage → 0.2.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,297 @@
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, and (from 0.2) member login with the signed-in
5
+ member's own details and calendar, for a website you build yourself.
6
+
7
+ Zero dependencies. Works in browsers and Node 18+ (it uses the global `fetch`). Written in TypeScript;
8
+ the types are generated from the API's OpenAPI contract.
9
+
10
+ ## Install
11
+
12
+ ```sh
13
+ npm install @lovebowls/api
14
+ ```
15
+
16
+ Or, with no build step, from jsDelivr:
17
+
18
+ ```html
19
+ <script type="module">
20
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm";
21
+ // or: ".../npm/@lovebowls/api@0.2.0/dist/index.js"
22
+ </script>
23
+ ```
24
+
25
+ ## Example: a plain HTML page
26
+
27
+ ```html
28
+ <ul id="fixtures"></ul>
29
+ <script type="module">
30
+ import { LovebowlsClient } from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm";
31
+ const lb = new LovebowlsClient({ apiKey: "lb_pk_..." }); // your publishable key
32
+ const page = await lb.listFixtures("YOUR-CLUB-ID", { limit: 10 });
33
+ for (const f of page.items) {
34
+ const li = document.createElement("li");
35
+ li.textContent = `${f.start.slice(0, 10)} ${f.opponent ?? f.eventName}`;
36
+ document.getElementById("fixtures").append(li);
37
+ }
38
+ </script>
39
+ ```
40
+
41
+ ## Example: Node
42
+
43
+ ```js
44
+ import { LovebowlsClient, LovebowlsApiError } from "@lovebowls/api";
45
+
46
+ const lb = new LovebowlsClient({ apiKey: process.env.LOVEBOWLS_API_KEY });
47
+ try {
48
+ const club = await lb.getClub("YOUR-CLUB-ID");
49
+ console.log(club.name, club.teams.map((t) => t.name));
50
+ } catch (e) {
51
+ if (e instanceof LovebowlsApiError) console.error(e.status, e.code, e.requestId);
52
+ else throw e;
53
+ }
54
+ ```
55
+
56
+ ## The browser rule
57
+
58
+ A **publishable** key (`lb_pk_...`) is meant for browsers: it works only from the origins listed on the
59
+ key, and only for reading. **Never put a server key in a page**: the API refuses it from a browser
60
+ (`server_key_in_browser`), and anyone can read what a page sends. Keep server keys in server code and
61
+ environment variables.
62
+
63
+ ## Client
64
+
65
+ ```ts
66
+ new LovebowlsClient({
67
+ apiKey: "lb_pk_...", // required; sent as X-Api-Key
68
+ auth, // optional: a LovebowlsAuth, for member methods
69
+ memberToken, // optional: a token (or async function) you already hold
70
+ baseUrl: "https://api.lovebowls.co.uk/v1", // optional, this is the default
71
+ fetch: customFetch, // optional, default globalThis.fetch
72
+ });
73
+ ```
74
+
75
+ ## Methods
76
+
77
+ Method names are the API's `operationId`s. Every method returns a promise and throws
78
+ `LovebowlsApiError` on failure. Responses are the API's JSON unchanged: dates stay ISO strings.
79
+
80
+ | Method | Returns |
81
+ |---|---|
82
+ | `getClub(clubId)` | `Club`: name, time zone, teams, current season |
83
+ | `listCompetitions(clubId, { kind? })` | `{ items: Competition[] }` (not paged) |
84
+ | `listFixtures(clubId, { from?, to?, competition?, team?, kind?, limit?, cursor? })` | `Page<Fixture>` |
85
+ | `iterateFixtures(clubId, filters?)` | `AsyncIterable<Fixture>`, all pages |
86
+ | `getFixture(clubId, fixtureId)` | `Fixture` |
87
+ | `getLeague(leagueId)` | `League` with its table (leagues have no club id) |
88
+ | `getMe(clubId)` | `Me`: the signed-in member's own record. Needs a member token |
89
+ | `getMyCalendar(clubId, { from?, to? })` | `{ items: CalendarEntry[] }`: the member's own calendar. Needs a member token; `from`/`to` as for fixtures |
90
+
91
+ Filters:
92
+
93
+ - `from` (inclusive) and `to` (exclusive) take a `Date` or an ISO string. A date-only string such as
94
+ `"2027-04-01"` is sent as is. Give both or neither; with neither you get the club's current season.
95
+ A range may not exceed 400 days.
96
+ - `competition` takes one competition id or an array (sent as a repeated parameter).
97
+ - `team` is a team id from `getClub`; `kind` is `"match"` or `"event"`.
98
+ - `limit` is 1 to 100 (default 50).
99
+
100
+ `listCompetitions` answers with `{ items }` rather than a bare array, as the contract says.
101
+
102
+ ## Paging
103
+
104
+ `listFixtures` returns one page: `{ items, nextCursor }`. `nextCursor` is `null` on the last page;
105
+ otherwise pass it back as `cursor`, with the same filters. `iterateFixtures` does that for you:
106
+
107
+ ```js
108
+ for await (const fixture of lb.iterateFixtures("YOUR-CLUB-ID", {
109
+ from: "2027-04-01",
110
+ to: "2027-10-01",
111
+ competition: ["COMP-ID-1", "COMP-ID-2"],
112
+ })) {
113
+ console.log(fixture.start, fixture.result?.text);
114
+ }
115
+ ```
116
+
117
+ ## Errors
118
+
119
+ Every failure is a `LovebowlsApiError` (an `Error`) with:
120
+
121
+ | Field | Meaning |
122
+ |---|---|
123
+ | `status` | HTTP status; `0` for `network_error` |
124
+ | `code` | stable machine-readable code: branch on this |
125
+ | `title`, `detail` | for people; may change. `detail` may be `null` |
126
+ | `requestId` | quote it when asking for support |
127
+ | `retryAfter` | seconds to wait, from `Retry-After` on 429 and 503; else `null` |
128
+
129
+ `code` is the API's problem code, for example `api_key_invalid`, `member_token_invalid`, `not_a_member`, `origin_not_allowed`,
130
+ `server_key_in_browser`, `club_mismatch`, `feature_not_in_plan`, `invalid_request`, `invalid_cursor`,
131
+ `club_not_found`, `fixture_not_found`, `league_not_found`, `rate_limited`, `upstream_error`
132
+ (safe to retry). The SDK adds some of its own:
133
+
134
+ - `network_error`: no answer (offline, DNS failure, a blocked cross-origin call, an abort);
135
+ - `invalid_response`: an answer that is not what the API sends (a non-JSON body, an error without a
136
+ problem document, or a paging cursor that repeats);
137
+ - `member_token_required`: a member method with no usable token, so no request was made (`status` 0);
138
+ - `login_failed`, `state_mismatch`: the sign-in did not complete (see Member login).
139
+
140
+ Neither the API key nor a member token is ever included in an error message.
141
+
142
+ ```js
143
+ try {
144
+ await lb.getFixture(clubId, id);
145
+ } catch (e) {
146
+ if (e.code === "fixture_not_found") { /* show "no such fixture" */ }
147
+ else if (e.code === "rate_limited") await new Promise((r) => setTimeout(r, (e.retryAfter ?? 1) * 1000));
148
+ else throw e;
149
+ }
150
+ ```
151
+
152
+ ## Member login
153
+
154
+ Member methods (`getMe`, `getMyCalendar`) need a **member token**: the member signs in on the
155
+ lovebowls login page and your page receives a short-lived token. `LovebowlsAuth` does the whole OAuth
156
+ flow (authorization code with PKCE, plain `fetch`, no other library); `LovebowlsClient` then sends the
157
+ token as `Authorization: Bearer <token>` on member calls only. A page that never logs anyone in needs none
158
+ of this.
159
+
160
+ You need two things from lovebowls: your **OAuth client id**, and your page's **redirect URI** added to the
161
+ client's list. The redirect URI must match **exactly** (scheme, host, path, trailing slash); anything else is
162
+ refused by Wix at the login page. It is the page that calls `handleRedirect()`.
163
+
164
+ ### In a plain HTML page
165
+
166
+ Use one page as both the login button and the return page. Import from the copy the API serves (no CDN) or
167
+ from jsDelivr:
168
+
169
+ ```html
170
+ <button id="login">Log in</button> <button id="logout" hidden>Log out</button>
171
+ <pre id="me"></pre>
172
+ <script type="module">
173
+ import { LovebowlsClient, LovebowlsAuth } from "https://api.lovebowls.co.uk/docs/example/lovebowls-api.js";
174
+ // or: from "https://cdn.jsdelivr.net/npm/@lovebowls/api@0.2.0/+esm"
175
+
176
+ const auth = new LovebowlsAuth({
177
+ clientId: "YOUR-OAUTH-CLIENT-ID",
178
+ redirectUri: location.origin + location.pathname, // must be on the client's list, exactly
179
+ });
180
+ const lb = new LovebowlsClient({ apiKey: "lb_pk_...", auth });
181
+ const CLUB = "YOUR-CLUB-ID";
182
+ const out = document.getElementById("me");
183
+
184
+ async function show() {
185
+ const loggedIn = auth.isLoggedIn();
186
+ document.getElementById("login").hidden = loggedIn;
187
+ document.getElementById("logout").hidden = !loggedIn;
188
+ out.textContent = "";
189
+ if (!loggedIn) return;
190
+ try {
191
+ out.textContent = JSON.stringify(await lb.getMe(CLUB), null, 2);
192
+ } catch (e) {
193
+ if (e.code === "not_a_member") out.textContent = "You are not a member of this club.";
194
+ else if (e.code === "member_token_required" || e.code === "member_token_invalid") show(); // session ended: offer login
195
+ else throw e;
196
+ }
197
+ }
198
+
199
+ try { await auth.handleRedirect(); } catch (e) { console.error(e.code); } // true if we just came back from the login
200
+ auth.onChange(show);
201
+ document.getElementById("login").onclick = () => auth.login();
202
+ document.getElementById("logout").onclick = () => auth.logout();
203
+ show();
204
+ </script>
205
+ ```
206
+
207
+ `handleRedirect()` is safe to call on every page load: it returns `false` when the page is not a login
208
+ return. When it is, it checks the `state` it stored before leaving, exchanges the code, and removes
209
+ `#code=...&state=...` from the address bar.
210
+
211
+ ### Options
212
+
213
+ ```ts
214
+ new LovebowlsAuth({
215
+ clientId: "...", // required
216
+ redirectUri: "https://...", // required, exact match on the client's list
217
+ storage: "session", // "session" (default) | "local" | "memory" | your own { getItem, setItem, removeItem }
218
+ offlineAccess: false, // true: also get a refresh token (see below)
219
+ postLogoutUrl: redirectUri, // where Wix sends the browser after logout()
220
+ fetch: customFetch, // optional
221
+ });
222
+ ```
223
+
224
+ Methods: `login()`, `handleRedirect()`, `isLoggedIn()`, `getAccessToken()`, `logout({ redirect? })`,
225
+ `onChange(cb)` (returns an unsubscribe function; `cb(loggedIn)` also fires when an expired session is dropped).
226
+
227
+ ### Where the token lives
228
+
229
+ By default the login asks for **only an access token**, which Wix issues for **4 hours**. It is kept in
230
+ `sessionStorage` (gone when the tab closes) under the key `lovebowls.auth.tokens`; during the trip to the login
231
+ page the PKCE secret is in `sessionStorage` too (`lovebowls.auth.pkce`) and is deleted on return.
232
+ `storage: "local"` survives closing the browser. `storage: "memory"` keeps the token in the page only, so it is
233
+ lost on reload. Any script on your page can read browser storage, so do not load scripts you do not trust.
234
+
235
+ When the 4 hours pass, `isLoggedIn()` turns `false`, the stored token is removed, and member methods throw
236
+ `member_token_required` without making a request: show your login button again.
237
+
238
+ ### Refresh tokens: off by default, and why
239
+
240
+ `offlineAccess: true` asks Wix for a refresh token as well, stores it in the same storage, and renews the
241
+ access token silently (just before it expires, and once, with one retry, if the API answers
242
+ `member_token_invalid`). The cost is a long-lived credential in the browser. **Measured: a Wix logout revokes
243
+ neither the access token nor the refresh token, and Wix has no revoke endpoint.** A stolen refresh token keeps
244
+ working after the member has logged out. Turn it on only if your members really need to stay signed in for
245
+ days, and prefer `storage: "session"`.
246
+
247
+ ### Logout
248
+
249
+ `logout()` **always clears the stored tokens and login state first**, in this browser, then (unless
250
+ `redirect: false`) sends the browser to Wix's logout page, which returns to `postLogoutUrl`. That URL's origin
251
+ must be an allowed redirect domain on the OAuth client. Wix's logout does not revoke tokens already issued, so a
252
+ copy of the access token taken earlier stays valid until its 4 hours are up: logging out protects this browser,
253
+ not a token someone already copied.
254
+
255
+ ### Member errors
256
+
257
+ | `code` | Meaning | What to do |
258
+ |---|---|---|
259
+ | `member_token_required` | no usable token (never logged in, or the session ended); **no request was made** | offer login |
260
+ | `member_token_invalid` | the API refused the token (expired, revoked or not ours). With a refresh token the SDK tries once more first; otherwise the session is cleared | offer login |
261
+ | `not_a_member` (403) | a valid login, but not a member of this club | tell the person; logging in again will not help |
262
+ | `state_mismatch`, `login_failed` | thrown by `handleRedirect()` or `login()`: the return did not match, was refused, or Wix did not answer | start again |
263
+
264
+ ### Node and servers
265
+
266
+ If you already hold a member token, pass it. There is no `window` and no `LovebowlsAuth`:
267
+
268
+ ```js
269
+ import { LovebowlsClient } from "@lovebowls/api";
270
+
271
+ const lb = new LovebowlsClient({
272
+ apiKey: process.env.LOVEBOWLS_API_KEY,
273
+ memberToken: async () => myTokenStore.get(userId), // or a plain string
274
+ });
275
+ const me = await lb.getMe("YOUR-CLUB-ID");
276
+ ```
277
+
278
+ Importing the package never touches a browser global, so it is safe in Node. The client does not renew a
279
+ `memberToken` for you: on `member_token_invalid`, get a new one and call again.
280
+
281
+ ## Types
282
+
283
+ `Club`, `Competition`, `Fixture`, `Result`, `League`, `LeagueTableRow`, `Me`, `CalendarEntry`,
284
+ `MyFixtureStatus`, `ClubRole`, `Page<T>`, `Problem` and `FixtureFilters` are exported. They are generated from `openapi.yaml`. The API only adds fields within v1, so
285
+ ignore unknown fields and unknown enum values (a new `kind`, say) as normal.
286
+
287
+ ## Development
288
+
289
+ ```sh
290
+ npm install
291
+ npm run generate # regenerate src/schema.ts from ../openapi.yaml
292
+ npm test # build, then run the tests (fake fetch, no network; fails if types are stale)
293
+ ```
294
+
295
+ ## Licence
296
+
297
+ MIT - see [LICENSE](LICENSE).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /** The part of `Storage` the SDK uses. */
2
+ export interface StorageLike {
3
+ getItem(key: string): string | null;
4
+ setItem(key: string, value: string): void;
5
+ removeItem(key: string): void;
6
+ }
7
+ /** The part of `window.location` the SDK uses. */
8
+ export interface LocationLike {
9
+ hash: string;
10
+ pathname: string;
11
+ search: string;
12
+ assign(url: string): void;
13
+ }
14
+ export type AuthStorage = "session" | "local" | "memory";
15
+ export interface LovebowlsAuthOptions {
16
+ /** The OAuth client id of your site's login (public). Ask lovebowls for it. */
17
+ clientId: string;
18
+ /** The page that handles the sign-in return. Must be on the OAuth client's list of redirect URIs, exactly. */
19
+ redirectUri: string;
20
+ /**
21
+ * Where the member token is kept: `"session"` (default, `sessionStorage`), `"local"`, `"memory"` (lost on
22
+ * reload), or your own `StorageLike`.
23
+ */
24
+ storage?: AuthStorage | StorageLike;
25
+ /** Also ask for a refresh token (silent renewal after the 4-hour access token). Off by default: see the README. */
26
+ offlineAccess?: boolean;
27
+ /** Where Wix sends the browser after `logout()`. Default `redirectUri`. Its origin must be an allowed redirect domain. */
28
+ postLogoutUrl?: string;
29
+ /** Default `globalThis.fetch`. */
30
+ fetch?: typeof fetch;
31
+ /** Default `window.location`. */
32
+ location?: LocationLike;
33
+ /** Default `window.history` (only `replaceState` is used, to clear the sign-in fragment). */
34
+ history?: {
35
+ replaceState(data: unknown, unused: string, url?: string | null): void;
36
+ };
37
+ }
38
+ export declare class LovebowlsAuth {
39
+ #private;
40
+ constructor(options: LovebowlsAuthOptions);
41
+ /** Drop the stored tokens and PKCE state and tell listeners. The client calls it when a token proves invalid. */
42
+ clearSession(): void;
43
+ /** Start the sign-in: builds PKCE and state, stores them, and sends the browser to Wix's login page. */
44
+ login(): Promise<void>;
45
+ /**
46
+ * Call once on page load at `redirectUri`. Returns `true` when it completed a sign-in, `false` when the page
47
+ * was not a sign-in return. Throws `state_mismatch` or `login_failed` (and clears the PKCE state) otherwise.
48
+ * The fragment (`#code=...`) is removed from the address bar either way.
49
+ */
50
+ handleRedirect(): Promise<boolean>;
51
+ /** `true` while a member token is held that has not expired (or can be refreshed). */
52
+ isLoggedIn(): boolean;
53
+ /** The current access token, refreshed first when it is about to expire and a refresh token is held; else `null`. */
54
+ getAccessToken(): Promise<string | null>;
55
+ /** Exchange the refresh token for a new access token. `false` when none is held or Wix refuses (a refusal clears the session). */
56
+ refresh(): Promise<boolean>;
57
+ /**
58
+ * Sign out. The stored tokens and PKCE state are cleared first, always. Then, unless `redirect: false`, the browser
59
+ * goes to Wix's logout URL and comes back to `postLogoutUrl`. Wix's logout does not revoke tokens already issued.
60
+ */
61
+ logout(options?: {
62
+ redirect?: boolean;
63
+ }): Promise<void>;
64
+ /** Listen for sign-in and sign-out (including an expired session being dropped). Returns the unsubscribe function. */
65
+ onChange(cb: (loggedIn: boolean) => void): () => void;
66
+ }
@@ -0,0 +1,33 @@
1
+ import type { components } from "./schema";
2
+ type Problem = components["schemas"]["Problem"];
3
+ export type { Problem };
4
+ /**
5
+ * Thrown for every failure. `code` is the gateway's stable problem code (for example
6
+ * `fixture_not_found`, `rate_limited`) or one the SDK raises itself:
7
+ * - `network_error`: the request never got an answer (offline, DNS, CORS, abort);
8
+ * - `invalid_response`: the answer was not what the API sends (non-JSON, wrong shape, a paging loop);
9
+ * - `member_token_required`: a member method with no usable member token (never logged in, or the session
10
+ * expired); no request was made. The API itself also sends this code;
11
+ * - `login_failed`, `state_mismatch`: raised by `LovebowlsAuth` when the sign-in did not complete.
12
+ * The API also sends `member_token_invalid` and `not_a_member` (403).
13
+ * `status` is 0 for `network_error` and the SDK-raised codes. Neither the API key nor a member token is ever
14
+ * part of the message.
15
+ */
16
+ export declare class LovebowlsApiError extends Error {
17
+ status: number;
18
+ code: string;
19
+ title: string;
20
+ detail: string | null;
21
+ requestId: string | null;
22
+ /** Seconds to wait, from `Retry-After` (429 and 503); `null` when absent. */
23
+ retryAfter: number | null;
24
+ constructor(init: {
25
+ status: number;
26
+ code: string;
27
+ title: string;
28
+ detail?: string | null;
29
+ requestId?: string | null;
30
+ retryAfter?: number | null;
31
+ cause?: unknown;
32
+ });
33
+ }