drivekit 1.1.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -50,7 +50,7 @@ async function startWebDAVServer(drive2, options = {}) {
50
50
  const port = options.port || 8080;
51
51
  const host = options.host || "127.0.0.1";
52
52
  await drive2.init();
53
- const server = import_node_http2.default.createServer(async (req, res) => {
53
+ const server = import_node_http4.default.createServer(async (req, res) => {
54
54
  try {
55
55
  if (options.auth?.username && options.auth?.password) {
56
56
  const authHeader = req.headers["authorization"];
@@ -73,9 +73,16 @@ async function startWebDAVServer(drive2, options = {}) {
73
73
  return;
74
74
  }
75
75
  }
76
- const parsedUrl = import_node_url.default.parse(req.url || "/", true);
76
+ const parsedUrl = import_node_url2.default.parse(req.url || "/", true);
77
77
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
78
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
78
+ const normalizedPath = import_node_path8.default.posix.normalize(decodedPath);
79
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
80
+ const baseName = import_node_path8.default.basename(virtualPath);
81
+ if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
82
+ res.writeHead(404, { "Content-Type": "text/plain" });
83
+ res.end("Not Found");
84
+ return;
85
+ }
79
86
  switch (req.method) {
80
87
  case "OPTIONS": {
81
88
  res.writeHead(200, {
@@ -90,6 +97,11 @@ async function startWebDAVServer(drive2, options = {}) {
90
97
  case "PROPFIND": {
91
98
  const depth = req.headers["depth"] || "1";
92
99
  const xml = await handlePropfind(drive2, virtualPath, depth);
100
+ if (xml === null) {
101
+ res.writeHead(404, { "Content-Type": "text/plain" });
102
+ res.end("Not Found");
103
+ return;
104
+ }
93
105
  res.writeHead(207, {
94
106
  "Content-Type": "application/xml; charset=utf-8"
95
107
  });
@@ -154,7 +166,7 @@ async function startWebDAVServer(drive2, options = {}) {
154
166
  return;
155
167
  }
156
168
  case "PUT": {
157
- const remoteDir = import_node_path6.default.dirname(virtualPath);
169
+ const remoteDir = import_node_path8.default.dirname(virtualPath);
158
170
  await drive2.mkdirp(remoteDir);
159
171
  let existed = false;
160
172
  try {
@@ -215,16 +227,16 @@ async function startWebDAVServer(drive2, options = {}) {
215
227
  res.end("Source file not found");
216
228
  return;
217
229
  }
218
- const destUrl = import_node_url.default.parse(destination);
230
+ const destUrl = import_node_url2.default.parse(destination);
219
231
  const destPath = decodeURIComponent(destUrl.pathname || "");
220
- const newName = import_node_path6.default.basename(destPath);
221
- const newParentDir = import_node_path6.default.dirname(destPath);
232
+ const newName = import_node_path8.default.basename(destPath);
233
+ const newParentDir = import_node_path8.default.dirname(destPath);
222
234
  const newParentFolderId = await drive2.mkdirp(newParentDir);
223
- const currentParentDir = import_node_path6.default.dirname(virtualPath);
235
+ const currentParentDir = import_node_path8.default.dirname(virtualPath);
224
236
  if (newParentDir !== currentParentDir) {
225
237
  await drive2.move(file.id, newParentFolderId);
226
238
  }
227
- if (newName !== import_node_path6.default.basename(virtualPath)) {
239
+ if (newName !== import_node_path8.default.basename(virtualPath)) {
228
240
  await drive2.rename(file.id, newName);
229
241
  }
230
242
  res.writeHead(201);
@@ -249,10 +261,10 @@ async function startWebDAVServer(drive2, options = {}) {
249
261
  res.end("Source file not found");
250
262
  return;
251
263
  }
252
- const destUrl = import_node_url.default.parse(destination);
264
+ const destUrl = import_node_url2.default.parse(destination);
253
265
  const destPath = decodeURIComponent(destUrl.pathname || "");
254
- const newName = import_node_path6.default.basename(destPath);
255
- const newParentDir = import_node_path6.default.dirname(destPath);
266
+ const newName = import_node_path8.default.basename(destPath);
267
+ const newParentDir = import_node_path8.default.dirname(destPath);
256
268
  const newParentFolderId = await drive2.mkdirp(newParentDir);
257
269
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
258
270
  res.writeHead(201);
@@ -300,25 +312,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
300
312
  virtualPath,
301
313
  isFolder,
302
314
  selfItem.size ? parseInt(selfItem.size, 10) : 0,
303
- selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
315
+ selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
316
+ selfItem.mimeType || void 0
304
317
  )
305
318
  );
306
319
  } catch {
307
- return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
320
+ return null;
308
321
  }
309
322
  }
310
323
  if (isFolder && depth !== "0") {
311
324
  try {
312
325
  const children = await drive2.ls(virtualPath);
326
+ const seenNames = /* @__PURE__ */ new Map();
313
327
  for (const child of children) {
328
+ let childName = child.name || "untitled";
329
+ if (seenNames.has(childName)) {
330
+ const count = seenNames.get(childName) + 1;
331
+ seenNames.set(childName, count);
332
+ const ext = import_node_path8.default.extname(childName);
333
+ const base = import_node_path8.default.basename(childName, ext);
334
+ childName = `${base} (${count})${ext}`;
335
+ } else {
336
+ seenNames.set(childName, 0);
337
+ }
314
338
  const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
315
- const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
339
+ const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
316
340
  responses.push(
317
341
  renderWebDAVResponse(
318
342
  childPath,
319
343
  childIsFolder,
320
344
  child.size ? parseInt(child.size, 10) : 0,
321
- child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
345
+ child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
346
+ child.mimeType || void 0
322
347
  )
323
348
  );
324
349
  }
@@ -330,11 +355,17 @@ async function handlePropfind(drive2, virtualPath, depth) {
330
355
  ${responses.join("\n")}
331
356
  </D:multistatus>`;
332
357
  }
333
- function renderWebDAVResponse(href, isDir, size, modifiedTime) {
334
- const encodedHref = encodeURI(href);
335
- const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
358
+ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
359
+ let cleanHref = href;
360
+ if (isDir && !cleanHref.endsWith("/")) {
361
+ cleanHref += "/";
362
+ }
363
+ const encodedHref = encodeURI(cleanHref);
364
+ const displayName = escapeXml(import_node_path8.default.basename(href) || "root");
336
365
  const resourceType = isDir ? "<D:collection/>" : "";
337
366
  const dateFormatted = new Date(modifiedTime).toUTCString();
367
+ const contentTypeTag = !isDir && mimeType ? `
368
+ <D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
338
369
  return ` <D:response>
339
370
  <D:href>${encodedHref}</D:href>
340
371
  <D:propstat>
@@ -342,27 +373,27 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime) {
342
373
  <D:displayname>${displayName}</D:displayname>
343
374
  <D:resourcetype>${resourceType}</D:resourcetype>
344
375
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
345
- <D:getlastmodified>${dateFormatted}</D:getlastmodified>
346
- <D:status>HTTP/1.1 200 OK</D:status>
376
+ <D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
347
377
  </D:prop>
348
378
  <D:status>HTTP/1.1 200 OK</D:status>
349
379
  </D:propstat>
350
380
  </D:response>`;
351
381
  }
352
- var import_node_http2, import_node_url, import_node_path6;
382
+ var import_node_http4, import_node_url2, import_node_path8;
353
383
  var init_webdav = __esm({
354
384
  "src/server/webdav.ts"() {
355
385
  "use strict";
356
386
  init_cjs_shims();
357
- import_node_http2 = __toESM(require("http"), 1);
358
- import_node_url = __toESM(require("url"), 1);
359
- import_node_path6 = __toESM(require("path"), 1);
387
+ import_node_http4 = __toESM(require("http"), 1);
388
+ import_node_url2 = __toESM(require("url"), 1);
389
+ import_node_path8 = __toESM(require("path"), 1);
360
390
  }
361
391
  });
362
392
 
363
393
  // src/index.ts
364
394
  var index_exports = {};
365
395
  __export(index_exports, {
396
+ BidirectionalSyncEngine: () => BidirectionalSyncEngine,
366
397
  ConcurrencyPool: () => ConcurrencyPool,
367
398
  DEFAULT_CHUNK_SIZE: () => DEFAULT_CHUNK_SIZE,
368
399
  DEFAULT_EXPORT_MIMES: () => DEFAULT_EXPORT_MIMES,
@@ -371,8 +402,10 @@ __export(index_exports, {
371
402
  DriveAuthError: () => DriveAuthError,
372
403
  DriveAuthenticator: () => DriveAuthenticator,
373
404
  DriveFileRef: () => DriveFileRef,
405
+ DriveFileRevisions: () => DriveFileRevisions,
374
406
  DriveFolderRef: () => DriveFolderRef,
375
407
  DriveKit: () => DriveKit,
408
+ DriveKitCrypto: () => DriveKitCrypto,
376
409
  DriveKitError: () => DriveKitError,
377
410
  DriveNotFoundError: () => DriveNotFoundError,
378
411
  DriveQueryBuilder: () => DriveQueryBuilder,
@@ -380,27 +413,47 @@ __export(index_exports, {
380
413
  DriveUploadError: () => DriveUploadError,
381
414
  DriveWatcher: () => DriveWatcher,
382
415
  GOOGLE_WORKSPACE_MIME_TYPES: () => GOOGLE_WORKSPACE_MIME_TYPES,
416
+ IV_LENGTH: () => IV_LENGTH,
417
+ MAGIC_HEADER: () => MAGIC_HEADER,
418
+ MAGIC_STREAM_HEADER: () => MAGIC_STREAM_HEADER,
383
419
  MIN_CHUNK_SIZE: () => MIN_CHUNK_SIZE,
384
420
  MULTIPART_THRESHOLD: () => MULTIPART_THRESHOLD,
385
421
  MemoryMetadataCache: () => MemoryMetadataCache,
422
+ PBKDF2_ROUNDS: () => PBKDF2_ROUNDS,
386
423
  PathResolver: () => PathResolver,
387
424
  PluginManager: () => PluginManager,
388
425
  ResumableUploader: () => ResumableUploader,
426
+ S3GatewayServer: () => S3GatewayServer,
427
+ SALT_LENGTH: () => SALT_LENGTH,
428
+ SecurityAuditor: () => SecurityAuditor,
429
+ SmartSearchEngine: () => SmartSearchEngine,
389
430
  SmartSyncEngine: () => SmartSyncEngine,
390
431
  SqliteMetadataCache: () => SqliteMetadataCache,
391
432
  StorageCleaner: () => StorageCleaner,
433
+ TAG_LENGTH: () => TAG_LENGTH,
392
434
  calculateFileMd5: () => calculateFileMd5,
435
+ compressBuffer: () => compressBuffer,
436
+ cosineSimilarity: () => cosineSimilarity,
393
437
  createAutoNamePlugin: () => createAutoNamePlugin,
438
+ createCompressStream: () => createCompressStream,
439
+ createDecompressStream: () => createDecompressStream,
394
440
  createDrive: () => createDrive,
441
+ createDriveUploadMiddleware: () => createDriveUploadMiddleware,
395
442
  createWebhookPlugin: () => createWebhookPlugin,
443
+ decompressBuffer: () => decompressBuffer,
396
444
  default: () => index_default,
445
+ deriveKey: () => deriveKey,
397
446
  escapeXml: () => escapeXml,
398
447
  formatBytes: () => formatBytes,
399
448
  formatDuration: () => formatDuration,
400
449
  formatSpeed: () => formatSpeed,
401
450
  getExtensionForMime: () => getExtensionForMime,
402
451
  getFileIcon: () => getFileIcon,
452
+ getOptimizedHttpAgent: () => getOptimizedHttpAgent,
453
+ getOptimizedHttpsAgent: () => getOptimizedHttpsAgent,
454
+ handleNextJsUpload: () => handleNextJsUpload,
403
455
  isGoogleWorkspaceDoc: () => isGoogleWorkspaceDoc,
456
+ isGzipBuffer: () => isGzipBuffer,
404
457
  isRetryableError: () => isRetryableError,
405
458
  loginWithBrowser: () => loginWithBrowser,
406
459
  lookupMimeType: () => lookupMimeType,
@@ -415,8 +468,9 @@ init_cjs_shims();
415
468
 
416
469
  // src/core/client.ts
417
470
  init_cjs_shims();
418
- var import_node_fs6 = __toESM(require("fs"), 1);
419
- var import_node_path7 = __toESM(require("path"), 1);
471
+ var import_node_fs7 = __toESM(require("fs"), 1);
472
+ var import_node_path9 = __toESM(require("path"), 1);
473
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
420
474
  var import_drive3 = require("@googleapis/drive");
421
475
 
422
476
  // src/auth/authenticator.ts
@@ -470,6 +524,39 @@ var DriveUploadError = class extends DriveKitError {
470
524
  }
471
525
  };
472
526
 
527
+ // src/utils/http-agent.ts
528
+ init_cjs_shims();
529
+ var import_node_https = __toESM(require("https"), 1);
530
+ var import_node_http = __toESM(require("http"), 1);
531
+ var sharedHttpsAgent = null;
532
+ var sharedHttpAgent = null;
533
+ function getOptimizedHttpsAgent(options) {
534
+ if (!sharedHttpsAgent) {
535
+ sharedHttpsAgent = new import_node_https.default.Agent({
536
+ keepAlive: options?.keepAlive ?? true,
537
+ maxSockets: options?.maxSockets ?? 64,
538
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
539
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
540
+ timeout: options?.timeout ?? 3e4,
541
+ noDelay: true
542
+ });
543
+ }
544
+ return sharedHttpsAgent;
545
+ }
546
+ function getOptimizedHttpAgent(options) {
547
+ if (!sharedHttpAgent) {
548
+ sharedHttpAgent = new import_node_http.default.Agent({
549
+ keepAlive: options?.keepAlive ?? true,
550
+ maxSockets: options?.maxSockets ?? 64,
551
+ maxFreeSockets: options?.maxFreeSockets ?? 32,
552
+ keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
553
+ timeout: options?.timeout ?? 3e4,
554
+ noDelay: true
555
+ });
556
+ }
557
+ return sharedHttpAgent;
558
+ }
559
+
473
560
  // src/auth/authenticator.ts
474
561
  var DEFAULT_SCOPES = [
475
562
  "https://www.googleapis.com/auth/drive"
@@ -493,44 +580,39 @@ var DriveAuthenticator = class {
493
580
  const oauth2Client = new import_drive.auth.OAuth2();
494
581
  oauth2Client.setCredentials({ access_token: this.config.accessToken });
495
582
  this.authClient = oauth2Client;
496
- return this.authClient;
497
- }
498
- if (this.config.oauth2Client) {
583
+ } else if (this.config.oauth2Client) {
499
584
  this.authClient = this.config.oauth2Client;
500
- return this.authClient;
501
- }
502
- if (this.config.oauth) {
585
+ } else if (this.config.oauth) {
503
586
  const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
504
587
  const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
505
588
  if (refreshToken) {
506
589
  oauth2Client.setCredentials({ refresh_token: refreshToken });
507
590
  }
508
591
  this.authClient = oauth2Client;
509
- return this.authClient;
510
- }
511
- const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
512
- if (keyFile) {
513
- if (!import_node_fs.default.existsSync(keyFile)) {
592
+ } else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
593
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
594
+ if (keyFile && !import_node_fs.default.existsSync(keyFile)) {
514
595
  throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
515
596
  }
516
- const auth2 = new import_drive.auth.GoogleAuth({
597
+ const auth = new import_drive.auth.GoogleAuth({
517
598
  keyFile,
518
599
  scopes
519
600
  });
520
- this.authClient = auth2;
521
- return this.authClient;
522
- }
523
- const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
524
- if (creds) {
525
- const auth2 = new import_drive.auth.GoogleAuth({
601
+ this.authClient = auth;
602
+ } else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
603
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
604
+ const auth = new import_drive.auth.GoogleAuth({
526
605
  credentials: creds,
527
606
  scopes
528
607
  });
529
- this.authClient = auth2;
530
- return this.authClient;
608
+ this.authClient = auth;
609
+ } else {
610
+ const auth = new import_drive.auth.GoogleAuth({ scopes });
611
+ this.authClient = auth;
612
+ }
613
+ if (this.authClient?.transporter?.defaults) {
614
+ this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
531
615
  }
532
- const auth = new import_drive.auth.GoogleAuth({ scopes });
533
- this.authClient = auth;
534
616
  return this.authClient;
535
617
  } catch (err) {
536
618
  if (err instanceof DriveAuthError) throw err;
@@ -669,6 +751,7 @@ var PathResolver = class {
669
751
  drive;
670
752
  rootFolderId;
671
753
  cache = /* @__PURE__ */ new Map();
754
+ inFlightResolves = /* @__PURE__ */ new Map();
672
755
  cacheTTL;
673
756
  enableCache;
674
757
  metadataCache;
@@ -692,8 +775,8 @@ var PathResolver = class {
692
775
  /**
693
776
  * Gets cache key for a path
694
777
  */
695
- getCacheKey(path8) {
696
- return `${this.rootFolderId}:${this.normalizePath(path8)}`;
778
+ getCacheKey(path11) {
779
+ return `${this.rootFolderId}:${this.normalizePath(path11)}`;
697
780
  }
698
781
  /**
699
782
  * Clears the path cache
@@ -707,8 +790,8 @@ var PathResolver = class {
707
790
  /**
708
791
  * Invalidate a single path from cache
709
792
  */
710
- invalidatePath(path8) {
711
- const norm = this.normalizePath(path8);
793
+ invalidatePath(path11) {
794
+ const norm = this.normalizePath(path11);
712
795
  const key = this.getCacheKey(norm);
713
796
  this.cache.delete(key);
714
797
  if (this.metadataCache) {
@@ -721,6 +804,7 @@ var PathResolver = class {
721
804
  /**
722
805
  * Resolves a path to a Google Drive item (file or folder).
723
806
  * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
807
+ * Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
724
808
  */
725
809
  async resolve(virtualPath, options = {}) {
726
810
  const norm = this.normalizePath(virtualPath);
@@ -754,6 +838,20 @@ var PathResolver = class {
754
838
  };
755
839
  }
756
840
  }
841
+ const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
842
+ const inFlight = this.inFlightResolves.get(flightKey);
843
+ if (inFlight) {
844
+ return await inFlight;
845
+ }
846
+ const task = this.doResolve(virtualPath, norm, options);
847
+ this.inFlightResolves.set(flightKey, task);
848
+ try {
849
+ return await task;
850
+ } finally {
851
+ this.inFlightResolves.delete(flightKey);
852
+ }
853
+ }
854
+ async doResolve(virtualPath, norm, options) {
757
855
  const segments = norm.split("/").filter(Boolean);
758
856
  let currentParentId = this.rootFolderId;
759
857
  let currentPath = "";
@@ -805,7 +903,7 @@ var PathResolver = class {
805
903
  });
806
904
  let file = response.data.files?.[0];
807
905
  if (!file && currentParentId === this.rootFolderId) {
808
- const sharedQ = `name = '${escapedName}' and trashed = false`;
906
+ const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
809
907
  const sharedResponse = await withRetry(async () => {
810
908
  return await this.drive.files.list({
811
909
  q: sharedQ,
@@ -915,6 +1013,7 @@ var PathResolver = class {
915
1013
  init_cjs_shims();
916
1014
  var import_node_fs2 = __toESM(require("fs"), 1);
917
1015
  var import_node_path = __toESM(require("path"), 1);
1016
+ var import_node_stream = require("stream");
918
1017
 
919
1018
  // src/utils/format.ts
920
1019
  init_cjs_shims();
@@ -979,6 +1078,15 @@ var ResumableUploader = class {
979
1078
  const totalBytes = stat.size;
980
1079
  const fileName = options.name || import_node_path.default.basename(filePath);
981
1080
  const mimeType = options.mimeType || lookupMimeType(filePath);
1081
+ if (totalBytes <= MULTIPART_THRESHOLD) {
1082
+ const readStream = import_node_fs2.default.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
1083
+ const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
1084
+ return await this.directUpload(stream, {
1085
+ ...options,
1086
+ name: fileName,
1087
+ mimeType
1088
+ });
1089
+ }
982
1090
  return await this.chunkedUpload({
983
1091
  filePath,
984
1092
  totalBytes,
@@ -994,6 +1102,16 @@ var ResumableUploader = class {
994
1102
  const totalBytes = buffer.length;
995
1103
  const fileName = options.name || "untitled";
996
1104
  const mimeType = options.mimeType || "application/octet-stream";
1105
+ if (totalBytes <= MULTIPART_THRESHOLD) {
1106
+ const { Readable } = await import("stream");
1107
+ const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
1108
+ const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
1109
+ return await this.directUpload(stream, {
1110
+ ...options,
1111
+ name: fileName,
1112
+ mimeType
1113
+ });
1114
+ }
997
1115
  return await this.chunkedUploadBuffer({
998
1116
  buffer,
999
1117
  totalBytes,
@@ -1014,6 +1132,50 @@ var ResumableUploader = class {
1014
1132
  mimeType
1015
1133
  });
1016
1134
  }
1135
+ /**
1136
+ * Calculates optimal chunk size based on file size for maximum throughput.
1137
+ */
1138
+ computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
1139
+ if (explicitChunkSize) {
1140
+ return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
1141
+ }
1142
+ if (totalBytes > 128 * 1024 * 1024) {
1143
+ return 32 * 1024 * 1024;
1144
+ }
1145
+ if (totalBytes > 32 * 1024 * 1024) {
1146
+ return 16 * 1024 * 1024;
1147
+ }
1148
+ return this.defaultChunkSize;
1149
+ }
1150
+ /**
1151
+ * Attaches real-time progress monitoring to direct stream uploads.
1152
+ */
1153
+ wrapStreamWithProgress(stream, totalBytes, onProgress) {
1154
+ let bytesSent = 0;
1155
+ const startTime = Date.now();
1156
+ const progressTransform = new import_node_stream.Transform({
1157
+ transform(chunk, _encoding, callback) {
1158
+ bytesSent += chunk.length;
1159
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
1160
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
1161
+ const remainingBytes = Math.max(0, totalBytes - bytesSent);
1162
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
1163
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
1164
+ onProgress({
1165
+ bytesSent,
1166
+ totalBytes,
1167
+ percentage,
1168
+ bytesPerSecond,
1169
+ speedFormatted: formatSpeed(bytesPerSecond),
1170
+ estimatedTimeRemainingSeconds,
1171
+ chunkIndex: 1,
1172
+ totalChunks: 1
1173
+ });
1174
+ callback(null, chunk);
1175
+ }
1176
+ });
1177
+ return stream.pipe(progressTransform);
1178
+ }
1017
1179
  /**
1018
1180
  * Fast direct upload using googleapis multipart
1019
1181
  */
@@ -1046,7 +1208,7 @@ var ResumableUploader = class {
1046
1208
  */
1047
1209
  async chunkedUpload(params) {
1048
1210
  const { filePath, totalBytes, fileName, mimeType, options } = params;
1049
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
1211
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
1050
1212
  const sessionUrl = await this.initiateResumableSession({
1051
1213
  fileName,
1052
1214
  mimeType,
@@ -1111,7 +1273,7 @@ var ResumableUploader = class {
1111
1273
  */
1112
1274
  async chunkedUploadBuffer(params) {
1113
1275
  const { buffer, totalBytes, fileName, mimeType, options } = params;
1114
- const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
1276
+ const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
1115
1277
  const sessionUrl = await this.initiateResumableSession({
1116
1278
  fileName,
1117
1279
  mimeType,
@@ -1190,7 +1352,8 @@ var ResumableUploader = class {
1190
1352
  url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
1191
1353
  method: "POST",
1192
1354
  headers,
1193
- data: metadata
1355
+ data: metadata,
1356
+ agent: getOptimizedHttpsAgent()
1194
1357
  });
1195
1358
  });
1196
1359
  const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
@@ -1216,6 +1379,7 @@ var ResumableUploader = class {
1216
1379
  method: "PUT",
1217
1380
  headers,
1218
1381
  data: buffer,
1382
+ agent: getOptimizedHttpsAgent(),
1219
1383
  validateStatus: (status) => status >= 200 && status < 300 || status === 308
1220
1384
  });
1221
1385
  if (res.status === 200 || res.status === 201) {
@@ -1249,7 +1413,7 @@ init_cjs_shims();
1249
1413
  var import_node_fs3 = __toESM(require("fs"), 1);
1250
1414
  var import_node_path2 = __toESM(require("path"), 1);
1251
1415
  var import_promises = require("stream/promises");
1252
- var import_node_stream = require("stream");
1416
+ var import_node_stream2 = require("stream");
1253
1417
  var Downloader = class {
1254
1418
  drive;
1255
1419
  constructor(drive2) {
@@ -1259,17 +1423,22 @@ var Downloader = class {
1259
1423
  * Downloads a file from Google Drive to local destination path or returns a readable stream.
1260
1424
  */
1261
1425
  async download(fileId, options = {}) {
1262
- const metaRes = await withRetry(async () => {
1263
- return await this.drive.files.get({
1264
- fileId,
1265
- fields: "id, name, mimeType, size",
1266
- supportsAllDrives: true
1426
+ let name = options.metadata?.name;
1427
+ let mimeType = options.metadata?.mimeType;
1428
+ let totalBytes = options.metadata?.size;
1429
+ if (!name || !mimeType) {
1430
+ const metaRes = await withRetry(async () => {
1431
+ return await this.drive.files.get({
1432
+ fileId,
1433
+ fields: "id, name, mimeType, size",
1434
+ supportsAllDrives: true
1435
+ });
1267
1436
  });
1268
- });
1269
- const file = metaRes.data;
1270
- const name = file.name || "downloaded-file";
1271
- const mimeType = file.mimeType || "application/octet-stream";
1272
- const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1437
+ const file = metaRes.data;
1438
+ name = file.name || "downloaded-file";
1439
+ mimeType = file.mimeType || "application/octet-stream";
1440
+ totalBytes = file.size ? parseInt(file.size, 10) : void 0;
1441
+ }
1273
1442
  let downloadStream;
1274
1443
  let finalFileName = name;
1275
1444
  if (isGoogleWorkspaceDoc(mimeType)) {
@@ -1300,7 +1469,7 @@ var Downloader = class {
1300
1469
  }
1301
1470
  let bytesRead = 0;
1302
1471
  const startTime = Date.now();
1303
- const progressTracker = new import_node_stream.Transform({
1472
+ const progressTracker = new import_node_stream2.Transform({
1304
1473
  transform(chunk, encoding, callback) {
1305
1474
  bytesRead += chunk.length;
1306
1475
  if (options.onProgress) {
@@ -1325,7 +1494,7 @@ var Downloader = class {
1325
1494
  destPath = import_node_path2.default.join(destPath, finalFileName);
1326
1495
  }
1327
1496
  await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
1328
- const writeStream = import_node_fs3.default.createWriteStream(destPath);
1497
+ const writeStream = import_node_fs3.default.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
1329
1498
  await (0, import_promises.pipeline)(monitoredStream, writeStream);
1330
1499
  return {
1331
1500
  filePath: destPath,
@@ -1568,6 +1737,7 @@ var DriveQueryBuilder = class {
1568
1737
  const q = this.toQueryString();
1569
1738
  const orderBy = this.orderClauses.join(", ");
1570
1739
  let pageToken = void 0;
1740
+ const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
1571
1741
  do {
1572
1742
  const res = await withRetry(async () => {
1573
1743
  return await this.drive.files.list({
@@ -1575,7 +1745,7 @@ var DriveQueryBuilder = class {
1575
1745
  orderBy: orderBy || void 0,
1576
1746
  pageSize: this.limitNumber,
1577
1747
  pageToken,
1578
- fields: this.requestedFields,
1748
+ fields: effectiveFields,
1579
1749
  spaces: this.spaces,
1580
1750
  supportsAllDrives: true,
1581
1751
  includeItemsFromAllDrives: true
@@ -1699,7 +1869,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
1699
1869
  const res = await withRetry(async () => {
1700
1870
  return await this.drive.changes.list({
1701
1871
  pageToken: nextPageToken,
1702
- fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1872
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
1703
1873
  supportsAllDrives: true,
1704
1874
  includeItemsFromAllDrives: true
1705
1875
  });
@@ -1790,16 +1960,24 @@ var StorageCleaner = class {
1790
1960
  async findDuplicates(options = {}) {
1791
1961
  const mode = options.by || "name";
1792
1962
  const maxScan = options.maxScan || 1e3;
1793
- const res = await withRetry(async () => {
1794
- return await this.drive.files.list({
1795
- q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1796
- pageSize: Math.min(1e3, maxScan),
1797
- fields: "files(id, name, size, md5Checksum, modifiedTime)",
1798
- supportsAllDrives: true,
1799
- includeItemsFromAllDrives: true
1963
+ const files = [];
1964
+ let pageToken = void 0;
1965
+ do {
1966
+ const remaining = maxScan - files.length;
1967
+ if (remaining <= 0) break;
1968
+ const res = await withRetry(async () => {
1969
+ return await this.drive.files.list({
1970
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1971
+ pageSize: Math.min(1e3, remaining),
1972
+ pageToken,
1973
+ fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
1974
+ supportsAllDrives: true,
1975
+ includeItemsFromAllDrives: true
1976
+ });
1800
1977
  });
1801
- });
1802
- const files = res.data.files || [];
1978
+ files.push(...res.data.files || []);
1979
+ pageToken = res.data.nextPageToken || void 0;
1980
+ } while (pageToken && files.length < maxScan);
1803
1981
  const map = /* @__PURE__ */ new Map();
1804
1982
  for (const f of files) {
1805
1983
  if (!f.id) continue;
@@ -1974,7 +2152,7 @@ var SmartSyncEngine = class {
1974
2152
 
1975
2153
  // src/auth/browser-login.ts
1976
2154
  init_cjs_shims();
1977
- var import_node_http = __toESM(require("http"), 1);
2155
+ var import_node_http2 = __toESM(require("http"), 1);
1978
2156
  var import_node_child_process = require("child_process");
1979
2157
  var import_drive2 = require("@googleapis/drive");
1980
2158
  async function loginWithBrowser(options) {
@@ -1992,7 +2170,7 @@ async function loginWithBrowser(options) {
1992
2170
  scope: scopes
1993
2171
  });
1994
2172
  return new Promise((resolve, reject) => {
1995
- const server = import_node_http.default.createServer(async (req, res) => {
2173
+ const server = import_node_http2.default.createServer(async (req, res) => {
1996
2174
  try {
1997
2175
  const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1998
2176
  if (reqUrl.pathname === "/oauth2callback") {
@@ -2076,7 +2254,11 @@ ${authUrl}
2076
2254
  });
2077
2255
  });
2078
2256
  server.on("error", (err) => {
2079
- reject(err);
2257
+ if (err.code === "EADDRINUSE") {
2258
+ reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
2259
+ } else {
2260
+ reject(err);
2261
+ }
2080
2262
  });
2081
2263
  });
2082
2264
  }
@@ -2143,6 +2325,10 @@ var DriveFileRef = class {
2143
2325
  async getLink() {
2144
2326
  return await this.drive.getShareableLink(this.pathOrId);
2145
2327
  }
2328
+ /** Access historical revisions & version control for this file */
2329
+ get revisions() {
2330
+ return this.drive.getRevisions(this.pathOrId);
2331
+ }
2146
2332
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
2147
2333
  async createReadStream(options) {
2148
2334
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2348,7 +2534,7 @@ function createAutoNamePlugin(options) {
2348
2534
  return {
2349
2535
  name: "drivekit-official-autoname",
2350
2536
  beforeUpload(opts) {
2351
- let name = opts.filename;
2537
+ let name = opts.name || opts.filename;
2352
2538
  if (!name && typeof opts.source === "string") {
2353
2539
  name = import_node_path4.default.basename(opts.source);
2354
2540
  }
@@ -2364,6 +2550,7 @@ function createAutoNamePlugin(options) {
2364
2550
  finalName = `${finalName}${ext}`;
2365
2551
  return {
2366
2552
  ...opts,
2553
+ name: finalName,
2367
2554
  filename: finalName
2368
2555
  };
2369
2556
  }
@@ -2511,10 +2698,35 @@ var SqliteMetadataCache = class {
2511
2698
  return;
2512
2699
  }
2513
2700
  if (!this.initialized || !this.db || entries.length === 0) return;
2701
+ const stmt = this.db.prepare(`
2702
+ INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
2703
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2704
+ ON CONFLICT(id) DO UPDATE SET
2705
+ name = excluded.name,
2706
+ mimeType = excluded.mimeType,
2707
+ size = excluded.size,
2708
+ parentId = excluded.parentId,
2709
+ path = COALESCE(excluded.path, files.path),
2710
+ md5Checksum = excluded.md5Checksum,
2711
+ trashed = excluded.trashed,
2712
+ modifiedTime = excluded.modifiedTime,
2713
+ updatedAt = excluded.updatedAt
2714
+ `);
2514
2715
  this.db.exec("BEGIN TRANSACTION;");
2515
2716
  try {
2516
2717
  for (const entry of entries) {
2517
- this.upsertFile(entry);
2718
+ stmt.run(
2719
+ entry.id,
2720
+ entry.name,
2721
+ entry.mimeType ?? null,
2722
+ entry.size ?? null,
2723
+ entry.parentId ?? null,
2724
+ entry.path ?? null,
2725
+ entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
2726
+ entry.trashed ? 1 : 0,
2727
+ entry.modifiedTime ?? null,
2728
+ entry.updatedAt ?? Date.now()
2729
+ );
2518
2730
  }
2519
2731
  this.db.exec("COMMIT;");
2520
2732
  } catch (e) {
@@ -2731,122 +2943,1336 @@ var MemoryMetadataCache = class {
2731
2943
  }
2732
2944
  };
2733
2945
 
2734
- // src/core/client.ts
2735
- var DriveKit = class _DriveKit {
2736
- options;
2737
- authenticator;
2738
- driveClient = null;
2739
- pathResolverInstance = null;
2740
- uploaderInstance = null;
2741
- downloaderInstance = null;
2742
- metadataCacheInstance = null;
2743
- rootFolderId;
2744
- pluginManager = new PluginManager();
2745
- constructor(options = {}) {
2746
- this.options = options;
2747
- this.rootFolderId = options.rootFolderId || "root";
2748
- this.authenticator = new DriveAuthenticator(options.auth);
2946
+ // src/crypto/encryption.ts
2947
+ init_cjs_shims();
2948
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
2949
+ var import_node_stream3 = require("stream");
2950
+ var MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2951
+ var MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2952
+ var SALT_LENGTH = 16;
2953
+ var IV_LENGTH = 12;
2954
+ var TAG_LENGTH = 16;
2955
+ var PBKDF2_ROUNDS = 1e5;
2956
+ function deriveKey(password, salt) {
2957
+ return import_node_crypto2.default.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2958
+ }
2959
+ var DriveKitCrypto = class {
2960
+ config;
2961
+ constructor(config) {
2962
+ if (!config.password && !config.key) {
2963
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2964
+ }
2965
+ if (config.key && config.key.length !== 32) {
2966
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2967
+ }
2968
+ this.config = config;
2749
2969
  }
2750
2970
  /**
2751
- * Registers a middleware plugin into DriveKit lifecycle
2971
+ * Encrypts a Buffer using AES-256-GCM.
2972
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2752
2973
  */
2753
- use(plugin) {
2754
- this.pluginManager.use(plugin);
2755
- return this;
2974
+ encryptBuffer(data) {
2975
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
2976
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
2977
+ const key = this.config.key || deriveKey(this.config.password, salt);
2978
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
2979
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2980
+ const tag = cipher.getAuthTag();
2981
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2756
2982
  }
2757
2983
  /**
2758
- * Returns a fluent, chained reference to a specific file
2984
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2759
2985
  */
2760
- file(pathOrId) {
2761
- return new DriveFileRef(this, pathOrId);
2986
+ decryptBuffer(encryptedData) {
2987
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2988
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2989
+ }
2990
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2991
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2992
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2993
+ if (!isStreamFormat && !isBufferFormat) {
2994
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2995
+ }
2996
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2997
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2998
+ const key = this.config.key || deriveKey(this.config.password, salt);
2999
+ let tag;
3000
+ let ciphertext;
3001
+ if (isStreamFormat) {
3002
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
3003
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
3004
+ } else {
3005
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
3006
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
3007
+ }
3008
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3009
+ decipher.setAuthTag(tag);
3010
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2762
3011
  }
2763
3012
  /**
2764
- * Returns a fluent, chained reference to a specific folder
3013
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
2765
3014
  */
2766
- folder(pathOrId) {
2767
- return new DriveFolderRef(this, pathOrId);
3015
+ createEncryptStream() {
3016
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
3017
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
3018
+ const key = this.config.key || deriveKey(this.config.password, salt);
3019
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
3020
+ let headerPushed = false;
3021
+ return new import_node_stream3.Transform({
3022
+ transform(chunk, _encoding, callback) {
3023
+ if (!headerPushed) {
3024
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
3025
+ headerPushed = true;
3026
+ }
3027
+ const encrypted = cipher.update(chunk);
3028
+ if (encrypted.length > 0) {
3029
+ this.push(encrypted);
3030
+ }
3031
+ callback();
3032
+ },
3033
+ flush(callback) {
3034
+ if (!headerPushed) {
3035
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
3036
+ headerPushed = true;
3037
+ }
3038
+ const finalChunk = cipher.final();
3039
+ const tag = cipher.getAuthTag();
3040
+ this.push(Buffer.concat([finalChunk, tag]));
3041
+ callback();
3042
+ }
3043
+ });
2768
3044
  }
2769
3045
  /**
2770
- * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
3046
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
2771
3047
  */
2772
- async init() {
2773
- if (!this.driveClient) {
2774
- const auth = await this.authenticator.getAuthClient();
2775
- this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
2776
- if (this.options.enablePersistentCache !== false) {
2777
- this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
2778
- this.metadataCacheInstance.init();
3048
+ createDecryptStream() {
3049
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
3050
+ let headerBuffer = Buffer.alloc(0);
3051
+ let decipher = null;
3052
+ let isStreamFormat = false;
3053
+ let pendingTail = Buffer.alloc(0);
3054
+ const self = this;
3055
+ return new import_node_stream3.Transform({
3056
+ transform(chunk, _encoding, callback) {
3057
+ try {
3058
+ let data = chunk;
3059
+ if (!decipher) {
3060
+ headerBuffer = Buffer.concat([headerBuffer, data]);
3061
+ if (headerBuffer.length < HEADER_BASE_LEN) {
3062
+ return callback();
3063
+ }
3064
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
3065
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
3066
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
3067
+ if (!isStreamFormat && !isBufferFormat) {
3068
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
3069
+ }
3070
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
3071
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
3072
+ const key = self.config.key || deriveKey(self.config.password, salt);
3073
+ decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3074
+ if (isBufferFormat) {
3075
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
3076
+ return callback();
3077
+ }
3078
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
3079
+ decipher.setAuthTag(tag);
3080
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
3081
+ headerBuffer = Buffer.alloc(0);
3082
+ } else {
3083
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
3084
+ headerBuffer = Buffer.alloc(0);
3085
+ }
3086
+ }
3087
+ if (data.length > 0) {
3088
+ if (isStreamFormat) {
3089
+ pendingTail = Buffer.concat([pendingTail, data]);
3090
+ if (pendingTail.length > TAG_LENGTH) {
3091
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
3092
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
3093
+ const decryptedChunk = decipher.update(toProcess);
3094
+ if (decryptedChunk.length > 0) {
3095
+ this.push(decryptedChunk);
3096
+ }
3097
+ }
3098
+ } else {
3099
+ const decryptedChunk = decipher.update(data);
3100
+ if (decryptedChunk.length > 0) {
3101
+ this.push(decryptedChunk);
3102
+ }
3103
+ }
3104
+ }
3105
+ callback();
3106
+ } catch (err) {
3107
+ callback(err);
3108
+ }
3109
+ },
3110
+ flush(callback) {
3111
+ try {
3112
+ if (!decipher) {
3113
+ return callback(new Error("Encrypted stream is too short: missing header."));
3114
+ }
3115
+ if (isStreamFormat) {
3116
+ if (pendingTail.length !== TAG_LENGTH) {
3117
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
3118
+ }
3119
+ decipher.setAuthTag(pendingTail);
3120
+ }
3121
+ const finalChunk = decipher.final();
3122
+ if (finalChunk.length > 0) {
3123
+ this.push(finalChunk);
3124
+ }
3125
+ callback();
3126
+ } catch (err) {
3127
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
3128
+ }
2779
3129
  }
2780
- this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
2781
- enableCache: this.options.enablePathCache ?? true,
2782
- cacheTTL: this.options.pathCacheTTL,
2783
- metadataCache: this.metadataCacheInstance || void 0
2784
- });
2785
- this.uploaderInstance = new ResumableUploader(
2786
- this.driveClient,
2787
- this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
2788
- );
2789
- this.downloaderInstance = new Downloader(this.driveClient);
2790
- }
2791
- return this;
3130
+ });
2792
3131
  }
2793
3132
  /**
2794
- * Access the underlying official `@googleapis/drive` instance for raw API calls
3133
+ * Encrypts a filename into a safe base64url string
2795
3134
  */
2796
- async getRawClient() {
2797
- await this.init();
2798
- return this.driveClient;
2799
- }
2800
- async getResolver() {
2801
- await this.init();
2802
- return this.pathResolverInstance;
2803
- }
2804
- async getUploader() {
2805
- await this.init();
2806
- return this.uploaderInstance;
2807
- }
2808
- async getDownloader() {
2809
- await this.init();
2810
- return this.downloaderInstance;
3135
+ encryptFilename(plainName) {
3136
+ const iv = import_node_crypto2.default.randomBytes(12);
3137
+ const salt = import_node_crypto2.default.randomBytes(8);
3138
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3139
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
3140
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
3141
+ const tag = cipher.getAuthTag();
3142
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
3143
+ return `dk_${payload.toString("base64url")}.enc`;
2811
3144
  }
2812
3145
  /**
2813
- * Resolves a target string that could be either an ID or a virtual path (starting with '/')
3146
+ * Decrypts a filename generated by encryptFilename
2814
3147
  */
2815
- async resolveId(idOrPath, autoCreateDir = false) {
2816
- if (idOrPath.startsWith("/")) {
2817
- const resolver = await this.getResolver();
2818
- const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });
2819
- return res.id;
3148
+ decryptFilename(encryptedName) {
3149
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
3150
+ return encryptedName;
3151
+ }
3152
+ try {
3153
+ const raw = encryptedName.slice(3, -4);
3154
+ const payload = Buffer.from(raw, "base64url");
3155
+ if (payload.length < 8 + 12 + 16) return encryptedName;
3156
+ const salt = payload.subarray(0, 8);
3157
+ const iv = payload.subarray(8, 20);
3158
+ const tag = payload.subarray(20, 36);
3159
+ const ciphertext = payload.subarray(36);
3160
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
3161
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
3162
+ decipher.setAuthTag(tag);
3163
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
3164
+ return decrypted.toString("utf8");
3165
+ } catch {
3166
+ return encryptedName;
2820
3167
  }
2821
- return idOrPath;
2822
3168
  }
2823
- // ==========================================
2824
- // DIRECTORY & PATH OPERATIONS
2825
- // ==========================================
3169
+ };
3170
+
3171
+ // src/core/revisions.ts
3172
+ init_cjs_shims();
3173
+ var DriveFileRevisions = class {
3174
+ drive;
3175
+ pathOrId;
3176
+ idResolver;
3177
+ constructor(drive2, pathOrId, idResolver) {
3178
+ this.drive = drive2;
3179
+ this.pathOrId = pathOrId;
3180
+ this.idResolver = idResolver;
3181
+ }
3182
+ async getId() {
3183
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
3184
+ return await this.idResolver(this.pathOrId);
3185
+ }
3186
+ return this.pathOrId;
3187
+ }
2826
3188
  /**
2827
- * Creates a folder structure recursively, similar to `mkdir -p`.
2828
- * @param virtualPath Path like "/Documents/Projects/2026"
2829
- * @returns Folder ID of the created or existing directory
3189
+ * Lists all historical revisions of the file
2830
3190
  */
2831
- async mkdirp(virtualPath) {
2832
- const resolver = await this.getResolver();
2833
- return await resolver.mkdirp(virtualPath);
3191
+ async list() {
3192
+ const fileId = await this.getId();
3193
+ const res = await withRetry(async () => {
3194
+ return await this.drive.revisions.list({
3195
+ fileId,
3196
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
3197
+ });
3198
+ });
3199
+ const revs = res.data.revisions || [];
3200
+ return revs.map((r) => ({
3201
+ id: r.id,
3202
+ mimeType: r.mimeType || void 0,
3203
+ modifiedTime: r.modifiedTime || void 0,
3204
+ keepForever: r.keepForever ?? false,
3205
+ size: r.size ? parseInt(r.size, 10) : void 0,
3206
+ originalFilename: r.originalFilename || void 0
3207
+ }));
2834
3208
  }
2835
3209
  /**
2836
- * Resolves a virtual path to its Drive metadata
3210
+ * Gets metadata for a specific revision
2837
3211
  */
2838
- async resolvePath(virtualPath) {
2839
- const resolver = await this.getResolver();
2840
- return await resolver.resolve(virtualPath);
3212
+ async get(revisionId) {
3213
+ const fileId = await this.getId();
3214
+ const res = await withRetry(async () => {
3215
+ return await this.drive.revisions.get({
3216
+ fileId,
3217
+ revisionId,
3218
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
3219
+ });
3220
+ });
3221
+ const r = res.data;
3222
+ return {
3223
+ id: r.id,
3224
+ mimeType: r.mimeType || void 0,
3225
+ modifiedTime: r.modifiedTime || void 0,
3226
+ keepForever: r.keepForever ?? false,
3227
+ size: r.size ? parseInt(r.size, 10) : void 0,
3228
+ originalFilename: r.originalFilename || void 0
3229
+ };
2841
3230
  }
2842
3231
  /**
2843
- * Check if a file or folder exists (by ID or virtual path)
3232
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
2844
3233
  */
2845
- async exists(idOrPath) {
2846
- try {
2847
- if (idOrPath.startsWith("/")) {
2848
- await this.resolvePath(idOrPath);
2849
- return true;
3234
+ async keepForever(revisionId, keep = true) {
3235
+ const fileId = await this.getId();
3236
+ const res = await withRetry(async () => {
3237
+ return await this.drive.revisions.update({
3238
+ fileId,
3239
+ revisionId,
3240
+ requestBody: {
3241
+ keepForever: keep
3242
+ },
3243
+ fields: "id, keepForever, modifiedTime"
3244
+ });
3245
+ });
3246
+ return {
3247
+ id: res.data.id,
3248
+ keepForever: res.data.keepForever ?? keep,
3249
+ modifiedTime: res.data.modifiedTime || void 0
3250
+ };
3251
+ }
3252
+ /**
3253
+ * Deletes a specific historical revision
3254
+ */
3255
+ async delete(revisionId) {
3256
+ const fileId = await this.getId();
3257
+ await withRetry(async () => {
3258
+ return await this.drive.revisions.delete({
3259
+ fileId,
3260
+ revisionId
3261
+ });
3262
+ });
3263
+ }
3264
+ /**
3265
+ * Gets a readable stream of a specific historical revision
3266
+ */
3267
+ async getStream(revisionId) {
3268
+ const fileId = await this.getId();
3269
+ const res = await withRetry(async () => {
3270
+ return await this.drive.revisions.get(
3271
+ { fileId, revisionId, alt: "media" },
3272
+ { responseType: "stream" }
3273
+ );
3274
+ });
3275
+ return res.data;
3276
+ }
3277
+ /**
3278
+ * Restores the file content to a specific previous revision
3279
+ */
3280
+ async restore(revisionId) {
3281
+ const fileId = await this.getId();
3282
+ const stream = await this.getStream(revisionId);
3283
+ const meta = await this.get(revisionId);
3284
+ await withRetry(async () => {
3285
+ return await this.drive.files.update({
3286
+ fileId,
3287
+ media: {
3288
+ mimeType: meta.mimeType || "application/octet-stream",
3289
+ body: stream
3290
+ }
3291
+ });
3292
+ });
3293
+ }
3294
+ };
3295
+
3296
+ // src/core/bidirectional-sync.ts
3297
+ init_cjs_shims();
3298
+ var import_node_fs6 = __toESM(require("fs"), 1);
3299
+ var import_node_path6 = __toESM(require("path"), 1);
3300
+ var BidirectionalSyncEngine = class {
3301
+ drive;
3302
+ ledger = /* @__PURE__ */ new Map();
3303
+ constructor(drive2) {
3304
+ this.drive = drive2;
3305
+ }
3306
+ /**
3307
+ * Performs a two-way synchronization cycle between local and remote directories
3308
+ */
3309
+ async sync(options) {
3310
+ const startTime = Date.now();
3311
+ const {
3312
+ localDir,
3313
+ remoteDir,
3314
+ conflictStrategy = "rename-conflict",
3315
+ deleteMissing = false,
3316
+ dryRun = false,
3317
+ onProgress
3318
+ } = options;
3319
+ const result = {
3320
+ uploaded: [],
3321
+ downloaded: [],
3322
+ deletedLocal: [],
3323
+ deletedRemote: [],
3324
+ conflicts: [],
3325
+ skipped: [],
3326
+ durationMs: 0
3327
+ };
3328
+ if (!import_node_fs6.default.existsSync(localDir)) {
3329
+ await import_node_fs6.default.promises.mkdir(localDir, { recursive: true });
3330
+ }
3331
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
3332
+ const localFiles = await this.scanLocalDir(localDir);
3333
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
3334
+ const allPaths = /* @__PURE__ */ new Set([
3335
+ ...localFiles.keys(),
3336
+ ...remoteFiles.keys(),
3337
+ ...this.ledger.keys()
3338
+ ]);
3339
+ for (const relPath of allPaths) {
3340
+ const resolvedLocal = import_node_path6.default.resolve(localDir, relPath);
3341
+ const resolvedRoot = import_node_path6.default.resolve(localDir);
3342
+ if (!resolvedLocal.startsWith(resolvedRoot + import_node_path6.default.sep) && resolvedLocal !== resolvedRoot) {
3343
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
3344
+ }
3345
+ const local = localFiles.get(relPath);
3346
+ const remote = remoteFiles.get(relPath);
3347
+ const prev = this.ledger.get(relPath);
3348
+ if (local && remote) {
3349
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
3350
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
3351
+ if (local.md5 === remote.md5) {
3352
+ result.skipped.push(relPath);
3353
+ onProgress?.({ action: "skip-identical", relPath });
3354
+ this.ledger.set(relPath, {
3355
+ relPath,
3356
+ localMtime: local.mtime,
3357
+ remoteMtime: remote.mtime,
3358
+ localMd5: local.md5,
3359
+ remoteMd5: remote.md5,
3360
+ remoteId: remote.id
3361
+ });
3362
+ continue;
3363
+ }
3364
+ if (localChanged && !remoteChanged) {
3365
+ if (!dryRun) {
3366
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3367
+ const freshRemote = await this.drive.getFile(remote.id);
3368
+ this.updateLedger(relPath, local, freshRemote);
3369
+ }
3370
+ result.uploaded.push(relPath);
3371
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
3372
+ continue;
3373
+ }
3374
+ if (remoteChanged && !localChanged) {
3375
+ if (!dryRun) {
3376
+ await this.downloadFile(remote.id, local.fullPath);
3377
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3378
+ this.ledger.set(relPath, {
3379
+ relPath,
3380
+ localMtime: freshStat.mtimeMs,
3381
+ remoteMtime: remote.mtime,
3382
+ localMd5: remote.md5,
3383
+ remoteMd5: remote.md5,
3384
+ remoteId: remote.id
3385
+ });
3386
+ }
3387
+ result.downloaded.push(relPath);
3388
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
3389
+ continue;
3390
+ }
3391
+ result.conflicts.push(relPath);
3392
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
3393
+ if (!dryRun) {
3394
+ if (conflictStrategy === "prefer-local") {
3395
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3396
+ const freshRemote = await this.drive.getFile(remote.id);
3397
+ this.updateLedger(relPath, local, freshRemote);
3398
+ result.uploaded.push(relPath);
3399
+ } else if (conflictStrategy === "prefer-cloud") {
3400
+ await this.downloadFile(remote.id, local.fullPath);
3401
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3402
+ this.ledger.set(relPath, {
3403
+ relPath,
3404
+ localMtime: freshStat.mtimeMs,
3405
+ remoteMtime: remote.mtime,
3406
+ localMd5: remote.md5,
3407
+ remoteMd5: remote.md5,
3408
+ remoteId: remote.id
3409
+ });
3410
+ result.downloaded.push(relPath);
3411
+ } else if (conflictStrategy === "keep-newer") {
3412
+ if (local.mtime >= remote.mtime) {
3413
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3414
+ const freshRemote = await this.drive.getFile(remote.id);
3415
+ this.updateLedger(relPath, local, freshRemote);
3416
+ result.uploaded.push(relPath);
3417
+ } else {
3418
+ await this.downloadFile(remote.id, local.fullPath);
3419
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3420
+ this.ledger.set(relPath, {
3421
+ relPath,
3422
+ localMtime: freshStat.mtimeMs,
3423
+ remoteMtime: remote.mtime,
3424
+ localMd5: remote.md5,
3425
+ remoteMd5: remote.md5,
3426
+ remoteId: remote.id
3427
+ });
3428
+ result.downloaded.push(relPath);
3429
+ }
3430
+ } else {
3431
+ const ext = import_node_path6.default.extname(relPath);
3432
+ const base = relPath.slice(0, relPath.length - ext.length);
3433
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3434
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3435
+ const conflictFullPath = import_node_path6.default.join(localDir, conflictRelPath);
3436
+ await this.downloadFile(remote.id, conflictFullPath);
3437
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3438
+ const freshRemote = await this.drive.getFile(remote.id);
3439
+ this.updateLedger(relPath, local, freshRemote);
3440
+ }
3441
+ }
3442
+ continue;
3443
+ }
3444
+ if (local && !remote) {
3445
+ if (prev && deleteMissing) {
3446
+ if (!dryRun) {
3447
+ await import_node_fs6.default.promises.unlink(local.fullPath);
3448
+ this.ledger.delete(relPath);
3449
+ }
3450
+ result.deletedLocal.push(relPath);
3451
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3452
+ } else {
3453
+ if (!dryRun) {
3454
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3455
+ this.updateLedger(relPath, local, uploadedFile);
3456
+ }
3457
+ result.uploaded.push(relPath);
3458
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3459
+ }
3460
+ continue;
3461
+ }
3462
+ if (!local && remote) {
3463
+ if (prev && deleteMissing) {
3464
+ if (!dryRun) {
3465
+ await this.drive.delete(remote.id, true);
3466
+ this.ledger.delete(relPath);
3467
+ }
3468
+ result.deletedRemote.push(relPath);
3469
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3470
+ } else {
3471
+ if (!dryRun) {
3472
+ const localDest = import_node_path6.default.join(localDir, relPath);
3473
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(localDest), { recursive: true });
3474
+ await this.downloadFile(remote.id, localDest);
3475
+ const stat = await import_node_fs6.default.promises.stat(localDest);
3476
+ this.ledger.set(relPath, {
3477
+ relPath,
3478
+ localMtime: stat.mtimeMs,
3479
+ remoteMtime: remote.mtime,
3480
+ localMd5: remote.md5,
3481
+ remoteMd5: remote.md5,
3482
+ remoteId: remote.id
3483
+ });
3484
+ }
3485
+ result.downloaded.push(relPath);
3486
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3487
+ }
3488
+ continue;
3489
+ }
3490
+ if (prev && !local && !remote) {
3491
+ this.ledger.delete(relPath);
3492
+ }
3493
+ }
3494
+ result.durationMs = Date.now() - startTime;
3495
+ return result;
3496
+ }
3497
+ async scanLocalDir(dir, baseDir = dir) {
3498
+ const map = /* @__PURE__ */ new Map();
3499
+ if (!import_node_fs6.default.existsSync(dir)) return map;
3500
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3501
+ for (const entry of entries) {
3502
+ const fullPath = import_node_path6.default.join(dir, entry.name);
3503
+ if (entry.isDirectory()) {
3504
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3505
+ for (const [k, v] of sub) map.set(k, v);
3506
+ } else if (entry.isFile()) {
3507
+ const rel = import_node_path6.default.relative(baseDir, fullPath).replace(/\\/g, "/");
3508
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
3509
+ const md5 = await calculateFileMd5(fullPath);
3510
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3511
+ }
3512
+ }
3513
+ return map;
3514
+ }
3515
+ async scanRemoteDir(folderId, relPrefix) {
3516
+ const map = /* @__PURE__ */ new Map();
3517
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3518
+ for (const item of items) {
3519
+ if (!item.id || !item.name) continue;
3520
+ const cleanName = import_node_path6.default.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3521
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3522
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3523
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3524
+ const sub = await this.scanRemoteDir(item.id, relPath);
3525
+ for (const [k, v] of sub) map.set(k, v);
3526
+ } else {
3527
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3528
+ map.set(relPath, {
3529
+ id: item.id,
3530
+ name: item.name,
3531
+ mtime,
3532
+ md5: item.md5Checksum || ""
3533
+ });
3534
+ }
3535
+ }
3536
+ return map;
3537
+ }
3538
+ async uploadFile(localPath, remoteDir, relPath) {
3539
+ const remoteSubDir = import_node_path6.default.dirname(relPath);
3540
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3541
+ return await this.drive.upload({
3542
+ source: localPath,
3543
+ name: import_node_path6.default.basename(relPath),
3544
+ parent: targetFolder,
3545
+ overwrite: true
3546
+ });
3547
+ }
3548
+ async downloadFile(fileId, destPath) {
3549
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(destPath), { recursive: true });
3550
+ await this.drive.download(fileId, { destination: destPath });
3551
+ }
3552
+ updateLedger(relPath, local, remote) {
3553
+ this.ledger.set(relPath, {
3554
+ relPath,
3555
+ localMtime: local.mtime,
3556
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3557
+ localMd5: local.md5,
3558
+ remoteMd5: remote.md5Checksum || local.md5,
3559
+ remoteId: remote.id
3560
+ });
3561
+ }
3562
+ };
3563
+
3564
+ // src/server/s3-gateway.ts
3565
+ init_cjs_shims();
3566
+ var import_node_http3 = __toESM(require("http"), 1);
3567
+ var import_node_path7 = __toESM(require("path"), 1);
3568
+ var import_node_url = require("url");
3569
+ var S3GatewayServer = class {
3570
+ drive;
3571
+ options;
3572
+ server = null;
3573
+ constructor(drive2, options = {}) {
3574
+ this.drive = drive2;
3575
+ this.options = {
3576
+ port: options.port || 9e3,
3577
+ host: options.host || "127.0.0.1",
3578
+ bucketRoot: options.bucketRoot || "/",
3579
+ ...options
3580
+ };
3581
+ }
3582
+ /**
3583
+ * Starts the S3 gateway HTTP server
3584
+ */
3585
+ async start() {
3586
+ return new Promise((resolve, reject) => {
3587
+ this.server = import_node_http3.default.createServer(async (req, res) => {
3588
+ try {
3589
+ await this.handleRequest(req, res);
3590
+ } catch (err) {
3591
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3592
+ }
3593
+ });
3594
+ this.server.on("error", reject);
3595
+ this.server.listen(this.options.port, this.options.host, () => {
3596
+ resolve({ port: this.options.port, host: this.options.host });
3597
+ });
3598
+ });
3599
+ }
3600
+ /**
3601
+ * Stops the S3 gateway HTTP server
3602
+ */
3603
+ async stop() {
3604
+ return new Promise((resolve) => {
3605
+ if (this.server) {
3606
+ this.server.close(() => resolve());
3607
+ } else {
3608
+ resolve();
3609
+ }
3610
+ });
3611
+ }
3612
+ async handleRequest(req, res) {
3613
+ const parsed = (0, import_node_url.parse)(req.url || "/", true);
3614
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3615
+ const pathname = import_node_path7.default.posix.normalize(rawPathname);
3616
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3617
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3618
+ return;
3619
+ }
3620
+ const method = req.method?.toUpperCase() || "GET";
3621
+ if (this.options.accessKeyId) {
3622
+ const authHeader = req.headers["authorization"];
3623
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3624
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3625
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3626
+ return;
3627
+ }
3628
+ }
3629
+ const segments = pathname.split("/").filter(Boolean);
3630
+ if (segments.some((s) => s === ".." || s === ".")) {
3631
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3632
+ return;
3633
+ }
3634
+ if (segments.length === 0) {
3635
+ if (method === "GET") {
3636
+ await this.handleListBuckets(res);
3637
+ return;
3638
+ }
3639
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3640
+ return;
3641
+ }
3642
+ const bucket = segments[0];
3643
+ const key = segments.slice(1).join("/");
3644
+ if (!key) {
3645
+ if (method === "GET") {
3646
+ const prefix = parsed.query.prefix || "";
3647
+ await this.handleListObjects(bucket, prefix, res);
3648
+ return;
3649
+ }
3650
+ if (method === "PUT") {
3651
+ await this.drive.mkdirp(`/${bucket}`);
3652
+ res.statusCode = 200;
3653
+ res.end();
3654
+ return;
3655
+ }
3656
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3657
+ return;
3658
+ }
3659
+ const remotePath = `/${bucket}/${key}`;
3660
+ if (method === "HEAD") {
3661
+ try {
3662
+ const file = await this.drive.getFile(remotePath);
3663
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3664
+ res.setHeader("Content-Length", file.size || "0");
3665
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3666
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3667
+ res.statusCode = 200;
3668
+ res.end();
3669
+ } catch {
3670
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3671
+ }
3672
+ return;
3673
+ }
3674
+ if (method === "GET") {
3675
+ try {
3676
+ const file = await this.drive.getFile(remotePath);
3677
+ const range = req.headers["range"];
3678
+ let options = void 0;
3679
+ if (range && range.startsWith("bytes=")) {
3680
+ const parts = range.replace("bytes=", "").split("-");
3681
+ options = {
3682
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3683
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3684
+ };
3685
+ res.statusCode = 206;
3686
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3687
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3688
+ } else {
3689
+ res.statusCode = 200;
3690
+ }
3691
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3692
+ res.setHeader("Content-Length", file.size || "0");
3693
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3694
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3695
+ const stream = await this.drive.createReadStream(remotePath, options);
3696
+ stream.pipe(res);
3697
+ } catch {
3698
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3699
+ }
3700
+ return;
3701
+ }
3702
+ if (method === "PUT") {
3703
+ const upload = await this.drive.createWriteStream(remotePath);
3704
+ req.pipe(upload);
3705
+ try {
3706
+ const file = await upload.done;
3707
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3708
+ res.statusCode = 200;
3709
+ res.end();
3710
+ } catch (err) {
3711
+ this.sendXmlError(res, 500, "InternalError", err.message);
3712
+ }
3713
+ return;
3714
+ }
3715
+ if (method === "DELETE") {
3716
+ try {
3717
+ const file = await this.drive.resolvePath(remotePath);
3718
+ await this.drive.delete(file.id, true);
3719
+ res.statusCode = 204;
3720
+ res.end();
3721
+ } catch {
3722
+ res.statusCode = 204;
3723
+ res.end();
3724
+ }
3725
+ return;
3726
+ }
3727
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3728
+ }
3729
+ async handleListBuckets(res) {
3730
+ const items = await this.drive.ls("/");
3731
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3732
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3733
+ xml += " <Buckets>\n";
3734
+ for (const f of folders) {
3735
+ xml += " <Bucket>\n";
3736
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3737
+ `;
3738
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3739
+ `;
3740
+ xml += " </Bucket>\n";
3741
+ }
3742
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3743
+ res.setHeader("Content-Type", "application/xml");
3744
+ res.statusCode = 200;
3745
+ res.end(xml);
3746
+ }
3747
+ async handleListObjects(bucket, prefix, res) {
3748
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3749
+ let items = [];
3750
+ try {
3751
+ items = await this.drive.ls(targetPath);
3752
+ } catch {
3753
+ items = [];
3754
+ }
3755
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3756
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3757
+ `;
3758
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3759
+ `;
3760
+ xml += " <IsTruncated>false</IsTruncated>\n";
3761
+ for (const item of items) {
3762
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3763
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3764
+ xml += " <Contents>\n";
3765
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3766
+ `;
3767
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3768
+ `;
3769
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3770
+ `;
3771
+ xml += ` <Size>${item.size || 0}</Size>
3772
+ `;
3773
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3774
+ xml += " </Contents>\n";
3775
+ }
3776
+ xml += "</ListBucketResult>";
3777
+ res.setHeader("Content-Type", "application/xml");
3778
+ res.statusCode = 200;
3779
+ res.end(xml);
3780
+ }
3781
+ sendXmlError(res, status, code, message) {
3782
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3783
+ <Error>
3784
+ <Code>${this.escapeXml(code)}</Code>
3785
+ <Message>${this.escapeXml(message)}</Message>
3786
+ </Error>`;
3787
+ res.setHeader("Content-Type", "application/xml");
3788
+ res.statusCode = status;
3789
+ res.end(xml);
3790
+ }
3791
+ escapeXml(unsafe) {
3792
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3793
+ switch (c) {
3794
+ case "<":
3795
+ return "&lt;";
3796
+ case ">":
3797
+ return "&gt;";
3798
+ case "&":
3799
+ return "&amp;";
3800
+ case "'":
3801
+ return "&apos;";
3802
+ case '"':
3803
+ return "&quot;";
3804
+ default:
3805
+ return c;
3806
+ }
3807
+ });
3808
+ }
3809
+ };
3810
+
3811
+ // src/core/security-auditor.ts
3812
+ init_cjs_shims();
3813
+ var SecurityAuditor = class {
3814
+ drive;
3815
+ constructor(drive2) {
3816
+ this.drive = drive2;
3817
+ }
3818
+ /**
3819
+ * Scans Google Drive files and audits their permission grants
3820
+ */
3821
+ async audit(options = {}) {
3822
+ const limit = options.scanLimit || 500;
3823
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3824
+ const issues = [];
3825
+ let publicCount = 0;
3826
+ let domainCount = 0;
3827
+ let externalCount = 0;
3828
+ let scannedTotal = 0;
3829
+ let pageToken = void 0;
3830
+ do {
3831
+ const res = await withRetry(async () => {
3832
+ return await this.drive.files.list({
3833
+ q: "trashed = false",
3834
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3835
+ pageSize: Math.min(100, limit - scannedTotal),
3836
+ supportsAllDrives: true,
3837
+ includeItemsFromAllDrives: true,
3838
+ pageToken
3839
+ });
3840
+ });
3841
+ const files = res.data.files || [];
3842
+ for (const file of files) {
3843
+ if (!file.id || !file.name) continue;
3844
+ scannedTotal++;
3845
+ const perms = file.permissions || [];
3846
+ for (const p of perms) {
3847
+ if (p.type === "anyone") {
3848
+ publicCount++;
3849
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3850
+ issues.push({
3851
+ fileId: file.id,
3852
+ fileName: file.name,
3853
+ risk: isCritical ? "CRITICAL" : "HIGH",
3854
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3855
+ permissionId: p.id,
3856
+ type: p.type,
3857
+ role: p.role || "reader",
3858
+ webViewLink: file.webViewLink || void 0
3859
+ });
3860
+ continue;
3861
+ }
3862
+ if (p.type === "domain") {
3863
+ domainCount++;
3864
+ issues.push({
3865
+ fileId: file.id,
3866
+ fileName: file.name,
3867
+ risk: "MEDIUM",
3868
+ reason: `Shared with entire organization domain (${p.domain})`,
3869
+ permissionId: p.id,
3870
+ type: p.type,
3871
+ role: p.role || "reader",
3872
+ domain: p.domain || void 0,
3873
+ webViewLink: file.webViewLink || void 0
3874
+ });
3875
+ continue;
3876
+ }
3877
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3878
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3879
+ if (userDomain && !allowedDomains.has(userDomain)) {
3880
+ externalCount++;
3881
+ issues.push({
3882
+ fileId: file.id,
3883
+ fileName: file.name,
3884
+ risk: "HIGH",
3885
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3886
+ permissionId: p.id,
3887
+ type: p.type,
3888
+ role: p.role || "reader",
3889
+ emailAddress: p.emailAddress,
3890
+ webViewLink: file.webViewLink || void 0
3891
+ });
3892
+ }
3893
+ }
3894
+ }
3895
+ }
3896
+ pageToken = res.data.nextPageToken || void 0;
3897
+ } while (pageToken && scannedTotal < limit);
3898
+ return {
3899
+ totalScanned: scannedTotal,
3900
+ publicFilesCount: publicCount,
3901
+ domainSharedCount: domainCount,
3902
+ externalSharesCount: externalCount,
3903
+ issues,
3904
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3905
+ };
3906
+ }
3907
+ /**
3908
+ * Revokes public 'anyone' permissions on specified files
3909
+ */
3910
+ async revokePublicAccess(fileIds) {
3911
+ const revoked = [];
3912
+ const errors = [];
3913
+ for (const fileId of fileIds) {
3914
+ try {
3915
+ const fileRes = await withRetry(async () => {
3916
+ return await this.drive.files.get({
3917
+ fileId,
3918
+ fields: "id, permissions(id, type)",
3919
+ supportsAllDrives: true
3920
+ });
3921
+ });
3922
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3923
+ for (const p of publicPerms) {
3924
+ if (p.id) {
3925
+ await withRetry(async () => {
3926
+ return await this.drive.permissions.delete({
3927
+ fileId,
3928
+ permissionId: p.id,
3929
+ supportsAllDrives: true
3930
+ });
3931
+ });
3932
+ }
3933
+ }
3934
+ revoked.push(fileId);
3935
+ } catch (err) {
3936
+ errors.push({ fileId, error: err.message });
3937
+ }
3938
+ }
3939
+ return { revoked, errors };
3940
+ }
3941
+ };
3942
+
3943
+ // src/core/semantic-search.ts
3944
+ init_cjs_shims();
3945
+ function levenshtein(a, b) {
3946
+ const an = a.length;
3947
+ const bn = b.length;
3948
+ if (an === 0) return bn;
3949
+ if (bn === 0) return an;
3950
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3951
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3952
+ for (let i = 1; i <= bn; i++) {
3953
+ for (let j = 1; j <= an; j++) {
3954
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3955
+ matrix[i][j] = matrix[i - 1][j - 1];
3956
+ } else {
3957
+ matrix[i][j] = Math.min(
3958
+ matrix[i - 1][j - 1] + 1,
3959
+ // substitution
3960
+ matrix[i][j - 1] + 1,
3961
+ // insertion
3962
+ matrix[i - 1][j] + 1
3963
+ // deletion
3964
+ );
3965
+ }
3966
+ }
3967
+ }
3968
+ return matrix[bn][an];
3969
+ }
3970
+ function cosineSimilarity(vecA, vecB) {
3971
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3972
+ let dot = 0;
3973
+ let normA = 0;
3974
+ let normB = 0;
3975
+ for (let i = 0; i < vecA.length; i++) {
3976
+ dot += vecA[i] * vecB[i];
3977
+ normA += vecA[i] * vecA[i];
3978
+ normB += vecB[i] * vecB[i];
3979
+ }
3980
+ if (normA === 0 || normB === 0) return 0;
3981
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3982
+ }
3983
+ var SmartSearchEngine = class {
3984
+ drive;
3985
+ constructor(drive2) {
3986
+ this.drive = drive2;
3987
+ }
3988
+ /**
3989
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3990
+ */
3991
+ async search(query, options = {}) {
3992
+ const limit = options.limit || 20;
3993
+ const minScore = options.minScore ?? 0.3;
3994
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3995
+ if (queryTokens.length === 0) return [];
3996
+ let candidates = [];
3997
+ if (options.parent) {
3998
+ candidates = await this.drive.ls(options.parent);
3999
+ } else {
4000
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
4001
+ }
4002
+ let queryVector = null;
4003
+ if (options.embedder) {
4004
+ try {
4005
+ queryVector = await options.embedder(query);
4006
+ } catch {
4007
+ queryVector = null;
4008
+ }
4009
+ }
4010
+ const scored = [];
4011
+ for (const file of candidates) {
4012
+ const fileName = (file.name || "").toLowerCase();
4013
+ const desc = (file.description || "").toLowerCase();
4014
+ const matchedOn = [];
4015
+ let nameScore = 0;
4016
+ let descScore = 0;
4017
+ let semanticScore = 0;
4018
+ if (fileName.includes(query.toLowerCase())) {
4019
+ nameScore = 0.95;
4020
+ matchedOn.push("name");
4021
+ } else {
4022
+ let tokensMatched = 0;
4023
+ for (const token of queryTokens) {
4024
+ if (fileName.includes(token)) {
4025
+ tokensMatched += 1;
4026
+ continue;
4027
+ }
4028
+ const words = fileName.split(/[\s._-]+/);
4029
+ for (const word of words) {
4030
+ const dist = levenshtein(token, word);
4031
+ const maxLen = Math.max(token.length, word.length);
4032
+ if (maxLen > 3 && dist <= 2) {
4033
+ tokensMatched += 1 - dist / maxLen;
4034
+ break;
4035
+ }
4036
+ }
4037
+ }
4038
+ nameScore = tokensMatched / queryTokens.length;
4039
+ if (nameScore > 0.4) matchedOn.push("name");
4040
+ }
4041
+ if (desc) {
4042
+ if (desc.includes(query.toLowerCase())) {
4043
+ descScore = 0.8;
4044
+ matchedOn.push("description");
4045
+ }
4046
+ }
4047
+ if (queryVector && options.embedder) {
4048
+ try {
4049
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
4050
+ semanticScore = cosineSimilarity(queryVector, fileVector);
4051
+ if (semanticScore > 0.6) matchedOn.push("semantic");
4052
+ } catch {
4053
+ }
4054
+ }
4055
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
4056
+ if (totalScore >= minScore) {
4057
+ scored.push({
4058
+ file,
4059
+ score: Math.round(totalScore * 100) / 100,
4060
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
4061
+ });
4062
+ }
4063
+ }
4064
+ scored.sort((a, b) => b.score - a.score);
4065
+ return scored.slice(0, limit);
4066
+ }
4067
+ };
4068
+
4069
+ // src/utils/compression.ts
4070
+ init_cjs_shims();
4071
+ var import_node_zlib = __toESM(require("zlib"), 1);
4072
+ var import_node_util = require("util");
4073
+ var gzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gzip);
4074
+ var gunzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gunzip);
4075
+ var brotliCompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliCompress);
4076
+ var brotliDecompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliDecompress);
4077
+ function createCompressStream(algorithm = "gzip") {
4078
+ switch (algorithm) {
4079
+ case "brotli":
4080
+ return import_node_zlib.default.createBrotliCompress();
4081
+ case "deflate":
4082
+ return import_node_zlib.default.createDeflate();
4083
+ case "gzip":
4084
+ default:
4085
+ return import_node_zlib.default.createGzip();
4086
+ }
4087
+ }
4088
+ function createDecompressStream(algorithm = "gzip") {
4089
+ switch (algorithm) {
4090
+ case "brotli":
4091
+ return import_node_zlib.default.createBrotliDecompress();
4092
+ case "deflate":
4093
+ return import_node_zlib.default.createInflate();
4094
+ case "gzip":
4095
+ default:
4096
+ return import_node_zlib.default.createGunzip();
4097
+ }
4098
+ }
4099
+ async function compressBuffer(buffer, algorithm = "gzip") {
4100
+ switch (algorithm) {
4101
+ case "brotli":
4102
+ return await brotliCompressAsync(buffer);
4103
+ case "deflate":
4104
+ return await (0, import_node_util.promisify)(import_node_zlib.default.deflate)(buffer);
4105
+ case "gzip":
4106
+ default:
4107
+ return await gzipAsync(buffer);
4108
+ }
4109
+ }
4110
+ async function decompressBuffer(buffer, algorithm = "gzip") {
4111
+ switch (algorithm) {
4112
+ case "brotli":
4113
+ return await brotliDecompressAsync(buffer);
4114
+ case "deflate":
4115
+ return await (0, import_node_util.promisify)(import_node_zlib.default.inflate)(buffer);
4116
+ case "gzip":
4117
+ default:
4118
+ return await gunzipAsync(buffer);
4119
+ }
4120
+ }
4121
+ function isGzipBuffer(buffer) {
4122
+ return buffer.length >= 2 && buffer[0] === 31 && buffer[1] === 139;
4123
+ }
4124
+
4125
+ // src/core/client.ts
4126
+ var DriveKit = class _DriveKit {
4127
+ options;
4128
+ authenticator;
4129
+ driveClient = null;
4130
+ pathResolverInstance = null;
4131
+ uploaderInstance = null;
4132
+ downloaderInstance = null;
4133
+ metadataCacheInstance = null;
4134
+ cryptoInstance = null;
4135
+ rootFolderId;
4136
+ pluginManager = new PluginManager();
4137
+ constructor(options = {}) {
4138
+ this.options = options;
4139
+ this.rootFolderId = options.rootFolderId || "root";
4140
+ this.authenticator = new DriveAuthenticator(options.auth);
4141
+ if (options.encryption) {
4142
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4143
+ }
4144
+ }
4145
+ /**
4146
+ * Access the client-side AES-256-GCM encryption engine
4147
+ */
4148
+ get crypto() {
4149
+ if (!this.cryptoInstance) {
4150
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4151
+ }
4152
+ return this.cryptoInstance;
4153
+ }
4154
+ /**
4155
+ * Access historical revisions & version control for a file
4156
+ */
4157
+ getRevisions(fileIdOrPath) {
4158
+ if (!this.driveClient) {
4159
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4160
+ }
4161
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
4162
+ }
4163
+ /**
4164
+ * Registers a middleware plugin into DriveKit lifecycle
4165
+ */
4166
+ use(plugin) {
4167
+ this.pluginManager.use(plugin);
4168
+ return this;
4169
+ }
4170
+ /**
4171
+ * Unregisters a middleware plugin by name
4172
+ */
4173
+ unuse(pluginName) {
4174
+ return this.pluginManager.unuse(pluginName);
4175
+ }
4176
+ /**
4177
+ * Access the underlying plugin manager instance
4178
+ */
4179
+ get plugins() {
4180
+ return this.pluginManager;
4181
+ }
4182
+ /**
4183
+ * Returns a fluent, chained reference to a specific file
4184
+ */
4185
+ file(pathOrId) {
4186
+ return new DriveFileRef(this, pathOrId);
4187
+ }
4188
+ /**
4189
+ * Returns a fluent, chained reference to a specific folder
4190
+ */
4191
+ folder(pathOrId) {
4192
+ return new DriveFolderRef(this, pathOrId);
4193
+ }
4194
+ /**
4195
+ * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
4196
+ */
4197
+ async init() {
4198
+ if (!this.driveClient) {
4199
+ const auth = await this.authenticator.getAuthClient();
4200
+ const agent = getOptimizedHttpsAgent();
4201
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth, agent });
4202
+ if (this.options.enablePersistentCache !== false) {
4203
+ this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
4204
+ this.metadataCacheInstance.init();
4205
+ }
4206
+ this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
4207
+ enableCache: this.options.enablePathCache ?? true,
4208
+ cacheTTL: this.options.pathCacheTTL,
4209
+ metadataCache: this.metadataCacheInstance || void 0
4210
+ });
4211
+ this.uploaderInstance = new ResumableUploader(
4212
+ this.driveClient,
4213
+ this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
4214
+ );
4215
+ this.downloaderInstance = new Downloader(this.driveClient);
4216
+ }
4217
+ return this;
4218
+ }
4219
+ /**
4220
+ * Access the underlying official `@googleapis/drive` instance for raw API calls
4221
+ */
4222
+ async getRawClient() {
4223
+ await this.init();
4224
+ return this.driveClient;
4225
+ }
4226
+ async getResolver() {
4227
+ await this.init();
4228
+ return this.pathResolverInstance;
4229
+ }
4230
+ async getUploader() {
4231
+ await this.init();
4232
+ return this.uploaderInstance;
4233
+ }
4234
+ async getDownloader() {
4235
+ await this.init();
4236
+ return this.downloaderInstance;
4237
+ }
4238
+ /**
4239
+ * Resolves a target string that could be either an ID or a virtual path (starting with '/')
4240
+ */
4241
+ async resolveId(idOrPath, autoCreateDir = false) {
4242
+ if (idOrPath.startsWith("/")) {
4243
+ const resolver = await this.getResolver();
4244
+ const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });
4245
+ return res.id;
4246
+ }
4247
+ return idOrPath;
4248
+ }
4249
+ // ==========================================
4250
+ // DIRECTORY & PATH OPERATIONS
4251
+ // ==========================================
4252
+ /**
4253
+ * Creates a folder structure recursively, similar to `mkdir -p`.
4254
+ * @param virtualPath Path like "/Documents/Projects/2026"
4255
+ * @returns Folder ID of the created or existing directory
4256
+ */
4257
+ async mkdirp(virtualPath) {
4258
+ const resolver = await this.getResolver();
4259
+ return await resolver.mkdirp(virtualPath);
4260
+ }
4261
+ /**
4262
+ * Resolves a virtual path to its Drive metadata
4263
+ */
4264
+ async resolvePath(virtualPath) {
4265
+ const resolver = await this.getResolver();
4266
+ return await resolver.resolve(virtualPath);
4267
+ }
4268
+ /**
4269
+ * Check if a file or folder exists (by ID or virtual path)
4270
+ */
4271
+ async exists(idOrPath) {
4272
+ try {
4273
+ if (idOrPath.startsWith("/")) {
4274
+ await this.resolvePath(idOrPath);
4275
+ return true;
2850
4276
  }
2851
4277
  const raw = await this.getRawClient();
2852
4278
  await raw.files.get({ fileId: idOrPath, fields: "id, trashed" });
@@ -2859,15 +4285,41 @@ var DriveKit = class _DriveKit {
2859
4285
  }
2860
4286
  }
2861
4287
  /**
2862
- * Lists contents of a folder (by folder ID or path)
4288
+ * Lists contents of a folder (by folder ID or path) with opportunistic tree caching
2863
4289
  */
2864
4290
  async ls(folderIdOrPath = "/") {
4291
+ let parentFolderId;
4292
+ let normalizedPath = null;
4293
+ let files;
2865
4294
  if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
4295
+ parentFolderId = this.rootFolderId;
4296
+ normalizedPath = "/";
2866
4297
  const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2867
- return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
4298
+ files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
4299
+ } else {
4300
+ if (folderIdOrPath.startsWith("/")) {
4301
+ normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
4302
+ parentFolderId = await this.resolveId(normalizedPath);
4303
+ } else {
4304
+ parentFolderId = folderIdOrPath;
4305
+ }
4306
+ files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
4307
+ }
4308
+ if (this.metadataCacheInstance && files.length > 0) {
4309
+ const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
4310
+ id: f.id,
4311
+ name: f.name || "untitled",
4312
+ mimeType: f.mimeType || "",
4313
+ size: f.size ? parseInt(f.size, 10) : void 0,
4314
+ parentId: parentFolderId,
4315
+ path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
4316
+ md5Checksum: f.md5Checksum || void 0,
4317
+ modifiedTime: f.modifiedTime || void 0,
4318
+ trashed: false
4319
+ }));
4320
+ this.metadataCacheInstance.upsertFiles(cacheEntries);
2868
4321
  }
2869
- const folderId = await this.resolveId(folderIdOrPath);
2870
- return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
4322
+ return files;
2871
4323
  }
2872
4324
  // ==========================================
2873
4325
  // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
@@ -2886,68 +4338,101 @@ var DriveKit = class _DriveKit {
2886
4338
  if (parentId && parentId.startsWith("/")) {
2887
4339
  parentId = await this.mkdirp(parentId);
2888
4340
  }
2889
- const targetName = opts.name || opts.filename;
2890
- if (opts.overwrite && targetName && parentId) {
4341
+ let uploadOpts = { ...opts };
4342
+ if (uploadOpts.compress) {
4343
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4344
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4345
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4346
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4347
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4348
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4349
+ }
4350
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4351
+ }
4352
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4353
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "encrypted.bin");
4354
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4355
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4356
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4357
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4358
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4359
+ }
4360
+ if (this.options.encryption?.encryptFilenames) {
4361
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4362
+ }
4363
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4364
+ }
4365
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : void 0);
4366
+ if (uploadOpts.overwrite && targetName && parentId) {
2891
4367
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
2892
4368
  if (existing?.id) {
2893
4369
  await this.delete(existing.id, true);
2894
4370
  }
2895
4371
  }
2896
- if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
2897
- const localMd5 = await calculateFileMd5(opts.source);
2898
- let existingId;
2899
- if (this.metadataCacheInstance) {
2900
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
2901
- if (cached) existingId = cached.id;
2902
- }
2903
- if (!existingId) {
2904
- const found = await this.query().md5(localMd5).notTrashed().first();
2905
- if (found?.id) {
2906
- existingId = found.id;
2907
- }
2908
- }
2909
- if (existingId) {
2910
- const fileName = targetName || import_node_path7.default.basename(opts.source);
2911
- const raw = await this.getRawClient();
2912
- const copyRes = await withRetry(async () => {
2913
- return await raw.files.copy({
2914
- fileId: existingId,
2915
- requestBody: {
2916
- name: fileName,
2917
- parents: parentId ? [parentId] : void 0,
2918
- description: opts.description
2919
- },
2920
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
2921
- supportsAllDrives: true
2922
- });
2923
- });
2924
- const file = copyRes.data;
2925
- if (this.metadataCacheInstance && file.id) {
2926
- this.metadataCacheInstance.upsertFile({
2927
- id: file.id,
2928
- name: file.name || fileName,
2929
- mimeType: file.mimeType || "",
2930
- size: file.size ? parseInt(file.size, 10) : void 0,
2931
- parentId,
2932
- md5Checksum: localMd5,
2933
- trashed: false
4372
+ if (uploadOpts.deduplicate) {
4373
+ let localMd5;
4374
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4375
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4376
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4377
+ localMd5 = import_node_crypto3.default.createHash("md5").update(uploadOpts.source).digest("hex");
4378
+ }
4379
+ if (localMd5) {
4380
+ let existingId;
4381
+ if (this.metadataCacheInstance) {
4382
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4383
+ if (cached) existingId = cached.id;
4384
+ }
4385
+ if (!existingId) {
4386
+ const found = await this.query().md5(localMd5).notTrashed().first();
4387
+ if (found?.id) {
4388
+ existingId = found.id;
4389
+ }
4390
+ }
4391
+ if (existingId) {
4392
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "file.bin");
4393
+ const raw = await this.getRawClient();
4394
+ const copyRes = await withRetry(async () => {
4395
+ return await raw.files.copy({
4396
+ fileId: existingId,
4397
+ requestBody: {
4398
+ name: fileName,
4399
+ parents: parentId ? [parentId] : void 0,
4400
+ description: uploadOpts.description
4401
+ },
4402
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4403
+ supportsAllDrives: true
4404
+ });
2934
4405
  });
4406
+ const file = copyRes.data;
4407
+ if (this.metadataCacheInstance && file.id) {
4408
+ this.metadataCacheInstance.upsertFile({
4409
+ id: file.id,
4410
+ name: file.name || fileName,
4411
+ mimeType: file.mimeType || "",
4412
+ size: file.size ? parseInt(file.size, 10) : void 0,
4413
+ parentId,
4414
+ md5Checksum: localMd5,
4415
+ trashed: false
4416
+ });
4417
+ }
4418
+ return await this.pluginManager.runAfterUpload(file);
2935
4419
  }
2936
- return await this.pluginManager.runAfterUpload(file);
2937
4420
  }
2938
4421
  }
2939
4422
  const uploaded = await uploader.upload({
2940
- ...opts,
4423
+ ...uploadOpts,
2941
4424
  name: targetName,
2942
4425
  parent: parentId
2943
4426
  });
2944
4427
  if (this.metadataCacheInstance && uploaded.id) {
4428
+ const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
2945
4429
  this.metadataCacheInstance.upsertFile({
2946
4430
  id: uploaded.id,
2947
4431
  name: uploaded.name || targetName || "untitled",
2948
4432
  mimeType: uploaded.mimeType || "",
2949
4433
  size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
2950
4434
  parentId,
4435
+ path: virtualPath,
2951
4436
  trashed: false
2952
4437
  });
2953
4438
  }
@@ -2958,16 +4443,35 @@ var DriveKit = class _DriveKit {
2958
4443
  * - Automatic conversion for Google Docs, Sheets, and Slides
2959
4444
  * - Progress events
2960
4445
  * - Saves directly to file or returns Readable Stream
4446
+ * - Leverages local metadata cache to bypass redundant Google API roundtrips
2961
4447
  */
2962
4448
  async download(fileIdOrPath, options = {}) {
2963
4449
  const fileId = await this.resolveId(fileIdOrPath);
2964
- const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
4450
+ let cachedMeta = options.metadata;
4451
+ if (!cachedMeta && this.metadataCacheInstance) {
4452
+ const cached = this.metadataCacheInstance.getById(fileId);
4453
+ if (cached && cached.name && cached.mimeType) {
4454
+ cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
4455
+ }
4456
+ }
4457
+ const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
4458
+ const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
2965
4459
  const downloader = await this.getDownloader();
2966
4460
  const result = await downloader.download(fileId, processedOpts);
4461
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4462
+ const encrypted = await import_node_fs7.default.promises.readFile(result.filePath);
4463
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4464
+ await import_node_fs7.default.promises.writeFile(result.filePath, decrypted);
4465
+ }
4466
+ if (processedOpts.decompress && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4467
+ const comp = await import_node_fs7.default.promises.readFile(result.filePath);
4468
+ const decomp = await decompressBuffer(comp);
4469
+ await import_node_fs7.default.promises.writeFile(result.filePath, decomp);
4470
+ }
2967
4471
  return await this.pluginManager.runAfterDownload(result);
2968
4472
  }
2969
4473
  /**
2970
- * Gets file metadata
4474
+ * Gets file metadata and updates the local metadata cache
2971
4475
  */
2972
4476
  async getFile(fileIdOrPath) {
2973
4477
  const fileId = await this.resolveId(fileIdOrPath);
@@ -2979,7 +4483,20 @@ var DriveKit = class _DriveKit {
2979
4483
  supportsAllDrives: true
2980
4484
  });
2981
4485
  });
2982
- return res.data;
4486
+ const file = res.data;
4487
+ if (this.metadataCacheInstance && file.id) {
4488
+ this.metadataCacheInstance.upsertFile({
4489
+ id: file.id,
4490
+ name: file.name || "",
4491
+ mimeType: file.mimeType || "",
4492
+ size: file.size ? parseInt(file.size, 10) : void 0,
4493
+ parentId: file.parents?.[0],
4494
+ path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
4495
+ modifiedTime: file.modifiedTime || void 0,
4496
+ trashed: file.trashed || false
4497
+ });
4498
+ }
4499
+ return file;
2983
4500
  }
2984
4501
  /**
2985
4502
  * Reads file content as UTF-8 string
@@ -3022,6 +4539,9 @@ var DriveKit = class _DriveKit {
3022
4539
  if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
3023
4540
  this.pathResolverInstance.invalidatePath(fileIdOrPath);
3024
4541
  }
4542
+ if (this.metadataCacheInstance) {
4543
+ this.metadataCacheInstance.deleteFile(fileId);
4544
+ }
3025
4545
  }
3026
4546
  /**
3027
4547
  * Move item to trash
@@ -3063,6 +4583,16 @@ var DriveKit = class _DriveKit {
3063
4583
  if (this.pathResolverInstance) {
3064
4584
  this.pathResolverInstance.clearCache();
3065
4585
  }
4586
+ if (this.metadataCacheInstance) {
4587
+ const cached = this.metadataCacheInstance.getById(fileId);
4588
+ if (cached) {
4589
+ this.metadataCacheInstance.upsertFile({
4590
+ ...cached,
4591
+ parentId: newParentId,
4592
+ path: void 0
4593
+ });
4594
+ }
4595
+ }
3066
4596
  return res.data;
3067
4597
  }
3068
4598
  /**
@@ -3071,10 +4601,7 @@ var DriveKit = class _DriveKit {
3071
4601
  async copy(fileIdOrPath, options = {}) {
3072
4602
  const fileId = await this.resolveId(fileIdOrPath);
3073
4603
  const raw = await this.getRawClient();
3074
- let parentId = options.parent;
3075
- if (parentId && parentId.startsWith("/")) {
3076
- parentId = await this.mkdirp(parentId);
3077
- }
4604
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3078
4605
  const requestBody = {};
3079
4606
  if (options.name) requestBody.name = options.name;
3080
4607
  if (parentId) requestBody.parents = [parentId];
@@ -3105,6 +4632,16 @@ var DriveKit = class _DriveKit {
3105
4632
  if (this.pathResolverInstance) {
3106
4633
  this.pathResolverInstance.clearCache();
3107
4634
  }
4635
+ if (this.metadataCacheInstance) {
4636
+ const cached = this.metadataCacheInstance.getById(fileId);
4637
+ if (cached) {
4638
+ this.metadataCacheInstance.upsertFile({
4639
+ ...cached,
4640
+ name: newName,
4641
+ path: void 0
4642
+ });
4643
+ }
4644
+ }
3108
4645
  return res.data;
3109
4646
  }
3110
4647
  // ==========================================
@@ -3191,16 +4728,16 @@ var DriveKit = class _DriveKit {
3191
4728
  durationMs: 0
3192
4729
  };
3193
4730
  const collectFiles = async (dir, base) => {
3194
- const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
4731
+ const entries = await import_node_fs7.default.promises.readdir(dir, { withFileTypes: true });
3195
4732
  const files = [];
3196
4733
  for (const entry of entries) {
3197
- const fullPath = import_node_path7.default.join(dir, entry.name);
3198
- const relPath = import_node_path7.default.join(base, entry.name);
4734
+ const fullPath = import_node_path9.default.join(dir, entry.name);
4735
+ const relPath = import_node_path9.default.join(base, entry.name);
3199
4736
  if (entry.isDirectory()) {
3200
4737
  const sub = await collectFiles(fullPath, relPath);
3201
4738
  files.push(...sub);
3202
4739
  } else if (entry.isFile()) {
3203
- const stat = await import_node_fs6.default.promises.stat(fullPath);
4740
+ const stat = await import_node_fs7.default.promises.stat(fullPath);
3204
4741
  files.push({ fullPath, relPath, size: stat.size });
3205
4742
  }
3206
4743
  }
@@ -3213,11 +4750,11 @@ var DriveKit = class _DriveKit {
3213
4750
  if (remoteDirCache.has(relDir)) {
3214
4751
  return remoteDirCache.get(relDir);
3215
4752
  }
3216
- const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
4753
+ const parts = relDir.split(import_node_path9.default.sep).filter(Boolean);
3217
4754
  let currentParent = targetFolderId;
3218
4755
  let currentRel = "";
3219
4756
  for (const part of parts) {
3220
- currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
4757
+ currentRel = currentRel ? import_node_path9.default.join(currentRel, part) : part;
3221
4758
  if (remoteDirCache.has(currentRel)) {
3222
4759
  currentParent = remoteDirCache.get(currentRel);
3223
4760
  continue;
@@ -3246,8 +4783,8 @@ var DriveKit = class _DriveKit {
3246
4783
  };
3247
4784
  await pool.map(allFiles, async (fileItem) => {
3248
4785
  try {
3249
- const relDir = import_node_path7.default.dirname(fileItem.relPath);
3250
- const fileName = import_node_path7.default.basename(fileItem.relPath);
4786
+ const relDir = import_node_path9.default.dirname(fileItem.relPath);
4787
+ const fileName = import_node_path9.default.basename(fileItem.relPath);
3251
4788
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3252
4789
  if (options.onFileStart) {
3253
4790
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3382,7 +4919,7 @@ var DriveKit = class _DriveKit {
3382
4919
  async createWriteStream(remotePath, options = {}) {
3383
4920
  await this.init();
3384
4921
  const { PassThrough } = await import("stream");
3385
- const passThrough = new PassThrough();
4922
+ const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
3386
4923
  let resolveDone;
3387
4924
  let rejectDone;
3388
4925
  const donePromise = new Promise((resolve, reject) => {
@@ -3390,8 +4927,8 @@ var DriveKit = class _DriveKit {
3390
4927
  rejectDone = reject;
3391
4928
  });
3392
4929
  passThrough.done = donePromise;
3393
- const remoteDir = import_node_path7.default.dirname(remotePath);
3394
- const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
4930
+ const remoteDir = import_node_path9.default.dirname(remotePath);
4931
+ const fileName = options.name || options.filename || import_node_path9.default.basename(remotePath);
3395
4932
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3396
4933
  const mimeType = options.mimeType || "application/octet-stream";
3397
4934
  const raw = this.driveClient;
@@ -3429,6 +4966,12 @@ var DriveKit = class _DriveKit {
3429
4966
  // ==========================================
3430
4967
  // METADATA CACHE OPERATIONS
3431
4968
  // ==========================================
4969
+ /**
4970
+ * Synchronous getter for the active metadata cache instance
4971
+ */
4972
+ get cache() {
4973
+ return this.metadataCacheInstance;
4974
+ }
3432
4975
  /**
3433
4976
  * Returns the active persistent metadata cache instance (SQLite/Memory)
3434
4977
  */
@@ -3451,6 +4994,9 @@ var DriveKit = class _DriveKit {
3451
4994
  if (this.pathResolverInstance) {
3452
4995
  this.pathResolverInstance.clearCache();
3453
4996
  }
4997
+ if (this.metadataCacheInstance) {
4998
+ this.metadataCacheInstance.clear();
4999
+ }
3454
5000
  }
3455
5001
  /**
3456
5002
  * Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
@@ -3615,6 +5161,47 @@ var DriveKit = class _DriveKit {
3615
5161
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3616
5162
  return await startWebDAVServer2(this, options);
3617
5163
  }
5164
+ /**
5165
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5166
+ */
5167
+ async syncBiDirectional(options) {
5168
+ await this.init();
5169
+ const engine = new BidirectionalSyncEngine(this);
5170
+ return await engine.sync(options);
5171
+ }
5172
+ /**
5173
+ * Starts an embedded S3-compatible HTTP gateway server
5174
+ */
5175
+ async serveS3(options = {}) {
5176
+ await this.init();
5177
+ const gateway = new S3GatewayServer(this, options);
5178
+ await gateway.start();
5179
+ return gateway;
5180
+ }
5181
+ /**
5182
+ * Scans Google Drive files and generates a security & permission audit report
5183
+ */
5184
+ async auditPermissions(options = {}) {
5185
+ await this.init();
5186
+ const auditor = new SecurityAuditor(this.driveClient);
5187
+ return await auditor.audit(options);
5188
+ }
5189
+ /**
5190
+ * Revokes public 'anyone' link permissions from the given files
5191
+ */
5192
+ async revokePublicPermissions(fileIds) {
5193
+ await this.init();
5194
+ const auditor = new SecurityAuditor(this.driveClient);
5195
+ return await auditor.revokePublicAccess(fileIds);
5196
+ }
5197
+ /**
5198
+ * Multi-word fuzzy and semantic search across files
5199
+ */
5200
+ async searchSmart(query, options = {}) {
5201
+ await this.init();
5202
+ const engine = new SmartSearchEngine(this);
5203
+ return await engine.search(query, options);
5204
+ }
3618
5205
  /**
3619
5206
  * Calculates local file MD5 hash for integrity and deduplication checks
3620
5207
  */
@@ -3788,6 +5375,90 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
3788
5375
  });
3789
5376
  }
3790
5377
 
5378
+ // src/integrations/middleware.ts
5379
+ init_cjs_shims();
5380
+ var import_node_path10 = __toESM(require("path"), 1);
5381
+ var import_busboy = __toESM(require("busboy"), 1);
5382
+ function createDriveUploadMiddleware(drive2, options = {}) {
5383
+ const targetDir = options.destination || "/Uploads";
5384
+ return async (req, res, next) => {
5385
+ const contentType = req.headers["content-type"] || "";
5386
+ if (!contentType.includes("multipart/form-data")) {
5387
+ return next();
5388
+ }
5389
+ req.drivekitFiles = [];
5390
+ req.drivekitFields = {};
5391
+ const uploadPromises = [];
5392
+ try {
5393
+ const bb = (0, import_busboy.default)({
5394
+ headers: req.headers,
5395
+ limits: {
5396
+ fileSize: options.maxFileSize
5397
+ }
5398
+ });
5399
+ bb.on("file", (name, fileStream, info) => {
5400
+ const { filename, mimeType } = info;
5401
+ const rawName = filename || "upload.bin";
5402
+ const sanitizedName = import_node_path10.default.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5403
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, mimeType) : sanitizedName;
5404
+ const finalName = import_node_path10.default.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5405
+ const remotePath = `${targetDir === "/" ? "" : targetDir}/${finalName}`;
5406
+ const uploadTask = (async () => {
5407
+ const driveStream = await drive2.createWriteStream(remotePath, {
5408
+ mimeType
5409
+ });
5410
+ fileStream.pipe(driveStream);
5411
+ const uploadedFile = await driveStream.done;
5412
+ req.drivekitFiles?.push(uploadedFile);
5413
+ return uploadedFile;
5414
+ })();
5415
+ uploadPromises.push(uploadTask);
5416
+ });
5417
+ bb.on("field", (name, val) => {
5418
+ if (req.drivekitFields) {
5419
+ req.drivekitFields[name] = val;
5420
+ }
5421
+ });
5422
+ bb.on("close", async () => {
5423
+ try {
5424
+ await Promise.all(uploadPromises);
5425
+ next();
5426
+ } catch (err) {
5427
+ next(err);
5428
+ }
5429
+ });
5430
+ bb.on("error", (err) => {
5431
+ next(err);
5432
+ });
5433
+ req.pipe(bb);
5434
+ } catch (err) {
5435
+ next(err);
5436
+ }
5437
+ };
5438
+ }
5439
+ async function handleNextJsUpload(formData, drive2, options = {}) {
5440
+ const targetDir = options.destination || "/Uploads";
5441
+ const results = [];
5442
+ for (const [key, value] of formData.entries()) {
5443
+ if (value && typeof value === "object" && "arrayBuffer" in value) {
5444
+ const file = value;
5445
+ const buffer = Buffer.from(await file.arrayBuffer());
5446
+ const rawName = file.name || "upload.bin";
5447
+ const sanitizedName = import_node_path10.default.basename(rawName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5448
+ const rawFinalName = options.filenameGenerator ? options.filenameGenerator(sanitizedName, file.type) : sanitizedName;
5449
+ const finalName = import_node_path10.default.basename(rawFinalName.replace(/\\/g, "/")).replace(/\0/g, "") || "upload.bin";
5450
+ const uploaded = await drive2.upload({
5451
+ source: buffer,
5452
+ name: finalName,
5453
+ parent: targetDir,
5454
+ mimeType: file.type || "application/octet-stream"
5455
+ });
5456
+ results.push(uploaded);
5457
+ }
5458
+ }
5459
+ return results;
5460
+ }
5461
+
3791
5462
  // src/index.ts
3792
5463
  async function createDrive(options) {
3793
5464
  const instance = new DriveKit(options);
@@ -3797,6 +5468,7 @@ async function createDrive(options) {
3797
5468
  var index_default = DriveKit;
3798
5469
  // Annotate the CommonJS export names for ESM import in node:
3799
5470
  0 && (module.exports = {
5471
+ BidirectionalSyncEngine,
3800
5472
  ConcurrencyPool,
3801
5473
  DEFAULT_CHUNK_SIZE,
3802
5474
  DEFAULT_EXPORT_MIMES,
@@ -3805,8 +5477,10 @@ var index_default = DriveKit;
3805
5477
  DriveAuthError,
3806
5478
  DriveAuthenticator,
3807
5479
  DriveFileRef,
5480
+ DriveFileRevisions,
3808
5481
  DriveFolderRef,
3809
5482
  DriveKit,
5483
+ DriveKitCrypto,
3810
5484
  DriveKitError,
3811
5485
  DriveNotFoundError,
3812
5486
  DriveQueryBuilder,
@@ -3814,26 +5488,46 @@ var index_default = DriveKit;
3814
5488
  DriveUploadError,
3815
5489
  DriveWatcher,
3816
5490
  GOOGLE_WORKSPACE_MIME_TYPES,
5491
+ IV_LENGTH,
5492
+ MAGIC_HEADER,
5493
+ MAGIC_STREAM_HEADER,
3817
5494
  MIN_CHUNK_SIZE,
3818
5495
  MULTIPART_THRESHOLD,
3819
5496
  MemoryMetadataCache,
5497
+ PBKDF2_ROUNDS,
3820
5498
  PathResolver,
3821
5499
  PluginManager,
3822
5500
  ResumableUploader,
5501
+ S3GatewayServer,
5502
+ SALT_LENGTH,
5503
+ SecurityAuditor,
5504
+ SmartSearchEngine,
3823
5505
  SmartSyncEngine,
3824
5506
  SqliteMetadataCache,
3825
5507
  StorageCleaner,
5508
+ TAG_LENGTH,
3826
5509
  calculateFileMd5,
5510
+ compressBuffer,
5511
+ cosineSimilarity,
3827
5512
  createAutoNamePlugin,
5513
+ createCompressStream,
5514
+ createDecompressStream,
3828
5515
  createDrive,
5516
+ createDriveUploadMiddleware,
3829
5517
  createWebhookPlugin,
5518
+ decompressBuffer,
5519
+ deriveKey,
3830
5520
  escapeXml,
3831
5521
  formatBytes,
3832
5522
  formatDuration,
3833
5523
  formatSpeed,
3834
5524
  getExtensionForMime,
3835
5525
  getFileIcon,
5526
+ getOptimizedHttpAgent,
5527
+ getOptimizedHttpsAgent,
5528
+ handleNextJsUpload,
3836
5529
  isGoogleWorkspaceDoc,
5530
+ isGzipBuffer,
3837
5531
  isRetryableError,
3838
5532
  loginWithBrowser,
3839
5533
  lookupMimeType,