drivekit 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,13 +1,272 @@
1
+ var __defProp = Object.defineProperty;
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
+ });
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
16
+
17
+ // node_modules/tsup/assets/esm_shims.js
18
+ import path from "path";
19
+ import { fileURLToPath } from "url";
20
+ var init_esm_shims = __esm({
21
+ "node_modules/tsup/assets/esm_shims.js"() {
22
+ "use strict";
23
+ }
24
+ });
25
+
26
+ // src/server/webdav.ts
27
+ var webdav_exports = {};
28
+ __export(webdav_exports, {
29
+ startWebDAVServer: () => startWebDAVServer
30
+ });
31
+ import http2 from "http";
32
+ import url from "url";
33
+ import path6 from "path";
34
+ async function startWebDAVServer(drive2, options = {}) {
35
+ const port = options.port || 8080;
36
+ const host = options.host || "127.0.0.1";
37
+ await drive2.init();
38
+ const server = http2.createServer(async (req, res) => {
39
+ try {
40
+ const parsedUrl = url.parse(req.url || "/", true);
41
+ const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
42
+ const virtualPath = decodedPath === "" ? "/" : decodedPath;
43
+ switch (req.method) {
44
+ case "OPTIONS": {
45
+ res.writeHead(200, {
46
+ DAV: "1, 2",
47
+ Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
48
+ "MS-Author-Via": "DAV"
49
+ });
50
+ res.end();
51
+ return;
52
+ }
53
+ case "PROPFIND": {
54
+ const depth = req.headers["depth"] || "1";
55
+ const xml = await handlePropfind(drive2, virtualPath, depth);
56
+ res.writeHead(207, {
57
+ "Content-Type": "application/xml; charset=utf-8"
58
+ });
59
+ res.end(xml);
60
+ return;
61
+ }
62
+ case "GET":
63
+ case "HEAD": {
64
+ if (virtualPath === "/" || virtualPath === "") {
65
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
66
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
67
+ return;
68
+ }
69
+ try {
70
+ const file = await drive2.getFile(virtualPath);
71
+ if (file.mimeType === "application/vnd.google-apps.folder") {
72
+ res.writeHead(405, { "Content-Type": "text/plain" });
73
+ res.end("Cannot GET a directory");
74
+ return;
75
+ }
76
+ const stream = await drive2.createReadStream(virtualPath);
77
+ res.writeHead(200, {
78
+ "Content-Type": file.mimeType || "application/octet-stream",
79
+ "Content-Length": file.size || void 0
80
+ });
81
+ if (req.method === "HEAD") {
82
+ res.end();
83
+ } else {
84
+ stream.pipe(res);
85
+ }
86
+ } catch (e) {
87
+ res.writeHead(404, { "Content-Type": "text/plain" });
88
+ res.end("File Not Found");
89
+ }
90
+ return;
91
+ }
92
+ case "PUT": {
93
+ const remoteDir = path6.dirname(virtualPath);
94
+ const fileName = path6.basename(virtualPath);
95
+ await drive2.mkdirp(remoteDir);
96
+ const chunks = [];
97
+ req.on("data", (chunk) => chunks.push(chunk));
98
+ req.on("end", async () => {
99
+ try {
100
+ const buffer = Buffer.concat(chunks);
101
+ await drive2.upload({
102
+ source: buffer,
103
+ filename: fileName,
104
+ parent: remoteDir,
105
+ overwrite: true
106
+ });
107
+ res.writeHead(201, { "Content-Type": "text/plain" });
108
+ res.end("Created");
109
+ } catch (err) {
110
+ res.writeHead(500, { "Content-Type": "text/plain" });
111
+ res.end(err.message || "Upload failed");
112
+ }
113
+ });
114
+ return;
115
+ }
116
+ case "MKCOL": {
117
+ try {
118
+ await drive2.mkdirp(virtualPath);
119
+ res.writeHead(201, { "Content-Type": "text/plain" });
120
+ res.end("Collection Created");
121
+ } catch (err) {
122
+ res.writeHead(500, { "Content-Type": "text/plain" });
123
+ res.end(err.message);
124
+ }
125
+ return;
126
+ }
127
+ case "DELETE": {
128
+ try {
129
+ await drive2.delete(virtualPath, true);
130
+ res.writeHead(204);
131
+ res.end();
132
+ } catch (err) {
133
+ res.writeHead(404, { "Content-Type": "text/plain" });
134
+ res.end("Not Found");
135
+ }
136
+ return;
137
+ }
138
+ case "MOVE": {
139
+ const destination = req.headers["destination"];
140
+ if (!destination || typeof destination !== "string") {
141
+ res.writeHead(400, { "Content-Type": "text/plain" });
142
+ res.end("Destination header missing");
143
+ return;
144
+ }
145
+ const destUrl = url.parse(destination);
146
+ const destPath = decodeURIComponent(destUrl.pathname || "");
147
+ const newName = path6.basename(destPath);
148
+ const newParent = path6.dirname(destPath);
149
+ try {
150
+ await drive2.move(virtualPath, newParent);
151
+ if (newName !== path6.basename(virtualPath)) {
152
+ await drive2.rename(destPath, newName);
153
+ }
154
+ res.writeHead(201);
155
+ res.end("Moved");
156
+ } catch (err) {
157
+ res.writeHead(500, { "Content-Type": "text/plain" });
158
+ res.end(err.message);
159
+ }
160
+ return;
161
+ }
162
+ default: {
163
+ res.writeHead(501, { "Content-Type": "text/plain" });
164
+ res.end("Method Not Implemented");
165
+ }
166
+ }
167
+ } catch (globalErr) {
168
+ res.writeHead(500, { "Content-Type": "text/plain" });
169
+ res.end(`Internal Server Error: ${globalErr.message}`);
170
+ }
171
+ });
172
+ return new Promise((resolve) => {
173
+ server.listen(port, host, () => {
174
+ const serverUrl = `http://${host}:${port}`;
175
+ resolve({
176
+ server,
177
+ url: serverUrl,
178
+ close: () => new Promise((resClose) => server.close(() => resClose()))
179
+ });
180
+ });
181
+ });
182
+ }
183
+ async function handlePropfind(drive2, virtualPath, depth) {
184
+ const responses = [];
185
+ let isFolder = false;
186
+ let selfItem = null;
187
+ if (virtualPath === "/" || virtualPath === "") {
188
+ isFolder = true;
189
+ responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
190
+ } else {
191
+ try {
192
+ selfItem = await drive2.getFile(virtualPath);
193
+ isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
194
+ responses.push(
195
+ renderWebDAVResponse(
196
+ virtualPath,
197
+ isFolder,
198
+ selfItem.size ? parseInt(selfItem.size, 10) : 0,
199
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
200
+ )
201
+ );
202
+ } catch {
203
+ return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
204
+ }
205
+ }
206
+ if (isFolder && depth !== "0") {
207
+ try {
208
+ const children = await drive2.ls(virtualPath);
209
+ for (const child of children) {
210
+ const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
211
+ const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
212
+ responses.push(
213
+ renderWebDAVResponse(
214
+ childPath,
215
+ childIsFolder,
216
+ child.size ? parseInt(child.size, 10) : 0,
217
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
218
+ )
219
+ );
220
+ }
221
+ } catch {
222
+ }
223
+ }
224
+ return `<?xml version="1.0" encoding="utf-8"?>
225
+ <D:multistatus xmlns:D="DAV:">
226
+ ${responses.join("\n")}
227
+ </D:multistatus>`;
228
+ }
229
+ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
230
+ const encodedHref = encodeURI(href);
231
+ const resourceType = isDir ? "<D:collection/>" : "";
232
+ const dateFormatted = new Date(modifiedTime).toUTCString();
233
+ return ` <D:response>
234
+ <D:href>${encodedHref}</D:href>
235
+ <D:propstat>
236
+ <D:prop>
237
+ <D:displayname>${path6.basename(href) || "root"}</D:displayname>
238
+ <D:resourcetype>${resourceType}</D:resourcetype>
239
+ <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
240
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>
241
+ <D:status>HTTP/1.1 200 OK</D:status>
242
+ </D:prop>
243
+ <D:status>HTTP/1.1 200 OK</D:status>
244
+ </D:propstat>
245
+ </D:response>`;
246
+ }
247
+ var init_webdav = __esm({
248
+ "src/server/webdav.ts"() {
249
+ "use strict";
250
+ init_esm_shims();
251
+ }
252
+ });
253
+
254
+ // src/index.ts
255
+ init_esm_shims();
256
+
1
257
  // src/core/client.ts
2
- import fs5 from "fs";
3
- import path4 from "path";
258
+ init_esm_shims();
259
+ import fs6 from "fs";
260
+ import path7 from "path";
4
261
  import { drive } from "@googleapis/drive";
5
262
 
6
263
  // src/auth/authenticator.ts
264
+ init_esm_shims();
7
265
  import fs from "fs";
8
266
  import { auth as googleAuth } from "@googleapis/drive";
9
267
 
10
268
  // src/errors.ts
269
+ init_esm_shims();
11
270
  var DriveKitError = class extends Error {
12
271
  code;
13
272
  originalError;
@@ -148,7 +407,11 @@ var DriveAuthenticator = class {
148
407
  }
149
408
  };
150
409
 
410
+ // src/core/path-resolver.ts
411
+ init_esm_shims();
412
+
151
413
  // src/utils/mime.ts
414
+ init_esm_shims();
152
415
  import mime from "mime-types";
153
416
  var GOOGLE_WORKSPACE_MIME_TYPES = {
154
417
  DOCUMENT: "application/vnd.google-apps.document",
@@ -192,6 +455,7 @@ function isGoogleWorkspaceDoc(mimeType) {
192
455
  }
193
456
 
194
457
  // src/utils/retry.ts
458
+ init_esm_shims();
195
459
  var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
196
460
  function isRetryableError(error) {
197
461
  if (!error) return false;
@@ -248,11 +512,13 @@ var PathResolver = class {
248
512
  cache = /* @__PURE__ */ new Map();
249
513
  cacheTTL;
250
514
  enableCache;
515
+ metadataCache;
251
516
  constructor(drive2, rootFolderId = "root", options) {
252
517
  this.drive = drive2;
253
518
  this.rootFolderId = rootFolderId;
254
519
  this.enableCache = options?.enableCache ?? true;
255
520
  this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
521
+ this.metadataCache = options?.metadataCache;
256
522
  }
257
523
  /**
258
524
  * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
@@ -267,21 +533,31 @@ var PathResolver = class {
267
533
  /**
268
534
  * Gets cache key for a path
269
535
  */
270
- getCacheKey(path5) {
271
- return `${this.rootFolderId}:${this.normalizePath(path5)}`;
536
+ getCacheKey(path8) {
537
+ return `${this.rootFolderId}:${this.normalizePath(path8)}`;
272
538
  }
273
539
  /**
274
540
  * Clears the path cache
275
541
  */
276
542
  clearCache() {
277
543
  this.cache.clear();
544
+ if (this.metadataCache) {
545
+ this.metadataCache.clear();
546
+ }
278
547
  }
279
548
  /**
280
549
  * Invalidate a single path from cache
281
550
  */
282
- invalidatePath(path5) {
283
- const key = this.getCacheKey(path5);
551
+ invalidatePath(path8) {
552
+ const norm = this.normalizePath(path8);
553
+ const key = this.getCacheKey(norm);
284
554
  this.cache.delete(key);
555
+ if (this.metadataCache) {
556
+ const item = this.metadataCache.getByPath(norm);
557
+ if (item) {
558
+ this.metadataCache.deleteFile(item.id);
559
+ }
560
+ }
285
561
  }
286
562
  /**
287
563
  * Resolves a path to a Google Drive item (file or folder).
@@ -297,6 +573,17 @@ var PathResolver = class {
297
573
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
298
574
  };
299
575
  }
576
+ if (this.metadataCache) {
577
+ const persistentCached = this.metadataCache.getByPath(norm);
578
+ if (persistentCached) {
579
+ return {
580
+ id: persistentCached.id,
581
+ name: persistentCached.name,
582
+ isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
583
+ mimeType: persistentCached.mimeType
584
+ };
585
+ }
586
+ }
300
587
  if (this.enableCache) {
301
588
  const cached = this.cache.get(this.getCacheKey(norm));
302
589
  if (cached && cached.expiresAt > Date.now()) {
@@ -315,6 +602,21 @@ var PathResolver = class {
315
602
  const segment = segments[i];
316
603
  const isLast = i === segments.length - 1;
317
604
  currentPath += `/${segment}`;
605
+ if (this.metadataCache) {
606
+ const pCached = this.metadataCache.getByPath(currentPath);
607
+ if (pCached) {
608
+ currentParentId = pCached.id;
609
+ if (isLast) {
610
+ return {
611
+ id: pCached.id,
612
+ name: pCached.name,
613
+ isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
614
+ mimeType: pCached.mimeType
615
+ };
616
+ }
617
+ continue;
618
+ }
619
+ }
318
620
  if (this.enableCache) {
319
621
  const cached = this.cache.get(this.getCacheKey(currentPath));
320
622
  if (cached && cached.expiresAt > Date.now()) {
@@ -359,6 +661,16 @@ var PathResolver = class {
359
661
  }
360
662
  if (file && file.id) {
361
663
  currentParentId = file.id;
664
+ if (this.metadataCache) {
665
+ this.metadataCache.upsertFile({
666
+ id: file.id,
667
+ name: file.name || segment,
668
+ mimeType: file.mimeType || "",
669
+ parentId: currentParentId,
670
+ path: currentPath,
671
+ trashed: false
672
+ });
673
+ }
362
674
  if (this.enableCache) {
363
675
  this.cache.set(this.getCacheKey(currentPath), {
364
676
  id: file.id,
@@ -393,6 +705,16 @@ var PathResolver = class {
393
705
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
394
706
  }
395
707
  currentParentId = newFolder.id;
708
+ if (this.metadataCache) {
709
+ this.metadataCache.upsertFile({
710
+ id: newFolder.id,
711
+ name: segment,
712
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
713
+ parentId: currentParentId,
714
+ path: currentPath,
715
+ trashed: false
716
+ });
717
+ }
396
718
  if (this.enableCache) {
397
719
  this.cache.set(this.getCacheKey(currentPath), {
398
720
  id: newFolder.id,
@@ -429,10 +751,12 @@ var PathResolver = class {
429
751
  };
430
752
 
431
753
  // src/core/resumable-uploader.ts
754
+ init_esm_shims();
432
755
  import fs2 from "fs";
433
- import path from "path";
756
+ import path2 from "path";
434
757
 
435
758
  // src/utils/format.ts
759
+ init_esm_shims();
436
760
  function formatBytes(bytes, decimals = 2) {
437
761
  if (bytes === 0) return "0 B";
438
762
  const k = 1024;
@@ -492,7 +816,7 @@ var ResumableUploader = class {
492
816
  }
493
817
  const stat = await fs2.promises.stat(filePath);
494
818
  const totalBytes = stat.size;
495
- const fileName = options.name || path.basename(filePath);
819
+ const fileName = options.name || path2.basename(filePath);
496
820
  const mimeType = options.mimeType || lookupMimeType(filePath);
497
821
  return await this.chunkedUpload({
498
822
  filePath,
@@ -578,6 +902,9 @@ var ResumableUploader = class {
578
902
  let chunkIndex = 0;
579
903
  try {
580
904
  while (bytesSent < totalBytes) {
905
+ if (options.signal?.aborted) {
906
+ throw new Error("Upload aborted by user signal");
907
+ }
581
908
  chunkIndex++;
582
909
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
583
910
  const buffer = Buffer.alloc(currentChunkSize);
@@ -638,6 +965,9 @@ var ResumableUploader = class {
638
965
  const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
639
966
  let chunkIndex = 0;
640
967
  while (bytesSent < totalBytes) {
968
+ if (options.signal?.aborted) {
969
+ throw new Error("Upload aborted by user signal");
970
+ }
641
971
  chunkIndex++;
642
972
  const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
643
973
  const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
@@ -754,8 +1084,9 @@ var ResumableUploader = class {
754
1084
  };
755
1085
 
756
1086
  // src/core/downloader.ts
1087
+ init_esm_shims();
757
1088
  import fs3 from "fs";
758
- import path2 from "path";
1089
+ import path3 from "path";
759
1090
  import { pipeline } from "stream/promises";
760
1091
  import { Transform } from "stream";
761
1092
  var Downloader = class {
@@ -830,9 +1161,9 @@ var Downloader = class {
830
1161
  if (options.destination) {
831
1162
  let destPath = options.destination;
832
1163
  if (fs3.existsSync(destPath) && fs3.statSync(destPath).isDirectory()) {
833
- destPath = path2.join(destPath, finalFileName);
1164
+ destPath = path3.join(destPath, finalFileName);
834
1165
  }
835
- await fs3.promises.mkdir(path2.dirname(destPath), { recursive: true });
1166
+ await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
836
1167
  const writeStream = fs3.createWriteStream(destPath);
837
1168
  await pipeline(monitoredStream, writeStream);
838
1169
  return {
@@ -849,9 +1180,28 @@ var Downloader = class {
849
1180
  size: totalBytes
850
1181
  };
851
1182
  }
1183
+ /**
1184
+ * Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
1185
+ */
1186
+ async createReadStream(fileId, options) {
1187
+ const headers = {};
1188
+ if (options?.start !== void 0 || options?.end !== void 0) {
1189
+ const start = options.start ?? 0;
1190
+ const end = options.end !== void 0 ? options.end : "";
1191
+ headers["Range"] = `bytes=${start}-${end}`;
1192
+ }
1193
+ const res = await withRetry(async () => {
1194
+ return await this.drive.files.get(
1195
+ { fileId, alt: "media", supportsAllDrives: true },
1196
+ { responseType: "stream", headers }
1197
+ );
1198
+ });
1199
+ return res.data;
1200
+ }
852
1201
  };
853
1202
 
854
1203
  // src/core/query-builder.ts
1204
+ init_esm_shims();
855
1205
  var DriveQueryBuilder = class {
856
1206
  drive;
857
1207
  conditions = [];
@@ -968,6 +1318,19 @@ var DriveQueryBuilder = class {
968
1318
  this.conditions.push(`(${condition})`);
969
1319
  return this;
970
1320
  }
1321
+ /**
1322
+ * Custom raw query condition (alias for raw)
1323
+ */
1324
+ custom(condition) {
1325
+ return this.raw(condition);
1326
+ }
1327
+ /**
1328
+ * Filter: Exact MD5 checksum match
1329
+ */
1330
+ md5(checksum) {
1331
+ this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
1332
+ return this;
1333
+ }
971
1334
  /**
972
1335
  * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
973
1336
  */
@@ -1014,6 +1377,12 @@ var DriveQueryBuilder = class {
1014
1377
  });
1015
1378
  return res.data.files || [];
1016
1379
  }
1380
+ /**
1381
+ * Executes query and returns array of matching files (alias for list)
1382
+ */
1383
+ async execute() {
1384
+ return await this.list();
1385
+ }
1017
1386
  /**
1018
1387
  * Returns the first matching file, or null if not found
1019
1388
  */
@@ -1061,6 +1430,7 @@ var DriveQueryBuilder = class {
1061
1430
  };
1062
1431
 
1063
1432
  // src/core/concurrency-pool.ts
1433
+ init_esm_shims();
1064
1434
  var ConcurrencyPool = class {
1065
1435
  concurrency;
1066
1436
  running = 0;
@@ -1105,6 +1475,7 @@ var ConcurrencyPool = class {
1105
1475
  };
1106
1476
 
1107
1477
  // src/core/watcher.ts
1478
+ init_esm_shims();
1108
1479
  import { EventEmitter } from "events";
1109
1480
  var DriveWatcher = class extends EventEmitter {
1110
1481
  drive;
@@ -1218,6 +1589,7 @@ var DriveWatcher = class extends EventEmitter {
1218
1589
  };
1219
1590
 
1220
1591
  // src/core/storage-cleaner.ts
1592
+ init_esm_shims();
1221
1593
  var StorageCleaner = class {
1222
1594
  drive;
1223
1595
  constructor(drive2) {
@@ -1314,8 +1686,9 @@ var StorageCleaner = class {
1314
1686
  };
1315
1687
 
1316
1688
  // src/core/smart-sync.ts
1689
+ init_esm_shims();
1317
1690
  import fs4 from "fs";
1318
- import path3 from "path";
1691
+ import path4 from "path";
1319
1692
  import crypto from "crypto";
1320
1693
  async function calculateFileMd5(filePath) {
1321
1694
  return new Promise((resolve, reject) => {
@@ -1365,7 +1738,7 @@ var SmartSyncEngine = class {
1365
1738
  for (const file of files) {
1366
1739
  if (!file.id || !file.name) continue;
1367
1740
  const isFolder = file.mimeType === "application/vnd.google-apps.folder";
1368
- const fileRel = relPath ? path3.join(relPath, file.name) : file.name;
1741
+ const fileRel = relPath ? path4.join(relPath, file.name) : file.name;
1369
1742
  if (isFolder) {
1370
1743
  const sub = await collectRemoteItems(file.id, fileRel);
1371
1744
  items.push(...sub);
@@ -1386,7 +1759,7 @@ var SmartSyncEngine = class {
1386
1759
  };
1387
1760
  const remoteFiles = await collectRemoteItems(remoteFolderId, "");
1388
1761
  await pool.map(remoteFiles, async (remoteItem) => {
1389
- const localFilePath = path3.join(localDestinationDir, remoteItem.relPath);
1762
+ const localFilePath = path4.join(localDestinationDir, remoteItem.relPath);
1390
1763
  if (!options.overwrite && fs4.existsSync(localFilePath)) {
1391
1764
  const localStat = await fs4.promises.stat(localFilePath);
1392
1765
  if (remoteItem.md5Checksum) {
@@ -1439,6 +1812,7 @@ var SmartSyncEngine = class {
1439
1812
  };
1440
1813
 
1441
1814
  // src/auth/browser-login.ts
1815
+ init_esm_shims();
1442
1816
  import http from "http";
1443
1817
  import { exec } from "child_process";
1444
1818
  import { auth as googleAuth2 } from "@googleapis/drive";
@@ -1546,20 +1920,614 @@ ${authUrl}
1546
1920
  });
1547
1921
  }
1548
1922
 
1923
+ // src/core/resource-refs.ts
1924
+ init_esm_shims();
1925
+ var DriveFileRef = class {
1926
+ drive;
1927
+ pathOrId;
1928
+ constructor(drive2, pathOrId) {
1929
+ this.drive = drive2;
1930
+ this.pathOrId = pathOrId;
1931
+ }
1932
+ /** Gets file metadata */
1933
+ async get() {
1934
+ return await this.drive.getFile(this.pathOrId);
1935
+ }
1936
+ /** Checks if the file exists */
1937
+ async exists() {
1938
+ return await this.drive.exists(this.pathOrId);
1939
+ }
1940
+ /** Reads file as UTF-8 string */
1941
+ async getText() {
1942
+ return await this.drive.getText(this.pathOrId);
1943
+ }
1944
+ /** Reads and parses JSON file */
1945
+ async getJson() {
1946
+ return await this.drive.getJson(this.pathOrId);
1947
+ }
1948
+ /** Downloads the file to destination */
1949
+ async download(optionsOrDestination) {
1950
+ const opts = typeof optionsOrDestination === "string" ? { destination: optionsOrDestination } : optionsOrDestination;
1951
+ return await this.drive.download(this.pathOrId, opts);
1952
+ }
1953
+ /** Moves the file to a new folder path or ID */
1954
+ async moveTo(newParentPathOrId) {
1955
+ return await this.drive.move(this.pathOrId, newParentPathOrId);
1956
+ }
1957
+ /** Copies the file to a target directory */
1958
+ async copyTo(parentPathOrId, newName) {
1959
+ return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });
1960
+ }
1961
+ /** Renames the file */
1962
+ async rename(newName) {
1963
+ return await this.drive.rename(this.pathOrId, newName);
1964
+ }
1965
+ /** Deletes the file (or moves to trash if permanent is false) */
1966
+ async delete(permanent = false) {
1967
+ return await this.drive.delete(this.pathOrId, permanent);
1968
+ }
1969
+ /** Moves file to trash */
1970
+ async trash() {
1971
+ return await this.drive.trash(this.pathOrId);
1972
+ }
1973
+ /** Shares file */
1974
+ async share(options) {
1975
+ return await this.drive.share(this.pathOrId, options);
1976
+ }
1977
+ /** Makes file publicly accessible */
1978
+ async sharePublic(role = "reader") {
1979
+ return await this.drive.sharePublic(this.pathOrId, role);
1980
+ }
1981
+ /** Gets public/preview links */
1982
+ async getLink() {
1983
+ return await this.drive.getShareableLink(this.pathOrId);
1984
+ }
1985
+ /** Returns a ReadableStream for this file, optionally with byte Range requests */
1986
+ async createReadStream(options) {
1987
+ return await this.drive.createReadStream(this.pathOrId, options);
1988
+ }
1989
+ /** Grants access to a specific email with custom role and notification */
1990
+ async grantAccess(options) {
1991
+ return await this.drive.grantAccess(this.pathOrId, options);
1992
+ }
1993
+ /** Revokes access by permission ID or user email */
1994
+ async revokeAccess(permissionIdOrEmail) {
1995
+ return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
1996
+ }
1997
+ /** Lists all granted permissions on this file */
1998
+ async listPermissions() {
1999
+ return await this.drive.listPermissions(this.pathOrId);
2000
+ }
2001
+ };
2002
+ var DriveFolderRef = class {
2003
+ drive;
2004
+ pathOrId;
2005
+ constructor(drive2, pathOrId) {
2006
+ this.drive = drive2;
2007
+ this.pathOrId = pathOrId;
2008
+ }
2009
+ /** Lists contents of this folder */
2010
+ async ls() {
2011
+ return await this.drive.ls(this.pathOrId);
2012
+ }
2013
+ /** Ensures this folder and subpaths exist (mkdir -p) */
2014
+ async mkdirp(subPath) {
2015
+ const target = subPath ? this.pathOrId.endsWith("/") ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}` : this.pathOrId;
2016
+ return await this.drive.mkdirp(target);
2017
+ }
2018
+ /** Uploads a file directly into this folder */
2019
+ async upload(source, options = {}) {
2020
+ return await this.drive.upload({
2021
+ ...options,
2022
+ source,
2023
+ parent: this.pathOrId
2024
+ });
2025
+ }
2026
+ /** Synchronizes a local directory into this remote folder */
2027
+ async syncFrom(localDir, options = {}) {
2028
+ return await this.drive.syncFolder(localDir, this.pathOrId, options);
2029
+ }
2030
+ /** Pulls this remote folder down to local directory */
2031
+ async pullTo(localDestinationDir, options = {}) {
2032
+ return await this.drive.pull(this.pathOrId, localDestinationDir, options);
2033
+ }
2034
+ /** Watches this folder for real-time changes */
2035
+ async watch(options = {}) {
2036
+ return await this.drive.watch(this.pathOrId, options);
2037
+ }
2038
+ /** Grants access to this entire folder */
2039
+ async grantAccess(options) {
2040
+ return await this.drive.grantAccess(this.pathOrId, options);
2041
+ }
2042
+ /** Creates a writable stream directly into a file inside this folder */
2043
+ async createWriteStream(fileName, options) {
2044
+ const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
2045
+ return await this.drive.createWriteStream(targetPath, options);
2046
+ }
2047
+ };
2048
+
2049
+ // src/core/plugins.ts
2050
+ init_esm_shims();
2051
+ var PluginManager = class {
2052
+ plugins = [];
2053
+ use(plugin) {
2054
+ this.plugins.push(plugin);
2055
+ return this;
2056
+ }
2057
+ async runBeforeUpload(options) {
2058
+ let current = { ...options };
2059
+ for (const plugin of this.plugins) {
2060
+ if (plugin.beforeUpload) {
2061
+ const modified = await plugin.beforeUpload(current);
2062
+ if (modified) current = modified;
2063
+ }
2064
+ }
2065
+ return current;
2066
+ }
2067
+ async runAfterUpload(file) {
2068
+ let current = file;
2069
+ for (const plugin of this.plugins) {
2070
+ if (plugin.afterUpload) {
2071
+ const modified = await plugin.afterUpload(current);
2072
+ if (modified) current = modified;
2073
+ }
2074
+ }
2075
+ return current;
2076
+ }
2077
+ async runBeforeDownload(fileId, options) {
2078
+ let current = { ...options };
2079
+ for (const plugin of this.plugins) {
2080
+ if (plugin.beforeDownload) {
2081
+ const modified = await plugin.beforeDownload(fileId, current);
2082
+ if (modified) current = modified;
2083
+ }
2084
+ }
2085
+ return current;
2086
+ }
2087
+ async runAfterDownload(result) {
2088
+ let current = result;
2089
+ for (const plugin of this.plugins) {
2090
+ if (plugin.afterDownload) {
2091
+ const modified = await plugin.afterDownload(current);
2092
+ if (modified) current = modified;
2093
+ }
2094
+ }
2095
+ return current;
2096
+ }
2097
+ };
2098
+ function createWebhookPlugin(options) {
2099
+ const events = options.events || ["upload"];
2100
+ return {
2101
+ name: "drivekit-official-webhook",
2102
+ async afterUpload(file) {
2103
+ if (!events.includes("upload")) return;
2104
+ try {
2105
+ await fetch(options.url, {
2106
+ method: "POST",
2107
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2108
+ body: JSON.stringify({
2109
+ event: "drivekit:upload",
2110
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2111
+ file: {
2112
+ id: file.id,
2113
+ name: file.name,
2114
+ size: file.size,
2115
+ mimeType: file.mimeType
2116
+ }
2117
+ })
2118
+ });
2119
+ } catch (e) {
2120
+ }
2121
+ },
2122
+ async afterDownload(result) {
2123
+ if (!events.includes("download")) return;
2124
+ try {
2125
+ await fetch(options.url, {
2126
+ method: "POST",
2127
+ headers: { "Content-Type": "application/json", ...options.headers || {} },
2128
+ body: JSON.stringify({
2129
+ event: "drivekit:download",
2130
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2131
+ file: {
2132
+ name: result.name,
2133
+ size: result.size
2134
+ }
2135
+ })
2136
+ });
2137
+ } catch (e) {
2138
+ }
2139
+ }
2140
+ };
2141
+ }
2142
+ function createAutoNamePlugin(options) {
2143
+ return {
2144
+ name: "drivekit-official-autoname",
2145
+ beforeUpload(opts) {
2146
+ let name = opts.filename;
2147
+ if (!name && typeof opts.source === "string") {
2148
+ const pathModule2 = __require("path");
2149
+ name = pathModule2.basename(opts.source);
2150
+ }
2151
+ if (!name) return opts;
2152
+ const pathModule = __require("path");
2153
+ const ext = pathModule.extname(name);
2154
+ const base = pathModule.basename(name, ext);
2155
+ let finalName = base;
2156
+ if (options.prefix) finalName = `${options.prefix}${finalName}`;
2157
+ if (options.appendTimestamp) {
2158
+ finalName = `${finalName}_${Date.now()}`;
2159
+ }
2160
+ if (options.suffix) finalName = `${finalName}${options.suffix}`;
2161
+ finalName = `${finalName}${ext}`;
2162
+ return {
2163
+ ...opts,
2164
+ filename: finalName
2165
+ };
2166
+ }
2167
+ };
2168
+ }
2169
+
2170
+ // src/core/cache.ts
2171
+ init_esm_shims();
2172
+ import os from "os";
2173
+ import path5 from "path";
2174
+ import fs5 from "fs";
2175
+ var SqliteMetadataCache = class {
2176
+ db = null;
2177
+ dbPath;
2178
+ initialized = false;
2179
+ fallbackMemory;
2180
+ constructor(customPath) {
2181
+ if (customPath) {
2182
+ this.dbPath = customPath;
2183
+ } else {
2184
+ const dir = path5.join(os.homedir(), ".drivekit");
2185
+ if (!fs5.existsSync(dir)) {
2186
+ try {
2187
+ fs5.mkdirSync(dir, { recursive: true });
2188
+ } catch {
2189
+ }
2190
+ }
2191
+ this.dbPath = path5.join(dir, "cache.db");
2192
+ }
2193
+ }
2194
+ init() {
2195
+ if (this.initialized) return;
2196
+ try {
2197
+ const { DatabaseSync } = __require("sqlite");
2198
+ if (!DatabaseSync) {
2199
+ throw new Error("DatabaseSync not available");
2200
+ }
2201
+ this.db = new DatabaseSync(this.dbPath);
2202
+ this.db.exec(`
2203
+ PRAGMA journal_mode = WAL;
2204
+ PRAGMA synchronous = NORMAL;
2205
+
2206
+ CREATE TABLE IF NOT EXISTS files (
2207
+ id TEXT PRIMARY KEY,
2208
+ name TEXT NOT NULL,
2209
+ mimeType TEXT NOT NULL,
2210
+ size INTEGER,
2211
+ parentId TEXT,
2212
+ path TEXT,
2213
+ md5Checksum TEXT,
2214
+ trashed INTEGER DEFAULT 0,
2215
+ modifiedTime TEXT,
2216
+ updatedAt INTEGER
2217
+ );
2218
+
2219
+ CREATE TABLE IF NOT EXISTS meta (
2220
+ key TEXT PRIMARY KEY,
2221
+ value TEXT NOT NULL
2222
+ );
2223
+
2224
+ CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
2225
+ CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
2226
+ CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
2227
+ CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
2228
+ `);
2229
+ this.initialized = true;
2230
+ } catch (err) {
2231
+ this.fallbackMemory = new MemoryMetadataCache();
2232
+ this.fallbackMemory.init();
2233
+ this.initialized = true;
2234
+ this.db = null;
2235
+ }
2236
+ }
2237
+ getById(id) {
2238
+ if (this.fallbackMemory) return this.fallbackMemory.getById(id);
2239
+ if (!this.initialized || !this.db) return null;
2240
+ const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
2241
+ const row = stmt.get(id);
2242
+ return row ? this.mapRow(row) : null;
2243
+ }
2244
+ getByPath(normalizedPath) {
2245
+ if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
2246
+ if (!this.initialized || !this.db) return null;
2247
+ const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
2248
+ const row = stmt.get(normalizedPath);
2249
+ return row ? this.mapRow(row) : null;
2250
+ }
2251
+ getChildren(parentId) {
2252
+ if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
2253
+ if (!this.initialized || !this.db) return [];
2254
+ const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
2255
+ const rows = stmt.all(parentId);
2256
+ return rows.map((r) => this.mapRow(r));
2257
+ }
2258
+ findByMd5(md5) {
2259
+ if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
2260
+ if (!this.initialized || !this.db || !md5) return null;
2261
+ const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
2262
+ const row = stmt.get(md5.toLowerCase());
2263
+ return row ? this.mapRow(row) : null;
2264
+ }
2265
+ searchByName(query) {
2266
+ if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
2267
+ if (!this.initialized || !this.db) return [];
2268
+ const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
2269
+ const rows = stmt.all(`%${query}%`);
2270
+ return rows.map((r) => this.mapRow(r));
2271
+ }
2272
+ upsertFile(entry) {
2273
+ if (this.fallbackMemory) {
2274
+ this.fallbackMemory.upsertFile(entry);
2275
+ return;
2276
+ }
2277
+ if (!this.initialized || !this.db) return;
2278
+ const stmt = this.db.prepare(`
2279
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2280
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2281
+ ON CONFLICT(id) DO UPDATE SET
2282
+ name = excluded.name,
2283
+ mimeType = excluded.mimeType,
2284
+ size = excluded.size,
2285
+ parentId = excluded.parentId,
2286
+ path = COALESCE(excluded.path, files.path),
2287
+ md5Checksum = excluded.md5Checksum,
2288
+ trashed = excluded.trashed,
2289
+ modifiedTime = excluded.modifiedTime,
2290
+ updatedAt = excluded.updatedAt
2291
+ `);
2292
+ stmt.run(
2293
+ entry.id,
2294
+ entry.name,
2295
+ entry.mimeType,
2296
+ entry.size ?? null,
2297
+ entry.parentId ?? null,
2298
+ entry.path ?? null,
2299
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2300
+ entry.trashed ? 1 : 0,
2301
+ entry.modifiedTime ?? null,
2302
+ entry.updatedAt ?? Date.now()
2303
+ );
2304
+ }
2305
+ upsertFiles(entries) {
2306
+ if (this.fallbackMemory) {
2307
+ this.fallbackMemory.upsertFiles(entries);
2308
+ return;
2309
+ }
2310
+ if (!this.initialized || !this.db || entries.length === 0) return;
2311
+ this.db.exec("BEGIN TRANSACTION;");
2312
+ try {
2313
+ for (const entry of entries) {
2314
+ this.upsertFile(entry);
2315
+ }
2316
+ this.db.exec("COMMIT;");
2317
+ } catch (e) {
2318
+ this.db.exec("ROLLBACK;");
2319
+ throw e;
2320
+ }
2321
+ }
2322
+ deleteFile(id) {
2323
+ if (this.fallbackMemory) {
2324
+ this.fallbackMemory.deleteFile(id);
2325
+ return;
2326
+ }
2327
+ if (!this.initialized || !this.db) return;
2328
+ const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2329
+ stmt.run(id);
2330
+ }
2331
+ clear() {
2332
+ if (this.fallbackMemory) {
2333
+ this.fallbackMemory.clear();
2334
+ return;
2335
+ }
2336
+ if (!this.initialized || !this.db) return;
2337
+ this.db.exec("DELETE FROM files; DELETE FROM meta;");
2338
+ }
2339
+ getMeta(key) {
2340
+ if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
2341
+ if (!this.initialized || !this.db) return null;
2342
+ const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
2343
+ const row = stmt.get(key);
2344
+ return row ? row.value : null;
2345
+ }
2346
+ setMeta(key, value) {
2347
+ if (this.fallbackMemory) {
2348
+ this.fallbackMemory.setMeta(key, value);
2349
+ return;
2350
+ }
2351
+ if (!this.initialized || !this.db) return;
2352
+ const stmt = this.db.prepare(`
2353
+ INSERT INTO meta (key, value) VALUES (?, ?)
2354
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value
2355
+ `);
2356
+ stmt.run(key, value);
2357
+ }
2358
+ getStats() {
2359
+ if (this.fallbackMemory) return this.fallbackMemory.getStats();
2360
+ if (!this.initialized || !this.db) {
2361
+ return {
2362
+ fileCount: 0,
2363
+ folderCount: 0,
2364
+ totalSizeBytes: 0,
2365
+ lastSyncTime: null,
2366
+ databasePath: this.dbPath
2367
+ };
2368
+ }
2369
+ const fileCountRow = this.db.prepare(
2370
+ "SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
2371
+ ).get();
2372
+ const folderCountRow = this.db.prepare(
2373
+ "SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
2374
+ ).get();
2375
+ const totalSizeRow = this.db.prepare(
2376
+ "SELECT SUM(size) as total FROM files WHERE trashed = 0"
2377
+ ).get();
2378
+ const lastSync = this.getMeta("last_sync_timestamp");
2379
+ return {
2380
+ fileCount: fileCountRow?.count || 0,
2381
+ folderCount: folderCountRow?.count || 0,
2382
+ totalSizeBytes: totalSizeRow?.total || 0,
2383
+ lastSyncTime: lastSync,
2384
+ databasePath: this.dbPath
2385
+ };
2386
+ }
2387
+ close() {
2388
+ if (this.fallbackMemory) {
2389
+ this.fallbackMemory.close();
2390
+ this.fallbackMemory = void 0;
2391
+ }
2392
+ if (this.db) {
2393
+ try {
2394
+ this.db.close();
2395
+ } catch {
2396
+ }
2397
+ this.initialized = false;
2398
+ this.db = null;
2399
+ }
2400
+ }
2401
+ mapRow(row) {
2402
+ return {
2403
+ id: row.id,
2404
+ name: row.name,
2405
+ mimeType: row.mimeType,
2406
+ size: row.size != null ? Number(row.size) : void 0,
2407
+ parentId: row.parentId || void 0,
2408
+ path: row.path || void 0,
2409
+ md5Checksum: row.md5Checksum || void 0,
2410
+ trashed: row.trashed === 1,
2411
+ modifiedTime: row.modifiedTime || void 0,
2412
+ updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
2413
+ };
2414
+ }
2415
+ };
2416
+ var MemoryMetadataCache = class {
2417
+ files = /* @__PURE__ */ new Map();
2418
+ meta = /* @__PURE__ */ new Map();
2419
+ init() {
2420
+ }
2421
+ getById(id) {
2422
+ return this.files.get(id) || null;
2423
+ }
2424
+ getByPath(normalizedPath) {
2425
+ for (const f of this.files.values()) {
2426
+ if (f.path === normalizedPath && !f.trashed) return f;
2427
+ }
2428
+ return null;
2429
+ }
2430
+ getChildren(parentId) {
2431
+ const list = [];
2432
+ for (const f of this.files.values()) {
2433
+ if (f.parentId === parentId && !f.trashed) list.push(f);
2434
+ }
2435
+ return list;
2436
+ }
2437
+ findByMd5(md5) {
2438
+ const target = md5.toLowerCase();
2439
+ for (const f of this.files.values()) {
2440
+ if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
2441
+ }
2442
+ return null;
2443
+ }
2444
+ searchByName(query) {
2445
+ const q = query.toLowerCase();
2446
+ const list = [];
2447
+ for (const f of this.files.values()) {
2448
+ if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
2449
+ }
2450
+ return list;
2451
+ }
2452
+ upsertFile(entry) {
2453
+ this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
2454
+ }
2455
+ upsertFiles(entries) {
2456
+ for (const e of entries) this.upsertFile(e);
2457
+ }
2458
+ deleteFile(id) {
2459
+ this.files.delete(id);
2460
+ }
2461
+ clear() {
2462
+ this.files.clear();
2463
+ this.meta.clear();
2464
+ }
2465
+ getMeta(key) {
2466
+ return this.meta.get(key) || null;
2467
+ }
2468
+ setMeta(key, value) {
2469
+ this.meta.set(key, value);
2470
+ }
2471
+ getStats() {
2472
+ let fileCount = 0;
2473
+ let folderCount = 0;
2474
+ let totalSizeBytes = 0;
2475
+ for (const f of this.files.values()) {
2476
+ if (f.trashed) continue;
2477
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2478
+ else {
2479
+ fileCount++;
2480
+ totalSizeBytes += f.size || 0;
2481
+ }
2482
+ }
2483
+ return {
2484
+ fileCount,
2485
+ folderCount,
2486
+ totalSizeBytes,
2487
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2488
+ databasePath: ":memory:"
2489
+ };
2490
+ }
2491
+ close() {
2492
+ this.clear();
2493
+ }
2494
+ };
2495
+
1549
2496
  // src/core/client.ts
1550
- var DriveKit = class {
2497
+ var DriveKit = class _DriveKit {
1551
2498
  options;
1552
2499
  authenticator;
1553
2500
  driveClient = null;
1554
2501
  pathResolverInstance = null;
1555
2502
  uploaderInstance = null;
1556
2503
  downloaderInstance = null;
2504
+ metadataCacheInstance = null;
1557
2505
  rootFolderId;
2506
+ pluginManager = new PluginManager();
1558
2507
  constructor(options = {}) {
1559
2508
  this.options = options;
1560
2509
  this.rootFolderId = options.rootFolderId || "root";
1561
2510
  this.authenticator = new DriveAuthenticator(options.auth);
1562
2511
  }
2512
+ /**
2513
+ * Registers a middleware plugin into DriveKit lifecycle
2514
+ */
2515
+ use(plugin) {
2516
+ this.pluginManager.use(plugin);
2517
+ return this;
2518
+ }
2519
+ /**
2520
+ * Returns a fluent, chained reference to a specific file
2521
+ */
2522
+ file(pathOrId) {
2523
+ return new DriveFileRef(this, pathOrId);
2524
+ }
2525
+ /**
2526
+ * Returns a fluent, chained reference to a specific folder
2527
+ */
2528
+ folder(pathOrId) {
2529
+ return new DriveFolderRef(this, pathOrId);
2530
+ }
1563
2531
  /**
1564
2532
  * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
1565
2533
  */
@@ -1567,9 +2535,14 @@ var DriveKit = class {
1567
2535
  if (!this.driveClient) {
1568
2536
  const auth = await this.authenticator.getAuthClient();
1569
2537
  this.driveClient = drive({ version: "v3", auth });
2538
+ if (this.options.enablePersistentCache !== false) {
2539
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2540
+ this.metadataCacheInstance.init();
2541
+ }
1570
2542
  this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1571
2543
  enableCache: this.options.enablePathCache ?? true,
1572
- cacheTTL: this.options.pathCacheTTL
2544
+ cacheTTL: this.options.pathCacheTTL,
2545
+ metadataCache: this.metadataCacheInstance || void 0
1573
2546
  });
1574
2547
  this.uploaderInstance = new ResumableUploader(
1575
2548
  this.driveClient,
@@ -1668,21 +2641,78 @@ var DriveKit = class {
1668
2641
  * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
1669
2642
  */
1670
2643
  async upload(options) {
2644
+ const opts = await this.pluginManager.runBeforeUpload(options);
1671
2645
  const uploader = await this.getUploader();
1672
- let parentId = options.parent;
2646
+ let parentId = opts.parent;
1673
2647
  if (parentId && parentId.startsWith("/")) {
1674
2648
  parentId = await this.mkdirp(parentId);
1675
2649
  }
1676
- if (options.overwrite && options.name && parentId) {
1677
- const existing = await this.query().inFolder(parentId).nameEquals(options.name).notTrashed().first();
2650
+ const targetName = opts.name || opts.filename;
2651
+ if (opts.overwrite && targetName && parentId) {
2652
+ const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
1678
2653
  if (existing?.id) {
1679
2654
  await this.delete(existing.id, true);
1680
2655
  }
1681
2656
  }
1682
- return await uploader.upload({
1683
- ...options,
2657
+ if (opts.deduplicate && typeof opts.source === "string" && fs6.existsSync(opts.source)) {
2658
+ const localMd5 = await calculateFileMd5(opts.source);
2659
+ let existingId;
2660
+ if (this.metadataCacheInstance) {
2661
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
2662
+ if (cached) existingId = cached.id;
2663
+ }
2664
+ if (!existingId) {
2665
+ const found = await this.query().md5(localMd5).notTrashed().first();
2666
+ if (found?.id) {
2667
+ existingId = found.id;
2668
+ }
2669
+ }
2670
+ if (existingId) {
2671
+ const fileName = targetName || path7.basename(opts.source);
2672
+ const raw = await this.getRawClient();
2673
+ const copyRes = await withRetry(async () => {
2674
+ return await raw.files.copy({
2675
+ fileId: existingId,
2676
+ requestBody: {
2677
+ name: fileName,
2678
+ parents: parentId ? [parentId] : void 0,
2679
+ description: opts.description
2680
+ },
2681
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2682
+ supportsAllDrives: true
2683
+ });
2684
+ });
2685
+ const file = copyRes.data;
2686
+ if (this.metadataCacheInstance && file.id) {
2687
+ this.metadataCacheInstance.upsertFile({
2688
+ id: file.id,
2689
+ name: file.name || fileName,
2690
+ mimeType: file.mimeType || "",
2691
+ size: file.size ? parseInt(file.size, 10) : void 0,
2692
+ parentId,
2693
+ md5Checksum: localMd5,
2694
+ trashed: false
2695
+ });
2696
+ }
2697
+ return await this.pluginManager.runAfterUpload(file);
2698
+ }
2699
+ }
2700
+ const uploaded = await uploader.upload({
2701
+ ...opts,
2702
+ name: targetName,
1684
2703
  parent: parentId
1685
2704
  });
2705
+ if (this.metadataCacheInstance && uploaded.id) {
2706
+ this.metadataCacheInstance.upsertFile({
2707
+ id: uploaded.id,
2708
+ name: uploaded.name || targetName || "untitled",
2709
+ mimeType: uploaded.mimeType || "",
2710
+ size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2711
+ parentId,
2712
+ trashed: false
2713
+ });
2714
+ }
2715
+ return await this.pluginManager.runAfterUpload(uploaded);
1686
2716
  }
1687
2717
  /**
1688
2718
  * Downloads a file from Google Drive:
@@ -1692,8 +2722,10 @@ var DriveKit = class {
1692
2722
  */
1693
2723
  async download(fileIdOrPath, options = {}) {
1694
2724
  const fileId = await this.resolveId(fileIdOrPath);
2725
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
1695
2726
  const downloader = await this.getDownloader();
1696
- return await downloader.download(fileId, options);
2727
+ const result = await downloader.download(fileId, processedOpts);
2728
+ return await this.pluginManager.runAfterDownload(result);
1697
2729
  }
1698
2730
  /**
1699
2731
  * Gets file metadata
@@ -1920,16 +2952,16 @@ var DriveKit = class {
1920
2952
  durationMs: 0
1921
2953
  };
1922
2954
  const collectFiles = async (dir, base) => {
1923
- const entries = await fs5.promises.readdir(dir, { withFileTypes: true });
2955
+ const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
1924
2956
  const files = [];
1925
2957
  for (const entry of entries) {
1926
- const fullPath = path4.join(dir, entry.name);
1927
- const relPath = path4.join(base, entry.name);
2958
+ const fullPath = path7.join(dir, entry.name);
2959
+ const relPath = path7.join(base, entry.name);
1928
2960
  if (entry.isDirectory()) {
1929
2961
  const sub = await collectFiles(fullPath, relPath);
1930
2962
  files.push(...sub);
1931
2963
  } else if (entry.isFile()) {
1932
- const stat = await fs5.promises.stat(fullPath);
2964
+ const stat = await fs6.promises.stat(fullPath);
1933
2965
  files.push({ fullPath, relPath, size: stat.size });
1934
2966
  }
1935
2967
  }
@@ -1942,11 +2974,11 @@ var DriveKit = class {
1942
2974
  if (remoteDirCache.has(relDir)) {
1943
2975
  return remoteDirCache.get(relDir);
1944
2976
  }
1945
- const parts = relDir.split(path4.sep).filter(Boolean);
2977
+ const parts = relDir.split(path7.sep).filter(Boolean);
1946
2978
  let currentParent = targetFolderId;
1947
2979
  let currentRel = "";
1948
2980
  for (const part of parts) {
1949
- currentRel = currentRel ? path4.join(currentRel, part) : part;
2981
+ currentRel = currentRel ? path7.join(currentRel, part) : part;
1950
2982
  if (remoteDirCache.has(currentRel)) {
1951
2983
  currentParent = remoteDirCache.get(currentRel);
1952
2984
  continue;
@@ -1975,8 +3007,8 @@ var DriveKit = class {
1975
3007
  };
1976
3008
  await pool.map(allFiles, async (fileItem) => {
1977
3009
  try {
1978
- const relDir = path4.dirname(fileItem.relPath);
1979
- const fileName = path4.basename(fileItem.relPath);
3010
+ const relDir = path7.dirname(fileItem.relPath);
3011
+ const fileName = path7.basename(fileItem.relPath);
1980
3012
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
1981
3013
  if (options.onFileStart) {
1982
3014
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -2094,6 +3126,217 @@ var DriveKit = class {
2094
3126
  const engine = new SmartSyncEngine(this.driveClient);
2095
3127
  return await engine.pullFolder(folderId, localDestinationDir, options);
2096
3128
  }
3129
+ // ==========================================
3130
+ // STREAMS & RANGE REQUESTS
3131
+ // ==========================================
3132
+ /**
3133
+ * Creates a readable stream for a file, supporting partial range requests
3134
+ */
3135
+ async createReadStream(pathOrId, options) {
3136
+ const fileId = await this.resolveId(pathOrId);
3137
+ const downloader = await this.getDownloader();
3138
+ return await downloader.createReadStream(fileId, options);
3139
+ }
3140
+ /**
3141
+ * Creates a writable stream directly into Google Drive
3142
+ */
3143
+ async createWriteStream(remotePath, options = {}) {
3144
+ await this.init();
3145
+ const { PassThrough } = await import("stream");
3146
+ const passThrough = new PassThrough();
3147
+ const remoteDir = path7.dirname(remotePath);
3148
+ const fileName = options.name || options.filename || path7.basename(remotePath);
3149
+ const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3150
+ const mimeType = options.mimeType || "application/octet-stream";
3151
+ const raw = this.driveClient;
3152
+ raw.files.create({
3153
+ requestBody: {
3154
+ name: fileName,
3155
+ parents: [targetParentId],
3156
+ description: options.description
3157
+ },
3158
+ media: {
3159
+ mimeType,
3160
+ body: passThrough
3161
+ },
3162
+ fields: "id, name, mimeType, size, md5Checksum",
3163
+ supportsAllDrives: true
3164
+ }).then((res) => {
3165
+ if (res.data.id && this.metadataCacheInstance) {
3166
+ this.metadataCacheInstance.upsertFile({
3167
+ id: res.data.id,
3168
+ name: fileName,
3169
+ mimeType,
3170
+ parentId: targetParentId,
3171
+ path: remotePath,
3172
+ trashed: false
3173
+ });
3174
+ }
3175
+ }).catch((err) => {
3176
+ passThrough.destroy(err);
3177
+ });
3178
+ return passThrough;
3179
+ }
3180
+ // ==========================================
3181
+ // METADATA CACHE OPERATIONS
3182
+ // ==========================================
3183
+ /**
3184
+ * Returns the active persistent metadata cache instance (SQLite/Memory)
3185
+ */
3186
+ async getMetadataCache() {
3187
+ await this.init();
3188
+ return this.metadataCacheInstance;
3189
+ }
3190
+ /**
3191
+ * Returns cache statistics (total files, folders, size, last sync)
3192
+ */
3193
+ async getCacheStats() {
3194
+ await this.init();
3195
+ return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
3196
+ }
3197
+ /**
3198
+ * Clears the path and metadata cache
3199
+ */
3200
+ async clearCache() {
3201
+ await this.init();
3202
+ if (this.pathResolverInstance) {
3203
+ this.pathResolverInstance.clearCache();
3204
+ }
3205
+ }
3206
+ /**
3207
+ * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
3208
+ */
3209
+ async syncCache(options) {
3210
+ await this.init();
3211
+ if (!this.metadataCacheInstance) {
3212
+ throw new Error("Persistent cache is disabled on this DriveKit instance");
3213
+ }
3214
+ const client = this.driveClient;
3215
+ let pageToken = void 0;
3216
+ let totalScanned = 0;
3217
+ do {
3218
+ const res = await withRetry(async () => {
3219
+ return await client.files.list({
3220
+ pageSize: 1e3,
3221
+ pageToken,
3222
+ fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
3223
+ spaces: "drive",
3224
+ supportsAllDrives: true,
3225
+ includeItemsFromAllDrives: true,
3226
+ q: "trashed = false"
3227
+ });
3228
+ });
3229
+ const files = res.data.files || [];
3230
+ const entries = files.map((f) => ({
3231
+ id: f.id,
3232
+ name: f.name || "untitled",
3233
+ mimeType: f.mimeType || "",
3234
+ size: f.size ? parseInt(f.size, 10) : void 0,
3235
+ parentId: f.parents?.[0],
3236
+ md5Checksum: f.md5Checksum || void 0,
3237
+ trashed: !!f.trashed,
3238
+ modifiedTime: f.modifiedTime || void 0
3239
+ }));
3240
+ this.metadataCacheInstance.upsertFiles(entries);
3241
+ totalScanned += entries.length;
3242
+ options?.onProgress?.(totalScanned);
3243
+ pageToken = res.data.nextPageToken || void 0;
3244
+ } while (pageToken);
3245
+ this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3246
+ return this.metadataCacheInstance.getStats();
3247
+ }
3248
+ // ==========================================
3249
+ // SHARED DRIVES & ENTERPRISE PERMISSIONS
3250
+ // ==========================================
3251
+ /**
3252
+ * Lists all Google Workspace Shared Drives accessible by current user or service account
3253
+ */
3254
+ async listSharedDrives(options = {}) {
3255
+ await this.init();
3256
+ const raw = await this.getRawClient();
3257
+ const res = await withRetry(async () => {
3258
+ return await raw.drives.list({
3259
+ pageSize: options.pageSize || 100,
3260
+ fields: "drives(id, name)"
3261
+ });
3262
+ });
3263
+ return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
3264
+ }
3265
+ /**
3266
+ * Creates a scoped DriveKit client locked to a specific Shared Drive
3267
+ */
3268
+ sharedDrive(driveId) {
3269
+ return new _DriveKit({
3270
+ ...this.options,
3271
+ rootFolderId: driveId
3272
+ });
3273
+ }
3274
+ /**
3275
+ * Grants access to a specific email with custom role and notification
3276
+ */
3277
+ async grantAccess(pathOrId, options) {
3278
+ const fileId = await this.resolveId(pathOrId);
3279
+ const raw = await this.getRawClient();
3280
+ const res = await withRetry(async () => {
3281
+ return await raw.permissions.create({
3282
+ fileId,
3283
+ requestBody: {
3284
+ type: "user",
3285
+ role: options.role || "reader",
3286
+ emailAddress: options.email
3287
+ },
3288
+ sendNotificationEmail: options.notify ?? true,
3289
+ emailMessage: options.message,
3290
+ fields: "id, type, role, emailAddress, displayName",
3291
+ supportsAllDrives: true
3292
+ });
3293
+ });
3294
+ return res.data;
3295
+ }
3296
+ /**
3297
+ * Revokes access for a specific permission ID or email address
3298
+ */
3299
+ async revokeAccess(pathOrId, permissionIdOrEmail) {
3300
+ const fileId = await this.resolveId(pathOrId);
3301
+ const raw = await this.getRawClient();
3302
+ let targetId = permissionIdOrEmail;
3303
+ if (permissionIdOrEmail.includes("@")) {
3304
+ const listRes = await this.listPermissions(fileId);
3305
+ const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
3306
+ if (found && found.id) {
3307
+ targetId = found.id;
3308
+ }
3309
+ }
3310
+ await withRetry(async () => {
3311
+ return await raw.permissions.delete({
3312
+ fileId,
3313
+ permissionId: targetId,
3314
+ supportsAllDrives: true
3315
+ });
3316
+ });
3317
+ }
3318
+ /**
3319
+ * Lists all active permissions on a file or folder
3320
+ */
3321
+ async listPermissions(pathOrId) {
3322
+ const fileId = await this.resolveId(pathOrId);
3323
+ const raw = await this.getRawClient();
3324
+ const res = await withRetry(async () => {
3325
+ return await raw.permissions.list({
3326
+ fileId,
3327
+ fields: "permissions(id, type, role, emailAddress, displayName)",
3328
+ supportsAllDrives: true
3329
+ });
3330
+ });
3331
+ return res.data.permissions || [];
3332
+ }
3333
+ /**
3334
+ * Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
3335
+ */
3336
+ async serveWebDAV(options) {
3337
+ const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3338
+ return await startWebDAVServer2(this, options);
3339
+ }
2097
3340
  /**
2098
3341
  * Calculates local file MD5 hash for integrity and deduplication checks
2099
3342
  */
@@ -2108,6 +3351,165 @@ var DriveKit = class {
2108
3351
  }
2109
3352
  };
2110
3353
 
3354
+ // src/types.ts
3355
+ init_esm_shims();
3356
+
3357
+ // src/index.ts
3358
+ init_webdav();
3359
+
3360
+ // src/cli/terminal-ui.ts
3361
+ init_esm_shims();
3362
+ import readline from "readline";
3363
+ import chalk from "chalk";
3364
+ function terminalLink(text, url2) {
3365
+ return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
3366
+ }
3367
+ function renderFileRow(item, index) {
3368
+ const isDir = item.mimeType === "application/vnd.google-apps.folder";
3369
+ const icon = isDir ? "\u{1F4C1}" : getFileIcon(item.mimeType || "");
3370
+ const prefix = index !== void 0 ? `${chalk.dim((index + 1).toString().padStart(2, " ") + ".")} ` : "";
3371
+ let nameFormatted = isDir ? chalk.bold.blue(item.name || "untitled") : chalk.white(item.name || "untitled");
3372
+ if (item.webViewLink) {
3373
+ nameFormatted = terminalLink(nameFormatted, item.webViewLink);
3374
+ }
3375
+ const sizeFormatted = item.size ? chalk.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, " ")}]`) : chalk.dim(isDir ? "[ FOLDER ]" : "[ DOC ]");
3376
+ const idFormatted = chalk.dim(`ID: ${item.id}`);
3377
+ return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;
3378
+ }
3379
+ function getFileIcon(mimeType) {
3380
+ if (mimeType.includes("pdf")) return "\u{1F4D5}";
3381
+ if (mimeType.includes("image")) return "\u{1F5BC}\uFE0F ";
3382
+ if (mimeType.includes("video")) return "\u{1F3AC}";
3383
+ if (mimeType.includes("audio")) return "\u{1F3B5}";
3384
+ if (mimeType.includes("zip") || mimeType.includes("compressed") || mimeType.includes("tar")) return "\u{1F4E6}";
3385
+ if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return "\u{1F4CA}";
3386
+ if (mimeType.includes("document") || mimeType.includes("word")) return "\u{1F4DD}";
3387
+ if (mimeType.includes("presentation")) return "\u{1F4FD}\uFE0F ";
3388
+ if (mimeType.includes("json") || mimeType.includes("javascript") || mimeType.includes("typescript")) return "\u2699\uFE0F ";
3389
+ return "\u{1F4C4}";
3390
+ }
3391
+ async function runInteractiveExplorer(client, initialFolder = "/") {
3392
+ let currentFolder = initialFolder;
3393
+ let items = [];
3394
+ let selectedIndex = 0;
3395
+ let history = [];
3396
+ const refreshItems = async () => {
3397
+ items = await client.ls(currentFolder);
3398
+ selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));
3399
+ };
3400
+ await refreshItems();
3401
+ if (!process.stdin.isTTY) {
3402
+ console.log(chalk.yellow("Interactive explorer requires a TTY terminal. Listing items instead:"));
3403
+ for (const item of items) {
3404
+ console.log(renderFileRow(item));
3405
+ }
3406
+ return;
3407
+ }
3408
+ readline.emitKeypressEvents(process.stdin);
3409
+ process.stdin.setRawMode(true);
3410
+ const renderScreen = () => {
3411
+ console.clear();
3412
+ 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"));
3413
+ console.log(chalk.bold.cyan("\u2551") + chalk.bold.yellow(" \u26A1 DriveKit Interactive Terminal Explorer ") + chalk.bold.cyan("\u2551"));
3414
+ 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"));
3415
+ console.log(chalk.bold.cyan("\u2551") + ` \u{1F4C2} Path: ${chalk.bold.green(currentFolder.padEnd(72))} ` + chalk.bold.cyan("\u2551"));
3416
+ 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"));
3417
+ console.log(chalk.dim(" [\u2191/\u2193] Navigate \u2022 [Enter] Open Folder \u2022 [B] Back \u2022 [S] Share \u2022 [Q] Exit\n"));
3418
+ if (items.length === 0) {
3419
+ console.log(chalk.dim(" (This folder is empty)\n"));
3420
+ return;
3421
+ }
3422
+ const pageSize = 12;
3423
+ const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));
3424
+ const endIdx = Math.min(items.length, startIdx + pageSize);
3425
+ for (let i = startIdx; i < endIdx; i++) {
3426
+ const isSelected = i === selectedIndex;
3427
+ const cursor = isSelected ? chalk.bold.cyan(" \u25BA ") : " ";
3428
+ const row = renderFileRow(items[i]);
3429
+ if (isSelected) {
3430
+ console.log(chalk.bgHex("#1e293b")(cursor + row));
3431
+ } else {
3432
+ console.log(cursor + row);
3433
+ }
3434
+ }
3435
+ console.log(chalk.dim(`
3436
+ Item ${selectedIndex + 1} of ${items.length}`));
3437
+ };
3438
+ renderScreen();
3439
+ return new Promise((resolve) => {
3440
+ const onKeypress = async (str, key) => {
3441
+ if (key.ctrl && key.name === "c") {
3442
+ cleanup();
3443
+ process.exit(0);
3444
+ }
3445
+ if (key.name === "q" || key.name === "escape" && history.length === 0) {
3446
+ cleanup();
3447
+ resolve();
3448
+ return;
3449
+ }
3450
+ if (key.name === "up") {
3451
+ selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;
3452
+ renderScreen();
3453
+ } else if (key.name === "down") {
3454
+ selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;
3455
+ renderScreen();
3456
+ } else if (key.name === "return") {
3457
+ const item = items[selectedIndex];
3458
+ if (item && item.mimeType === "application/vnd.google-apps.folder") {
3459
+ history.push(currentFolder);
3460
+ currentFolder = currentFolder === "/" ? `/${item.name}` : `${currentFolder}/${item.name}`;
3461
+ selectedIndex = 0;
3462
+ await refreshItems();
3463
+ renderScreen();
3464
+ } else if (item && item.webViewLink) {
3465
+ const { exec: exec2 } = await import("child_process");
3466
+ const openCmd = process.platform === "darwin" ? `open "${item.webViewLink}"` : `xdg-open "${item.webViewLink}"`;
3467
+ exec2(openCmd);
3468
+ renderScreen();
3469
+ }
3470
+ } else if (key.name === "b" || key.name === "backspace") {
3471
+ if (history.length > 0) {
3472
+ currentFolder = history.pop();
3473
+ selectedIndex = 0;
3474
+ await refreshItems();
3475
+ renderScreen();
3476
+ }
3477
+ } else if (str === "s" || str === "S") {
3478
+ const item = items[selectedIndex];
3479
+ if (item && item.id) {
3480
+ process.stdin.pause();
3481
+ console.log(`
3482
+
3483
+ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}...`);
3484
+ try {
3485
+ const links = await client.sharePublic(item.id);
3486
+ console.log(`Preview URL: ${chalk.underline(links.previewLink)}`);
3487
+ console.log(`Direct Download URL: ${chalk.underline(links.directDownloadLink)}`);
3488
+ console.log(chalk.dim("\nPress any key to return to explorer..."));
3489
+ process.stdin.resume();
3490
+ process.stdin.once("data", () => {
3491
+ renderScreen();
3492
+ });
3493
+ } catch (err) {
3494
+ console.error(chalk.red(`Failed to share: ${err.message}`));
3495
+ setTimeout(renderScreen, 2e3);
3496
+ }
3497
+ }
3498
+ }
3499
+ };
3500
+ const cleanup = () => {
3501
+ process.stdin.removeListener("keypress", onKeypress);
3502
+ if (process.stdin.setRawMode) {
3503
+ process.stdin.setRawMode(false);
3504
+ }
3505
+ process.stdin.pause();
3506
+ console.clear();
3507
+ console.log(chalk.green("\u{1F44B} Exited DriveKit explorer."));
3508
+ };
3509
+ process.stdin.on("keypress", onKeypress);
3510
+ });
3511
+ }
3512
+
2111
3513
  // src/index.ts
2112
3514
  async function createDrive(options) {
2113
3515
  const instance = new DriveKit(options);
@@ -2123,6 +3525,8 @@ export {
2123
3525
  Downloader,
2124
3526
  DriveAuthError,
2125
3527
  DriveAuthenticator,
3528
+ DriveFileRef,
3529
+ DriveFolderRef,
2126
3530
  DriveKit,
2127
3531
  DriveKitError,
2128
3532
  DriveNotFoundError,
@@ -2133,21 +3537,31 @@ export {
2133
3537
  GOOGLE_WORKSPACE_MIME_TYPES,
2134
3538
  MIN_CHUNK_SIZE,
2135
3539
  MULTIPART_THRESHOLD,
3540
+ MemoryMetadataCache,
2136
3541
  PathResolver,
3542
+ PluginManager,
2137
3543
  ResumableUploader,
2138
3544
  SmartSyncEngine,
3545
+ SqliteMetadataCache,
2139
3546
  StorageCleaner,
2140
3547
  calculateFileMd5,
3548
+ createAutoNamePlugin,
2141
3549
  createDrive,
3550
+ createWebhookPlugin,
2142
3551
  index_default as default,
2143
3552
  formatBytes,
2144
3553
  formatDuration,
2145
3554
  formatSpeed,
2146
3555
  getExtensionForMime,
3556
+ getFileIcon,
2147
3557
  isGoogleWorkspaceDoc,
2148
3558
  isRetryableError,
2149
3559
  loginWithBrowser,
2150
3560
  lookupMimeType,
3561
+ renderFileRow,
3562
+ runInteractiveExplorer,
3563
+ startWebDAVServer,
3564
+ terminalLink,
2151
3565
  withRetry
2152
3566
  };
2153
3567
  //# sourceMappingURL=index.js.map