@kokimoki/app 3.1.3 → 3.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +1 -2
  2. package/dist/core/kokimoki-client.d.ts +4 -4
  3. package/dist/core/kokimoki-client.js +4 -4
  4. package/dist/index.d.ts +1 -2
  5. package/dist/index.js +1 -2
  6. package/dist/utils/valtio.d.ts +2 -5
  7. package/dist/utils/valtio.js +4 -2
  8. package/dist/version.d.ts +1 -1
  9. package/dist/version.js +1 -1
  10. package/docs/kokimoki-ai.instructions.md +4 -2
  11. package/docs/kokimoki-dynamic-stores.instructions.md +3 -3
  12. package/docs/kokimoki-i18n.instructions.md +1 -1
  13. package/docs/kokimoki-sdk.instructions.md +46 -7
  14. package/package.json +15 -2
  15. package/dist/fields.d.ts +0 -110
  16. package/dist/fields.js +0 -158
  17. package/dist/kokimoki-ai.d.ts +0 -153
  18. package/dist/kokimoki-ai.js +0 -164
  19. package/dist/kokimoki-awareness.d.ts +0 -21
  20. package/dist/kokimoki-awareness.js +0 -48
  21. package/dist/kokimoki-client-refactored.d.ts +0 -80
  22. package/dist/kokimoki-client-refactored.js +0 -400
  23. package/dist/kokimoki-client.d.ts +0 -362
  24. package/dist/kokimoki-client.js +0 -823
  25. package/dist/kokimoki-leaderboard.d.ts +0 -175
  26. package/dist/kokimoki-leaderboard.js +0 -203
  27. package/dist/kokimoki-local-store.d.ts +0 -11
  28. package/dist/kokimoki-local-store.js +0 -40
  29. package/dist/kokimoki-queue.d.ts +0 -0
  30. package/dist/kokimoki-queue.js +0 -38
  31. package/dist/kokimoki-req-res.d.ts +0 -0
  32. package/dist/kokimoki-req-res.js +0 -198
  33. package/dist/kokimoki-schema.d.ts +0 -113
  34. package/dist/kokimoki-schema.js +0 -162
  35. package/dist/kokimoki-storage.d.ts +0 -156
  36. package/dist/kokimoki-storage.js +0 -208
  37. package/dist/kokimoki-store.d.ts +0 -23
  38. package/dist/kokimoki-store.js +0 -117
  39. package/dist/kokimoki-transaction.d.ts +0 -18
  40. package/dist/kokimoki-transaction.js +0 -143
  41. package/dist/kokimoki.min.d.ts +0 -1244
  42. package/dist/kokimoki.min.js +0 -19108
  43. package/dist/kokimoki.min.js.map +0 -1
  44. package/dist/llms.txt +0 -665
  45. package/dist/message-queue.d.ts +0 -8
  46. package/dist/message-queue.js +0 -19
  47. package/dist/room-subscription-mode.d.ts +0 -5
  48. package/dist/room-subscription-mode.js +0 -6
  49. package/dist/room-subscription.d.ts +0 -15
  50. package/dist/room-subscription.js +0 -52
  51. package/dist/synced-schema.d.ts +0 -74
  52. package/dist/synced-schema.js +0 -83
  53. package/dist/synced-store.d.ts +0 -10
  54. package/dist/synced-store.js +0 -9
  55. package/dist/synced-types.d.ts +0 -47
  56. package/dist/synced-types.js +0 -67
  57. package/dist/ws-message-reader.d.ts +0 -11
  58. package/dist/ws-message-reader.js +0 -36
  59. package/dist/ws-message-type copy.d.ts +0 -6
  60. package/dist/ws-message-type copy.js +0 -7
  61. package/dist/ws-message-type.d.ts +0 -11
  62. package/dist/ws-message-type.js +0 -12
  63. package/dist/ws-message-writer.d.ts +0 -9
  64. package/dist/ws-message-writer.js +0 -45
package/dist/llms.txt DELETED
@@ -1,665 +0,0 @@
1
- # Kokimoki SDK
2
-
3
- The Kokimoki SDK is a comprehensive development toolkit for building real-time collaborative game applications
4
-
5
- ## General guidelines
6
-
7
- - **IMPORTANT** `kmClient` is the main entry point for Kokimoki SDK
8
- - Use `kmClient.id` as a unique identifier for each client (player)
9
- - Use `kmClient.store` for global stores and `kmClient.localStore` for local stores
10
- - Use `kmClient.transact` for atomic state updates across single store or multiple stores
11
- - Use `kmClient.storage.upload` and related API methods to handle file uploads (media, JSON, etc.) in application
12
- - Use `kmClient.serverTimestamp()` for time-related matters as this will be synced among players
13
- - Use `useSnapshot` hook from `valtio` to get reactive state inside React components
14
- - Use AI integration API methods: `kmClient.ai.chat`, `kmClient.ai.generateJson`, and `kmClient.ai.modifyImage` to add AI capabilities to application
15
- - Use leaderboard API methods: `kmClient.leaderboard.insertEntry`, `kmClient.leaderboard.upsertEntry`, `kmClient.leaderboard.listEntries`, and `kmClient.leaderboard.getBestEntry` to add leaderboard capabilities to application
16
-
17
- ## Kokimoki Client
18
-
19
- - The `kmClient` instance is created in [km-client.ts](../../src/services/km-client.ts)
20
- - The `kmClient` provides the following key functionalities:
21
- - `kmClient.store` and `kmClient.localStore` for creating stores
22
- - `kmClient.transact` for atomic state updates
23
- - `kmClient.serverTimestamp()` for synchronized timestamps
24
- - `kmClient.id` for unique player identification
25
-
26
- ## Client ID
27
-
28
- - Each client (player) has a unique `kmClient.id` (aka `clientId`), stable identifier that represents a player across multiple connections
29
- (client sessions)
30
- - The `kmClient.id` is persistent across client connections
31
- - The `kmClient.id` remains consistent after user reconnect or page reload
32
- - Use `kmClient.id` to identify players in global stores
33
- - Each client (player) can have multiple connections, but all connections share the same `kmClient.id`
34
-
35
- ## Kokimoki Store
36
-
37
- Kokimoki Store powered by `valtio` and `valtio-yjs` for real-time state management in Kokimoki game applications
38
-
39
- ### Store initialization
40
-
41
- - Stores should be defined in `src/state/stores/`
42
- - Store can be created in two ways:
43
- - `kmClient.localStore` is used for data stored on the player device (local)
44
- - `kmClient.store` is used for data shared among all players in a game (global)
45
-
46
- **Example: Creating a Store**
47
-
48
- ```typescript
49
- import { kmClient } from "@services/km-client";
50
-
51
- interface State {
52
- title: string;
53
- count: number;
54
- }
55
-
56
- const initialState: State = {
57
- title: "Store",
58
- count: 0,
59
- };
60
-
61
- // Initialize global store with initial state
62
- export const store = kmClient.store<PlayerState>("store-name", initialState);
63
- ```
64
-
65
- ### State management
66
-
67
- - State actions are functions that modify the store state by performing transactions
68
- - Actions should be defined in `/src/state/actions/`
69
- - Use async/await for all state transactions by `kmClient.transact` function for global stores
70
- - Transactions are atomic and ensure state consistency
71
- - ALWAYS update store state inside `kmClient.transact()` within action function
72
- - Prefer using records, not arrays: store collections as `Record<string, T>` with timestamp keys for automatic sorting and better sync performance
73
-
74
- **Example: Updating State**
75
-
76
- ```typescript
77
- import { store } from "../store";
78
-
79
- // Update state
80
- await kmClient.transact([store], ([state]) => {
81
- state.title = "New store";
82
- state.count += 1;
83
- });
84
- ```
85
-
86
- ### Combining Stores
87
-
88
- - Multiple stores can be updated in a single transaction
89
- - Prefer to update stores in a single transaction to ensure state consistency
90
-
91
- **Example: Multiple Stores**
92
-
93
- ```typescript
94
- // Update multiple stores in a single transaction
95
- await kmClient.transact([store1, store2], ([state1, state2]) => {
96
- state1.name = "My Store1";
97
- state2.name = "My Store2";
98
- });
99
- ```
100
-
101
- ### Reactive State in Components
102
-
103
- - Use `useSnapshot` hook from `valtio` to get reactive state inside React components
104
- - The component will re-render when the store state changes
105
-
106
- **Example: Using State in Components**
107
-
108
- ```tsx
109
- import { useSnapshot } from "valtio";
110
- import { store } from "../store";
111
-
112
- const Component = () => {
113
- // Get reactive snapshot of the store state
114
- const { title, count } = useSnapshot(store.proxy);
115
-
116
- return (
117
- <div>
118
- <h1>Title: {title}</h1>
119
- <p>Count: {count}</p>
120
- </div>
121
- );
122
- };
123
- ```
124
-
125
- ## Server Time Synchronization
126
-
127
- Kokimoki SDK implements a time synchronization system to ensure consistent timestamps across all connected clients, regardless of their local clock differences
128
-
129
- - Use `kmClient.serverTimestamp()` to get the current server-synchronized timestamp
130
- - The timestamp is a Epoch Unix Timestamp
131
- - Use server timestamps for time-related matters like event scheduling, timeouts, timers, etc.
132
-
133
- ## Storage
134
-
135
- Kokimoki SDK provides a storage service for uploading and managing files. Commonly used for media files (images, videos, audio), but also supports other file types like JSON or text files that aren't suitable for real-time stores. No setup required.
136
-
137
- Access storage API via `kmClient.storage`.
138
-
139
- ### API Methods
140
-
141
- #### storage.upload(name, blob, tags?): Promise<Upload>
142
-
143
- Uploads a file to storage.
144
-
145
- **Parameters:**
146
-
147
- - **name**: `string` filename
148
- - **blob**: `Blob` object to upload
149
- - **tags**: `string[]` (optional, default: [])
150
-
151
- **Example:**
152
-
153
- ```typescript
154
- const upload: Upload = await kmClient.storage.upload("filename.jpg", fileBlob, [
155
- "tag1",
156
- "tag2",
157
- ]);
158
- // Use upload.url to access the media file
159
- ```
160
-
161
- #### storage.listUploads(filter?, skip?, limit?): Promise<Paginated<Upload>>
162
-
163
- Query uploaded files by filter and pagination
164
-
165
- **Parameters:**
166
-
167
- - **filter.clientId**: `string` Specific client (optional)
168
- - **filter.mimeTypes**: `string[]` E.g., ['image/jpeg', 'image/png'] (optional)
169
- - **filter.tags**: `string[]` All tags must match (optional)
170
- - **skip**: `number` Pagination offset (default: 0)
171
- - **limit**: `number` Max results (default: 100)
172
-
173
- **Example:**
174
-
175
- ```typescript
176
- // Query uploads by tag and uploaded by this client
177
- const { items, total } = await kmClient.storage.listUploads(
178
- { clientId: kmClient.id, tags: ["tag1"] },
179
- skip,
180
- limit
181
- );
182
- ```
183
-
184
- #### storage.updateUpload(id, update): Promise<Upload>
185
-
186
- Replace uploaded file tags with new tags
187
-
188
- **Parameters:**
189
-
190
- - **id**: `string` Upload id
191
- - **update.tags**: `string[]` (optional)
192
-
193
- **Example:**
194
-
195
- ```typescript
196
- const updatedUpload: Upload = await kmClient.storage.updateUpload(upload.id, {
197
- tags: ["new"],
198
- });
199
- ```
200
-
201
- #### storage.deleteUpload(id): Promise<{ acknowledged: boolean; deletedCount: number }>
202
-
203
- Permanently delete uploaded file
204
-
205
- **Parameters:**
206
-
207
- - **id**: `string` Upload id
208
-
209
- **Example:**
210
-
211
- ```typescript
212
- await kmClient.storage.deleteUpload(upload.id);
213
- ```
214
-
215
- ### Types
216
-
217
- ```typescript
218
- interface Upload {
219
- id: string; // unique id
220
- url: string; // file url (CDN)
221
- name: string; // original filename
222
- size: number; // in bytes
223
- mimeType: string;
224
- clientId: string; // who uploaded
225
- tags: string[]; // metadata for filtering and organization
226
- completed: boolean; // upload status
227
- createdAt: Date;
228
- appId: string;
229
- }
230
-
231
- interface Paginated<T> {
232
- items: T[];
233
- total: number;
234
- }
235
- ```
236
-
237
- ### Common Patterns
238
-
239
- #### Example: User-specific uploads
240
-
241
- ```typescript
242
- // Get uploaded files by clientId
243
- const clientUploads = await kmClient.storage.listUploads({
244
- clientId: kmClient.id,
245
- });
246
- ```
247
-
248
- #### Example: Filter by file type
249
-
250
- ```typescript
251
- // Get only uploaded images
252
- const images = await kmClient.storage.listUploads({
253
- mimeTypes: ["image/jpeg", "image/png"],
254
- });
255
- ```
256
-
257
- #### Example: Tag-based uploads
258
-
259
- ```typescript
260
- // Upload file with tag
261
- await kmClient.storage.upload("avatar.jpg", blob, ["profile"]);
262
-
263
- // Query uploads by tag
264
- const profileUploads = await kmClient.storage.listUploads({
265
- tags: ["profile"],
266
- });
267
- ```
268
-
269
- #### Example: Usage in Kokimoki Store
270
-
271
- ```typescript
272
- // Upload image from Blob
273
- const upload = await kmClient.storage.upload("file.jpg", blob);
274
-
275
- await kmClient.transact([store], (state) => {
276
- // Add image to images array in the store
277
- state.playerImages[upload.id] = { url: upload.url };
278
- });
279
- ```
280
-
281
- ### Key Points
282
-
283
- - **Use Cases**: Commonly used for media files (images, videos, audio), but also supports JSON, text files, or any data not suitable for real-time stores
284
- - **CDN**: File `upload.url` is public and can be used directly
285
- - **Tags**: Use tag system to organize uploads
286
- - **Pagination**: Use skip/limit to paginate results
287
- - **Filtering**: Combine clientId, mimeTypes, and tags to query uploads
288
-
289
- ## AI Integration
290
-
291
- Built-in methods for AI text generation and image transformation. No API keys required.
292
-
293
- Access AI API via `kmClient.ai`.
294
-
295
- ### API Methods
296
-
297
- #### ai.chat(req): Promise<{ content: string }>
298
-
299
- Used to generate text response with AI
300
-
301
- **Parameters:**
302
-
303
- - **req.model**: `string` AI model to use (optional). Available models:
304
- - `gpt-4o`: OpenAI GPT-4 Optimized
305
- - `gpt-4o-mini`: Smaller, faster GPT-4 variant
306
- - `gpt-5`: OpenAI GPT-5 (latest)
307
- - `gpt-5-mini`: Smaller GPT-5 variant
308
- - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
309
- - `gemini-2.5-flash-lite`: Google Gemini lite variant
310
- - `gemini-2.5-flash`: Google Gemini fast variant
311
- - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
312
- - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
313
- - **req.systemPrompt**: `string` AI role/behavior (optional)
314
- - **req.userPrompt**: `string` User message (optional)
315
- - **req.temperature**: `number` Creativity level from 0.0 = factual to 2.0 = creative (optional)
316
- - **req.maxTokens**: `number` Response length limit (optional)
317
- - **req.imageUrls**: `string[]` Image URLs to include with the user prompt (Gemini models only) (optional)
318
-
319
- **Examples:**
320
-
321
- ```typescript
322
- // Generate text response
323
- const { content } = await kmClient.ai.chat({
324
- model: "gemini-2.5-flash-lite",
325
- systemPrompt: "You are a sarcastic assistant",
326
- userPrompt: "Write a story about dragons",
327
- temperature: 0.7, // moderate creativity
328
- maxTokens: 500, // limit to 500 tokens
329
- });
330
- ```
331
-
332
- #### ai.generateJson<T>(req): Promise<T>
333
-
334
- Used to generate structured JSON output with AI. Automatically ensures the response is valid JSON and parses it for you.
335
-
336
- **Important:** Your prompt must include the word "json" and should describe the expected output schema (field names, types, and structure) to ensure the AI generates properly formatted responses.
337
-
338
- **Parameters:**
339
-
340
- - **req.model**: `string` AI model to use (optional). Available models:
341
- - `gpt-4o`: OpenAI GPT-4 Optimized
342
- - `gpt-4o-mini`: Smaller, faster GPT-4 variant
343
- - `gpt-5`: OpenAI GPT-5 (latest)
344
- - `gpt-5-mini`: Smaller GPT-5 variant
345
- - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
346
- - `gemini-2.5-flash-lite`: Google Gemini lite variant
347
- - `gemini-2.5-flash`: Google Gemini fast variant
348
- - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
349
- - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
350
- - **req.systemPrompt**: `string` AI role/behavior (optional)
351
- - **req.userPrompt**: `string` User message (optional)
352
- - **req.temperature**: `number` Creativity level from 0.0 = factual to 2.0 = creative (optional)
353
- - **req.maxTokens**: `number` Response length limit (optional)
354
- - **req.imageUrls**: `string[]` Image URLs to include with the user prompt (Gemini models only) (optional)
355
-
356
- **Returns:** Promise resolving to parsed JSON object of type T
357
-
358
- **Examples:**
359
-
360
- ```typescript
361
- // Generate quiz questions
362
- interface Question {
363
- question: string;
364
- options: string[];
365
- correctAnswer: number;
366
- }
367
-
368
- const questions = await kmClient.ai.generateJson<Question[]>({
369
- systemPrompt: "Generate quiz questions as JSON array",
370
- userPrompt: "Create 5 history quiz questions with 4 options each",
371
- temperature: 0.7,
372
- });
373
-
374
- // questions is already parsed and typed
375
- questions.forEach((q) => console.log(q.question));
376
- ```
377
-
378
- ```typescript
379
- // Generate game character data
380
- interface Character {
381
- name: string;
382
- strength: number;
383
- agility: number;
384
- backstory: string;
385
- }
386
-
387
- const character = await kmClient.ai.generateJson<Character>({
388
- userPrompt: "Create a fantasy warrior character with stats",
389
- temperature: 0.8,
390
- });
391
-
392
- console.log(character.name, character.strength);
393
- ```
394
-
395
- #### ai.modifyImage(baseImageUrl, prompt, tags?): Promise<Upload>
396
-
397
- Used to modify/transform image with AI. The result is stored as [`Upload`](#storage) object
398
-
399
- **Parameters:**
400
-
401
- - **baseImageUrl**: `string` Source image URL
402
- - **prompt**: `string` Modification/transformation description
403
- - **tags**: `string[]` Tags for the result in `Upload` format (optional, default: [])
404
-
405
- **Example:**
406
-
407
- ```typescript
408
- // Modify image from url
409
- const upload: Upload = await kmClient.ai.modifyImage(
410
- "https://static.kokimoki.com/game/image.jpg",
411
- "Make it look like a painting",
412
- ["art", "ai-generated"]
413
- );
414
- ```
415
-
416
- ## Store Connections
417
-
418
- Each Kokimoki store has a `connections` property that provides real-time presence information of all clients connected to that store.
419
-
420
- ### Accessing Connections
421
-
422
- - Use `store.connections` to access the connections proxy for any Kokimoki store
423
- - Use `store.connections.clientIds` to get a `Set` of online client IDs
424
- - Use `useSnapshot` to get reactive updates when connections change
425
- - **ALWAYS** use `useSnapshot(store.connections)` to get reactive updates when connections change
426
-
427
- ### Example: Track Online Players
428
-
429
- ```tsx
430
- import { useSnapshot } from "valtio";
431
- import { globalStore } from "@/state/stores/global-store";
432
-
433
- const Component = () => {
434
- // Get online client IDs from store connections
435
- const onlineClientIds = useSnapshot(globalStore.connections).clientIds;
436
-
437
- // Check if specific player is online
438
- const isPlayerOnline = onlineClientIds.has(playerId);
439
-
440
- // Get count of online players
441
- const onlineCount = onlineClientIds.size;
442
-
443
- return <div>Online players: {onlineCount}</div>;
444
- };
445
- ```
446
-
447
- ### Example: Display Player List with Online Status
448
-
449
- ```tsx
450
- import { useSnapshot } from "valtio";
451
- import { globalStore } from "@/state/stores/global-store";
452
-
453
- const PlayerList = () => {
454
- const players = useSnapshot(globalStore.proxy).players;
455
- const onlineClientIds = useSnapshot(globalStore.connections).clientIds;
456
-
457
- const playersList = Object.entries(players).map(([clientId, player]) => ({
458
- clientId,
459
- name: player.name,
460
-
461
- isOnline: onlineClientIds.has(clientId),
462
- }));
463
-
464
- return (
465
- <ul>
466
- {playersList.map((player) => (
467
- <li key={player.clientId}>
468
- {player.name} - {player.isOnline ? "Online" : "Offline"}
469
- </li>
470
- ))}
471
- </ul>
472
- );
473
- };
474
- ```
475
-
476
- ### Key Points
477
-
478
- - Each store has its own `connections` property
479
- - `connections.clientIds` is a `Set<string>` containing connected client IDs
480
- - Use `useSnapshot(store.connections)` to get reactive updates
481
- - Players can have multiple browser tabs open, but all share the same `clientId`
482
- - A player is considered online if their `clientId` is in the `clientIds` set
483
-
484
- ## Leaderboard
485
-
486
- Kokimoki SDK provides a leaderboard system to track and display player rankings. No setup required.
487
-
488
- Access leaderboard API via `kmClient.leaderboard`.
489
-
490
- ### When to Use Leaderboard API vs Global Store
491
-
492
- **Use the Leaderboard API when:**
493
-
494
- - You have a large number of entries (hundreds to thousands of players)
495
- - You need efficient ranking and sorting with database indexes
496
- - You want pagination and optimized queries for top scores
497
- - Memory and network efficiency are important
498
-
499
- **Use a Global Store when:**
500
-
501
- - You have a small number of players (typically under 100)
502
- - You need real-time updates and live leaderboard changes
503
- - You want to combine player scores with other game state
504
- - The leaderboard is temporary (session-based or reset frequently)
505
-
506
- The leaderboard API is optimized for scalability with database indexes and efficient queries, making it the better choice for games with many players. Global stores are ideal for smaller, real-time collaborative scenarios where you want immediate synchronization.
507
-
508
- ### API Methods
509
-
510
- #### leaderboard.insertEntry<MetadataT, PrivateMetadataT>(leaderboardName, sortDir, score, metadata, privateMetadata): Promise<{ rank: number }>
511
-
512
- Add a new entry to a leaderboard. Creates a new entry each time it's called.
513
-
514
- **Parameters:**
515
-
516
- - **leaderboardName**: `string` Name of the leaderboard
517
- - **sortDir**: `"asc" | "desc"` Sort direction (asc = lowest is best, desc = highest is best)
518
- - **score**: `number` The score value
519
- - **metadata**: `MetadataT` Public metadata visible to all players
520
- - **privateMetadata**: `PrivateMetadataT` Private metadata only accessible via API
521
-
522
- **Returns:** Promise resolving to an object with the entry's rank
523
-
524
- **Example:**
525
-
526
- ```typescript
527
- const { rank } = await kmClient.leaderboard.insertEntry(
528
- "high-scores",
529
- "desc",
530
- 1500,
531
- { playerName: "Alice", level: 10 },
532
- { sessionId: "abc123" }
533
- );
534
- console.log(`New rank: ${rank}`);
535
- ```
536
-
537
- #### leaderboard.upsertEntry<MetadataT, PrivateMetadataT>(leaderboardName, sortDir, score, metadata, privateMetadata): Promise<{ rank: number }>
538
-
539
- Add or update the latest entry for the current client in a leaderboard. Replaces the previous entry if one exists.
540
-
541
- **Parameters:**
542
-
543
- - **leaderboardName**: `string` Name of the leaderboard
544
- - **sortDir**: `"asc" | "desc"` Sort direction (asc = lowest is best, desc = highest is best)
545
- - **score**: `number` The score value
546
- - **metadata**: `MetadataT` Public metadata visible to all players
547
- - **privateMetadata**: `PrivateMetadataT` Private metadata only accessible via API
548
-
549
- **Returns:** Promise resolving to an object with the entry's rank
550
-
551
- **Example:**
552
-
553
- ```typescript
554
- const { rank } = await kmClient.leaderboard.upsertEntry(
555
- "daily-scores",
556
- "desc",
557
- 2000,
558
- { playerName: "Bob", completionTime: 120 },
559
- { deviceId: "xyz789" }
560
- );
561
- console.log(`Updated rank: ${rank}`);
562
- ```
563
-
564
- #### leaderboard.listEntries<MetadataT>(leaderboardName, sortDir, skip?, limit?): Promise<Paginated<{ rank: number; score: number; metadata: MetadataT }>>
565
-
566
- List entries in a leaderboard with pagination.
567
-
568
- **Parameters:**
569
-
570
- - **leaderboardName**: `string` Name of the leaderboard
571
- - **sortDir**: `"asc" | "desc"` Sort direction (asc = lowest is best, desc = highest is best)
572
- - **skip**: `number` Number of entries to skip for pagination (default: 0)
573
- - **limit**: `number` Maximum number of entries to return (default: 100)
574
-
575
- **Returns:** Promise resolving to a paginated list of entries
576
-
577
- **Example:**
578
-
579
- ```typescript
580
- const { items, total } = await kmClient.leaderboard.listEntries(
581
- "weekly-scores",
582
- "desc",
583
- 0, // skip
584
- 10 // limit - get top 10
585
- );
586
-
587
- items.forEach((entry) => {
588
- console.log(
589
- `Rank ${entry.rank}: ${entry.metadata.playerName} - ${entry.score}`
590
- );
591
- });
592
- ```
593
-
594
- #### leaderboard.getBestEntry<MetadataT>(leaderboardName, sortDir, clientId?): Promise<{ rank: number; score: number; metadata: MetadataT }>
595
-
596
- Get the best entry for a specific client in a leaderboard.
597
-
598
- **Parameters:**
599
-
600
- - **leaderboardName**: `string` Name of the leaderboard
601
- - **sortDir**: `"asc" | "desc"` Sort direction (asc = lowest is best, desc = highest is best)
602
- - **clientId**: `string` (optional) Client ID to get entry for. Defaults to current client if not provided.
603
-
604
- **Returns:** Promise resolving to the best entry for the client
605
-
606
- **Example:**
607
-
608
- ```typescript
609
- // Get current client's best entry
610
- const myBest = await kmClient.leaderboard.getBestEntry("all-time-high", "desc");
611
- console.log(`My best: Rank ${myBest.rank}, Score ${myBest.score}`);
612
-
613
- // Get another player's best entry
614
- const otherBest = await kmClient.leaderboard.getBestEntry(
615
- "all-time-high",
616
- "desc",
617
- "other-client-id"
618
- );
619
- ```
620
-
621
- ### Common Patterns
622
-
623
- #### Example: Track High Scores
624
-
625
- ```typescript
626
- // Submit a new high score
627
- await kmClient.leaderboard.upsertEntry(
628
- "high-scores",
629
- "desc",
630
- score,
631
- { playerName: player.name },
632
- { timestamp: Date.now() }
633
- );
634
-
635
- // Display top 10
636
- const { items } = await kmClient.leaderboard.listEntries(
637
- "high-scores",
638
- "desc",
639
- 0,
640
- 10
641
- );
642
- ```
643
-
644
- #### Example: Track Speed Run Times
645
-
646
- ```typescript
647
- // Submit completion time (lower is better)
648
- await kmClient.leaderboard.upsertEntry(
649
- "speed-run",
650
- "asc",
651
- completionTimeInSeconds,
652
- { playerName: player.name, difficulty: "hard" },
653
- {}
654
- );
655
-
656
- // Get personal best
657
- const myBest = await kmClient.leaderboard.getBestEntry("speed-run", "asc");
658
- ```
659
-
660
- ### Key Points
661
-
662
- - **Sort Direction**: Use `asc` when lower scores are better (e.g., completion time), `desc` when higher scores are better (e.g., points)
663
- - **Insert vs Upsert**: Use `insertEntry` to keep all attempts, `upsertEntry` to keep only the latest/best
664
- - **Metadata**: Public metadata is visible to all, private metadata is only accessible via API calls
665
- - **Pagination**: Use skip/limit to implement leaderboard pages or "load more" functionality
@@ -1,8 +0,0 @@
1
- import { SyncedStore } from "./synced-store";
2
- export declare class MessageQueue<T> extends SyncedStore<{
3
- messages: T[];
4
- }> {
5
- name: string;
6
- constructor(name: string);
7
- push(message: T): Promise<Uint8Array>;
8
- }
@@ -1,19 +0,0 @@
1
- import EventEmitter from "events";
2
- import { SyncedStore } from "./synced-store";
3
- import Y from "yjs";
4
- export class MessageQueue extends SyncedStore {
5
- name;
6
- constructor(name) {
7
- super({ messages: [] });
8
- this.name = name;
9
- }
10
- async push(message) {
11
- // Construct Y update to push the message to the queue
12
- const id = crypto.randomUUID();
13
- const ydoc = new Y.Doc();
14
- const map = ydoc.getMap("messages");
15
- map.set(id, message);
16
- const update = Y.encodeStateAsUpdate(ydoc);
17
- return update;
18
- }
19
- }
@@ -1,5 +0,0 @@
1
- export declare enum RoomSubscriptionMode {
2
- Read = "r",
3
- Write = "w",
4
- ReadWrite = "b"
5
- }
@@ -1,6 +0,0 @@
1
- export var RoomSubscriptionMode;
2
- (function (RoomSubscriptionMode) {
3
- RoomSubscriptionMode["Read"] = "r";
4
- RoomSubscriptionMode["Write"] = "w";
5
- RoomSubscriptionMode["ReadWrite"] = "b";
6
- })(RoomSubscriptionMode || (RoomSubscriptionMode = {}));