@kokimoki/app 1.17.0 → 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.
@@ -0,0 +1,156 @@
1
+ import { KokimokiClient } from "./kokimoki-client";
2
+ import { Paginated } from "./types/common";
3
+ import { Upload } from "./types/upload";
4
+ /**
5
+ * Kokimoki Storage Service
6
+ *
7
+ * Provides file upload and management capabilities for game applications. Ideal for media files
8
+ * (images, videos, audio) and other data not suitable for real-time stores (JSON, text files).
9
+ *
10
+ * **Key Features:**
11
+ * - Upload files to cloud storage with CDN delivery
12
+ * - Tag-based organization and filtering
13
+ * - Query uploads by client, MIME type, or tags
14
+ * - Pagination support for large collections
15
+ * - Public CDN URLs for direct access
16
+ *
17
+ * **Common Use Cases:**
18
+ * - Player avatars and profile images
19
+ * - Game screenshots and replays
20
+ * - User-generated content
21
+ * - Asset uploads (levels, maps, custom skins)
22
+ * - JSON configuration files
23
+ *
24
+ * Access via `kmClient.storage`
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // Upload an image
29
+ * const upload = await kmClient.storage.upload('avatar.jpg', imageBlob, ['profile']);
30
+ *
31
+ * // Query user's uploads
32
+ * const myUploads = await kmClient.storage.listUploads({
33
+ * clientId: kmClient.id
34
+ * });
35
+ *
36
+ * // Use in store
37
+ * await kmClient.transact([store], (state) => {
38
+ * state.playerAvatar = upload.url;
39
+ * });
40
+ * ```
41
+ */
42
+ export declare class KokimokiStorage {
43
+ private readonly client;
44
+ constructor(client: KokimokiClient);
45
+ private createUpload;
46
+ private uploadChunks;
47
+ private completeUpload;
48
+ /**
49
+ * Upload a file to cloud storage.
50
+ *
51
+ * Uploads a file (Blob) to Kokimoki storage and returns an Upload object with a public CDN URL.
52
+ * Files are automatically chunked for efficient upload. The returned URL can be used directly
53
+ * in your application (e.g., in img tags or store state).
54
+ *
55
+ * @param name The filename for the upload
56
+ * @param blob The Blob object containing the file data
57
+ * @param tags Optional array of tags for organizing and filtering uploads (default: [])
58
+ * @returns A promise resolving to the Upload object with CDN URL and metadata
59
+ *
60
+ * @example
61
+ * ```typescript
62
+ * // Upload image with tags
63
+ * const upload = await kmClient.storage.upload(
64
+ * 'avatar.jpg',
65
+ * imageBlob,
66
+ * ['profile', 'avatar']
67
+ * );
68
+ *
69
+ * // Use the CDN URL
70
+ * console.log(upload.url); // https://cdn.kokimoki.com/...
71
+ *
72
+ * // Store in game state
73
+ * await kmClient.transact([store], (state) => {
74
+ * state.players[kmClient.id].avatar = upload.url;
75
+ * });
76
+ * ```
77
+ */
78
+ upload(name: string, blob: Blob, tags?: string[]): Promise<Upload>;
79
+ /**
80
+ * Update metadata for an existing upload.
81
+ *
82
+ * Allows you to replace the tags associated with an upload. Useful for reorganizing
83
+ * or recategorizing uploaded files.
84
+ *
85
+ * @param id The upload ID to update
86
+ * @param update Object containing the new tags array
87
+ * @returns A promise resolving to the updated Upload object
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * // Update tags
92
+ * const updated = await kmClient.storage.updateUpload(upload.id, {
93
+ * tags: ['archived', 'old-profile']
94
+ * });
95
+ * ```
96
+ */
97
+ updateUpload(id: string, update: {
98
+ tags?: string[];
99
+ }): Promise<Upload>;
100
+ /**
101
+ * Query uploaded files with filtering and pagination.
102
+ *
103
+ * Retrieves a list of uploads matching the specified criteria. Supports filtering by
104
+ * client (uploader), MIME types, and tags. Use pagination for large collections.
105
+ *
106
+ * @param filter Optional filter criteria
107
+ * @param filter.clientId Filter by uploader's client ID
108
+ * @param filter.mimeTypes Filter by MIME types (e.g., ['image/jpeg', 'image/png'])
109
+ * @param filter.tags Filter by tags (all specified tags must match)
110
+ * @param skip Number of results to skip for pagination (default: 0)
111
+ * @param limit Maximum number of results to return (default: 100)
112
+ * @returns A promise resolving to paginated Upload results with total count
113
+ *
114
+ * @example
115
+ * ```typescript
116
+ * // Get current user's images
117
+ * const myImages = await kmClient.storage.listUploads({
118
+ * clientId: kmClient.id,
119
+ * mimeTypes: ['image/jpeg', 'image/png']
120
+ * });
121
+ *
122
+ * // Get all profile avatars
123
+ * const avatars = await kmClient.storage.listUploads({
124
+ * tags: ['profile', 'avatar']
125
+ * });
126
+ *
127
+ * // Pagination
128
+ * const page2 = await kmClient.storage.listUploads({}, 10, 10);
129
+ * ```
130
+ */
131
+ listUploads(filter?: {
132
+ clientId?: string;
133
+ mimeTypes?: string[];
134
+ tags?: string[];
135
+ }, skip?: number, limit?: number): Promise<Paginated<Upload>>;
136
+ /**
137
+ * Permanently delete an uploaded file.
138
+ *
139
+ * Removes the file from cloud storage and the CDN. The URL will no longer be accessible.
140
+ * This operation cannot be undone.
141
+ *
142
+ * @param id The upload ID to delete
143
+ * @returns A promise resolving to deletion confirmation
144
+ *
145
+ * @example
146
+ * ```typescript
147
+ * // Delete an upload
148
+ * const result = await kmClient.storage.deleteUpload(upload.id);
149
+ * console.log(`Deleted: ${result.deletedCount} file(s)`);
150
+ * ```
151
+ */
152
+ deleteUpload(id: string): Promise<{
153
+ acknowledged: boolean;
154
+ deletedCount: number;
155
+ }>;
156
+ }
@@ -0,0 +1,208 @@
1
+ /**
2
+ * Kokimoki Storage Service
3
+ *
4
+ * Provides file upload and management capabilities for game applications. Ideal for media files
5
+ * (images, videos, audio) and other data not suitable for real-time stores (JSON, text files).
6
+ *
7
+ * **Key Features:**
8
+ * - Upload files to cloud storage with CDN delivery
9
+ * - Tag-based organization and filtering
10
+ * - Query uploads by client, MIME type, or tags
11
+ * - Pagination support for large collections
12
+ * - Public CDN URLs for direct access
13
+ *
14
+ * **Common Use Cases:**
15
+ * - Player avatars and profile images
16
+ * - Game screenshots and replays
17
+ * - User-generated content
18
+ * - Asset uploads (levels, maps, custom skins)
19
+ * - JSON configuration files
20
+ *
21
+ * Access via `kmClient.storage`
22
+ *
23
+ * @example
24
+ * ```typescript
25
+ * // Upload an image
26
+ * const upload = await kmClient.storage.upload('avatar.jpg', imageBlob, ['profile']);
27
+ *
28
+ * // Query user's uploads
29
+ * const myUploads = await kmClient.storage.listUploads({
30
+ * clientId: kmClient.id
31
+ * });
32
+ *
33
+ * // Use in store
34
+ * await kmClient.transact([store], (state) => {
35
+ * state.playerAvatar = upload.url;
36
+ * });
37
+ * ```
38
+ */
39
+ export class KokimokiStorage {
40
+ client;
41
+ constructor(client) {
42
+ this.client = client;
43
+ }
44
+ // Storage
45
+ async createUpload(name, blob, tags) {
46
+ const res = await fetch(`${this.client.apiUrl}/uploads`, {
47
+ method: "POST",
48
+ headers: this.client.apiHeaders,
49
+ body: JSON.stringify({
50
+ name,
51
+ size: blob.size,
52
+ mimeType: blob.type,
53
+ tags,
54
+ }),
55
+ });
56
+ return await res.json();
57
+ }
58
+ async uploadChunks(blob, chunkSize, signedUrls) {
59
+ return await Promise.all(signedUrls.map(async (url, index) => {
60
+ const start = index * chunkSize;
61
+ const end = Math.min(start + chunkSize, blob.size);
62
+ const chunk = blob.slice(start, end);
63
+ const res = await fetch(url, { method: "PUT", body: chunk });
64
+ return JSON.parse(res.headers.get("ETag") || '""');
65
+ }));
66
+ }
67
+ async completeUpload(id, etags) {
68
+ const res = await fetch(`${this.client.apiUrl}/uploads/${id}`, {
69
+ method: "PUT",
70
+ headers: this.client.apiHeaders,
71
+ body: JSON.stringify({ etags }),
72
+ });
73
+ return await res.json();
74
+ }
75
+ /**
76
+ * Upload a file to cloud storage.
77
+ *
78
+ * Uploads a file (Blob) to Kokimoki storage and returns an Upload object with a public CDN URL.
79
+ * Files are automatically chunked for efficient upload. The returned URL can be used directly
80
+ * in your application (e.g., in img tags or store state).
81
+ *
82
+ * @param name The filename for the upload
83
+ * @param blob The Blob object containing the file data
84
+ * @param tags Optional array of tags for organizing and filtering uploads (default: [])
85
+ * @returns A promise resolving to the Upload object with CDN URL and metadata
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * // Upload image with tags
90
+ * const upload = await kmClient.storage.upload(
91
+ * 'avatar.jpg',
92
+ * imageBlob,
93
+ * ['profile', 'avatar']
94
+ * );
95
+ *
96
+ * // Use the CDN URL
97
+ * console.log(upload.url); // https://cdn.kokimoki.com/...
98
+ *
99
+ * // Store in game state
100
+ * await kmClient.transact([store], (state) => {
101
+ * state.players[kmClient.id].avatar = upload.url;
102
+ * });
103
+ * ```
104
+ */
105
+ async upload(name, blob, tags = []) {
106
+ const { id, chunkSize, urls } = await this.createUpload(name, blob, tags);
107
+ const etags = await this.uploadChunks(blob, chunkSize, urls);
108
+ return await this.completeUpload(id, etags);
109
+ }
110
+ /**
111
+ * Update metadata for an existing upload.
112
+ *
113
+ * Allows you to replace the tags associated with an upload. Useful for reorganizing
114
+ * or recategorizing uploaded files.
115
+ *
116
+ * @param id The upload ID to update
117
+ * @param update Object containing the new tags array
118
+ * @returns A promise resolving to the updated Upload object
119
+ *
120
+ * @example
121
+ * ```typescript
122
+ * // Update tags
123
+ * const updated = await kmClient.storage.updateUpload(upload.id, {
124
+ * tags: ['archived', 'old-profile']
125
+ * });
126
+ * ```
127
+ */
128
+ async updateUpload(id, update) {
129
+ const res = await fetch(`${this.client.apiUrl}/uploads/${id}`, {
130
+ method: "PUT",
131
+ headers: this.client.apiHeaders,
132
+ body: JSON.stringify(update),
133
+ });
134
+ return await res.json();
135
+ }
136
+ /**
137
+ * Query uploaded files with filtering and pagination.
138
+ *
139
+ * Retrieves a list of uploads matching the specified criteria. Supports filtering by
140
+ * client (uploader), MIME types, and tags. Use pagination for large collections.
141
+ *
142
+ * @param filter Optional filter criteria
143
+ * @param filter.clientId Filter by uploader's client ID
144
+ * @param filter.mimeTypes Filter by MIME types (e.g., ['image/jpeg', 'image/png'])
145
+ * @param filter.tags Filter by tags (all specified tags must match)
146
+ * @param skip Number of results to skip for pagination (default: 0)
147
+ * @param limit Maximum number of results to return (default: 100)
148
+ * @returns A promise resolving to paginated Upload results with total count
149
+ *
150
+ * @example
151
+ * ```typescript
152
+ * // Get current user's images
153
+ * const myImages = await kmClient.storage.listUploads({
154
+ * clientId: kmClient.id,
155
+ * mimeTypes: ['image/jpeg', 'image/png']
156
+ * });
157
+ *
158
+ * // Get all profile avatars
159
+ * const avatars = await kmClient.storage.listUploads({
160
+ * tags: ['profile', 'avatar']
161
+ * });
162
+ *
163
+ * // Pagination
164
+ * const page2 = await kmClient.storage.listUploads({}, 10, 10);
165
+ * ```
166
+ */
167
+ async listUploads(filter = {}, skip = 0, limit = 100) {
168
+ const url = new URL("/uploads", this.client.apiUrl);
169
+ url.searchParams.set("skip", skip.toString());
170
+ url.searchParams.set("limit", limit.toString());
171
+ if (filter.clientId) {
172
+ url.searchParams.set("clientId", filter.clientId);
173
+ }
174
+ if (filter.mimeTypes) {
175
+ url.searchParams.set("mimeTypes", filter.mimeTypes.join());
176
+ }
177
+ if (filter.tags) {
178
+ url.searchParams.set("tags", filter.tags.join());
179
+ }
180
+ const res = await fetch(url.href, {
181
+ headers: this.client.apiHeaders,
182
+ });
183
+ return await res.json();
184
+ }
185
+ /**
186
+ * Permanently delete an uploaded file.
187
+ *
188
+ * Removes the file from cloud storage and the CDN. The URL will no longer be accessible.
189
+ * This operation cannot be undone.
190
+ *
191
+ * @param id The upload ID to delete
192
+ * @returns A promise resolving to deletion confirmation
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * // Delete an upload
197
+ * const result = await kmClient.storage.deleteUpload(upload.id);
198
+ * console.log(`Deleted: ${result.deletedCount} file(s)`);
199
+ * ```
200
+ */
201
+ async deleteUpload(id) {
202
+ const res = await fetch(`${this.client.apiUrl}/uploads/${id}`, {
203
+ method: "DELETE",
204
+ headers: this.client.apiHeaders,
205
+ });
206
+ return await res.json();
207
+ }
208
+ }