drivekit 1.0.2 → 1.1.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/dist/index.d.cts 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,6 +132,10 @@ 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>;
@@ -145,6 +155,20 @@ interface DownloadOptions {
145
155
  /** Optional AbortSignal for instant operation cancellation */
146
156
  signal?: AbortSignal;
147
157
  }
158
+ /**
159
+ * Writable stream for direct uploads into Google Drive with completion promise
160
+ */
161
+ interface DriveWriteStream extends NodeJS.WritableStream {
162
+ /** Resolves with the uploaded file metadata upon completion, or rejects on upload failure */
163
+ done: Promise<DriveApiFile>;
164
+ }
165
+ /**
166
+ * Writable stream for direct uploads into Google Drive with completion promise
167
+ */
168
+ interface DriveWriteStream extends NodeJS.WritableStream {
169
+ /** Resolves with the uploaded file metadata upon completion, or rejects on upload failure */
170
+ done: Promise<DriveApiFile>;
171
+ }
148
172
  /**
149
173
  * Permission role types
150
174
  */
@@ -255,6 +279,14 @@ declare class DriveQueryBuilder {
255
279
  * Custom raw query condition
256
280
  */
257
281
  raw(condition: string): this;
282
+ /**
283
+ * Custom raw query condition (alias for raw)
284
+ */
285
+ custom(condition: string): this;
286
+ /**
287
+ * Filter: Exact MD5 checksum match
288
+ */
289
+ md5(checksum: string): this;
258
290
  /**
259
291
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
260
292
  */
@@ -275,6 +307,10 @@ declare class DriveQueryBuilder {
275
307
  * Executes query and returns array of matching files
276
308
  */
277
309
  list(): Promise<DriveApiFile[]>;
310
+ /**
311
+ * Executes query and returns array of matching files (alias for list)
312
+ */
313
+ execute(): Promise<DriveApiFile[]>;
278
314
  /**
279
315
  * Returns the first matching file, or null if not found
280
316
  */
@@ -449,6 +485,22 @@ declare class DriveFileRef {
449
485
  previewLink: string;
450
486
  directDownloadLink: string;
451
487
  }>;
488
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
489
+ createReadStream(options?: {
490
+ start?: number;
491
+ end?: number;
492
+ }): Promise<NodeJS.ReadableStream>;
493
+ /** Grants access to a specific email with custom role and notification */
494
+ grantAccess(options: {
495
+ email: string;
496
+ role?: 'reader' | 'commenter' | 'writer';
497
+ notify?: boolean;
498
+ message?: string;
499
+ }): Promise<DriveApiPermission>;
500
+ /** Revokes access by permission ID or user email */
501
+ revokeAccess(permissionIdOrEmail: string): Promise<void>;
502
+ /** Lists all granted permissions on this file */
503
+ listPermissions(): Promise<DriveApiPermission[]>;
452
504
  }
453
505
  /**
454
506
  * Fluent reference to a specific folder in Google Drive
@@ -469,6 +521,15 @@ declare class DriveFolderRef {
469
521
  pullTo(localDestinationDir: string, options?: Parameters<DriveKit['pull']>[2]): Promise<PullResult>;
470
522
  /** Watches this folder for real-time changes */
471
523
  watch(options?: Omit<WatcherOptions, 'folderId'>): Promise<DriveWatcher>;
524
+ /** Grants access to this entire folder */
525
+ grantAccess(options: {
526
+ email: string;
527
+ role?: 'reader' | 'commenter' | 'writer';
528
+ notify?: boolean;
529
+ message?: string;
530
+ }): Promise<DriveApiPermission>;
531
+ /** Creates a writable stream directly into a file inside this folder */
532
+ createWriteStream(fileName: string, options?: Omit<UploadOptions, 'source' | 'filename' | 'parent'>): Promise<NodeJS.WritableStream>;
472
533
  }
473
534
 
474
535
  interface DriveKitPlugin {
@@ -480,12 +541,136 @@ interface DriveKitPlugin {
480
541
  }
481
542
  declare class PluginManager {
482
543
  private plugins;
544
+ /**
545
+ * Register a plugin. If a plugin with the same name already exists,
546
+ * it replaces the old one to avoid duplicate side-effects.
547
+ */
483
548
  use(plugin: DriveKitPlugin): this;
549
+ /**
550
+ * Unregister a plugin by its name.
551
+ * Returns true if a plugin was found and removed, false otherwise.
552
+ */
553
+ unuse(pluginName: string): boolean;
554
+ /**
555
+ * Check if a plugin with given name is currently active
556
+ */
557
+ has(pluginName: string): boolean;
558
+ /**
559
+ * Returns all currently registered plugins
560
+ */
561
+ getPlugins(): readonly DriveKitPlugin[];
484
562
  runBeforeUpload(options: UploadOptions): Promise<UploadOptions>;
485
563
  runAfterUpload(file: DriveApiFile): Promise<DriveApiFile>;
486
564
  runBeforeDownload(fileId: string, options: DownloadOptions): Promise<DownloadOptions>;
487
565
  runAfterDownload(result: any): Promise<any>;
488
566
  }
567
+ interface WebhookPluginOptions {
568
+ url: string;
569
+ headers?: Record<string, string>;
570
+ events?: ('upload' | 'download')[];
571
+ timeout?: number;
572
+ retries?: number;
573
+ onError?: (err: Error, event: 'upload' | 'download') => void;
574
+ }
575
+ /**
576
+ * Creates an official Webhook Plugin to notify external services (Slack, Discord, Telegram, Zapier)
577
+ * when uploads or downloads finish. Includes configurable timeout, retry mechanism, and error callback.
578
+ */
579
+ declare function createWebhookPlugin(options: WebhookPluginOptions): DriveKitPlugin;
580
+ /**
581
+ * Creates an Auto-Namer Plugin to automatically prefix/suffix or timestamp files
582
+ */
583
+ declare function createAutoNamePlugin(options: {
584
+ prefix?: string;
585
+ suffix?: string;
586
+ appendTimestamp?: boolean;
587
+ }): DriveKitPlugin;
588
+
589
+ interface CacheFileEntry {
590
+ id: string;
591
+ name: string;
592
+ mimeType: string;
593
+ size?: number;
594
+ parentId?: string;
595
+ path?: string;
596
+ md5Checksum?: string;
597
+ trashed: boolean;
598
+ modifiedTime?: string;
599
+ updatedAt?: number;
600
+ }
601
+ interface CacheStats {
602
+ fileCount: number;
603
+ folderCount: number;
604
+ totalSizeBytes: number;
605
+ lastSyncTime: string | null;
606
+ databasePath: string;
607
+ }
608
+ interface IMetadataCache {
609
+ init(): void;
610
+ getById(id: string): CacheFileEntry | null;
611
+ getByPath(normalizedPath: string): CacheFileEntry | null;
612
+ getChildren(parentId: string): CacheFileEntry[];
613
+ findByMd5(md5: string): CacheFileEntry | null;
614
+ searchByName(query: string): CacheFileEntry[];
615
+ upsertFile(entry: CacheFileEntry): void;
616
+ upsertFiles(entries: CacheFileEntry[]): void;
617
+ deleteFile(id: string): void;
618
+ pruneMissing(activeIds: string[]): number;
619
+ clear(): void;
620
+ getMeta(key: string): string | null;
621
+ setMeta(key: string, value: string): void;
622
+ getStats(): CacheStats;
623
+ close(): void;
624
+ }
625
+ /**
626
+ * High-performance SQLite-backed persistent cache for DriveKit metadata.
627
+ * Uses Node 22's built-in `node:sqlite` (DatabaseSync).
628
+ */
629
+ declare class SqliteMetadataCache implements IMetadataCache {
630
+ private db;
631
+ private dbPath;
632
+ private initialized;
633
+ private fallbackMemory?;
634
+ constructor(customPath?: string);
635
+ init(): void;
636
+ getById(id: string): CacheFileEntry | null;
637
+ getByPath(normalizedPath: string): CacheFileEntry | null;
638
+ getChildren(parentId: string): CacheFileEntry[];
639
+ findByMd5(md5: string): CacheFileEntry | null;
640
+ searchByName(query: string): CacheFileEntry[];
641
+ upsertFile(entry: CacheFileEntry): void;
642
+ upsertFiles(entries: CacheFileEntry[]): void;
643
+ deleteFile(id: string): void;
644
+ pruneMissing(activeIds: string[]): number;
645
+ clear(): void;
646
+ getMeta(key: string): string | null;
647
+ setMeta(key: string, value: string): void;
648
+ getStats(): CacheStats;
649
+ close(): void;
650
+ private mapRow;
651
+ }
652
+ /**
653
+ * Fallback in-memory cache if SQLite is unavailable
654
+ */
655
+ declare class MemoryMetadataCache implements IMetadataCache {
656
+ private files;
657
+ private meta;
658
+ init(): void;
659
+ getById(id: string): CacheFileEntry | null;
660
+ getByPath(normalizedPath: string): CacheFileEntry | null;
661
+ getChildren(parentId: string): CacheFileEntry[];
662
+ findByMd5(md5: string): CacheFileEntry | null;
663
+ searchByName(query: string): CacheFileEntry[];
664
+ upsertFile(entry: CacheFileEntry): void;
665
+ upsertFiles(entries: CacheFileEntry[]): void;
666
+ deleteFile(id: string): void;
667
+ pruneMissing(activeIds: string[]): number;
668
+ clear(): void;
669
+ getMeta(key: string): string | null;
670
+ setMeta(key: string, value: string): void;
671
+ getStats(): CacheStats;
672
+ close(): void;
673
+ }
489
674
 
490
675
  declare class DriveKit {
491
676
  private options;
@@ -494,6 +679,7 @@ declare class DriveKit {
494
679
  private pathResolverInstance;
495
680
  private uploaderInstance;
496
681
  private downloaderInstance;
682
+ private metadataCacheInstance;
497
683
  private rootFolderId;
498
684
  private pluginManager;
499
685
  constructor(options?: DriveKitOptions);
@@ -682,6 +868,82 @@ declare class DriveKit {
682
868
  onFileStart?: (remoteName: string, relativePath: string) => void;
683
869
  onFileComplete?: (remoteName: string, localPath: string) => void;
684
870
  }): Promise<PullResult>;
871
+ /**
872
+ * Creates a readable stream for a file, supporting partial range requests
873
+ */
874
+ createReadStream(pathOrId: string, options?: {
875
+ start?: number;
876
+ end?: number;
877
+ }): Promise<NodeJS.ReadableStream>;
878
+ /**
879
+ * Creates a writable stream directly into Google Drive
880
+ */
881
+ createWriteStream(remotePath: string, options?: Omit<UploadOptions, 'source'>): Promise<NodeJS.WritableStream & {
882
+ done: Promise<DriveApiFile>;
883
+ }>;
884
+ /**
885
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
886
+ */
887
+ getMetadataCache(): Promise<IMetadataCache | null>;
888
+ /**
889
+ * Returns cache statistics (total files, folders, size, last sync)
890
+ */
891
+ getCacheStats(): Promise<CacheStats | null>;
892
+ /**
893
+ * Clears the path and metadata cache
894
+ */
895
+ clearCache(): Promise<void>;
896
+ /**
897
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
898
+ */
899
+ syncCache(options?: {
900
+ onProgress?: (scanned: number) => void;
901
+ }): Promise<CacheStats>;
902
+ /**
903
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
904
+ */
905
+ listSharedDrives(options?: {
906
+ pageSize?: number;
907
+ }): Promise<{
908
+ id: string;
909
+ name: string;
910
+ }[]>;
911
+ /**
912
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
913
+ */
914
+ sharedDrive(driveId: string): DriveKit;
915
+ /**
916
+ * Grants access to a specific email with custom role and notification
917
+ */
918
+ grantAccess(pathOrId: string, options: {
919
+ email: string;
920
+ role?: 'reader' | 'commenter' | 'writer';
921
+ notify?: boolean;
922
+ message?: string;
923
+ }): Promise<DriveApiPermission>;
924
+ /**
925
+ * Revokes access for a specific permission ID or email address
926
+ */
927
+ revokeAccess(pathOrId: string, permissionIdOrEmail: string): Promise<void>;
928
+ /**
929
+ * Lists all active permissions on a file or folder
930
+ */
931
+ listPermissions(pathOrId: string): Promise<DriveApiPermission[]>;
932
+ /**
933
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
934
+ */
935
+ serveWebDAV(options?: {
936
+ port?: number;
937
+ host?: string;
938
+ auth?: {
939
+ username?: string;
940
+ password?: string;
941
+ };
942
+ }): Promise<{
943
+ server: http.Server;
944
+ url: string;
945
+ close: () => Promise<void>;
946
+ }>;
685
947
  /**
686
948
  * Calculates local file MD5 hash for integrity and deduplication checks
687
949
  */
@@ -774,9 +1036,11 @@ declare class PathResolver {
774
1036
  private cache;
775
1037
  private cacheTTL;
776
1038
  private enableCache;
1039
+ private metadataCache?;
777
1040
  constructor(drive: drive_v3.Drive, rootFolderId?: string, options?: {
778
1041
  enableCache?: boolean;
779
1042
  cacheTTL?: number;
1043
+ metadataCache?: IMetadataCache;
780
1044
  });
781
1045
  /**
782
1046
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -874,6 +1138,13 @@ declare class Downloader {
874
1138
  mimeType: string;
875
1139
  size?: number;
876
1140
  }>;
1141
+ /**
1142
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1143
+ */
1144
+ createReadStream(fileId: string, options?: {
1145
+ start?: number;
1146
+ end?: number;
1147
+ }): Promise<NodeJS.ReadableStream>;
877
1148
  }
878
1149
 
879
1150
  /**
@@ -898,6 +1169,28 @@ declare class ConcurrencyPool {
898
1169
  map<Item, Result>(items: Item[], fn: (item: Item, index: number) => Promise<Result>): Promise<Result[]>;
899
1170
  }
900
1171
 
1172
+ interface WebDAVServerOptions {
1173
+ port?: number;
1174
+ host?: string;
1175
+ auth?: {
1176
+ username?: string;
1177
+ password?: string;
1178
+ };
1179
+ }
1180
+ /**
1181
+ * Escapes unsafe characters for valid XML output
1182
+ */
1183
+ declare function escapeXml(unsafe: string): string;
1184
+ /**
1185
+ * Creates and starts a production-grade, zero-dependency WebDAV server for DriveKit.
1186
+ * Supports HTTP Basic Authentication, Streaming PUT (Zero-Buffer), Range requests, MOVE, COPY, and MKCOL.
1187
+ */
1188
+ declare function startWebDAVServer(drive: DriveKit, options?: WebDAVServerOptions): Promise<{
1189
+ server: http$1.Server;
1190
+ url: string;
1191
+ close: () => Promise<void>;
1192
+ }>;
1193
+
901
1194
  /**
902
1195
  * Creates an OSC 8 clickable hyperlink in supported modern terminals (macOS Terminal, iTerm2, VS Code, etc.)
903
1196
  */
@@ -993,4 +1286,4 @@ declare function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Pro
993
1286
  */
994
1287
  declare function createDrive(options?: DriveKitOptions): Promise<DriveKit>;
995
1288
 
996
- 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, DriveFileRef, DriveFolderRef, DriveKit, type DriveKitAuthConfig, DriveKitError, type DriveKitOptions, type DriveKitPlugin, 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, PluginManager, 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, getFileIcon, isGoogleWorkspaceDoc, isRetryableError, loginWithBrowser, lookupMimeType, renderFileRow, runInteractiveExplorer, terminalLink, withRetry };
1289
+ 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 DriveWriteStream, 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, type WebhookPluginOptions, calculateFileMd5, createAutoNamePlugin, createDrive, createWebhookPlugin, DriveKit as default, escapeXml, formatBytes, formatDuration, formatSpeed, getExtensionForMime, getFileIcon, isGoogleWorkspaceDoc, isRetryableError, loginWithBrowser, lookupMimeType, renderFileRow, runInteractiveExplorer, startWebDAVServer, terminalLink, withRetry };