drivekit 0.0.0-stage → 1.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.
@@ -0,0 +1,893 @@
1
+ import { drive_v3 } from '@googleapis/drive';
2
+ import { OAuth2Client } from 'google-auth-library';
3
+ import { EventEmitter } from 'node:events';
4
+
5
+ interface BrowserLoginOptions {
6
+ clientId: string;
7
+ clientSecret: string;
8
+ port?: number;
9
+ scopes?: string[];
10
+ }
11
+ interface LoginResult {
12
+ tokens: {
13
+ access_token?: string | null;
14
+ refresh_token?: string | null;
15
+ expiry_date?: number | null;
16
+ token_type?: string | null;
17
+ };
18
+ client: any;
19
+ }
20
+ /**
21
+ * Initiates interactive 1-click browser login flow:
22
+ * 1. Starts ephemeral local callback server
23
+ * 2. Opens default browser to Google OAuth consent
24
+ * 3. Catches callback, exchanges code for tokens, and serves success page
25
+ */
26
+ declare function loginWithBrowser(options: BrowserLoginOptions): Promise<LoginResult>;
27
+
28
+ type DriveApiFile = drive_v3.Schema$File;
29
+ type DriveApiFileList = drive_v3.Schema$FileList;
30
+ type DriveApiPermission = drive_v3.Schema$Permission;
31
+ /**
32
+ * Authentication configuration options for DriveKit
33
+ */
34
+ interface DriveKitAuthConfig {
35
+ /** Path to Google Service Account JSON file */
36
+ keyFilePath?: string;
37
+ /** Parsed Service Account JSON object */
38
+ credentials?: {
39
+ client_email?: string;
40
+ private_key?: string;
41
+ project_id?: string;
42
+ [key: string]: any;
43
+ };
44
+ /** Pre-existing OAuth2Client or access token */
45
+ oauth2Client?: OAuth2Client;
46
+ /** Direct bearer access token */
47
+ accessToken?: string;
48
+ /** OAuth2 Client Credentials for OAuth flow */
49
+ oauth?: {
50
+ clientId: string;
51
+ clientSecret: string;
52
+ redirectUri?: string;
53
+ refreshToken?: string;
54
+ };
55
+ /** Scopes (defaults to full drive scope: ['https://www.googleapis.com/auth/drive']) */
56
+ scopes?: string[];
57
+ }
58
+ /**
59
+ * Global configuration options for DriveKit instance
60
+ */
61
+ interface DriveKitOptions {
62
+ auth?: DriveKitAuthConfig;
63
+ /** Root folder ID to restrict operations (defaults to 'root') */
64
+ rootFolderId?: string;
65
+ /** Default chunk size in bytes for resumable uploads (default: 8MB) */
66
+ uploadChunkSize?: number;
67
+ /** Maximum parallel operations for batch/sync (default: 4) */
68
+ concurrency?: number;
69
+ /** Cache folder paths to reduce API queries (default: true) */
70
+ enablePathCache?: boolean;
71
+ /** Cache TTL in milliseconds (default: 5 minutes) */
72
+ pathCacheTTL?: number;
73
+ /** Number of retry attempts for 429/5xx errors (default: 5) */
74
+ maxRetries?: number;
75
+ /** Base delay for exponential backoff in ms (default: 1000) */
76
+ retryBaseDelayMs?: number;
77
+ }
78
+ /**
79
+ * Upload progress event payload
80
+ */
81
+ interface UploadProgress {
82
+ /** Bytes transferred so far */
83
+ bytesSent: number;
84
+ /** Total bytes of the file */
85
+ totalBytes: number;
86
+ /** Percentage completed (0 - 100) */
87
+ percentage: number;
88
+ /** Current transfer speed in bytes per second */
89
+ bytesPerSecond: number;
90
+ /** Formatted speed (e.g. "4.2 MB/s") */
91
+ speedFormatted: string;
92
+ /** Estimated time remaining in seconds */
93
+ estimatedTimeRemainingSeconds: number;
94
+ /** Chunk index currently sent */
95
+ chunkIndex: number;
96
+ /** Total chunks */
97
+ totalChunks: number;
98
+ }
99
+ /**
100
+ * Download progress event payload
101
+ */
102
+ interface DownloadProgress {
103
+ bytesRead: number;
104
+ totalBytes?: number;
105
+ percentage?: number;
106
+ bytesPerSecond: number;
107
+ speedFormatted: string;
108
+ }
109
+ /**
110
+ * File upload parameters
111
+ */
112
+ interface UploadOptions {
113
+ /** Local file path, Buffer, or Readable stream */
114
+ source: string | Buffer | NodeJS.ReadableStream;
115
+ /** Target file name on Google Drive */
116
+ name?: string;
117
+ /** Target parent folder ID or virtual path (e.g. '/Backups/2026') */
118
+ parent?: string;
119
+ /** MIME type (inferred automatically if omitted) */
120
+ mimeType?: string;
121
+ /** File description */
122
+ description?: string;
123
+ /** Custom chunk size for this specific upload */
124
+ chunkSize?: number;
125
+ /** Progress callback */
126
+ onProgress?: (progress: UploadProgress) => void;
127
+ /** Whether to overwrite file with same name in destination */
128
+ overwrite?: boolean;
129
+ /** Custom properties / metadata */
130
+ properties?: Record<string, string>;
131
+ appProperties?: Record<string, string>;
132
+ }
133
+ /**
134
+ * File download parameters
135
+ */
136
+ interface DownloadOptions {
137
+ /** Destination local file path (if saving to disk) */
138
+ destination?: string;
139
+ /** Progress callback */
140
+ onProgress?: (progress: DownloadProgress) => void;
141
+ /** Export MIME type for Google Workspace documents */
142
+ exportMimeType?: string;
143
+ }
144
+ /**
145
+ * Permission role types
146
+ */
147
+ type PermissionRole = 'owner' | 'organizer' | 'fileOrganizer' | 'writer' | 'commenter' | 'reader';
148
+ /**
149
+ * Permission grantee types
150
+ */
151
+ type PermissionType = 'user' | 'group' | 'domain' | 'anyone';
152
+ /**
153
+ * Share file options
154
+ */
155
+ interface ShareOptions {
156
+ role?: PermissionRole;
157
+ type?: PermissionType;
158
+ emailAddress?: string;
159
+ domain?: string;
160
+ sendNotificationEmail?: boolean;
161
+ emailMessage?: string;
162
+ transferOwnership?: boolean;
163
+ }
164
+ /**
165
+ * Directory sync summary
166
+ */
167
+ interface SyncResult {
168
+ uploaded: {
169
+ localPath: string;
170
+ fileId: string;
171
+ name: string;
172
+ }[];
173
+ skipped: {
174
+ localPath: string;
175
+ name: string;
176
+ reason: string;
177
+ }[];
178
+ failed: {
179
+ localPath: string;
180
+ error: Error;
181
+ }[];
182
+ totalBytes: number;
183
+ durationMs: number;
184
+ }
185
+
186
+ declare class DriveQueryBuilder {
187
+ private drive;
188
+ private conditions;
189
+ private orderClauses;
190
+ private limitNumber;
191
+ private requestedFields;
192
+ private spaces;
193
+ constructor(drive: drive_v3.Drive);
194
+ /**
195
+ * Escape single quotes and backslashes for Google Drive search queries
196
+ */
197
+ private escape;
198
+ /**
199
+ * Filter: Exact file name match
200
+ */
201
+ nameEquals(name: string): this;
202
+ /**
203
+ * Filter: File name contains substring
204
+ */
205
+ nameContains(substring: string): this;
206
+ /**
207
+ * Filter: Specific MIME type
208
+ */
209
+ mimeType(mime: string): this;
210
+ /**
211
+ * Filter: Only folders
212
+ */
213
+ isFolder(): this;
214
+ /**
215
+ * Filter: Exclude folders (only files)
216
+ */
217
+ isFile(): this;
218
+ /**
219
+ * Filter: Direct parent folder ID
220
+ */
221
+ inFolder(folderId: string): this;
222
+ /**
223
+ * Filter: Items not in trash (default recommended)
224
+ */
225
+ notTrashed(): this;
226
+ /**
227
+ * Filter: Only trashed items
228
+ */
229
+ onlyTrashed(): this;
230
+ /**
231
+ * Filter: Starred items
232
+ */
233
+ starred(isStarred?: boolean): this;
234
+ /**
235
+ * Filter: Shared with current user
236
+ */
237
+ sharedWithMe(): this;
238
+ /**
239
+ * Filter: Modified after timestamp or Date
240
+ */
241
+ modifiedAfter(date: Date | string): this;
242
+ /**
243
+ * Filter: Modified before timestamp or Date
244
+ */
245
+ modifiedBefore(date: Date | string): this;
246
+ /**
247
+ * Filter: Full-text search across content and name
248
+ */
249
+ fullText(term: string): this;
250
+ /**
251
+ * Custom raw query condition
252
+ */
253
+ raw(condition: string): this;
254
+ /**
255
+ * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
256
+ */
257
+ orderBy(order: string): this;
258
+ /**
259
+ * Maximum items to retrieve per page or query
260
+ */
261
+ pageSize(size: number): this;
262
+ /**
263
+ * Custom fields to return from Drive API
264
+ */
265
+ fields(fieldsString: string): this;
266
+ /**
267
+ * Compiles the full query string
268
+ */
269
+ toQueryString(): string;
270
+ /**
271
+ * Executes query and returns array of matching files
272
+ */
273
+ list(): Promise<DriveApiFile[]>;
274
+ /**
275
+ * Returns the first matching file, or null if not found
276
+ */
277
+ first(): Promise<DriveApiFile | null>;
278
+ /**
279
+ * Counts matching items (up to 1000)
280
+ */
281
+ count(): Promise<number>;
282
+ /**
283
+ * Async iterator to stream all pages automatically without loading all into memory
284
+ */
285
+ [Symbol.asyncIterator](): AsyncIterableIterator<DriveApiFile>;
286
+ }
287
+
288
+ interface WatcherOptions {
289
+ /** Polling interval in milliseconds (default: 5000) */
290
+ intervalMs?: number;
291
+ /** Restrict changes to a specific folder ID or path */
292
+ folderId?: string;
293
+ /** Whether to emit initial existing files on startup (default: false) */
294
+ emitInitial?: boolean;
295
+ }
296
+ interface FileChangeEvent {
297
+ type: 'create' | 'modify' | 'delete';
298
+ fileId: string;
299
+ file?: DriveApiFile;
300
+ removed?: boolean;
301
+ time: Date;
302
+ }
303
+ /**
304
+ * Real-time Google Drive Change Watcher
305
+ * Listens for new files, updates, and deletions using the Google Drive Changes API.
306
+ */
307
+ declare class DriveWatcher extends EventEmitter {
308
+ private drive;
309
+ private options;
310
+ private timer;
311
+ private isRunning;
312
+ private pageToken;
313
+ constructor(drive: drive_v3.Drive, options?: WatcherOptions);
314
+ /**
315
+ * Starts listening for changes
316
+ */
317
+ start(): Promise<this>;
318
+ /**
319
+ * Stops listening
320
+ */
321
+ stop(): void;
322
+ /**
323
+ * Internal polling cycle
324
+ */
325
+ private poll;
326
+ }
327
+
328
+ interface DuplicateGroup {
329
+ name: string;
330
+ count: number;
331
+ totalSize: number;
332
+ formattedTotalSize: string;
333
+ files: {
334
+ id: string;
335
+ name: string;
336
+ size: number;
337
+ modifiedTime: string;
338
+ md5Checksum?: string;
339
+ }[];
340
+ }
341
+ declare class StorageCleaner {
342
+ private drive;
343
+ constructor(drive: drive_v3.Drive);
344
+ /**
345
+ * Finds the largest files occupying space in the Google Drive account
346
+ */
347
+ findLargestFiles(limit?: number): Promise<{
348
+ id: string;
349
+ name: string;
350
+ size: number;
351
+ formattedSize: string;
352
+ mimeType: string;
353
+ modifiedTime?: string;
354
+ webViewLink?: string;
355
+ }[]>;
356
+ /**
357
+ * Scans Google Drive and detects duplicate files (by MD5 hash or exact name)
358
+ */
359
+ findDuplicates(options?: {
360
+ by?: 'md5' | 'name';
361
+ maxScan?: number;
362
+ }): Promise<DuplicateGroup[]>;
363
+ /**
364
+ * Empties the entire trash in Google Drive
365
+ */
366
+ emptyTrash(): Promise<void>;
367
+ }
368
+
369
+ /**
370
+ * Calculates MD5 checksum of a local file via streams (low memory)
371
+ */
372
+ declare function calculateFileMd5(filePath: string): Promise<string>;
373
+ interface PullResult {
374
+ downloaded: {
375
+ remoteId: string;
376
+ remoteName: string;
377
+ localPath: string;
378
+ size: number;
379
+ }[];
380
+ skipped: {
381
+ remoteId: string;
382
+ remoteName: string;
383
+ reason: string;
384
+ }[];
385
+ failed: {
386
+ remoteId: string;
387
+ remoteName: string;
388
+ error: Error;
389
+ }[];
390
+ totalBytes: number;
391
+ durationMs: number;
392
+ }
393
+ declare class SmartSyncEngine {
394
+ private drive;
395
+ private downloader;
396
+ constructor(drive: drive_v3.Drive);
397
+ /**
398
+ * Pulls (downloads) an entire Google Drive folder tree to a local directory
399
+ */
400
+ pullFolder(remoteFolderId: string, localDestinationDir: string, options?: {
401
+ concurrency?: number;
402
+ overwrite?: boolean;
403
+ onFileStart?: (remoteName: string, relativePath: string) => void;
404
+ onFileComplete?: (remoteName: string, localPath: string) => void;
405
+ }): Promise<PullResult>;
406
+ }
407
+
408
+ declare class DriveKit {
409
+ private options;
410
+ private authenticator;
411
+ private driveClient;
412
+ private pathResolverInstance;
413
+ private uploaderInstance;
414
+ private downloaderInstance;
415
+ private rootFolderId;
416
+ constructor(options?: DriveKitOptions);
417
+ /**
418
+ * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
419
+ */
420
+ init(): Promise<this>;
421
+ /**
422
+ * Access the underlying official `@googleapis/drive` instance for raw API calls
423
+ */
424
+ getRawClient(): Promise<drive_v3.Drive>;
425
+ private getResolver;
426
+ private getUploader;
427
+ private getDownloader;
428
+ /**
429
+ * Resolves a target string that could be either an ID or a virtual path (starting with '/')
430
+ */
431
+ private resolveId;
432
+ /**
433
+ * Creates a folder structure recursively, similar to `mkdir -p`.
434
+ * @param virtualPath Path like "/Documents/Projects/2026"
435
+ * @returns Folder ID of the created or existing directory
436
+ */
437
+ mkdirp(virtualPath: string): Promise<string>;
438
+ /**
439
+ * Resolves a virtual path to its Drive metadata
440
+ */
441
+ resolvePath(virtualPath: string): Promise<{
442
+ id: string;
443
+ name: string;
444
+ isFolder: boolean;
445
+ mimeType: string;
446
+ }>;
447
+ /**
448
+ * Check if a file or folder exists (by ID or virtual path)
449
+ */
450
+ exists(idOrPath: string): Promise<boolean>;
451
+ /**
452
+ * Lists contents of a folder (by folder ID or path)
453
+ */
454
+ ls(folderIdOrPath?: string): Promise<DriveApiFile[]>;
455
+ /**
456
+ * Powerful upload method:
457
+ * - Supports local paths, Buffers, or Streams
458
+ * - Automatically uses high-speed resumable chunked upload for large files
459
+ * - Parent can be a folder ID OR a virtual path (e.g. '/Backups/2026')
460
+ * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
461
+ */
462
+ upload(options: UploadOptions): Promise<DriveApiFile>;
463
+ /**
464
+ * Downloads a file from Google Drive:
465
+ * - Automatic conversion for Google Docs, Sheets, and Slides
466
+ * - Progress events
467
+ * - Saves directly to file or returns Readable Stream
468
+ */
469
+ download(fileIdOrPath: string, options?: DownloadOptions): Promise<{
470
+ filePath?: string;
471
+ stream?: NodeJS.ReadableStream;
472
+ name: string;
473
+ mimeType: string;
474
+ size?: number;
475
+ }>;
476
+ /**
477
+ * Gets file metadata
478
+ */
479
+ getFile(fileIdOrPath: string): Promise<DriveApiFile>;
480
+ /**
481
+ * Reads file content as UTF-8 string
482
+ */
483
+ getText(fileIdOrPath: string): Promise<string>;
484
+ /**
485
+ * Reads file content and parses as JSON
486
+ */
487
+ getJson<T = any>(fileIdOrPath: string): Promise<T>;
488
+ /**
489
+ * Deletes a file or moves it to trash
490
+ */
491
+ delete(fileIdOrPath: string, permanent?: boolean): Promise<void>;
492
+ /**
493
+ * Move item to trash
494
+ */
495
+ trash(fileIdOrPath: string): Promise<void>;
496
+ /**
497
+ * Restore item from trash
498
+ */
499
+ restore(fileId: string): Promise<void>;
500
+ /**
501
+ * Move file to a different folder
502
+ */
503
+ move(fileIdOrPath: string, newParentIdOrPath: string): Promise<DriveApiFile>;
504
+ /**
505
+ * Copies a file
506
+ */
507
+ copy(fileIdOrPath: string, options?: {
508
+ name?: string;
509
+ parent?: string;
510
+ }): Promise<DriveApiFile>;
511
+ /**
512
+ * Renames a file
513
+ */
514
+ rename(fileIdOrPath: string, newName: string): Promise<DriveApiFile>;
515
+ /**
516
+ * Share file with user, group, domain, or anyone
517
+ */
518
+ share(fileIdOrPath: string, options?: ShareOptions): Promise<DriveApiPermission>;
519
+ /**
520
+ * Quickly make a file public to anyone with the link
521
+ */
522
+ sharePublic(fileIdOrPath: string, role?: 'reader' | 'commenter' | 'writer'): Promise<{
523
+ fileId: string;
524
+ previewLink: string;
525
+ directDownloadLink: string;
526
+ }>;
527
+ /**
528
+ * Returns sharing links for a file
529
+ */
530
+ getShareableLink(fileIdOrPath: string): Promise<{
531
+ previewLink: string;
532
+ directDownloadLink: string;
533
+ }>;
534
+ /**
535
+ * Returns a fluent search query builder
536
+ */
537
+ query(): DriveQueryBuilder;
538
+ /**
539
+ * Recursively uploads a local folder to a Google Drive path with high concurrency
540
+ */
541
+ syncFolder(localDir: string, remotePathOrId: string, options?: {
542
+ concurrency?: number;
543
+ overwrite?: boolean;
544
+ onFileStart?: (filePath: string, relativePath: string) => void;
545
+ onFileComplete?: (filePath: string, fileId: string) => void;
546
+ }): Promise<SyncResult>;
547
+ /**
548
+ * Retrieves Google Drive storage quota usage and limits
549
+ */
550
+ getStorageQuota(): Promise<{
551
+ user: drive_v3.Schema$User | undefined;
552
+ limit: number | null;
553
+ usage: number;
554
+ usageInDrive: number;
555
+ usageInDriveTrash: number;
556
+ percentUsed: number | null;
557
+ formattedUsage: string;
558
+ formattedLimit: string;
559
+ }>;
560
+ /**
561
+ * Watches Google Drive or a specific folder for real-time changes, creations, and deletions
562
+ */
563
+ watch(folderIdOrPath?: string, options?: Omit<WatcherOptions, 'folderId'>): Promise<DriveWatcher>;
564
+ /**
565
+ * Finds the largest files consuming Google Drive storage
566
+ */
567
+ findLargestFiles(limit?: number): Promise<{
568
+ id: string;
569
+ name: string;
570
+ size: number;
571
+ formattedSize: string;
572
+ mimeType: string;
573
+ modifiedTime?: string;
574
+ webViewLink?: string;
575
+ }[]>;
576
+ /**
577
+ * Finds duplicate files (by MD5 hash or exact file name)
578
+ */
579
+ findDuplicates(options?: {
580
+ by?: 'md5' | 'name';
581
+ maxScan?: number;
582
+ }): Promise<DuplicateGroup[]>;
583
+ /**
584
+ * Empties the entire trash bin in Google Drive
585
+ */
586
+ emptyTrash(): Promise<void>;
587
+ /**
588
+ * Pulls (downloads) an entire remote Google Drive directory down to a local folder with MD5 deduplication
589
+ */
590
+ pull(remoteFolderIdOrPath: string, localDestinationDir: string, options?: {
591
+ concurrency?: number;
592
+ overwrite?: boolean;
593
+ onFileStart?: (remoteName: string, relativePath: string) => void;
594
+ onFileComplete?: (remoteName: string, localPath: string) => void;
595
+ }): Promise<PullResult>;
596
+ /**
597
+ * Calculates local file MD5 hash for integrity and deduplication checks
598
+ */
599
+ static calculateFileMd5(filePath: string): Promise<string>;
600
+ /**
601
+ * Interactive 1-click browser OAuth login flow
602
+ */
603
+ static loginWithBrowser(options: BrowserLoginOptions): Promise<LoginResult>;
604
+ }
605
+
606
+ /**
607
+ * Base DriveKit Error
608
+ */
609
+ declare class DriveKitError extends Error {
610
+ readonly code: string;
611
+ readonly originalError?: unknown;
612
+ constructor(message: string, code?: string, originalError?: unknown);
613
+ }
614
+ /**
615
+ * Authentication Error
616
+ */
617
+ declare class DriveAuthError extends DriveKitError {
618
+ constructor(message: string, originalError?: unknown);
619
+ }
620
+ /**
621
+ * Resource Not Found Error
622
+ */
623
+ declare class DriveNotFoundError extends DriveKitError {
624
+ readonly resourceIdOrPath: string;
625
+ constructor(resourceIdOrPath: string, message?: string);
626
+ }
627
+ /**
628
+ * Rate limit / Quota exceeded Error
629
+ */
630
+ declare class DriveRateLimitError extends DriveKitError {
631
+ readonly retryAfterSeconds?: number;
632
+ constructor(message: string, retryAfterSeconds?: number, originalError?: unknown);
633
+ }
634
+ /**
635
+ * Upload Error (chunk or resumable session failure)
636
+ */
637
+ declare class DriveUploadError extends DriveKitError {
638
+ readonly bytesUploaded?: number;
639
+ readonly totalBytes?: number;
640
+ constructor(message: string, bytesUploaded?: number, totalBytes?: number, originalError?: unknown);
641
+ }
642
+
643
+ declare const DEFAULT_SCOPES: string[];
644
+ /**
645
+ * Handles Google Drive authentication across various methods
646
+ */
647
+ declare class DriveAuthenticator {
648
+ private config;
649
+ private authClient;
650
+ constructor(config?: DriveKitAuthConfig);
651
+ /**
652
+ * Initializes and returns an authenticated Google client
653
+ */
654
+ getAuthClient(): Promise<any>;
655
+ /**
656
+ * Helper to generate OAuth2 Consent URL for user authorization
657
+ */
658
+ static generateAuthUrl(options: {
659
+ clientId: string;
660
+ clientSecret: string;
661
+ redirectUri?: string;
662
+ scopes?: string[];
663
+ }): string;
664
+ /**
665
+ * Helper to exchange authorization code for tokens
666
+ */
667
+ static exchangeCodeForTokens(options: {
668
+ clientId: string;
669
+ clientSecret: string;
670
+ code: string;
671
+ redirectUri?: string;
672
+ }): Promise<{
673
+ access_token?: string | null;
674
+ refresh_token?: string | null;
675
+ expiry_date?: number | null;
676
+ }>;
677
+ }
678
+
679
+ /**
680
+ * Resolves virtual hierarchical paths like "/Projects/2026/file.pdf" to Google Drive File/Folder IDs.
681
+ */
682
+ declare class PathResolver {
683
+ private drive;
684
+ private rootFolderId;
685
+ private cache;
686
+ private cacheTTL;
687
+ private enableCache;
688
+ constructor(drive: drive_v3.Drive, rootFolderId?: string, options?: {
689
+ enableCache?: boolean;
690
+ cacheTTL?: number;
691
+ });
692
+ /**
693
+ * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
694
+ */
695
+ normalizePath(rawPath: string): string;
696
+ /**
697
+ * Gets cache key for a path
698
+ */
699
+ private getCacheKey;
700
+ /**
701
+ * Clears the path cache
702
+ */
703
+ clearCache(): void;
704
+ /**
705
+ * Invalidate a single path from cache
706
+ */
707
+ invalidatePath(path: string): void;
708
+ /**
709
+ * Resolves a path to a Google Drive item (file or folder).
710
+ * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
711
+ */
712
+ resolve(virtualPath: string, options?: {
713
+ createIfMissing?: boolean;
714
+ }): Promise<{
715
+ id: string;
716
+ name: string;
717
+ isFolder: boolean;
718
+ mimeType: string;
719
+ }>;
720
+ /**
721
+ * Ensures that a directory structure exists (like mkdir -p).
722
+ */
723
+ mkdirp(virtualPath: string): Promise<string>;
724
+ }
725
+
726
+ /** Minimum Google Drive chunk granularity: 256 KiB */
727
+ declare const MIN_CHUNK_SIZE: number;
728
+ /** Default chunk size: 8 MiB (must be multiple of 256 KiB) */
729
+ declare const DEFAULT_CHUNK_SIZE: number;
730
+ /** Files smaller than this can use direct single-request multipart upload */
731
+ declare const MULTIPART_THRESHOLD: number;
732
+ declare class ResumableUploader {
733
+ private drive;
734
+ private defaultChunkSize;
735
+ constructor(drive: drive_v3.Drive, defaultChunkSize?: number);
736
+ /**
737
+ * Uploads a file with automatic selection of direct multipart (small files)
738
+ * or resumable chunked upload with progress events (large files).
739
+ */
740
+ upload(options: UploadOptions): Promise<DriveApiFile>;
741
+ /**
742
+ * Upload from local file path with memory-efficient chunked streaming
743
+ */
744
+ private uploadFromPath;
745
+ /**
746
+ * Upload from in-memory Buffer
747
+ */
748
+ private uploadFromBuffer;
749
+ /**
750
+ * Upload from generic Readable Stream
751
+ */
752
+ private uploadFromStream;
753
+ /**
754
+ * Fast direct upload using googleapis multipart
755
+ */
756
+ private directUpload;
757
+ /**
758
+ * Chunked resumable upload for local files with low memory footprint
759
+ */
760
+ private chunkedUpload;
761
+ /**
762
+ * Chunked resumable upload for memory buffers
763
+ */
764
+ private chunkedUploadBuffer;
765
+ /**
766
+ * Request an upload session URI from Google Drive API
767
+ */
768
+ private initiateResumableSession;
769
+ /**
770
+ * Upload a chunk with exponential backoff on network failures
771
+ */
772
+ private uploadChunkWithRetry;
773
+ }
774
+
775
+ declare class Downloader {
776
+ private drive;
777
+ constructor(drive: drive_v3.Drive);
778
+ /**
779
+ * Downloads a file from Google Drive to local destination path or returns a readable stream.
780
+ */
781
+ download(fileId: string, options?: DownloadOptions): Promise<{
782
+ filePath?: string;
783
+ stream?: NodeJS.ReadableStream;
784
+ name: string;
785
+ mimeType: string;
786
+ size?: number;
787
+ }>;
788
+ }
789
+
790
+ /**
791
+ * Lightweight asynchronous worker pool for concurrent operations
792
+ */
793
+ declare class ConcurrencyPool {
794
+ private concurrency;
795
+ private running;
796
+ private queue;
797
+ constructor(concurrency?: number);
798
+ /**
799
+ * Run a task when a slot becomes available
800
+ */
801
+ run<T>(task: () => Promise<T>): Promise<T>;
802
+ /**
803
+ * Run all tasks in parallel bounded by concurrency limit
804
+ */
805
+ all<T>(tasks: (() => Promise<T>)[]): Promise<T[]>;
806
+ /**
807
+ * Execute an array of items concurrently through an async mapper
808
+ */
809
+ map<Item, Result>(items: Item[], fn: (item: Item, index: number) => Promise<Result>): Promise<Result[]>;
810
+ }
811
+
812
+ /**
813
+ * Formats bytes to human-readable string (KB, MB, GB)
814
+ */
815
+ declare function formatBytes(bytes: number, decimals?: number): string;
816
+ /**
817
+ * Formats speed in bytes/sec to human readable format (e.g. 5.4 MB/s)
818
+ */
819
+ declare function formatSpeed(bytesPerSecond: number): string;
820
+ /**
821
+ * Formats seconds to mm:ss or hh:mm:ss
822
+ */
823
+ declare function formatDuration(seconds: number): string;
824
+
825
+ /**
826
+ * Standard Google Workspace MIME types
827
+ */
828
+ declare const GOOGLE_WORKSPACE_MIME_TYPES: {
829
+ readonly DOCUMENT: "application/vnd.google-apps.document";
830
+ readonly SPREADSHEET: "application/vnd.google-apps.spreadsheet";
831
+ readonly PRESENTATION: "application/vnd.google-apps.presentation";
832
+ readonly DRAWING: "application/vnd.google-apps.drawing";
833
+ readonly FORM: "application/vnd.google-apps.form";
834
+ readonly SCRIPT: "application/vnd.google-apps.script";
835
+ readonly FOLDER: "application/vnd.google-apps.folder";
836
+ readonly SHORTCUT: "application/vnd.google-apps.shortcut";
837
+ };
838
+ /**
839
+ * Default export MIME types for Google Docs, Sheets, Slides
840
+ */
841
+ declare const DEFAULT_EXPORT_MIMES: Record<string, {
842
+ mimeType: string;
843
+ extension: string;
844
+ }>;
845
+ /**
846
+ * Detects MIME type from file path or fallback to octet-stream
847
+ */
848
+ declare function lookupMimeType(filePath: string): string;
849
+ /**
850
+ * Returns extension for a given MIME type
851
+ */
852
+ declare function getExtensionForMime(mimeType: string): string;
853
+ /**
854
+ * Checks if a MIME type is a native Google Workspace format
855
+ */
856
+ declare function isGoogleWorkspaceDoc(mimeType?: string | null): boolean;
857
+
858
+ interface RetryOptions {
859
+ maxRetries?: number;
860
+ baseDelayMs?: number;
861
+ maxDelayMs?: number;
862
+ shouldRetry?: (error: any) => boolean;
863
+ }
864
+ /**
865
+ * Checks if an error returned by Google Drive is retryable
866
+ */
867
+ declare function isRetryableError(error: any): boolean;
868
+ /**
869
+ * Executes an async operation with exponential backoff and full jitter
870
+ */
871
+ declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T>;
872
+
873
+ /**
874
+ * Creates and initializes a DriveKit instance
875
+ *
876
+ * @example
877
+ * ```typescript
878
+ * import { createDrive } from 'drivekit';
879
+ *
880
+ * const drive = await createDrive({
881
+ * auth: { keyFilePath: './service-account.json' }
882
+ * });
883
+ *
884
+ * const file = await drive.upload({
885
+ * source: './report.pdf',
886
+ * parent: '/Backups/2026',
887
+ * onProgress: (p) => console.log(`${p.percentage}% (${p.speedFormatted})`)
888
+ * });
889
+ * ```
890
+ */
891
+ declare function createDrive(options?: DriveKitOptions): Promise<DriveKit>;
892
+
893
+ export { type BrowserLoginOptions, ConcurrencyPool, DEFAULT_CHUNK_SIZE, DEFAULT_EXPORT_MIMES, DEFAULT_SCOPES, type DownloadOptions, type DownloadProgress, Downloader, type DriveApiFile, type DriveApiFileList, type DriveApiPermission, DriveAuthError, DriveAuthenticator, DriveKit, type DriveKitAuthConfig, DriveKitError, type DriveKitOptions, DriveNotFoundError, DriveQueryBuilder, DriveRateLimitError, DriveUploadError, DriveWatcher, type DuplicateGroup, type FileChangeEvent, GOOGLE_WORKSPACE_MIME_TYPES, type LoginResult, MIN_CHUNK_SIZE, MULTIPART_THRESHOLD, PathResolver, type PermissionRole, type PermissionType, type PullResult, ResumableUploader, type RetryOptions, type ShareOptions, SmartSyncEngine, StorageCleaner, type SyncResult, type UploadOptions, type UploadProgress, type WatcherOptions, calculateFileMd5, createDrive, DriveKit as default, formatBytes, formatDuration, formatSpeed, getExtensionForMime, isGoogleWorkspaceDoc, isRetryableError, loginWithBrowser, lookupMimeType, withRetry };