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/cli.js CHANGED
@@ -1,5 +1,11 @@
1
1
  var __defProp = Object.defineProperty;
2
2
  var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
+ }) : x)(function(x) {
6
+ if (typeof require !== "undefined") return require.apply(this, arguments);
7
+ throw Error('Dynamic require of "' + x + '" is not supported');
8
+ });
3
9
  var __esm = (fn, res) => function __init() {
4
10
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
11
  };
@@ -298,11 +304,13 @@ var init_path_resolver = __esm({
298
304
  cache = /* @__PURE__ */ new Map();
299
305
  cacheTTL;
300
306
  enableCache;
307
+ metadataCache;
301
308
  constructor(drive2, rootFolderId = "root", options) {
302
309
  this.drive = drive2;
303
310
  this.rootFolderId = rootFolderId;
304
311
  this.enableCache = options?.enableCache ?? true;
305
312
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
313
+ this.metadataCache = options?.metadataCache;
306
314
  }
307
315
  /**
308
316
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -317,21 +325,31 @@ var init_path_resolver = __esm({
317
325
  /**
318
326
  * Gets cache key for a path
319
327
  */
320
- getCacheKey(path7) {
321
- return `${this.rootFolderId}:${this.normalizePath(path7)}`;
328
+ getCacheKey(path9) {
329
+ return `${this.rootFolderId}:${this.normalizePath(path9)}`;
322
330
  }
323
331
  /**
324
332
  * Clears the path cache
325
333
  */
326
334
  clearCache() {
327
335
  this.cache.clear();
336
+ if (this.metadataCache) {
337
+ this.metadataCache.clear();
338
+ }
328
339
  }
329
340
  /**
330
341
  * Invalidate a single path from cache
331
342
  */
332
- invalidatePath(path7) {
333
- const key = this.getCacheKey(path7);
343
+ invalidatePath(path9) {
344
+ const norm = this.normalizePath(path9);
345
+ const key = this.getCacheKey(norm);
334
346
  this.cache.delete(key);
347
+ if (this.metadataCache) {
348
+ const item = this.metadataCache.getByPath(norm);
349
+ if (item) {
350
+ this.metadataCache.deleteFile(item.id);
351
+ }
352
+ }
335
353
  }
336
354
  /**
337
355
  * Resolves a path to a Google Drive item (file or folder).
@@ -347,6 +365,17 @@ var init_path_resolver = __esm({
347
365
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
348
366
  };
349
367
  }
368
+ if (this.metadataCache) {
369
+ const persistentCached = this.metadataCache.getByPath(norm);
370
+ if (persistentCached) {
371
+ return {
372
+ id: persistentCached.id,
373
+ name: persistentCached.name,
374
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
375
+ mimeType: persistentCached.mimeType
376
+ };
377
+ }
378
+ }
350
379
  if (this.enableCache) {
351
380
  const cached = this.cache.get(this.getCacheKey(norm));
352
381
  if (cached && cached.expiresAt > Date.now()) {
@@ -365,6 +394,21 @@ var init_path_resolver = __esm({
365
394
  const segment = segments[i];
366
395
  const isLast = i === segments.length - 1;
367
396
  currentPath += `/${segment}`;
397
+ if (this.metadataCache) {
398
+ const pCached = this.metadataCache.getByPath(currentPath);
399
+ if (pCached) {
400
+ currentParentId = pCached.id;
401
+ if (isLast) {
402
+ return {
403
+ id: pCached.id,
404
+ name: pCached.name,
405
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
406
+ mimeType: pCached.mimeType
407
+ };
408
+ }
409
+ continue;
410
+ }
411
+ }
368
412
  if (this.enableCache) {
369
413
  const cached = this.cache.get(this.getCacheKey(currentPath));
370
414
  if (cached && cached.expiresAt > Date.now()) {
@@ -409,6 +453,16 @@ var init_path_resolver = __esm({
409
453
  }
410
454
  if (file && file.id) {
411
455
  currentParentId = file.id;
456
+ if (this.metadataCache) {
457
+ this.metadataCache.upsertFile({
458
+ id: file.id,
459
+ name: file.name || segment,
460
+ mimeType: file.mimeType || "",
461
+ parentId: currentParentId,
462
+ path: currentPath,
463
+ trashed: false
464
+ });
465
+ }
412
466
  if (this.enableCache) {
413
467
  this.cache.set(this.getCacheKey(currentPath), {
414
468
  id: file.id,
@@ -443,6 +497,16 @@ var init_path_resolver = __esm({
443
497
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
444
498
  }
445
499
  currentParentId = newFolder.id;
500
+ if (this.metadataCache) {
501
+ this.metadataCache.upsertFile({
502
+ id: newFolder.id,
503
+ name: segment,
504
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
505
+ parentId: currentParentId,
506
+ path: currentPath,
507
+ trashed: false
508
+ });
509
+ }
446
510
  if (this.enableCache) {
447
511
  this.cache.set(this.getCacheKey(currentPath), {
448
512
  id: newFolder.id,
@@ -632,6 +696,9 @@ var init_resumable_uploader = __esm({
632
696
  let chunkIndex = 0;
633
697
  try {
634
698
  while (bytesSent < totalBytes) {
699
+ if (options.signal?.aborted) {
700
+ throw new Error("Upload aborted by user signal");
701
+ }
635
702
  chunkIndex++;
636
703
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
637
704
  const buffer = Buffer.alloc(currentChunkSize);
@@ -692,6 +759,9 @@ var init_resumable_uploader = __esm({
692
759
  const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
693
760
  let chunkIndex = 0;
694
761
  while (bytesSent < totalBytes) {
762
+ if (options.signal?.aborted) {
763
+ throw new Error("Upload aborted by user signal");
764
+ }
695
765
  chunkIndex++;
696
766
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
697
767
  const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
@@ -913,6 +983,24 @@ var init_downloader = __esm({
913
983
  size: totalBytes
914
984
  };
915
985
  }
986
+ /**
987
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
988
+ */
989
+ async createReadStream(fileId, options) {
990
+ const headers = {};
991
+ if (options?.start !== void 0 || options?.end !== void 0) {
992
+ const start = options.start ?? 0;
993
+ const end = options.end !== void 0 ? options.end : "";
994
+ headers["Range"] = `bytes=${start}-${end}`;
995
+ }
996
+ const res = await withRetry(async () => {
997
+ return await this.drive.files.get(
998
+ { fileId, alt: "media", supportsAllDrives: true },
999
+ { responseType: "stream", headers }
1000
+ );
1001
+ });
1002
+ return res.data;
1003
+ }
916
1004
  };
917
1005
  }
918
1006
  });
@@ -1041,6 +1129,19 @@ var init_query_builder = __esm({
1041
1129
  this.conditions.push(`(${condition})`);
1042
1130
  return this;
1043
1131
  }
1132
+ /**
1133
+ * Custom raw query condition (alias for raw)
1134
+ */
1135
+ custom(condition) {
1136
+ return this.raw(condition);
1137
+ }
1138
+ /**
1139
+ * Filter: Exact MD5 checksum match
1140
+ */
1141
+ md5(checksum) {
1142
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1143
+ return this;
1144
+ }
1044
1145
  /**
1045
1146
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1046
1147
  */
@@ -1087,6 +1188,12 @@ var init_query_builder = __esm({
1087
1188
  });
1088
1189
  return res.data.files || [];
1089
1190
  }
1191
+ /**
1192
+ * Executes query and returns array of matching files (alias for list)
1193
+ */
1194
+ async execute() {
1195
+ return await this.list();
1196
+ }
1090
1197
  /**
1091
1198
  * Returns the first matching file, or null if not found
1092
1199
  */
@@ -1662,13 +1769,761 @@ var init_browser_login = __esm({
1662
1769
  }
1663
1770
  });
1664
1771
 
1772
+ // src/core/resource-refs.ts
1773
+ var DriveFileRef, DriveFolderRef;
1774
+ var init_resource_refs = __esm({
1775
+ "src/core/resource-refs.ts"() {
1776
+ "use strict";
1777
+ init_esm_shims();
1778
+ DriveFileRef = class {
1779
+ drive;
1780
+ pathOrId;
1781
+ constructor(drive2, pathOrId) {
1782
+ this.drive = drive2;
1783
+ this.pathOrId = pathOrId;
1784
+ }
1785
+ /** Gets file metadata */
1786
+ async get() {
1787
+ return await this.drive.getFile(this.pathOrId);
1788
+ }
1789
+ /** Checks if the file exists */
1790
+ async exists() {
1791
+ return await this.drive.exists(this.pathOrId);
1792
+ }
1793
+ /** Reads file as UTF-8 string */
1794
+ async getText() {
1795
+ return await this.drive.getText(this.pathOrId);
1796
+ }
1797
+ /** Reads and parses JSON file */
1798
+ async getJson() {
1799
+ return await this.drive.getJson(this.pathOrId);
1800
+ }
1801
+ /** Downloads the file to destination */
1802
+ async download(optionsOrDestination) {
1803
+ const opts = typeof optionsOrDestination === "string" ? { destination: optionsOrDestination } : optionsOrDestination;
1804
+ return await this.drive.download(this.pathOrId, opts);
1805
+ }
1806
+ /** Moves the file to a new folder path or ID */
1807
+ async moveTo(newParentPathOrId) {
1808
+ return await this.drive.move(this.pathOrId, newParentPathOrId);
1809
+ }
1810
+ /** Copies the file to a target directory */
1811
+ async copyTo(parentPathOrId, newName) {
1812
+ return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });
1813
+ }
1814
+ /** Renames the file */
1815
+ async rename(newName) {
1816
+ return await this.drive.rename(this.pathOrId, newName);
1817
+ }
1818
+ /** Deletes the file (or moves to trash if permanent is false) */
1819
+ async delete(permanent = false) {
1820
+ return await this.drive.delete(this.pathOrId, permanent);
1821
+ }
1822
+ /** Moves file to trash */
1823
+ async trash() {
1824
+ return await this.drive.trash(this.pathOrId);
1825
+ }
1826
+ /** Shares file */
1827
+ async share(options) {
1828
+ return await this.drive.share(this.pathOrId, options);
1829
+ }
1830
+ /** Makes file publicly accessible */
1831
+ async sharePublic(role = "reader") {
1832
+ return await this.drive.sharePublic(this.pathOrId, role);
1833
+ }
1834
+ /** Gets public/preview links */
1835
+ async getLink() {
1836
+ return await this.drive.getShareableLink(this.pathOrId);
1837
+ }
1838
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
1839
+ async createReadStream(options) {
1840
+ return await this.drive.createReadStream(this.pathOrId, options);
1841
+ }
1842
+ /** Grants access to a specific email with custom role and notification */
1843
+ async grantAccess(options) {
1844
+ return await this.drive.grantAccess(this.pathOrId, options);
1845
+ }
1846
+ /** Revokes access by permission ID or user email */
1847
+ async revokeAccess(permissionIdOrEmail) {
1848
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
1849
+ }
1850
+ /** Lists all granted permissions on this file */
1851
+ async listPermissions() {
1852
+ return await this.drive.listPermissions(this.pathOrId);
1853
+ }
1854
+ };
1855
+ DriveFolderRef = class {
1856
+ drive;
1857
+ pathOrId;
1858
+ constructor(drive2, pathOrId) {
1859
+ this.drive = drive2;
1860
+ this.pathOrId = pathOrId;
1861
+ }
1862
+ /** Lists contents of this folder */
1863
+ async ls() {
1864
+ return await this.drive.ls(this.pathOrId);
1865
+ }
1866
+ /** Ensures this folder and subpaths exist (mkdir -p) */
1867
+ async mkdirp(subPath) {
1868
+ const target = subPath ? this.pathOrId.endsWith("/") ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}` : this.pathOrId;
1869
+ return await this.drive.mkdirp(target);
1870
+ }
1871
+ /** Uploads a file directly into this folder */
1872
+ async upload(source, options = {}) {
1873
+ return await this.drive.upload({
1874
+ ...options,
1875
+ source,
1876
+ parent: this.pathOrId
1877
+ });
1878
+ }
1879
+ /** Synchronizes a local directory into this remote folder */
1880
+ async syncFrom(localDir, options = {}) {
1881
+ return await this.drive.syncFolder(localDir, this.pathOrId, options);
1882
+ }
1883
+ /** Pulls this remote folder down to local directory */
1884
+ async pullTo(localDestinationDir, options = {}) {
1885
+ return await this.drive.pull(this.pathOrId, localDestinationDir, options);
1886
+ }
1887
+ /** Watches this folder for real-time changes */
1888
+ async watch(options = {}) {
1889
+ return await this.drive.watch(this.pathOrId, options);
1890
+ }
1891
+ /** Grants access to this entire folder */
1892
+ async grantAccess(options) {
1893
+ return await this.drive.grantAccess(this.pathOrId, options);
1894
+ }
1895
+ /** Creates a writable stream directly into a file inside this folder */
1896
+ async createWriteStream(fileName, options) {
1897
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
1898
+ return await this.drive.createWriteStream(targetPath, options);
1899
+ }
1900
+ };
1901
+ }
1902
+ });
1903
+
1904
+ // src/core/plugins.ts
1905
+ var PluginManager;
1906
+ var init_plugins = __esm({
1907
+ "src/core/plugins.ts"() {
1908
+ "use strict";
1909
+ init_esm_shims();
1910
+ PluginManager = class {
1911
+ plugins = [];
1912
+ use(plugin) {
1913
+ this.plugins.push(plugin);
1914
+ return this;
1915
+ }
1916
+ async runBeforeUpload(options) {
1917
+ let current = { ...options };
1918
+ for (const plugin of this.plugins) {
1919
+ if (plugin.beforeUpload) {
1920
+ const modified = await plugin.beforeUpload(current);
1921
+ if (modified) current = modified;
1922
+ }
1923
+ }
1924
+ return current;
1925
+ }
1926
+ async runAfterUpload(file) {
1927
+ let current = file;
1928
+ for (const plugin of this.plugins) {
1929
+ if (plugin.afterUpload) {
1930
+ const modified = await plugin.afterUpload(current);
1931
+ if (modified) current = modified;
1932
+ }
1933
+ }
1934
+ return current;
1935
+ }
1936
+ async runBeforeDownload(fileId, options) {
1937
+ let current = { ...options };
1938
+ for (const plugin of this.plugins) {
1939
+ if (plugin.beforeDownload) {
1940
+ const modified = await plugin.beforeDownload(fileId, current);
1941
+ if (modified) current = modified;
1942
+ }
1943
+ }
1944
+ return current;
1945
+ }
1946
+ async runAfterDownload(result) {
1947
+ let current = result;
1948
+ for (const plugin of this.plugins) {
1949
+ if (plugin.afterDownload) {
1950
+ const modified = await plugin.afterDownload(current);
1951
+ if (modified) current = modified;
1952
+ }
1953
+ }
1954
+ return current;
1955
+ }
1956
+ };
1957
+ }
1958
+ });
1959
+
1960
+ // src/core/cache.ts
1961
+ import os from "os";
1962
+ import path5 from "path";
1963
+ import fs5 from "fs";
1964
+ var SqliteMetadataCache, MemoryMetadataCache;
1965
+ var init_cache = __esm({
1966
+ "src/core/cache.ts"() {
1967
+ "use strict";
1968
+ init_esm_shims();
1969
+ SqliteMetadataCache = class {
1970
+ db = null;
1971
+ dbPath;
1972
+ initialized = false;
1973
+ fallbackMemory;
1974
+ constructor(customPath) {
1975
+ if (customPath) {
1976
+ this.dbPath = customPath;
1977
+ } else {
1978
+ const dir = path5.join(os.homedir(), ".drivekit");
1979
+ if (!fs5.existsSync(dir)) {
1980
+ try {
1981
+ fs5.mkdirSync(dir, { recursive: true });
1982
+ } catch {
1983
+ }
1984
+ }
1985
+ this.dbPath = path5.join(dir, "cache.db");
1986
+ }
1987
+ }
1988
+ init() {
1989
+ if (this.initialized) return;
1990
+ try {
1991
+ const { DatabaseSync } = __require("sqlite");
1992
+ if (!DatabaseSync) {
1993
+ throw new Error("DatabaseSync not available");
1994
+ }
1995
+ this.db = new DatabaseSync(this.dbPath);
1996
+ this.db.exec(`
1997
+ PRAGMA journal_mode = WAL;
1998
+ PRAGMA synchronous = NORMAL;
1999
+
2000
+ CREATE TABLE IF NOT EXISTS files (
2001
+ id TEXT PRIMARY KEY,
2002
+ name TEXT NOT NULL,
2003
+ mimeType TEXT NOT NULL,
2004
+ size INTEGER,
2005
+ parentId TEXT,
2006
+ path TEXT,
2007
+ md5Checksum TEXT,
2008
+ trashed INTEGER DEFAULT 0,
2009
+ modifiedTime TEXT,
2010
+ updatedAt INTEGER
2011
+ );
2012
+
2013
+ CREATE TABLE IF NOT EXISTS meta (
2014
+ key TEXT PRIMARY KEY,
2015
+ value TEXT NOT NULL
2016
+ );
2017
+
2018
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2019
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2020
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2021
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2022
+ `);
2023
+ this.initialized = true;
2024
+ } catch (err) {
2025
+ this.fallbackMemory = new MemoryMetadataCache();
2026
+ this.fallbackMemory.init();
2027
+ this.initialized = true;
2028
+ this.db = null;
2029
+ }
2030
+ }
2031
+ getById(id) {
2032
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2033
+ if (!this.initialized || !this.db) return null;
2034
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2035
+ const row = stmt.get(id);
2036
+ return row ? this.mapRow(row) : null;
2037
+ }
2038
+ getByPath(normalizedPath) {
2039
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2040
+ if (!this.initialized || !this.db) return null;
2041
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2042
+ const row = stmt.get(normalizedPath);
2043
+ return row ? this.mapRow(row) : null;
2044
+ }
2045
+ getChildren(parentId) {
2046
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2047
+ if (!this.initialized || !this.db) return [];
2048
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2049
+ const rows = stmt.all(parentId);
2050
+ return rows.map((r) => this.mapRow(r));
2051
+ }
2052
+ findByMd5(md5) {
2053
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2054
+ if (!this.initialized || !this.db || !md5) return null;
2055
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2056
+ const row = stmt.get(md5.toLowerCase());
2057
+ return row ? this.mapRow(row) : null;
2058
+ }
2059
+ searchByName(query) {
2060
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2061
+ if (!this.initialized || !this.db) return [];
2062
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2063
+ const rows = stmt.all(`%${query}%`);
2064
+ return rows.map((r) => this.mapRow(r));
2065
+ }
2066
+ upsertFile(entry) {
2067
+ if (this.fallbackMemory) {
2068
+ this.fallbackMemory.upsertFile(entry);
2069
+ return;
2070
+ }
2071
+ if (!this.initialized || !this.db) return;
2072
+ const stmt = this.db.prepare(`
2073
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2074
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2075
+ ON CONFLICT(id) DO UPDATE SET
2076
+ name = excluded.name,
2077
+ mimeType = excluded.mimeType,
2078
+ size = excluded.size,
2079
+ parentId = excluded.parentId,
2080
+ path = COALESCE(excluded.path, files.path),
2081
+ md5Checksum = excluded.md5Checksum,
2082
+ trashed = excluded.trashed,
2083
+ modifiedTime = excluded.modifiedTime,
2084
+ updatedAt = excluded.updatedAt
2085
+ `);
2086
+ stmt.run(
2087
+ entry.id,
2088
+ entry.name,
2089
+ entry.mimeType,
2090
+ entry.size ?? null,
2091
+ entry.parentId ?? null,
2092
+ entry.path ?? null,
2093
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2094
+ entry.trashed ? 1 : 0,
2095
+ entry.modifiedTime ?? null,
2096
+ entry.updatedAt ?? Date.now()
2097
+ );
2098
+ }
2099
+ upsertFiles(entries) {
2100
+ if (this.fallbackMemory) {
2101
+ this.fallbackMemory.upsertFiles(entries);
2102
+ return;
2103
+ }
2104
+ if (!this.initialized || !this.db || entries.length === 0) return;
2105
+ this.db.exec("BEGIN TRANSACTION;");
2106
+ try {
2107
+ for (const entry of entries) {
2108
+ this.upsertFile(entry);
2109
+ }
2110
+ this.db.exec("COMMIT;");
2111
+ } catch (e) {
2112
+ this.db.exec("ROLLBACK;");
2113
+ throw e;
2114
+ }
2115
+ }
2116
+ deleteFile(id) {
2117
+ if (this.fallbackMemory) {
2118
+ this.fallbackMemory.deleteFile(id);
2119
+ return;
2120
+ }
2121
+ if (!this.initialized || !this.db) return;
2122
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2123
+ stmt.run(id);
2124
+ }
2125
+ clear() {
2126
+ if (this.fallbackMemory) {
2127
+ this.fallbackMemory.clear();
2128
+ return;
2129
+ }
2130
+ if (!this.initialized || !this.db) return;
2131
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2132
+ }
2133
+ getMeta(key) {
2134
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2135
+ if (!this.initialized || !this.db) return null;
2136
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2137
+ const row = stmt.get(key);
2138
+ return row ? row.value : null;
2139
+ }
2140
+ setMeta(key, value) {
2141
+ if (this.fallbackMemory) {
2142
+ this.fallbackMemory.setMeta(key, value);
2143
+ return;
2144
+ }
2145
+ if (!this.initialized || !this.db) return;
2146
+ const stmt = this.db.prepare(`
2147
+ INSERT INTO meta (key, value) VALUES (?, ?)
2148
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2149
+ `);
2150
+ stmt.run(key, value);
2151
+ }
2152
+ getStats() {
2153
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2154
+ if (!this.initialized || !this.db) {
2155
+ return {
2156
+ fileCount: 0,
2157
+ folderCount: 0,
2158
+ totalSizeBytes: 0,
2159
+ lastSyncTime: null,
2160
+ databasePath: this.dbPath
2161
+ };
2162
+ }
2163
+ const fileCountRow = this.db.prepare(
2164
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2165
+ ).get();
2166
+ const folderCountRow = this.db.prepare(
2167
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2168
+ ).get();
2169
+ const totalSizeRow = this.db.prepare(
2170
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2171
+ ).get();
2172
+ const lastSync = this.getMeta("last_sync_timestamp");
2173
+ return {
2174
+ fileCount: fileCountRow?.count || 0,
2175
+ folderCount: folderCountRow?.count || 0,
2176
+ totalSizeBytes: totalSizeRow?.total || 0,
2177
+ lastSyncTime: lastSync,
2178
+ databasePath: this.dbPath
2179
+ };
2180
+ }
2181
+ close() {
2182
+ if (this.fallbackMemory) {
2183
+ this.fallbackMemory.close();
2184
+ this.fallbackMemory = void 0;
2185
+ }
2186
+ if (this.db) {
2187
+ try {
2188
+ this.db.close();
2189
+ } catch {
2190
+ }
2191
+ this.initialized = false;
2192
+ this.db = null;
2193
+ }
2194
+ }
2195
+ mapRow(row) {
2196
+ return {
2197
+ id: row.id,
2198
+ name: row.name,
2199
+ mimeType: row.mimeType,
2200
+ size: row.size != null ? Number(row.size) : void 0,
2201
+ parentId: row.parentId || void 0,
2202
+ path: row.path || void 0,
2203
+ md5Checksum: row.md5Checksum || void 0,
2204
+ trashed: row.trashed === 1,
2205
+ modifiedTime: row.modifiedTime || void 0,
2206
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2207
+ };
2208
+ }
2209
+ };
2210
+ MemoryMetadataCache = class {
2211
+ files = /* @__PURE__ */ new Map();
2212
+ meta = /* @__PURE__ */ new Map();
2213
+ init() {
2214
+ }
2215
+ getById(id) {
2216
+ return this.files.get(id) || null;
2217
+ }
2218
+ getByPath(normalizedPath) {
2219
+ for (const f of this.files.values()) {
2220
+ if (f.path === normalizedPath && !f.trashed) return f;
2221
+ }
2222
+ return null;
2223
+ }
2224
+ getChildren(parentId) {
2225
+ const list = [];
2226
+ for (const f of this.files.values()) {
2227
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2228
+ }
2229
+ return list;
2230
+ }
2231
+ findByMd5(md5) {
2232
+ const target = md5.toLowerCase();
2233
+ for (const f of this.files.values()) {
2234
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2235
+ }
2236
+ return null;
2237
+ }
2238
+ searchByName(query) {
2239
+ const q = query.toLowerCase();
2240
+ const list = [];
2241
+ for (const f of this.files.values()) {
2242
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2243
+ }
2244
+ return list;
2245
+ }
2246
+ upsertFile(entry) {
2247
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2248
+ }
2249
+ upsertFiles(entries) {
2250
+ for (const e of entries) this.upsertFile(e);
2251
+ }
2252
+ deleteFile(id) {
2253
+ this.files.delete(id);
2254
+ }
2255
+ clear() {
2256
+ this.files.clear();
2257
+ this.meta.clear();
2258
+ }
2259
+ getMeta(key) {
2260
+ return this.meta.get(key) || null;
2261
+ }
2262
+ setMeta(key, value) {
2263
+ this.meta.set(key, value);
2264
+ }
2265
+ getStats() {
2266
+ let fileCount = 0;
2267
+ let folderCount = 0;
2268
+ let totalSizeBytes = 0;
2269
+ for (const f of this.files.values()) {
2270
+ if (f.trashed) continue;
2271
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2272
+ else {
2273
+ fileCount++;
2274
+ totalSizeBytes += f.size || 0;
2275
+ }
2276
+ }
2277
+ return {
2278
+ fileCount,
2279
+ folderCount,
2280
+ totalSizeBytes,
2281
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2282
+ databasePath: ":memory:"
2283
+ };
2284
+ }
2285
+ close() {
2286
+ this.clear();
2287
+ }
2288
+ };
2289
+ }
2290
+ });
2291
+
2292
+ // src/server/webdav.ts
2293
+ var webdav_exports = {};
2294
+ __export(webdav_exports, {
2295
+ startWebDAVServer: () => startWebDAVServer
2296
+ });
2297
+ import http2 from "http";
2298
+ import url from "url";
2299
+ import path6 from "path";
2300
+ async function startWebDAVServer(drive2, options = {}) {
2301
+ const port = options.port || 8080;
2302
+ const host = options.host || "127.0.0.1";
2303
+ await drive2.init();
2304
+ const server = http2.createServer(async (req, res) => {
2305
+ try {
2306
+ const parsedUrl = url.parse(req.url || "/", true);
2307
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2308
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
2309
+ switch (req.method) {
2310
+ case "OPTIONS": {
2311
+ res.writeHead(200, {
2312
+ DAV: "1, 2",
2313
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2314
+ "MS-Author-Via": "DAV"
2315
+ });
2316
+ res.end();
2317
+ return;
2318
+ }
2319
+ case "PROPFIND": {
2320
+ const depth = req.headers["depth"] || "1";
2321
+ const xml = await handlePropfind(drive2, virtualPath, depth);
2322
+ res.writeHead(207, {
2323
+ "Content-Type": "application/xml; charset=utf-8"
2324
+ });
2325
+ res.end(xml);
2326
+ return;
2327
+ }
2328
+ case "GET":
2329
+ case "HEAD": {
2330
+ if (virtualPath === "/" || virtualPath === "") {
2331
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2332
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
2333
+ return;
2334
+ }
2335
+ try {
2336
+ const file = await drive2.getFile(virtualPath);
2337
+ if (file.mimeType === "application/vnd.google-apps.folder") {
2338
+ res.writeHead(405, { "Content-Type": "text/plain" });
2339
+ res.end("Cannot GET a directory");
2340
+ return;
2341
+ }
2342
+ const stream = await drive2.createReadStream(virtualPath);
2343
+ res.writeHead(200, {
2344
+ "Content-Type": file.mimeType || "application/octet-stream",
2345
+ "Content-Length": file.size || void 0
2346
+ });
2347
+ if (req.method === "HEAD") {
2348
+ res.end();
2349
+ } else {
2350
+ stream.pipe(res);
2351
+ }
2352
+ } catch (e) {
2353
+ res.writeHead(404, { "Content-Type": "text/plain" });
2354
+ res.end("File Not Found");
2355
+ }
2356
+ return;
2357
+ }
2358
+ case "PUT": {
2359
+ const remoteDir = path6.dirname(virtualPath);
2360
+ const fileName = path6.basename(virtualPath);
2361
+ await drive2.mkdirp(remoteDir);
2362
+ const chunks = [];
2363
+ req.on("data", (chunk) => chunks.push(chunk));
2364
+ req.on("end", async () => {
2365
+ try {
2366
+ const buffer = Buffer.concat(chunks);
2367
+ await drive2.upload({
2368
+ source: buffer,
2369
+ filename: fileName,
2370
+ parent: remoteDir,
2371
+ overwrite: true
2372
+ });
2373
+ res.writeHead(201, { "Content-Type": "text/plain" });
2374
+ res.end("Created");
2375
+ } catch (err) {
2376
+ res.writeHead(500, { "Content-Type": "text/plain" });
2377
+ res.end(err.message || "Upload failed");
2378
+ }
2379
+ });
2380
+ return;
2381
+ }
2382
+ case "MKCOL": {
2383
+ try {
2384
+ await drive2.mkdirp(virtualPath);
2385
+ res.writeHead(201, { "Content-Type": "text/plain" });
2386
+ res.end("Collection Created");
2387
+ } catch (err) {
2388
+ res.writeHead(500, { "Content-Type": "text/plain" });
2389
+ res.end(err.message);
2390
+ }
2391
+ return;
2392
+ }
2393
+ case "DELETE": {
2394
+ try {
2395
+ await drive2.delete(virtualPath, true);
2396
+ res.writeHead(204);
2397
+ res.end();
2398
+ } catch (err) {
2399
+ res.writeHead(404, { "Content-Type": "text/plain" });
2400
+ res.end("Not Found");
2401
+ }
2402
+ return;
2403
+ }
2404
+ case "MOVE": {
2405
+ const destination = req.headers["destination"];
2406
+ if (!destination || typeof destination !== "string") {
2407
+ res.writeHead(400, { "Content-Type": "text/plain" });
2408
+ res.end("Destination header missing");
2409
+ return;
2410
+ }
2411
+ const destUrl = url.parse(destination);
2412
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2413
+ const newName = path6.basename(destPath);
2414
+ const newParent = path6.dirname(destPath);
2415
+ try {
2416
+ await drive2.move(virtualPath, newParent);
2417
+ if (newName !== path6.basename(virtualPath)) {
2418
+ await drive2.rename(destPath, newName);
2419
+ }
2420
+ res.writeHead(201);
2421
+ res.end("Moved");
2422
+ } catch (err) {
2423
+ res.writeHead(500, { "Content-Type": "text/plain" });
2424
+ res.end(err.message);
2425
+ }
2426
+ return;
2427
+ }
2428
+ default: {
2429
+ res.writeHead(501, { "Content-Type": "text/plain" });
2430
+ res.end("Method Not Implemented");
2431
+ }
2432
+ }
2433
+ } catch (globalErr) {
2434
+ res.writeHead(500, { "Content-Type": "text/plain" });
2435
+ res.end(`Internal Server Error: ${globalErr.message}`);
2436
+ }
2437
+ });
2438
+ return new Promise((resolve) => {
2439
+ server.listen(port, host, () => {
2440
+ const serverUrl = `http://${host}:${port}`;
2441
+ resolve({
2442
+ server,
2443
+ url: serverUrl,
2444
+ close: () => new Promise((resClose) => server.close(() => resClose()))
2445
+ });
2446
+ });
2447
+ });
2448
+ }
2449
+ async function handlePropfind(drive2, virtualPath, depth) {
2450
+ const responses = [];
2451
+ let isFolder = false;
2452
+ let selfItem = null;
2453
+ if (virtualPath === "/" || virtualPath === "") {
2454
+ isFolder = true;
2455
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
2456
+ } else {
2457
+ try {
2458
+ selfItem = await drive2.getFile(virtualPath);
2459
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
2460
+ responses.push(
2461
+ renderWebDAVResponse(
2462
+ virtualPath,
2463
+ isFolder,
2464
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
2465
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2466
+ )
2467
+ );
2468
+ } catch {
2469
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
2470
+ }
2471
+ }
2472
+ if (isFolder && depth !== "0") {
2473
+ try {
2474
+ const children = await drive2.ls(virtualPath);
2475
+ for (const child of children) {
2476
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2477
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
2478
+ responses.push(
2479
+ renderWebDAVResponse(
2480
+ childPath,
2481
+ childIsFolder,
2482
+ child.size ? parseInt(child.size, 10) : 0,
2483
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2484
+ )
2485
+ );
2486
+ }
2487
+ } catch {
2488
+ }
2489
+ }
2490
+ return `<?xml version="1.0" encoding="utf-8"?>
2491
+ <D:multistatus xmlns:D="DAV:">
2492
+ ${responses.join("\n")}
2493
+ </D:multistatus>`;
2494
+ }
2495
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2496
+ const encodedHref = encodeURI(href);
2497
+ const resourceType = isDir ? "<D:collection/>" : "";
2498
+ const dateFormatted = new Date(modifiedTime).toUTCString();
2499
+ return ` <D:response>
2500
+ <D:href>${encodedHref}</D:href>
2501
+ <D:propstat>
2502
+ <D:prop>
2503
+ <D:displayname>${path6.basename(href) || "root"}</D:displayname>
2504
+ <D:resourcetype>${resourceType}</D:resourcetype>
2505
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2506
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2507
+ <D:status>HTTP/1.1 200 OK</D:status>
2508
+ </D:prop>
2509
+ <D:status>HTTP/1.1 200 OK</D:status>
2510
+ </D:propstat>
2511
+ </D:response>`;
2512
+ }
2513
+ var init_webdav = __esm({
2514
+ "src/server/webdav.ts"() {
2515
+ "use strict";
2516
+ init_esm_shims();
2517
+ }
2518
+ });
2519
+
1665
2520
  // src/core/client.ts
1666
2521
  var client_exports = {};
1667
2522
  __export(client_exports, {
1668
2523
  DriveKit: () => DriveKit
1669
2524
  });
1670
- import fs5 from "fs";
1671
- import path5 from "path";
2525
+ import fs6 from "fs";
2526
+ import path7 from "path";
1672
2527
  import { drive } from "@googleapis/drive";
1673
2528
  var DriveKit;
1674
2529
  var init_client = __esm({
@@ -1685,22 +2540,46 @@ var init_client = __esm({
1685
2540
  init_storage_cleaner();
1686
2541
  init_smart_sync();
1687
2542
  init_browser_login();
2543
+ init_resource_refs();
2544
+ init_plugins();
1688
2545
  init_retry();
1689
2546
  init_format();
1690
2547
  init_mime();
1691
- DriveKit = class {
2548
+ init_cache();
2549
+ DriveKit = class _DriveKit {
1692
2550
  options;
1693
2551
  authenticator;
1694
2552
  driveClient = null;
1695
2553
  pathResolverInstance = null;
1696
2554
  uploaderInstance = null;
1697
2555
  downloaderInstance = null;
2556
+ metadataCacheInstance = null;
1698
2557
  rootFolderId;
2558
+ pluginManager = new PluginManager();
1699
2559
  constructor(options = {}) {
1700
2560
  this.options = options;
1701
2561
  this.rootFolderId = options.rootFolderId || "root";
1702
2562
  this.authenticator = new DriveAuthenticator(options.auth);
1703
2563
  }
2564
+ /**
2565
+ * Registers a middleware plugin into DriveKit lifecycle
2566
+ */
2567
+ use(plugin) {
2568
+ this.pluginManager.use(plugin);
2569
+ return this;
2570
+ }
2571
+ /**
2572
+ * Returns a fluent, chained reference to a specific file
2573
+ */
2574
+ file(pathOrId) {
2575
+ return new DriveFileRef(this, pathOrId);
2576
+ }
2577
+ /**
2578
+ * Returns a fluent, chained reference to a specific folder
2579
+ */
2580
+ folder(pathOrId) {
2581
+ return new DriveFolderRef(this, pathOrId);
2582
+ }
1704
2583
  /**
1705
2584
  * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
1706
2585
  */
@@ -1708,9 +2587,14 @@ var init_client = __esm({
1708
2587
  if (!this.driveClient) {
1709
2588
  const auth = await this.authenticator.getAuthClient();
1710
2589
  this.driveClient = drive({ version: "v3", auth });
2590
+ if (this.options.enablePersistentCache !== false) {
2591
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2592
+ this.metadataCacheInstance.init();
2593
+ }
1711
2594
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1712
2595
  enableCache: this.options.enablePathCache ?? true,
1713
- cacheTTL: this.options.pathCacheTTL
2596
+ cacheTTL: this.options.pathCacheTTL,
2597
+ metadataCache: this.metadataCacheInstance || void 0
1714
2598
  });
1715
2599
  this.uploaderInstance = new ResumableUploader(
1716
2600
  this.driveClient,
@@ -1809,21 +2693,78 @@ var init_client = __esm({
1809
2693
  * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
1810
2694
  */
1811
2695
  async upload(options) {
2696
+ const opts = await this.pluginManager.runBeforeUpload(options);
1812
2697
  const uploader = await this.getUploader();
1813
- let parentId = options.parent;
2698
+ let parentId = opts.parent;
1814
2699
  if (parentId && parentId.startsWith("/")) {
1815
2700
  parentId = await this.mkdirp(parentId);
1816
2701
  }
1817
- if (options.overwrite && options.name && parentId) {
1818
- const existing = await this.query().inFolder(parentId).nameEquals(options.name).notTrashed().first();
2702
+ const targetName = opts.name || opts.filename;
2703
+ if (opts.overwrite && targetName && parentId) {
2704
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1819
2705
  if (existing?.id) {
1820
2706
  await this.delete(existing.id, true);
1821
2707
  }
1822
2708
  }
1823
- return await uploader.upload({
1824
- ...options,
2709
+ if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
2710
+ const localMd5 = await calculateFileMd5(opts.source);
2711
+ let existingId;
2712
+ if (this.metadataCacheInstance) {
2713
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2714
+ if (cached) existingId = cached.id;
2715
+ }
2716
+ if (!existingId) {
2717
+ const found = await this.query().md5(localMd5).notTrashed().first();
2718
+ if (found?.id) {
2719
+ existingId = found.id;
2720
+ }
2721
+ }
2722
+ if (existingId) {
2723
+ const fileName = targetName || path7.basename(opts.source);
2724
+ const raw = await this.getRawClient();
2725
+ const copyRes = await withRetry(async () => {
2726
+ return await raw.files.copy({
2727
+ fileId: existingId,
2728
+ requestBody: {
2729
+ name: fileName,
2730
+ parents: parentId ? [parentId] : void 0,
2731
+ description: opts.description
2732
+ },
2733
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2734
+ supportsAllDrives: true
2735
+ });
2736
+ });
2737
+ const file = copyRes.data;
2738
+ if (this.metadataCacheInstance && file.id) {
2739
+ this.metadataCacheInstance.upsertFile({
2740
+ id: file.id,
2741
+ name: file.name || fileName,
2742
+ mimeType: file.mimeType || "",
2743
+ size: file.size ? parseInt(file.size, 10) : void 0,
2744
+ parentId,
2745
+ md5Checksum: localMd5,
2746
+ trashed: false
2747
+ });
2748
+ }
2749
+ return await this.pluginManager.runAfterUpload(file);
2750
+ }
2751
+ }
2752
+ const uploaded = await uploader.upload({
2753
+ ...opts,
2754
+ name: targetName,
1825
2755
  parent: parentId
1826
2756
  });
2757
+ if (this.metadataCacheInstance && uploaded.id) {
2758
+ this.metadataCacheInstance.upsertFile({
2759
+ id: uploaded.id,
2760
+ name: uploaded.name || targetName || "untitled",
2761
+ mimeType: uploaded.mimeType || "",
2762
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2763
+ parentId,
2764
+ trashed: false
2765
+ });
2766
+ }
2767
+ return await this.pluginManager.runAfterUpload(uploaded);
1827
2768
  }
1828
2769
  /**
1829
2770
  * Downloads a file from Google Drive:
@@ -1833,8 +2774,10 @@ var init_client = __esm({
1833
2774
  */
1834
2775
  async download(fileIdOrPath, options = {}) {
1835
2776
  const fileId = await this.resolveId(fileIdOrPath);
2777
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
1836
2778
  const downloader = await this.getDownloader();
1837
- return await downloader.download(fileId, options);
2779
+ const result = await downloader.download(fileId, processedOpts);
2780
+ return await this.pluginManager.runAfterDownload(result);
1838
2781
  }
1839
2782
  /**
1840
2783
  * Gets file metadata
@@ -2061,16 +3004,16 @@ var init_client = __esm({
2061
3004
  durationMs: 0
2062
3005
  };
2063
3006
  const collectFiles = async (dir, base) => {
2064
- const entries = await fs5.promises.readdir(dir, { withFileTypes: true });
3007
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
2065
3008
  const files = [];
2066
3009
  for (const entry of entries) {
2067
- const fullPath = path5.join(dir, entry.name);
2068
- const relPath = path5.join(base, entry.name);
3010
+ const fullPath = path7.join(dir, entry.name);
3011
+ const relPath = path7.join(base, entry.name);
2069
3012
  if (entry.isDirectory()) {
2070
3013
  const sub = await collectFiles(fullPath, relPath);
2071
3014
  files.push(...sub);
2072
3015
  } else if (entry.isFile()) {
2073
- const stat = await fs5.promises.stat(fullPath);
3016
+ const stat = await fs6.promises.stat(fullPath);
2074
3017
  files.push({ fullPath, relPath, size: stat.size });
2075
3018
  }
2076
3019
  }
@@ -2083,11 +3026,11 @@ var init_client = __esm({
2083
3026
  if (remoteDirCache.has(relDir)) {
2084
3027
  return remoteDirCache.get(relDir);
2085
3028
  }
2086
- const parts = relDir.split(path5.sep).filter(Boolean);
3029
+ const parts = relDir.split(path7.sep).filter(Boolean);
2087
3030
  let currentParent = targetFolderId;
2088
3031
  let currentRel = "";
2089
3032
  for (const part of parts) {
2090
- currentRel = currentRel ? path5.join(currentRel, part) : part;
3033
+ currentRel = currentRel ? path7.join(currentRel, part) : part;
2091
3034
  if (remoteDirCache.has(currentRel)) {
2092
3035
  currentParent = remoteDirCache.get(currentRel);
2093
3036
  continue;
@@ -2116,8 +3059,8 @@ var init_client = __esm({
2116
3059
  };
2117
3060
  await pool.map(allFiles, async (fileItem) => {
2118
3061
  try {
2119
- const relDir = path5.dirname(fileItem.relPath);
2120
- const fileName = path5.basename(fileItem.relPath);
3062
+ const relDir = path7.dirname(fileItem.relPath);
3063
+ const fileName = path7.basename(fileItem.relPath);
2121
3064
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2122
3065
  if (options.onFileStart) {
2123
3066
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2235,6 +3178,217 @@ var init_client = __esm({
2235
3178
  const engine = new SmartSyncEngine(this.driveClient);
2236
3179
  return await engine.pullFolder(folderId, localDestinationDir, options);
2237
3180
  }
3181
+ // ==========================================
3182
+ // STREAMS & RANGE REQUESTS
3183
+ // ==========================================
3184
+ /**
3185
+ * Creates a readable stream for a file, supporting partial range requests
3186
+ */
3187
+ async createReadStream(pathOrId, options) {
3188
+ const fileId = await this.resolveId(pathOrId);
3189
+ const downloader = await this.getDownloader();
3190
+ return await downloader.createReadStream(fileId, options);
3191
+ }
3192
+ /**
3193
+ * Creates a writable stream directly into Google Drive
3194
+ */
3195
+ async createWriteStream(remotePath, options = {}) {
3196
+ await this.init();
3197
+ const { PassThrough } = await import("stream");
3198
+ const passThrough = new PassThrough();
3199
+ const remoteDir = path7.dirname(remotePath);
3200
+ const fileName = options.name || options.filename || path7.basename(remotePath);
3201
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3202
+ const mimeType = options.mimeType || "application/octet-stream";
3203
+ const raw = this.driveClient;
3204
+ raw.files.create({
3205
+ requestBody: {
3206
+ name: fileName,
3207
+ parents: [targetParentId],
3208
+ description: options.description
3209
+ },
3210
+ media: {
3211
+ mimeType,
3212
+ body: passThrough
3213
+ },
3214
+ fields: "id, name, mimeType, size, md5Checksum",
3215
+ supportsAllDrives: true
3216
+ }).then((res) => {
3217
+ if (res.data.id && this.metadataCacheInstance) {
3218
+ this.metadataCacheInstance.upsertFile({
3219
+ id: res.data.id,
3220
+ name: fileName,
3221
+ mimeType,
3222
+ parentId: targetParentId,
3223
+ path: remotePath,
3224
+ trashed: false
3225
+ });
3226
+ }
3227
+ }).catch((err) => {
3228
+ passThrough.destroy(err);
3229
+ });
3230
+ return passThrough;
3231
+ }
3232
+ // ==========================================
3233
+ // METADATA CACHE OPERATIONS
3234
+ // ==========================================
3235
+ /**
3236
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3237
+ */
3238
+ async getMetadataCache() {
3239
+ await this.init();
3240
+ return this.metadataCacheInstance;
3241
+ }
3242
+ /**
3243
+ * Returns cache statistics (total files, folders, size, last sync)
3244
+ */
3245
+ async getCacheStats() {
3246
+ await this.init();
3247
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3248
+ }
3249
+ /**
3250
+ * Clears the path and metadata cache
3251
+ */
3252
+ async clearCache() {
3253
+ await this.init();
3254
+ if (this.pathResolverInstance) {
3255
+ this.pathResolverInstance.clearCache();
3256
+ }
3257
+ }
3258
+ /**
3259
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3260
+ */
3261
+ async syncCache(options) {
3262
+ await this.init();
3263
+ if (!this.metadataCacheInstance) {
3264
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3265
+ }
3266
+ const client = this.driveClient;
3267
+ let pageToken = void 0;
3268
+ let totalScanned = 0;
3269
+ do {
3270
+ const res = await withRetry(async () => {
3271
+ return await client.files.list({
3272
+ pageSize: 1e3,
3273
+ pageToken,
3274
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3275
+ spaces: "drive",
3276
+ supportsAllDrives: true,
3277
+ includeItemsFromAllDrives: true,
3278
+ q: "trashed = false"
3279
+ });
3280
+ });
3281
+ const files = res.data.files || [];
3282
+ const entries = files.map((f) => ({
3283
+ id: f.id,
3284
+ name: f.name || "untitled",
3285
+ mimeType: f.mimeType || "",
3286
+ size: f.size ? parseInt(f.size, 10) : void 0,
3287
+ parentId: f.parents?.[0],
3288
+ md5Checksum: f.md5Checksum || void 0,
3289
+ trashed: !!f.trashed,
3290
+ modifiedTime: f.modifiedTime || void 0
3291
+ }));
3292
+ this.metadataCacheInstance.upsertFiles(entries);
3293
+ totalScanned += entries.length;
3294
+ options?.onProgress?.(totalScanned);
3295
+ pageToken = res.data.nextPageToken || void 0;
3296
+ } while (pageToken);
3297
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3298
+ return this.metadataCacheInstance.getStats();
3299
+ }
3300
+ // ==========================================
3301
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3302
+ // ==========================================
3303
+ /**
3304
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3305
+ */
3306
+ async listSharedDrives(options = {}) {
3307
+ await this.init();
3308
+ const raw = await this.getRawClient();
3309
+ const res = await withRetry(async () => {
3310
+ return await raw.drives.list({
3311
+ pageSize: options.pageSize || 100,
3312
+ fields: "drives(id, name)"
3313
+ });
3314
+ });
3315
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3316
+ }
3317
+ /**
3318
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3319
+ */
3320
+ sharedDrive(driveId) {
3321
+ return new _DriveKit({
3322
+ ...this.options,
3323
+ rootFolderId: driveId
3324
+ });
3325
+ }
3326
+ /**
3327
+ * Grants access to a specific email with custom role and notification
3328
+ */
3329
+ async grantAccess(pathOrId, options) {
3330
+ const fileId = await this.resolveId(pathOrId);
3331
+ const raw = await this.getRawClient();
3332
+ const res = await withRetry(async () => {
3333
+ return await raw.permissions.create({
3334
+ fileId,
3335
+ requestBody: {
3336
+ type: "user",
3337
+ role: options.role || "reader",
3338
+ emailAddress: options.email
3339
+ },
3340
+ sendNotificationEmail: options.notify ?? true,
3341
+ emailMessage: options.message,
3342
+ fields: "id, type, role, emailAddress, displayName",
3343
+ supportsAllDrives: true
3344
+ });
3345
+ });
3346
+ return res.data;
3347
+ }
3348
+ /**
3349
+ * Revokes access for a specific permission ID or email address
3350
+ */
3351
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3352
+ const fileId = await this.resolveId(pathOrId);
3353
+ const raw = await this.getRawClient();
3354
+ let targetId = permissionIdOrEmail;
3355
+ if (permissionIdOrEmail.includes("@")) {
3356
+ const listRes = await this.listPermissions(fileId);
3357
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3358
+ if (found && found.id) {
3359
+ targetId = found.id;
3360
+ }
3361
+ }
3362
+ await withRetry(async () => {
3363
+ return await raw.permissions.delete({
3364
+ fileId,
3365
+ permissionId: targetId,
3366
+ supportsAllDrives: true
3367
+ });
3368
+ });
3369
+ }
3370
+ /**
3371
+ * Lists all active permissions on a file or folder
3372
+ */
3373
+ async listPermissions(pathOrId) {
3374
+ const fileId = await this.resolveId(pathOrId);
3375
+ const raw = await this.getRawClient();
3376
+ const res = await withRetry(async () => {
3377
+ return await raw.permissions.list({
3378
+ fileId,
3379
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3380
+ supportsAllDrives: true
3381
+ });
3382
+ });
3383
+ return res.data.permissions || [];
3384
+ }
3385
+ /**
3386
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3387
+ */
3388
+ async serveWebDAV(options) {
3389
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3390
+ return await startWebDAVServer2(this, options);
3391
+ }
2238
3392
  /**
2239
3393
  * Calculates local file MD5 hash for integrity and deduplication checks
2240
3394
  */
@@ -2255,13 +3409,169 @@ var init_client = __esm({
2255
3409
  init_esm_shims();
2256
3410
  init_client();
2257
3411
  init_format();
2258
- import fs6 from "fs";
2259
- import path6 from "path";
3412
+ import fs7 from "fs";
3413
+ import path8 from "path";
2260
3414
  import { Command } from "commander";
2261
- import chalk from "chalk";
3415
+ import chalk2 from "chalk";
2262
3416
  import ora from "ora";
3417
+
3418
+ // src/cli/terminal-ui.ts
3419
+ init_esm_shims();
3420
+ init_format();
3421
+ import readline from "readline";
3422
+ import chalk from "chalk";
3423
+ function terminalLink(text, url2) {
3424
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
3425
+ }
3426
+ function renderFileRow(item, index) {
3427
+ const isDir = item.mimeType === "application/vnd.google-apps.folder";
3428
+ const icon = isDir ? "\u{1F4C1}" : getFileIcon(item.mimeType || "");
3429
+ const prefix = index !== void 0 ? `${chalk.dim((index + 1).toString().padStart(2, " ") + ".")} ` : "";
3430
+ let nameFormatted = isDir ? chalk.bold.blue(item.name || "untitled") : chalk.white(item.name || "untitled");
3431
+ if (item.webViewLink) {
3432
+ nameFormatted = terminalLink(nameFormatted, item.webViewLink);
3433
+ }
3434
+ const sizeFormatted = item.size ? chalk.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, " ")}]`) : chalk.dim(isDir ? "[ FOLDER ]" : "[ DOC ]");
3435
+ const idFormatted = chalk.dim(`ID: ${item.id}`);
3436
+ return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;
3437
+ }
3438
+ function getFileIcon(mimeType) {
3439
+ if (mimeType.includes("pdf")) return "\u{1F4D5}";
3440
+ if (mimeType.includes("image")) return "\u{1F5BC}\uFE0F ";
3441
+ if (mimeType.includes("video")) return "\u{1F3AC}";
3442
+ if (mimeType.includes("audio")) return "\u{1F3B5}";
3443
+ if (mimeType.includes("zip") || mimeType.includes("compressed") || mimeType.includes("tar")) return "\u{1F4E6}";
3444
+ if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return "\u{1F4CA}";
3445
+ if (mimeType.includes("document") || mimeType.includes("word")) return "\u{1F4DD}";
3446
+ if (mimeType.includes("presentation")) return "\u{1F4FD}\uFE0F ";
3447
+ if (mimeType.includes("json") || mimeType.includes("javascript") || mimeType.includes("typescript")) return "\u2699\uFE0F ";
3448
+ return "\u{1F4C4}";
3449
+ }
3450
+ async function runInteractiveExplorer(client, initialFolder = "/") {
3451
+ let currentFolder = initialFolder;
3452
+ let items = [];
3453
+ let selectedIndex = 0;
3454
+ let history = [];
3455
+ const refreshItems = async () => {
3456
+ items = await client.ls(currentFolder);
3457
+ selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));
3458
+ };
3459
+ await refreshItems();
3460
+ if (!process.stdin.isTTY) {
3461
+ console.log(chalk.yellow("Interactive explorer requires a TTY terminal. Listing items instead:"));
3462
+ for (const item of items) {
3463
+ console.log(renderFileRow(item));
3464
+ }
3465
+ return;
3466
+ }
3467
+ readline.emitKeypressEvents(process.stdin);
3468
+ process.stdin.setRawMode(true);
3469
+ const renderScreen = () => {
3470
+ console.clear();
3471
+ console.log(chalk.bold.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"));
3472
+ console.log(chalk.bold.cyan("\u2551") + chalk.bold.yellow(" \u26A1 DriveKit Interactive Terminal Explorer ") + chalk.bold.cyan("\u2551"));
3473
+ console.log(chalk.bold.cyan("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"));
3474
+ console.log(chalk.bold.cyan("\u2551") + ` \u{1F4C2} Path: ${chalk.bold.green(currentFolder.padEnd(72))} ` + chalk.bold.cyan("\u2551"));
3475
+ console.log(chalk.bold.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"));
3476
+ console.log(chalk.dim(" [\u2191/\u2193] Navigate \u2022 [Enter] Open Folder \u2022 [B] Back \u2022 [S] Share \u2022 [Q] Exit\n"));
3477
+ if (items.length === 0) {
3478
+ console.log(chalk.dim(" (This folder is empty)\n"));
3479
+ return;
3480
+ }
3481
+ const pageSize = 12;
3482
+ const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));
3483
+ const endIdx = Math.min(items.length, startIdx + pageSize);
3484
+ for (let i = startIdx; i < endIdx; i++) {
3485
+ const isSelected = i === selectedIndex;
3486
+ const cursor = isSelected ? chalk.bold.cyan(" \u25BA ") : " ";
3487
+ const row = renderFileRow(items[i]);
3488
+ if (isSelected) {
3489
+ console.log(chalk.bgHex("#1e293b")(cursor + row));
3490
+ } else {
3491
+ console.log(cursor + row);
3492
+ }
3493
+ }
3494
+ console.log(chalk.dim(`
3495
+ Item ${selectedIndex + 1} of ${items.length}`));
3496
+ };
3497
+ renderScreen();
3498
+ return new Promise((resolve) => {
3499
+ const onKeypress = async (str, key) => {
3500
+ if (key.ctrl && key.name === "c") {
3501
+ cleanup();
3502
+ process.exit(0);
3503
+ }
3504
+ if (key.name === "q" || key.name === "escape" && history.length === 0) {
3505
+ cleanup();
3506
+ resolve();
3507
+ return;
3508
+ }
3509
+ if (key.name === "up") {
3510
+ selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;
3511
+ renderScreen();
3512
+ } else if (key.name === "down") {
3513
+ selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;
3514
+ renderScreen();
3515
+ } else if (key.name === "return") {
3516
+ const item = items[selectedIndex];
3517
+ if (item && item.mimeType === "application/vnd.google-apps.folder") {
3518
+ history.push(currentFolder);
3519
+ currentFolder = currentFolder === "/" ? `/${item.name}` : `${currentFolder}/${item.name}`;
3520
+ selectedIndex = 0;
3521
+ await refreshItems();
3522
+ renderScreen();
3523
+ } else if (item && item.webViewLink) {
3524
+ const { exec: exec2 } = await import("child_process");
3525
+ const openCmd = process.platform === "darwin" ? `open "${item.webViewLink}"` : `xdg-open "${item.webViewLink}"`;
3526
+ exec2(openCmd);
3527
+ renderScreen();
3528
+ }
3529
+ } else if (key.name === "b" || key.name === "backspace") {
3530
+ if (history.length > 0) {
3531
+ currentFolder = history.pop();
3532
+ selectedIndex = 0;
3533
+ await refreshItems();
3534
+ renderScreen();
3535
+ }
3536
+ } else if (str === "s" || str === "S") {
3537
+ const item = items[selectedIndex];
3538
+ if (item && item.id) {
3539
+ process.stdin.pause();
3540
+ console.log(`
3541
+
3542
+ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}...`);
3543
+ try {
3544
+ const links = await client.sharePublic(item.id);
3545
+ console.log(`Preview URL: ${chalk.underline(links.previewLink)}`);
3546
+ console.log(`Direct Download URL: ${chalk.underline(links.directDownloadLink)}`);
3547
+ console.log(chalk.dim("\nPress any key to return to explorer..."));
3548
+ process.stdin.resume();
3549
+ process.stdin.once("data", () => {
3550
+ renderScreen();
3551
+ });
3552
+ } catch (err) {
3553
+ console.error(chalk.red(`Failed to share: ${err.message}`));
3554
+ setTimeout(renderScreen, 2e3);
3555
+ }
3556
+ }
3557
+ }
3558
+ };
3559
+ const cleanup = () => {
3560
+ process.stdin.removeListener("keypress", onKeypress);
3561
+ if (process.stdin.setRawMode) {
3562
+ process.stdin.setRawMode(false);
3563
+ }
3564
+ process.stdin.pause();
3565
+ console.clear();
3566
+ console.log(chalk.green("\u{1F44B} Exited DriveKit explorer."));
3567
+ };
3568
+ process.stdin.on("keypress", onKeypress);
3569
+ });
3570
+ }
3571
+
3572
+ // src/cli.ts
2263
3573
  var program = new Command();
2264
- program.name("drivekit").description(chalk.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3574
+ program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
2265
3575
  function getAuthConfig(cmdOptions) {
2266
3576
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
2267
3577
  const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
@@ -2284,19 +3594,19 @@ program.command("quota").description("Show Google Drive storage usage & quota").
2284
3594
  const client = await getClient(options);
2285
3595
  const quota = await client.getStorageQuota();
2286
3596
  spinner.stop();
2287
- console.log(chalk.bold.cyan("\n\u{1F4CA} Google Drive Storage Quota:"));
3597
+ console.log(chalk2.bold.cyan("\n\u{1F4CA} Google Drive Storage Quota:"));
2288
3598
  if (quota.user?.displayName) {
2289
- console.log(`\u{1F464} User: ${chalk.yellow(quota.user.displayName)} (${quota.user.emailAddress})`);
3599
+ console.log(`\u{1F464} User: ${chalk2.yellow(quota.user.displayName)} (${quota.user.emailAddress})`);
2290
3600
  }
2291
- console.log(`\u{1F4BE} Total Usage: ${chalk.green(quota.formattedUsage)} / ${chalk.blue(quota.formattedLimit)}`);
3601
+ console.log(`\u{1F4BE} Total Usage: ${chalk2.green(quota.formattedUsage)} / ${chalk2.blue(quota.formattedLimit)}`);
2292
3602
  if (quota.percentUsed !== null) {
2293
- console.log(`\u{1F4C8} Usage %: ${chalk.bold(quota.percentUsed + "%")}`);
3603
+ console.log(`\u{1F4C8} Usage %: ${chalk2.bold(quota.percentUsed + "%")}`);
2294
3604
  }
2295
3605
  console.log(`\u{1F4C1} In Drive: ${formatBytes(quota.usageInDrive)}`);
2296
3606
  console.log(`\u{1F5D1}\uFE0F In Trash: ${formatBytes(quota.usageInDriveTrash)}
2297
3607
  `);
2298
3608
  } catch (err) {
2299
- spinner.fail(chalk.red(`Failed to fetch quota: ${err.message}`));
3609
+ spinner.fail(chalk2.red(`Failed to fetch quota: ${err.message}`));
2300
3610
  process.exit(1);
2301
3611
  }
2302
3612
  });
@@ -2307,34 +3617,38 @@ program.command("ls [folder]").description("List files and folders (by virtual p
2307
3617
  const items = await client.ls(folder);
2308
3618
  spinner.stop();
2309
3619
  if (items.length === 0) {
2310
- console.log(chalk.dim(`(Folder ${folder} is empty)`));
3620
+ console.log(chalk2.dim(`(Folder ${folder} is empty)`));
2311
3621
  return;
2312
3622
  }
2313
- console.log(chalk.bold.cyan(`
3623
+ console.log(chalk2.bold.cyan(`
2314
3624
  \u{1F4C1} Contents of "${folder}":
2315
3625
  `));
2316
- for (const item of items) {
2317
- const isDir = item.mimeType === "application/vnd.google-apps.folder";
2318
- const icon = isDir ? "\u{1F4C1}" : "\u{1F4C4}";
2319
- const nameFormatted = isDir ? chalk.bold.blue(item.name) : chalk.white(item.name);
2320
- const sizeFormatted = item.size ? chalk.dim(`[${formatBytes(parseInt(item.size, 10))}]`) : chalk.dim(isDir ? "[DIR]" : "[Google Doc]");
2321
- const idFormatted = chalk.dim(`(ID: ${item.id})`);
2322
- console.log(` ${icon} ${nameFormatted.padEnd(40)} ${sizeFormatted.padEnd(16)} ${idFormatted}`);
3626
+ for (let i = 0; i < items.length; i++) {
3627
+ console.log(renderFileRow(items[i], i));
2323
3628
  }
2324
3629
  console.log(`
2325
- Total items: ${chalk.green(items.length)}
3630
+ Total items: ${chalk2.green(items.length)}
2326
3631
  `);
2327
3632
  } catch (err) {
2328
- spinner.fail(chalk.red(`Failed to list items: ${err.message}`));
3633
+ spinner.fail(chalk2.red(`Failed to list items: ${err.message}`));
3634
+ process.exit(1);
3635
+ }
3636
+ });
3637
+ program.command("explore [folder]").description("Interactive terminal keyboard file explorer (TUI) for Google Drive").action(async (folder = "/", options) => {
3638
+ try {
3639
+ const client = await getClient(options);
3640
+ await runInteractiveExplorer(client, folder);
3641
+ } catch (err) {
3642
+ console.error(chalk2.red(`Explorer failed: ${err.message}`));
2329
3643
  process.exit(1);
2330
3644
  }
2331
3645
  });
2332
- program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").action(async (localFile, remotePath = "/", options) => {
2333
- if (!fs6.existsSync(localFile)) {
2334
- console.error(chalk.red(`\u274C Local file not found: ${localFile}`));
3646
+ program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
3647
+ if (!fs7.existsSync(localFile)) {
3648
+ console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
2335
3649
  process.exit(1);
2336
3650
  }
2337
- const fileName = path6.basename(localFile);
3651
+ const fileName = path8.basename(localFile);
2338
3652
  const spinner = ora(`Preparing upload: ${fileName}...`).start();
2339
3653
  try {
2340
3654
  const client = await getClient(options);
@@ -2345,24 +3659,25 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
2345
3659
  name: fileName,
2346
3660
  parent: remotePath,
2347
3661
  overwrite: options.overwrite,
3662
+ deduplicate: options.dedup,
2348
3663
  onProgress: (p) => {
2349
3664
  process.stdout.write(
2350
- `\r\u{1F680} Uploading: ${chalk.cyan(p.percentage + "%")} | Speed: ${chalk.green(p.speedFormatted)} | ETA: ${chalk.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
3665
+ `\r\u{1F680} Uploading: ${chalk2.cyan(p.percentage + "%")} | Speed: ${chalk2.green(p.speedFormatted)} | ETA: ${chalk2.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
2351
3666
  );
2352
3667
  }
2353
3668
  });
2354
3669
  process.stdout.write("\n");
2355
3670
  const durationSecs = ((Date.now() - startTime) / 1e3).toFixed(1);
2356
- console.log(chalk.green(`
3671
+ console.log(chalk2.green(`
2357
3672
  \u2705 Upload completed successfully in ${durationSecs}s!`));
2358
- console.log(`\u{1F4C4} Name: ${chalk.bold(res.name)}`);
2359
- console.log(`\u{1F194} ID: ${chalk.cyan(res.id)}`);
3673
+ console.log(`\u{1F4C4} Name: ${chalk2.bold(res.name)}`);
3674
+ console.log(`\u{1F194} ID: ${chalk2.cyan(res.id)}`);
2360
3675
  if (res.webViewLink) {
2361
- console.log(`\u{1F517} Link: ${chalk.underline(res.webViewLink)}`);
3676
+ console.log(`\u{1F517} Link: ${chalk2.underline(res.webViewLink)}`);
2362
3677
  }
2363
3678
  console.log("");
2364
3679
  } catch (err) {
2365
- spinner.fail(chalk.red(`Upload failed: ${err.message}`));
3680
+ spinner.fail(chalk2.red(`Upload failed: ${err.message}`));
2366
3681
  process.exit(1);
2367
3682
  }
2368
3683
  });
@@ -2376,20 +3691,20 @@ program.command("download <fileIdOrPath> [destination]").description("Download a
2376
3691
  onProgress: (p) => {
2377
3692
  const pct = p.percentage !== void 0 ? `${p.percentage}%` : `${formatBytes(p.bytesRead)}`;
2378
3693
  process.stdout.write(
2379
- `\r\u2B07\uFE0F Downloading: ${chalk.cyan(pct)} | Speed: ${chalk.green(p.speedFormatted)}`
3694
+ `\r\u2B07\uFE0F Downloading: ${chalk2.cyan(pct)} | Speed: ${chalk2.green(p.speedFormatted)}`
2380
3695
  );
2381
3696
  }
2382
3697
  });
2383
3698
  process.stdout.write("\n");
2384
- console.log(chalk.green(`
3699
+ console.log(chalk2.green(`
2385
3700
  \u2705 Download completed!`));
2386
- console.log(`\u{1F4C2} Saved to: ${chalk.bold(res.filePath)}`);
3701
+ console.log(`\u{1F4C2} Saved to: ${chalk2.bold(res.filePath)}`);
2387
3702
  if (res.size) {
2388
3703
  console.log(`\u{1F4E6} Size: ${formatBytes(res.size)}`);
2389
3704
  }
2390
3705
  console.log("");
2391
3706
  } catch (err) {
2392
- spinner.fail(chalk.red(`Download failed: ${err.message}`));
3707
+ spinner.fail(chalk2.red(`Download failed: ${err.message}`));
2393
3708
  process.exit(1);
2394
3709
  }
2395
3710
  });
@@ -2403,16 +3718,16 @@ program.command("share <fileIdOrPath> [email]").description("Share file publicly
2403
3718
  type: "user",
2404
3719
  emailAddress: email
2405
3720
  });
2406
- spinner.succeed(chalk.green(`File shared with ${email} as reader!`));
3721
+ spinner.succeed(chalk2.green(`File shared with ${email} as reader!`));
2407
3722
  } else {
2408
3723
  const links = await client.sharePublic(fileIdOrPath);
2409
- spinner.succeed(chalk.green(`File is now publicly accessible to anyone with the link!`));
2410
- console.log(`\u{1F517} Preview Link: ${chalk.underline(links.previewLink)}`);
2411
- console.log(`\u{1F4E5} Direct Download Link: ${chalk.underline(links.directDownloadLink)}
3724
+ spinner.succeed(chalk2.green(`File is now publicly accessible to anyone with the link!`));
3725
+ console.log(`\u{1F517} Preview Link: ${chalk2.underline(links.previewLink)}`);
3726
+ console.log(`\u{1F4E5} Direct Download Link: ${chalk2.underline(links.directDownloadLink)}
2412
3727
  `);
2413
3728
  }
2414
3729
  } catch (err) {
2415
- spinner.fail(chalk.red(`Sharing failed: ${err.message}`));
3730
+ spinner.fail(chalk2.red(`Sharing failed: ${err.message}`));
2416
3731
  process.exit(1);
2417
3732
  }
2418
3733
  });
@@ -2422,19 +3737,19 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
2422
3737
  try {
2423
3738
  const client = await getClient(options);
2424
3739
  await client.delete(fileIdOrPath, options.permanent);
2425
- spinner.succeed(chalk.green(`Success! ${fileIdOrPath} has been ${options.permanent ? "permanently deleted" : "moved to trash"}.`));
3740
+ spinner.succeed(chalk2.green(`Success! ${fileIdOrPath} has been ${options.permanent ? "permanently deleted" : "moved to trash"}.`));
2426
3741
  } catch (err) {
2427
- spinner.fail(chalk.red(`Failed: ${err.message}`));
3742
+ spinner.fail(chalk2.red(`Failed: ${err.message}`));
2428
3743
  process.exit(1);
2429
3744
  }
2430
3745
  });
2431
3746
  program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
2432
- if (!fs6.existsSync(localDir)) {
2433
- console.error(chalk.red(`\u274C Local directory not found: ${localDir}`));
3747
+ if (!fs7.existsSync(localDir)) {
3748
+ console.error(chalk2.red(`\u274C Local directory not found: ${localDir}`));
2434
3749
  process.exit(1);
2435
3750
  }
2436
3751
  const concurrency = parseInt(options.concurrency, 10) || 4;
2437
- console.log(chalk.bold.cyan(`
3752
+ console.log(chalk2.bold.cyan(`
2438
3753
  \u26A1 Starting recursive sync:`));
2439
3754
  console.log(`\u{1F4C2} Local: ${localDir}`);
2440
3755
  console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
@@ -2448,30 +3763,30 @@ program.command("sync <localDir> <remoteFolder>").description("Sync a local dire
2448
3763
  concurrency,
2449
3764
  overwrite: options.overwrite,
2450
3765
  onFileStart: (_, rel) => {
2451
- console.log(` \u2B06\uFE0F Uploading: ${chalk.dim(rel)}`);
3766
+ console.log(` \u2B06\uFE0F Uploading: ${chalk2.dim(rel)}`);
2452
3767
  },
2453
3768
  onFileComplete: (_, fileId) => {
2454
- console.log(` ${chalk.green("\u2713 Completed")} ${chalk.dim(`(ID: ${fileId})`)}`);
3769
+ console.log(` ${chalk2.green("\u2713 Completed")} ${chalk2.dim(`(ID: ${fileId})`)}`);
2455
3770
  }
2456
3771
  });
2457
- console.log(chalk.bold.green(`
3772
+ console.log(chalk2.bold.green(`
2458
3773
  \u{1F389} Sync Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2459
- console.log(`\u2705 Uploaded: ${chalk.green(result.uploaded.length)} files (${formatBytes(result.totalBytes)})`);
3774
+ console.log(`\u2705 Uploaded: ${chalk2.green(result.uploaded.length)} files (${formatBytes(result.totalBytes)})`);
2460
3775
  if (result.failed.length > 0) {
2461
- console.log(`\u274C Failed: ${chalk.red(result.failed.length)} files`);
3776
+ console.log(`\u274C Failed: ${chalk2.red(result.failed.length)} files`);
2462
3777
  for (const f of result.failed) {
2463
- console.log(` - ${f.localPath}: ${chalk.red(f.error.message)}`);
3778
+ console.log(` - ${f.localPath}: ${chalk2.red(f.error.message)}`);
2464
3779
  }
2465
3780
  }
2466
3781
  console.log("");
2467
3782
  } catch (err) {
2468
- spinner.fail(chalk.red(`Sync failed: ${err.message}`));
3783
+ spinner.fail(chalk2.red(`Sync failed: ${err.message}`));
2469
3784
  process.exit(1);
2470
3785
  }
2471
3786
  });
2472
3787
  program.command("pull <remoteFolder> <localDir>").description("Download an entire remote Google Drive folder down to local directory with MD5 deduplication").option("-c, --concurrency <number>", "Parallel downloads", "4").option("-o, --overwrite", "Overwrite local files even if identical").action(async (remoteFolder, localDir, options) => {
2473
3788
  const concurrency = parseInt(options.concurrency, 10) || 4;
2474
- console.log(chalk.bold.cyan(`
3789
+ console.log(chalk2.bold.cyan(`
2475
3790
  \u2B07\uFE0F Starting smart pull:`));
2476
3791
  console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
2477
3792
  console.log(`\u{1F4C2} Local: ${localDir}`);
@@ -2485,24 +3800,24 @@ program.command("pull <remoteFolder> <localDir>").description("Download an entir
2485
3800
  concurrency,
2486
3801
  overwrite: options.overwrite,
2487
3802
  onFileStart: (name, rel) => {
2488
- console.log(` \u2B07\uFE0F Downloading: ${chalk.dim(rel)}`);
3803
+ console.log(` \u2B07\uFE0F Downloading: ${chalk2.dim(rel)}`);
2489
3804
  },
2490
3805
  onFileComplete: (name) => {
2491
- console.log(` ${chalk.green("\u2713 Saved")} ${name}`);
3806
+ console.log(` ${chalk2.green("\u2713 Saved")} ${name}`);
2492
3807
  }
2493
3808
  });
2494
- console.log(chalk.bold.green(`
3809
+ console.log(chalk2.bold.green(`
2495
3810
  \u{1F389} Pull Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2496
- console.log(`\u2705 Downloaded: ${chalk.green(result.downloaded.length)} files (${formatBytes(result.totalBytes)})`);
3811
+ console.log(`\u2705 Downloaded: ${chalk2.green(result.downloaded.length)} files (${formatBytes(result.totalBytes)})`);
2497
3812
  if (result.skipped.length > 0) {
2498
- console.log(`\u23ED\uFE0F Skipped: ${chalk.yellow(result.skipped.length)} identical files`);
3813
+ console.log(`\u23ED\uFE0F Skipped: ${chalk2.yellow(result.skipped.length)} identical files`);
2499
3814
  }
2500
3815
  if (result.failed.length > 0) {
2501
- console.log(`\u274C Failed: ${chalk.red(result.failed.length)} files`);
3816
+ console.log(`\u274C Failed: ${chalk2.red(result.failed.length)} files`);
2502
3817
  }
2503
3818
  console.log("");
2504
3819
  } catch (err) {
2505
- spinner.fail(chalk.red(`Pull failed: ${err.message}`));
3820
+ spinner.fail(chalk2.red(`Pull failed: ${err.message}`));
2506
3821
  process.exit(1);
2507
3822
  }
2508
3823
  });
@@ -2512,7 +3827,7 @@ program.command("clean").description("Storage management: find largest files, de
2512
3827
  if (options.emptyTrash) {
2513
3828
  const spinner2 = ora("Emptying trash bin...").start();
2514
3829
  await client.emptyTrash();
2515
- spinner2.succeed(chalk.green("Trash bin emptied successfully!"));
3830
+ spinner2.succeed(chalk2.green("Trash bin emptied successfully!"));
2516
3831
  return;
2517
3832
  }
2518
3833
  if (options.duplicates) {
@@ -2520,16 +3835,16 @@ program.command("clean").description("Storage management: find largest files, de
2520
3835
  const duplicates = await client.findDuplicates({ by: "name" });
2521
3836
  spinner2.stop();
2522
3837
  if (duplicates.length === 0) {
2523
- console.log(chalk.green("\n\u2728 No duplicate files found!"));
3838
+ console.log(chalk2.green("\n\u2728 No duplicate files found!"));
2524
3839
  return;
2525
3840
  }
2526
- console.log(chalk.bold.yellow(`
3841
+ console.log(chalk2.bold.yellow(`
2527
3842
  \u26A0\uFE0F Found ${duplicates.length} duplicate groups:
2528
3843
  `));
2529
3844
  for (const g of duplicates) {
2530
- console.log(`\u{1F4C4} "${chalk.bold(g.name)}" (${chalk.cyan(g.count + " copies")} - total: ${chalk.magenta(g.formattedTotalSize)})`);
3845
+ console.log(`\u{1F4C4} "${chalk2.bold(g.name)}" (${chalk2.cyan(g.count + " copies")} - total: ${chalk2.magenta(g.formattedTotalSize)})`);
2531
3846
  for (const f of g.files) {
2532
- console.log(` - ID: ${chalk.dim(f.id)} [${formatBytes(f.size)}] modified: ${chalk.dim(f.modifiedTime || "unknown")}`);
3847
+ console.log(` - ID: ${chalk2.dim(f.id)} [${formatBytes(f.size)}] modified: ${chalk2.dim(f.modifiedTime || "unknown")}`);
2533
3848
  }
2534
3849
  }
2535
3850
  console.log("");
@@ -2539,51 +3854,51 @@ program.command("clean").description("Storage management: find largest files, de
2539
3854
  const spinner = ora(`Finding top ${limit} largest files...`).start();
2540
3855
  const largest = await client.findLargestFiles(limit);
2541
3856
  spinner.stop();
2542
- console.log(chalk.bold.cyan(`
3857
+ console.log(chalk2.bold.cyan(`
2543
3858
  \u{1F4CA} Top ${largest.length} Largest Files in Drive:
2544
3859
  `));
2545
3860
  for (let i = 0; i < largest.length; i++) {
2546
3861
  const f = largest[i];
2547
- console.log(` ${chalk.bold(i + 1 + ".")} ${chalk.white(f.name.padEnd(35))} ${chalk.green(f.formattedSize.padEnd(12))} ID: ${chalk.dim(f.id)}`);
3862
+ console.log(` ${chalk2.bold(i + 1 + ".")} ${chalk2.white(f.name.padEnd(35))} ${chalk2.green(f.formattedSize.padEnd(12))} ID: ${chalk2.dim(f.id)}`);
2548
3863
  }
2549
3864
  console.log("");
2550
3865
  } catch (err) {
2551
- console.error(chalk.red(`Clean operation failed: ${err.message}`));
3866
+ console.error(chalk2.red(`Clean operation failed: ${err.message}`));
2552
3867
  process.exit(1);
2553
3868
  }
2554
3869
  });
2555
3870
  program.command("watch [folder]").description("Watch Google Drive or a specific folder for real-time changes").option("-i, --interval <ms>", "Polling interval in milliseconds", "5000").action(async (folder = "/", options) => {
2556
3871
  const intervalMs = parseInt(options.interval, 10) || 5e3;
2557
- console.log(chalk.bold.cyan(`
3872
+ console.log(chalk2.bold.cyan(`
2558
3873
  \u{1F440} Watching for changes in "${folder}" (polling every ${intervalMs / 1e3}s)...`));
2559
- console.log(chalk.dim("Press Ctrl+C to stop watching.\n"));
3874
+ console.log(chalk2.dim("Press Ctrl+C to stop watching.\n"));
2560
3875
  try {
2561
3876
  const client = await getClient(options);
2562
3877
  const watcher = await client.watch(folder === "/" ? void 0 : folder, { intervalMs });
2563
3878
  watcher.on("create", (e) => {
2564
- console.log(`${chalk.green("[CREATED]")} ${chalk.bold(e.file?.name || e.fileId)} ${chalk.dim(`(ID: ${e.fileId})`)}`);
3879
+ console.log(`${chalk2.green("[CREATED]")} ${chalk2.bold(e.file?.name || e.fileId)} ${chalk2.dim(`(ID: ${e.fileId})`)}`);
2565
3880
  });
2566
3881
  watcher.on("modify", (e) => {
2567
- console.log(`${chalk.yellow("[MODIFIED]")} ${chalk.bold(e.file?.name || e.fileId)} ${chalk.dim(`(ID: ${e.fileId})`)}`);
3882
+ console.log(`${chalk2.yellow("[MODIFIED]")} ${chalk2.bold(e.file?.name || e.fileId)} ${chalk2.dim(`(ID: ${e.fileId})`)}`);
2568
3883
  });
2569
3884
  watcher.on("delete", (e) => {
2570
- console.log(`${chalk.red("[DELETED]")} ${chalk.bold(e.file?.name || e.fileId)} ${chalk.dim(`(ID: ${e.fileId})`)}`);
3885
+ console.log(`${chalk2.red("[DELETED]")} ${chalk2.bold(e.file?.name || e.fileId)} ${chalk2.dim(`(ID: ${e.fileId})`)}`);
2571
3886
  });
2572
3887
  watcher.on("error", (err) => {
2573
- console.error(chalk.red(`[WATCHER ERROR] ${err.message}`));
3888
+ console.error(chalk2.red(`[WATCHER ERROR] ${err.message}`));
2574
3889
  });
2575
3890
  process.on("SIGINT", () => {
2576
3891
  watcher.stop();
2577
- console.log(chalk.yellow("\nWatcher stopped. Goodbye!"));
3892
+ console.log(chalk2.yellow("\nWatcher stopped. Goodbye!"));
2578
3893
  process.exit(0);
2579
3894
  });
2580
3895
  } catch (err) {
2581
- console.error(chalk.red(`Failed to start watcher: ${err.message}`));
3896
+ console.error(chalk2.red(`Failed to start watcher: ${err.message}`));
2582
3897
  process.exit(1);
2583
3898
  }
2584
3899
  });
2585
3900
  program.command("login").description("Interactive 1-click browser OAuth2 sign-in").requiredOption("--client-id <id>", "Google OAuth2 Client ID").requiredOption("--client-secret <secret>", "Google OAuth2 Client Secret").option("-p, --port <port>", "Local callback port", "3000").action(async (options) => {
2586
- console.log(chalk.bold.cyan("\n\u26A1 DriveKit Interactive Login"));
3901
+ console.log(chalk2.bold.cyan("\n\u26A1 DriveKit Interactive Login"));
2587
3902
  console.log("Opening your browser for one-click Google OAuth sign-in...\n");
2588
3903
  try {
2589
3904
  const { DriveKit: DriveKit2 } = await Promise.resolve().then(() => (init_client(), client_exports));
@@ -2592,17 +3907,115 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2592
3907
  clientSecret: options.clientSecret,
2593
3908
  port: parseInt(options.port, 10) || 3e3
2594
3909
  });
2595
- console.log(chalk.bold.green("\n\u{1F389} Login successful!"));
2596
- console.log(`Access Token: ${chalk.cyan(result.tokens.access_token?.slice(0, 25) + "...")}`);
3910
+ console.log(chalk2.bold.green("\n\u{1F389} Login successful!"));
3911
+ console.log(`Access Token: ${chalk2.cyan(result.tokens.access_token?.slice(0, 25) + "...")}`);
2597
3912
  if (result.tokens.refresh_token) {
2598
- console.log(`Refresh Token: ${chalk.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3913
+ console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3914
+ }
3915
+ const outPath = path8.resolve("./gdrive-tokens.json");
3916
+ fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3917
+ console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
3918
+ `);
3919
+ } catch (err) {
3920
+ console.error(chalk2.red(`Login failed: ${err.message}`));
3921
+ process.exit(1);
3922
+ }
3923
+ });
3924
+ var cacheCmd = program.command("cache").description("Manage local persistent SQLite metadata cache");
3925
+ cacheCmd.command("status").description("Display SQLite cache statistics and database path").action(async (options) => {
3926
+ try {
3927
+ const client = await getClient(options);
3928
+ const stats = await client.getCacheStats();
3929
+ if (!stats) {
3930
+ console.log(chalk2.yellow("\u26A0\uFE0F Persistent cache is disabled or not available."));
3931
+ return;
3932
+ }
3933
+ console.log(chalk2.bold.cyan("\n\u26A1 DriveKit Persistent SQLite Cache Status:"));
3934
+ console.log(`\u{1F4C1} Database Path: ${chalk2.dim(stats.databasePath)}`);
3935
+ console.log(`\u{1F4C2} Cached Folders: ${chalk2.bold.green(stats.folderCount.toLocaleString())}`);
3936
+ console.log(`\u{1F4C4} Cached Files: ${chalk2.bold.cyan(stats.fileCount.toLocaleString())}`);
3937
+ console.log(`\u{1F4BE} Indexed Size: ${chalk2.bold.white(formatBytes(stats.totalSizeBytes))}`);
3938
+ console.log(`\u{1F552} Last Full Sync: ${chalk2.dim(stats.lastSyncTime || "Never")}
3939
+ `);
3940
+ } catch (err) {
3941
+ console.error(chalk2.red(`Cache status failed: ${err.message}`));
3942
+ process.exit(1);
3943
+ }
3944
+ });
3945
+ cacheCmd.command("sync").description("Crawl Google Drive and index all file metadata into local SQLite for 0ms lookups").action(async (options) => {
3946
+ const spinner = ora("Indexing Google Drive metadata into SQLite...").start();
3947
+ try {
3948
+ const client = await getClient(options);
3949
+ const stats = await client.syncCache({
3950
+ onProgress: (scanned) => {
3951
+ spinner.text = `Indexing Google Drive metadata... (${chalk2.cyan(scanned.toLocaleString())} items scanned)`;
3952
+ }
3953
+ });
3954
+ spinner.succeed(chalk2.green(`Indexed ${stats.fileCount + stats.folderCount} items successfully!`));
3955
+ console.log(`\u{1F4BE} Database: ${chalk2.dim(stats.databasePath)}
3956
+ `);
3957
+ } catch (err) {
3958
+ spinner.fail(chalk2.red(`Cache sync failed: ${err.message}`));
3959
+ process.exit(1);
3960
+ }
3961
+ });
3962
+ cacheCmd.command("clear").description("Clear all cached metadata from local SQLite database").action(async (options) => {
3963
+ try {
3964
+ const client = await getClient(options);
3965
+ await client.clearCache();
3966
+ console.log(chalk2.green("\u{1F9F9} Local SQLite cache cleared successfully."));
3967
+ } catch (err) {
3968
+ console.error(chalk2.red(`Cache clear failed: ${err.message}`));
3969
+ process.exit(1);
3970
+ }
3971
+ });
3972
+ program.command("shared-drives").description("List accessible Google Workspace Shared Drives").action(async (options) => {
3973
+ const spinner = ora("Fetching Shared Drives...").start();
3974
+ try {
3975
+ const client = await getClient(options);
3976
+ const drives = await client.listSharedDrives();
3977
+ spinner.stop();
3978
+ if (drives.length === 0) {
3979
+ console.log(chalk2.yellow("\nNo Shared Drives found or accessible for this account.\n"));
3980
+ return;
3981
+ }
3982
+ console.log(chalk2.bold.cyan(`
3983
+ \u{1F3E2} Google Workspace Shared Drives (${drives.length}):`));
3984
+ for (const d of drives) {
3985
+ console.log(` \u{1F4C1} ${chalk2.bold.blue(d.name.padEnd(35))} ${chalk2.dim(`(ID: ${d.id})`)}`);
2599
3986
  }
2600
- const outPath = path6.resolve("./gdrive-tokens.json");
2601
- fs6.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
2602
- console.log(`\u{1F4BE} Saved tokens to: ${chalk.bold(outPath)}
3987
+ console.log("");
3988
+ } catch (err) {
3989
+ spinner.fail(chalk2.red(`Failed to list shared drives: ${err.message}`));
3990
+ process.exit(1);
3991
+ }
3992
+ });
3993
+ program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").action(async (options) => {
3994
+ try {
3995
+ const client = await getClient(options);
3996
+ const port = parseInt(options.port, 10) || 8080;
3997
+ const host = options.host || "127.0.0.1";
3998
+ console.log(chalk2.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
3999
+ console.log("Starting local WebDAV bridge to Google Drive...\n");
4000
+ const serverInstance = await client.serveWebDAV({ port, host });
4001
+ console.log(chalk2.bold.green(`\u{1F680} Server active at: ${chalk2.underline(serverInstance.url)}`));
4002
+ console.log(chalk2.white("\n\u{1F4CC} How to mount on macOS Finder:"));
4003
+ console.log(` 1. Open Finder and press ${chalk2.bold.cyan("Cmd + K")} (Connect to Server)`);
4004
+ console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}`);
4005
+ console.log(` 3. Click ${chalk2.bold("Connect")} (Connect as Guest)
2603
4006
  `);
4007
+ console.log(chalk2.white("\u{1F4CC} How to mount on Windows:"));
4008
+ console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);
4009
+ console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}
4010
+ `);
4011
+ console.log(chalk2.dim("Press Ctrl+C to stop the WebDAV server.\n"));
4012
+ process.on("SIGINT", async () => {
4013
+ await serverInstance.close();
4014
+ console.log(chalk2.yellow("\nWebDAV server stopped. Goodbye!"));
4015
+ process.exit(0);
4016
+ });
2604
4017
  } catch (err) {
2605
- console.error(chalk.red(`Login failed: ${err.message}`));
4018
+ console.error(chalk2.red(`Failed to start WebDAV server: ${err.message}`));
2606
4019
  process.exit(1);
2607
4020
  }
2608
4021
  });