drivekit 1.1.0 → 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
@@ -31,9 +31,12 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
31
31
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
32
 
33
33
  // node_modules/tsup/assets/cjs_shims.js
34
+ var getImportMetaUrl, importMetaUrl;
34
35
  var init_cjs_shims = __esm({
35
36
  "node_modules/tsup/assets/cjs_shims.js"() {
36
37
  "use strict";
38
+ getImportMetaUrl = () => typeof document === "undefined" ? new URL(`file:${__filename}`).href : document.currentScript && document.currentScript.tagName.toUpperCase() === "SCRIPT" ? document.currentScript.src : new URL("main.js", document.baseURI).href;
39
+ importMetaUrl = /* @__PURE__ */ getImportMetaUrl();
37
40
  }
38
41
  });
39
42
 
@@ -89,6 +92,31 @@ var init_errors = __esm({
89
92
  }
90
93
  });
91
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
+
92
120
  // src/auth/authenticator.ts
93
121
  var import_node_fs, import_drive, DEFAULT_SCOPES, DriveAuthenticator;
94
122
  var init_authenticator = __esm({
@@ -98,6 +126,7 @@ var init_authenticator = __esm({
98
126
  import_node_fs = __toESM(require("fs"), 1);
99
127
  import_drive = require("@googleapis/drive");
100
128
  init_errors();
129
+ init_http_agent();
101
130
  DEFAULT_SCOPES = [
102
131
  "https://www.googleapis.com/auth/drive"
103
132
  ];
@@ -120,44 +149,39 @@ var init_authenticator = __esm({
120
149
  const oauth2Client = new import_drive.auth.OAuth2();
121
150
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
122
151
  this.authClient = oauth2Client;
123
- return this.authClient;
124
- }
125
- if (this.config.oauth2Client) {
152
+ } else if (this.config.oauth2Client) {
126
153
  this.authClient = this.config.oauth2Client;
127
- return this.authClient;
128
- }
129
- if (this.config.oauth) {
154
+ } else if (this.config.oauth) {
130
155
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
131
156
  const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
132
157
  if (refreshToken) {
133
158
  oauth2Client.setCredentials({ refresh_token: refreshToken });
134
159
  }
135
160
  this.authClient = oauth2Client;
136
- return this.authClient;
137
- }
138
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
139
- if (keyFile) {
140
- 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)) {
141
164
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
142
165
  }
143
- const auth2 = new import_drive.auth.GoogleAuth({
166
+ const auth = new import_drive.auth.GoogleAuth({
144
167
  keyFile,
145
168
  scopes
146
169
  });
147
- this.authClient = auth2;
148
- return this.authClient;
149
- }
150
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
151
- if (creds) {
152
- 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({
153
174
  credentials: creds,
154
175
  scopes
155
176
  });
156
- this.authClient = auth2;
157
- 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();
158
184
  }
159
- const auth = new import_drive.auth.GoogleAuth({ scopes });
160
- this.authClient = auth;
161
185
  return this.authClient;
162
186
  } catch (err) {
163
187
  if (err instanceof DriveAuthError) throw err;
@@ -316,6 +340,7 @@ var init_path_resolver = __esm({
316
340
  drive;
317
341
  rootFolderId;
318
342
  cache = /* @__PURE__ */ new Map();
343
+ inFlightResolves = /* @__PURE__ */ new Map();
319
344
  cacheTTL;
320
345
  enableCache;
321
346
  metadataCache;
@@ -339,8 +364,8 @@ var init_path_resolver = __esm({
339
364
  /**
340
365
  * Gets cache key for a path
341
366
  */
342
- getCacheKey(path8) {
343
- return `${this.rootFolderId}:${this.normalizePath(path8)}`;
367
+ getCacheKey(path9) {
368
+ return `${this.rootFolderId}:${this.normalizePath(path9)}`;
344
369
  }
345
370
  /**
346
371
  * Clears the path cache
@@ -354,8 +379,8 @@ var init_path_resolver = __esm({
354
379
  /**
355
380
  * Invalidate a single path from cache
356
381
  */
357
- invalidatePath(path8) {
358
- const norm = this.normalizePath(path8);
382
+ invalidatePath(path9) {
383
+ const norm = this.normalizePath(path9);
359
384
  const key = this.getCacheKey(norm);
360
385
  this.cache.delete(key);
361
386
  if (this.metadataCache) {
@@ -368,6 +393,7 @@ var init_path_resolver = __esm({
368
393
  /**
369
394
  * Resolves a path to a Google Drive item (file or folder).
370
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.
371
397
  */
372
398
  async resolve(virtualPath, options = {}) {
373
399
  const norm = this.normalizePath(virtualPath);
@@ -401,6 +427,20 @@ var init_path_resolver = __esm({
401
427
  };
402
428
  }
403
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) {
404
444
  const segments = norm.split("/").filter(Boolean);
405
445
  let currentParentId = this.rootFolderId;
406
446
  let currentPath = "";
@@ -452,7 +492,7 @@ var init_path_resolver = __esm({
452
492
  });
453
493
  let file = response.data.files?.[0];
454
494
  if (!file && currentParentId === this.rootFolderId) {
455
- const sharedQ = `name = '${escapedName}' and trashed = false`;
495
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
456
496
  const sharedResponse = await withRetry(async () => {
457
497
  return await this.drive.files.list({
458
498
  q: sharedQ,
@@ -466,13 +506,14 @@ var init_path_resolver = __esm({
466
506
  file = sharedResponse.data.files?.[0];
467
507
  }
468
508
  if (file && file.id) {
509
+ const segmentParentId = currentParentId;
469
510
  currentParentId = file.id;
470
511
  if (this.metadataCache) {
471
512
  this.metadataCache.upsertFile({
472
513
  id: file.id,
473
514
  name: file.name || segment,
474
515
  mimeType: file.mimeType || "",
475
- parentId: currentParentId,
516
+ parentId: segmentParentId,
476
517
  path: currentPath,
477
518
  trashed: false
478
519
  });
@@ -510,13 +551,14 @@ var init_path_resolver = __esm({
510
551
  if (!newFolder.id) {
511
552
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
512
553
  }
554
+ const segmentParentId = currentParentId;
513
555
  currentParentId = newFolder.id;
514
556
  if (this.metadataCache) {
515
557
  this.metadataCache.upsertFile({
516
558
  id: newFolder.id,
517
559
  name: segment,
518
560
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
519
- parentId: currentParentId,
561
+ parentId: segmentParentId,
520
562
  path: currentPath,
521
563
  trashed: false
522
564
  });
@@ -578,17 +620,19 @@ var init_format = __esm({
578
620
  });
579
621
 
580
622
  // src/core/resumable-uploader.ts
581
- 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;
582
624
  var init_resumable_uploader = __esm({
583
625
  "src/core/resumable-uploader.ts"() {
584
626
  "use strict";
585
627
  init_cjs_shims();
586
628
  import_node_fs2 = __toESM(require("fs"), 1);
587
629
  import_node_path = __toESM(require("path"), 1);
630
+ import_node_stream = require("stream");
588
631
  init_errors();
589
632
  init_format();
590
633
  init_mime();
591
634
  init_retry();
635
+ init_http_agent();
592
636
  MIN_CHUNK_SIZE = 256 * 1024;
593
637
  DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
594
638
  MULTIPART_THRESHOLD = 5 * 1024 * 1024;
@@ -626,6 +670,15 @@ var init_resumable_uploader = __esm({
626
670
  const totalBytes = stat.size;
627
671
  const fileName = options.name || import_node_path.default.basename(filePath);
628
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
+ }
629
682
  return await this.chunkedUpload({
630
683
  filePath,
631
684
  totalBytes,
@@ -641,6 +694,16 @@ var init_resumable_uploader = __esm({
641
694
  const totalBytes = buffer.length;
642
695
  const fileName = options.name || "untitled";
643
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
+ }
644
707
  return await this.chunkedUploadBuffer({
645
708
  buffer,
646
709
  totalBytes,
@@ -661,6 +724,50 @@ var init_resumable_uploader = __esm({
661
724
  mimeType
662
725
  });
663
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
+ }
664
771
  /**
665
772
  * Fast direct upload using googleapis multipart
666
773
  */
@@ -693,7 +800,7 @@ var init_resumable_uploader = __esm({
693
800
  */
694
801
  async chunkedUpload(params) {
695
802
  const { filePath, totalBytes, fileName, mimeType, options } = params;
696
- 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);
697
804
  const sessionUrl = await this.initiateResumableSession({
698
805
  fileName,
699
806
  mimeType,
@@ -758,7 +865,7 @@ var init_resumable_uploader = __esm({
758
865
  */
759
866
  async chunkedUploadBuffer(params) {
760
867
  const { buffer, totalBytes, fileName, mimeType, options } = params;
761
- 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);
762
869
  const sessionUrl = await this.initiateResumableSession({
763
870
  fileName,
764
871
  mimeType,
@@ -837,7 +944,8 @@ var init_resumable_uploader = __esm({
837
944
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
838
945
  method: "POST",
839
946
  headers,
840
- data: metadata
947
+ data: metadata,
948
+ agent: getOptimizedHttpsAgent()
841
949
  });
842
950
  });
843
951
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -863,6 +971,7 @@ var init_resumable_uploader = __esm({
863
971
  method: "PUT",
864
972
  headers,
865
973
  data: buffer,
974
+ agent: getOptimizedHttpsAgent(),
866
975
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
867
976
  });
868
977
  if (res.status === 200 || res.status === 201) {
@@ -894,7 +1003,7 @@ var init_resumable_uploader = __esm({
894
1003
  });
895
1004
 
896
1005
  // src/core/downloader.ts
897
- 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;
898
1007
  var init_downloader = __esm({
899
1008
  "src/core/downloader.ts"() {
900
1009
  "use strict";
@@ -902,7 +1011,7 @@ var init_downloader = __esm({
902
1011
  import_node_fs3 = __toESM(require("fs"), 1);
903
1012
  import_node_path2 = __toESM(require("path"), 1);
904
1013
  import_promises = require("stream/promises");
905
- import_node_stream = require("stream");
1014
+ import_node_stream2 = require("stream");
906
1015
  init_mime();
907
1016
  init_format();
908
1017
  init_retry();
@@ -915,17 +1024,22 @@ var init_downloader = __esm({
915
1024
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
916
1025
  */
917
1026
  async download(fileId, options = {}) {
918
- const metaRes = await withRetry(async () => {
919
- return await this.drive.files.get({
920
- fileId,
921
- fields: "id, name, mimeType, size",
922
- 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
+ });
923
1037
  });
924
- });
925
- const file = metaRes.data;
926
- const name = file.name || "downloaded-file";
927
- const mimeType = file.mimeType || "application/octet-stream";
928
- 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
+ }
929
1043
  let downloadStream;
930
1044
  let finalFileName = name;
931
1045
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -956,7 +1070,7 @@ var init_downloader = __esm({
956
1070
  }
957
1071
  let bytesRead = 0;
958
1072
  const startTime = Date.now();
959
- const progressTracker = new import_node_stream.Transform({
1073
+ const progressTracker = new import_node_stream2.Transform({
960
1074
  transform(chunk, encoding, callback) {
961
1075
  bytesRead += chunk.length;
962
1076
  if (options.onProgress) {
@@ -981,7 +1095,7 @@ var init_downloader = __esm({
981
1095
  destPath = import_node_path2.default.join(destPath, finalFileName);
982
1096
  }
983
1097
  await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
984
- const writeStream = import_node_fs3.default.createWriteStream(destPath);
1098
+ const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
985
1099
  await (0, import_promises.pipeline)(monitoredStream, writeStream);
986
1100
  return {
987
1101
  filePath: destPath,
@@ -1232,6 +1346,7 @@ var init_query_builder = __esm({
1232
1346
  const q = this.toQueryString();
1233
1347
  const orderBy = this.orderClauses.join(", ");
1234
1348
  let pageToken = void 0;
1349
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1235
1350
  do {
1236
1351
  const res = await withRetry(async () => {
1237
1352
  return await this.drive.files.list({
@@ -1239,7 +1354,7 @@ var init_query_builder = __esm({
1239
1354
  orderBy: orderBy || void 0,
1240
1355
  pageSize: this.limitNumber,
1241
1356
  pageToken,
1242
- fields: this.requestedFields,
1357
+ fields: effectiveFields,
1243
1358
  spaces: this.spaces,
1244
1359
  supportsAllDrives: true,
1245
1360
  includeItemsFromAllDrives: true
@@ -1376,7 +1491,7 @@ var init_watcher = __esm({
1376
1491
  const res = await withRetry(async () => {
1377
1492
  return await this.drive.changes.list({
1378
1493
  pageToken: nextPageToken,
1379
- 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))",
1380
1495
  supportsAllDrives: true,
1381
1496
  includeItemsFromAllDrives: true
1382
1497
  });
@@ -1475,16 +1590,24 @@ var init_storage_cleaner = __esm({
1475
1590
  async findDuplicates(options = {}) {
1476
1591
  const mode = options.by || "name";
1477
1592
  const maxScan = options.maxScan || 1e3;
1478
- const res = await withRetry(async () => {
1479
- return await this.drive.files.list({
1480
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1481
- pageSize: Math.min(1e3, maxScan),
1482
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1483
- supportsAllDrives: true,
1484
- 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
+ });
1485
1607
  });
1486
- });
1487
- const files = res.data.files || [];
1608
+ files.push(...res.data.files || []);
1609
+ pageToken = res.data.nextPageToken || void 0;
1610
+ } while (pageToken && files.length < maxScan);
1488
1611
  const map = /* @__PURE__ */ new Map();
1489
1612
  for (const f of files) {
1490
1613
  if (!f.id) continue;
@@ -1684,7 +1807,7 @@ async function loginWithBrowser(options) {
1684
1807
  scope: scopes
1685
1808
  });
1686
1809
  return new Promise((resolve, reject) => {
1687
- const server = import_node_http.default.createServer(async (req, res) => {
1810
+ const server = import_node_http2.default.createServer(async (req, res) => {
1688
1811
  try {
1689
1812
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1690
1813
  if (reqUrl.pathname === "/oauth2callback") {
@@ -1768,16 +1891,20 @@ ${authUrl}
1768
1891
  });
1769
1892
  });
1770
1893
  server.on("error", (err) => {
1771
- 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
+ }
1772
1899
  });
1773
1900
  });
1774
1901
  }
1775
- var import_node_http, import_node_child_process, import_drive2;
1902
+ var import_node_http2, import_node_child_process, import_drive2;
1776
1903
  var init_browser_login = __esm({
1777
1904
  "src/auth/browser-login.ts"() {
1778
1905
  "use strict";
1779
1906
  init_cjs_shims();
1780
- import_node_http = __toESM(require("http"), 1);
1907
+ import_node_http2 = __toESM(require("http"), 1);
1781
1908
  import_node_child_process = require("child_process");
1782
1909
  import_drive2 = require("@googleapis/drive");
1783
1910
  init_authenticator();
@@ -1917,17 +2044,44 @@ var init_resource_refs = __esm({
1917
2044
  });
1918
2045
 
1919
2046
  // src/core/plugins.ts
1920
- var PluginManager;
2047
+ var import_node_path4, PluginManager;
1921
2048
  var init_plugins = __esm({
1922
2049
  "src/core/plugins.ts"() {
1923
2050
  "use strict";
1924
2051
  init_cjs_shims();
2052
+ import_node_path4 = __toESM(require("path"), 1);
1925
2053
  PluginManager = class {
1926
2054
  plugins = [];
2055
+ /**
2056
+ * Register a plugin. If a plugin with the same name already exists,
2057
+ * it replaces the old one to avoid duplicate side-effects.
2058
+ */
1927
2059
  use(plugin) {
2060
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
1928
2061
  this.plugins.push(plugin);
1929
2062
  return this;
1930
2063
  }
2064
+ /**
2065
+ * Unregister a plugin by its name.
2066
+ * Returns true if a plugin was found and removed, false otherwise.
2067
+ */
2068
+ unuse(pluginName) {
2069
+ const initialLen = this.plugins.length;
2070
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
2071
+ return this.plugins.length < initialLen;
2072
+ }
2073
+ /**
2074
+ * Check if a plugin with given name is currently active
2075
+ */
2076
+ has(pluginName) {
2077
+ return this.plugins.some((p) => p.name === pluginName);
2078
+ }
2079
+ /**
2080
+ * Returns all currently registered plugins
2081
+ */
2082
+ getPlugins() {
2083
+ return [...this.plugins];
2084
+ }
1931
2085
  async runBeforeUpload(options) {
1932
2086
  let current = { ...options };
1933
2087
  for (const plugin of this.plugins) {
@@ -1973,13 +2127,13 @@ var init_plugins = __esm({
1973
2127
  });
1974
2128
 
1975
2129
  // src/core/cache.ts
1976
- var import_node_os, import_node_path4, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
2130
+ var import_node_os, import_node_path5, import_node_fs5, SqliteMetadataCache, MemoryMetadataCache;
1977
2131
  var init_cache = __esm({
1978
2132
  "src/core/cache.ts"() {
1979
2133
  "use strict";
1980
2134
  init_cjs_shims();
1981
2135
  import_node_os = __toESM(require("os"), 1);
1982
- import_node_path4 = __toESM(require("path"), 1);
2136
+ import_node_path5 = __toESM(require("path"), 1);
1983
2137
  import_node_fs5 = __toESM(require("fs"), 1);
1984
2138
  SqliteMetadataCache = class {
1985
2139
  db = null;
@@ -1990,14 +2144,14 @@ var init_cache = __esm({
1990
2144
  if (customPath) {
1991
2145
  this.dbPath = customPath;
1992
2146
  } else {
1993
- const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
2147
+ const dir = import_node_path5.default.join(import_node_os.default.homedir(), ".drivekit");
1994
2148
  if (!import_node_fs5.default.existsSync(dir)) {
1995
2149
  try {
1996
2150
  import_node_fs5.default.mkdirSync(dir, { recursive: true });
1997
2151
  } catch {
1998
2152
  }
1999
2153
  }
2000
- this.dbPath = import_node_path4.default.join(dir, "cache.db");
2154
+ this.dbPath = import_node_path5.default.join(dir, "cache.db");
2001
2155
  }
2002
2156
  }
2003
2157
  init() {
@@ -2015,7 +2169,7 @@ var init_cache = __esm({
2015
2169
  CREATE TABLE IF NOT EXISTS files (
2016
2170
  id TEXT PRIMARY KEY,
2017
2171
  name TEXT NOT NULL,
2018
- mimeType TEXT NOT NULL,
2172
+ mimeType TEXT,
2019
2173
  size INTEGER,
2020
2174
  parentId TEXT,
2021
2175
  path TEXT,
@@ -2101,7 +2255,7 @@ var init_cache = __esm({
2101
2255
  stmt.run(
2102
2256
  entry.id,
2103
2257
  entry.name,
2104
- entry.mimeType,
2258
+ entry.mimeType ?? null,
2105
2259
  entry.size ?? null,
2106
2260
  entry.parentId ?? null,
2107
2261
  entry.path ?? null,
@@ -2117,10 +2271,35 @@ var init_cache = __esm({
2117
2271
  return;
2118
2272
  }
2119
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
+ `);
2120
2288
  this.db.exec("BEGIN TRANSACTION;");
2121
2289
  try {
2122
2290
  for (const entry of entries) {
2123
- 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
+ );
2124
2303
  }
2125
2304
  this.db.exec("COMMIT;");
2126
2305
  } catch (e) {
@@ -2137,6 +2316,30 @@ var init_cache = __esm({
2137
2316
  const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2138
2317
  stmt.run(id);
2139
2318
  }
2319
+ pruneMissing(activeIds) {
2320
+ if (this.fallbackMemory) {
2321
+ return this.fallbackMemory.pruneMissing(activeIds);
2322
+ }
2323
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2324
+ const idSet = new Set(activeIds);
2325
+ const rows = this.db.prepare("SELECT id FROM files").all();
2326
+ let pruned = 0;
2327
+ this.db.exec("BEGIN TRANSACTION;");
2328
+ try {
2329
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2330
+ for (const row of rows) {
2331
+ if (!idSet.has(row.id)) {
2332
+ deleteStmt.run(row.id);
2333
+ pruned++;
2334
+ }
2335
+ }
2336
+ this.db.exec("COMMIT;");
2337
+ return pruned;
2338
+ } catch (e) {
2339
+ this.db.exec("ROLLBACK;");
2340
+ throw e;
2341
+ }
2342
+ }
2140
2343
  clear() {
2141
2344
  if (this.fallbackMemory) {
2142
2345
  this.fallbackMemory.clear();
@@ -2267,6 +2470,17 @@ var init_cache = __esm({
2267
2470
  deleteFile(id) {
2268
2471
  this.files.delete(id);
2269
2472
  }
2473
+ pruneMissing(activeIds) {
2474
+ const idSet = new Set(activeIds);
2475
+ let pruned = 0;
2476
+ for (const id of Array.from(this.files.keys())) {
2477
+ if (!idSet.has(id)) {
2478
+ this.files.delete(id);
2479
+ pruned++;
2480
+ }
2481
+ }
2482
+ return pruned;
2483
+ }
2270
2484
  clear() {
2271
2485
  this.files.clear();
2272
2486
  this.meta.clear();
@@ -2307,23 +2521,55 @@ var init_cache = __esm({
2307
2521
  // src/server/webdav.ts
2308
2522
  var webdav_exports = {};
2309
2523
  __export(webdav_exports, {
2524
+ escapeXml: () => escapeXml,
2310
2525
  startWebDAVServer: () => startWebDAVServer
2311
2526
  });
2527
+ function escapeXml(unsafe) {
2528
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2529
+ }
2312
2530
  async function startWebDAVServer(drive2, options = {}) {
2313
2531
  const port = options.port || 8080;
2314
2532
  const host = options.host || "127.0.0.1";
2315
2533
  await drive2.init();
2316
- const server = import_node_http2.default.createServer(async (req, res) => {
2534
+ const server = import_node_http3.default.createServer(async (req, res) => {
2317
2535
  try {
2536
+ if (options.auth?.username && options.auth?.password) {
2537
+ const authHeader = req.headers["authorization"];
2538
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
2539
+ res.writeHead(401, {
2540
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2541
+ "Content-Type": "text/plain"
2542
+ });
2543
+ res.end("Authentication required");
2544
+ return;
2545
+ }
2546
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
2547
+ const [user, pass] = credentials.split(":");
2548
+ if (user !== options.auth.username || pass !== options.auth.password) {
2549
+ res.writeHead(401, {
2550
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2551
+ "Content-Type": "text/plain"
2552
+ });
2553
+ res.end("Invalid credentials");
2554
+ return;
2555
+ }
2556
+ }
2318
2557
  const parsedUrl = import_node_url.default.parse(req.url || "/", true);
2319
2558
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2320
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
+ }
2321
2566
  switch (req.method) {
2322
2567
  case "OPTIONS": {
2323
2568
  res.writeHead(200, {
2324
2569
  DAV: "1, 2",
2325
2570
  Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2326
- "MS-Author-Via": "DAV"
2571
+ "MS-Author-Via": "DAV",
2572
+ "Accept-Ranges": "bytes"
2327
2573
  });
2328
2574
  res.end();
2329
2575
  return;
@@ -2331,6 +2577,11 @@ async function startWebDAVServer(drive2, options = {}) {
2331
2577
  case "PROPFIND": {
2332
2578
  const depth = req.headers["depth"] || "1";
2333
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
+ }
2334
2585
  res.writeHead(207, {
2335
2586
  "Content-Type": "application/xml; charset=utf-8"
2336
2587
  });
@@ -2341,7 +2592,7 @@ async function startWebDAVServer(drive2, options = {}) {
2341
2592
  case "HEAD": {
2342
2593
  if (virtualPath === "/" || virtualPath === "") {
2343
2594
  res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
2344
- res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
2595
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
2345
2596
  return;
2346
2597
  }
2347
2598
  try {
@@ -2351,15 +2602,42 @@ async function startWebDAVServer(drive2, options = {}) {
2351
2602
  res.end("Cannot GET a directory");
2352
2603
  return;
2353
2604
  }
2354
- const stream = await drive2.createReadStream(virtualPath);
2355
- res.writeHead(200, {
2356
- "Content-Type": file.mimeType || "application/octet-stream",
2357
- "Content-Length": file.size || void 0
2358
- });
2359
- if (req.method === "HEAD") {
2360
- res.end();
2605
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
2606
+ const rangeHeader = req.headers["range"];
2607
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
2608
+ const parts = rangeHeader.replace("bytes=", "").split("-");
2609
+ const start = parseInt(parts[0], 10);
2610
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
2611
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
2612
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
2613
+ res.end();
2614
+ return;
2615
+ }
2616
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
2617
+ const chunkLength = end - start + 1;
2618
+ res.writeHead(206, {
2619
+ "Content-Type": file.mimeType || "application/octet-stream",
2620
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
2621
+ "Content-Length": chunkLength,
2622
+ "Accept-Ranges": "bytes"
2623
+ });
2624
+ if (req.method === "HEAD") {
2625
+ res.end();
2626
+ } else {
2627
+ stream.pipe(res);
2628
+ }
2361
2629
  } else {
2362
- stream.pipe(res);
2630
+ const stream = await drive2.createReadStream(virtualPath);
2631
+ res.writeHead(200, {
2632
+ "Content-Type": file.mimeType || "application/octet-stream",
2633
+ "Content-Length": file.size || void 0,
2634
+ "Accept-Ranges": "bytes"
2635
+ });
2636
+ if (req.method === "HEAD") {
2637
+ res.end();
2638
+ } else {
2639
+ stream.pipe(res);
2640
+ }
2363
2641
  }
2364
2642
  } catch (e) {
2365
2643
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -2368,27 +2646,29 @@ async function startWebDAVServer(drive2, options = {}) {
2368
2646
  return;
2369
2647
  }
2370
2648
  case "PUT": {
2371
- const remoteDir = import_node_path5.default.dirname(virtualPath);
2372
- const fileName = import_node_path5.default.basename(virtualPath);
2649
+ const remoteDir = import_node_path6.default.dirname(virtualPath);
2373
2650
  await drive2.mkdirp(remoteDir);
2374
- const chunks = [];
2375
- req.on("data", (chunk) => chunks.push(chunk));
2376
- req.on("end", async () => {
2377
- try {
2378
- const buffer = Buffer.concat(chunks);
2379
- await drive2.upload({
2380
- source: buffer,
2381
- filename: fileName,
2382
- parent: remoteDir,
2383
- overwrite: true
2384
- });
2385
- res.writeHead(201, { "Content-Type": "text/plain" });
2386
- res.end("Created");
2387
- } catch (err) {
2388
- res.writeHead(500, { "Content-Type": "text/plain" });
2389
- res.end(err.message || "Upload failed");
2651
+ let existed = false;
2652
+ try {
2653
+ const existingFile = await drive2.getFile(virtualPath);
2654
+ if (existingFile && existingFile.id) {
2655
+ existed = true;
2390
2656
  }
2391
- });
2657
+ } catch {
2658
+ existed = false;
2659
+ }
2660
+ try {
2661
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
2662
+ overwrite: true
2663
+ });
2664
+ req.pipe(uploadStream);
2665
+ await uploadStream.done;
2666
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
2667
+ res.end(existed ? "" : "Created");
2668
+ } catch (err) {
2669
+ res.writeHead(500, { "Content-Type": "text/plain" });
2670
+ res.end(err.message || "Upload failed");
2671
+ }
2392
2672
  return;
2393
2673
  }
2394
2674
  case "MKCOL": {
@@ -2420,14 +2700,24 @@ async function startWebDAVServer(drive2, options = {}) {
2420
2700
  res.end("Destination header missing");
2421
2701
  return;
2422
2702
  }
2423
- const destUrl = import_node_url.default.parse(destination);
2424
- const destPath = decodeURIComponent(destUrl.pathname || "");
2425
- const newName = import_node_path5.default.basename(destPath);
2426
- const newParent = import_node_path5.default.dirname(destPath);
2427
2703
  try {
2428
- await drive2.move(virtualPath, newParent);
2429
- if (newName !== import_node_path5.default.basename(virtualPath)) {
2430
- await drive2.rename(destPath, newName);
2704
+ const file = await drive2.getFile(virtualPath);
2705
+ if (!file?.id) {
2706
+ res.writeHead(404, { "Content-Type": "text/plain" });
2707
+ res.end("Source file not found");
2708
+ return;
2709
+ }
2710
+ const destUrl = import_node_url.default.parse(destination);
2711
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2712
+ const newName = import_node_path6.default.basename(destPath);
2713
+ const newParentDir = import_node_path6.default.dirname(destPath);
2714
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2715
+ const currentParentDir = import_node_path6.default.dirname(virtualPath);
2716
+ if (newParentDir !== currentParentDir) {
2717
+ await drive2.move(file.id, newParentFolderId);
2718
+ }
2719
+ if (newName !== import_node_path6.default.basename(virtualPath)) {
2720
+ await drive2.rename(file.id, newName);
2431
2721
  }
2432
2722
  res.writeHead(201);
2433
2723
  res.end("Moved");
@@ -2437,6 +2727,34 @@ async function startWebDAVServer(drive2, options = {}) {
2437
2727
  }
2438
2728
  return;
2439
2729
  }
2730
+ case "COPY": {
2731
+ const destination = req.headers["destination"];
2732
+ if (!destination || typeof destination !== "string") {
2733
+ res.writeHead(400, { "Content-Type": "text/plain" });
2734
+ res.end("Destination header missing");
2735
+ return;
2736
+ }
2737
+ try {
2738
+ const file = await drive2.getFile(virtualPath);
2739
+ if (!file?.id) {
2740
+ res.writeHead(404, { "Content-Type": "text/plain" });
2741
+ res.end("Source file not found");
2742
+ return;
2743
+ }
2744
+ const destUrl = import_node_url.default.parse(destination);
2745
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2746
+ const newName = import_node_path6.default.basename(destPath);
2747
+ const newParentDir = import_node_path6.default.dirname(destPath);
2748
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2749
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2750
+ res.writeHead(201);
2751
+ res.end("Copied");
2752
+ } catch (err) {
2753
+ res.writeHead(500, { "Content-Type": "text/plain" });
2754
+ res.end(err.message);
2755
+ }
2756
+ return;
2757
+ }
2440
2758
  default: {
2441
2759
  res.writeHead(501, { "Content-Type": "text/plain" });
2442
2760
  res.end("Method Not Implemented");
@@ -2474,25 +2792,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
2474
2792
  virtualPath,
2475
2793
  isFolder,
2476
2794
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
2477
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2795
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2796
+ selfItem.mimeType || void 0
2478
2797
  )
2479
2798
  );
2480
2799
  } catch {
2481
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
2800
+ return null;
2482
2801
  }
2483
2802
  }
2484
2803
  if (isFolder && depth !== "0") {
2485
2804
  try {
2486
2805
  const children = await drive2.ls(virtualPath);
2806
+ const seenNames = /* @__PURE__ */ new Map();
2487
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
+ }
2488
2818
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
2489
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
2819
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
2490
2820
  responses.push(
2491
2821
  renderWebDAVResponse(
2492
2822
  childPath,
2493
2823
  childIsFolder,
2494
2824
  child.size ? parseInt(child.size, 10) : 0,
2495
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
2825
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
2826
+ child.mimeType || void 0
2496
2827
  )
2497
2828
  );
2498
2829
  }
@@ -2504,32 +2835,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
2504
2835
  ${responses.join("\n")}
2505
2836
  </D:multistatus>`;
2506
2837
  }
2507
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2508
- 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);
2844
+ const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
2509
2845
  const resourceType = isDir ? "<D:collection/>" : "";
2510
2846
  const dateFormatted = new Date(modifiedTime).toUTCString();
2847
+ const contentTypeTag = !isDir && mimeType ? `
2848
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
2511
2849
  return ` <D:response>
2512
2850
  <D:href>${encodedHref}</D:href>
2513
2851
  <D:propstat>
2514
2852
  <D:prop>
2515
- <D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
2853
+ <D:displayname>${displayName}</D:displayname>
2516
2854
  <D:resourcetype>${resourceType}</D:resourcetype>
2517
2855
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2518
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
2519
- <D:status>HTTP/1.1 200 OK</D:status>
2856
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
2520
2857
  </D:prop>
2521
2858
  <D:status>HTTP/1.1 200 OK</D:status>
2522
2859
  </D:propstat>
2523
2860
  </D:response>`;
2524
2861
  }
2525
- var import_node_http2, import_node_url, import_node_path5;
2862
+ var import_node_http3, import_node_url, import_node_path6;
2526
2863
  var init_webdav = __esm({
2527
2864
  "src/server/webdav.ts"() {
2528
2865
  "use strict";
2529
2866
  init_cjs_shims();
2530
- import_node_http2 = __toESM(require("http"), 1);
2867
+ import_node_http3 = __toESM(require("http"), 1);
2531
2868
  import_node_url = __toESM(require("url"), 1);
2532
- import_node_path5 = __toESM(require("path"), 1);
2869
+ import_node_path6 = __toESM(require("path"), 1);
2533
2870
  }
2534
2871
  });
2535
2872
 
@@ -2538,13 +2875,13 @@ var client_exports = {};
2538
2875
  __export(client_exports, {
2539
2876
  DriveKit: () => DriveKit
2540
2877
  });
2541
- var import_node_fs6, import_node_path6, import_drive3, DriveKit;
2878
+ var import_node_fs6, import_node_path7, import_drive3, DriveKit;
2542
2879
  var init_client = __esm({
2543
2880
  "src/core/client.ts"() {
2544
2881
  "use strict";
2545
2882
  init_cjs_shims();
2546
2883
  import_node_fs6 = __toESM(require("fs"), 1);
2547
- import_node_path6 = __toESM(require("path"), 1);
2884
+ import_node_path7 = __toESM(require("path"), 1);
2548
2885
  import_drive3 = require("@googleapis/drive");
2549
2886
  init_authenticator();
2550
2887
  init_path_resolver();
@@ -2562,6 +2899,7 @@ var init_client = __esm({
2562
2899
  init_format();
2563
2900
  init_mime();
2564
2901
  init_cache();
2902
+ init_http_agent();
2565
2903
  DriveKit = class _DriveKit {
2566
2904
  options;
2567
2905
  authenticator;
@@ -2584,6 +2922,18 @@ var init_client = __esm({
2584
2922
  this.pluginManager.use(plugin);
2585
2923
  return this;
2586
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
+ }
2587
2937
  /**
2588
2938
  * Returns a fluent, chained reference to a specific file
2589
2939
  */
@@ -2602,7 +2952,8 @@ var init_client = __esm({
2602
2952
  async init() {
2603
2953
  if (!this.driveClient) {
2604
2954
  const auth = await this.authenticator.getAuthClient();
2605
- this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2955
+ const agent = getOptimizedHttpsAgent();
2956
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
2606
2957
  if (this.options.enablePersistentCache !== false) {
2607
2958
  this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2608
2959
  this.metadataCacheInstance.init();
@@ -2689,14 +3040,41 @@ var init_client = __esm({
2689
3040
  }
2690
3041
  }
2691
3042
  /**
2692
- * 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
2693
3044
  */
2694
3045
  async ls(folderIdOrPath = "/") {
2695
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
2696
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
3046
+ let parentFolderId;
3047
+ let normalizedPath = null;
3048
+ let files;
3049
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
3050
+ parentFolderId = this.rootFolderId;
3051
+ normalizedPath = "/";
3052
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
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();
2697
3062
  }
2698
- const folderId = await this.resolveId(folderIdOrPath);
2699
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
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);
3076
+ }
3077
+ return files;
2700
3078
  }
2701
3079
  // ==========================================
2702
3080
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2715,7 +3093,7 @@ var init_client = __esm({
2715
3093
  if (parentId && parentId.startsWith("/")) {
2716
3094
  parentId = await this.mkdirp(parentId);
2717
3095
  }
2718
- 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);
2719
3097
  if (opts.overwrite && targetName && parentId) {
2720
3098
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2721
3099
  if (existing?.id) {
@@ -2736,7 +3114,7 @@ var init_client = __esm({
2736
3114
  }
2737
3115
  }
2738
3116
  if (existingId) {
2739
- const fileName = targetName || import_node_path6.default.basename(opts.source);
3117
+ const fileName = targetName || import_node_path7.default.basename(opts.source);
2740
3118
  const raw = await this.getRawClient();
2741
3119
  const copyRes = await withRetry(async () => {
2742
3120
  return await raw.files.copy({
@@ -2771,12 +3149,14 @@ var init_client = __esm({
2771
3149
  parent: parentId
2772
3150
  });
2773
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;
2774
3153
  this.metadataCacheInstance.upsertFile({
2775
3154
  id: uploaded.id,
2776
3155
  name: uploaded.name || targetName || "untitled",
2777
3156
  mimeType: uploaded.mimeType || "",
2778
3157
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2779
3158
  parentId,
3159
+ path: virtualPath,
2780
3160
  trashed: false
2781
3161
  });
2782
3162
  }
@@ -2787,16 +3167,25 @@ var init_client = __esm({
2787
3167
  * - Automatic conversion for Google Docs, Sheets, and Slides
2788
3168
  * - Progress events
2789
3169
  * - Saves directly to file or returns Readable Stream
3170
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2790
3171
  */
2791
3172
  async download(fileIdOrPath, options = {}) {
2792
3173
  const fileId = await this.resolveId(fileIdOrPath);
2793
- 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);
2794
3183
  const downloader = await this.getDownloader();
2795
3184
  const result = await downloader.download(fileId, processedOpts);
2796
3185
  return await this.pluginManager.runAfterDownload(result);
2797
3186
  }
2798
3187
  /**
2799
- * Gets file metadata
3188
+ * Gets file metadata and updates the local metadata cache
2800
3189
  */
2801
3190
  async getFile(fileIdOrPath) {
2802
3191
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2808,7 +3197,20 @@ var init_client = __esm({
2808
3197
  supportsAllDrives: true
2809
3198
  });
2810
3199
  });
2811
- 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;
2812
3214
  }
2813
3215
  /**
2814
3216
  * Reads file content as UTF-8 string
@@ -2851,6 +3253,9 @@ var init_client = __esm({
2851
3253
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
2852
3254
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
2853
3255
  }
3256
+ if (this.metadataCacheInstance) {
3257
+ this.metadataCacheInstance.deleteFile(fileId);
3258
+ }
2854
3259
  }
2855
3260
  /**
2856
3261
  * Move item to trash
@@ -2892,6 +3297,16 @@ var init_client = __esm({
2892
3297
  if (this.pathResolverInstance) {
2893
3298
  this.pathResolverInstance.clearCache();
2894
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
+ }
2895
3310
  return res.data;
2896
3311
  }
2897
3312
  /**
@@ -2934,6 +3349,16 @@ var init_client = __esm({
2934
3349
  if (this.pathResolverInstance) {
2935
3350
  this.pathResolverInstance.clearCache();
2936
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
+ }
2937
3362
  return res.data;
2938
3363
  }
2939
3364
  // ==========================================
@@ -3023,8 +3448,8 @@ var init_client = __esm({
3023
3448
  const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3024
3449
  const files = [];
3025
3450
  for (const entry of entries) {
3026
- const fullPath = import_node_path6.default.join(dir, entry.name);
3027
- const relPath = import_node_path6.default.join(base, entry.name);
3451
+ const fullPath = import_node_path7.default.join(dir, entry.name);
3452
+ const relPath = import_node_path7.default.join(base, entry.name);
3028
3453
  if (entry.isDirectory()) {
3029
3454
  const sub = await collectFiles(fullPath, relPath);
3030
3455
  files.push(...sub);
@@ -3042,11 +3467,11 @@ var init_client = __esm({
3042
3467
  if (remoteDirCache.has(relDir)) {
3043
3468
  return remoteDirCache.get(relDir);
3044
3469
  }
3045
- const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
3470
+ const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
3046
3471
  let currentParent = targetFolderId;
3047
3472
  let currentRel = "";
3048
3473
  for (const part of parts) {
3049
- currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
3474
+ currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
3050
3475
  if (remoteDirCache.has(currentRel)) {
3051
3476
  currentParent = remoteDirCache.get(currentRel);
3052
3477
  continue;
@@ -3075,8 +3500,8 @@ var init_client = __esm({
3075
3500
  };
3076
3501
  await pool.map(allFiles, async (fileItem) => {
3077
3502
  try {
3078
- const relDir = import_node_path6.default.dirname(fileItem.relPath);
3079
- const fileName = import_node_path6.default.basename(fileItem.relPath);
3503
+ const relDir = import_node_path7.default.dirname(fileItem.relPath);
3504
+ const fileName = import_node_path7.default.basename(fileItem.relPath);
3080
3505
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3081
3506
  if (options.onFileStart) {
3082
3507
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3211,9 +3636,16 @@ var init_client = __esm({
3211
3636
  async createWriteStream(remotePath, options = {}) {
3212
3637
  await this.init();
3213
3638
  const { PassThrough } = await import("stream");
3214
- const passThrough = new PassThrough();
3215
- const remoteDir = import_node_path6.default.dirname(remotePath);
3216
- const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
3639
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3640
+ let resolveDone;
3641
+ let rejectDone;
3642
+ const donePromise = new Promise((resolve, reject) => {
3643
+ resolveDone = resolve;
3644
+ rejectDone = reject;
3645
+ });
3646
+ passThrough.done = donePromise;
3647
+ const remoteDir = import_node_path7.default.dirname(remotePath);
3648
+ const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
3217
3649
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3218
3650
  const mimeType = options.mimeType || "application/octet-stream";
3219
3651
  const raw = this.driveClient;
@@ -3230,9 +3662,10 @@ var init_client = __esm({
3230
3662
  fields: "id, name, mimeType, size, md5Checksum",
3231
3663
  supportsAllDrives: true
3232
3664
  }).then((res) => {
3233
- if (res.data.id && this.metadataCacheInstance) {
3665
+ const file = res.data;
3666
+ if (file.id && this.metadataCacheInstance) {
3234
3667
  this.metadataCacheInstance.upsertFile({
3235
- id: res.data.id,
3668
+ id: file.id,
3236
3669
  name: fileName,
3237
3670
  mimeType,
3238
3671
  parentId: targetParentId,
@@ -3240,14 +3673,22 @@ var init_client = __esm({
3240
3673
  trashed: false
3241
3674
  });
3242
3675
  }
3676
+ resolveDone(file);
3243
3677
  }).catch((err) => {
3244
3678
  passThrough.destroy(err);
3679
+ rejectDone(err);
3245
3680
  });
3246
3681
  return passThrough;
3247
3682
  }
3248
3683
  // ==========================================
3249
3684
  // METADATA CACHE OPERATIONS
3250
3685
  // ==========================================
3686
+ /**
3687
+ * Synchronous getter for the active metadata cache instance
3688
+ */
3689
+ get cache() {
3690
+ return this.metadataCacheInstance;
3691
+ }
3251
3692
  /**
3252
3693
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3253
3694
  */
@@ -3270,6 +3711,9 @@ var init_client = __esm({
3270
3711
  if (this.pathResolverInstance) {
3271
3712
  this.pathResolverInstance.clearCache();
3272
3713
  }
3714
+ if (this.metadataCacheInstance) {
3715
+ this.metadataCacheInstance.clear();
3716
+ }
3273
3717
  }
3274
3718
  /**
3275
3719
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3282,6 +3726,7 @@ var init_client = __esm({
3282
3726
  const client = this.driveClient;
3283
3727
  let pageToken = void 0;
3284
3728
  let totalScanned = 0;
3729
+ const rawFiles = [];
3285
3730
  do {
3286
3731
  const res = await withRetry(async () => {
3287
3732
  return await client.files.list({
@@ -3295,21 +3740,49 @@ var init_client = __esm({
3295
3740
  });
3296
3741
  });
3297
3742
  const files = res.data.files || [];
3298
- const entries = files.map((f) => ({
3299
- id: f.id,
3300
- name: f.name || "untitled",
3301
- mimeType: f.mimeType || "",
3302
- size: f.size ? parseInt(f.size, 10) : void 0,
3303
- parentId: f.parents?.[0],
3304
- md5Checksum: f.md5Checksum || void 0,
3305
- trashed: !!f.trashed,
3306
- modifiedTime: f.modifiedTime || void 0
3307
- }));
3308
- this.metadataCacheInstance.upsertFiles(entries);
3309
- totalScanned += entries.length;
3743
+ for (const f of files) {
3744
+ if (f.id) rawFiles.push(f);
3745
+ }
3746
+ totalScanned += files.length;
3310
3747
  options?.onProgress?.(totalScanned);
3311
3748
  pageToken = res.data.nextPageToken || void 0;
3312
3749
  } while (pageToken);
3750
+ const fileMap = /* @__PURE__ */ new Map();
3751
+ for (const f of rawFiles) {
3752
+ fileMap.set(f.id, f);
3753
+ }
3754
+ const pathMemo = /* @__PURE__ */ new Map();
3755
+ const rootId = this.rootFolderId;
3756
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3757
+ if (pathMemo.has(id)) return pathMemo.get(id);
3758
+ if (visited.has(id)) return "";
3759
+ visited.add(id);
3760
+ const f = fileMap.get(id);
3761
+ if (!f || !f.name) return "";
3762
+ const parentId = f.parents?.[0];
3763
+ if (!parentId || parentId === "root" || parentId === rootId) {
3764
+ const p = `/${f.name}`;
3765
+ pathMemo.set(id, p);
3766
+ return p;
3767
+ }
3768
+ const parentPath = computePath(parentId, visited);
3769
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3770
+ pathMemo.set(id, fullPath);
3771
+ return fullPath;
3772
+ }
3773
+ const entries = rawFiles.map((f) => ({
3774
+ id: f.id,
3775
+ name: f.name || "untitled",
3776
+ mimeType: f.mimeType || "",
3777
+ size: f.size ? parseInt(f.size, 10) : void 0,
3778
+ parentId: f.parents?.[0],
3779
+ path: computePath(f.id),
3780
+ md5Checksum: f.md5Checksum || void 0,
3781
+ trashed: !!f.trashed,
3782
+ modifiedTime: f.modifiedTime || void 0
3783
+ }));
3784
+ this.metadataCacheInstance.upsertFiles(entries);
3785
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3313
3786
  this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3314
3787
  return this.metadataCacheInstance.getStats();
3315
3788
  }
@@ -3429,7 +3902,7 @@ __export(cli_exports, {
3429
3902
  module.exports = __toCommonJS(cli_exports);
3430
3903
  init_cjs_shims();
3431
3904
  var import_node_fs7 = __toESM(require("fs"), 1);
3432
- var import_node_path7 = __toESM(require("path"), 1);
3905
+ var import_node_path8 = __toESM(require("path"), 1);
3433
3906
  var import_commander = require("commander");
3434
3907
  var import_chalk2 = __toESM(require("chalk"), 1);
3435
3908
  var import_ora = __toESM(require("ora"), 1);
@@ -3592,10 +4065,29 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
3592
4065
 
3593
4066
  // src/cli.ts
3594
4067
  var program = new import_commander.Command();
3595
- program.name("drivekit").description(import_chalk2.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
4068
+ var pkgVersion = "1.1.2";
4069
+ try {
4070
+ const pkgPath = new URL("../package.json", importMetaUrl);
4071
+ const pkg = JSON.parse(import_node_fs7.default.readFileSync(pkgPath, "utf8"));
4072
+ if (pkg.version) pkgVersion = pkg.version;
4073
+ } catch {
4074
+ }
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");
3596
4076
  function getAuthConfig(cmdOptions) {
3597
4077
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3598
- 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
+ }
3599
4091
  return {
3600
4092
  keyFilePath,
3601
4093
  accessToken
@@ -3669,7 +4161,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
3669
4161
  console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
3670
4162
  process.exit(1);
3671
4163
  }
3672
- const fileName = import_node_path7.default.basename(localFile);
4164
+ const fileName = import_node_path8.default.basename(localFile);
3673
4165
  const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
3674
4166
  try {
3675
4167
  const client = await getClient(options);
@@ -3933,7 +4425,7 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
3933
4425
  if (result.tokens.refresh_token) {
3934
4426
  console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3935
4427
  }
3936
- const outPath = import_node_path7.default.resolve("./gdrive-tokens.json");
4428
+ const outPath = import_node_path8.default.resolve("./gdrive-tokens.json");
3937
4429
  import_node_fs7.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3938
4430
  console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
3939
4431
  `);
@@ -4011,19 +4503,25 @@ program.command("shared-drives").description("List accessible Google Workspace S
4011
4503
  process.exit(1);
4012
4504
  }
4013
4505
  });
4014
- program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").action(async (options) => {
4506
+ program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-u, --username <username>", "HTTP Basic auth username").option("-P, --password <password>", "HTTP Basic auth password").action(async (options) => {
4015
4507
  try {
4016
4508
  const client = await getClient(options);
4017
4509
  const port = parseInt(options.port, 10) || 8080;
4018
4510
  const host = options.host || "127.0.0.1";
4511
+ const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
4019
4512
  console.log(import_chalk2.default.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
4020
4513
  console.log("Starting local WebDAV bridge to Google Drive...\n");
4021
- const serverInstance = await client.serveWebDAV({ port, host });
4514
+ const serverInstance = await client.serveWebDAV({ port, host, auth });
4022
4515
  console.log(import_chalk2.default.bold.green(`\u{1F680} Server active at: ${import_chalk2.default.underline(serverInstance.url)}`));
4516
+ if (auth) {
4517
+ console.log(import_chalk2.default.yellow(`\u{1F512} Basic Authentication: ENABLED (User: ${auth.username})`));
4518
+ } else {
4519
+ console.log(import_chalk2.default.dim("\u{1F513} Authentication: Anonymous (Localhost only recommended)"));
4520
+ }
4023
4521
  console.log(import_chalk2.default.white("\n\u{1F4CC} How to mount on macOS Finder:"));
4024
4522
  console.log(` 1. Open Finder and press ${import_chalk2.default.bold.cyan("Cmd + K")} (Connect to Server)`);
4025
4523
  console.log(` 2. Enter: ${import_chalk2.default.bold.yellow(serverInstance.url)}`);
4026
- console.log(` 3. Click ${import_chalk2.default.bold("Connect")} (Connect as Guest)
4524
+ console.log(` 3. Click ${import_chalk2.default.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
4027
4525
  `);
4028
4526
  console.log(import_chalk2.default.white("\u{1F4CC} How to mount on Windows:"));
4029
4527
  console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);