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.cjs CHANGED
@@ -92,6 +92,31 @@ var init_errors = __esm({
92
92
  }
93
93
  });
94
94
 
95
+ // src/utils/http-agent.ts
96
+ function getOptimizedHttpsAgent(options) {
97
+ if (!sharedHttpsAgent) {
98
+ sharedHttpsAgent = new import_node_https.default.Agent({
99
+ keepAlive: options?.keepAlive ?? true,
100
+ maxSockets: options?.maxSockets ?? 64,
101
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
102
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
103
+ timeout: options?.timeout ?? 3e4,
104
+ noDelay: true
105
+ });
106
+ }
107
+ return sharedHttpsAgent;
108
+ }
109
+ var import_node_https, import_node_http, sharedHttpsAgent;
110
+ var init_http_agent = __esm({
111
+ "src/utils/http-agent.ts"() {
112
+ "use strict";
113
+ init_cjs_shims();
114
+ import_node_https = __toESM(require("https"), 1);
115
+ import_node_http = __toESM(require("http"), 1);
116
+ sharedHttpsAgent = null;
117
+ }
118
+ });
119
+
95
120
  // src/auth/authenticator.ts
96
121
  var import_node_fs, import_drive, DEFAULT_SCOPES, DriveAuthenticator;
97
122
  var init_authenticator = __esm({
@@ -101,6 +126,7 @@ var init_authenticator = __esm({
101
126
  import_node_fs = __toESM(require("fs"), 1);
102
127
  import_drive = require("@googleapis/drive");
103
128
  init_errors();
129
+ init_http_agent();
104
130
  DEFAULT_SCOPES = [
105
131
  "https://www.googleapis.com/auth/drive"
106
132
  ];
@@ -123,44 +149,39 @@ var init_authenticator = __esm({
123
149
  const oauth2Client = new import_drive.auth.OAuth2();
124
150
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
125
151
  this.authClient = oauth2Client;
126
- return this.authClient;
127
- }
128
- if (this.config.oauth2Client) {
152
+ } else if (this.config.oauth2Client) {
129
153
  this.authClient = this.config.oauth2Client;
130
- return this.authClient;
131
- }
132
- if (this.config.oauth) {
154
+ } else if (this.config.oauth) {
133
155
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
134
156
  const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
135
157
  if (refreshToken) {
136
158
  oauth2Client.setCredentials({ refresh_token: refreshToken });
137
159
  }
138
160
  this.authClient = oauth2Client;
139
- return this.authClient;
140
- }
141
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
142
- if (keyFile) {
143
- if (!import_node_fs.default.existsSync(keyFile)) {
161
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
162
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
163
+ if (keyFile && !import_node_fs.default.existsSync(keyFile)) {
144
164
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
145
165
  }
146
- const auth2 = new import_drive.auth.GoogleAuth({
166
+ const auth = new import_drive.auth.GoogleAuth({
147
167
  keyFile,
148
168
  scopes
149
169
  });
150
- this.authClient = auth2;
151
- return this.authClient;
152
- }
153
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
154
- if (creds) {
155
- const auth2 = new import_drive.auth.GoogleAuth({
170
+ this.authClient = auth;
171
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
172
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
173
+ const auth = new import_drive.auth.GoogleAuth({
156
174
  credentials: creds,
157
175
  scopes
158
176
  });
159
- this.authClient = auth2;
160
- return this.authClient;
177
+ this.authClient = auth;
178
+ } else {
179
+ const auth = new import_drive.auth.GoogleAuth({ scopes });
180
+ this.authClient = auth;
181
+ }
182
+ if (this.authClient?.transporter?.defaults) {
183
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
161
184
  }
162
- const auth = new import_drive.auth.GoogleAuth({ scopes });
163
- this.authClient = auth;
164
185
  return this.authClient;
165
186
  } catch (err) {
166
187
  if (err instanceof DriveAuthError) throw err;
@@ -319,6 +340,7 @@ var init_path_resolver = __esm({
319
340
  drive;
320
341
  rootFolderId;
321
342
  cache = /* @__PURE__ */ new Map();
343
+ inFlightResolves = /* @__PURE__ */ new Map();
322
344
  cacheTTL;
323
345
  enableCache;
324
346
  metadataCache;
@@ -371,6 +393,7 @@ var init_path_resolver = __esm({
371
393
  /**
372
394
  * Resolves a path to a Google Drive item (file or folder).
373
395
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
396
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
374
397
  */
375
398
  async resolve(virtualPath, options = {}) {
376
399
  const norm = this.normalizePath(virtualPath);
@@ -404,6 +427,20 @@ var init_path_resolver = __esm({
404
427
  };
405
428
  }
406
429
  }
430
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
431
+ const inFlight = this.inFlightResolves.get(flightKey);
432
+ if (inFlight) {
433
+ return await inFlight;
434
+ }
435
+ const task = this.doResolve(virtualPath, norm, options);
436
+ this.inFlightResolves.set(flightKey, task);
437
+ try {
438
+ return await task;
439
+ } finally {
440
+ this.inFlightResolves.delete(flightKey);
441
+ }
442
+ }
443
+ async doResolve(virtualPath, norm, options) {
407
444
  const segments = norm.split("/").filter(Boolean);
408
445
  let currentParentId = this.rootFolderId;
409
446
  let currentPath = "";
@@ -455,7 +492,7 @@ var init_path_resolver = __esm({
455
492
  });
456
493
  let file = response.data.files?.[0];
457
494
  if (!file && currentParentId === this.rootFolderId) {
458
- const sharedQ = `name = '${escapedName}' and trashed = false`;
495
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
459
496
  const sharedResponse = await withRetry(async () => {
460
497
  return await this.drive.files.list({
461
498
  q: sharedQ,
@@ -583,17 +620,19 @@ var init_format = __esm({
583
620
  });
584
621
 
585
622
  // src/core/resumable-uploader.ts
586
- var import_node_fs2, import_node_path, MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
623
+ var import_node_fs2, import_node_path, import_node_stream, MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
587
624
  var init_resumable_uploader = __esm({
588
625
  "src/core/resumable-uploader.ts"() {
589
626
  "use strict";
590
627
  init_cjs_shims();
591
628
  import_node_fs2 = __toESM(require("fs"), 1);
592
629
  import_node_path = __toESM(require("path"), 1);
630
+ import_node_stream = require("stream");
593
631
  init_errors();
594
632
  init_format();
595
633
  init_mime();
596
634
  init_retry();
635
+ init_http_agent();
597
636
  MIN_CHUNK_SIZE = 256 * 1024;
598
637
  DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
599
638
  MULTIPART_THRESHOLD = 5 * 1024 * 1024;
@@ -631,6 +670,15 @@ var init_resumable_uploader = __esm({
631
670
  const totalBytes = stat.size;
632
671
  const fileName = options.name || import_node_path.default.basename(filePath);
633
672
  const mimeType = options.mimeType || lookupMimeType(filePath);
673
+ if (totalBytes <= MULTIPART_THRESHOLD) {
674
+ const readStream = import_node_fs2.default.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
675
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
676
+ return await this.directUpload(stream, {
677
+ ...options,
678
+ name: fileName,
679
+ mimeType
680
+ });
681
+ }
634
682
  return await this.chunkedUpload({
635
683
  filePath,
636
684
  totalBytes,
@@ -646,6 +694,16 @@ var init_resumable_uploader = __esm({
646
694
  const totalBytes = buffer.length;
647
695
  const fileName = options.name || "untitled";
648
696
  const mimeType = options.mimeType || "application/octet-stream";
697
+ if (totalBytes <= MULTIPART_THRESHOLD) {
698
+ const { Readable } = await import("stream");
699
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
700
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
701
+ return await this.directUpload(stream, {
702
+ ...options,
703
+ name: fileName,
704
+ mimeType
705
+ });
706
+ }
649
707
  return await this.chunkedUploadBuffer({
650
708
  buffer,
651
709
  totalBytes,
@@ -666,6 +724,50 @@ var init_resumable_uploader = __esm({
666
724
  mimeType
667
725
  });
668
726
  }
727
+ /**
728
+ * Calculates optimal chunk size based on file size for maximum throughput.
729
+ */
730
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
731
+ if (explicitChunkSize) {
732
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
733
+ }
734
+ if (totalBytes > 128 * 1024 * 1024) {
735
+ return 32 * 1024 * 1024;
736
+ }
737
+ if (totalBytes > 32 * 1024 * 1024) {
738
+ return 16 * 1024 * 1024;
739
+ }
740
+ return this.defaultChunkSize;
741
+ }
742
+ /**
743
+ * Attaches real-time progress monitoring to direct stream uploads.
744
+ */
745
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
746
+ let bytesSent = 0;
747
+ const startTime = Date.now();
748
+ const progressTransform = new import_node_stream.Transform({
749
+ transform(chunk, _encoding, callback) {
750
+ bytesSent += chunk.length;
751
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
752
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
753
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
754
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
755
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
756
+ onProgress({
757
+ bytesSent,
758
+ totalBytes,
759
+ percentage,
760
+ bytesPerSecond,
761
+ speedFormatted: formatSpeed(bytesPerSecond),
762
+ estimatedTimeRemainingSeconds,
763
+ chunkIndex: 1,
764
+ totalChunks: 1
765
+ });
766
+ callback(null, chunk);
767
+ }
768
+ });
769
+ return stream.pipe(progressTransform);
770
+ }
669
771
  /**
670
772
  * Fast direct upload using googleapis multipart
671
773
  */
@@ -698,7 +800,7 @@ var init_resumable_uploader = __esm({
698
800
  */
699
801
  async chunkedUpload(params) {
700
802
  const { filePath, totalBytes, fileName, mimeType, options } = params;
701
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
803
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
702
804
  const sessionUrl = await this.initiateResumableSession({
703
805
  fileName,
704
806
  mimeType,
@@ -763,7 +865,7 @@ var init_resumable_uploader = __esm({
763
865
  */
764
866
  async chunkedUploadBuffer(params) {
765
867
  const { buffer, totalBytes, fileName, mimeType, options } = params;
766
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
868
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
767
869
  const sessionUrl = await this.initiateResumableSession({
768
870
  fileName,
769
871
  mimeType,
@@ -842,7 +944,8 @@ var init_resumable_uploader = __esm({
842
944
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
843
945
  method: "POST",
844
946
  headers,
845
- data: metadata
947
+ data: metadata,
948
+ agent: getOptimizedHttpsAgent()
846
949
  });
847
950
  });
848
951
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -868,6 +971,7 @@ var init_resumable_uploader = __esm({
868
971
  method: "PUT",
869
972
  headers,
870
973
  data: buffer,
974
+ agent: getOptimizedHttpsAgent(),
871
975
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
872
976
  });
873
977
  if (res.status === 200 || res.status === 201) {
@@ -899,7 +1003,7 @@ var init_resumable_uploader = __esm({
899
1003
  });
900
1004
 
901
1005
  // src/core/downloader.ts
902
- var import_node_fs3, import_node_path2, import_promises, import_node_stream, Downloader;
1006
+ var import_node_fs3, import_node_path2, import_promises, import_node_stream2, Downloader;
903
1007
  var init_downloader = __esm({
904
1008
  "src/core/downloader.ts"() {
905
1009
  "use strict";
@@ -907,7 +1011,7 @@ var init_downloader = __esm({
907
1011
  import_node_fs3 = __toESM(require("fs"), 1);
908
1012
  import_node_path2 = __toESM(require("path"), 1);
909
1013
  import_promises = require("stream/promises");
910
- import_node_stream = require("stream");
1014
+ import_node_stream2 = require("stream");
911
1015
  init_mime();
912
1016
  init_format();
913
1017
  init_retry();
@@ -920,17 +1024,22 @@ var init_downloader = __esm({
920
1024
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
921
1025
  */
922
1026
  async download(fileId, options = {}) {
923
- const metaRes = await withRetry(async () => {
924
- return await this.drive.files.get({
925
- fileId,
926
- fields: "id, name, mimeType, size",
927
- supportsAllDrives: true
1027
+ let name = options.metadata?.name;
1028
+ let mimeType = options.metadata?.mimeType;
1029
+ let totalBytes = options.metadata?.size;
1030
+ if (!name || !mimeType) {
1031
+ const metaRes = await withRetry(async () => {
1032
+ return await this.drive.files.get({
1033
+ fileId,
1034
+ fields: "id, name, mimeType, size",
1035
+ supportsAllDrives: true
1036
+ });
928
1037
  });
929
- });
930
- const file = metaRes.data;
931
- const name = file.name || "downloaded-file";
932
- const mimeType = file.mimeType || "application/octet-stream";
933
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1038
+ const file = metaRes.data;
1039
+ name = file.name || "downloaded-file";
1040
+ mimeType = file.mimeType || "application/octet-stream";
1041
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1042
+ }
934
1043
  let downloadStream;
935
1044
  let finalFileName = name;
936
1045
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -961,7 +1070,7 @@ var init_downloader = __esm({
961
1070
  }
962
1071
  let bytesRead = 0;
963
1072
  const startTime = Date.now();
964
- const progressTracker = new import_node_stream.Transform({
1073
+ const progressTracker = new import_node_stream2.Transform({
965
1074
  transform(chunk, encoding, callback) {
966
1075
  bytesRead += chunk.length;
967
1076
  if (options.onProgress) {
@@ -986,7 +1095,7 @@ var init_downloader = __esm({
986
1095
  destPath = import_node_path2.default.join(destPath, finalFileName);
987
1096
  }
988
1097
  await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
989
- const writeStream = import_node_fs3.default.createWriteStream(destPath);
1098
+ const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
990
1099
  await (0, import_promises.pipeline)(monitoredStream, writeStream);
991
1100
  return {
992
1101
  filePath: destPath,
@@ -1237,6 +1346,7 @@ var init_query_builder = __esm({
1237
1346
  const q = this.toQueryString();
1238
1347
  const orderBy = this.orderClauses.join(", ");
1239
1348
  let pageToken = void 0;
1349
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1240
1350
  do {
1241
1351
  const res = await withRetry(async () => {
1242
1352
  return await this.drive.files.list({
@@ -1244,7 +1354,7 @@ var init_query_builder = __esm({
1244
1354
  orderBy: orderBy || void 0,
1245
1355
  pageSize: this.limitNumber,
1246
1356
  pageToken,
1247
- fields: this.requestedFields,
1357
+ fields: effectiveFields,
1248
1358
  spaces: this.spaces,
1249
1359
  supportsAllDrives: true,
1250
1360
  includeItemsFromAllDrives: true
@@ -1381,7 +1491,7 @@ var init_watcher = __esm({
1381
1491
  const res = await withRetry(async () => {
1382
1492
  return await this.drive.changes.list({
1383
1493
  pageToken: nextPageToken,
1384
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1494
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1385
1495
  supportsAllDrives: true,
1386
1496
  includeItemsFromAllDrives: true
1387
1497
  });
@@ -1480,16 +1590,24 @@ var init_storage_cleaner = __esm({
1480
1590
  async findDuplicates(options = {}) {
1481
1591
  const mode = options.by || "name";
1482
1592
  const maxScan = options.maxScan || 1e3;
1483
- const res = await withRetry(async () => {
1484
- return await this.drive.files.list({
1485
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1486
- pageSize: Math.min(1e3, maxScan),
1487
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1488
- supportsAllDrives: true,
1489
- includeItemsFromAllDrives: true
1593
+ const files = [];
1594
+ let pageToken = void 0;
1595
+ do {
1596
+ const remaining = maxScan - files.length;
1597
+ if (remaining <= 0) break;
1598
+ const res = await withRetry(async () => {
1599
+ return await this.drive.files.list({
1600
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1601
+ pageSize: Math.min(1e3, remaining),
1602
+ pageToken,
1603
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1604
+ supportsAllDrives: true,
1605
+ includeItemsFromAllDrives: true
1606
+ });
1490
1607
  });
1491
- });
1492
- const files = res.data.files || [];
1608
+ files.push(...res.data.files || []);
1609
+ pageToken = res.data.nextPageToken || void 0;
1610
+ } while (pageToken && files.length < maxScan);
1493
1611
  const map = /* @__PURE__ */ new Map();
1494
1612
  for (const f of files) {
1495
1613
  if (!f.id) continue;
@@ -1689,7 +1807,7 @@ async function loginWithBrowser(options) {
1689
1807
  scope: scopes
1690
1808
  });
1691
1809
  return new Promise((resolve, reject) => {
1692
- const server = import_node_http.default.createServer(async (req, res) => {
1810
+ const server = import_node_http2.default.createServer(async (req, res) => {
1693
1811
  try {
1694
1812
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1695
1813
  if (reqUrl.pathname === "/oauth2callback") {
@@ -1773,16 +1891,20 @@ ${authUrl}
1773
1891
  });
1774
1892
  });
1775
1893
  server.on("error", (err) => {
1776
- reject(err);
1894
+ if (err.code === "EADDRINUSE") {
1895
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
1896
+ } else {
1897
+ reject(err);
1898
+ }
1777
1899
  });
1778
1900
  });
1779
1901
  }
1780
- var import_node_http, import_node_child_process, import_drive2;
1902
+ var import_node_http2, import_node_child_process, import_drive2;
1781
1903
  var init_browser_login = __esm({
1782
1904
  "src/auth/browser-login.ts"() {
1783
1905
  "use strict";
1784
1906
  init_cjs_shims();
1785
- import_node_http = __toESM(require("http"), 1);
1907
+ import_node_http2 = __toESM(require("http"), 1);
1786
1908
  import_node_child_process = require("child_process");
1787
1909
  import_drive2 = require("@googleapis/drive");
1788
1910
  init_authenticator();
@@ -2149,10 +2271,35 @@ var init_cache = __esm({
2149
2271
  return;
2150
2272
  }
2151
2273
  if (!this.initialized || !this.db || entries.length === 0) return;
2274
+ const stmt = this.db.prepare(`
2275
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2276
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2277
+ ON CONFLICT(id) DO UPDATE SET
2278
+ name = excluded.name,
2279
+ mimeType = excluded.mimeType,
2280
+ size = excluded.size,
2281
+ parentId = excluded.parentId,
2282
+ path = COALESCE(excluded.path, files.path),
2283
+ md5Checksum = excluded.md5Checksum,
2284
+ trashed = excluded.trashed,
2285
+ modifiedTime = excluded.modifiedTime,
2286
+ updatedAt = excluded.updatedAt
2287
+ `);
2152
2288
  this.db.exec("BEGIN TRANSACTION;");
2153
2289
  try {
2154
2290
  for (const entry of entries) {
2155
- this.upsertFile(entry);
2291
+ stmt.run(
2292
+ entry.id,
2293
+ entry.name,
2294
+ entry.mimeType ?? null,
2295
+ entry.size ?? null,
2296
+ entry.parentId ?? null,
2297
+ entry.path ?? null,
2298
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2299
+ entry.trashed ? 1 : 0,
2300
+ entry.modifiedTime ?? null,
2301
+ entry.updatedAt ?? Date.now()
2302
+ );
2156
2303
  }
2157
2304
  this.db.exec("COMMIT;");
2158
2305
  } catch (e) {
@@ -2384,7 +2531,7 @@ async function startWebDAVServer(drive2, options = {}) {
2384
2531
  const port = options.port || 8080;
2385
2532
  const host = options.host || "127.0.0.1";
2386
2533
  await drive2.init();
2387
- const server = import_node_http2.default.createServer(async (req, res) => {
2534
+ const server = import_node_http3.default.createServer(async (req, res) => {
2388
2535
  try {
2389
2536
  if (options.auth?.username && options.auth?.password) {
2390
2537
  const authHeader = req.headers["authorization"];
@@ -2410,6 +2557,12 @@ async function startWebDAVServer(drive2, options = {}) {
2410
2557
  const parsedUrl = import_node_url.default.parse(req.url || "/", true);
2411
2558
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2412
2559
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
2560
+ const baseName = import_node_path6.default.basename(virtualPath);
2561
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
2562
+ res.writeHead(404, { "Content-Type": "text/plain" });
2563
+ res.end("Not Found");
2564
+ return;
2565
+ }
2413
2566
  switch (req.method) {
2414
2567
  case "OPTIONS": {
2415
2568
  res.writeHead(200, {
@@ -2424,6 +2577,11 @@ async function startWebDAVServer(drive2, options = {}) {
2424
2577
  case "PROPFIND": {
2425
2578
  const depth = req.headers["depth"] || "1";
2426
2579
  const xml = await handlePropfind(drive2, virtualPath, depth);
2580
+ if (xml === null) {
2581
+ res.writeHead(404, { "Content-Type": "text/plain" });
2582
+ res.end("Not Found");
2583
+ return;
2584
+ }
2427
2585
  res.writeHead(207, {
2428
2586
  "Content-Type": "application/xml; charset=utf-8"
2429
2587
  });
@@ -2634,25 +2792,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
2634
2792
  virtualPath,
2635
2793
  isFolder,
2636
2794
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
2637
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2795
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2796
+ selfItem.mimeType || void 0
2638
2797
  )
2639
2798
  );
2640
2799
  } catch {
2641
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
2800
+ return null;
2642
2801
  }
2643
2802
  }
2644
2803
  if (isFolder && depth !== "0") {
2645
2804
  try {
2646
2805
  const children = await drive2.ls(virtualPath);
2806
+ const seenNames = /* @__PURE__ */ new Map();
2647
2807
  for (const child of children) {
2808
+ let childName = child.name || "untitled";
2809
+ if (seenNames.has(childName)) {
2810
+ const count = seenNames.get(childName) + 1;
2811
+ seenNames.set(childName, count);
2812
+ const ext = import_node_path6.default.extname(childName);
2813
+ const base = import_node_path6.default.basename(childName, ext);
2814
+ childName = `${base} (${count})${ext}`;
2815
+ } else {
2816
+ seenNames.set(childName, 0);
2817
+ }
2648
2818
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2649
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
2819
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
2650
2820
  responses.push(
2651
2821
  renderWebDAVResponse(
2652
2822
  childPath,
2653
2823
  childIsFolder,
2654
2824
  child.size ? parseInt(child.size, 10) : 0,
2655
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2825
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2826
+ child.mimeType || void 0
2656
2827
  )
2657
2828
  );
2658
2829
  }
@@ -2664,11 +2835,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
2664
2835
  ${responses.join("\n")}
2665
2836
  </D:multistatus>`;
2666
2837
  }
2667
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2668
- const encodedHref = encodeURI(href);
2838
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
2839
+ let cleanHref = href;
2840
+ if (isDir && !cleanHref.endsWith("/")) {
2841
+ cleanHref += "/";
2842
+ }
2843
+ const encodedHref = encodeURI(cleanHref);
2669
2844
  const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
2670
2845
  const resourceType = isDir ? "<D:collection/>" : "";
2671
2846
  const dateFormatted = new Date(modifiedTime).toUTCString();
2847
+ const contentTypeTag = !isDir && mimeType ? `
2848
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
2672
2849
  return ` <D:response>
2673
2850
  <D:href>${encodedHref}</D:href>
2674
2851
  <D:propstat>
@@ -2676,19 +2853,18 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2676
2853
  <D:displayname>${displayName}</D:displayname>
2677
2854
  <D:resourcetype>${resourceType}</D:resourcetype>
2678
2855
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2679
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2680
- <D:status>HTTP/1.1 200 OK</D:status>
2856
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
2681
2857
  </D:prop>
2682
2858
  <D:status>HTTP/1.1 200 OK</D:status>
2683
2859
  </D:propstat>
2684
2860
  </D:response>`;
2685
2861
  }
2686
- var import_node_http2, import_node_url, import_node_path6;
2862
+ var import_node_http3, import_node_url, import_node_path6;
2687
2863
  var init_webdav = __esm({
2688
2864
  "src/server/webdav.ts"() {
2689
2865
  "use strict";
2690
2866
  init_cjs_shims();
2691
- import_node_http2 = __toESM(require("http"), 1);
2867
+ import_node_http3 = __toESM(require("http"), 1);
2692
2868
  import_node_url = __toESM(require("url"), 1);
2693
2869
  import_node_path6 = __toESM(require("path"), 1);
2694
2870
  }
@@ -2723,6 +2899,7 @@ var init_client = __esm({
2723
2899
  init_format();
2724
2900
  init_mime();
2725
2901
  init_cache();
2902
+ init_http_agent();
2726
2903
  DriveKit = class _DriveKit {
2727
2904
  options;
2728
2905
  authenticator;
@@ -2745,6 +2922,18 @@ var init_client = __esm({
2745
2922
  this.pluginManager.use(plugin);
2746
2923
  return this;
2747
2924
  }
2925
+ /**
2926
+ * Unregisters a middleware plugin by name
2927
+ */
2928
+ unuse(pluginName) {
2929
+ return this.pluginManager.unuse(pluginName);
2930
+ }
2931
+ /**
2932
+ * Access the underlying plugin manager instance
2933
+ */
2934
+ get plugins() {
2935
+ return this.pluginManager;
2936
+ }
2748
2937
  /**
2749
2938
  * Returns a fluent, chained reference to a specific file
2750
2939
  */
@@ -2763,7 +2952,8 @@ var init_client = __esm({
2763
2952
  async init() {
2764
2953
  if (!this.driveClient) {
2765
2954
  const auth = await this.authenticator.getAuthClient();
2766
- this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2955
+ const agent = getOptimizedHttpsAgent();
2956
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
2767
2957
  if (this.options.enablePersistentCache !== false) {
2768
2958
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2769
2959
  this.metadataCacheInstance.init();
@@ -2850,15 +3040,41 @@ var init_client = __esm({
2850
3040
  }
2851
3041
  }
2852
3042
  /**
2853
- * Lists contents of a folder (by folder ID or path)
3043
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2854
3044
  */
2855
3045
  async ls(folderIdOrPath = "/") {
3046
+ let parentFolderId;
3047
+ let normalizedPath = null;
3048
+ let files;
2856
3049
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3050
+ parentFolderId = this.rootFolderId;
3051
+ normalizedPath = "/";
2857
3052
  const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2858
- return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3053
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
3054
+ } else {
3055
+ if (folderIdOrPath.startsWith("/")) {
3056
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
3057
+ parentFolderId = await this.resolveId(normalizedPath);
3058
+ } else {
3059
+ parentFolderId = folderIdOrPath;
3060
+ }
3061
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
3062
+ }
3063
+ if (this.metadataCacheInstance && files.length > 0) {
3064
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
3065
+ id: f.id,
3066
+ name: f.name || "untitled",
3067
+ mimeType: f.mimeType || "",
3068
+ size: f.size ? parseInt(f.size, 10) : void 0,
3069
+ parentId: parentFolderId,
3070
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
3071
+ md5Checksum: f.md5Checksum || void 0,
3072
+ modifiedTime: f.modifiedTime || void 0,
3073
+ trashed: false
3074
+ }));
3075
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
2859
3076
  }
2860
- const folderId = await this.resolveId(folderIdOrPath);
2861
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
3077
+ return files;
2862
3078
  }
2863
3079
  // ==========================================
2864
3080
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2877,7 +3093,7 @@ var init_client = __esm({
2877
3093
  if (parentId && parentId.startsWith("/")) {
2878
3094
  parentId = await this.mkdirp(parentId);
2879
3095
  }
2880
- const targetName = opts.name || opts.filename;
3096
+ const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? import_node_path7.default.basename(opts.source) : void 0);
2881
3097
  if (opts.overwrite && targetName && parentId) {
2882
3098
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2883
3099
  if (existing?.id) {
@@ -2933,12 +3149,14 @@ var init_client = __esm({
2933
3149
  parent: parentId
2934
3150
  });
2935
3151
  if (this.metadataCacheInstance && uploaded.id) {
3152
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2936
3153
  this.metadataCacheInstance.upsertFile({
2937
3154
  id: uploaded.id,
2938
3155
  name: uploaded.name || targetName || "untitled",
2939
3156
  mimeType: uploaded.mimeType || "",
2940
3157
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2941
3158
  parentId,
3159
+ path: virtualPath,
2942
3160
  trashed: false
2943
3161
  });
2944
3162
  }
@@ -2949,16 +3167,25 @@ var init_client = __esm({
2949
3167
  * - Automatic conversion for Google Docs, Sheets, and Slides
2950
3168
  * - Progress events
2951
3169
  * - Saves directly to file or returns Readable Stream
3170
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2952
3171
  */
2953
3172
  async download(fileIdOrPath, options = {}) {
2954
3173
  const fileId = await this.resolveId(fileIdOrPath);
2955
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
3174
+ let cachedMeta = options.metadata;
3175
+ if (!cachedMeta && this.metadataCacheInstance) {
3176
+ const cached = this.metadataCacheInstance.getById(fileId);
3177
+ if (cached && cached.name && cached.mimeType) {
3178
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
3179
+ }
3180
+ }
3181
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
3182
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2956
3183
  const downloader = await this.getDownloader();
2957
3184
  const result = await downloader.download(fileId, processedOpts);
2958
3185
  return await this.pluginManager.runAfterDownload(result);
2959
3186
  }
2960
3187
  /**
2961
- * Gets file metadata
3188
+ * Gets file metadata and updates the local metadata cache
2962
3189
  */
2963
3190
  async getFile(fileIdOrPath) {
2964
3191
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2970,7 +3197,20 @@ var init_client = __esm({
2970
3197
  supportsAllDrives: true
2971
3198
  });
2972
3199
  });
2973
- return res.data;
3200
+ const file = res.data;
3201
+ if (this.metadataCacheInstance && file.id) {
3202
+ this.metadataCacheInstance.upsertFile({
3203
+ id: file.id,
3204
+ name: file.name || "",
3205
+ mimeType: file.mimeType || "",
3206
+ size: file.size ? parseInt(file.size, 10) : void 0,
3207
+ parentId: file.parents?.[0],
3208
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
3209
+ modifiedTime: file.modifiedTime || void 0,
3210
+ trashed: file.trashed || false
3211
+ });
3212
+ }
3213
+ return file;
2974
3214
  }
2975
3215
  /**
2976
3216
  * Reads file content as UTF-8 string
@@ -3013,6 +3253,9 @@ var init_client = __esm({
3013
3253
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
3014
3254
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
3015
3255
  }
3256
+ if (this.metadataCacheInstance) {
3257
+ this.metadataCacheInstance.deleteFile(fileId);
3258
+ }
3016
3259
  }
3017
3260
  /**
3018
3261
  * Move item to trash
@@ -3054,6 +3297,16 @@ var init_client = __esm({
3054
3297
  if (this.pathResolverInstance) {
3055
3298
  this.pathResolverInstance.clearCache();
3056
3299
  }
3300
+ if (this.metadataCacheInstance) {
3301
+ const cached = this.metadataCacheInstance.getById(fileId);
3302
+ if (cached) {
3303
+ this.metadataCacheInstance.upsertFile({
3304
+ ...cached,
3305
+ parentId: newParentId,
3306
+ path: void 0
3307
+ });
3308
+ }
3309
+ }
3057
3310
  return res.data;
3058
3311
  }
3059
3312
  /**
@@ -3096,6 +3349,16 @@ var init_client = __esm({
3096
3349
  if (this.pathResolverInstance) {
3097
3350
  this.pathResolverInstance.clearCache();
3098
3351
  }
3352
+ if (this.metadataCacheInstance) {
3353
+ const cached = this.metadataCacheInstance.getById(fileId);
3354
+ if (cached) {
3355
+ this.metadataCacheInstance.upsertFile({
3356
+ ...cached,
3357
+ name: newName,
3358
+ path: void 0
3359
+ });
3360
+ }
3361
+ }
3099
3362
  return res.data;
3100
3363
  }
3101
3364
  // ==========================================
@@ -3373,7 +3636,7 @@ var init_client = __esm({
3373
3636
  async createWriteStream(remotePath, options = {}) {
3374
3637
  await this.init();
3375
3638
  const { PassThrough } = await import("stream");
3376
- const passThrough = new PassThrough();
3639
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3377
3640
  let resolveDone;
3378
3641
  let rejectDone;
3379
3642
  const donePromise = new Promise((resolve, reject) => {
@@ -3420,6 +3683,12 @@ var init_client = __esm({
3420
3683
  // ==========================================
3421
3684
  // METADATA CACHE OPERATIONS
3422
3685
  // ==========================================
3686
+ /**
3687
+ * Synchronous getter for the active metadata cache instance
3688
+ */
3689
+ get cache() {
3690
+ return this.metadataCacheInstance;
3691
+ }
3423
3692
  /**
3424
3693
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3425
3694
  */
@@ -3442,6 +3711,9 @@ var init_client = __esm({
3442
3711
  if (this.pathResolverInstance) {
3443
3712
  this.pathResolverInstance.clearCache();
3444
3713
  }
3714
+ if (this.metadataCacheInstance) {
3715
+ this.metadataCacheInstance.clear();
3716
+ }
3445
3717
  }
3446
3718
  /**
3447
3719
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3793,7 +4065,7 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
3793
4065
 
3794
4066
  // src/cli.ts
3795
4067
  var program = new import_commander.Command();
3796
- var pkgVersion = "1.1.1";
4068
+ var pkgVersion = "1.1.2";
3797
4069
  try {
3798
4070
  const pkgPath = new URL("../package.json", importMetaUrl);
3799
4071
  const pkg = JSON.parse(import_node_fs7.default.readFileSync(pkgPath, "utf8"));
@@ -3803,7 +4075,19 @@ try {
3803
4075
  program.name("drivekit").description(import_chalk2.default.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");
3804
4076
  function getAuthConfig(cmdOptions) {
3805
4077
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3806
- const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4078
+ let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4079
+ if (!keyFilePath && !accessToken) {
4080
+ const tokensFile = import_node_path8.default.resolve(process.cwd(), "gdrive-tokens.json");
4081
+ if (import_node_fs7.default.existsSync(tokensFile)) {
4082
+ try {
4083
+ const tokens = JSON.parse(import_node_fs7.default.readFileSync(tokensFile, "utf8"));
4084
+ if (tokens.access_token) {
4085
+ accessToken = tokens.access_token;
4086
+ }
4087
+ } catch {
4088
+ }
4089
+ }
4090
+ }
3807
4091
  return {
3808
4092
  keyFilePath,
3809
4093
  accessToken