keeperboard 1.0.3 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -9,55 +9,92 @@ var KeeperBoardError = class extends Error {
9
9
  };
10
10
 
11
11
  // src/KeeperBoardClient.ts
12
- var KeeperBoardClient = class {
12
+ var _KeeperBoardClient = class _KeeperBoardClient {
13
13
  constructor(config) {
14
- this.apiUrl = config.apiUrl.replace(/\/$/, "");
14
+ const url = config.apiUrl ?? _KeeperBoardClient.DEFAULT_API_URL;
15
+ this.apiUrl = url.replace(/\/$/, "");
15
16
  this.apiKey = config.apiKey;
17
+ this.defaultLeaderboard = config.defaultLeaderboard;
16
18
  }
17
- async submitScore(playerGuid, playerName, score, leaderboard, metadata) {
19
+ // ============================================
20
+ // SCORE SUBMISSION
21
+ // ============================================
22
+ /**
23
+ * Submit a score. Only updates if the new score is higher than the existing one.
24
+ *
25
+ * @example
26
+ * const result = await client.submitScore({
27
+ * playerGuid: 'abc-123',
28
+ * playerName: 'ACE',
29
+ * score: 1500,
30
+ * });
31
+ * console.log(result.rank, result.isNewHighScore);
32
+ */
33
+ async submitScore(options) {
34
+ const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
18
35
  const params = new URLSearchParams();
19
- if (leaderboard) {
20
- params.set("leaderboard", leaderboard);
21
- }
36
+ if (leaderboard) params.set("leaderboard", leaderboard);
22
37
  const url = `${this.apiUrl}/api/v1/scores${params.toString() ? "?" + params.toString() : ""}`;
23
38
  const body = {
24
- player_guid: playerGuid,
25
- player_name: playerName,
26
- score,
27
- ...metadata && { metadata }
39
+ player_guid: options.playerGuid,
40
+ player_name: options.playerName,
41
+ score: options.score,
42
+ ...options.metadata && { metadata: options.metadata }
28
43
  };
29
- return this.request(url, {
44
+ const raw = await this.request(url, {
30
45
  method: "POST",
31
46
  body: JSON.stringify(body)
32
47
  });
48
+ return this.mapScoreResponse(raw);
33
49
  }
34
- async getLeaderboard(name, limit = 10, offset = 0) {
35
- const params = new URLSearchParams();
36
- params.set("limit", String(Math.min(limit, 100)));
37
- params.set("offset", String(offset));
38
- if (name) {
39
- params.set("leaderboard", name);
40
- }
41
- const url = `${this.apiUrl}/api/v1/leaderboard?${params.toString()}`;
42
- return this.request(url, { method: "GET" });
43
- }
44
- async getLeaderboardVersion(name, version, limit = 10, offset = 0) {
50
+ // ============================================
51
+ // LEADERBOARD
52
+ // ============================================
53
+ /**
54
+ * Get a leaderboard. Supports pagination and version-based lookups for
55
+ * time-based boards.
56
+ *
57
+ * @example
58
+ * // Top 10 on default board
59
+ * const lb = await client.getLeaderboard();
60
+ *
61
+ * // Top 25 on a specific board
62
+ * const lb = await client.getLeaderboard({ leaderboard: 'Weekly', limit: 25 });
63
+ *
64
+ * // Historical version
65
+ * const lb = await client.getLeaderboard({ leaderboard: 'Weekly', version: 3 });
66
+ */
67
+ async getLeaderboard(options) {
68
+ const leaderboard = options?.leaderboard ?? this.defaultLeaderboard;
69
+ const limit = options?.limit ?? 10;
70
+ const offset = options?.offset ?? 0;
45
71
  const params = new URLSearchParams();
46
- params.set("leaderboard", name);
47
- params.set("version", String(version));
48
72
  params.set("limit", String(Math.min(limit, 100)));
49
73
  params.set("offset", String(offset));
74
+ if (leaderboard) params.set("leaderboard", leaderboard);
75
+ if (options?.version !== void 0) params.set("version", String(options.version));
50
76
  const url = `${this.apiUrl}/api/v1/leaderboard?${params.toString()}`;
51
- return this.request(url, { method: "GET" });
77
+ const raw = await this.request(url, { method: "GET" });
78
+ return this.mapLeaderboardResponse(raw);
52
79
  }
53
- async getPlayerRank(playerGuid, leaderboard) {
80
+ // ============================================
81
+ // PLAYER
82
+ // ============================================
83
+ /**
84
+ * Get a player's rank and score. Returns `null` if the player has no score.
85
+ *
86
+ * @example
87
+ * const player = await client.getPlayerRank({ playerGuid: 'abc-123' });
88
+ * if (player) console.log(`Rank #${player.rank}`);
89
+ */
90
+ async getPlayerRank(options) {
91
+ const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
54
92
  const params = new URLSearchParams();
55
- if (leaderboard) {
56
- params.set("leaderboard", leaderboard);
57
- }
58
- const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
93
+ if (leaderboard) params.set("leaderboard", leaderboard);
94
+ const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(options.playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
59
95
  try {
60
- return await this.request(url, { method: "GET" });
96
+ const raw = await this.request(url, { method: "GET" });
97
+ return this.mapPlayerResponse(raw);
61
98
  } catch (error) {
62
99
  if (error instanceof KeeperBoardError && error.code === "NOT_FOUND") {
63
100
  return null;
@@ -65,37 +102,52 @@ var KeeperBoardClient = class {
65
102
  throw error;
66
103
  }
67
104
  }
68
- async updatePlayerName(playerGuid, newName, leaderboard) {
105
+ /**
106
+ * Update a player's display name.
107
+ *
108
+ * @example
109
+ * const player = await client.updatePlayerName({
110
+ * playerGuid: 'abc-123',
111
+ * newName: 'MAVERICK',
112
+ * });
113
+ */
114
+ async updatePlayerName(options) {
115
+ const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
69
116
  const params = new URLSearchParams();
70
- if (leaderboard) {
71
- params.set("leaderboard", leaderboard);
72
- }
73
- const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
74
- return this.request(url, {
117
+ if (leaderboard) params.set("leaderboard", leaderboard);
118
+ const url = `${this.apiUrl}/api/v1/player/${encodeURIComponent(options.playerGuid)}${params.toString() ? "?" + params.toString() : ""}`;
119
+ const raw = await this.request(url, {
75
120
  method: "PUT",
76
- body: JSON.stringify({ player_name: newName })
121
+ body: JSON.stringify({ player_name: options.newName })
77
122
  });
123
+ return this.mapPlayerResponse(raw);
78
124
  }
79
- async claimScore(playerGuid, playerName, leaderboard) {
125
+ // ============================================
126
+ // CLAIM (for migrated scores)
127
+ // ============================================
128
+ /**
129
+ * Claim a migrated score by matching player name.
130
+ * Used when scores were imported without player GUIDs.
131
+ */
132
+ async claimScore(options) {
133
+ const leaderboard = options.leaderboard ?? this.defaultLeaderboard;
80
134
  const params = new URLSearchParams();
81
- if (leaderboard) {
82
- params.set("leaderboard", leaderboard);
83
- }
135
+ if (leaderboard) params.set("leaderboard", leaderboard);
84
136
  const url = `${this.apiUrl}/api/v1/claim${params.toString() ? "?" + params.toString() : ""}`;
85
- return this.request(url, {
137
+ const raw = await this.request(url, {
86
138
  method: "POST",
87
139
  body: JSON.stringify({
88
- player_guid: playerGuid,
89
- player_name: playerName
140
+ player_guid: options.playerGuid,
141
+ player_name: options.playerName
90
142
  })
91
143
  });
144
+ return this.mapClaimResponse(raw);
92
145
  }
93
146
  // ============================================
94
147
  // HEALTH CHECK
95
148
  // ============================================
96
149
  /**
97
- * Check if the API is healthy.
98
- * This endpoint does not require an API key.
150
+ * Check if the API is healthy. Does not require an API key.
99
151
  */
100
152
  async healthCheck() {
101
153
  const url = `${this.apiUrl}/api/v1/health`;
@@ -110,6 +162,51 @@ var KeeperBoardClient = class {
110
162
  return json.data;
111
163
  }
112
164
  // ============================================
165
+ // RESPONSE MAPPERS (snake_case → camelCase)
166
+ // ============================================
167
+ mapScoreResponse(raw) {
168
+ return {
169
+ id: raw.id,
170
+ playerGuid: raw.player_guid,
171
+ playerName: raw.player_name,
172
+ score: raw.score,
173
+ rank: raw.rank,
174
+ isNewHighScore: raw.is_new_high_score
175
+ };
176
+ }
177
+ mapLeaderboardResponse(raw) {
178
+ return {
179
+ entries: raw.entries.map((e) => ({
180
+ rank: e.rank,
181
+ playerGuid: e.player_guid,
182
+ playerName: e.player_name,
183
+ score: e.score
184
+ })),
185
+ totalCount: raw.total_count,
186
+ resetSchedule: raw.reset_schedule,
187
+ version: raw.version,
188
+ oldestVersion: raw.oldest_version,
189
+ nextReset: raw.next_reset
190
+ };
191
+ }
192
+ mapPlayerResponse(raw) {
193
+ return {
194
+ id: raw.id,
195
+ playerGuid: raw.player_guid,
196
+ playerName: raw.player_name,
197
+ score: raw.score,
198
+ rank: raw.rank
199
+ };
200
+ }
201
+ mapClaimResponse(raw) {
202
+ return {
203
+ claimed: raw.claimed,
204
+ score: raw.score,
205
+ rank: raw.rank,
206
+ playerName: raw.player_name
207
+ };
208
+ }
209
+ // ============================================
113
210
  // INTERNAL
114
211
  // ============================================
115
212
  async request(url, options) {
@@ -129,6 +226,8 @@ var KeeperBoardClient = class {
129
226
  return json.data;
130
227
  }
131
228
  };
229
+ _KeeperBoardClient.DEFAULT_API_URL = "https://keeperboard.vercel.app";
230
+ var KeeperBoardClient = _KeeperBoardClient;
132
231
 
133
232
  // src/PlayerIdentity.ts
134
233
  var DEFAULT_KEY_PREFIX = "keeperboard_";
@@ -217,8 +316,309 @@ var PlayerIdentity = class {
217
316
  });
218
317
  }
219
318
  };
319
+
320
+ // src/Cache.ts
321
+ var Cache = class {
322
+ constructor(ttlMs) {
323
+ this.fetchedAt = 0;
324
+ this.inflight = null;
325
+ this.ttlMs = ttlMs;
326
+ }
327
+ /**
328
+ * Get cached value if fresh, otherwise fetch via the provided function.
329
+ * Deduplicates concurrent calls — only one fetch runs at a time.
330
+ */
331
+ async getOrFetch(fetchFn) {
332
+ if (this.isFresh()) {
333
+ return this.data;
334
+ }
335
+ if (this.inflight) {
336
+ return this.inflight;
337
+ }
338
+ this.inflight = fetchFn().then((result) => {
339
+ this.data = result;
340
+ this.fetchedAt = Date.now();
341
+ this.inflight = null;
342
+ return result;
343
+ }).catch((err) => {
344
+ this.inflight = null;
345
+ throw err;
346
+ });
347
+ return this.inflight;
348
+ }
349
+ /**
350
+ * Trigger a background refresh without awaiting the result.
351
+ * Returns immediately. If a fetch is already in flight, does nothing.
352
+ */
353
+ refreshInBackground(fetchFn) {
354
+ if (this.inflight) return;
355
+ this.inflight = fetchFn().then((result) => {
356
+ this.data = result;
357
+ this.fetchedAt = Date.now();
358
+ this.inflight = null;
359
+ return result;
360
+ }).catch((err) => {
361
+ this.inflight = null;
362
+ throw err;
363
+ });
364
+ this.inflight.catch(() => {
365
+ });
366
+ }
367
+ /** Invalidate the cache, forcing the next getOrFetch to re-fetch. */
368
+ invalidate() {
369
+ this.fetchedAt = 0;
370
+ }
371
+ /** Get the cached value without fetching. Returns undefined if empty or stale. */
372
+ get() {
373
+ return this.isFresh() ? this.data : void 0;
374
+ }
375
+ /** Get the cached value even if stale. Returns undefined only if never fetched. */
376
+ getStale() {
377
+ return this.data;
378
+ }
379
+ /** Check if the cache has fresh (non-expired) data. */
380
+ isFresh() {
381
+ return this.data !== void 0 && Date.now() - this.fetchedAt < this.ttlMs;
382
+ }
383
+ };
384
+
385
+ // src/RetryQueue.ts
386
+ var DEFAULT_MAX_AGE_MS = 24 * 60 * 60 * 1e3;
387
+ var RetryQueue = class {
388
+ constructor(storageKey, maxAgeMs = DEFAULT_MAX_AGE_MS) {
389
+ this.storageKey = storageKey;
390
+ this.maxAgeMs = maxAgeMs;
391
+ }
392
+ /** Save a failed score for later retry. */
393
+ save(score, metadata) {
394
+ try {
395
+ const pending = { score, metadata, timestamp: Date.now() };
396
+ localStorage.setItem(this.storageKey, JSON.stringify(pending));
397
+ } catch {
398
+ }
399
+ }
400
+ /**
401
+ * Get the pending score, or null if none exists or it has expired.
402
+ * Automatically clears expired entries.
403
+ */
404
+ get() {
405
+ try {
406
+ const raw = localStorage.getItem(this.storageKey);
407
+ if (!raw) return null;
408
+ const pending = JSON.parse(raw);
409
+ if (Date.now() - pending.timestamp > this.maxAgeMs) {
410
+ this.clear();
411
+ return null;
412
+ }
413
+ return { score: pending.score, metadata: pending.metadata };
414
+ } catch {
415
+ return null;
416
+ }
417
+ }
418
+ /** Check if there's a pending score. */
419
+ hasPending() {
420
+ return this.get() !== null;
421
+ }
422
+ /** Clear the pending score. */
423
+ clear() {
424
+ try {
425
+ localStorage.removeItem(this.storageKey);
426
+ } catch {
427
+ }
428
+ }
429
+ };
430
+
431
+ // src/validation.ts
432
+ var DEFAULTS = {
433
+ minLength: 2,
434
+ maxLength: 12,
435
+ uppercase: true,
436
+ allowedPattern: /[^A-Z0-9_]/g
437
+ };
438
+ function validateName(input, options) {
439
+ const opts = { ...DEFAULTS, ...options };
440
+ let name = input.trim();
441
+ if (opts.uppercase) {
442
+ name = name.toUpperCase();
443
+ }
444
+ name = name.replace(opts.allowedPattern, "");
445
+ name = name.substring(0, opts.maxLength);
446
+ if (name.length < opts.minLength) {
447
+ return null;
448
+ }
449
+ return name;
450
+ }
451
+
452
+ // src/KeeperBoardSession.ts
453
+ var KeeperBoardSession = class {
454
+ constructor(config) {
455
+ this.isSubmitting = false;
456
+ this.client = new KeeperBoardClient({
457
+ apiKey: config.apiKey,
458
+ defaultLeaderboard: config.leaderboard,
459
+ apiUrl: config.apiUrl
460
+ });
461
+ this.identity = new PlayerIdentity(config.identity);
462
+ this.leaderboard = config.leaderboard;
463
+ this.defaultPlayerName = config.defaultPlayerName ?? "ANON";
464
+ this.cache = config.cache ? new Cache(config.cache.ttlMs) : null;
465
+ this.retryQueue = config.retry ? new RetryQueue(
466
+ `keeperboard_retry_${config.leaderboard}`,
467
+ config.retry.maxAgeMs
468
+ ) : null;
469
+ }
470
+ // ============================================
471
+ // IDENTITY
472
+ // ============================================
473
+ /** Get or create a persistent player GUID. */
474
+ getPlayerGuid() {
475
+ return this.identity.getOrCreatePlayerGuid();
476
+ }
477
+ /** Get the stored player name, falling back to defaultPlayerName. */
478
+ getPlayerName() {
479
+ return this.identity.getPlayerName() ?? this.defaultPlayerName;
480
+ }
481
+ /** Store a player name locally. Does NOT update the server — call updatePlayerName() for that. */
482
+ setPlayerName(name) {
483
+ this.identity.setPlayerName(name);
484
+ }
485
+ /** Validate a name using configurable rules. Returns sanitized string or null. */
486
+ validateName(input, options) {
487
+ return validateName(input, options);
488
+ }
489
+ // ============================================
490
+ // CORE API
491
+ // ============================================
492
+ /**
493
+ * Submit a score. Identity and leaderboard are auto-injected.
494
+ * Returns a discriminated union: `{ success: true, rank, isNewHighScore }` or `{ success: false, error }`.
495
+ *
496
+ * If retry is enabled, failed submissions are saved to localStorage for later retry.
497
+ * Prevents concurrent double-submissions.
498
+ */
499
+ async submitScore(score, metadata) {
500
+ if (this.isSubmitting) {
501
+ return { success: false, error: "Submission in progress" };
502
+ }
503
+ this.isSubmitting = true;
504
+ try {
505
+ const result = await this.client.submitScore({
506
+ playerGuid: this.getPlayerGuid(),
507
+ playerName: this.getPlayerName(),
508
+ score,
509
+ metadata
510
+ });
511
+ this.retryQueue?.clear();
512
+ if (this.cache) {
513
+ this.cache.invalidate();
514
+ this.cache.refreshInBackground(() => this.fetchSnapshot());
515
+ }
516
+ return {
517
+ success: true,
518
+ rank: result.rank,
519
+ isNewHighScore: result.isNewHighScore
520
+ };
521
+ } catch (error) {
522
+ this.retryQueue?.save(score, metadata);
523
+ return {
524
+ success: false,
525
+ error: error instanceof Error ? error.message : "Unknown error"
526
+ };
527
+ } finally {
528
+ this.isSubmitting = false;
529
+ }
530
+ }
531
+ /**
532
+ * Get a combined snapshot: leaderboard entries (with `isCurrentPlayer` flag)
533
+ * plus the current player's rank if they're outside the top N.
534
+ *
535
+ * Uses cache if enabled and fresh.
536
+ */
537
+ async getSnapshot(options) {
538
+ const limit = options?.limit ?? 10;
539
+ if (this.cache) {
540
+ return this.cache.getOrFetch(() => this.fetchSnapshot(limit));
541
+ }
542
+ return this.fetchSnapshot(limit);
543
+ }
544
+ /**
545
+ * Update the player's name on the server and locally.
546
+ * Returns true on success, false on failure.
547
+ */
548
+ async updatePlayerName(newName) {
549
+ try {
550
+ await this.client.updatePlayerName({
551
+ playerGuid: this.getPlayerGuid(),
552
+ newName
553
+ });
554
+ this.identity.setPlayerName(newName);
555
+ this.cache?.invalidate();
556
+ return true;
557
+ } catch {
558
+ return false;
559
+ }
560
+ }
561
+ /**
562
+ * Retry submitting a pending score (from a previous failed submission).
563
+ * Call this on app startup.
564
+ */
565
+ async retryPendingScore() {
566
+ const pending = this.retryQueue?.get();
567
+ if (!pending) return null;
568
+ const result = await this.submitScore(pending.score, pending.metadata);
569
+ if (result.success) {
570
+ this.retryQueue?.clear();
571
+ }
572
+ return result;
573
+ }
574
+ /** Check if there's a pending score in the retry queue. */
575
+ hasPendingScore() {
576
+ return this.retryQueue?.hasPending() ?? false;
577
+ }
578
+ /**
579
+ * Pre-fetch snapshot data in the background for instant display later.
580
+ * No-op if cache is disabled or already fresh.
581
+ */
582
+ prefetch() {
583
+ if (!this.cache) return;
584
+ if (this.cache.isFresh()) return;
585
+ this.cache.refreshInBackground(() => this.fetchSnapshot());
586
+ }
587
+ /** Escape hatch: access the underlying KeeperBoardClient. */
588
+ getClient() {
589
+ return this.client;
590
+ }
591
+ // ============================================
592
+ // INTERNAL
593
+ // ============================================
594
+ async fetchSnapshot(limit = 10) {
595
+ const playerGuid = this.getPlayerGuid();
596
+ const [leaderboard, playerRank] = await Promise.all([
597
+ this.client.getLeaderboard({ limit }),
598
+ this.client.getPlayerRank({ playerGuid })
599
+ ]);
600
+ const entries = leaderboard.entries.map((e) => ({
601
+ rank: e.rank,
602
+ playerGuid: e.playerGuid,
603
+ playerName: e.playerName,
604
+ score: e.score,
605
+ isCurrentPlayer: e.playerGuid === playerGuid
606
+ }));
607
+ const playerInEntries = entries.some((e) => e.isCurrentPlayer);
608
+ const effectivePlayerRank = playerRank && !playerInEntries ? playerRank : null;
609
+ return {
610
+ entries,
611
+ totalCount: leaderboard.totalCount,
612
+ playerRank: effectivePlayerRank
613
+ };
614
+ }
615
+ };
220
616
  export {
617
+ Cache,
221
618
  KeeperBoardClient,
222
619
  KeeperBoardError,
223
- PlayerIdentity
620
+ KeeperBoardSession,
621
+ PlayerIdentity,
622
+ RetryQueue,
623
+ validateName
224
624
  };
package/package.json CHANGED
@@ -1,15 +1,15 @@
1
1
  {
2
2
  "name": "keeperboard",
3
- "version": "1.0.3",
3
+ "version": "2.0.0",
4
4
  "description": "TypeScript client SDK for KeeperBoard leaderboard-as-a-service",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
8
  "exports": {
9
9
  ".": {
10
+ "types": "./dist/index.d.ts",
10
11
  "import": "./dist/index.mjs",
11
- "require": "./dist/index.js",
12
- "types": "./dist/index.d.ts"
12
+ "require": "./dist/index.js"
13
13
  }
14
14
  },
15
15
  "files": [