@kokimoki/app 3.1.4 → 3.1.6

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 (37) hide show
  1. package/dist/core/index.d.ts +3 -3
  2. package/dist/core/index.js +3 -3
  3. package/dist/core/kokimoki-client.d.ts +5 -4
  4. package/dist/core/kokimoki-client.js +7 -7
  5. package/dist/core/room-subscription-mode.d.ts +1 -1
  6. package/dist/core/room-subscription-mode.js +1 -1
  7. package/dist/core/room-subscription.d.ts +2 -2
  8. package/dist/core/room-subscription.js +1 -1
  9. package/dist/index.d.ts +9 -10
  10. package/dist/index.js +5 -6
  11. package/dist/protocol/ws-message/index.d.ts +3 -3
  12. package/dist/protocol/ws-message/index.js +3 -3
  13. package/dist/services/index.d.ts +4 -4
  14. package/dist/services/index.js +4 -4
  15. package/dist/services/kokimoki-ai.d.ts +1 -1
  16. package/dist/services/kokimoki-i18n.d.ts +1 -1
  17. package/dist/services/kokimoki-i18n.js +1 -1
  18. package/dist/services/kokimoki-leaderboard.d.ts +2 -2
  19. package/dist/services/kokimoki-storage.d.ts +2 -2
  20. package/dist/stores/index.d.ts +3 -3
  21. package/dist/stores/index.js +3 -3
  22. package/dist/stores/kokimoki-local-store.d.ts +1 -1
  23. package/dist/stores/kokimoki-local-store.js +2 -2
  24. package/dist/stores/kokimoki-store.d.ts +1 -1
  25. package/dist/stores/kokimoki-transaction.d.ts +1 -1
  26. package/dist/types/index.d.ts +4 -4
  27. package/dist/types/index.js +4 -4
  28. package/dist/utils/kokimoki-client.d.ts +1 -1
  29. package/dist/utils/kokimoki-client.js +1 -1
  30. package/dist/utils/kokimoki-env.d.ts +1 -1
  31. package/dist/version.d.ts +1 -1
  32. package/dist/version.js +1 -1
  33. package/package.json +8 -1
  34. package/dist/kokimoki.min.d.ts +0 -926
  35. package/dist/kokimoki.min.js +0 -17857
  36. package/dist/kokimoki.min.js.map +0 -1
  37. package/dist/llms.txt +0 -665
@@ -1,926 +0,0 @@
1
- import TypedEmitter from 'typed-emitter';
2
- import { Snapshot } from 'valtio/vanilla';
3
- import * as Y from 'yjs';
4
- export { proxy, ref, snapshot, subscribe, useSnapshot } from 'valtio';
5
- export { derive, underive } from 'derive-valtio';
6
- export { devtools, subscribeKey, useProxy, watch } from 'valtio/utils';
7
-
8
- interface Paginated<T> {
9
- items: T[];
10
- total: number;
11
- }
12
-
13
- type KokimokiClientEvents = {
14
- connected: () => void;
15
- disconnected: () => void;
16
- };
17
-
18
- interface Upload {
19
- id: string;
20
- appId: string;
21
- clientId: string;
22
- createdAt: Date;
23
- name: string;
24
- url: string;
25
- size: number;
26
- mimeType: string;
27
- completed: boolean;
28
- tags: string[];
29
- }
30
-
31
- /**
32
- * Kokimoki AI Integration Service
33
- *
34
- * Provides built-in AI capabilities for game applications without requiring API keys or setup.
35
- * Includes text generation, structured JSON output, and image modification.
36
- *
37
- * **Key Features:**
38
- * - Multiple AI models (GPT-4, GPT-5, Gemini variants)
39
- * - Text generation with configurable creativity (temperature)
40
- * - Structured JSON output for game data
41
- * - AI-powered image modifications
42
- * - No API keys or configuration required
43
- *
44
- * **Common Use Cases:**
45
- * - Generate dynamic game content (quests, dialogues, stories)
46
- * - Create AI opponents or NPCs with personalities
47
- * - Generate quiz questions or trivia
48
- * - Create game assets (character stats, item descriptions)
49
- * - Transform user-uploaded images
50
- * - Generate procedural content
51
- *
52
- * Access via `kmClient.ai`
53
- *
54
- * @example
55
- * ```typescript
56
- * // Generate story text
57
- * const story = await kmClient.ai.chat({
58
- * systemPrompt: 'You are a fantasy story writer',
59
- * userPrompt: 'Write a short quest description',
60
- * temperature: 0.8
61
- * });
62
- *
63
- * // Generate structured game data
64
- * interface Enemy {
65
- * name: string;
66
- * health: number;
67
- * attack: number;
68
- * }
69
- * const enemy = await kmClient.ai.generateJson<Enemy>({
70
- * userPrompt: 'Create a level 5 goblin warrior'
71
- * });
72
- *
73
- * // Transform image
74
- * const modified = await kmClient.ai.modifyImage(
75
- * imageUrl,
76
- * 'Make it look like pixel art'
77
- * );
78
- * ```
79
- */
80
- declare class KokimokiAiService {
81
- private readonly client;
82
- constructor(client: KokimokiClient);
83
- /**
84
- * Generate a chat response from the AI model.
85
- *
86
- * Sends a chat request to the AI service and returns the generated response.
87
- * Supports multiple AI models including GPT and Gemini variants with configurable
88
- * parameters for fine-tuning the response behavior.
89
- *
90
- * @param req The chat request parameters.
91
- * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
92
- * Available models:
93
- * - `gpt-4o`: OpenAI GPT-4 Optimized
94
- * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
95
- * - `gpt-5`: OpenAI GPT-5 (latest)
96
- * - `gpt-5-mini`: Smaller GPT-5 variant
97
- * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
98
- * - `gemini-2.5-flash-lite`: Google Gemini lite variant
99
- * - `gemini-2.5-flash`: Google Gemini fast variant
100
- * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
101
- * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
102
- * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
103
- * This helps define the AI's role, personality, and constraints.
104
- * @param req.userPrompt The user's message or question to send to the AI.
105
- * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
106
- * Lower values make output more focused and deterministic,
107
- * higher values make it more creative and varied.
108
- * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
109
- * Controls the length of the AI's output.
110
- * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
111
- * Allows the AI to analyze and respond based on the provided images.
112
- *
113
- * @returns A promise that resolves to an object containing the AI-generated response.
114
- * @returns {string} content The text content of the AI's response.
115
- *
116
- * @throws An error object if the API request fails.
117
- *
118
- * @example
119
- * ```typescript
120
- * const response = await client.ai.chat({
121
- * model: "gpt-4o",
122
- * systemPrompt: "You are a helpful coding assistant.",
123
- * userPrompt: "Explain what TypeScript is in one sentence.",
124
- * temperature: 0.7,
125
- * maxTokens: 100
126
- * });
127
- * console.log(response.content);
128
- * ```
129
- */
130
- chat(req: {
131
- model?: "gpt-4o" | "gpt-4o-mini" | "gpt-5" | "gpt-5-mini" | "gpt-5-nano" | "gemini-2.5-flash-lite" | "gemini-2.5-flash" | "gemini-3-flash-preview" | "gemini-3-pro-preview";
132
- systemPrompt?: string;
133
- userPrompt: string;
134
- temperature?: number;
135
- maxTokens?: number;
136
- responseMimeType?: string;
137
- /** Image URLs to include with the user prompt (Gemini models only) */
138
- imageUrls?: string[];
139
- }): Promise<{
140
- content: string;
141
- }>;
142
- /**
143
- * Generate structured JSON output from the AI model.
144
- *
145
- * Sends a chat request to the AI service with the expectation of receiving
146
- * a JSON-formatted response. This is useful for scenarios where the output
147
- * needs to be parsed or processed programmatically.
148
- *
149
- * **Important:** Your prompt must include the word "json" and should describe
150
- * the expected output schema (field names, types, and structure) to ensure
151
- * the AI generates properly formatted responses.
152
- *
153
- * @param req The chat request parameters.
154
- * @param req.model Optional. The AI model to use. Defaults to server-side default if not specified.
155
- * Available models:
156
- * - `gpt-4o`: OpenAI GPT-4 Optimized
157
- * - `gpt-4o-mini`: Smaller, faster GPT-4 variant
158
- * - `gpt-5`: OpenAI GPT-5 (latest)
159
- * - `gpt-5-mini`: Smaller GPT-5 variant
160
- * - `gpt-5-nano`: Smallest GPT-5 variant for lightweight tasks
161
- * - `gemini-2.5-flash-lite`: Google Gemini lite variant
162
- * - `gemini-2.5-flash`: Google Gemini fast variant
163
- * - `gemini-3-flash-preview`: Google Gemini 3 Flash preview
164
- * - `gemini-3-pro-preview`: Google Gemini 3 Pro preview
165
- * @param req.systemPrompt Optional. The system message that sets the behavior and context for the AI.
166
- * This helps define the AI's role, personality, and constraints.
167
- * @param req.userPrompt The user's message or question to send to the AI.
168
- * @param req.temperature Optional. Controls randomness in the response (0.0 to 1.0).
169
- * Lower values make output more focused and deterministic,
170
- * higher values make it more creative and varied.
171
- * @param req.maxTokens Optional. The maximum number of tokens to generate in the response.
172
- * Controls the length of the AI's output.
173
- * @param req.imageUrls Optional. Image URLs to include with the user prompt (Gemini models only).
174
- * Allows the AI to analyze images and generate structured JSON based on them.
175
- *
176
- * @returns A promise that resolves to the parsed JSON object generated by the AI.
177
- *
178
- * @throws An error object if the API request fails or if the response is not valid JSON.
179
- */
180
- generateJson<T extends object>(req: {
181
- model?: "gpt-4o" | "gpt-4o-mini" | "gpt-5" | "gpt-5-mini" | "gpt-5-nano" | "gemini-2.5-flash-lite" | "gemini-2.5-flash" | "gemini-3-flash-preview" | "gemini-3-pro-preview";
182
- systemPrompt?: string;
183
- userPrompt: string;
184
- temperature?: number;
185
- maxTokens?: number;
186
- /** Image URLs to include with the user prompt (Gemini models only) */
187
- imageUrls?: string[];
188
- }): Promise<T>;
189
- /**
190
- * Modify an image using the AI service.
191
- * @param baseImageUrl The URL of the base image to modify.
192
- * @param prompt The modification prompt to apply to the image.
193
- * @param tags Optional. Tags to associate with the image.
194
- * @returns A promise that resolves to the modified image upload information.
195
- */
196
- modifyImage(baseImageUrl: string, prompt: string, tags?: string[], model?: "gemini-2.5-flash-image" | "gemini-3-pro-image-preview"): Promise<Upload>;
197
- }
198
-
199
- /**
200
- * Kokimoki Leaderboard Service
201
- *
202
- * Provides efficient player ranking and score tracking with database indexes and optimized queries.
203
- * Ideal for games with large numbers of players and competitive scoring.
204
- *
205
- * **Key Features:**
206
- * - Efficient ranking with database indexes
207
- * - Support for ascending (lowest-is-best) and descending (highest-is-best) sorting
208
- * - Pagination for large leaderboards
209
- * - Public and private metadata for entries
210
- * - Insert (preserve all attempts) or upsert (keep latest only) modes
211
- *
212
- * **When to use Leaderboard API vs Global Store:**
213
- *
214
- * Use the **Leaderboard API** when:
215
- * - You have a large number of entries (hundreds to thousands of players)
216
- * - You need efficient ranking and sorting with database indexes
217
- * - You want pagination and optimized queries for top scores
218
- * - Memory and network efficiency are important
219
- *
220
- * Use a **Global Store** when:
221
- * - You have a small number of players (typically under 100)
222
- * - You need real-time updates and live leaderboard changes
223
- * - You want to combine player scores with other game state
224
- * - The leaderboard is temporary (session-based or reset frequently)
225
- *
226
- * Access via `kmClient.leaderboard`
227
- *
228
- * @example
229
- * ```typescript
230
- * // Submit a high score
231
- * const { rank } = await kmClient.leaderboard.upsertEntry(
232
- * 'high-scores',
233
- * 'desc',
234
- * 1500,
235
- * { playerName: 'Alice' },
236
- * {}
237
- * );
238
- *
239
- * // Get top 10
240
- * const { items } = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
241
- *
242
- * // Get player's best
243
- * const best = await kmClient.leaderboard.getBestEntry('high-scores', 'desc');
244
- * ```
245
- */
246
- declare class KokimokiLeaderboardService {
247
- private readonly client;
248
- constructor(client: KokimokiClient);
249
- /**
250
- * Add a new entry to a leaderboard.
251
- *
252
- * Creates a new entry each time it's called, preserving all attempts. Use this when you want
253
- * to track every score submission (e.g., all game attempts).
254
- *
255
- * @param leaderboardName The name of the leaderboard to add the entry to
256
- * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
257
- * "desc" for highest-is-best (e.g., points)
258
- * @param score The numeric score value
259
- * @param metadata Public metadata visible to all players (e.g., player name, level)
260
- * @param privateMetadata Private metadata only accessible via API calls (e.g., session ID)
261
- * @returns A promise resolving to an object with the entry's rank
262
- *
263
- * @example
264
- * ```typescript
265
- * const { rank } = await kmClient.leaderboard.insertEntry(
266
- * 'high-scores',
267
- * 'desc',
268
- * 1500,
269
- * { playerName: 'Alice', level: 10 },
270
- * { sessionId: 'abc123' }
271
- * );
272
- * console.log(`New rank: ${rank}`);
273
- * ```
274
- */
275
- insertEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
276
- rank: number;
277
- }>;
278
- /**
279
- * Add or update the latest entry for the current client in a leaderboard.
280
- *
281
- * Replaces the previous entry if one exists for this client. Use this when you only want
282
- * to keep the latest or best score per player (e.g., daily high score).
283
- *
284
- * @param leaderboardName The name of the leaderboard to upsert the entry in
285
- * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
286
- * "desc" for highest-is-best (e.g., points)
287
- * @param score The numeric score value
288
- * @param metadata Public metadata visible to all players (e.g., player name, completion time)
289
- * @param privateMetadata Private metadata only accessible via API calls (e.g., device ID)
290
- * @returns A promise resolving to an object with the entry's updated rank
291
- *
292
- * @example
293
- * ```typescript
294
- * const { rank } = await kmClient.leaderboard.upsertEntry(
295
- * 'daily-scores',
296
- * 'desc',
297
- * 2000,
298
- * { playerName: 'Bob', completionTime: 120 },
299
- * { deviceId: 'xyz789' }
300
- * );
301
- * console.log(`Updated rank: ${rank}`);
302
- * ```
303
- */
304
- upsertEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
305
- rank: number;
306
- }>;
307
- /**
308
- * List entries in a leaderboard with pagination.
309
- *
310
- * Retrieves a sorted list of leaderboard entries. Use skip and limit parameters for
311
- * pagination (e.g., showing top 10, or implementing "load more" functionality).
312
- *
313
- * @param leaderboardName The name of the leaderboard to query
314
- * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
315
- * "desc" for highest-is-best (e.g., points)
316
- * @param skip Number of entries to skip for pagination (default: 0)
317
- * @param limit Maximum number of entries to return (default: 100)
318
- * @returns A promise resolving to a paginated list of entries with rank, score, and metadata
319
- *
320
- * @example
321
- * ```typescript
322
- * // Get top 10 scores
323
- * const { items, total } = await kmClient.leaderboard.listEntries(
324
- * 'weekly-scores',
325
- * 'desc',
326
- * 0,
327
- * 10
328
- * );
329
- *
330
- * items.forEach(entry => {
331
- * console.log(`Rank ${entry.rank}: ${entry.metadata.playerName} - ${entry.score}`);
332
- * });
333
- * ```
334
- */
335
- listEntries<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", skip?: number, limit?: number): Promise<Paginated<{
336
- rank: number;
337
- score: number;
338
- metadata: MetadataT;
339
- }>>;
340
- /**
341
- * Get the best entry for a specific client in a leaderboard.
342
- *
343
- * Retrieves the highest-ranked entry for a client based on the sort direction.
344
- * Defaults to the current client if no clientId is provided.
345
- *
346
- * @param leaderboardName The name of the leaderboard to query
347
- * @param sortDir Sort direction: "asc" for lowest-is-best (e.g., completion time),
348
- * "desc" for highest-is-best (e.g., points)
349
- * @param clientId The client ID to get the best entry for (optional, defaults to current client)
350
- * @returns A promise resolving to the best entry with rank, score, and metadata
351
- *
352
- * @example
353
- * ```typescript
354
- * // Get current client's best entry
355
- * const myBest = await kmClient.leaderboard.getBestEntry('all-time-high', 'desc');
356
- * console.log(`My best: Rank ${myBest.rank}, Score ${myBest.score}`);
357
- *
358
- * // Get another player's best entry
359
- * const otherBest = await kmClient.leaderboard.getBestEntry(
360
- * 'all-time-high',
361
- * 'desc',
362
- * 'other-client-id'
363
- * );
364
- * ```
365
- */
366
- getBestEntry<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", clientId?: string): Promise<{
367
- rank: number;
368
- score: number;
369
- metadata: MetadataT;
370
- }>;
371
- }
372
-
373
- /**
374
- * Kokimoki Storage Service
375
- *
376
- * Provides file upload and management capabilities for game applications. Ideal for media files
377
- * (images, videos, audio) and other data not suitable for real-time stores (JSON, text files).
378
- *
379
- * **Key Features:**
380
- * - Upload files to cloud storage with CDN delivery
381
- * - Tag-based organization and filtering
382
- * - Query uploads by client, MIME type, or tags
383
- * - Pagination support for large collections
384
- * - Public CDN URLs for direct access
385
- *
386
- * **Common Use Cases:**
387
- * - Player avatars and profile images
388
- * - Game screenshots and replays
389
- * - User-generated content
390
- * - Asset uploads (levels, maps, custom skins)
391
- * - JSON configuration files
392
- *
393
- * Access via `kmClient.storage`
394
- *
395
- * @example
396
- * ```typescript
397
- * // Upload an image
398
- * const upload = await kmClient.storage.upload('avatar.jpg', imageBlob, ['profile']);
399
- *
400
- * // Query user's uploads
401
- * const myUploads = await kmClient.storage.listUploads({
402
- * clientId: kmClient.id
403
- * });
404
- *
405
- * // Use in store
406
- * await kmClient.transact([store], (state) => {
407
- * state.playerAvatar = upload.url;
408
- * });
409
- * ```
410
- */
411
- declare class KokimokiStorageService {
412
- private readonly client;
413
- constructor(client: KokimokiClient);
414
- private createUpload;
415
- private uploadChunks;
416
- private completeUpload;
417
- /**
418
- * Upload a file to cloud storage.
419
- *
420
- * Uploads a file (Blob) to Kokimoki storage and returns an Upload object with a public CDN URL.
421
- * Files are automatically chunked for efficient upload. The returned URL can be used directly
422
- * in your application (e.g., in img tags or store state).
423
- *
424
- * @param name The filename for the upload
425
- * @param blob The Blob object containing the file data
426
- * @param tags Optional array of tags for organizing and filtering uploads (default: [])
427
- * @returns A promise resolving to the Upload object with CDN URL and metadata
428
- *
429
- * @example
430
- * ```typescript
431
- * // Upload image with tags
432
- * const upload = await kmClient.storage.upload(
433
- * 'avatar.jpg',
434
- * imageBlob,
435
- * ['profile', 'avatar']
436
- * );
437
- *
438
- * // Use the CDN URL
439
- * console.log(upload.url); // https://cdn.kokimoki.com/...
440
- *
441
- * // Store in game state
442
- * await kmClient.transact([store], (state) => {
443
- * state.players[kmClient.id].avatar = upload.url;
444
- * });
445
- * ```
446
- */
447
- upload(name: string, blob: Blob, tags?: string[]): Promise<Upload>;
448
- /**
449
- * Update metadata for an existing upload.
450
- *
451
- * Allows you to replace the tags associated with an upload. Useful for reorganizing
452
- * or recategorizing uploaded files.
453
- *
454
- * @param id The upload ID to update
455
- * @param update Object containing the new tags array
456
- * @returns A promise resolving to the updated Upload object
457
- *
458
- * @example
459
- * ```typescript
460
- * // Update tags
461
- * const updated = await kmClient.storage.updateUpload(upload.id, {
462
- * tags: ['archived', 'old-profile']
463
- * });
464
- * ```
465
- */
466
- updateUpload(id: string, update: {
467
- tags?: string[];
468
- }): Promise<Upload>;
469
- /**
470
- * Query uploaded files with filtering and pagination.
471
- *
472
- * Retrieves a list of uploads matching the specified criteria. Supports filtering by
473
- * client (uploader), MIME types, and tags. Use pagination for large collections.
474
- *
475
- * @param filter Optional filter criteria
476
- * @param filter.clientId Filter by uploader's client ID
477
- * @param filter.mimeTypes Filter by MIME types (e.g., ['image/jpeg', 'image/png'])
478
- * @param filter.tags Filter by tags (all specified tags must match)
479
- * @param skip Number of results to skip for pagination (default: 0)
480
- * @param limit Maximum number of results to return (default: 100)
481
- * @returns A promise resolving to paginated Upload results with total count
482
- *
483
- * @example
484
- * ```typescript
485
- * // Get current user's images
486
- * const myImages = await kmClient.storage.listUploads({
487
- * clientId: kmClient.id,
488
- * mimeTypes: ['image/jpeg', 'image/png']
489
- * });
490
- *
491
- * // Get all profile avatars
492
- * const avatars = await kmClient.storage.listUploads({
493
- * tags: ['profile', 'avatar']
494
- * });
495
- *
496
- * // Pagination
497
- * const page2 = await kmClient.storage.listUploads({}, 10, 10);
498
- * ```
499
- */
500
- listUploads(filter?: {
501
- clientId?: string;
502
- mimeTypes?: string[];
503
- tags?: string[];
504
- }, skip?: number, limit?: number): Promise<Paginated<Upload>>;
505
- /**
506
- * Permanently delete an uploaded file.
507
- *
508
- * Removes the file from cloud storage and the CDN. The URL will no longer be accessible.
509
- * This operation cannot be undone.
510
- *
511
- * @param id The upload ID to delete
512
- * @returns A promise resolving to deletion confirmation
513
- *
514
- * @example
515
- * ```typescript
516
- * // Delete an upload
517
- * const result = await kmClient.storage.deleteUpload(upload.id);
518
- * console.log(`Deleted: ${result.deletedCount} file(s)`);
519
- * ```
520
- */
521
- deleteUpload(id: string): Promise<{
522
- acknowledged: boolean;
523
- deletedCount: number;
524
- }>;
525
- }
526
-
527
- declare class KokimokiStore<T extends object> {
528
- readonly roomName: string;
529
- readonly defaultValue: T;
530
- readonly mode: RoomSubscriptionMode;
531
- readonly doc: Y.Doc;
532
- readonly proxy: T;
533
- readonly docRoot: Y.Map<unknown>;
534
- readonly connections: {
535
- connectionIds: Set<string>;
536
- clientIds: Set<string>;
537
- };
538
- private _unsubscribeConnectionsHandler;
539
- constructor(roomName: string, defaultValue: T, mode?: RoomSubscriptionMode);
540
- get(): Snapshot<T>;
541
- subscribe(set: (value: Snapshot<T>) => void): () => void;
542
- onJoin(client: KokimokiClient<any>): Promise<void>;
543
- onBeforeLeave(_client: KokimokiClient): Promise<void>;
544
- onLeave(_client: KokimokiClient): Promise<void>;
545
- }
546
-
547
- declare class KokimokiLocalStore<T extends object> extends KokimokiStore<T> {
548
- private readonly localRoomName;
549
- private _stateKey?;
550
- private get stateKey();
551
- constructor(localRoomName: string, defaultState: T);
552
- getInitialUpdate(appId: string, clientId: string): {
553
- roomHash: number;
554
- initialUpdate: Uint8Array<ArrayBufferLike> | undefined;
555
- };
556
- }
557
-
558
- type Mutable<T> = {
559
- -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K];
560
- };
561
- type StoreValue<S> = S extends KokimokiStore<infer U> ? Mutable<U> : never;
562
- declare const KokimokiClient_base: {
563
- new (): TypedEmitter<KokimokiClientEvents>;
564
- };
565
- /**
566
- * Kokimoki Client - Real-time Collaborative Game Development SDK
567
- *
568
- * The main entry point for building multiplayer games and collaborative applications.
569
- * Provides real-time state synchronization, AI integration, cloud storage, leaderboards,
570
- * and more - all without complex backend setup.
571
- *
572
- * **Core Capabilities:**
573
- * - **Real-time Stores**: Synchronized state with automatic conflict resolution (powered by Valtio + Y.js)
574
- * - **Atomic Transactions**: Update multiple stores consistently with automatic batching
575
- * - **AI Integration**: Built-in text generation, structured JSON output, and image modification
576
- * - **Cloud Storage**: File uploads with CDN delivery and tag-based organization
577
- * - **Leaderboards**: Efficient player ranking with database indexes and pagination
578
- * - **Presence Tracking**: Real-time connection status for all players
579
- * - **Time Sync**: Server-synchronized timestamps across all clients
580
- * - **Webhooks**: Send data to external services for backend processing
581
- *
582
- * **Quick Start:**
583
- * ```typescript
584
- * import { KokimokiClient } from '@kokimoki/app';
585
- *
586
- * // Initialize the client
587
- * const kmClient = new KokimokiClient(
588
- * 'your-host.kokimoki.com',
589
- * 'your-app-id',
590
- * 'optional-access-code'
591
- * );
592
- *
593
- * // Connect to the server
594
- * await kmClient.connect();
595
- *
596
- * // Create a synchronized store
597
- * interface GameState {
598
- * players: Record<string, { name: string; score: number }>;
599
- * round: number;
600
- * }
601
- *
602
- * const gameStore = kmClient.store<GameState>('game', {
603
- * players: {},
604
- * round: 1
605
- * });
606
- *
607
- * // Update state atomically
608
- * await kmClient.transact([gameStore], ([game]) => {
609
- * game.players[kmClient.id] = { name: 'Player 1', score: 0 };
610
- * game.round = 2;
611
- * });
612
- *
613
- * // Use in React components with Valtio
614
- * import { useSnapshot } from 'valtio';
615
- *
616
- * function GameComponent() {
617
- * const game = useSnapshot(gameStore.proxy);
618
- * return <div>Round: {game.round}</div>;
619
- * }
620
- * ```
621
- *
622
- * **Key Features:**
623
- *
624
- * **1. Real-time State Management**
625
- * - Create global stores shared across all players: `kmClient.store()`
626
- * - Create local stores for client-side data: `kmClient.localStore()`
627
- * - Automatic synchronization and conflict resolution
628
- * - Use `useSnapshot()` from Valtio for reactive React components
629
- *
630
- * **2. Atomic Transactions**
631
- * ```typescript
632
- * // Update multiple stores atomically
633
- * await kmClient.transact([playerStore, gameStore], ([player, game]) => {
634
- * player.score += 10;
635
- * game.lastUpdate = kmClient.serverTimestamp();
636
- * });
637
- * ```
638
- *
639
- * **3. AI Integration (No API keys required)**
640
- * ```typescript
641
- * // Generate text
642
- * const story = await kmClient.ai.chat({
643
- * model: 'gpt-4o',
644
- * userPrompt: 'Write a quest description',
645
- * temperature: 0.8
646
- * });
647
- *
648
- * // Generate structured data
649
- * interface Quest { title: string; reward: number; }
650
- * const quest = await kmClient.ai.generateJson<Quest>({
651
- * userPrompt: 'Create a level 5 quest'
652
- * });
653
- *
654
- * // Modify images
655
- * const modified = await kmClient.ai.modifyImage(url, 'Make it pixel art');
656
- * ```
657
- *
658
- * **4. Cloud Storage**
659
- * ```typescript
660
- * // Upload files with tags
661
- * const upload = await kmClient.storage.upload('avatar.jpg', blob, ['profile']);
662
- *
663
- * // Query uploads
664
- * const images = await kmClient.storage.listUploads({
665
- * clientId: kmClient.id,
666
- * mimeTypes: ['image/jpeg', 'image/png']
667
- * });
668
- * ```
669
- *
670
- * **5. Leaderboards**
671
- * ```typescript
672
- * // Submit score (replaces previous entry)
673
- * await kmClient.leaderboard.upsertEntry(
674
- * 'high-scores',
675
- * 'desc',
676
- * 1500,
677
- * { playerName: 'Alice' },
678
- * {}
679
- * );
680
- *
681
- * // Get top 10
682
- * const top10 = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
683
- * ```
684
- *
685
- * **6. Presence Tracking**
686
- * ```typescript
687
- * // Track online players
688
- * const onlineClientIds = useSnapshot(gameStore.connections).clientIds;
689
- * const isPlayerOnline = onlineClientIds.has(playerId);
690
- * ```
691
- *
692
- * **Best Practices:**
693
- * - Always use `kmClient.serverTimestamp()` for time-sensitive operations
694
- * - Prefer Records over Arrays: `Record<string, T>` with timestamp keys
695
- * - Use `kmClient.transact()` for all state updates to ensure atomicity
696
- * - Tag uploads for easy filtering and organization
697
- * - Use local stores for client-side settings and preferences
698
- * - Leverage TypeScript generics for type-safe stores
699
- *
700
- * **Events:**
701
- * - `connected`: Fired when client connects/reconnects to server
702
- * - `disconnected`: Fired when connection is lost
703
- *
704
- * @template ClientContextT The type of client context data (custom user data from your backend)
705
- *
706
- * @example
707
- * ```typescript
708
- * // Listen for connection events
709
- * kmClient.on('connected', () => {
710
- * console.log('Connected to Kokimoki!');
711
- * });
712
- *
713
- * kmClient.on('disconnected', () => {
714
- * console.log('Connection lost, will auto-reconnect...');
715
- * });
716
- * ```
717
- */
718
- declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
719
- readonly host: string;
720
- readonly appId: string;
721
- readonly code: string;
722
- private _wsUrl;
723
- private _apiUrl;
724
- private _id?;
725
- private _connectionId?;
726
- private _token?;
727
- private _apiHeaders?;
728
- private _serverTimeOffset;
729
- private _clientContext?;
730
- private _ws?;
731
- private _subscriptionsByName;
732
- private _subscriptionsByHash;
733
- private _subscribeReqPromises;
734
- private _unsubscribeReqPromises;
735
- private _transactionPromises;
736
- private _connected;
737
- private _connectPromise?;
738
- private _messageId;
739
- private _autoReconnect;
740
- private _reconnectTimeout;
741
- private _pingInterval;
742
- private _clientTokenKey;
743
- private _editorContext;
744
- private _ai?;
745
- private _storage?;
746
- private _leaderboard?;
747
- constructor(host: string, appId: string, code?: string);
748
- get id(): string;
749
- get connectionId(): string;
750
- get token(): string;
751
- get apiUrl(): string;
752
- get apiHeaders(): Headers;
753
- get clientContext(): ClientContextT & ({} | null);
754
- /**
755
- * Indicates whether the client is currently connected to the server.
756
- */
757
- get connected(): boolean;
758
- get ws(): WebSocket;
759
- /**
760
- * Indicates whether the client is running in editor/development mode.
761
- */
762
- get isEditor(): boolean;
763
- /**
764
- * Establishes a connection to the Kokimoki server.
765
- *
766
- * Handles authentication, WebSocket setup, and automatic reconnection.
767
- * If already connecting, returns the existing connection promise.
768
- *
769
- * @returns A promise that resolves when the connection is established.
770
- * @throws Error if the connection fails.
771
- */
772
- connect(): Promise<void>;
773
- private handleInitMessage;
774
- private handleBinaryMessage;
775
- private handleErrorMessage;
776
- private handleSubscribeResMessage;
777
- private handleUnsubscribeResMessage;
778
- private handleRoomUpdateMessage;
779
- /**
780
- * Gets the current server timestamp, accounting for client-server time offset.
781
- *
782
- * @returns The current server timestamp in milliseconds.
783
- */
784
- serverTimestamp(): number;
785
- /**
786
- * Sends a Y.js update to a specific room.
787
- *
788
- * @param room - The name of the room to update.
789
- * @param update - The Y.js update as a Uint8Array.
790
- * @returns A promise that resolves with the server response.
791
- */
792
- patchRoomState(room: string, update: Uint8Array): Promise<any>;
793
- private sendSubscribeReq;
794
- private sendUnsubscribeReq;
795
- /**
796
- * Joins a store by subscribing to its corresponding room.
797
- *
798
- * If already joined, this method does nothing. For local stores, initializes
799
- * the store locally. For remote stores, sends a subscription request to the server.
800
- *
801
- * @param store - The KokimokiStore to join.
802
- * @template T - The type of the store's state object.
803
- */
804
- join<T extends object>(store: KokimokiStore<T>): Promise<void>;
805
- /**
806
- * Leaves a store by unsubscribing from its corresponding room.
807
- *
808
- * Triggers the store's `onBeforeLeave` and `onLeave` lifecycle hooks.
809
- *
810
- * @param store - The KokimokiStore to leave.
811
- * @template T - The type of the store's state object.
812
- */
813
- leave<T extends object>(store: KokimokiStore<T>): Promise<void>;
814
- /**
815
- * Executes a transaction across one or more stores.
816
- *
817
- * Provides proxies to the stores that track changes. All changes are batched
818
- * and sent to the server atomically. The transaction ensures consistency across
819
- * multiple stores.
820
- *
821
- * @param stores - Array of stores to include in the transaction.
822
- * @param handler - Function that receives store proxies and performs modifications.
823
- * @returns A promise that resolves with the return value of the handler.
824
- * @template TStores - Tuple type of the stores array.
825
- * @template ReturnT - The return type of the handler function.
826
- *
827
- * @example
828
- * ```ts
829
- * await client.transact([playerStore, gameStore], ([player, game]) => {
830
- * player.score += 10;
831
- * game.lastUpdate = Date.now();
832
- * });
833
- * ```
834
- */
835
- transact<TStores extends readonly KokimokiStore<any>[], ReturnT = void>(stores: [...TStores], handler: (proxies: {
836
- [K in keyof TStores]: StoreValue<TStores[K]>;
837
- }) => ReturnT | Promise<ReturnT>): Promise<ReturnT>;
838
- /**
839
- * Closes the client connection and cleans up resources.
840
- *
841
- * Disables automatic reconnection, closes the WebSocket, and clears all intervals.
842
- */
843
- close(): Promise<void>;
844
- /**
845
- * Gets the internal room hash identifier for a store.
846
- *
847
- * @param store - The store to get the room hash for.
848
- * @returns The room hash as a number.
849
- * @throws Error if the store hasn't been joined.
850
- * @template T - The type of the store's state object.
851
- */
852
- getRoomHash<T extends object>(store: KokimokiStore<T>): number;
853
- /**
854
- * Creates a new remote store synchronized with the server.
855
- *
856
- * @param name - The name of the room/store.
857
- * @param defaultState - The initial state of the store.
858
- * @param autoJoin - Whether to automatically join the store (default: true).
859
- * @returns A new KokimokiStore instance.
860
- * @template T - The type of the store's state object.
861
- *
862
- * @example
863
- * ```ts
864
- * const gameStore = client.store('game', { players: [], score: 0 });
865
- * ```
866
- */
867
- store<T extends object>(name: string, defaultState: T, autoJoin?: boolean): KokimokiStore<T>;
868
- /**
869
- * Creates a new local store that persists only in the client's browser.
870
- *
871
- * Local stores are automatically joined and are not synchronized with the server.
872
- * Data is stored locally per client and app.
873
- *
874
- * @param name - The name of the local store.
875
- * @param defaultState - The initial state of the store.
876
- * @returns A new KokimokiLocalStore instance.
877
- * @template T - The type of the store's state object.
878
- *
879
- * @example
880
- * ```ts
881
- * const settingsStore = client.localStore('settings', { volume: 0.5, theme: 'dark' });
882
- * ```
883
- */
884
- localStore<T extends object>(name: string, defaultState: T): KokimokiLocalStore<T>;
885
- /**
886
- * Sends app data to the server via webhook for external processing.
887
- *
888
- * @param event - The name of the webhook event.
889
- * @param data - The data to send with the webhook.
890
- * @returns A promise that resolves with the job ID.
891
- * @template T - The type of the data being sent.
892
- *
893
- * @example
894
- * ```ts
895
- * await client.sendWebhook('game-ended', { winner: 'player1', score: 100 });
896
- * ```
897
- */
898
- sendWebhook<T>(event: string, data: T): Promise<{
899
- jobId: string;
900
- }>;
901
- /**
902
- * Access AI capabilities including text generation, structured JSON output, and image modification.
903
- */
904
- get ai(): KokimokiAiService;
905
- /**
906
- * Access file upload and management for media files, images, and user-generated content.
907
- */
908
- get storage(): KokimokiStorageService;
909
- /**
910
- * Access player ranking and score tracking with efficient queries and pagination.
911
- */
912
- get leaderboard(): KokimokiLeaderboardService;
913
- }
914
-
915
- declare enum RoomSubscriptionMode {
916
- Read = "r",
917
- Write = "w",
918
- ReadWrite = "b"
919
- }
920
-
921
- declare module "valtio" {
922
- function useSnapshot<T extends object>(p: T): T;
923
- }
924
-
925
- export { KokimokiClient, KokimokiStore };
926
- export type { KokimokiClientEvents, Paginated, Upload };