@kokimoki/app 1.17.0 → 2.0.1

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 (71) hide show
  1. package/dist/core/index.d.ts +3 -0
  2. package/dist/core/index.js +3 -0
  3. package/dist/core/kokimoki-client.d.ts +361 -0
  4. package/dist/core/kokimoki-client.js +819 -0
  5. package/dist/core/room-subscription-mode.d.ts +5 -0
  6. package/dist/core/room-subscription-mode.js +6 -0
  7. package/dist/core/room-subscription.d.ts +15 -0
  8. package/dist/core/room-subscription.js +53 -0
  9. package/dist/fields.d.ts +110 -0
  10. package/dist/fields.js +158 -0
  11. package/dist/index.d.ts +4 -8
  12. package/dist/index.js +4 -9
  13. package/dist/kokimoki-ai.d.ts +153 -0
  14. package/dist/kokimoki-ai.js +164 -0
  15. package/dist/kokimoki-awareness.d.ts +14 -13
  16. package/dist/kokimoki-awareness.js +41 -33
  17. package/dist/kokimoki-client-refactored.d.ts +80 -0
  18. package/dist/kokimoki-client-refactored.js +400 -0
  19. package/dist/kokimoki-client.d.ts +282 -76
  20. package/dist/kokimoki-client.js +295 -232
  21. package/dist/kokimoki-leaderboard.d.ts +175 -0
  22. package/dist/kokimoki-leaderboard.js +203 -0
  23. package/dist/kokimoki-schema.d.ts +113 -0
  24. package/dist/kokimoki-schema.js +162 -0
  25. package/dist/kokimoki-storage.d.ts +156 -0
  26. package/dist/kokimoki-storage.js +208 -0
  27. package/dist/kokimoki.min.d.ts +775 -110
  28. package/dist/kokimoki.min.js +4088 -2408
  29. package/dist/kokimoki.min.js.map +1 -1
  30. package/dist/llms.txt +657 -0
  31. package/dist/message-queue.d.ts +8 -0
  32. package/dist/message-queue.js +19 -0
  33. package/dist/protocol/ws-message/index.d.ts +3 -0
  34. package/dist/protocol/ws-message/index.js +3 -0
  35. package/dist/protocol/ws-message/reader.d.ts +11 -0
  36. package/dist/protocol/ws-message/reader.js +36 -0
  37. package/dist/protocol/ws-message/type.d.ts +11 -0
  38. package/dist/protocol/ws-message/type.js +12 -0
  39. package/dist/protocol/ws-message/writer.d.ts +9 -0
  40. package/dist/protocol/ws-message/writer.js +45 -0
  41. package/dist/services/index.d.ts +3 -0
  42. package/dist/services/index.js +3 -0
  43. package/dist/services/kokimoki-ai.d.ts +153 -0
  44. package/dist/services/kokimoki-ai.js +164 -0
  45. package/dist/services/kokimoki-leaderboard.d.ts +175 -0
  46. package/dist/services/kokimoki-leaderboard.js +203 -0
  47. package/dist/services/kokimoki-storage.d.ts +155 -0
  48. package/dist/services/kokimoki-storage.js +208 -0
  49. package/dist/stores/index.d.ts +3 -0
  50. package/dist/stores/index.js +3 -0
  51. package/dist/stores/kokimoki-local-store.d.ts +11 -0
  52. package/dist/stores/kokimoki-local-store.js +40 -0
  53. package/dist/stores/kokimoki-store.d.ts +22 -0
  54. package/dist/stores/kokimoki-store.js +117 -0
  55. package/dist/stores/kokimoki-transaction.d.ts +18 -0
  56. package/dist/stores/kokimoki-transaction.js +143 -0
  57. package/dist/synced-schema.d.ts +74 -0
  58. package/dist/synced-schema.js +83 -0
  59. package/dist/synced-store.d.ts +10 -0
  60. package/dist/synced-store.js +9 -0
  61. package/dist/synced-types.d.ts +47 -0
  62. package/dist/synced-types.js +67 -0
  63. package/dist/types/index.d.ts +3 -0
  64. package/dist/types/index.js +3 -0
  65. package/dist/utils/valtio.d.ts +7 -0
  66. package/dist/utils/valtio.js +6 -0
  67. package/dist/version.d.ts +1 -1
  68. package/dist/version.js +2 -1
  69. package/dist/ws-message-type copy.d.ts +6 -0
  70. package/dist/ws-message-type copy.js +7 -0
  71. package/package.json +4 -3
@@ -1,15 +1,168 @@
1
1
  import type TypedEmitter from "typed-emitter";
2
2
  import type { KokimokiClientEvents } from "./types/events";
3
- import type { Upload } from "./types/upload";
4
- import type { Paginated } from "./types/common";
5
3
  import { KokimokiStore } from "./kokimoki-store";
6
- import { KokimokiAwareness } from "./kokimoki-awareness";
7
4
  import { KokimokiLocalStore } from "./kokimoki-local-store";
5
+ import { KokimokiAi } from "./kokimoki-ai";
6
+ import { KokimokiLeaderboard } from "./kokimoki-leaderboard";
7
+ import { KokimokiStorage } from "./kokimoki-storage";
8
8
  type Mutable<T> = {
9
9
  -readonly [K in keyof T]: T[K] extends object ? Mutable<T[K]> : T[K];
10
10
  };
11
11
  type StoreValue<S> = S extends KokimokiStore<infer U> ? Mutable<U> : never;
12
12
  declare const KokimokiClient_base: new () => TypedEmitter<KokimokiClientEvents>;
13
+ /**
14
+ * Kokimoki Client - Real-time Collaborative Game Development SDK
15
+ *
16
+ * The main entry point for building multiplayer games and collaborative applications.
17
+ * Provides real-time state synchronization, AI integration, cloud storage, leaderboards,
18
+ * and more - all without complex backend setup.
19
+ *
20
+ * **Core Capabilities:**
21
+ * - **Real-time Stores**: Synchronized state with automatic conflict resolution (powered by Valtio + Y.js)
22
+ * - **Atomic Transactions**: Update multiple stores consistently with automatic batching
23
+ * - **AI Integration**: Built-in text generation, structured JSON output, and image modification
24
+ * - **Cloud Storage**: File uploads with CDN delivery and tag-based organization
25
+ * - **Leaderboards**: Efficient player ranking with database indexes and pagination
26
+ * - **Presence Tracking**: Real-time connection status for all players
27
+ * - **Time Sync**: Server-synchronized timestamps across all clients
28
+ * - **Webhooks**: Send data to external services for backend processing
29
+ *
30
+ * **Quick Start:**
31
+ * ```typescript
32
+ * import { KokimokiClient } from '@kokimoki/app';
33
+ *
34
+ * // Initialize the client
35
+ * const kmClient = new KokimokiClient(
36
+ * 'your-host.kokimoki.com',
37
+ * 'your-app-id',
38
+ * 'optional-access-code'
39
+ * );
40
+ *
41
+ * // Connect to the server
42
+ * await kmClient.connect();
43
+ *
44
+ * // Create a synchronized store
45
+ * interface GameState {
46
+ * players: Record<string, { name: string; score: number }>;
47
+ * round: number;
48
+ * }
49
+ *
50
+ * const gameStore = kmClient.store<GameState>('game', {
51
+ * players: {},
52
+ * round: 1
53
+ * });
54
+ *
55
+ * // Update state atomically
56
+ * await kmClient.transact([gameStore], ([game]) => {
57
+ * game.players[kmClient.id] = { name: 'Player 1', score: 0 };
58
+ * game.round = 2;
59
+ * });
60
+ *
61
+ * // Use in React components with Valtio
62
+ * import { useSnapshot } from 'valtio';
63
+ *
64
+ * function GameComponent() {
65
+ * const game = useSnapshot(gameStore.proxy);
66
+ * return <div>Round: {game.round}</div>;
67
+ * }
68
+ * ```
69
+ *
70
+ * **Key Features:**
71
+ *
72
+ * **1. Real-time State Management**
73
+ * - Create global stores shared across all players: `kmClient.store()`
74
+ * - Create local stores for client-side data: `kmClient.localStore()`
75
+ * - Automatic synchronization and conflict resolution
76
+ * - Use `useSnapshot()` from Valtio for reactive React components
77
+ *
78
+ * **2. Atomic Transactions**
79
+ * ```typescript
80
+ * // Update multiple stores atomically
81
+ * await kmClient.transact([playerStore, gameStore], ([player, game]) => {
82
+ * player.score += 10;
83
+ * game.lastUpdate = kmClient.serverTimestamp();
84
+ * });
85
+ * ```
86
+ *
87
+ * **3. AI Integration (No API keys required)**
88
+ * ```typescript
89
+ * // Generate text
90
+ * const story = await kmClient.ai.chat({
91
+ * model: 'gpt-4o',
92
+ * userPrompt: 'Write a quest description',
93
+ * temperature: 0.8
94
+ * });
95
+ *
96
+ * // Generate structured data
97
+ * interface Quest { title: string; reward: number; }
98
+ * const quest = await kmClient.ai.generateJson<Quest>({
99
+ * userPrompt: 'Create a level 5 quest'
100
+ * });
101
+ *
102
+ * // Modify images
103
+ * const modified = await kmClient.ai.modifyImage(url, 'Make it pixel art');
104
+ * ```
105
+ *
106
+ * **4. Cloud Storage**
107
+ * ```typescript
108
+ * // Upload files with tags
109
+ * const upload = await kmClient.storage.upload('avatar.jpg', blob, ['profile']);
110
+ *
111
+ * // Query uploads
112
+ * const images = await kmClient.storage.listUploads({
113
+ * clientId: kmClient.id,
114
+ * mimeTypes: ['image/jpeg', 'image/png']
115
+ * });
116
+ * ```
117
+ *
118
+ * **5. Leaderboards**
119
+ * ```typescript
120
+ * // Submit score (replaces previous entry)
121
+ * await kmClient.leaderboard.upsertEntry(
122
+ * 'high-scores',
123
+ * 'desc',
124
+ * 1500,
125
+ * { playerName: 'Alice' },
126
+ * {}
127
+ * );
128
+ *
129
+ * // Get top 10
130
+ * const top10 = await kmClient.leaderboard.listEntries('high-scores', 'desc', 0, 10);
131
+ * ```
132
+ *
133
+ * **6. Presence Tracking**
134
+ * ```typescript
135
+ * // Track online players
136
+ * const onlineClientIds = useSnapshot(gameStore.connections).clientIds;
137
+ * const isPlayerOnline = onlineClientIds.has(playerId);
138
+ * ```
139
+ *
140
+ * **Best Practices:**
141
+ * - Always use `kmClient.serverTimestamp()` for time-sensitive operations
142
+ * - Prefer Records over Arrays: `Record<string, T>` with timestamp keys
143
+ * - Use `kmClient.transact()` for all state updates to ensure atomicity
144
+ * - Tag uploads for easy filtering and organization
145
+ * - Use local stores for client-side settings and preferences
146
+ * - Leverage TypeScript generics for type-safe stores
147
+ *
148
+ * **Events:**
149
+ * - `connected`: Fired when client connects/reconnects to server
150
+ * - `disconnected`: Fired when connection is lost
151
+ *
152
+ * @template ClientContextT The type of client context data (custom user data from your backend)
153
+ *
154
+ * @example
155
+ * ```typescript
156
+ * // Listen for connection events
157
+ * kmClient.on('connected', () => {
158
+ * console.log('Connected to Kokimoki!');
159
+ * });
160
+ *
161
+ * kmClient.on('disconnected', () => {
162
+ * console.log('Connection lost, will auto-reconnect...');
163
+ * });
164
+ * ```
165
+ */
13
166
  export declare class KokimokiClient<ClientContextT = any> extends KokimokiClient_base {
14
167
  readonly host: string;
15
168
  readonly appId: string;
@@ -36,6 +189,9 @@ export declare class KokimokiClient<ClientContextT = any> extends KokimokiClient
36
189
  private _pingInterval;
37
190
  private _clientTokenKey;
38
191
  private _editorContext;
192
+ private _ai?;
193
+ private _storage?;
194
+ private _leaderboard?;
39
195
  constructor(host: string, appId: string, code?: string);
40
196
  get id(): string;
41
197
  get connectionId(): string;
@@ -43,9 +199,24 @@ export declare class KokimokiClient<ClientContextT = any> extends KokimokiClient
43
199
  get apiUrl(): string;
44
200
  get apiHeaders(): Headers;
45
201
  get clientContext(): ClientContextT & ({} | null);
202
+ /**
203
+ * Indicates whether the client is currently connected to the server.
204
+ */
46
205
  get connected(): boolean;
47
206
  get ws(): WebSocket;
207
+ /**
208
+ * Indicates whether the client is running in editor/development mode.
209
+ */
48
210
  get isEditor(): boolean;
211
+ /**
212
+ * Establishes a connection to the Kokimoki server.
213
+ *
214
+ * Handles authentication, WebSocket setup, and automatic reconnection.
215
+ * If already connecting, returns the existing connection promise.
216
+ *
217
+ * @returns A promise that resolves when the connection is established.
218
+ * @throws Error if the connection fails.
219
+ */
49
220
  connect(): Promise<void>;
50
221
  private handleInitMessage;
51
222
  private handleBinaryMessage;
@@ -53,104 +224,139 @@ export declare class KokimokiClient<ClientContextT = any> extends KokimokiClient
53
224
  private handleSubscribeResMessage;
54
225
  private handleUnsubscribeResMessage;
55
226
  private handleRoomUpdateMessage;
227
+ /**
228
+ * Gets the current server timestamp, accounting for client-server time offset.
229
+ *
230
+ * @returns The current server timestamp in milliseconds.
231
+ */
56
232
  serverTimestamp(): number;
233
+ /**
234
+ * Sends a Y.js update to a specific room.
235
+ *
236
+ * @param room - The name of the room to update.
237
+ * @param update - The Y.js update as a Uint8Array.
238
+ * @returns A promise that resolves with the server response.
239
+ */
57
240
  patchRoomState(room: string, update: Uint8Array): Promise<any>;
58
- private createUpload;
59
- private uploadChunks;
60
- private completeUpload;
61
- upload(name: string, blob: Blob, tags?: string[]): Promise<Upload>;
62
- updateUpload(id: string, update: {
63
- tags?: string[];
64
- }): Promise<Upload>;
65
- listUploads(filter?: {
66
- clientId?: string;
67
- mimeTypes?: string[];
68
- tags?: string[];
69
- }, skip?: number, limit?: number): Promise<Paginated<Upload>>;
70
- deleteUpload(id: string): Promise<{
71
- acknowledged: boolean;
72
- deletedCount: number;
73
- }>;
74
- exposeScriptingContext(context: any): Promise<void>;
75
241
  private sendSubscribeReq;
76
242
  private sendUnsubscribeReq;
243
+ /**
244
+ * Joins a store by subscribing to its corresponding room.
245
+ *
246
+ * If already joined, this method does nothing. For local stores, initializes
247
+ * the store locally. For remote stores, sends a subscription request to the server.
248
+ *
249
+ * @param store - The KokimokiStore to join.
250
+ * @template T - The type of the store's state object.
251
+ */
77
252
  join<T extends object>(store: KokimokiStore<T>): Promise<void>;
253
+ /**
254
+ * Leaves a store by unsubscribing from its corresponding room.
255
+ *
256
+ * Triggers the store's `onBeforeLeave` and `onLeave` lifecycle hooks.
257
+ *
258
+ * @param store - The KokimokiStore to leave.
259
+ * @template T - The type of the store's state object.
260
+ */
78
261
  leave<T extends object>(store: KokimokiStore<T>): Promise<void>;
262
+ /**
263
+ * Executes a transaction across one or more stores.
264
+ *
265
+ * Provides proxies to the stores that track changes. All changes are batched
266
+ * and sent to the server atomically. The transaction ensures consistency across
267
+ * multiple stores.
268
+ *
269
+ * @param stores - Array of stores to include in the transaction.
270
+ * @param handler - Function that receives store proxies and performs modifications.
271
+ * @returns A promise that resolves with the return value of the handler.
272
+ * @template TStores - Tuple type of the stores array.
273
+ * @template ReturnT - The return type of the handler function.
274
+ *
275
+ * @example
276
+ * ```ts
277
+ * await client.transact([playerStore, gameStore], ([player, game]) => {
278
+ * player.score += 10;
279
+ * game.lastUpdate = Date.now();
280
+ * });
281
+ * ```
282
+ */
79
283
  transact<TStores extends readonly KokimokiStore<any>[], ReturnT = void>(stores: [...TStores], handler: (proxies: {
80
284
  [K in keyof TStores]: StoreValue<TStores[K]>;
81
285
  }) => ReturnT | Promise<ReturnT>): Promise<ReturnT>;
286
+ /**
287
+ * Closes the client connection and cleans up resources.
288
+ *
289
+ * Disables automatic reconnection, closes the WebSocket, and clears all intervals.
290
+ */
82
291
  close(): Promise<void>;
83
- getRoomHash<T extends object>(store: KokimokiStore<T>): number;
84
- /** Initializers */
85
- store<T extends object>(name: string, defaultState: T, autoJoin?: boolean): KokimokiStore<T>;
86
- localStore<T extends object>(name: string, defaultState: T): KokimokiLocalStore<T>;
87
- awareness<T>(name: string, initialData: T, autoJoin?: boolean): KokimokiAwareness<T>;
88
292
  /**
89
- * Add a new entry to a leaderboard
90
- * @param leaderboardName
91
- * @param score
92
- * @param metadata
93
- * @returns
293
+ * Gets the internal room hash identifier for a store.
294
+ *
295
+ * @param store - The store to get the room hash for.
296
+ * @returns The room hash as a number.
297
+ * @throws Error if the store hasn't been joined.
298
+ * @template T - The type of the store's state object.
94
299
  */
95
- insertLeaderboardEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
96
- rank: number;
97
- }>;
300
+ getRoomHash<T extends object>(store: KokimokiStore<T>): number;
98
301
  /**
99
- * Add or update latest entry to a leaderboard
100
- * @param leaderboardName
101
- * @param score
102
- * @param metadata
103
- * @param privateMetadata Can only be read using the leaderboard API
104
- * @returns
302
+ * Creates a new remote store synchronized with the server.
303
+ *
304
+ * @param name - The name of the room/store.
305
+ * @param defaultState - The initial state of the store.
306
+ * @param autoJoin - Whether to automatically join the store (default: true).
307
+ * @returns A new KokimokiStore instance.
308
+ * @template T - The type of the store's state object.
309
+ *
310
+ * @example
311
+ * ```ts
312
+ * const gameStore = client.store('game', { players: [], score: 0 });
313
+ * ```
105
314
  */
106
- upsertLeaderboardEntry<MetadataT, PrivateMetadataT>(leaderboardName: string, sortDir: "asc" | "desc", score: number, metadata: MetadataT, privateMetadata: PrivateMetadataT): Promise<{
107
- rank: number;
108
- }>;
315
+ store<T extends object>(name: string, defaultState: T, autoJoin?: boolean): KokimokiStore<T>;
109
316
  /**
110
- * List entries in a leaderboard
111
- * @param leaderboardName
112
- * @param skip
113
- * @param limit
114
- * @returns
115
- */
116
- listLeaderboardEntries<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", skip?: number, limit?: number): Promise<Paginated<{
117
- rank: number;
118
- score: number;
119
- metadata: MetadataT;
120
- }>>;
121
- /**
122
- * Get best entry in leaderboard for a client, defaults to current client
123
- * @param leaderboardName
124
- * @param sortDir
125
- * @param clientId
126
- */
127
- getBestLeaderboardEntry<MetadataT>(leaderboardName: string, sortDir: "asc" | "desc", clientId?: string): Promise<{
128
- rank: number;
129
- score: number;
130
- metadata: MetadataT;
131
- }>;
317
+ * Creates a new local store that persists only in the client's browser.
318
+ *
319
+ * Local stores are automatically joined and are not synchronized with the server.
320
+ * Data is stored locally per client and app.
321
+ *
322
+ * @param name - The name of the local store.
323
+ * @param defaultState - The initial state of the store.
324
+ * @returns A new KokimokiLocalStore instance.
325
+ * @template T - The type of the store's state object.
326
+ *
327
+ * @example
328
+ * ```ts
329
+ * const settingsStore = client.localStore('settings', { volume: 0.5, theme: 'dark' });
330
+ * ```
331
+ */
332
+ localStore<T extends object>(name: string, defaultState: T): KokimokiLocalStore<T>;
132
333
  /**
133
- * Send app data via webhook
334
+ * Sends app data to the server via webhook for external processing.
335
+ *
336
+ * @param event - The name of the webhook event.
337
+ * @param data - The data to send with the webhook.
338
+ * @returns A promise that resolves with the job ID.
339
+ * @template T - The type of the data being sent.
340
+ *
341
+ * @example
342
+ * ```ts
343
+ * await client.sendWebhook('game-ended', { winner: 'player1', score: 100 });
344
+ * ```
134
345
  */
135
346
  sendWebhook<T>(event: string, data: T): Promise<{
136
347
  jobId: string;
137
348
  }>;
138
349
  /**
139
- * Generic AI chat endpoint: send a system prompt (and optional user prompt) to get a response.
350
+ * Access AI capabilities including text generation, structured JSON output, and image modification.
140
351
  */
141
- chat(systemPrompt: string, userPrompt?: string, temperature?: number, maxTokens?: number): Promise<{
142
- content: string;
143
- }>;
352
+ get ai(): KokimokiAi;
144
353
  /**
145
- * Use AI to apply prompt to an image
354
+ * Access file upload and management for media files, images, and user-generated content.
146
355
  */
147
- transformImage(baseImageUrl: string, prompt: string, tags?: string[]): Promise<Upload>;
356
+ get storage(): KokimokiStorage;
148
357
  /**
149
- * Load app config - optionally translated to any language
358
+ * Access player ranking and score tracking with efficient queries and pagination.
150
359
  */
151
- getConfig<T>(language?: string): Promise<{
152
- status: "processing" | "failed" | "completed";
153
- config: T;
154
- }>;
360
+ get leaderboard(): KokimokiLeaderboard;
155
361
  }
156
362
  export {};