tuturuuu 0.2.0 → 0.2.2

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/src/storage.ts DELETED
@@ -1,1082 +0,0 @@
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 packageJson from '../package.json';
29
- import { EpmClient } from './epm';
30
- import {
31
- createErrorFromResponse,
32
- isApiErrorResponse,
33
- NetworkError,
34
- RateLimitError,
35
- ValidationError,
36
- } from './errors';
37
- import { ExternalProjectsClient } from './external-projects';
38
- import type {
39
- AnalyticsResponse,
40
- BatchShareResponse,
41
- CreateDocumentData,
42
- CreateFolderResponse,
43
- CreateSignedUploadUrlOptions,
44
- DeleteDocumentResponse,
45
- DeleteResponse,
46
- DocumentResponse,
47
- DownloadOptions,
48
- GetDocumentResponse,
49
- ImageTransformOptions,
50
- ListDocumentsOptions,
51
- ListDocumentsResponse,
52
- ListStorageOptions,
53
- ListStorageResponse,
54
- ShareOptions,
55
- ShareResponse,
56
- SignedUploadUrlResponse,
57
- StorageObject,
58
- UpdateDocumentData,
59
- UploadOptions,
60
- UploadResponse,
61
- } from './types';
62
- import {
63
- createDocumentDataSchema,
64
- createSignedUploadUrlOptionsSchema,
65
- downloadOptionsSchema,
66
- listDocumentsOptionsSchema,
67
- listStorageOptionsSchema,
68
- shareOptionsSchema,
69
- updateDocumentDataSchema,
70
- uploadOptionsSchema,
71
- } from './types';
72
-
73
- /**
74
- * Transform snake_case API response to camelCase SDK format
75
- */
76
- function transformStorageObject(apiObject: any): StorageObject {
77
- return {
78
- id: apiObject.id,
79
- name: apiObject.name,
80
- createdAt: apiObject.created_at,
81
- updatedAt: apiObject.updated_at,
82
- lastAccessedAt: apiObject.last_accessed_at,
83
- metadata: apiObject.metadata,
84
- };
85
- }
86
-
87
- /**
88
- * Helper function to validate data with Zod schema and convert errors to ValidationError
89
- */
90
- function validateWithSchema<T>(
91
- schema: {
92
- parse: (data: unknown) => T;
93
- },
94
- data: unknown
95
- ): T {
96
- try {
97
- return schema.parse(data);
98
- } catch (error) {
99
- // Check if it's a Zod error by presence of errors array
100
- if (
101
- error &&
102
- typeof error === 'object' &&
103
- 'issues' in error &&
104
- Array.isArray((error as any).issues)
105
- ) {
106
- const zodError = error as any;
107
- const message = zodError.issues
108
- .map((e: any) => {
109
- const path =
110
- e.path && e.path.length > 0 ? `${e.path.join('.')}: ` : '';
111
- return `${path}${e.message}`;
112
- })
113
- .join(', ');
114
- throw new ValidationError(message);
115
- }
116
- throw error;
117
- }
118
- }
119
-
120
- function getEnvValue(key: 'TUTURUUU_API_KEY' | 'TUTURUUU_BASE_URL'): string {
121
- const env = (
122
- globalThis as typeof globalThis & {
123
- process?: {
124
- env?: Record<string, string | undefined>;
125
- };
126
- }
127
- ).process?.env;
128
-
129
- return env?.[key] ?? '';
130
- }
131
-
132
- function appendImageTransformParams(
133
- params: URLSearchParams,
134
- transform?: ImageTransformOptions
135
- ): void {
136
- if (!transform) {
137
- return;
138
- }
139
-
140
- if (transform.width !== undefined) {
141
- params.set('width', transform.width.toString());
142
- }
143
-
144
- if (transform.height !== undefined) {
145
- params.set('height', transform.height.toString());
146
- }
147
-
148
- if (transform.resize) {
149
- params.set('resize', transform.resize);
150
- }
151
-
152
- if (transform.quality !== undefined) {
153
- params.set('quality', transform.quality.toString());
154
- }
155
-
156
- if (transform.format) {
157
- params.set('format', transform.format);
158
- }
159
- }
160
-
161
- /**
162
- * Retry configuration for rate limit handling
163
- */
164
- export interface RetryConfig {
165
- /** Maximum number of retry attempts (default: 3) */
166
- maxRetries?: number;
167
- /** Initial delay in milliseconds before first retry (default: 1000) */
168
- initialDelayMs?: number;
169
- /** Maximum delay in milliseconds between retries (default: 30000) */
170
- maxDelayMs?: number;
171
- /** Whether to automatically retry on 429 rate limit errors (default: true) */
172
- retryOn429?: boolean;
173
- }
174
-
175
- /**
176
- * Configuration options for the Tuturuuu client
177
- */
178
- export interface TuturuuuClientConfig {
179
- apiKey?: string;
180
- baseUrl?: string;
181
- timeout?: number;
182
- fetch?: typeof fetch;
183
- /** Retry configuration for handling rate limits */
184
- retry?: RetryConfig;
185
- }
186
-
187
- /**
188
- * Storage operations client
189
- */
190
- export class StorageClient {
191
- constructor(private client: TuturuuuClient) {}
192
-
193
- /**
194
- * Lists files and folders in the workspace drive
195
- *
196
- * @param options - Options for listing files
197
- * @returns List of storage objects with pagination
198
- *
199
- * @example
200
- * ```typescript
201
- * const files = await client.storage.list({
202
- * path: 'documents',
203
- * search: 'report',
204
- * limit: 50,
205
- * sortBy: 'created_at',
206
- * sortOrder: 'desc'
207
- * });
208
- * ```
209
- */
210
- async list(options: ListStorageOptions = {}): Promise<ListStorageResponse> {
211
- // Validate options
212
- const validatedOptions = validateWithSchema(
213
- listStorageOptionsSchema,
214
- options
215
- );
216
-
217
- const params = new URLSearchParams();
218
- if (validatedOptions.path) params.set('path', validatedOptions.path);
219
- if (validatedOptions.search) params.set('search', validatedOptions.search);
220
- if (validatedOptions.limit !== undefined)
221
- params.set('limit', validatedOptions.limit.toString());
222
- if (validatedOptions.offset !== undefined)
223
- params.set('offset', validatedOptions.offset.toString());
224
- if (validatedOptions.sortBy) params.set('sortBy', validatedOptions.sortBy);
225
- if (validatedOptions.sortOrder)
226
- params.set('sortOrder', validatedOptions.sortOrder);
227
-
228
- const response = await this.client.requestWithRetry<any>(
229
- `/storage/list?${params.toString()}`
230
- );
231
-
232
- // Transform snake_case API response to camelCase SDK format
233
- return {
234
- data: response.data.map(transformStorageObject),
235
- pagination: response.pagination,
236
- };
237
- }
238
-
239
- /**
240
- * Uploads a file to the workspace drive using signed upload URLs
241
- *
242
- * This method first requests a signed upload URL from the platform,
243
- * then uploads the file directly to Supabase Storage. This approach
244
- * is more efficient and secure than proxying files through the API.
245
- *
246
- * @param file - File to upload (File or Blob)
247
- * @param options - Upload options
248
- * @returns Upload result with path information
249
- *
250
- * @example
251
- * ```typescript
252
- * const file = new File(['content'], 'document.pdf');
253
- * const result = await client.storage.upload(file, {
254
- * path: 'documents',
255
- * upsert: true
256
- * });
257
- *
258
- * // For Buffer in Node.js, convert to Blob first:
259
- * const buffer = Buffer.from('content');
260
- * const blob = new Blob([buffer]);
261
- * await client.storage.upload(blob, { path: 'documents' });
262
- * ```
263
- */
264
- async upload(
265
- file: File | Blob,
266
- options: UploadOptions = {}
267
- ): Promise<UploadResponse> {
268
- // Validate options
269
- const validatedOptions = validateWithSchema(uploadOptionsSchema, options);
270
-
271
- // Extract filename from File or use default for Blob
272
- const filename =
273
- file instanceof File ? file.name : `file-${Date.now()}.bin`;
274
-
275
- // Step 1: Request a signed upload URL from the platform (with retry for rate limits)
276
- const signedUrlResponse = await this.client.requestWithRetry<
277
- import('./types').SignedUploadUrlResponse
278
- >('/storage/upload-url', {
279
- method: 'POST',
280
- body: JSON.stringify({
281
- filename,
282
- path: validatedOptions.path || '',
283
- upsert: validatedOptions.upsert ?? false,
284
- }),
285
- });
286
-
287
- const { signedUrl, path } = signedUrlResponse.data;
288
-
289
- // Step 2: Upload the file directly to Supabase using the signed URL
290
- try {
291
- const uploadResponse = await this.client.fetch(signedUrl, {
292
- method: 'PUT',
293
- body: file,
294
- headers: {
295
- 'Content-Type':
296
- file instanceof File ? file.type : 'application/octet-stream',
297
- 'x-upsert': validatedOptions.upsert ? 'true' : 'false',
298
- },
299
- });
300
-
301
- if (!uploadResponse.ok) {
302
- const errorText = await uploadResponse.text();
303
- throw new NetworkError(
304
- `Upload failed: ${uploadResponse.status} ${uploadResponse.statusText} - ${errorText}`
305
- );
306
- }
307
-
308
- // Return success response in the expected format
309
- // Remove "[wsId]/" prefix to get relative path
310
- // Path format from API: [wsId]/[relativePath]
311
- const relativePath = path.replace(/^[^/]+\//, '');
312
-
313
- return {
314
- message: 'File uploaded successfully',
315
- data: {
316
- path: relativePath,
317
- fullPath: path,
318
- },
319
- };
320
- } catch (error) {
321
- if (error instanceof NetworkError) {
322
- throw error;
323
- }
324
- throw new NetworkError(
325
- `Failed to upload file: ${error instanceof Error ? error.message : 'Unknown error'}`
326
- );
327
- }
328
- }
329
-
330
- /**
331
- * Creates a signed upload URL for direct file uploads to storage
332
- *
333
- * This method returns a signed URL that external applications can use to
334
- * upload files directly to Tuturuuu storage without proxying through your server.
335
- * Useful for client-side uploads, progress tracking, and custom upload flows.
336
- *
337
- * @param options - Options for creating the signed URL
338
- * @returns Signed upload URL with metadata
339
- *
340
- * @example
341
- * ```typescript
342
- * // Get a signed URL for uploading a file
343
- * const result = await client.storage.createSignedUploadUrl({
344
- * filename: 'document.pdf',
345
- * path: 'documents',
346
- * upsert: true
347
- * });
348
- *
349
- * // Use the signed URL to upload directly from the client
350
- * const file = new File(['content'], 'document.pdf');
351
- * await fetch(result.data.signedUrl, {
352
- * method: 'PUT',
353
- * body: file,
354
- * headers: {
355
- * 'Content-Type': file.type,
356
- * 'x-upsert': 'true'
357
- * }
358
- * });
359
- * ```
360
- */
361
- async createSignedUploadUrl(
362
- options: CreateSignedUploadUrlOptions
363
- ): Promise<SignedUploadUrlResponse> {
364
- // Validate options
365
- const validatedOptions = validateWithSchema(
366
- createSignedUploadUrlOptionsSchema,
367
- options
368
- );
369
-
370
- return this.client.requestWithRetry<SignedUploadUrlResponse>(
371
- '/storage/upload-url',
372
- {
373
- method: 'POST',
374
- body: JSON.stringify({
375
- filename: validatedOptions.filename,
376
- path: validatedOptions.path || '',
377
- upsert: validatedOptions.upsert ?? false,
378
- }),
379
- }
380
- );
381
- }
382
-
383
- /**
384
- * Downloads a file from the workspace drive
385
- *
386
- * @param path - Path to the file
387
- * @returns File blob
388
- *
389
- * @example
390
- * ```typescript
391
- * const blob = await client.storage.download('documents/report.pdf');
392
- * ```
393
- */
394
- async download(path: string, options: DownloadOptions = {}): Promise<Blob> {
395
- if (!path) {
396
- throw new ValidationError('Path is required');
397
- }
398
-
399
- const validatedOptions = validateWithSchema(downloadOptionsSchema, options);
400
-
401
- // Properly encode path to handle spaces and special characters
402
- // Normalize backslashes to forward slashes
403
- const normalizedPath = path.replace(/\\/g, '/');
404
-
405
- // Split path into segments, encode each segment, and rejoin
406
- const segments = normalizedPath.split('/').filter((s) => s.length > 0);
407
- const encodedPath = segments.map((s) => encodeURIComponent(s)).join('/');
408
- const queryParams = new URLSearchParams();
409
- appendImageTransformParams(queryParams, validatedOptions.transform);
410
-
411
- // Ensure baseUrl doesn't end with slash to avoid double slashes
412
- const baseUrl = this.client.baseUrl.replace(/\/$/, '');
413
- const downloadUrl = `${baseUrl}/storage/download/${encodedPath}${
414
- queryParams.size > 0 ? `?${queryParams.toString()}` : ''
415
- }`;
416
-
417
- const response = await this.client.fetch(downloadUrl, {
418
- method: 'GET',
419
- headers: {
420
- Authorization: `Bearer ${this.client.apiKey}`,
421
- 'X-SDK-Client': `tuturuuu/${packageJson.version || '0.0.1'}`,
422
- Accept: 'application/octet-stream, */*',
423
- },
424
- });
425
-
426
- if (!response.ok) {
427
- // Check if response is JSON before attempting to parse
428
- const contentType = response.headers.get('content-type');
429
- const isJson = contentType?.toLowerCase().includes('application/json');
430
-
431
- if (isJson) {
432
- try {
433
- const errorData = await response.json();
434
- if (isApiErrorResponse(errorData)) {
435
- throw createErrorFromResponse(errorData, response.status);
436
- }
437
- throw new NetworkError(
438
- `HTTP ${response.status}: ${response.statusText}`
439
- );
440
- } catch (error) {
441
- // If JSON parsing fails, fall back to text
442
- if (error instanceof SyntaxError) {
443
- const text = await response.text();
444
- throw new NetworkError(
445
- `HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
446
- );
447
- }
448
- throw error;
449
- }
450
- } else {
451
- // Non-JSON response
452
- const text = await response.text();
453
- throw new NetworkError(
454
- `HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
455
- );
456
- }
457
- }
458
-
459
- return response.blob();
460
- }
461
-
462
- /**
463
- * Deletes files or folders from the workspace drive
464
- *
465
- * @param paths - Array of paths to delete
466
- * @returns Delete result
467
- *
468
- * @example
469
- * ```typescript
470
- * const result = await client.storage.delete([
471
- * 'documents/old-report.pdf',
472
- * 'images/screenshot.png'
473
- * ]);
474
- * ```
475
- */
476
- async delete(paths: string[]): Promise<DeleteResponse> {
477
- if (!Array.isArray(paths) || paths.length === 0) {
478
- throw new ValidationError('At least one path is required');
479
- }
480
-
481
- if (paths.length > 100) {
482
- throw new ValidationError('Maximum 100 paths can be deleted at once');
483
- }
484
-
485
- return this.client.request<DeleteResponse>('/storage/delete', {
486
- method: 'DELETE',
487
- body: JSON.stringify({ paths }),
488
- });
489
- }
490
-
491
- /**
492
- * Creates a new folder in the workspace drive
493
- *
494
- * @param path - Parent path
495
- * @param name - Folder name
496
- * @returns Create folder result
497
- *
498
- * @example
499
- * ```typescript
500
- * const result = await client.storage.createFolder('documents', 'reports');
501
- * ```
502
- */
503
- async createFolder(
504
- path: string,
505
- name: string
506
- ): Promise<CreateFolderResponse> {
507
- if (!name) {
508
- throw new ValidationError('Folder name is required');
509
- }
510
-
511
- return this.client.request<CreateFolderResponse>('/storage/folders', {
512
- method: 'POST',
513
- body: JSON.stringify({ path, name }),
514
- });
515
- }
516
-
517
- /**
518
- * Generates a signed URL for sharing a file
519
- *
520
- * @param path - Path to the file
521
- * @param options - Share options
522
- * @returns Signed URL with expiration
523
- *
524
- * @example
525
- * ```typescript
526
- * const result = await client.storage.share('documents/report.pdf', {
527
- * expiresIn: 3600 // 1 hour
528
- * });
529
- * console.log(result.data.signedUrl);
530
- * ```
531
- */
532
- async share(
533
- path: string,
534
- options: ShareOptions = {}
535
- ): Promise<ShareResponse> {
536
- if (!path) {
537
- throw new ValidationError('Path is required');
538
- }
539
-
540
- // Validate options
541
- const validatedOptions = validateWithSchema(shareOptionsSchema, options);
542
-
543
- return this.client.requestWithRetry<ShareResponse>('/storage/share', {
544
- method: 'POST',
545
- body: JSON.stringify({
546
- path,
547
- expiresIn: validatedOptions.expiresIn,
548
- transform: validatedOptions.transform,
549
- }),
550
- });
551
- }
552
-
553
- /**
554
- * Generates signed URLs for multiple files at once (batch operation)
555
- *
556
- * @param paths - Array of file paths (max 100)
557
- * @param expiresIn - Expiration time in seconds (default 3600)
558
- * @returns Array of signed URL data with path, signedUrl, and optional error
559
- *
560
- * @example
561
- * ```typescript
562
- * const result = await client.storage.createSignedUrls(
563
- * ['folder/avatar1.png', 'folder/avatar2.png'],
564
- * 3600
565
- * );
566
- *
567
- * // Access successful URLs
568
- * result.data.forEach(item => {
569
- * if (!item.error) {
570
- * console.log(`${item.path}: ${item.signedUrl}`);
571
- * } else {
572
- * console.error(`${item.path} failed: ${item.error}`);
573
- * }
574
- * });
575
- * ```
576
- */
577
- async createSignedUrls(
578
- paths: string[],
579
- expiresIn = 3600
580
- ): Promise<BatchShareResponse> {
581
- if (!Array.isArray(paths) || paths.length === 0) {
582
- throw new ValidationError(
583
- 'Paths array is required and must not be empty'
584
- );
585
- }
586
-
587
- if (paths.length > 100) {
588
- throw new ValidationError('Maximum 100 paths can be processed at once');
589
- }
590
-
591
- return this.client.requestWithRetry<BatchShareResponse>(
592
- '/storage/share-batch',
593
- {
594
- method: 'POST',
595
- body: JSON.stringify({ paths, expiresIn }),
596
- }
597
- );
598
- }
599
-
600
- /**
601
- * Retrieves storage analytics for the workspace
602
- *
603
- * @returns Storage usage statistics
604
- *
605
- * @example
606
- * ```typescript
607
- * const analytics = await client.storage.getAnalytics();
608
- * console.log(`Used: ${analytics.data.totalSize} bytes`);
609
- * console.log(`Files: ${analytics.data.fileCount}`);
610
- * ```
611
- */
612
- async getAnalytics(): Promise<AnalyticsResponse> {
613
- return this.client.requestWithRetry<AnalyticsResponse>(
614
- '/storage/analytics'
615
- );
616
- }
617
- }
618
-
619
- /**
620
- * Documents operations client
621
- */
622
- export class DocumentsClient {
623
- constructor(private client: TuturuuuClient) {}
624
-
625
- /**
626
- * Lists documents in the workspace
627
- *
628
- * @param options - Options for listing documents
629
- * @returns List of documents with pagination
630
- *
631
- * @example
632
- * ```typescript
633
- * const docs = await client.documents.list({
634
- * search: 'meeting',
635
- * limit: 20,
636
- * isPublic: false
637
- * });
638
- * ```
639
- */
640
- async list(
641
- options: ListDocumentsOptions = {}
642
- ): Promise<ListDocumentsResponse> {
643
- // Validate options
644
- const validatedOptions = validateWithSchema(
645
- listDocumentsOptionsSchema,
646
- options
647
- );
648
-
649
- const params = new URLSearchParams();
650
- if (validatedOptions.search) params.set('search', validatedOptions.search);
651
- if (validatedOptions.limit !== undefined)
652
- params.set('limit', validatedOptions.limit.toString());
653
- if (validatedOptions.offset !== undefined)
654
- params.set('offset', validatedOptions.offset.toString());
655
- if (validatedOptions.isPublic !== undefined)
656
- params.set('isPublic', validatedOptions.isPublic.toString());
657
-
658
- return this.client.requestWithRetry<ListDocumentsResponse>(
659
- `/documents?${params.toString()}`
660
- );
661
- }
662
-
663
- /**
664
- * Creates a new document
665
- *
666
- * @param data - Document data
667
- * @returns Created document
668
- *
669
- * @example
670
- * ```typescript
671
- * const doc = await client.documents.create({
672
- * name: 'Meeting Notes',
673
- * content: 'Discussion points...',
674
- * isPublic: false
675
- * });
676
- * ```
677
- */
678
- async create(data: CreateDocumentData): Promise<DocumentResponse> {
679
- // Validate data
680
- const validatedData = validateWithSchema(createDocumentDataSchema, data);
681
-
682
- return this.client.request<DocumentResponse>('/documents', {
683
- method: 'POST',
684
- body: JSON.stringify(validatedData),
685
- });
686
- }
687
-
688
- /**
689
- * Gets a document by ID
690
- *
691
- * @param id - Document ID
692
- * @returns Document data
693
- *
694
- * @example
695
- * ```typescript
696
- * const doc = await client.documents.get('doc-id-123');
697
- * ```
698
- */
699
- async get(id: string): Promise<GetDocumentResponse> {
700
- if (!id) {
701
- throw new ValidationError('Document ID is required');
702
- }
703
-
704
- return this.client.requestWithRetry<GetDocumentResponse>(
705
- `/documents/${id}`
706
- );
707
- }
708
-
709
- /**
710
- * Updates a document
711
- *
712
- * @param id - Document ID
713
- * @param data - Update data
714
- * @returns Updated document
715
- *
716
- * @example
717
- * ```typescript
718
- * const doc = await client.documents.update('doc-id-123', {
719
- * name: 'Updated Meeting Notes',
720
- * content: 'New content...'
721
- * });
722
- * ```
723
- */
724
- async update(
725
- id: string,
726
- data: UpdateDocumentData
727
- ): Promise<DocumentResponse> {
728
- if (!id) {
729
- throw new ValidationError('Document ID is required');
730
- }
731
-
732
- // Validate data
733
- const validatedData = validateWithSchema(updateDocumentDataSchema, data);
734
-
735
- return this.client.request<DocumentResponse>(`/documents/${id}`, {
736
- method: 'PATCH',
737
- body: JSON.stringify(validatedData),
738
- });
739
- }
740
-
741
- /**
742
- * Deletes a document
743
- *
744
- * @param id - Document ID
745
- * @returns Delete confirmation
746
- *
747
- * @example
748
- * ```typescript
749
- * await client.documents.delete('doc-id-123');
750
- * ```
751
- */
752
- async delete(id: string): Promise<DeleteDocumentResponse> {
753
- if (!id) {
754
- throw new ValidationError('Document ID is required');
755
- }
756
-
757
- return this.client.request<DeleteDocumentResponse>(`/documents/${id}`, {
758
- method: 'DELETE',
759
- });
760
- }
761
-
762
- /**
763
- * Searches documents by name
764
- * Alias for list() with search parameter
765
- *
766
- * @param query - Search query
767
- * @param options - Additional list options
768
- * @returns List of matching documents
769
- */
770
- async search(
771
- query: string,
772
- options: Omit<ListDocumentsOptions, 'search'> = {}
773
- ): Promise<ListDocumentsResponse> {
774
- return this.list({ ...options, search: query });
775
- }
776
- }
777
-
778
- /**
779
- * Default retry configuration
780
- */
781
- const DEFAULT_RETRY_CONFIG: Required<RetryConfig> = {
782
- maxRetries: 3,
783
- initialDelayMs: 1000,
784
- maxDelayMs: 30000,
785
- retryOn429: true,
786
- };
787
-
788
- /**
789
- * Main Tuturuuu SDK client
790
- */
791
- export class TuturuuuClient {
792
- public readonly apiKey: string;
793
- public readonly baseUrl: string;
794
- public readonly timeout: number;
795
- public readonly fetch: typeof fetch;
796
- public readonly retryConfig: Required<RetryConfig>;
797
-
798
- public readonly storage: StorageClient;
799
- public readonly documents: DocumentsClient;
800
- public readonly epm: EpmClient;
801
- public readonly externalProjects: ExternalProjectsClient;
802
-
803
- /**
804
- * Creates a new Tuturuuu client instance
805
- *
806
- * @param config - Client configuration (optional, will auto-load from environment variables)
807
- *
808
- * @example
809
- * ```typescript
810
- * // Explicit configuration
811
- * const client = new TuturuuuClient({
812
- * apiKey: 'ttr_your_api_key',
813
- * baseUrl: 'https://tuturuuu.com/api/v1', // optional, this is the default
814
- * timeout: 30000 // optional, default 30s
815
- * });
816
- *
817
- * // Auto-load from environment variables (TUTURUUU_API_KEY, TUTURUUU_BASE_URL)
818
- * const client = new TuturuuuClient();
819
- * ```
820
- */
821
- constructor(config?: string | TuturuuuClientConfig) {
822
- // Support both string API key and config object
823
- if (typeof config === 'string') {
824
- this.apiKey = config;
825
- this.baseUrl = 'https://tuturuuu.com/api/v1';
826
- this.timeout = 30000;
827
- this.fetch = globalThis.fetch;
828
- this.retryConfig = { ...DEFAULT_RETRY_CONFIG };
829
- } else if (config) {
830
- this.apiKey = config.apiKey || getEnvValue('TUTURUUU_API_KEY');
831
- this.baseUrl =
832
- config.baseUrl ||
833
- getEnvValue('TUTURUUU_BASE_URL') ||
834
- 'https://tuturuuu.com/api/v1';
835
- this.timeout = config.timeout || 30000;
836
- this.fetch = config.fetch || globalThis.fetch;
837
- this.retryConfig = { ...DEFAULT_RETRY_CONFIG, ...config.retry };
838
- } else {
839
- // Auto-load from environment variables
840
- this.apiKey = getEnvValue('TUTURUUU_API_KEY');
841
- this.baseUrl =
842
- getEnvValue('TUTURUUU_BASE_URL') || 'https://tuturuuu.com/api/v1';
843
- this.timeout = 30000;
844
- this.fetch = globalThis.fetch;
845
- this.retryConfig = { ...DEFAULT_RETRY_CONFIG };
846
- }
847
-
848
- // Validate API key
849
- if (!this.apiKey?.startsWith('ttr_')) {
850
- throw new ValidationError(
851
- 'Invalid API key format. Expected key to start with "ttr_" or set TUTURUUU_API_KEY environment variable'
852
- );
853
- }
854
-
855
- // Initialize sub-clients
856
- this.storage = new StorageClient(this);
857
- this.documents = new DocumentsClient(this);
858
- this.epm = new EpmClient({
859
- apiKey: this.apiKey,
860
- baseUrl: this.baseUrl,
861
- fetch: this.fetch,
862
- timeout: this.timeout,
863
- });
864
- this.externalProjects = new ExternalProjectsClient({
865
- apiKey: this.apiKey,
866
- baseUrl: this.baseUrl,
867
- fetch: this.fetch,
868
- timeout: this.timeout,
869
- });
870
- }
871
-
872
- /**
873
- * Internal method to make HTTP requests
874
- * @internal
875
- */
876
- async request<T>(
877
- endpoint: string,
878
- options: {
879
- method?: string;
880
- body?: string | FormData;
881
- skipJsonContentType?: boolean;
882
- } = {}
883
- ): Promise<T> {
884
- const { method = 'GET', body, skipJsonContentType = false } = options;
885
-
886
- const headers: Record<string, string> = {
887
- Authorization: `Bearer ${this.apiKey}`,
888
- 'X-SDK-Client': `tuturuuu/${packageJson.version || '0.0.1'}`,
889
- Accept: 'application/json',
890
- };
891
-
892
- // Only set Content-Type for JSON bodies
893
- // For FormData, we must NOT set Content-Type - let fetch set it automatically with the boundary
894
- if (!skipJsonContentType && typeof body === 'string') {
895
- headers['Content-Type'] = 'application/json';
896
- }
897
-
898
- // IMPORTANT: When using FormData, we must not pass Content-Type header at all
899
- // The fetch implementation will automatically set it with the correct multipart boundary
900
- // If we pass any Content-Type (even undefined), it can interfere with boundary generation
901
- const isFormData = body instanceof FormData;
902
-
903
- try {
904
- const controller = new AbortController();
905
- const timeoutId = setTimeout(() => controller.abort(), this.timeout);
906
-
907
- const response = await this.fetch(`${this.baseUrl}${endpoint}`, {
908
- method,
909
- // For FormData, omit headers that might interfere with automatic Content-Type setting
910
- headers: isFormData
911
- ? ({
912
- Authorization: headers.Authorization,
913
- 'X-SDK-Client': headers['X-SDK-Client'],
914
- Accept: headers.Accept,
915
- // Do NOT include Content-Type - let fetch set it automatically
916
- } as HeadersInit)
917
- : headers,
918
- body,
919
- signal: controller.signal,
920
- });
921
-
922
- clearTimeout(timeoutId);
923
-
924
- if (!response.ok) {
925
- // Extract rate limit headers for 429 responses
926
- const retryAfter = response.headers.get('Retry-After');
927
- const resetTime = response.headers.get('X-RateLimit-Reset');
928
-
929
- // Handle 429 rate limit errors specially - they may come from infrastructure
930
- // (e.g., Vercel) with HTML content, not JSON
931
- if (response.status === 429) {
932
- const message = retryAfter
933
- ? `Rate limit exceeded. Retry after ${retryAfter} seconds.`
934
- : 'Rate limit exceeded. Please try again later.';
935
-
936
- throw new RateLimitError(message, {
937
- code: 'RATE_LIMIT_EXCEEDED',
938
- retryAfter: retryAfter ? parseInt(retryAfter, 10) : undefined,
939
- resetTime: resetTime ? parseInt(resetTime, 10) : undefined,
940
- });
941
- }
942
-
943
- // Check if response is JSON before attempting to parse
944
- const contentType = response.headers.get('content-type');
945
- const isJson = contentType?.toLowerCase().includes('application/json');
946
-
947
- if (isJson) {
948
- try {
949
- const errorData = await response.json();
950
- if (isApiErrorResponse(errorData)) {
951
- throw createErrorFromResponse(errorData, response.status, {
952
- retryAfter,
953
- resetTime,
954
- });
955
- }
956
- throw new NetworkError(
957
- `HTTP ${response.status}: ${response.statusText}`
958
- );
959
- } catch (error) {
960
- // If JSON parsing fails, fall back to text
961
- if (error instanceof SyntaxError) {
962
- const text = await response.text();
963
- throw new NetworkError(
964
- `HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
965
- );
966
- }
967
- throw error;
968
- }
969
- } else {
970
- // Non-JSON response
971
- const text = await response.text();
972
- throw new NetworkError(
973
- `HTTP ${response.status}: ${response.statusText} - ${text.substring(0, 200)}`
974
- );
975
- }
976
- }
977
-
978
- // Check if success response is JSON before parsing
979
- const contentType = response.headers.get('content-type');
980
- const isJson = contentType?.toLowerCase().includes('application/json');
981
-
982
- if (!isJson) {
983
- const text = await response.text();
984
- throw new NetworkError(
985
- `Expected JSON response but received ${contentType || 'unknown content type'} - ${text.substring(0, 200)}`
986
- );
987
- }
988
-
989
- return response.json();
990
- } catch (error) {
991
- if (error instanceof Error && error.name === 'AbortError') {
992
- throw new NetworkError(`Request timeout after ${this.timeout}ms`);
993
- }
994
- throw error;
995
- }
996
- }
997
-
998
- /**
999
- * Internal method to make HTTP requests with automatic retry on rate limit errors
1000
- * @internal
1001
- */
1002
- async requestWithRetry<T>(
1003
- endpoint: string,
1004
- options: {
1005
- method?: string;
1006
- body?: string | FormData;
1007
- skipJsonContentType?: boolean;
1008
- } = {}
1009
- ): Promise<T> {
1010
- const { maxRetries, initialDelayMs, maxDelayMs, retryOn429 } =
1011
- this.retryConfig;
1012
-
1013
- if (!retryOn429) {
1014
- return this.request<T>(endpoint, options);
1015
- }
1016
-
1017
- let lastError: Error | undefined;
1018
-
1019
- for (let attempt = 0; attempt <= maxRetries; attempt++) {
1020
- try {
1021
- return await this.request<T>(endpoint, options);
1022
- } catch (error) {
1023
- if (error instanceof RateLimitError && attempt < maxRetries) {
1024
- // Calculate delay: use retryAfter if available, otherwise exponential backoff
1025
- const baseDelay = error.retryAfter
1026
- ? error.retryAfter * 1000
1027
- : initialDelayMs * 2 ** attempt;
1028
- const delay = Math.min(baseDelay, maxDelayMs);
1029
-
1030
- await this.sleep(delay);
1031
- lastError = error;
1032
- continue;
1033
- }
1034
- throw error;
1035
- }
1036
- }
1037
-
1038
- // This should never be reached, but TypeScript needs it
1039
- throw lastError ?? new Error('Unexpected retry loop exit');
1040
- }
1041
-
1042
- /**
1043
- * Sleep helper for retry delays
1044
- * @internal
1045
- */
1046
- private sleep(ms: number): Promise<void> {
1047
- return new Promise((resolve) => setTimeout(resolve, ms));
1048
- }
1049
- }
1050
-
1051
- /**
1052
- * Default singleton instance of TuturuuuClient with auto-configured credentials
1053
- *
1054
- * This instance automatically loads credentials from environment variables:
1055
- * - TUTURUUU_API_KEY (required)
1056
- * - TUTURUUU_BASE_URL (optional, defaults to https://tuturuuu.com/api/v1)
1057
- *
1058
- * Uses lazy initialization to avoid validation errors during module imports.
1059
- * The client is only instantiated when first accessed.
1060
- *
1061
- * @example
1062
- * ```typescript
1063
- * import { tuturuuu } from 'tuturuuu';
1064
- *
1065
- * // Use storage operations
1066
- * const analytics = await tuturuuu.storage.getAnalytics();
1067
- * const files = await tuturuuu.storage.list({ path: 'documents' });
1068
- *
1069
- * // Use document operations
1070
- * const docs = await tuturuuu.documents.list();
1071
- * ```
1072
- */
1073
- let _tuturuuuInstance: TuturuuuClient | undefined;
1074
-
1075
- export const tuturuuu: TuturuuuClient = new Proxy({} as TuturuuuClient, {
1076
- get(_targett, prop) {
1077
- if (!_tuturuuuInstance) {
1078
- _tuturuuuInstance = new TuturuuuClient();
1079
- }
1080
- return _tuturuuuInstance[prop as keyof TuturuuuClient];
1081
- },
1082
- });