drivekit 1.1.1 → 1.1.2

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
@@ -75,6 +75,31 @@ var init_errors = __esm({
75
75
  }
76
76
  });
77
77
 
78
+ // src/utils/http-agent.ts
79
+ import https from "https";
80
+ import http from "http";
81
+ function getOptimizedHttpsAgent(options) {
82
+ if (!sharedHttpsAgent) {
83
+ sharedHttpsAgent = new https.Agent({
84
+ keepAlive: options?.keepAlive ?? true,
85
+ maxSockets: options?.maxSockets ?? 64,
86
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
87
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
88
+ timeout: options?.timeout ?? 3e4,
89
+ noDelay: true
90
+ });
91
+ }
92
+ return sharedHttpsAgent;
93
+ }
94
+ var sharedHttpsAgent;
95
+ var init_http_agent = __esm({
96
+ "src/utils/http-agent.ts"() {
97
+ "use strict";
98
+ init_esm_shims();
99
+ sharedHttpsAgent = null;
100
+ }
101
+ });
102
+
78
103
  // src/auth/authenticator.ts
79
104
  import fs from "fs";
80
105
  import { auth as googleAuth } from "@googleapis/drive";
@@ -84,6 +109,7 @@ var init_authenticator = __esm({
84
109
  "use strict";
85
110
  init_esm_shims();
86
111
  init_errors();
112
+ init_http_agent();
87
113
  DEFAULT_SCOPES = [
88
114
  "https://www.googleapis.com/auth/drive"
89
115
  ];
@@ -106,44 +132,39 @@ var init_authenticator = __esm({
106
132
  const oauth2Client = new googleAuth.OAuth2();
107
133
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
108
134
  this.authClient = oauth2Client;
109
- return this.authClient;
110
- }
111
- if (this.config.oauth2Client) {
135
+ } else if (this.config.oauth2Client) {
112
136
  this.authClient = this.config.oauth2Client;
113
- return this.authClient;
114
- }
115
- if (this.config.oauth) {
137
+ } else if (this.config.oauth) {
116
138
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
117
139
  const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
118
140
  if (refreshToken) {
119
141
  oauth2Client.setCredentials({ refresh_token: refreshToken });
120
142
  }
121
143
  this.authClient = oauth2Client;
122
- return this.authClient;
123
- }
124
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
125
- if (keyFile) {
126
- if (!fs.existsSync(keyFile)) {
144
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
145
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
146
+ if (keyFile && !fs.existsSync(keyFile)) {
127
147
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
128
148
  }
129
- const auth2 = new googleAuth.GoogleAuth({
149
+ const auth = new googleAuth.GoogleAuth({
130
150
  keyFile,
131
151
  scopes
132
152
  });
133
- this.authClient = auth2;
134
- return this.authClient;
135
- }
136
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
137
- if (creds) {
138
- const auth2 = new googleAuth.GoogleAuth({
153
+ this.authClient = auth;
154
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
155
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
156
+ const auth = new googleAuth.GoogleAuth({
139
157
  credentials: creds,
140
158
  scopes
141
159
  });
142
- this.authClient = auth2;
143
- return this.authClient;
160
+ this.authClient = auth;
161
+ } else {
162
+ const auth = new googleAuth.GoogleAuth({ scopes });
163
+ this.authClient = auth;
164
+ }
165
+ if (this.authClient?.transporter?.defaults) {
166
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
144
167
  }
145
- const auth = new googleAuth.GoogleAuth({ scopes });
146
- this.authClient = auth;
147
168
  return this.authClient;
148
169
  } catch (err) {
149
170
  if (err instanceof DriveAuthError) throw err;
@@ -302,6 +323,7 @@ var init_path_resolver = __esm({
302
323
  drive;
303
324
  rootFolderId;
304
325
  cache = /* @__PURE__ */ new Map();
326
+ inFlightResolves = /* @__PURE__ */ new Map();
305
327
  cacheTTL;
306
328
  enableCache;
307
329
  metadataCache;
@@ -354,6 +376,7 @@ var init_path_resolver = __esm({
354
376
  /**
355
377
  * Resolves a path to a Google Drive item (file or folder).
356
378
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
379
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
357
380
  */
358
381
  async resolve(virtualPath, options = {}) {
359
382
  const norm = this.normalizePath(virtualPath);
@@ -387,6 +410,20 @@ var init_path_resolver = __esm({
387
410
  };
388
411
  }
389
412
  }
413
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
414
+ const inFlight = this.inFlightResolves.get(flightKey);
415
+ if (inFlight) {
416
+ return await inFlight;
417
+ }
418
+ const task = this.doResolve(virtualPath, norm, options);
419
+ this.inFlightResolves.set(flightKey, task);
420
+ try {
421
+ return await task;
422
+ } finally {
423
+ this.inFlightResolves.delete(flightKey);
424
+ }
425
+ }
426
+ async doResolve(virtualPath, norm, options) {
390
427
  const segments = norm.split("/").filter(Boolean);
391
428
  let currentParentId = this.rootFolderId;
392
429
  let currentPath = "";
@@ -438,7 +475,7 @@ var init_path_resolver = __esm({
438
475
  });
439
476
  let file = response.data.files?.[0];
440
477
  if (!file && currentParentId === this.rootFolderId) {
441
- const sharedQ = `name = '${escapedName}' and trashed = false`;
478
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
442
479
  const sharedResponse = await withRetry(async () => {
443
480
  return await this.drive.files.list({
444
481
  q: sharedQ,
@@ -568,6 +605,7 @@ var init_format = __esm({
568
605
  // src/core/resumable-uploader.ts
569
606
  import fs2 from "fs";
570
607
  import path2 from "path";
608
+ import { Transform } from "stream";
571
609
  var MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
572
610
  var init_resumable_uploader = __esm({
573
611
  "src/core/resumable-uploader.ts"() {
@@ -577,6 +615,7 @@ var init_resumable_uploader = __esm({
577
615
  init_format();
578
616
  init_mime();
579
617
  init_retry();
618
+ init_http_agent();
580
619
  MIN_CHUNK_SIZE = 256 * 1024;
581
620
  DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
582
621
  MULTIPART_THRESHOLD = 5 * 1024 * 1024;
@@ -614,6 +653,15 @@ var init_resumable_uploader = __esm({
614
653
  const totalBytes = stat.size;
615
654
  const fileName = options.name || path2.basename(filePath);
616
655
  const mimeType = options.mimeType || lookupMimeType(filePath);
656
+ if (totalBytes <= MULTIPART_THRESHOLD) {
657
+ const readStream = fs2.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
658
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
659
+ return await this.directUpload(stream, {
660
+ ...options,
661
+ name: fileName,
662
+ mimeType
663
+ });
664
+ }
617
665
  return await this.chunkedUpload({
618
666
  filePath,
619
667
  totalBytes,
@@ -629,6 +677,16 @@ var init_resumable_uploader = __esm({
629
677
  const totalBytes = buffer.length;
630
678
  const fileName = options.name || "untitled";
631
679
  const mimeType = options.mimeType || "application/octet-stream";
680
+ if (totalBytes <= MULTIPART_THRESHOLD) {
681
+ const { Readable } = await import("stream");
682
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
683
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
684
+ return await this.directUpload(stream, {
685
+ ...options,
686
+ name: fileName,
687
+ mimeType
688
+ });
689
+ }
632
690
  return await this.chunkedUploadBuffer({
633
691
  buffer,
634
692
  totalBytes,
@@ -649,6 +707,50 @@ var init_resumable_uploader = __esm({
649
707
  mimeType
650
708
  });
651
709
  }
710
+ /**
711
+ * Calculates optimal chunk size based on file size for maximum throughput.
712
+ */
713
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
714
+ if (explicitChunkSize) {
715
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
716
+ }
717
+ if (totalBytes > 128 * 1024 * 1024) {
718
+ return 32 * 1024 * 1024;
719
+ }
720
+ if (totalBytes > 32 * 1024 * 1024) {
721
+ return 16 * 1024 * 1024;
722
+ }
723
+ return this.defaultChunkSize;
724
+ }
725
+ /**
726
+ * Attaches real-time progress monitoring to direct stream uploads.
727
+ */
728
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
729
+ let bytesSent = 0;
730
+ const startTime = Date.now();
731
+ const progressTransform = new Transform({
732
+ transform(chunk, _encoding, callback) {
733
+ bytesSent += chunk.length;
734
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
735
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
736
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
737
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
738
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
739
+ onProgress({
740
+ bytesSent,
741
+ totalBytes,
742
+ percentage,
743
+ bytesPerSecond,
744
+ speedFormatted: formatSpeed(bytesPerSecond),
745
+ estimatedTimeRemainingSeconds,
746
+ chunkIndex: 1,
747
+ totalChunks: 1
748
+ });
749
+ callback(null, chunk);
750
+ }
751
+ });
752
+ return stream.pipe(progressTransform);
753
+ }
652
754
  /**
653
755
  * Fast direct upload using googleapis multipart
654
756
  */
@@ -681,7 +783,7 @@ var init_resumable_uploader = __esm({
681
783
  */
682
784
  async chunkedUpload(params) {
683
785
  const { filePath, totalBytes, fileName, mimeType, options } = params;
684
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
786
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
685
787
  const sessionUrl = await this.initiateResumableSession({
686
788
  fileName,
687
789
  mimeType,
@@ -746,7 +848,7 @@ var init_resumable_uploader = __esm({
746
848
  */
747
849
  async chunkedUploadBuffer(params) {
748
850
  const { buffer, totalBytes, fileName, mimeType, options } = params;
749
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
851
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
750
852
  const sessionUrl = await this.initiateResumableSession({
751
853
  fileName,
752
854
  mimeType,
@@ -825,7 +927,8 @@ var init_resumable_uploader = __esm({
825
927
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
826
928
  method: "POST",
827
929
  headers,
828
- data: metadata
930
+ data: metadata,
931
+ agent: getOptimizedHttpsAgent()
829
932
  });
830
933
  });
831
934
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -851,6 +954,7 @@ var init_resumable_uploader = __esm({
851
954
  method: "PUT",
852
955
  headers,
853
956
  data: buffer,
957
+ agent: getOptimizedHttpsAgent(),
854
958
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
855
959
  });
856
960
  if (res.status === 200 || res.status === 201) {
@@ -885,7 +989,7 @@ var init_resumable_uploader = __esm({
885
989
  import fs3 from "fs";
886
990
  import path3 from "path";
887
991
  import { pipeline } from "stream/promises";
888
- import { Transform } from "stream";
992
+ import { Transform as Transform2 } from "stream";
889
993
  var Downloader;
890
994
  var init_downloader = __esm({
891
995
  "src/core/downloader.ts"() {
@@ -903,17 +1007,22 @@ var init_downloader = __esm({
903
1007
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
904
1008
  */
905
1009
  async download(fileId, options = {}) {
906
- const metaRes = await withRetry(async () => {
907
- return await this.drive.files.get({
908
- fileId,
909
- fields: "id, name, mimeType, size",
910
- supportsAllDrives: true
1010
+ let name = options.metadata?.name;
1011
+ let mimeType = options.metadata?.mimeType;
1012
+ let totalBytes = options.metadata?.size;
1013
+ if (!name || !mimeType) {
1014
+ const metaRes = await withRetry(async () => {
1015
+ return await this.drive.files.get({
1016
+ fileId,
1017
+ fields: "id, name, mimeType, size",
1018
+ supportsAllDrives: true
1019
+ });
911
1020
  });
912
- });
913
- const file = metaRes.data;
914
- const name = file.name || "downloaded-file";
915
- const mimeType = file.mimeType || "application/octet-stream";
916
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1021
+ const file = metaRes.data;
1022
+ name = file.name || "downloaded-file";
1023
+ mimeType = file.mimeType || "application/octet-stream";
1024
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1025
+ }
917
1026
  let downloadStream;
918
1027
  let finalFileName = name;
919
1028
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -944,7 +1053,7 @@ var init_downloader = __esm({
944
1053
  }
945
1054
  let bytesRead = 0;
946
1055
  const startTime = Date.now();
947
- const progressTracker = new Transform({
1056
+ const progressTracker = new Transform2({
948
1057
  transform(chunk, encoding, callback) {
949
1058
  bytesRead += chunk.length;
950
1059
  if (options.onProgress) {
@@ -969,7 +1078,7 @@ var init_downloader = __esm({
969
1078
  destPath = path3.join(destPath, finalFileName);
970
1079
  }
971
1080
  await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
972
- const writeStream = fs3.createWriteStream(destPath);
1081
+ const writeStream = fs3.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
973
1082
  await pipeline(monitoredStream, writeStream);
974
1083
  return {
975
1084
  filePath: destPath,
@@ -1220,6 +1329,7 @@ var init_query_builder = __esm({
1220
1329
  const q = this.toQueryString();
1221
1330
  const orderBy = this.orderClauses.join(", ");
1222
1331
  let pageToken = void 0;
1332
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1223
1333
  do {
1224
1334
  const res = await withRetry(async () => {
1225
1335
  return await this.drive.files.list({
@@ -1227,7 +1337,7 @@ var init_query_builder = __esm({
1227
1337
  orderBy: orderBy || void 0,
1228
1338
  pageSize: this.limitNumber,
1229
1339
  pageToken,
1230
- fields: this.requestedFields,
1340
+ fields: effectiveFields,
1231
1341
  spaces: this.spaces,
1232
1342
  supportsAllDrives: true,
1233
1343
  includeItemsFromAllDrives: true
@@ -1364,7 +1474,7 @@ var init_watcher = __esm({
1364
1474
  const res = await withRetry(async () => {
1365
1475
  return await this.drive.changes.list({
1366
1476
  pageToken: nextPageToken,
1367
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1477
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1368
1478
  supportsAllDrives: true,
1369
1479
  includeItemsFromAllDrives: true
1370
1480
  });
@@ -1463,16 +1573,24 @@ var init_storage_cleaner = __esm({
1463
1573
  async findDuplicates(options = {}) {
1464
1574
  const mode = options.by || "name";
1465
1575
  const maxScan = options.maxScan || 1e3;
1466
- const res = await withRetry(async () => {
1467
- return await this.drive.files.list({
1468
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1469
- pageSize: Math.min(1e3, maxScan),
1470
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1471
- supportsAllDrives: true,
1472
- includeItemsFromAllDrives: true
1576
+ const files = [];
1577
+ let pageToken = void 0;
1578
+ do {
1579
+ const remaining = maxScan - files.length;
1580
+ if (remaining <= 0) break;
1581
+ const res = await withRetry(async () => {
1582
+ return await this.drive.files.list({
1583
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1584
+ pageSize: Math.min(1e3, remaining),
1585
+ pageToken,
1586
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1587
+ supportsAllDrives: true,
1588
+ includeItemsFromAllDrives: true
1589
+ });
1473
1590
  });
1474
- });
1475
- const files = res.data.files || [];
1591
+ files.push(...res.data.files || []);
1592
+ pageToken = res.data.nextPageToken || void 0;
1593
+ } while (pageToken && files.length < maxScan);
1476
1594
  const map = /* @__PURE__ */ new Map();
1477
1595
  for (const f of files) {
1478
1596
  if (!f.id) continue;
@@ -1657,7 +1775,7 @@ var init_smart_sync = __esm({
1657
1775
  });
1658
1776
 
1659
1777
  // src/auth/browser-login.ts
1660
- import http from "http";
1778
+ import http2 from "http";
1661
1779
  import { exec } from "child_process";
1662
1780
  import { auth as googleAuth2 } from "@googleapis/drive";
1663
1781
  async function loginWithBrowser(options) {
@@ -1675,7 +1793,7 @@ async function loginWithBrowser(options) {
1675
1793
  scope: scopes
1676
1794
  });
1677
1795
  return new Promise((resolve, reject) => {
1678
- const server = http.createServer(async (req, res) => {
1796
+ const server = http2.createServer(async (req, res) => {
1679
1797
  try {
1680
1798
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1681
1799
  if (reqUrl.pathname === "/oauth2callback") {
@@ -1759,7 +1877,11 @@ ${authUrl}
1759
1877
  });
1760
1878
  });
1761
1879
  server.on("error", (err) => {
1762
- reject(err);
1880
+ if (err.code === "EADDRINUSE") {
1881
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
1882
+ } else {
1883
+ reject(err);
1884
+ }
1763
1885
  });
1764
1886
  });
1765
1887
  }
@@ -2131,10 +2253,35 @@ var init_cache = __esm({
2131
2253
  return;
2132
2254
  }
2133
2255
  if (!this.initialized || !this.db || entries.length === 0) return;
2256
+ const stmt = this.db.prepare(`
2257
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2258
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2259
+ ON CONFLICT(id) DO UPDATE SET
2260
+ name = excluded.name,
2261
+ mimeType = excluded.mimeType,
2262
+ size = excluded.size,
2263
+ parentId = excluded.parentId,
2264
+ path = COALESCE(excluded.path, files.path),
2265
+ md5Checksum = excluded.md5Checksum,
2266
+ trashed = excluded.trashed,
2267
+ modifiedTime = excluded.modifiedTime,
2268
+ updatedAt = excluded.updatedAt
2269
+ `);
2134
2270
  this.db.exec("BEGIN TRANSACTION;");
2135
2271
  try {
2136
2272
  for (const entry of entries) {
2137
- this.upsertFile(entry);
2273
+ stmt.run(
2274
+ entry.id,
2275
+ entry.name,
2276
+ entry.mimeType ?? null,
2277
+ entry.size ?? null,
2278
+ entry.parentId ?? null,
2279
+ entry.path ?? null,
2280
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2281
+ entry.trashed ? 1 : 0,
2282
+ entry.modifiedTime ?? null,
2283
+ entry.updatedAt ?? Date.now()
2284
+ );
2138
2285
  }
2139
2286
  this.db.exec("COMMIT;");
2140
2287
  } catch (e) {
@@ -2359,7 +2506,7 @@ __export(webdav_exports, {
2359
2506
  escapeXml: () => escapeXml,
2360
2507
  startWebDAVServer: () => startWebDAVServer
2361
2508
  });
2362
- import http2 from "http";
2509
+ import http3 from "http";
2363
2510
  import url from "url";
2364
2511
  import path7 from "path";
2365
2512
  function escapeXml(unsafe) {
@@ -2369,7 +2516,7 @@ async function startWebDAVServer(drive2, options = {}) {
2369
2516
  const port = options.port || 8080;
2370
2517
  const host = options.host || "127.0.0.1";
2371
2518
  await drive2.init();
2372
- const server = http2.createServer(async (req, res) => {
2519
+ const server = http3.createServer(async (req, res) => {
2373
2520
  try {
2374
2521
  if (options.auth?.username && options.auth?.password) {
2375
2522
  const authHeader = req.headers["authorization"];
@@ -2395,6 +2542,12 @@ async function startWebDAVServer(drive2, options = {}) {
2395
2542
  const parsedUrl = url.parse(req.url || "/", true);
2396
2543
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2397
2544
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
2545
+ const baseName = path7.basename(virtualPath);
2546
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
2547
+ res.writeHead(404, { "Content-Type": "text/plain" });
2548
+ res.end("Not Found");
2549
+ return;
2550
+ }
2398
2551
  switch (req.method) {
2399
2552
  case "OPTIONS": {
2400
2553
  res.writeHead(200, {
@@ -2409,6 +2562,11 @@ async function startWebDAVServer(drive2, options = {}) {
2409
2562
  case "PROPFIND": {
2410
2563
  const depth = req.headers["depth"] || "1";
2411
2564
  const xml = await handlePropfind(drive2, virtualPath, depth);
2565
+ if (xml === null) {
2566
+ res.writeHead(404, { "Content-Type": "text/plain" });
2567
+ res.end("Not Found");
2568
+ return;
2569
+ }
2412
2570
  res.writeHead(207, {
2413
2571
  "Content-Type": "application/xml; charset=utf-8"
2414
2572
  });
@@ -2619,25 +2777,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
2619
2777
  virtualPath,
2620
2778
  isFolder,
2621
2779
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
2622
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2780
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2781
+ selfItem.mimeType || void 0
2623
2782
  )
2624
2783
  );
2625
2784
  } catch {
2626
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
2785
+ return null;
2627
2786
  }
2628
2787
  }
2629
2788
  if (isFolder && depth !== "0") {
2630
2789
  try {
2631
2790
  const children = await drive2.ls(virtualPath);
2791
+ const seenNames = /* @__PURE__ */ new Map();
2632
2792
  for (const child of children) {
2793
+ let childName = child.name || "untitled";
2794
+ if (seenNames.has(childName)) {
2795
+ const count = seenNames.get(childName) + 1;
2796
+ seenNames.set(childName, count);
2797
+ const ext = path7.extname(childName);
2798
+ const base = path7.basename(childName, ext);
2799
+ childName = `${base} (${count})${ext}`;
2800
+ } else {
2801
+ seenNames.set(childName, 0);
2802
+ }
2633
2803
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2634
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
2804
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
2635
2805
  responses.push(
2636
2806
  renderWebDAVResponse(
2637
2807
  childPath,
2638
2808
  childIsFolder,
2639
2809
  child.size ? parseInt(child.size, 10) : 0,
2640
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2810
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2811
+ child.mimeType || void 0
2641
2812
  )
2642
2813
  );
2643
2814
  }
@@ -2649,11 +2820,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
2649
2820
  ${responses.join("\n")}
2650
2821
  </D:multistatus>`;
2651
2822
  }
2652
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2653
- const encodedHref = encodeURI(href);
2823
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
2824
+ let cleanHref = href;
2825
+ if (isDir && !cleanHref.endsWith("/")) {
2826
+ cleanHref += "/";
2827
+ }
2828
+ const encodedHref = encodeURI(cleanHref);
2654
2829
  const displayName = escapeXml(path7.basename(href) || "root");
2655
2830
  const resourceType = isDir ? "<D:collection/>" : "";
2656
2831
  const dateFormatted = new Date(modifiedTime).toUTCString();
2832
+ const contentTypeTag = !isDir && mimeType ? `
2833
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
2657
2834
  return ` <D:response>
2658
2835
  <D:href>${encodedHref}</D:href>
2659
2836
  <D:propstat>
@@ -2661,8 +2838,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2661
2838
  <D:displayname>${displayName}</D:displayname>
2662
2839
  <D:resourcetype>${resourceType}</D:resourcetype>
2663
2840
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2664
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2665
- <D:status>HTTP/1.1 200 OK</D:status>
2841
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
2666
2842
  </D:prop>
2667
2843
  <D:status>HTTP/1.1 200 OK</D:status>
2668
2844
  </D:propstat>
@@ -2704,6 +2880,7 @@ var init_client = __esm({
2704
2880
  init_format();
2705
2881
  init_mime();
2706
2882
  init_cache();
2883
+ init_http_agent();
2707
2884
  DriveKit = class _DriveKit {
2708
2885
  options;
2709
2886
  authenticator;
@@ -2726,6 +2903,18 @@ var init_client = __esm({
2726
2903
  this.pluginManager.use(plugin);
2727
2904
  return this;
2728
2905
  }
2906
+ /**
2907
+ * Unregisters a middleware plugin by name
2908
+ */
2909
+ unuse(pluginName) {
2910
+ return this.pluginManager.unuse(pluginName);
2911
+ }
2912
+ /**
2913
+ * Access the underlying plugin manager instance
2914
+ */
2915
+ get plugins() {
2916
+ return this.pluginManager;
2917
+ }
2729
2918
  /**
2730
2919
  * Returns a fluent, chained reference to a specific file
2731
2920
  */
@@ -2744,7 +2933,8 @@ var init_client = __esm({
2744
2933
  async init() {
2745
2934
  if (!this.driveClient) {
2746
2935
  const auth = await this.authenticator.getAuthClient();
2747
- this.driveClient = drive({ version: "v3", auth });
2936
+ const agent = getOptimizedHttpsAgent();
2937
+ this.driveClient = drive({ version: "v3", auth, agent });
2748
2938
  if (this.options.enablePersistentCache !== false) {
2749
2939
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2750
2940
  this.metadataCacheInstance.init();
@@ -2831,15 +3021,41 @@ var init_client = __esm({
2831
3021
  }
2832
3022
  }
2833
3023
  /**
2834
- * Lists contents of a folder (by folder ID or path)
3024
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2835
3025
  */
2836
3026
  async ls(folderIdOrPath = "/") {
3027
+ let parentFolderId;
3028
+ let normalizedPath = null;
3029
+ let files;
2837
3030
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3031
+ parentFolderId = this.rootFolderId;
3032
+ normalizedPath = "/";
2838
3033
  const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2839
- return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3034
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3035
+ } else {
3036
+ if (folderIdOrPath.startsWith("/")) {
3037
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
3038
+ parentFolderId = await this.resolveId(normalizedPath);
3039
+ } else {
3040
+ parentFolderId = folderIdOrPath;
3041
+ }
3042
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
3043
+ }
3044
+ if (this.metadataCacheInstance && files.length > 0) {
3045
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
3046
+ id: f.id,
3047
+ name: f.name || "untitled",
3048
+ mimeType: f.mimeType || "",
3049
+ size: f.size ? parseInt(f.size, 10) : void 0,
3050
+ parentId: parentFolderId,
3051
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
3052
+ md5Checksum: f.md5Checksum || void 0,
3053
+ modifiedTime: f.modifiedTime || void 0,
3054
+ trashed: false
3055
+ }));
3056
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
2840
3057
  }
2841
- const folderId = await this.resolveId(folderIdOrPath);
2842
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
3058
+ return files;
2843
3059
  }
2844
3060
  // ==========================================
2845
3061
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2858,7 +3074,7 @@ var init_client = __esm({
2858
3074
  if (parentId && parentId.startsWith("/")) {
2859
3075
  parentId = await this.mkdirp(parentId);
2860
3076
  }
2861
- const targetName = opts.name || opts.filename;
3077
+ const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? path8.basename(opts.source) : void 0);
2862
3078
  if (opts.overwrite && targetName && parentId) {
2863
3079
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2864
3080
  if (existing?.id) {
@@ -2914,12 +3130,14 @@ var init_client = __esm({
2914
3130
  parent: parentId
2915
3131
  });
2916
3132
  if (this.metadataCacheInstance && uploaded.id) {
3133
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2917
3134
  this.metadataCacheInstance.upsertFile({
2918
3135
  id: uploaded.id,
2919
3136
  name: uploaded.name || targetName || "untitled",
2920
3137
  mimeType: uploaded.mimeType || "",
2921
3138
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2922
3139
  parentId,
3140
+ path: virtualPath,
2923
3141
  trashed: false
2924
3142
  });
2925
3143
  }
@@ -2930,16 +3148,25 @@ var init_client = __esm({
2930
3148
  * - Automatic conversion for Google Docs, Sheets, and Slides
2931
3149
  * - Progress events
2932
3150
  * - Saves directly to file or returns Readable Stream
3151
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2933
3152
  */
2934
3153
  async download(fileIdOrPath, options = {}) {
2935
3154
  const fileId = await this.resolveId(fileIdOrPath);
2936
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
3155
+ let cachedMeta = options.metadata;
3156
+ if (!cachedMeta && this.metadataCacheInstance) {
3157
+ const cached = this.metadataCacheInstance.getById(fileId);
3158
+ if (cached && cached.name && cached.mimeType) {
3159
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
3160
+ }
3161
+ }
3162
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
3163
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2937
3164
  const downloader = await this.getDownloader();
2938
3165
  const result = await downloader.download(fileId, processedOpts);
2939
3166
  return await this.pluginManager.runAfterDownload(result);
2940
3167
  }
2941
3168
  /**
2942
- * Gets file metadata
3169
+ * Gets file metadata and updates the local metadata cache
2943
3170
  */
2944
3171
  async getFile(fileIdOrPath) {
2945
3172
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2951,7 +3178,20 @@ var init_client = __esm({
2951
3178
  supportsAllDrives: true
2952
3179
  });
2953
3180
  });
2954
- return res.data;
3181
+ const file = res.data;
3182
+ if (this.metadataCacheInstance && file.id) {
3183
+ this.metadataCacheInstance.upsertFile({
3184
+ id: file.id,
3185
+ name: file.name || "",
3186
+ mimeType: file.mimeType || "",
3187
+ size: file.size ? parseInt(file.size, 10) : void 0,
3188
+ parentId: file.parents?.[0],
3189
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
3190
+ modifiedTime: file.modifiedTime || void 0,
3191
+ trashed: file.trashed || false
3192
+ });
3193
+ }
3194
+ return file;
2955
3195
  }
2956
3196
  /**
2957
3197
  * Reads file content as UTF-8 string
@@ -2994,6 +3234,9 @@ var init_client = __esm({
2994
3234
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
2995
3235
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
2996
3236
  }
3237
+ if (this.metadataCacheInstance) {
3238
+ this.metadataCacheInstance.deleteFile(fileId);
3239
+ }
2997
3240
  }
2998
3241
  /**
2999
3242
  * Move item to trash
@@ -3035,6 +3278,16 @@ var init_client = __esm({
3035
3278
  if (this.pathResolverInstance) {
3036
3279
  this.pathResolverInstance.clearCache();
3037
3280
  }
3281
+ if (this.metadataCacheInstance) {
3282
+ const cached = this.metadataCacheInstance.getById(fileId);
3283
+ if (cached) {
3284
+ this.metadataCacheInstance.upsertFile({
3285
+ ...cached,
3286
+ parentId: newParentId,
3287
+ path: void 0
3288
+ });
3289
+ }
3290
+ }
3038
3291
  return res.data;
3039
3292
  }
3040
3293
  /**
@@ -3077,6 +3330,16 @@ var init_client = __esm({
3077
3330
  if (this.pathResolverInstance) {
3078
3331
  this.pathResolverInstance.clearCache();
3079
3332
  }
3333
+ if (this.metadataCacheInstance) {
3334
+ const cached = this.metadataCacheInstance.getById(fileId);
3335
+ if (cached) {
3336
+ this.metadataCacheInstance.upsertFile({
3337
+ ...cached,
3338
+ name: newName,
3339
+ path: void 0
3340
+ });
3341
+ }
3342
+ }
3080
3343
  return res.data;
3081
3344
  }
3082
3345
  // ==========================================
@@ -3354,7 +3617,7 @@ var init_client = __esm({
3354
3617
  async createWriteStream(remotePath, options = {}) {
3355
3618
  await this.init();
3356
3619
  const { PassThrough } = await import("stream");
3357
- const passThrough = new PassThrough();
3620
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3358
3621
  let resolveDone;
3359
3622
  let rejectDone;
3360
3623
  const donePromise = new Promise((resolve, reject) => {
@@ -3401,6 +3664,12 @@ var init_client = __esm({
3401
3664
  // ==========================================
3402
3665
  // METADATA CACHE OPERATIONS
3403
3666
  // ==========================================
3667
+ /**
3668
+ * Synchronous getter for the active metadata cache instance
3669
+ */
3670
+ get cache() {
3671
+ return this.metadataCacheInstance;
3672
+ }
3404
3673
  /**
3405
3674
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3406
3675
  */
@@ -3423,6 +3692,9 @@ var init_client = __esm({
3423
3692
  if (this.pathResolverInstance) {
3424
3693
  this.pathResolverInstance.clearCache();
3425
3694
  }
3695
+ if (this.metadataCacheInstance) {
3696
+ this.metadataCacheInstance.clear();
3697
+ }
3426
3698
  }
3427
3699
  /**
3428
3700
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3769,7 +4041,7 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
3769
4041
 
3770
4042
  // src/cli.ts
3771
4043
  var program = new Command();
3772
- var pkgVersion = "1.1.1";
4044
+ var pkgVersion = "1.1.2";
3773
4045
  try {
3774
4046
  const pkgPath = new URL("../package.json", import.meta.url);
3775
4047
  const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
@@ -3779,7 +4051,19 @@ try {
3779
4051
  program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3780
4052
  function getAuthConfig(cmdOptions) {
3781
4053
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3782
- const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4054
+ let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4055
+ if (!keyFilePath && !accessToken) {
4056
+ const tokensFile = path9.resolve(process.cwd(), "gdrive-tokens.json");
4057
+ if (fs7.existsSync(tokensFile)) {
4058
+ try {
4059
+ const tokens = JSON.parse(fs7.readFileSync(tokensFile, "utf8"));
4060
+ if (tokens.access_token) {
4061
+ accessToken = tokens.access_token;
4062
+ }
4063
+ } catch {
4064
+ }
4065
+ }
4066
+ }
3783
4067
  return {
3784
4068
  keyFilePath,
3785
4069
  accessToken