tuturuuu 0.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.
- package/README.md +270 -0
- package/package.json +47 -0
- package/src/documents.test.ts +523 -0
- package/src/errors.test.ts +278 -0
- package/src/errors.ts +161 -0
- package/src/index.ts +60 -0
- package/src/storage.test.ts +604 -0
- package/src/storage.ts +702 -0
- package/src/types.test.ts +562 -0
- package/src/types.ts +291 -0
package/src/storage.ts
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tuturuuu Storage SDK
|
|
3
|
+
*
|
|
4
|
+
* Official SDK for interacting with Tuturuuu workspace resources
|
|
5
|
+
* including storage (files/folders) and documents.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* ```typescript
|
|
9
|
+
* import { TuturuuuClient } from 'tuturuuu';
|
|
10
|
+
*
|
|
11
|
+
* const client = new TuturuuuClient('ttr_your_api_key');
|
|
12
|
+
*
|
|
13
|
+
* // List files
|
|
14
|
+
* const files = await client.storage.list({ path: 'documents' });
|
|
15
|
+
*
|
|
16
|
+
* // Upload a file
|
|
17
|
+
* const file = new File(['content'], 'example.txt');
|
|
18
|
+
* await client.storage.upload(file, { path: 'documents' });
|
|
19
|
+
*
|
|
20
|
+
* // Create a document
|
|
21
|
+
* const doc = await client.documents.create({
|
|
22
|
+
* name: 'My Document',
|
|
23
|
+
* content: 'Hello World'
|
|
24
|
+
* });
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
import type { ZodSchema } from 'zod';
|
|
29
|
+
import packageJson from '../package.json';
|
|
30
|
+
import {
|
|
31
|
+
createErrorFromResponse,
|
|
32
|
+
isApiErrorResponse,
|
|
33
|
+
NetworkError,
|
|
34
|
+
ValidationError,
|
|
35
|
+
} from './errors';
|
|
36
|
+
import type {
|
|
37
|
+
AnalyticsResponse,
|
|
38
|
+
CreateDocumentData,
|
|
39
|
+
CreateFolderResponse,
|
|
40
|
+
DeleteDocumentResponse,
|
|
41
|
+
DeleteResponse,
|
|
42
|
+
DocumentResponse,
|
|
43
|
+
GetDocumentResponse,
|
|
44
|
+
ListDocumentsOptions,
|
|
45
|
+
ListDocumentsResponse,
|
|
46
|
+
ListStorageOptions,
|
|
47
|
+
ListStorageResponse,
|
|
48
|
+
ShareOptions,
|
|
49
|
+
ShareResponse,
|
|
50
|
+
StorageObject,
|
|
51
|
+
UpdateDocumentData,
|
|
52
|
+
UploadOptions,
|
|
53
|
+
UploadResponse,
|
|
54
|
+
} from './types';
|
|
55
|
+
import {
|
|
56
|
+
createDocumentDataSchema,
|
|
57
|
+
listDocumentsOptionsSchema,
|
|
58
|
+
listStorageOptionsSchema,
|
|
59
|
+
shareOptionsSchema,
|
|
60
|
+
updateDocumentDataSchema,
|
|
61
|
+
uploadOptionsSchema,
|
|
62
|
+
} from './types';
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Transform snake_case API response to camelCase SDK format
|
|
66
|
+
*/
|
|
67
|
+
function transformStorageObject(apiObject: any): StorageObject {
|
|
68
|
+
return {
|
|
69
|
+
id: apiObject.id,
|
|
70
|
+
name: apiObject.name,
|
|
71
|
+
createdAt: apiObject.created_at,
|
|
72
|
+
updatedAt: apiObject.updated_at,
|
|
73
|
+
lastAccessedAt: apiObject.last_accessed_at,
|
|
74
|
+
metadata: apiObject.metadata,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Helper function to validate data with Zod schema and convert errors to ValidationError
|
|
80
|
+
*/
|
|
81
|
+
function validateWithSchema<T>(schema: ZodSchema<T>, data: unknown): T {
|
|
82
|
+
try {
|
|
83
|
+
return schema.parse(data);
|
|
84
|
+
} catch (error) {
|
|
85
|
+
// Check if it's a Zod error by presence of errors array
|
|
86
|
+
if (
|
|
87
|
+
error &&
|
|
88
|
+
typeof error === 'object' &&
|
|
89
|
+
'issues' in error &&
|
|
90
|
+
Array.isArray((error as any).issues)
|
|
91
|
+
) {
|
|
92
|
+
const zodError = error as any;
|
|
93
|
+
const message = zodError.issues
|
|
94
|
+
.map((e: any) => {
|
|
95
|
+
const path =
|
|
96
|
+
e.path && e.path.length > 0 ? `${e.path.join('.')}: ` : '';
|
|
97
|
+
return `${path}${e.message}`;
|
|
98
|
+
})
|
|
99
|
+
.join(', ');
|
|
100
|
+
throw new ValidationError(message);
|
|
101
|
+
}
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* Configuration options for the Tuturuuu client
|
|
108
|
+
*/
|
|
109
|
+
export interface TuturuuuClientConfig {
|
|
110
|
+
apiKey: string;
|
|
111
|
+
baseUrl?: string;
|
|
112
|
+
timeout?: number;
|
|
113
|
+
fetch?: typeof fetch;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Storage operations client
|
|
118
|
+
*/
|
|
119
|
+
export class StorageClient {
|
|
120
|
+
constructor(private client: TuturuuuClient) {}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Lists files and folders in the workspace drive
|
|
124
|
+
*
|
|
125
|
+
* @param options - Options for listing files
|
|
126
|
+
* @returns List of storage objects with pagination
|
|
127
|
+
*
|
|
128
|
+
* @example
|
|
129
|
+
* ```typescript
|
|
130
|
+
* const files = await client.storage.list({
|
|
131
|
+
* path: 'documents',
|
|
132
|
+
* search: 'report',
|
|
133
|
+
* limit: 50,
|
|
134
|
+
* sortBy: 'created_at',
|
|
135
|
+
* sortOrder: 'desc'
|
|
136
|
+
* });
|
|
137
|
+
* ```
|
|
138
|
+
*/
|
|
139
|
+
async list(options: ListStorageOptions = {}): Promise<ListStorageResponse> {
|
|
140
|
+
// Validate options
|
|
141
|
+
const validatedOptions = validateWithSchema(
|
|
142
|
+
listStorageOptionsSchema,
|
|
143
|
+
options
|
|
144
|
+
);
|
|
145
|
+
|
|
146
|
+
const params = new URLSearchParams();
|
|
147
|
+
if (validatedOptions.path) params.set('path', validatedOptions.path);
|
|
148
|
+
if (validatedOptions.search) params.set('search', validatedOptions.search);
|
|
149
|
+
if (validatedOptions.limit !== undefined)
|
|
150
|
+
params.set('limit', validatedOptions.limit.toString());
|
|
151
|
+
if (validatedOptions.offset !== undefined)
|
|
152
|
+
params.set('offset', validatedOptions.offset.toString());
|
|
153
|
+
if (validatedOptions.sortBy) params.set('sortBy', validatedOptions.sortBy);
|
|
154
|
+
if (validatedOptions.sortOrder)
|
|
155
|
+
params.set('sortOrder', validatedOptions.sortOrder);
|
|
156
|
+
|
|
157
|
+
const response = await this.client.request<any>(
|
|
158
|
+
`/storage/list?${params.toString()}`
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
// Transform snake_case API response to camelCase SDK format
|
|
162
|
+
return {
|
|
163
|
+
data: response.data.map(transformStorageObject),
|
|
164
|
+
pagination: response.pagination,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Uploads a file to the workspace drive
|
|
170
|
+
*
|
|
171
|
+
* @param file - File to upload (File or Blob)
|
|
172
|
+
* @param options - Upload options
|
|
173
|
+
* @returns Upload result with path information
|
|
174
|
+
*
|
|
175
|
+
* @example
|
|
176
|
+
* ```typescript
|
|
177
|
+
* const file = new File(['content'], 'document.pdf');
|
|
178
|
+
* const result = await client.storage.upload(file, {
|
|
179
|
+
* path: 'documents',
|
|
180
|
+
* upsert: true
|
|
181
|
+
* });
|
|
182
|
+
*
|
|
183
|
+
* // For Buffer in Node.js, convert to Blob first:
|
|
184
|
+
* const buffer = Buffer.from('content');
|
|
185
|
+
* const blob = new Blob([buffer]);
|
|
186
|
+
* await client.storage.upload(blob, { path: 'documents' });
|
|
187
|
+
* ```
|
|
188
|
+
*/
|
|
189
|
+
async upload(
|
|
190
|
+
file: File | Blob,
|
|
191
|
+
options: UploadOptions = {}
|
|
192
|
+
): Promise<UploadResponse> {
|
|
193
|
+
// Validate options
|
|
194
|
+
const validatedOptions = validateWithSchema(uploadOptionsSchema, options);
|
|
195
|
+
|
|
196
|
+
const formData = new FormData();
|
|
197
|
+
|
|
198
|
+
// Append file with proper filename for File objects
|
|
199
|
+
if (file instanceof File) {
|
|
200
|
+
formData.append('file', file);
|
|
201
|
+
} else {
|
|
202
|
+
// For Blob, provide a default filename
|
|
203
|
+
formData.append('file', file, 'file');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (validatedOptions.path) {
|
|
207
|
+
formData.append('path', validatedOptions.path);
|
|
208
|
+
}
|
|
209
|
+
if (validatedOptions.upsert !== undefined) {
|
|
210
|
+
formData.append('upsert', validatedOptions.upsert.toString());
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return this.client.request<UploadResponse>('/storage/upload', {
|
|
214
|
+
method: 'POST',
|
|
215
|
+
body: formData,
|
|
216
|
+
// Don't set Content-Type header - let browser set it with boundary
|
|
217
|
+
skipJsonContentType: true,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Downloads a file from the workspace drive
|
|
223
|
+
*
|
|
224
|
+
* @param path - Path to the file
|
|
225
|
+
* @returns File blob
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```typescript
|
|
229
|
+
* const blob = await client.storage.download('documents/report.pdf');
|
|
230
|
+
* ```
|
|
231
|
+
*/
|
|
232
|
+
async download(path: string): Promise<Blob> {
|
|
233
|
+
if (!path) {
|
|
234
|
+
throw new ValidationError('Path is required');
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Properly encode path to handle spaces and special characters
|
|
238
|
+
// Normalize backslashes to forward slashes
|
|
239
|
+
const normalizedPath = path.replace(/\\/g, '/');
|
|
240
|
+
|
|
241
|
+
// Split path into segments, encode each segment, and rejoin
|
|
242
|
+
const segments = normalizedPath.split('/').filter((s) => s.length > 0);
|
|
243
|
+
const encodedPath = segments.map((s) => encodeURIComponent(s)).join('/');
|
|
244
|
+
|
|
245
|
+
// Ensure baseUrl doesn't end with slash to avoid double slashes
|
|
246
|
+
const baseUrl = this.client.baseUrl.replace(/\/$/, '');
|
|
247
|
+
|
|
248
|
+
const response = await this.client.fetch(
|
|
249
|
+
`${baseUrl}/storage/download/${encodedPath}`,
|
|
250
|
+
{
|
|
251
|
+
method: 'GET',
|
|
252
|
+
headers: {
|
|
253
|
+
Authorization: `Bearer ${this.client.apiKey}`,
|
|
254
|
+
'X-SDK-Client': `tuturuuu/${packageJson.version || '0.0.1'}`,
|
|
255
|
+
Accept: 'application/octet-stream, */*',
|
|
256
|
+
},
|
|
257
|
+
}
|
|
258
|
+
);
|
|
259
|
+
|
|
260
|
+
if (!response.ok) {
|
|
261
|
+
// Check if response is JSON before attempting to parse
|
|
262
|
+
const contentType = response.headers.get('content-type');
|
|
263
|
+
const isJson = contentType?.toLowerCase().includes('application/json');
|
|
264
|
+
|
|
265
|
+
if (isJson) {
|
|
266
|
+
try {
|
|
267
|
+
const errorData = await response.json();
|
|
268
|
+
if (isApiErrorResponse(errorData)) {
|
|
269
|
+
throw createErrorFromResponse(errorData, response.status);
|
|
270
|
+
}
|
|
271
|
+
throw new NetworkError(
|
|
272
|
+
`HTTP ${response.status}: ${response.statusText}`
|
|
273
|
+
);
|
|
274
|
+
} catch (error) {
|
|
275
|
+
// If JSON parsing fails, fall back to text
|
|
276
|
+
if (error instanceof SyntaxError) {
|
|
277
|
+
const text = await response.text();
|
|
278
|
+
throw new NetworkError(
|
|
279
|
+
`HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
throw error;
|
|
283
|
+
}
|
|
284
|
+
} else {
|
|
285
|
+
// Non-JSON response
|
|
286
|
+
const text = await response.text();
|
|
287
|
+
throw new NetworkError(
|
|
288
|
+
`HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
|
|
289
|
+
);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return response.blob();
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Deletes files or folders from the workspace drive
|
|
298
|
+
*
|
|
299
|
+
* @param paths - Array of paths to delete
|
|
300
|
+
* @returns Delete result
|
|
301
|
+
*
|
|
302
|
+
* @example
|
|
303
|
+
* ```typescript
|
|
304
|
+
* const result = await client.storage.delete([
|
|
305
|
+
* 'documents/old-report.pdf',
|
|
306
|
+
* 'images/screenshot.png'
|
|
307
|
+
* ]);
|
|
308
|
+
* ```
|
|
309
|
+
*/
|
|
310
|
+
async delete(paths: string[]): Promise<DeleteResponse> {
|
|
311
|
+
if (!Array.isArray(paths) || paths.length === 0) {
|
|
312
|
+
throw new ValidationError('At least one path is required');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (paths.length > 100) {
|
|
316
|
+
throw new ValidationError('Maximum 100 paths can be deleted at once');
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return this.client.request<DeleteResponse>('/storage/delete', {
|
|
320
|
+
method: 'DELETE',
|
|
321
|
+
body: JSON.stringify({ paths }),
|
|
322
|
+
});
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/**
|
|
326
|
+
* Creates a new folder in the workspace drive
|
|
327
|
+
*
|
|
328
|
+
* @param path - Parent path
|
|
329
|
+
* @param name - Folder name
|
|
330
|
+
* @returns Create folder result
|
|
331
|
+
*
|
|
332
|
+
* @example
|
|
333
|
+
* ```typescript
|
|
334
|
+
* const result = await client.storage.createFolder('documents', 'reports');
|
|
335
|
+
* ```
|
|
336
|
+
*/
|
|
337
|
+
async createFolder(
|
|
338
|
+
path: string,
|
|
339
|
+
name: string
|
|
340
|
+
): Promise<CreateFolderResponse> {
|
|
341
|
+
if (!name) {
|
|
342
|
+
throw new ValidationError('Folder name is required');
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
return this.client.request<CreateFolderResponse>('/storage/folders', {
|
|
346
|
+
method: 'POST',
|
|
347
|
+
body: JSON.stringify({ path, name }),
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Generates a signed URL for sharing a file
|
|
353
|
+
*
|
|
354
|
+
* @param path - Path to the file
|
|
355
|
+
* @param options - Share options
|
|
356
|
+
* @returns Signed URL with expiration
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* ```typescript
|
|
360
|
+
* const result = await client.storage.share('documents/report.pdf', {
|
|
361
|
+
* expiresIn: 3600 // 1 hour
|
|
362
|
+
* });
|
|
363
|
+
* console.log(result.data.signedUrl);
|
|
364
|
+
* ```
|
|
365
|
+
*/
|
|
366
|
+
async share(
|
|
367
|
+
path: string,
|
|
368
|
+
options: ShareOptions = {}
|
|
369
|
+
): Promise<ShareResponse> {
|
|
370
|
+
if (!path) {
|
|
371
|
+
throw new ValidationError('Path is required');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Validate options
|
|
375
|
+
const validatedOptions = validateWithSchema(shareOptionsSchema, options);
|
|
376
|
+
|
|
377
|
+
return this.client.request<ShareResponse>('/storage/share', {
|
|
378
|
+
method: 'POST',
|
|
379
|
+
body: JSON.stringify({
|
|
380
|
+
path,
|
|
381
|
+
expiresIn: validatedOptions.expiresIn,
|
|
382
|
+
}),
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/**
|
|
387
|
+
* Retrieves storage analytics for the workspace
|
|
388
|
+
*
|
|
389
|
+
* @returns Storage usage statistics
|
|
390
|
+
*
|
|
391
|
+
* @example
|
|
392
|
+
* ```typescript
|
|
393
|
+
* const analytics = await client.storage.getAnalytics();
|
|
394
|
+
* console.log(`Used: ${analytics.data.totalSize} bytes`);
|
|
395
|
+
* console.log(`Files: ${analytics.data.fileCount}`);
|
|
396
|
+
* ```
|
|
397
|
+
*/
|
|
398
|
+
async getAnalytics(): Promise<AnalyticsResponse> {
|
|
399
|
+
return this.client.request<AnalyticsResponse>('/storage/analytics');
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Documents operations client
|
|
405
|
+
*/
|
|
406
|
+
export class DocumentsClient {
|
|
407
|
+
constructor(private client: TuturuuuClient) {}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Lists documents in the workspace
|
|
411
|
+
*
|
|
412
|
+
* @param options - Options for listing documents
|
|
413
|
+
* @returns List of documents with pagination
|
|
414
|
+
*
|
|
415
|
+
* @example
|
|
416
|
+
* ```typescript
|
|
417
|
+
* const docs = await client.documents.list({
|
|
418
|
+
* search: 'meeting',
|
|
419
|
+
* limit: 20,
|
|
420
|
+
* isPublic: false
|
|
421
|
+
* });
|
|
422
|
+
* ```
|
|
423
|
+
*/
|
|
424
|
+
async list(
|
|
425
|
+
options: ListDocumentsOptions = {}
|
|
426
|
+
): Promise<ListDocumentsResponse> {
|
|
427
|
+
// Validate options
|
|
428
|
+
const validatedOptions = validateWithSchema(
|
|
429
|
+
listDocumentsOptionsSchema,
|
|
430
|
+
options
|
|
431
|
+
);
|
|
432
|
+
|
|
433
|
+
const params = new URLSearchParams();
|
|
434
|
+
if (validatedOptions.search) params.set('search', validatedOptions.search);
|
|
435
|
+
if (validatedOptions.limit !== undefined)
|
|
436
|
+
params.set('limit', validatedOptions.limit.toString());
|
|
437
|
+
if (validatedOptions.offset !== undefined)
|
|
438
|
+
params.set('offset', validatedOptions.offset.toString());
|
|
439
|
+
if (validatedOptions.isPublic !== undefined)
|
|
440
|
+
params.set('isPublic', validatedOptions.isPublic.toString());
|
|
441
|
+
|
|
442
|
+
return this.client.request<ListDocumentsResponse>(
|
|
443
|
+
`/documents?${params.toString()}`
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/**
|
|
448
|
+
* Creates a new document
|
|
449
|
+
*
|
|
450
|
+
* @param data - Document data
|
|
451
|
+
* @returns Created document
|
|
452
|
+
*
|
|
453
|
+
* @example
|
|
454
|
+
* ```typescript
|
|
455
|
+
* const doc = await client.documents.create({
|
|
456
|
+
* name: 'Meeting Notes',
|
|
457
|
+
* content: 'Discussion points...',
|
|
458
|
+
* isPublic: false
|
|
459
|
+
* });
|
|
460
|
+
* ```
|
|
461
|
+
*/
|
|
462
|
+
async create(data: CreateDocumentData): Promise<DocumentResponse> {
|
|
463
|
+
// Validate data
|
|
464
|
+
const validatedData = validateWithSchema(createDocumentDataSchema, data);
|
|
465
|
+
|
|
466
|
+
return this.client.request<DocumentResponse>('/documents', {
|
|
467
|
+
method: 'POST',
|
|
468
|
+
body: JSON.stringify(validatedData),
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Gets a document by ID
|
|
474
|
+
*
|
|
475
|
+
* @param id - Document ID
|
|
476
|
+
* @returns Document data
|
|
477
|
+
*
|
|
478
|
+
* @example
|
|
479
|
+
* ```typescript
|
|
480
|
+
* const doc = await client.documents.get('doc-id-123');
|
|
481
|
+
* ```
|
|
482
|
+
*/
|
|
483
|
+
async get(id: string): Promise<GetDocumentResponse> {
|
|
484
|
+
if (!id) {
|
|
485
|
+
throw new ValidationError('Document ID is required');
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
return this.client.request<GetDocumentResponse>(`/documents/${id}`);
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* Updates a document
|
|
493
|
+
*
|
|
494
|
+
* @param id - Document ID
|
|
495
|
+
* @param data - Update data
|
|
496
|
+
* @returns Updated document
|
|
497
|
+
*
|
|
498
|
+
* @example
|
|
499
|
+
* ```typescript
|
|
500
|
+
* const doc = await client.documents.update('doc-id-123', {
|
|
501
|
+
* name: 'Updated Meeting Notes',
|
|
502
|
+
* content: 'New content...'
|
|
503
|
+
* });
|
|
504
|
+
* ```
|
|
505
|
+
*/
|
|
506
|
+
async update(
|
|
507
|
+
id: string,
|
|
508
|
+
data: UpdateDocumentData
|
|
509
|
+
): Promise<DocumentResponse> {
|
|
510
|
+
if (!id) {
|
|
511
|
+
throw new ValidationError('Document ID is required');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// Validate data
|
|
515
|
+
const validatedData = validateWithSchema(updateDocumentDataSchema, data);
|
|
516
|
+
|
|
517
|
+
return this.client.request<DocumentResponse>(`/documents/${id}`, {
|
|
518
|
+
method: 'PATCH',
|
|
519
|
+
body: JSON.stringify(validatedData),
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
/**
|
|
524
|
+
* Deletes a document
|
|
525
|
+
*
|
|
526
|
+
* @param id - Document ID
|
|
527
|
+
* @returns Delete confirmation
|
|
528
|
+
*
|
|
529
|
+
* @example
|
|
530
|
+
* ```typescript
|
|
531
|
+
* await client.documents.delete('doc-id-123');
|
|
532
|
+
* ```
|
|
533
|
+
*/
|
|
534
|
+
async delete(id: string): Promise<DeleteDocumentResponse> {
|
|
535
|
+
if (!id) {
|
|
536
|
+
throw new ValidationError('Document ID is required');
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
return this.client.request<DeleteDocumentResponse>(`/documents/${id}`, {
|
|
540
|
+
method: 'DELETE',
|
|
541
|
+
});
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
/**
|
|
545
|
+
* Searches documents by name
|
|
546
|
+
* Alias for list() with search parameter
|
|
547
|
+
*
|
|
548
|
+
* @param query - Search query
|
|
549
|
+
* @param options - Additional list options
|
|
550
|
+
* @returns List of matching documents
|
|
551
|
+
*/
|
|
552
|
+
async search(
|
|
553
|
+
query: string,
|
|
554
|
+
options: Omit<ListDocumentsOptions, 'search'> = {}
|
|
555
|
+
): Promise<ListDocumentsResponse> {
|
|
556
|
+
return this.list({ ...options, search: query });
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* Main Tuturuuu SDK client
|
|
562
|
+
*/
|
|
563
|
+
export class TuturuuuClient {
|
|
564
|
+
public readonly apiKey: string;
|
|
565
|
+
public readonly baseUrl: string;
|
|
566
|
+
public readonly timeout: number;
|
|
567
|
+
public readonly fetch: typeof fetch;
|
|
568
|
+
|
|
569
|
+
public readonly storage: StorageClient;
|
|
570
|
+
public readonly documents: DocumentsClient;
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Creates a new Tuturuuu client instance
|
|
574
|
+
*
|
|
575
|
+
* @param config - Client configuration
|
|
576
|
+
*
|
|
577
|
+
* @example
|
|
578
|
+
* ```typescript
|
|
579
|
+
* const client = new TuturuuuClient({
|
|
580
|
+
* apiKey: 'ttr_your_api_key',
|
|
581
|
+
* baseUrl: 'https://tuturuuu.com/api/v1', // optional, this is the default
|
|
582
|
+
* timeout: 30000 // optional, default 30s
|
|
583
|
+
* });
|
|
584
|
+
* ```
|
|
585
|
+
*/
|
|
586
|
+
constructor(config: string | TuturuuuClientConfig) {
|
|
587
|
+
// Support both string API key and config object
|
|
588
|
+
if (typeof config === 'string') {
|
|
589
|
+
this.apiKey = config;
|
|
590
|
+
this.baseUrl = 'https://tuturuuu.com/api/v1';
|
|
591
|
+
this.timeout = 30000;
|
|
592
|
+
this.fetch = globalThis.fetch;
|
|
593
|
+
} else {
|
|
594
|
+
this.apiKey = config.apiKey;
|
|
595
|
+
this.baseUrl = config.baseUrl || 'https://tuturuuu.com/api/v1';
|
|
596
|
+
this.timeout = config.timeout || 30000;
|
|
597
|
+
this.fetch = config.fetch || globalThis.fetch;
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
// Validate API key
|
|
601
|
+
if (!this.apiKey || !this.apiKey.startsWith('ttr_')) {
|
|
602
|
+
throw new ValidationError(
|
|
603
|
+
'Invalid API key format. Expected key to start with "ttr_"'
|
|
604
|
+
);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Initialize sub-clients
|
|
608
|
+
this.storage = new StorageClient(this);
|
|
609
|
+
this.documents = new DocumentsClient(this);
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Internal method to make HTTP requests
|
|
614
|
+
* @internal
|
|
615
|
+
*/
|
|
616
|
+
async request<T>(
|
|
617
|
+
endpoint: string,
|
|
618
|
+
options: {
|
|
619
|
+
method?: string;
|
|
620
|
+
body?: string | FormData;
|
|
621
|
+
skipJsonContentType?: boolean;
|
|
622
|
+
} = {}
|
|
623
|
+
): Promise<T> {
|
|
624
|
+
const { method = 'GET', body, skipJsonContentType = false } = options;
|
|
625
|
+
|
|
626
|
+
const headers: Record<string, string> = {
|
|
627
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
628
|
+
'X-SDK-Client': `tuturuuu/${packageJson.version || '0.0.1'}`,
|
|
629
|
+
Accept: 'application/json',
|
|
630
|
+
};
|
|
631
|
+
|
|
632
|
+
// Only set Content-Type for JSON bodies
|
|
633
|
+
if (!skipJsonContentType && typeof body === 'string') {
|
|
634
|
+
headers['Content-Type'] = 'application/json';
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
try {
|
|
638
|
+
const controller = new AbortController();
|
|
639
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
640
|
+
|
|
641
|
+
const response = await this.fetch(`${this.baseUrl}${endpoint}`, {
|
|
642
|
+
method,
|
|
643
|
+
headers,
|
|
644
|
+
body,
|
|
645
|
+
signal: controller.signal,
|
|
646
|
+
});
|
|
647
|
+
|
|
648
|
+
clearTimeout(timeoutId);
|
|
649
|
+
|
|
650
|
+
if (!response.ok) {
|
|
651
|
+
// Check if response is JSON before attempting to parse
|
|
652
|
+
const contentType = response.headers.get('content-type');
|
|
653
|
+
const isJson = contentType?.toLowerCase().includes('application/json');
|
|
654
|
+
|
|
655
|
+
if (isJson) {
|
|
656
|
+
try {
|
|
657
|
+
const errorData = await response.json();
|
|
658
|
+
if (isApiErrorResponse(errorData)) {
|
|
659
|
+
throw createErrorFromResponse(errorData, response.status);
|
|
660
|
+
}
|
|
661
|
+
throw new NetworkError(
|
|
662
|
+
`HTTP ${response.status}: ${response.statusText}`
|
|
663
|
+
);
|
|
664
|
+
} catch (error) {
|
|
665
|
+
// If JSON parsing fails, fall back to text
|
|
666
|
+
if (error instanceof SyntaxError) {
|
|
667
|
+
const text = await response.text();
|
|
668
|
+
throw new NetworkError(
|
|
669
|
+
`HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
throw error;
|
|
673
|
+
}
|
|
674
|
+
} else {
|
|
675
|
+
// Non-JSON response
|
|
676
|
+
const text = await response.text();
|
|
677
|
+
throw new NetworkError(
|
|
678
|
+
`HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Check if success response is JSON before parsing
|
|
684
|
+
const contentType = response.headers.get('content-type');
|
|
685
|
+
const isJson = contentType?.toLowerCase().includes('application/json');
|
|
686
|
+
|
|
687
|
+
if (!isJson) {
|
|
688
|
+
const text = await response.text();
|
|
689
|
+
throw new NetworkError(
|
|
690
|
+
`Expected JSON response but received ${contentType || 'unknown content type'} - ${text.substring(0, 200)}`
|
|
691
|
+
);
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
return response.json();
|
|
695
|
+
} catch (error) {
|
|
696
|
+
if (error instanceof Error && error.name === 'AbortError') {
|
|
697
|
+
throw new NetworkError(`Request timeout after ${this.timeout}ms`);
|
|
698
|
+
}
|
|
699
|
+
throw error;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
}
|