drivekit 1.0.2 → 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,
@@ -919,6 +983,24 @@ var init_downloader = __esm({
919
983
  size: totalBytes
920
984
  };
921
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
+ }
922
1004
  };
923
1005
  }
924
1006
  });
@@ -1047,6 +1129,19 @@ var init_query_builder = __esm({
1047
1129
  this.conditions.push(`(${condition})`);
1048
1130
  return this;
1049
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
+ }
1050
1145
  /**
1051
1146
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1052
1147
  */
@@ -1093,6 +1188,12 @@ var init_query_builder = __esm({
1093
1188
  });
1094
1189
  return res.data.files || [];
1095
1190
  }
1191
+ /**
1192
+ * Executes query and returns array of matching files (alias for list)
1193
+ */
1194
+ async execute() {
1195
+ return await this.list();
1196
+ }
1096
1197
  /**
1097
1198
  * Returns the first matching file, or null if not found
1098
1199
  */
@@ -1734,6 +1835,22 @@ var init_resource_refs = __esm({
1734
1835
  async getLink() {
1735
1836
  return await this.drive.getShareableLink(this.pathOrId);
1736
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
+ }
1737
1854
  };
1738
1855
  DriveFolderRef = class {
1739
1856
  drive;
@@ -1771,6 +1888,15 @@ var init_resource_refs = __esm({
1771
1888
  async watch(options = {}) {
1772
1889
  return await this.drive.watch(this.pathOrId, options);
1773
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
+ }
1774
1900
  };
1775
1901
  }
1776
1902
  });
@@ -1831,13 +1957,573 @@ var init_plugins = __esm({
1831
1957
  }
1832
1958
  });
1833
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
+
1834
2520
  // src/core/client.ts
1835
2521
  var client_exports = {};
1836
2522
  __export(client_exports, {
1837
2523
  DriveKit: () => DriveKit
1838
2524
  });
1839
- import fs5 from "fs";
1840
- import path5 from "path";
2525
+ import fs6 from "fs";
2526
+ import path7 from "path";
1841
2527
  import { drive } from "@googleapis/drive";
1842
2528
  var DriveKit;
1843
2529
  var init_client = __esm({
@@ -1859,13 +2545,15 @@ var init_client = __esm({
1859
2545
  init_retry();
1860
2546
  init_format();
1861
2547
  init_mime();
1862
- DriveKit = class {
2548
+ init_cache();
2549
+ DriveKit = class _DriveKit {
1863
2550
  options;
1864
2551
  authenticator;
1865
2552
  driveClient = null;
1866
2553
  pathResolverInstance = null;
1867
2554
  uploaderInstance = null;
1868
2555
  downloaderInstance = null;
2556
+ metadataCacheInstance = null;
1869
2557
  rootFolderId;
1870
2558
  pluginManager = new PluginManager();
1871
2559
  constructor(options = {}) {
@@ -1899,9 +2587,14 @@ var init_client = __esm({
1899
2587
  if (!this.driveClient) {
1900
2588
  const auth = await this.authenticator.getAuthClient();
1901
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
+ }
1902
2594
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1903
2595
  enableCache: this.options.enablePathCache ?? true,
1904
- cacheTTL: this.options.pathCacheTTL
2596
+ cacheTTL: this.options.pathCacheTTL,
2597
+ metadataCache: this.metadataCacheInstance || void 0
1905
2598
  });
1906
2599
  this.uploaderInstance = new ResumableUploader(
1907
2600
  this.driveClient,
@@ -2006,16 +2699,71 @@ var init_client = __esm({
2006
2699
  if (parentId && parentId.startsWith("/")) {
2007
2700
  parentId = await this.mkdirp(parentId);
2008
2701
  }
2009
- if (opts.overwrite && opts.name && parentId) {
2010
- const existing = await this.query().inFolder(parentId).nameEquals(opts.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();
2011
2705
  if (existing?.id) {
2012
2706
  await this.delete(existing.id, true);
2013
2707
  }
2014
2708
  }
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
+ }
2015
2752
  const uploaded = await uploader.upload({
2016
2753
  ...opts,
2754
+ name: targetName,
2017
2755
  parent: parentId
2018
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
+ }
2019
2767
  return await this.pluginManager.runAfterUpload(uploaded);
2020
2768
  }
2021
2769
  /**
@@ -2256,16 +3004,16 @@ var init_client = __esm({
2256
3004
  durationMs: 0
2257
3005
  };
2258
3006
  const collectFiles = async (dir, base) => {
2259
- const entries = await fs5.promises.readdir(dir, { withFileTypes: true });
3007
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
2260
3008
  const files = [];
2261
3009
  for (const entry of entries) {
2262
- const fullPath = path5.join(dir, entry.name);
2263
- const relPath = path5.join(base, entry.name);
3010
+ const fullPath = path7.join(dir, entry.name);
3011
+ const relPath = path7.join(base, entry.name);
2264
3012
  if (entry.isDirectory()) {
2265
3013
  const sub = await collectFiles(fullPath, relPath);
2266
3014
  files.push(...sub);
2267
3015
  } else if (entry.isFile()) {
2268
- const stat = await fs5.promises.stat(fullPath);
3016
+ const stat = await fs6.promises.stat(fullPath);
2269
3017
  files.push({ fullPath, relPath, size: stat.size });
2270
3018
  }
2271
3019
  }
@@ -2278,11 +3026,11 @@ var init_client = __esm({
2278
3026
  if (remoteDirCache.has(relDir)) {
2279
3027
  return remoteDirCache.get(relDir);
2280
3028
  }
2281
- const parts = relDir.split(path5.sep).filter(Boolean);
3029
+ const parts = relDir.split(path7.sep).filter(Boolean);
2282
3030
  let currentParent = targetFolderId;
2283
3031
  let currentRel = "";
2284
3032
  for (const part of parts) {
2285
- currentRel = currentRel ? path5.join(currentRel, part) : part;
3033
+ currentRel = currentRel ? path7.join(currentRel, part) : part;
2286
3034
  if (remoteDirCache.has(currentRel)) {
2287
3035
  currentParent = remoteDirCache.get(currentRel);
2288
3036
  continue;
@@ -2311,8 +3059,8 @@ var init_client = __esm({
2311
3059
  };
2312
3060
  await pool.map(allFiles, async (fileItem) => {
2313
3061
  try {
2314
- const relDir = path5.dirname(fileItem.relPath);
2315
- const fileName = path5.basename(fileItem.relPath);
3062
+ const relDir = path7.dirname(fileItem.relPath);
3063
+ const fileName = path7.basename(fileItem.relPath);
2316
3064
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2317
3065
  if (options.onFileStart) {
2318
3066
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2430,6 +3178,217 @@ var init_client = __esm({
2430
3178
  const engine = new SmartSyncEngine(this.driveClient);
2431
3179
  return await engine.pullFolder(folderId, localDestinationDir, options);
2432
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
+ }
2433
3392
  /**
2434
3393
  * Calculates local file MD5 hash for integrity and deduplication checks
2435
3394
  */
@@ -2450,8 +3409,8 @@ var init_client = __esm({
2450
3409
  init_esm_shims();
2451
3410
  init_client();
2452
3411
  init_format();
2453
- import fs6 from "fs";
2454
- import path6 from "path";
3412
+ import fs7 from "fs";
3413
+ import path8 from "path";
2455
3414
  import { Command } from "commander";
2456
3415
  import chalk2 from "chalk";
2457
3416
  import ora from "ora";
@@ -2461,8 +3420,8 @@ init_esm_shims();
2461
3420
  init_format();
2462
3421
  import readline from "readline";
2463
3422
  import chalk from "chalk";
2464
- function terminalLink(text, url) {
2465
- return `\x1B]8;;${url}\x07${text}\x1B]8;;\x07`;
3423
+ function terminalLink(text, url2) {
3424
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
2466
3425
  }
2467
3426
  function renderFileRow(item, index) {
2468
3427
  const isDir = item.mimeType === "application/vnd.google-apps.folder";
@@ -2684,12 +3643,12 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
2684
3643
  process.exit(1);
2685
3644
  }
2686
3645
  });
2687
- 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) => {
2688
- if (!fs6.existsSync(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)) {
2689
3648
  console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
2690
3649
  process.exit(1);
2691
3650
  }
2692
- const fileName = path6.basename(localFile);
3651
+ const fileName = path8.basename(localFile);
2693
3652
  const spinner = ora(`Preparing upload: ${fileName}...`).start();
2694
3653
  try {
2695
3654
  const client = await getClient(options);
@@ -2700,6 +3659,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
2700
3659
  name: fileName,
2701
3660
  parent: remotePath,
2702
3661
  overwrite: options.overwrite,
3662
+ deduplicate: options.dedup,
2703
3663
  onProgress: (p) => {
2704
3664
  process.stdout.write(
2705
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)}]`
@@ -2784,7 +3744,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
2784
3744
  }
2785
3745
  });
2786
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) => {
2787
- if (!fs6.existsSync(localDir)) {
3747
+ if (!fs7.existsSync(localDir)) {
2788
3748
  console.error(chalk2.red(`\u274C Local directory not found: ${localDir}`));
2789
3749
  process.exit(1);
2790
3750
  }
@@ -2952,8 +3912,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2952
3912
  if (result.tokens.refresh_token) {
2953
3913
  console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
2954
3914
  }
2955
- const outPath = path6.resolve("./gdrive-tokens.json");
2956
- fs6.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3915
+ const outPath = path8.resolve("./gdrive-tokens.json");
3916
+ fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
2957
3917
  console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
2958
3918
  `);
2959
3919
  } catch (err) {
@@ -2961,6 +3921,104 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
2961
3921
  process.exit(1);
2962
3922
  }
2963
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})`)}`);
3986
+ }
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)
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
+ });
4017
+ } catch (err) {
4018
+ console.error(chalk2.red(`Failed to start WebDAV server: ${err.message}`));
4019
+ process.exit(1);
4020
+ }
4021
+ });
2964
4022
  function runCLI() {
2965
4023
  program.parse(process.argv);
2966
4024
  }