drivekit 1.0.1 → 1.1.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.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,8 @@
1
+ import * as http from 'http';
1
2
  import { drive_v3 } from '@googleapis/drive';
2
3
  import { OAuth2Client } from 'google-auth-library';
3
4
  import { EventEmitter } from 'node:events';
5
+ import http$1 from 'node:http';
4
6
 
5
7
  interface BrowserLoginOptions {
6
8
  clientId: string;
@@ -70,6 +72,10 @@ interface DriveKitOptions {
70
72
  enablePathCache?: boolean;
71
73
  /** Cache TTL in milliseconds (default: 5 minutes) */
72
74
  pathCacheTTL?: number;
75
+ /** Enable persistent SQLite metadata cache for 0ms path resolution across sessions (default: true) */
76
+ enablePersistentCache?: boolean;
77
+ /** Custom path to the SQLite cache database file (default: ~/.drivekit/cache.db) */
78
+ cacheDatabasePath?: string;
73
79
  /** Number of retry attempts for 429/5xx errors (default: 5) */
74
80
  maxRetries?: number;
75
81
  /** Base delay for exponential backoff in ms (default: 1000) */
@@ -126,9 +132,15 @@ interface UploadOptions {
126
132
  onProgress?: (progress: UploadProgress) => void;
127
133
  /** Whether to overwrite file with same name in destination */
128
134
  overwrite?: boolean;
135
+ /** Whether to enable instant upload deduplication by file MD5 hash */
136
+ deduplicate?: boolean;
137
+ /** Alias for target file name */
138
+ filename?: string;
129
139
  /** Custom properties / metadata */
130
140
  properties?: Record<string, string>;
131
141
  appProperties?: Record<string, string>;
142
+ /** Optional AbortSignal for instant operation cancellation */
143
+ signal?: AbortSignal;
132
144
  }
133
145
  /**
134
146
  * File download parameters
@@ -140,6 +152,8 @@ interface DownloadOptions {
140
152
  onProgress?: (progress: DownloadProgress) => void;
141
153
  /** Export MIME type for Google Workspace documents */
142
154
  exportMimeType?: string;
155
+ /** Optional AbortSignal for instant operation cancellation */
156
+ signal?: AbortSignal;
143
157
  }
144
158
  /**
145
159
  * Permission role types
@@ -251,6 +265,14 @@ declare class DriveQueryBuilder {
251
265
  * Custom raw query condition
252
266
  */
253
267
  raw(condition: string): this;
268
+ /**
269
+ * Custom raw query condition (alias for raw)
270
+ */
271
+ custom(condition: string): this;
272
+ /**
273
+ * Filter: Exact MD5 checksum match
274
+ */
275
+ md5(checksum: string): this;
254
276
  /**
255
277
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
256
278
  */
@@ -271,6 +293,10 @@ declare class DriveQueryBuilder {
271
293
  * Executes query and returns array of matching files
272
294
  */
273
295
  list(): Promise<DriveApiFile[]>;
296
+ /**
297
+ * Executes query and returns array of matching files (alias for list)
298
+ */
299
+ execute(): Promise<DriveApiFile[]>;
274
300
  /**
275
301
  * Returns the first matching file, or null if not found
276
302
  */
@@ -405,6 +431,209 @@ declare class SmartSyncEngine {
405
431
  }): Promise<PullResult>;
406
432
  }
407
433
 
434
+ /**
435
+ * Fluent reference to a specific file in Google Drive
436
+ */
437
+ declare class DriveFileRef {
438
+ private drive;
439
+ readonly pathOrId: string;
440
+ constructor(drive: DriveKit, pathOrId: string);
441
+ /** Gets file metadata */
442
+ get(): Promise<DriveApiFile>;
443
+ /** Checks if the file exists */
444
+ exists(): Promise<boolean>;
445
+ /** Reads file as UTF-8 string */
446
+ getText(): Promise<string>;
447
+ /** Reads and parses JSON file */
448
+ getJson<T = any>(): Promise<T>;
449
+ /** Downloads the file to destination */
450
+ download(optionsOrDestination?: string | DownloadOptions): Promise<any>;
451
+ /** Moves the file to a new folder path or ID */
452
+ moveTo(newParentPathOrId: string): Promise<DriveApiFile>;
453
+ /** Copies the file to a target directory */
454
+ copyTo(parentPathOrId?: string, newName?: string): Promise<DriveApiFile>;
455
+ /** Renames the file */
456
+ rename(newName: string): Promise<DriveApiFile>;
457
+ /** Deletes the file (or moves to trash if permanent is false) */
458
+ delete(permanent?: boolean): Promise<void>;
459
+ /** Moves file to trash */
460
+ trash(): Promise<void>;
461
+ /** Shares file */
462
+ share(options: ShareOptions): Promise<DriveApiPermission>;
463
+ /** Makes file publicly accessible */
464
+ sharePublic(role?: 'reader' | 'commenter' | 'writer'): Promise<{
465
+ fileId: string;
466
+ previewLink: string;
467
+ directDownloadLink: string;
468
+ }>;
469
+ /** Gets public/preview links */
470
+ getLink(): Promise<{
471
+ previewLink: string;
472
+ directDownloadLink: string;
473
+ }>;
474
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
475
+ createReadStream(options?: {
476
+ start?: number;
477
+ end?: number;
478
+ }): Promise<NodeJS.ReadableStream>;
479
+ /** Grants access to a specific email with custom role and notification */
480
+ grantAccess(options: {
481
+ email: string;
482
+ role?: 'reader' | 'commenter' | 'writer';
483
+ notify?: boolean;
484
+ message?: string;
485
+ }): Promise<DriveApiPermission>;
486
+ /** Revokes access by permission ID or user email */
487
+ revokeAccess(permissionIdOrEmail: string): Promise<void>;
488
+ /** Lists all granted permissions on this file */
489
+ listPermissions(): Promise<DriveApiPermission[]>;
490
+ }
491
+ /**
492
+ * Fluent reference to a specific folder in Google Drive
493
+ */
494
+ declare class DriveFolderRef {
495
+ private drive;
496
+ readonly pathOrId: string;
497
+ constructor(drive: DriveKit, pathOrId: string);
498
+ /** Lists contents of this folder */
499
+ ls(): Promise<DriveApiFile[]>;
500
+ /** Ensures this folder and subpaths exist (mkdir -p) */
501
+ mkdirp(subPath?: string): Promise<string>;
502
+ /** Uploads a file directly into this folder */
503
+ upload(source: UploadOptions['source'], options?: Omit<UploadOptions, 'source' | 'parent'>): Promise<DriveApiFile>;
504
+ /** Synchronizes a local directory into this remote folder */
505
+ syncFrom(localDir: string, options?: Parameters<DriveKit['syncFolder']>[2]): Promise<SyncResult>;
506
+ /** Pulls this remote folder down to local directory */
507
+ pullTo(localDestinationDir: string, options?: Parameters<DriveKit['pull']>[2]): Promise<PullResult>;
508
+ /** Watches this folder for real-time changes */
509
+ watch(options?: Omit<WatcherOptions, 'folderId'>): Promise<DriveWatcher>;
510
+ /** Grants access to this entire folder */
511
+ grantAccess(options: {
512
+ email: string;
513
+ role?: 'reader' | 'commenter' | 'writer';
514
+ notify?: boolean;
515
+ message?: string;
516
+ }): Promise<DriveApiPermission>;
517
+ /** Creates a writable stream directly into a file inside this folder */
518
+ createWriteStream(fileName: string, options?: Omit<UploadOptions, 'source' | 'filename' | 'parent'>): Promise<NodeJS.WritableStream>;
519
+ }
520
+
521
+ interface DriveKitPlugin {
522
+ name: string;
523
+ beforeUpload?: (options: UploadOptions) => Promise<UploadOptions | void> | UploadOptions | void;
524
+ afterUpload?: (file: DriveApiFile) => Promise<DriveApiFile | void> | DriveApiFile | void;
525
+ beforeDownload?: (fileId: string, options: DownloadOptions) => Promise<DownloadOptions | void> | DownloadOptions | void;
526
+ afterDownload?: (result: any) => Promise<any | void> | any | void;
527
+ }
528
+ declare class PluginManager {
529
+ private plugins;
530
+ use(plugin: DriveKitPlugin): this;
531
+ runBeforeUpload(options: UploadOptions): Promise<UploadOptions>;
532
+ runAfterUpload(file: DriveApiFile): Promise<DriveApiFile>;
533
+ runBeforeDownload(fileId: string, options: DownloadOptions): Promise<DownloadOptions>;
534
+ runAfterDownload(result: any): Promise<any>;
535
+ }
536
+ /**
537
+ * Creates an official Webhook Plugin to notify external services (Slack, Discord, Telegram, Zapier)
538
+ * when uploads or downloads finish.
539
+ */
540
+ declare function createWebhookPlugin(options: {
541
+ url: string;
542
+ headers?: Record<string, string>;
543
+ events?: ('upload' | 'download')[];
544
+ }): DriveKitPlugin;
545
+ /**
546
+ * Creates an Auto-Namer Plugin to automatically prefix/suffix or timestamp files
547
+ */
548
+ declare function createAutoNamePlugin(options: {
549
+ prefix?: string;
550
+ suffix?: string;
551
+ appendTimestamp?: boolean;
552
+ }): DriveKitPlugin;
553
+
554
+ interface CacheFileEntry {
555
+ id: string;
556
+ name: string;
557
+ mimeType: string;
558
+ size?: number;
559
+ parentId?: string;
560
+ path?: string;
561
+ md5Checksum?: string;
562
+ trashed: boolean;
563
+ modifiedTime?: string;
564
+ updatedAt?: number;
565
+ }
566
+ interface CacheStats {
567
+ fileCount: number;
568
+ folderCount: number;
569
+ totalSizeBytes: number;
570
+ lastSyncTime: string | null;
571
+ databasePath: string;
572
+ }
573
+ interface IMetadataCache {
574
+ init(): void;
575
+ getById(id: string): CacheFileEntry | null;
576
+ getByPath(normalizedPath: string): CacheFileEntry | null;
577
+ getChildren(parentId: string): CacheFileEntry[];
578
+ findByMd5(md5: string): CacheFileEntry | null;
579
+ searchByName(query: string): CacheFileEntry[];
580
+ upsertFile(entry: CacheFileEntry): void;
581
+ upsertFiles(entries: CacheFileEntry[]): void;
582
+ deleteFile(id: string): void;
583
+ clear(): void;
584
+ getMeta(key: string): string | null;
585
+ setMeta(key: string, value: string): void;
586
+ getStats(): CacheStats;
587
+ close(): void;
588
+ }
589
+ /**
590
+ * High-performance SQLite-backed persistent cache for DriveKit metadata.
591
+ * Uses Node 22's built-in `node:sqlite` (DatabaseSync).
592
+ */
593
+ declare class SqliteMetadataCache implements IMetadataCache {
594
+ private db;
595
+ private dbPath;
596
+ private initialized;
597
+ private fallbackMemory?;
598
+ constructor(customPath?: string);
599
+ init(): void;
600
+ getById(id: string): CacheFileEntry | null;
601
+ getByPath(normalizedPath: string): CacheFileEntry | null;
602
+ getChildren(parentId: string): CacheFileEntry[];
603
+ findByMd5(md5: string): CacheFileEntry | null;
604
+ searchByName(query: string): CacheFileEntry[];
605
+ upsertFile(entry: CacheFileEntry): void;
606
+ upsertFiles(entries: CacheFileEntry[]): void;
607
+ deleteFile(id: string): void;
608
+ clear(): void;
609
+ getMeta(key: string): string | null;
610
+ setMeta(key: string, value: string): void;
611
+ getStats(): CacheStats;
612
+ close(): void;
613
+ private mapRow;
614
+ }
615
+ /**
616
+ * Fallback in-memory cache if SQLite is unavailable
617
+ */
618
+ declare class MemoryMetadataCache implements IMetadataCache {
619
+ private files;
620
+ private meta;
621
+ init(): void;
622
+ getById(id: string): CacheFileEntry | null;
623
+ getByPath(normalizedPath: string): CacheFileEntry | null;
624
+ getChildren(parentId: string): CacheFileEntry[];
625
+ findByMd5(md5: string): CacheFileEntry | null;
626
+ searchByName(query: string): CacheFileEntry[];
627
+ upsertFile(entry: CacheFileEntry): void;
628
+ upsertFiles(entries: CacheFileEntry[]): void;
629
+ deleteFile(id: string): void;
630
+ clear(): void;
631
+ getMeta(key: string): string | null;
632
+ setMeta(key: string, value: string): void;
633
+ getStats(): CacheStats;
634
+ close(): void;
635
+ }
636
+
408
637
  declare class DriveKit {
409
638
  private options;
410
639
  private authenticator;
@@ -412,8 +641,22 @@ declare class DriveKit {
412
641
  private pathResolverInstance;
413
642
  private uploaderInstance;
414
643
  private downloaderInstance;
644
+ private metadataCacheInstance;
415
645
  private rootFolderId;
646
+ private pluginManager;
416
647
  constructor(options?: DriveKitOptions);
648
+ /**
649
+ * Registers a middleware plugin into DriveKit lifecycle
650
+ */
651
+ use(plugin: DriveKitPlugin): this;
652
+ /**
653
+ * Returns a fluent, chained reference to a specific file
654
+ */
655
+ file(pathOrId: string): DriveFileRef;
656
+ /**
657
+ * Returns a fluent, chained reference to a specific folder
658
+ */
659
+ folder(pathOrId: string): DriveFolderRef;
417
660
  /**
418
661
  * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
419
662
  */
@@ -466,13 +709,7 @@ declare class DriveKit {
466
709
  * - Progress events
467
710
  * - Saves directly to file or returns Readable Stream
468
711
  */
469
- download(fileIdOrPath: string, options?: DownloadOptions): Promise<{
470
- filePath?: string;
471
- stream?: NodeJS.ReadableStream;
472
- name: string;
473
- mimeType: string;
474
- size?: number;
475
- }>;
712
+ download(fileIdOrPath: string, options?: DownloadOptions): Promise<any>;
476
713
  /**
477
714
  * Gets file metadata
478
715
  */
@@ -593,6 +830,76 @@ declare class DriveKit {
593
830
  onFileStart?: (remoteName: string, relativePath: string) => void;
594
831
  onFileComplete?: (remoteName: string, localPath: string) => void;
595
832
  }): Promise<PullResult>;
833
+ /**
834
+ * Creates a readable stream for a file, supporting partial range requests
835
+ */
836
+ createReadStream(pathOrId: string, options?: {
837
+ start?: number;
838
+ end?: number;
839
+ }): Promise<NodeJS.ReadableStream>;
840
+ /**
841
+ * Creates a writable stream directly into Google Drive
842
+ */
843
+ createWriteStream(remotePath: string, options?: Omit<UploadOptions, 'source'>): Promise<NodeJS.WritableStream>;
844
+ /**
845
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
846
+ */
847
+ getMetadataCache(): Promise<IMetadataCache | null>;
848
+ /**
849
+ * Returns cache statistics (total files, folders, size, last sync)
850
+ */
851
+ getCacheStats(): Promise<CacheStats | null>;
852
+ /**
853
+ * Clears the path and metadata cache
854
+ */
855
+ clearCache(): Promise<void>;
856
+ /**
857
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
858
+ */
859
+ syncCache(options?: {
860
+ onProgress?: (scanned: number) => void;
861
+ }): Promise<CacheStats>;
862
+ /**
863
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
864
+ */
865
+ listSharedDrives(options?: {
866
+ pageSize?: number;
867
+ }): Promise<{
868
+ id: string;
869
+ name: string;
870
+ }[]>;
871
+ /**
872
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
873
+ */
874
+ sharedDrive(driveId: string): DriveKit;
875
+ /**
876
+ * Grants access to a specific email with custom role and notification
877
+ */
878
+ grantAccess(pathOrId: string, options: {
879
+ email: string;
880
+ role?: 'reader' | 'commenter' | 'writer';
881
+ notify?: boolean;
882
+ message?: string;
883
+ }): Promise<DriveApiPermission>;
884
+ /**
885
+ * Revokes access for a specific permission ID or email address
886
+ */
887
+ revokeAccess(pathOrId: string, permissionIdOrEmail: string): Promise<void>;
888
+ /**
889
+ * Lists all active permissions on a file or folder
890
+ */
891
+ listPermissions(pathOrId: string): Promise<DriveApiPermission[]>;
892
+ /**
893
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
894
+ */
895
+ serveWebDAV(options?: {
896
+ port?: number;
897
+ host?: string;
898
+ }): Promise<{
899
+ server: http.Server;
900
+ url: string;
901
+ close: () => Promise<void>;
902
+ }>;
596
903
  /**
597
904
  * Calculates local file MD5 hash for integrity and deduplication checks
598
905
  */
@@ -685,9 +992,11 @@ declare class PathResolver {
685
992
  private cache;
686
993
  private cacheTTL;
687
994
  private enableCache;
995
+ private metadataCache?;
688
996
  constructor(drive: drive_v3.Drive, rootFolderId?: string, options?: {
689
997
  enableCache?: boolean;
690
998
  cacheTTL?: number;
999
+ metadataCache?: IMetadataCache;
691
1000
  });
692
1001
  /**
693
1002
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -785,6 +1094,13 @@ declare class Downloader {
785
1094
  mimeType: string;
786
1095
  size?: number;
787
1096
  }>;
1097
+ /**
1098
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1099
+ */
1100
+ createReadStream(fileId: string, options?: {
1101
+ start?: number;
1102
+ end?: number;
1103
+ }): Promise<NodeJS.ReadableStream>;
788
1104
  }
789
1105
 
790
1106
  /**
@@ -809,6 +1125,34 @@ declare class ConcurrencyPool {
809
1125
  map<Item, Result>(items: Item[], fn: (item: Item, index: number) => Promise<Result>): Promise<Result[]>;
810
1126
  }
811
1127
 
1128
+ interface WebDAVServerOptions {
1129
+ port?: number;
1130
+ host?: string;
1131
+ }
1132
+ /**
1133
+ * Creates and starts a lightweight zero-dependency WebDAV server for DriveKit.
1134
+ * Allows mounting Google Drive directly in macOS Finder, Windows Explorer, or Linux.
1135
+ */
1136
+ declare function startWebDAVServer(drive: DriveKit, options?: WebDAVServerOptions): Promise<{
1137
+ server: http$1.Server;
1138
+ url: string;
1139
+ close: () => Promise<void>;
1140
+ }>;
1141
+
1142
+ /**
1143
+ * Creates an OSC 8 clickable hyperlink in supported modern terminals (macOS Terminal, iTerm2, VS Code, etc.)
1144
+ */
1145
+ declare function terminalLink(text: string, url: string): string;
1146
+ /**
1147
+ * Renders a visually stunning, colored file table with clickable links
1148
+ */
1149
+ declare function renderFileRow(item: DriveApiFile, index?: number): string;
1150
+ declare function getFileIcon(mimeType: string): string;
1151
+ /**
1152
+ * Interactive Keyboard-driven Google Drive File Explorer (TUI)
1153
+ */
1154
+ declare function runInteractiveExplorer(client: DriveKit, initialFolder?: string): Promise<void>;
1155
+
812
1156
  /**
813
1157
  * Formats bytes to human-readable string (KB, MB, GB)
814
1158
  */
@@ -890,4 +1234,4 @@ declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Pro
890
1234
  */
891
1235
  declare function createDrive(options?: DriveKitOptions): Promise<DriveKit>;
892
1236
 
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 };
1237
+ export { type BrowserLoginOptions, type CacheFileEntry, type CacheStats, ConcurrencyPool, DEFAULT_CHUNK_SIZE, DEFAULT_EXPORT_MIMES, DEFAULT_SCOPES, type DownloadOptions, type DownloadProgress, Downloader, type DriveApiFile, type DriveApiFileList, type DriveApiPermission, DriveAuthError, DriveAuthenticator, DriveFileRef, DriveFolderRef, DriveKit, type DriveKitAuthConfig, DriveKitError, type DriveKitOptions, type DriveKitPlugin, DriveNotFoundError, DriveQueryBuilder, DriveRateLimitError, DriveUploadError, DriveWatcher, type DuplicateGroup, type FileChangeEvent, GOOGLE_WORKSPACE_MIME_TYPES, type IMetadataCache, type LoginResult, MIN_CHUNK_SIZE, MULTIPART_THRESHOLD, MemoryMetadataCache, PathResolver, type PermissionRole, type PermissionType, PluginManager, type PullResult, ResumableUploader, type RetryOptions, type ShareOptions, SmartSyncEngine, SqliteMetadataCache, StorageCleaner, type SyncResult, type UploadOptions, type UploadProgress, type WatcherOptions, type WebDAVServerOptions, calculateFileMd5, createAutoNamePlugin, createDrive, createWebhookPlugin, DriveKit as default, formatBytes, formatDuration, formatSpeed, getExtensionForMime, getFileIcon, isGoogleWorkspaceDoc, isRetryableError, loginWithBrowser, lookupMimeType, renderFileRow, runInteractiveExplorer, startWebDAVServer, terminalLink, withRetry };