drivekit 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,2153 @@
1
+ // src/core/client.ts
2
+ import fs5 from "fs";
3
+ import path4 from "path";
4
+ import { drive } from "@googleapis/drive";
5
+
6
+ // src/auth/authenticator.ts
7
+ import fs from "fs";
8
+ import { auth as googleAuth } from "@googleapis/drive";
9
+
10
+ // src/errors.ts
11
+ var DriveKitError = class extends Error {
12
+ code;
13
+ originalError;
14
+ constructor(message, code = "DRIVEKIT_ERROR", originalError) {
15
+ super(message);
16
+ this.name = "DriveKitError";
17
+ this.code = code;
18
+ this.originalError = originalError;
19
+ Object.setPrototypeOf(this, new.target.prototype);
20
+ }
21
+ };
22
+ var DriveAuthError = class extends DriveKitError {
23
+ constructor(message, originalError) {
24
+ super(message, "AUTH_ERROR", originalError);
25
+ this.name = "DriveAuthError";
26
+ }
27
+ };
28
+ var DriveNotFoundError = class extends DriveKitError {
29
+ resourceIdOrPath;
30
+ constructor(resourceIdOrPath, message) {
31
+ super(message || `Resource not found: "${resourceIdOrPath}"`, "NOT_FOUND");
32
+ this.name = "DriveNotFoundError";
33
+ this.resourceIdOrPath = resourceIdOrPath;
34
+ }
35
+ };
36
+ var DriveRateLimitError = class extends DriveKitError {
37
+ retryAfterSeconds;
38
+ constructor(message, retryAfterSeconds, originalError) {
39
+ super(message, "RATE_LIMIT_EXCEEDED", originalError);
40
+ this.name = "DriveRateLimitError";
41
+ this.retryAfterSeconds = retryAfterSeconds;
42
+ }
43
+ };
44
+ var DriveUploadError = class extends DriveKitError {
45
+ bytesUploaded;
46
+ totalBytes;
47
+ constructor(message, bytesUploaded, totalBytes, originalError) {
48
+ super(message, "UPLOAD_ERROR", originalError);
49
+ this.name = "DriveUploadError";
50
+ this.bytesUploaded = bytesUploaded;
51
+ this.totalBytes = totalBytes;
52
+ }
53
+ };
54
+
55
+ // src/auth/authenticator.ts
56
+ var DEFAULT_SCOPES = [
57
+ "https://www.googleapis.com/auth/drive"
58
+ ];
59
+ var DriveAuthenticator = class {
60
+ config;
61
+ authClient = null;
62
+ constructor(config = {}) {
63
+ this.config = config;
64
+ }
65
+ /**
66
+ * Initializes and returns an authenticated Google client
67
+ */
68
+ async getAuthClient() {
69
+ if (this.authClient) {
70
+ return this.authClient;
71
+ }
72
+ try {
73
+ const scopes = this.config.scopes || DEFAULT_SCOPES;
74
+ if (this.config.accessToken) {
75
+ const oauth2Client = new googleAuth.OAuth2();
76
+ oauth2Client.setCredentials({ access_token: this.config.accessToken });
77
+ this.authClient = oauth2Client;
78
+ return this.authClient;
79
+ }
80
+ if (this.config.oauth2Client) {
81
+ this.authClient = this.config.oauth2Client;
82
+ return this.authClient;
83
+ }
84
+ if (this.config.oauth) {
85
+ const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
86
+ const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
87
+ if (refreshToken) {
88
+ oauth2Client.setCredentials({ refresh_token: refreshToken });
89
+ }
90
+ this.authClient = oauth2Client;
91
+ return this.authClient;
92
+ }
93
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
94
+ if (keyFile) {
95
+ if (!fs.existsSync(keyFile)) {
96
+ throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
97
+ }
98
+ const auth2 = new googleAuth.GoogleAuth({
99
+ keyFile,
100
+ scopes
101
+ });
102
+ this.authClient = auth2;
103
+ return this.authClient;
104
+ }
105
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
106
+ if (creds) {
107
+ const auth2 = new googleAuth.GoogleAuth({
108
+ credentials: creds,
109
+ scopes
110
+ });
111
+ this.authClient = auth2;
112
+ return this.authClient;
113
+ }
114
+ const auth = new googleAuth.GoogleAuth({ scopes });
115
+ this.authClient = auth;
116
+ return this.authClient;
117
+ } catch (err) {
118
+ if (err instanceof DriveAuthError) throw err;
119
+ throw new DriveAuthError(`Failed to authenticate with Google Drive: ${err.message}`, err);
120
+ }
121
+ }
122
+ /**
123
+ * Helper to generate OAuth2 Consent URL for user authorization
124
+ */
125
+ static generateAuthUrl(options) {
126
+ const oauth2Client = new googleAuth.OAuth2(
127
+ options.clientId,
128
+ options.clientSecret,
129
+ options.redirectUri || "urn:ietf:wg:oauth:2.0:oob"
130
+ );
131
+ return oauth2Client.generateAuthUrl({
132
+ access_type: "offline",
133
+ prompt: "consent",
134
+ scope: options.scopes || DEFAULT_SCOPES
135
+ });
136
+ }
137
+ /**
138
+ * Helper to exchange authorization code for tokens
139
+ */
140
+ static async exchangeCodeForTokens(options) {
141
+ const oauth2Client = new googleAuth.OAuth2(
142
+ options.clientId,
143
+ options.clientSecret,
144
+ options.redirectUri || "urn:ietf:wg:oauth:2.0:oob"
145
+ );
146
+ const { tokens } = await oauth2Client.getToken(options.code);
147
+ return tokens;
148
+ }
149
+ };
150
+
151
+ // src/utils/mime.ts
152
+ import mime from "mime-types";
153
+ var GOOGLE_WORKSPACE_MIME_TYPES = {
154
+ DOCUMENT: "application/vnd.google-apps.document",
155
+ SPREADSHEET: "application/vnd.google-apps.spreadsheet",
156
+ PRESENTATION: "application/vnd.google-apps.presentation",
157
+ DRAWING: "application/vnd.google-apps.drawing",
158
+ FORM: "application/vnd.google-apps.form",
159
+ SCRIPT: "application/vnd.google-apps.script",
160
+ FOLDER: "application/vnd.google-apps.folder",
161
+ SHORTCUT: "application/vnd.google-apps.shortcut"
162
+ };
163
+ var DEFAULT_EXPORT_MIMES = {
164
+ [GOOGLE_WORKSPACE_MIME_TYPES.DOCUMENT]: {
165
+ mimeType: "application/pdf",
166
+ extension: ".pdf"
167
+ },
168
+ [GOOGLE_WORKSPACE_MIME_TYPES.SPREADSHEET]: {
169
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
170
+ extension: ".xlsx"
171
+ },
172
+ [GOOGLE_WORKSPACE_MIME_TYPES.PRESENTATION]: {
173
+ mimeType: "application/pdf",
174
+ extension: ".pdf"
175
+ },
176
+ [GOOGLE_WORKSPACE_MIME_TYPES.DRAWING]: {
177
+ mimeType: "image/png",
178
+ extension: ".png"
179
+ }
180
+ };
181
+ function lookupMimeType(filePath) {
182
+ const detected = mime.lookup(filePath);
183
+ return detected || "application/octet-stream";
184
+ }
185
+ function getExtensionForMime(mimeType) {
186
+ const ext = mime.extension(mimeType);
187
+ return ext ? `.${ext}` : "";
188
+ }
189
+ function isGoogleWorkspaceDoc(mimeType) {
190
+ if (!mimeType) return false;
191
+ return mimeType.startsWith("application/vnd.google-apps.") && mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.FOLDER && mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.SHORTCUT;
192
+ }
193
+
194
+ // src/utils/retry.ts
195
+ var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
196
+ function isRetryableError(error) {
197
+ if (!error) return false;
198
+ const status = error.status || error.statusCode || error.response?.status;
199
+ if (status && DEFAULT_RETRYABLE_STATUSES.has(status)) {
200
+ return true;
201
+ }
202
+ const message = (error.message || "").toLowerCase();
203
+ if (message.includes("rate limit") || message.includes("quota") || message.includes("userate") || message.includes("backend error") || message.includes("socket hang up") || message.includes("econnreset") || message.includes("etimedout")) {
204
+ return true;
205
+ }
206
+ const errors = error.errors || error.response?.data?.error?.errors;
207
+ if (Array.isArray(errors)) {
208
+ for (const e of errors) {
209
+ if (e.reason === "rateLimitExceeded" || e.reason === "userRateLimitExceeded" || e.reason === "backendError") {
210
+ return true;
211
+ }
212
+ }
213
+ }
214
+ return false;
215
+ }
216
+ async function withRetry(fn, options = {}) {
217
+ const maxRetries = options.maxRetries ?? 5;
218
+ const baseDelayMs = options.baseDelayMs ?? 1e3;
219
+ const maxDelayMs = options.maxDelayMs ?? 32e3;
220
+ const shouldRetry = options.shouldRetry ?? isRetryableError;
221
+ let attempt = 0;
222
+ while (true) {
223
+ try {
224
+ return await fn();
225
+ } catch (error) {
226
+ attempt++;
227
+ if (attempt > maxRetries || !shouldRetry(error)) {
228
+ if (error?.status === 429 || error?.response?.status === 429) {
229
+ throw new DriveRateLimitError(
230
+ `Drive API rate limit exceeded after ${attempt} attempts.`,
231
+ void 0,
232
+ error
233
+ );
234
+ }
235
+ throw error;
236
+ }
237
+ const calculatedDelay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
238
+ const jitterDelay = Math.floor(Math.random() * calculatedDelay);
239
+ await new Promise((resolve) => setTimeout(resolve, jitterDelay));
240
+ }
241
+ }
242
+ }
243
+
244
+ // src/core/path-resolver.ts
245
+ var PathResolver = class {
246
+ drive;
247
+ rootFolderId;
248
+ cache = /* @__PURE__ */ new Map();
249
+ cacheTTL;
250
+ enableCache;
251
+ constructor(drive2, rootFolderId = "root", options) {
252
+ this.drive = drive2;
253
+ this.rootFolderId = rootFolderId;
254
+ this.enableCache = options?.enableCache ?? true;
255
+ this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
256
+ }
257
+ /**
258
+ * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
259
+ */
260
+ normalizePath(rawPath) {
261
+ if (!rawPath || rawPath.trim() === "" || rawPath === "/") {
262
+ return "/";
263
+ }
264
+ const parts = rawPath.split("/").map((p) => p.trim()).filter(Boolean);
265
+ return `/${parts.join("/")}`;
266
+ }
267
+ /**
268
+ * Gets cache key for a path
269
+ */
270
+ getCacheKey(path5) {
271
+ return `${this.rootFolderId}:${this.normalizePath(path5)}`;
272
+ }
273
+ /**
274
+ * Clears the path cache
275
+ */
276
+ clearCache() {
277
+ this.cache.clear();
278
+ }
279
+ /**
280
+ * Invalidate a single path from cache
281
+ */
282
+ invalidatePath(path5) {
283
+ const key = this.getCacheKey(path5);
284
+ this.cache.delete(key);
285
+ }
286
+ /**
287
+ * Resolves a path to a Google Drive item (file or folder).
288
+ * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
289
+ */
290
+ async resolve(virtualPath, options = {}) {
291
+ const norm = this.normalizePath(virtualPath);
292
+ if (norm === "/") {
293
+ return {
294
+ id: this.rootFolderId,
295
+ name: "root",
296
+ isFolder: true,
297
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
298
+ };
299
+ }
300
+ if (this.enableCache) {
301
+ const cached = this.cache.get(this.getCacheKey(norm));
302
+ if (cached && cached.expiresAt > Date.now()) {
303
+ return {
304
+ id: cached.id,
305
+ name: cached.name,
306
+ isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
307
+ mimeType: cached.mimeType
308
+ };
309
+ }
310
+ }
311
+ const segments = norm.split("/").filter(Boolean);
312
+ let currentParentId = this.rootFolderId;
313
+ let currentPath = "";
314
+ for (let i = 0; i < segments.length; i++) {
315
+ const segment = segments[i];
316
+ const isLast = i === segments.length - 1;
317
+ currentPath += `/${segment}`;
318
+ if (this.enableCache) {
319
+ const cached = this.cache.get(this.getCacheKey(currentPath));
320
+ if (cached && cached.expiresAt > Date.now()) {
321
+ currentParentId = cached.id;
322
+ if (isLast) {
323
+ return {
324
+ id: cached.id,
325
+ name: cached.name,
326
+ isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
327
+ mimeType: cached.mimeType
328
+ };
329
+ }
330
+ continue;
331
+ }
332
+ }
333
+ const escapedName = segment.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
334
+ const q = `'${currentParentId}' in parents and name = '${escapedName}' and trashed = false`;
335
+ const response = await withRetry(async () => {
336
+ return await this.drive.files.list({
337
+ q,
338
+ fields: "files(id, name, mimeType, parents)",
339
+ pageSize: 1,
340
+ spaces: "drive",
341
+ supportsAllDrives: true,
342
+ includeItemsFromAllDrives: true
343
+ });
344
+ });
345
+ let file = response.data.files?.[0];
346
+ if (!file && currentParentId === this.rootFolderId) {
347
+ const sharedQ = `name = '${escapedName}' and trashed = false`;
348
+ const sharedResponse = await withRetry(async () => {
349
+ return await this.drive.files.list({
350
+ q: sharedQ,
351
+ fields: "files(id, name, mimeType, parents)",
352
+ pageSize: 1,
353
+ spaces: "drive",
354
+ supportsAllDrives: true,
355
+ includeItemsFromAllDrives: true
356
+ });
357
+ });
358
+ file = sharedResponse.data.files?.[0];
359
+ }
360
+ if (file && file.id) {
361
+ currentParentId = file.id;
362
+ if (this.enableCache) {
363
+ this.cache.set(this.getCacheKey(currentPath), {
364
+ id: file.id,
365
+ name: file.name || segment,
366
+ mimeType: file.mimeType || "",
367
+ expiresAt: Date.now() + this.cacheTTL
368
+ });
369
+ }
370
+ if (isLast) {
371
+ return {
372
+ id: file.id,
373
+ name: file.name || segment,
374
+ isFolder: file.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
375
+ mimeType: file.mimeType || ""
376
+ };
377
+ }
378
+ } else {
379
+ if (options.createIfMissing) {
380
+ const createRes = await withRetry(async () => {
381
+ return await this.drive.files.create({
382
+ requestBody: {
383
+ name: segment,
384
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
385
+ parents: [currentParentId]
386
+ },
387
+ fields: "id, name, mimeType",
388
+ supportsAllDrives: true
389
+ });
390
+ });
391
+ const newFolder = createRes.data;
392
+ if (!newFolder.id) {
393
+ throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
394
+ }
395
+ currentParentId = newFolder.id;
396
+ if (this.enableCache) {
397
+ this.cache.set(this.getCacheKey(currentPath), {
398
+ id: newFolder.id,
399
+ name: segment,
400
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
401
+ expiresAt: Date.now() + this.cacheTTL
402
+ });
403
+ }
404
+ if (isLast) {
405
+ return {
406
+ id: newFolder.id,
407
+ name: segment,
408
+ isFolder: true,
409
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
410
+ };
411
+ }
412
+ } else {
413
+ throw new DriveNotFoundError(
414
+ virtualPath,
415
+ `Path segment "${segment}" not found in path "${virtualPath}" under folder ID "${currentParentId}"`
416
+ );
417
+ }
418
+ }
419
+ }
420
+ throw new DriveNotFoundError(virtualPath);
421
+ }
422
+ /**
423
+ * Ensures that a directory structure exists (like mkdir -p).
424
+ */
425
+ async mkdirp(virtualPath) {
426
+ const res = await this.resolve(virtualPath, { createIfMissing: true });
427
+ return res.id;
428
+ }
429
+ };
430
+
431
+ // src/core/resumable-uploader.ts
432
+ import fs2 from "fs";
433
+ import path from "path";
434
+
435
+ // src/utils/format.ts
436
+ function formatBytes(bytes, decimals = 2) {
437
+ if (bytes === 0) return "0 B";
438
+ const k = 1024;
439
+ const dm = decimals < 0 ? 0 : decimals;
440
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
441
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
442
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
443
+ }
444
+ function formatSpeed(bytesPerSecond) {
445
+ return `${formatBytes(bytesPerSecond)}/s`;
446
+ }
447
+ function formatDuration(seconds) {
448
+ if (!Number.isFinite(seconds) || seconds < 0) return "--:--";
449
+ const totalSeconds = Math.round(seconds);
450
+ const hrs = Math.floor(totalSeconds / 3600);
451
+ const mins = Math.floor(totalSeconds % 3600 / 60);
452
+ const secs = totalSeconds % 60;
453
+ if (hrs > 0) {
454
+ return `${hrs}h ${mins}m ${secs}s`;
455
+ }
456
+ return `${mins}m ${secs}s`;
457
+ }
458
+
459
+ // src/core/resumable-uploader.ts
460
+ var MIN_CHUNK_SIZE = 256 * 1024;
461
+ var DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
462
+ var MULTIPART_THRESHOLD = 5 * 1024 * 1024;
463
+ var ResumableUploader = class {
464
+ drive;
465
+ defaultChunkSize;
466
+ constructor(drive2, defaultChunkSize = DEFAULT_CHUNK_SIZE) {
467
+ this.drive = drive2;
468
+ this.defaultChunkSize = Math.max(
469
+ MIN_CHUNK_SIZE,
470
+ Math.floor(defaultChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE
471
+ );
472
+ }
473
+ /**
474
+ * Uploads a file with automatic selection of direct multipart (small files)
475
+ * or resumable chunked upload with progress events (large files).
476
+ */
477
+ async upload(options) {
478
+ if (typeof options.source === "string") {
479
+ return await this.uploadFromPath(options.source, options);
480
+ } else if (Buffer.isBuffer(options.source)) {
481
+ return await this.uploadFromBuffer(options.source, options);
482
+ } else {
483
+ return await this.uploadFromStream(options.source, options);
484
+ }
485
+ }
486
+ /**
487
+ * Upload from local file path with memory-efficient chunked streaming
488
+ */
489
+ async uploadFromPath(filePath, options) {
490
+ if (!fs2.existsSync(filePath)) {
491
+ throw new Error(`File does not exist at path: "${filePath}"`);
492
+ }
493
+ const stat = await fs2.promises.stat(filePath);
494
+ const totalBytes = stat.size;
495
+ const fileName = options.name || path.basename(filePath);
496
+ const mimeType = options.mimeType || lookupMimeType(filePath);
497
+ return await this.chunkedUpload({
498
+ filePath,
499
+ totalBytes,
500
+ fileName,
501
+ mimeType,
502
+ options
503
+ });
504
+ }
505
+ /**
506
+ * Upload from in-memory Buffer
507
+ */
508
+ async uploadFromBuffer(buffer, options) {
509
+ const totalBytes = buffer.length;
510
+ const fileName = options.name || "untitled";
511
+ const mimeType = options.mimeType || "application/octet-stream";
512
+ return await this.chunkedUploadBuffer({
513
+ buffer,
514
+ totalBytes,
515
+ fileName,
516
+ mimeType,
517
+ options
518
+ });
519
+ }
520
+ /**
521
+ * Upload from generic Readable Stream
522
+ */
523
+ async uploadFromStream(stream, options) {
524
+ const fileName = options.name || "untitled";
525
+ const mimeType = options.mimeType || "application/octet-stream";
526
+ return await this.directUpload(stream, {
527
+ ...options,
528
+ name: fileName,
529
+ mimeType
530
+ });
531
+ }
532
+ /**
533
+ * Fast direct upload using googleapis multipart
534
+ */
535
+ async directUpload(stream, options) {
536
+ const requestBody = {
537
+ name: options.name,
538
+ mimeType: options.mimeType,
539
+ description: options.description,
540
+ properties: options.properties,
541
+ appProperties: options.appProperties
542
+ };
543
+ if (options.parent) {
544
+ requestBody.parents = [options.parent];
545
+ }
546
+ const res = await withRetry(async () => {
547
+ return await this.drive.files.create({
548
+ requestBody,
549
+ media: {
550
+ mimeType: options.mimeType,
551
+ body: stream
552
+ },
553
+ fields: "id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime",
554
+ supportsAllDrives: true
555
+ });
556
+ });
557
+ return res.data;
558
+ }
559
+ /**
560
+ * Chunked resumable upload for local files with low memory footprint
561
+ */
562
+ async chunkedUpload(params) {
563
+ const { filePath, totalBytes, fileName, mimeType, options } = params;
564
+ const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
565
+ const sessionUrl = await this.initiateResumableSession({
566
+ fileName,
567
+ mimeType,
568
+ totalBytes,
569
+ parent: options.parent,
570
+ description: options.description,
571
+ properties: options.properties,
572
+ appProperties: options.appProperties
573
+ });
574
+ const fd = await fs2.promises.open(filePath, "r");
575
+ let bytesSent = 0;
576
+ const startTime = Date.now();
577
+ const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
578
+ let chunkIndex = 0;
579
+ try {
580
+ while (bytesSent < totalBytes) {
581
+ chunkIndex++;
582
+ const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
583
+ const buffer = Buffer.alloc(currentChunkSize);
584
+ await fd.read(buffer, 0, currentChunkSize, bytesSent);
585
+ const rangeStart = bytesSent;
586
+ const rangeEnd = bytesSent + currentChunkSize - 1;
587
+ const chunkResult = await this.uploadChunkWithRetry({
588
+ sessionUrl,
589
+ buffer,
590
+ rangeStart,
591
+ rangeEnd,
592
+ totalBytes
593
+ });
594
+ bytesSent += currentChunkSize;
595
+ if (options.onProgress) {
596
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
597
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
598
+ const remainingBytes = totalBytes - bytesSent;
599
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
600
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
601
+ options.onProgress({
602
+ bytesSent,
603
+ totalBytes,
604
+ percentage,
605
+ bytesPerSecond,
606
+ speedFormatted: formatSpeed(bytesPerSecond),
607
+ estimatedTimeRemainingSeconds,
608
+ chunkIndex,
609
+ totalChunks
610
+ });
611
+ }
612
+ if (chunkResult.isComplete && chunkResult.file) {
613
+ return chunkResult.file;
614
+ }
615
+ }
616
+ } finally {
617
+ await fd.close();
618
+ }
619
+ throw new DriveUploadError("Resumable upload loop ended without completion response", bytesSent, totalBytes);
620
+ }
621
+ /**
622
+ * Chunked resumable upload for memory buffers
623
+ */
624
+ async chunkedUploadBuffer(params) {
625
+ const { buffer, totalBytes, fileName, mimeType, options } = params;
626
+ const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
627
+ const sessionUrl = await this.initiateResumableSession({
628
+ fileName,
629
+ mimeType,
630
+ totalBytes,
631
+ parent: options.parent,
632
+ description: options.description,
633
+ properties: options.properties,
634
+ appProperties: options.appProperties
635
+ });
636
+ let bytesSent = 0;
637
+ const startTime = Date.now();
638
+ const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
639
+ let chunkIndex = 0;
640
+ while (bytesSent < totalBytes) {
641
+ chunkIndex++;
642
+ const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
643
+ const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
644
+ const rangeStart = bytesSent;
645
+ const rangeEnd = bytesSent + currentChunkSize - 1;
646
+ const chunkResult = await this.uploadChunkWithRetry({
647
+ sessionUrl,
648
+ buffer: chunk,
649
+ rangeStart,
650
+ rangeEnd,
651
+ totalBytes
652
+ });
653
+ bytesSent += currentChunkSize;
654
+ if (options.onProgress) {
655
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
656
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
657
+ const remainingBytes = totalBytes - bytesSent;
658
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
659
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
660
+ options.onProgress({
661
+ bytesSent,
662
+ totalBytes,
663
+ percentage,
664
+ bytesPerSecond,
665
+ speedFormatted: formatSpeed(bytesPerSecond),
666
+ estimatedTimeRemainingSeconds,
667
+ chunkIndex,
668
+ totalChunks
669
+ });
670
+ }
671
+ if (chunkResult.isComplete && chunkResult.file) {
672
+ return chunkResult.file;
673
+ }
674
+ }
675
+ throw new DriveUploadError("Resumable buffer upload ended without completion", bytesSent, totalBytes);
676
+ }
677
+ /**
678
+ * Request an upload session URI from Google Drive API
679
+ */
680
+ async initiateResumableSession(meta) {
681
+ const authClient = this.drive.context._options.auth;
682
+ const headers = {
683
+ "X-Upload-Content-Type": meta.mimeType,
684
+ "X-Upload-Content-Length": meta.totalBytes.toString(),
685
+ "Content-Type": "application/json; charset=UTF-8"
686
+ };
687
+ const metadata = {
688
+ name: meta.fileName,
689
+ mimeType: meta.mimeType,
690
+ description: meta.description,
691
+ properties: meta.properties,
692
+ appProperties: meta.appProperties
693
+ };
694
+ if (meta.parent) {
695
+ metadata.parents = [meta.parent];
696
+ }
697
+ const res = await withRetry(async () => {
698
+ return await authClient.request({
699
+ url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
700
+ method: "POST",
701
+ headers,
702
+ data: metadata
703
+ });
704
+ });
705
+ const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
706
+ if (!sessionUrl) {
707
+ throw new DriveUploadError("Failed to initiate resumable upload session: No Location header in response");
708
+ }
709
+ return sessionUrl;
710
+ }
711
+ /**
712
+ * Upload a chunk with exponential backoff on network failures
713
+ */
714
+ async uploadChunkWithRetry(params) {
715
+ const { sessionUrl, buffer, rangeStart, rangeEnd, totalBytes } = params;
716
+ const authClient = this.drive.context._options.auth;
717
+ const headers = {
718
+ "Content-Length": buffer.length.toString(),
719
+ "Content-Range": `bytes ${rangeStart}-${rangeEnd}/${totalBytes}`
720
+ };
721
+ return await withRetry(async () => {
722
+ try {
723
+ const res = await authClient.request({
724
+ url: sessionUrl,
725
+ method: "PUT",
726
+ headers,
727
+ data: buffer,
728
+ validateStatus: (status) => status >= 200 && status < 300 || status === 308
729
+ });
730
+ if (res.status === 200 || res.status === 201) {
731
+ return { isComplete: true, file: res.data };
732
+ }
733
+ if (res.status === 308) {
734
+ return { isComplete: false };
735
+ }
736
+ throw new DriveUploadError(`Unexpected response status ${res.status} during chunk upload`);
737
+ } catch (err) {
738
+ if (err.status === 308) {
739
+ return { isComplete: false };
740
+ }
741
+ const msg = err.message || err.response?.data?.error?.message || "";
742
+ if (msg.includes("Service Accounts do not have storage quota") || msg.includes("storageQuotaExceeded")) {
743
+ throw new DriveUploadError(
744
+ "Google Drive Policy: Service Accounts do not have file storage quota in personal Google accounts. To upload files, use an OAuth2 token or pass accessToken.",
745
+ params.rangeStart,
746
+ params.totalBytes,
747
+ err
748
+ );
749
+ }
750
+ throw err;
751
+ }
752
+ });
753
+ }
754
+ };
755
+
756
+ // src/core/downloader.ts
757
+ import fs3 from "fs";
758
+ import path2 from "path";
759
+ import { pipeline } from "stream/promises";
760
+ import { Transform } from "stream";
761
+ var Downloader = class {
762
+ drive;
763
+ constructor(drive2) {
764
+ this.drive = drive2;
765
+ }
766
+ /**
767
+ * Downloads a file from Google Drive to local destination path or returns a readable stream.
768
+ */
769
+ async download(fileId, options = {}) {
770
+ const metaRes = await withRetry(async () => {
771
+ return await this.drive.files.get({
772
+ fileId,
773
+ fields: "id, name, mimeType, size",
774
+ supportsAllDrives: true
775
+ });
776
+ });
777
+ const file = metaRes.data;
778
+ const name = file.name || "downloaded-file";
779
+ const mimeType = file.mimeType || "application/octet-stream";
780
+ const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
781
+ let downloadStream;
782
+ let finalFileName = name;
783
+ if (isGoogleWorkspaceDoc(mimeType)) {
784
+ const exportConfig = DEFAULT_EXPORT_MIMES[mimeType] || {
785
+ mimeType: "application/pdf",
786
+ extension: ".pdf"
787
+ };
788
+ const targetMime = options.exportMimeType || exportConfig.mimeType;
789
+ const ext = getExtensionForMime(targetMime) || exportConfig.extension;
790
+ if (!finalFileName.endsWith(ext)) {
791
+ finalFileName = `${finalFileName}${ext}`;
792
+ }
793
+ const res = await withRetry(async () => {
794
+ return await this.drive.files.export(
795
+ { fileId, mimeType: targetMime },
796
+ { responseType: "stream" }
797
+ );
798
+ });
799
+ downloadStream = res.data;
800
+ } else {
801
+ const res = await withRetry(async () => {
802
+ return await this.drive.files.get(
803
+ { fileId, alt: "media", supportsAllDrives: true },
804
+ { responseType: "stream" }
805
+ );
806
+ });
807
+ downloadStream = res.data;
808
+ }
809
+ let bytesRead = 0;
810
+ const startTime = Date.now();
811
+ const progressTracker = new Transform({
812
+ transform(chunk, encoding, callback) {
813
+ bytesRead += chunk.length;
814
+ if (options.onProgress) {
815
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
816
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesRead / elapsedSecs) : 0;
817
+ const percentage = totalBytes ? Math.min(100, Math.round(bytesRead / totalBytes * 1e3) / 10) : void 0;
818
+ options.onProgress({
819
+ bytesRead,
820
+ totalBytes,
821
+ percentage,
822
+ bytesPerSecond,
823
+ speedFormatted: formatSpeed(bytesPerSecond)
824
+ });
825
+ }
826
+ callback(null, chunk);
827
+ }
828
+ });
829
+ const monitoredStream = downloadStream.pipe(progressTracker);
830
+ if (options.destination) {
831
+ let destPath = options.destination;
832
+ if (fs3.existsSync(destPath) && fs3.statSync(destPath).isDirectory()) {
833
+ destPath = path2.join(destPath, finalFileName);
834
+ }
835
+ await fs3.promises.mkdir(path2.dirname(destPath), { recursive: true });
836
+ const writeStream = fs3.createWriteStream(destPath);
837
+ await pipeline(monitoredStream, writeStream);
838
+ return {
839
+ filePath: destPath,
840
+ name: finalFileName,
841
+ mimeType,
842
+ size: bytesRead
843
+ };
844
+ }
845
+ return {
846
+ stream: monitoredStream,
847
+ name: finalFileName,
848
+ mimeType,
849
+ size: totalBytes
850
+ };
851
+ }
852
+ };
853
+
854
+ // src/core/query-builder.ts
855
+ var DriveQueryBuilder = class {
856
+ drive;
857
+ conditions = [];
858
+ orderClauses = [];
859
+ limitNumber = 100;
860
+ requestedFields = "nextPageToken, files(id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, shared)";
861
+ spaces = "drive";
862
+ constructor(drive2) {
863
+ this.drive = drive2;
864
+ }
865
+ /**
866
+ * Escape single quotes and backslashes for Google Drive search queries
867
+ */
868
+ escape(str) {
869
+ return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
870
+ }
871
+ /**
872
+ * Filter: Exact file name match
873
+ */
874
+ nameEquals(name) {
875
+ this.conditions.push(`name = '${this.escape(name)}'`);
876
+ return this;
877
+ }
878
+ /**
879
+ * Filter: File name contains substring
880
+ */
881
+ nameContains(substring) {
882
+ this.conditions.push(`name contains '${this.escape(substring)}'`);
883
+ return this;
884
+ }
885
+ /**
886
+ * Filter: Specific MIME type
887
+ */
888
+ mimeType(mime2) {
889
+ this.conditions.push(`mimeType = '${this.escape(mime2)}'`);
890
+ return this;
891
+ }
892
+ /**
893
+ * Filter: Only folders
894
+ */
895
+ isFolder() {
896
+ this.conditions.push(`mimeType = '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);
897
+ return this;
898
+ }
899
+ /**
900
+ * Filter: Exclude folders (only files)
901
+ */
902
+ isFile() {
903
+ this.conditions.push(`mimeType != '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);
904
+ return this;
905
+ }
906
+ /**
907
+ * Filter: Direct parent folder ID
908
+ */
909
+ inFolder(folderId) {
910
+ this.conditions.push(`'${this.escape(folderId)}' in parents`);
911
+ return this;
912
+ }
913
+ /**
914
+ * Filter: Items not in trash (default recommended)
915
+ */
916
+ notTrashed() {
917
+ this.conditions.push("trashed = false");
918
+ return this;
919
+ }
920
+ /**
921
+ * Filter: Only trashed items
922
+ */
923
+ onlyTrashed() {
924
+ this.conditions.push("trashed = true");
925
+ return this;
926
+ }
927
+ /**
928
+ * Filter: Starred items
929
+ */
930
+ starred(isStarred = true) {
931
+ this.conditions.push(`starred = ${isStarred}`);
932
+ return this;
933
+ }
934
+ /**
935
+ * Filter: Shared with current user
936
+ */
937
+ sharedWithMe() {
938
+ this.conditions.push("sharedWithMe = true");
939
+ return this;
940
+ }
941
+ /**
942
+ * Filter: Modified after timestamp or Date
943
+ */
944
+ modifiedAfter(date) {
945
+ const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();
946
+ this.conditions.push(`modifiedTime > '${iso}'`);
947
+ return this;
948
+ }
949
+ /**
950
+ * Filter: Modified before timestamp or Date
951
+ */
952
+ modifiedBefore(date) {
953
+ const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();
954
+ this.conditions.push(`modifiedTime < '${iso}'`);
955
+ return this;
956
+ }
957
+ /**
958
+ * Filter: Full-text search across content and name
959
+ */
960
+ fullText(term) {
961
+ this.conditions.push(`fullText contains '${this.escape(term)}'`);
962
+ return this;
963
+ }
964
+ /**
965
+ * Custom raw query condition
966
+ */
967
+ raw(condition) {
968
+ this.conditions.push(`(${condition})`);
969
+ return this;
970
+ }
971
+ /**
972
+ * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
973
+ */
974
+ orderBy(order) {
975
+ this.orderClauses.push(order);
976
+ return this;
977
+ }
978
+ /**
979
+ * Maximum items to retrieve per page or query
980
+ */
981
+ pageSize(size) {
982
+ this.limitNumber = Math.min(1e3, Math.max(1, size));
983
+ return this;
984
+ }
985
+ /**
986
+ * Custom fields to return from Drive API
987
+ */
988
+ fields(fieldsString) {
989
+ this.requestedFields = fieldsString;
990
+ return this;
991
+ }
992
+ /**
993
+ * Compiles the full query string
994
+ */
995
+ toQueryString() {
996
+ return this.conditions.join(" and ");
997
+ }
998
+ /**
999
+ * Executes query and returns array of matching files
1000
+ */
1001
+ async list() {
1002
+ const q = this.toQueryString();
1003
+ const orderBy = this.orderClauses.join(", ");
1004
+ const res = await withRetry(async () => {
1005
+ return await this.drive.files.list({
1006
+ q: q || void 0,
1007
+ orderBy: orderBy || void 0,
1008
+ pageSize: this.limitNumber,
1009
+ fields: this.requestedFields,
1010
+ spaces: this.spaces,
1011
+ supportsAllDrives: true,
1012
+ includeItemsFromAllDrives: true
1013
+ });
1014
+ });
1015
+ return res.data.files || [];
1016
+ }
1017
+ /**
1018
+ * Returns the first matching file, or null if not found
1019
+ */
1020
+ async first() {
1021
+ const originalLimit = this.limitNumber;
1022
+ this.limitNumber = 1;
1023
+ const items = await this.list();
1024
+ this.limitNumber = originalLimit;
1025
+ return items[0] || null;
1026
+ }
1027
+ /**
1028
+ * Counts matching items (up to 1000)
1029
+ */
1030
+ async count() {
1031
+ const items = await this.list();
1032
+ return items.length;
1033
+ }
1034
+ /**
1035
+ * Async iterator to stream all pages automatically without loading all into memory
1036
+ */
1037
+ async *[Symbol.asyncIterator]() {
1038
+ const q = this.toQueryString();
1039
+ const orderBy = this.orderClauses.join(", ");
1040
+ let pageToken = void 0;
1041
+ do {
1042
+ const res = await withRetry(async () => {
1043
+ return await this.drive.files.list({
1044
+ q: q || void 0,
1045
+ orderBy: orderBy || void 0,
1046
+ pageSize: this.limitNumber,
1047
+ pageToken,
1048
+ fields: this.requestedFields,
1049
+ spaces: this.spaces,
1050
+ supportsAllDrives: true,
1051
+ includeItemsFromAllDrives: true
1052
+ });
1053
+ });
1054
+ const files = res.data.files || [];
1055
+ for (const file of files) {
1056
+ yield file;
1057
+ }
1058
+ pageToken = res.data.nextPageToken || void 0;
1059
+ } while (pageToken);
1060
+ }
1061
+ };
1062
+
1063
+ // src/core/concurrency-pool.ts
1064
+ var ConcurrencyPool = class {
1065
+ concurrency;
1066
+ running = 0;
1067
+ queue = [];
1068
+ constructor(concurrency = 4) {
1069
+ this.concurrency = Math.max(1, concurrency);
1070
+ }
1071
+ /**
1072
+ * Run a task when a slot becomes available
1073
+ */
1074
+ async run(task) {
1075
+ if (this.running >= this.concurrency) {
1076
+ await new Promise((resolve) => {
1077
+ this.queue.push(async () => {
1078
+ resolve();
1079
+ });
1080
+ });
1081
+ }
1082
+ this.running++;
1083
+ try {
1084
+ return await task();
1085
+ } finally {
1086
+ this.running--;
1087
+ if (this.queue.length > 0) {
1088
+ const next = this.queue.shift();
1089
+ if (next) next();
1090
+ }
1091
+ }
1092
+ }
1093
+ /**
1094
+ * Run all tasks in parallel bounded by concurrency limit
1095
+ */
1096
+ async all(tasks) {
1097
+ return Promise.all(tasks.map((task) => this.run(task)));
1098
+ }
1099
+ /**
1100
+ * Execute an array of items concurrently through an async mapper
1101
+ */
1102
+ async map(items, fn) {
1103
+ return Promise.all(items.map((item, index) => this.run(() => fn(item, index))));
1104
+ }
1105
+ };
1106
+
1107
+ // src/core/watcher.ts
1108
+ import { EventEmitter } from "events";
1109
+ var DriveWatcher = class extends EventEmitter {
1110
+ drive;
1111
+ options;
1112
+ timer = null;
1113
+ isRunning = false;
1114
+ pageToken = null;
1115
+ constructor(drive2, options = {}) {
1116
+ super();
1117
+ this.drive = drive2;
1118
+ this.options = {
1119
+ intervalMs: 5e3,
1120
+ ...options
1121
+ };
1122
+ }
1123
+ /**
1124
+ * Starts listening for changes
1125
+ */
1126
+ async start() {
1127
+ if (this.isRunning) return this;
1128
+ this.isRunning = true;
1129
+ if (!this.pageToken) {
1130
+ const tokenRes = await withRetry(async () => {
1131
+ return await this.drive.changes.getStartPageToken({
1132
+ supportsAllDrives: true
1133
+ });
1134
+ });
1135
+ this.pageToken = tokenRes.data.startPageToken || null;
1136
+ }
1137
+ this.poll();
1138
+ return this;
1139
+ }
1140
+ /**
1141
+ * Stops listening
1142
+ */
1143
+ stop() {
1144
+ this.isRunning = false;
1145
+ if (this.timer) {
1146
+ clearTimeout(this.timer);
1147
+ this.timer = null;
1148
+ }
1149
+ this.emit("stop");
1150
+ }
1151
+ /**
1152
+ * Internal polling cycle
1153
+ */
1154
+ async poll() {
1155
+ if (!this.isRunning) return;
1156
+ try {
1157
+ if (!this.pageToken) {
1158
+ const tokenRes = await withRetry(async () => {
1159
+ return await this.drive.changes.getStartPageToken({
1160
+ supportsAllDrives: true
1161
+ });
1162
+ });
1163
+ this.pageToken = tokenRes.data.startPageToken || null;
1164
+ }
1165
+ let nextPageToken = this.pageToken;
1166
+ do {
1167
+ const res = await withRetry(async () => {
1168
+ return await this.drive.changes.list({
1169
+ pageToken: nextPageToken,
1170
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1171
+ supportsAllDrives: true,
1172
+ includeItemsFromAllDrives: true
1173
+ });
1174
+ });
1175
+ const changes = res.data.changes || [];
1176
+ for (const change of changes) {
1177
+ if (!change.fileId) continue;
1178
+ if (this.options.folderId && change.file) {
1179
+ const parents = change.file.parents || [];
1180
+ if (!parents.includes(this.options.folderId)) {
1181
+ continue;
1182
+ }
1183
+ }
1184
+ let eventType = "modify";
1185
+ if (change.removed || change.file?.trashed) {
1186
+ eventType = "delete";
1187
+ } else if (change.file?.createdTime && change.file?.modifiedTime) {
1188
+ const created = new Date(change.file.createdTime).getTime();
1189
+ const modified = new Date(change.file.modifiedTime).getTime();
1190
+ if (Math.abs(modified - created) < 2e3) {
1191
+ eventType = "create";
1192
+ }
1193
+ }
1194
+ const eventPayload = {
1195
+ type: eventType,
1196
+ fileId: change.fileId,
1197
+ file: change.file || void 0,
1198
+ removed: change.removed || false,
1199
+ time: change.time ? new Date(change.time) : /* @__PURE__ */ new Date()
1200
+ };
1201
+ this.emit("change", eventPayload);
1202
+ this.emit(eventType, eventPayload);
1203
+ }
1204
+ if (res.data.newStartPageToken) {
1205
+ this.pageToken = res.data.newStartPageToken;
1206
+ break;
1207
+ }
1208
+ nextPageToken = res.data.nextPageToken || null;
1209
+ } while (nextPageToken);
1210
+ } catch (err) {
1211
+ this.emit("error", err);
1212
+ } finally {
1213
+ if (this.isRunning) {
1214
+ this.timer = setTimeout(() => this.poll(), this.options.intervalMs);
1215
+ }
1216
+ }
1217
+ }
1218
+ };
1219
+
1220
+ // src/core/storage-cleaner.ts
1221
+ var StorageCleaner = class {
1222
+ drive;
1223
+ constructor(drive2) {
1224
+ this.drive = drive2;
1225
+ }
1226
+ /**
1227
+ * Finds the largest files occupying space in the Google Drive account
1228
+ */
1229
+ async findLargestFiles(limit = 10) {
1230
+ const res = await withRetry(async () => {
1231
+ return await this.drive.files.list({
1232
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1233
+ orderBy: "quotaBytesUsed desc",
1234
+ pageSize: Math.min(100, Math.max(1, limit)),
1235
+ fields: "files(id, name, size, mimeType, modifiedTime, webViewLink, quotaBytesUsed)",
1236
+ supportsAllDrives: true,
1237
+ includeItemsFromAllDrives: true
1238
+ });
1239
+ });
1240
+ const files = res.data.files || [];
1241
+ return files.map((f) => {
1242
+ const sizeBytes = parseInt(f.size || f.quotaBytesUsed || "0", 10);
1243
+ return {
1244
+ id: f.id,
1245
+ name: f.name || "untitled",
1246
+ size: sizeBytes,
1247
+ formattedSize: formatBytes(sizeBytes),
1248
+ mimeType: f.mimeType || "unknown",
1249
+ modifiedTime: f.modifiedTime || void 0,
1250
+ webViewLink: f.webViewLink || void 0
1251
+ };
1252
+ });
1253
+ }
1254
+ /**
1255
+ * Scans Google Drive and detects duplicate files (by MD5 hash or exact name)
1256
+ */
1257
+ async findDuplicates(options = {}) {
1258
+ const mode = options.by || "name";
1259
+ const maxScan = options.maxScan || 1e3;
1260
+ const res = await withRetry(async () => {
1261
+ return await this.drive.files.list({
1262
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1263
+ pageSize: Math.min(1e3, maxScan),
1264
+ fields: "files(id, name, size, md5Checksum, modifiedTime)",
1265
+ supportsAllDrives: true,
1266
+ includeItemsFromAllDrives: true
1267
+ });
1268
+ });
1269
+ const files = res.data.files || [];
1270
+ const map = /* @__PURE__ */ new Map();
1271
+ for (const f of files) {
1272
+ if (!f.id) continue;
1273
+ const key = mode === "md5" && f.md5Checksum ? f.md5Checksum : f.name || "";
1274
+ if (!key) continue;
1275
+ if (!map.has(key)) {
1276
+ map.set(key, []);
1277
+ }
1278
+ map.get(key).push(f);
1279
+ }
1280
+ const duplicates = [];
1281
+ for (const [key, group] of map.entries()) {
1282
+ if (group.length > 1) {
1283
+ let totalSize = 0;
1284
+ const mappedFiles = group.map((item) => {
1285
+ const s = parseInt(item.size || "0", 10);
1286
+ totalSize += s;
1287
+ return {
1288
+ id: item.id,
1289
+ name: item.name,
1290
+ size: s,
1291
+ modifiedTime: item.modifiedTime,
1292
+ md5Checksum: item.md5Checksum
1293
+ };
1294
+ });
1295
+ duplicates.push({
1296
+ name: key,
1297
+ count: group.length,
1298
+ totalSize,
1299
+ formattedTotalSize: formatBytes(totalSize),
1300
+ files: mappedFiles
1301
+ });
1302
+ }
1303
+ }
1304
+ return duplicates.sort((a, b) => b.totalSize - a.totalSize);
1305
+ }
1306
+ /**
1307
+ * Empties the entire trash in Google Drive
1308
+ */
1309
+ async emptyTrash() {
1310
+ await withRetry(async () => {
1311
+ await this.drive.files.emptyTrash({});
1312
+ });
1313
+ }
1314
+ };
1315
+
1316
+ // src/core/smart-sync.ts
1317
+ import fs4 from "fs";
1318
+ import path3 from "path";
1319
+ import crypto from "crypto";
1320
+ async function calculateFileMd5(filePath) {
1321
+ return new Promise((resolve, reject) => {
1322
+ const hash = crypto.createHash("md5");
1323
+ const stream = fs4.createReadStream(filePath);
1324
+ stream.on("data", (chunk) => hash.update(chunk));
1325
+ stream.on("end", () => resolve(hash.digest("hex")));
1326
+ stream.on("error", reject);
1327
+ });
1328
+ }
1329
+ var SmartSyncEngine = class {
1330
+ drive;
1331
+ downloader;
1332
+ constructor(drive2) {
1333
+ this.drive = drive2;
1334
+ this.downloader = new Downloader(drive2);
1335
+ }
1336
+ /**
1337
+ * Pulls (downloads) an entire Google Drive folder tree to a local directory
1338
+ */
1339
+ async pullFolder(remoteFolderId, localDestinationDir, options = {}) {
1340
+ const startTime = Date.now();
1341
+ const concurrency = options.concurrency || 4;
1342
+ const pool = new ConcurrencyPool(concurrency);
1343
+ const result = {
1344
+ downloaded: [],
1345
+ skipped: [],
1346
+ failed: [],
1347
+ totalBytes: 0,
1348
+ durationMs: 0
1349
+ };
1350
+ await fs4.promises.mkdir(localDestinationDir, { recursive: true });
1351
+ const collectRemoteItems = async (folderId, relPath) => {
1352
+ const items = [];
1353
+ let pageToken = void 0;
1354
+ do {
1355
+ const res = await withRetry(async () => {
1356
+ return await this.drive.files.list({
1357
+ q: `'${folderId}' in parents and trashed = false`,
1358
+ fields: "nextPageToken, files(id, name, mimeType, size, md5Checksum)",
1359
+ pageSize: 500,
1360
+ supportsAllDrives: true,
1361
+ includeItemsFromAllDrives: true
1362
+ });
1363
+ });
1364
+ const files = res.data.files || [];
1365
+ for (const file of files) {
1366
+ if (!file.id || !file.name) continue;
1367
+ const isFolder = file.mimeType === "application/vnd.google-apps.folder";
1368
+ const fileRel = relPath ? path3.join(relPath, file.name) : file.name;
1369
+ if (isFolder) {
1370
+ const sub = await collectRemoteItems(file.id, fileRel);
1371
+ items.push(...sub);
1372
+ } else {
1373
+ items.push({
1374
+ id: file.id,
1375
+ name: file.name,
1376
+ isFolder: false,
1377
+ relPath: fileRel,
1378
+ size: parseInt(file.size || "0", 10),
1379
+ md5Checksum: file.md5Checksum
1380
+ });
1381
+ }
1382
+ }
1383
+ pageToken = res.data.nextPageToken || void 0;
1384
+ } while (pageToken);
1385
+ return items;
1386
+ };
1387
+ const remoteFiles = await collectRemoteItems(remoteFolderId, "");
1388
+ await pool.map(remoteFiles, async (remoteItem) => {
1389
+ const localFilePath = path3.join(localDestinationDir, remoteItem.relPath);
1390
+ if (!options.overwrite && fs4.existsSync(localFilePath)) {
1391
+ const localStat = await fs4.promises.stat(localFilePath);
1392
+ if (remoteItem.md5Checksum) {
1393
+ const localMd5 = await calculateFileMd5(localFilePath);
1394
+ if (localMd5.toLowerCase() === remoteItem.md5Checksum.toLowerCase()) {
1395
+ result.skipped.push({
1396
+ remoteId: remoteItem.id,
1397
+ remoteName: remoteItem.name,
1398
+ reason: "Identical MD5 checksum matches local file"
1399
+ });
1400
+ return;
1401
+ }
1402
+ } else if (localStat.size === remoteItem.size && remoteItem.size > 0) {
1403
+ result.skipped.push({
1404
+ remoteId: remoteItem.id,
1405
+ remoteName: remoteItem.name,
1406
+ reason: "Identical file size exists locally"
1407
+ });
1408
+ return;
1409
+ }
1410
+ }
1411
+ try {
1412
+ if (options.onFileStart) {
1413
+ options.onFileStart(remoteItem.name, remoteItem.relPath);
1414
+ }
1415
+ await this.downloader.download(remoteItem.id, {
1416
+ destination: localFilePath
1417
+ });
1418
+ result.downloaded.push({
1419
+ remoteId: remoteItem.id,
1420
+ remoteName: remoteItem.name,
1421
+ localPath: localFilePath,
1422
+ size: remoteItem.size
1423
+ });
1424
+ result.totalBytes += remoteItem.size;
1425
+ if (options.onFileComplete) {
1426
+ options.onFileComplete(remoteItem.name, localFilePath);
1427
+ }
1428
+ } catch (err) {
1429
+ result.failed.push({
1430
+ remoteId: remoteItem.id,
1431
+ remoteName: remoteItem.name,
1432
+ error: err
1433
+ });
1434
+ }
1435
+ });
1436
+ result.durationMs = Date.now() - startTime;
1437
+ return result;
1438
+ }
1439
+ };
1440
+
1441
+ // src/auth/browser-login.ts
1442
+ import http from "http";
1443
+ import { exec } from "child_process";
1444
+ import { auth as googleAuth2 } from "@googleapis/drive";
1445
+ async function loginWithBrowser(options) {
1446
+ const port = options.port || 3e3;
1447
+ const redirectUri = `http://localhost:${port}/oauth2callback`;
1448
+ const scopes = options.scopes || DEFAULT_SCOPES;
1449
+ const oauth2Client = new googleAuth2.OAuth2(
1450
+ options.clientId,
1451
+ options.clientSecret,
1452
+ redirectUri
1453
+ );
1454
+ const authUrl = oauth2Client.generateAuthUrl({
1455
+ access_type: "offline",
1456
+ prompt: "consent",
1457
+ scope: scopes
1458
+ });
1459
+ return new Promise((resolve, reject) => {
1460
+ const server = http.createServer(async (req, res) => {
1461
+ try {
1462
+ const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1463
+ if (reqUrl.pathname === "/oauth2callback") {
1464
+ const code = reqUrl.searchParams.get("code");
1465
+ const error = reqUrl.searchParams.get("error");
1466
+ if (error) {
1467
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1468
+ res.end(`<h2>\u274C Authorization Failed</h2><p>${error}</p>`);
1469
+ server.close();
1470
+ return reject(new Error(`OAuth error: ${error}`));
1471
+ }
1472
+ if (!code) {
1473
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1474
+ res.end("<h2>\u274C Missing authorization code</h2>");
1475
+ return;
1476
+ }
1477
+ const { tokens } = await oauth2Client.getToken(code);
1478
+ oauth2Client.setCredentials(tokens);
1479
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1480
+ res.end(`
1481
+ <!DOCTYPE html>
1482
+ <html lang="en">
1483
+ <head>
1484
+ <meta charset="UTF-8">
1485
+ <title>DriveKit Authentication</title>
1486
+ <style>
1487
+ body {
1488
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1489
+ display: flex;
1490
+ align-items: center;
1491
+ justify-content: center;
1492
+ height: 100vh;
1493
+ margin: 0;
1494
+ background: #0f172a;
1495
+ color: #f8fafc;
1496
+ }
1497
+ .card {
1498
+ text-align: center;
1499
+ padding: 40px;
1500
+ background: #1e293b;
1501
+ border-radius: 16px;
1502
+ box-shadow: 0 10px 25px rgba(0,0,0,0.5);
1503
+ }
1504
+ .badge {
1505
+ font-size: 48px;
1506
+ margin-bottom: 12px;
1507
+ }
1508
+ h1 { color: #38bdf8; margin: 0 0 10px 0; }
1509
+ p { color: #94a3b8; font-size: 16px; }
1510
+ </style>
1511
+ </head>
1512
+ <body>
1513
+ <div class="card">
1514
+ <div class="badge">\u26A1</div>
1515
+ <h1>Authentication Successful!</h1>
1516
+ <p>DriveKit is now connected to your Google Drive account.</p>
1517
+ <p>You can close this window and return to your terminal.</p>
1518
+ </div>
1519
+ </body>
1520
+ </html>
1521
+ `);
1522
+ server.close();
1523
+ resolve({ tokens, client: oauth2Client });
1524
+ }
1525
+ } catch (err) {
1526
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
1527
+ res.end(`<h2>\u274C Server Error</h2><p>${err.message}</p>`);
1528
+ server.close();
1529
+ reject(err);
1530
+ }
1531
+ });
1532
+ server.listen(port, () => {
1533
+ const openCmd = process.platform === "darwin" ? `open "${authUrl}"` : process.platform === "win32" ? `start "" "${authUrl}"` : `xdg-open "${authUrl}"`;
1534
+ exec(openCmd, (err) => {
1535
+ if (err) {
1536
+ console.log(`
1537
+ Please open the following URL in your browser to sign in:
1538
+ ${authUrl}
1539
+ `);
1540
+ }
1541
+ });
1542
+ });
1543
+ server.on("error", (err) => {
1544
+ reject(err);
1545
+ });
1546
+ });
1547
+ }
1548
+
1549
+ // src/core/client.ts
1550
+ var DriveKit = class {
1551
+ options;
1552
+ authenticator;
1553
+ driveClient = null;
1554
+ pathResolverInstance = null;
1555
+ uploaderInstance = null;
1556
+ downloaderInstance = null;
1557
+ rootFolderId;
1558
+ constructor(options = {}) {
1559
+ this.options = options;
1560
+ this.rootFolderId = options.rootFolderId || "root";
1561
+ this.authenticator = new DriveAuthenticator(options.auth);
1562
+ }
1563
+ /**
1564
+ * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
1565
+ */
1566
+ async init() {
1567
+ if (!this.driveClient) {
1568
+ const auth = await this.authenticator.getAuthClient();
1569
+ this.driveClient = drive({ version: "v3", auth });
1570
+ this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1571
+ enableCache: this.options.enablePathCache ?? true,
1572
+ cacheTTL: this.options.pathCacheTTL
1573
+ });
1574
+ this.uploaderInstance = new ResumableUploader(
1575
+ this.driveClient,
1576
+ this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
1577
+ );
1578
+ this.downloaderInstance = new Downloader(this.driveClient);
1579
+ }
1580
+ return this;
1581
+ }
1582
+ /**
1583
+ * Access the underlying official `@googleapis/drive` instance for raw API calls
1584
+ */
1585
+ async getRawClient() {
1586
+ await this.init();
1587
+ return this.driveClient;
1588
+ }
1589
+ async getResolver() {
1590
+ await this.init();
1591
+ return this.pathResolverInstance;
1592
+ }
1593
+ async getUploader() {
1594
+ await this.init();
1595
+ return this.uploaderInstance;
1596
+ }
1597
+ async getDownloader() {
1598
+ await this.init();
1599
+ return this.downloaderInstance;
1600
+ }
1601
+ /**
1602
+ * Resolves a target string that could be either an ID or a virtual path (starting with '/')
1603
+ */
1604
+ async resolveId(idOrPath, autoCreateDir = false) {
1605
+ if (idOrPath.startsWith("/")) {
1606
+ const resolver = await this.getResolver();
1607
+ const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });
1608
+ return res.id;
1609
+ }
1610
+ return idOrPath;
1611
+ }
1612
+ // ==========================================
1613
+ // DIRECTORY & PATH OPERATIONS
1614
+ // ==========================================
1615
+ /**
1616
+ * Creates a folder structure recursively, similar to `mkdir -p`.
1617
+ * @param virtualPath Path like "/Documents/Projects/2026"
1618
+ * @returns Folder ID of the created or existing directory
1619
+ */
1620
+ async mkdirp(virtualPath) {
1621
+ const resolver = await this.getResolver();
1622
+ return await resolver.mkdirp(virtualPath);
1623
+ }
1624
+ /**
1625
+ * Resolves a virtual path to its Drive metadata
1626
+ */
1627
+ async resolvePath(virtualPath) {
1628
+ const resolver = await this.getResolver();
1629
+ return await resolver.resolve(virtualPath);
1630
+ }
1631
+ /**
1632
+ * Check if a file or folder exists (by ID or virtual path)
1633
+ */
1634
+ async exists(idOrPath) {
1635
+ try {
1636
+ if (idOrPath.startsWith("/")) {
1637
+ await this.resolvePath(idOrPath);
1638
+ return true;
1639
+ }
1640
+ const raw = await this.getRawClient();
1641
+ await raw.files.get({ fileId: idOrPath, fields: "id, trashed" });
1642
+ return true;
1643
+ } catch (err) {
1644
+ if (err.status === 404 || err.code === "NOT_FOUND") {
1645
+ return false;
1646
+ }
1647
+ throw err;
1648
+ }
1649
+ }
1650
+ /**
1651
+ * Lists contents of a folder (by folder ID or path)
1652
+ */
1653
+ async ls(folderIdOrPath = "/") {
1654
+ if (folderIdOrPath === "/" || folderIdOrPath === "root") {
1655
+ return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
1656
+ }
1657
+ const folderId = await this.resolveId(folderIdOrPath);
1658
+ return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
1659
+ }
1660
+ // ==========================================
1661
+ // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
1662
+ // ==========================================
1663
+ /**
1664
+ * Powerful upload method:
1665
+ * - Supports local paths, Buffers, or Streams
1666
+ * - Automatically uses high-speed resumable chunked upload for large files
1667
+ * - Parent can be a folder ID OR a virtual path (e.g. '/Backups/2026')
1668
+ * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
1669
+ */
1670
+ async upload(options) {
1671
+ const uploader = await this.getUploader();
1672
+ let parentId = options.parent;
1673
+ if (parentId && parentId.startsWith("/")) {
1674
+ parentId = await this.mkdirp(parentId);
1675
+ }
1676
+ if (options.overwrite && options.name && parentId) {
1677
+ const existing = await this.query().inFolder(parentId).nameEquals(options.name).notTrashed().first();
1678
+ if (existing?.id) {
1679
+ await this.delete(existing.id, true);
1680
+ }
1681
+ }
1682
+ return await uploader.upload({
1683
+ ...options,
1684
+ parent: parentId
1685
+ });
1686
+ }
1687
+ /**
1688
+ * Downloads a file from Google Drive:
1689
+ * - Automatic conversion for Google Docs, Sheets, and Slides
1690
+ * - Progress events
1691
+ * - Saves directly to file or returns Readable Stream
1692
+ */
1693
+ async download(fileIdOrPath, options = {}) {
1694
+ const fileId = await this.resolveId(fileIdOrPath);
1695
+ const downloader = await this.getDownloader();
1696
+ return await downloader.download(fileId, options);
1697
+ }
1698
+ /**
1699
+ * Gets file metadata
1700
+ */
1701
+ async getFile(fileIdOrPath) {
1702
+ const fileId = await this.resolveId(fileIdOrPath);
1703
+ const raw = await this.getRawClient();
1704
+ const res = await withRetry(async () => {
1705
+ return await raw.files.get({
1706
+ fileId,
1707
+ fields: "id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, description, properties, shared",
1708
+ supportsAllDrives: true
1709
+ });
1710
+ });
1711
+ return res.data;
1712
+ }
1713
+ /**
1714
+ * Reads file content as UTF-8 string
1715
+ */
1716
+ async getText(fileIdOrPath) {
1717
+ const { stream } = await this.download(fileIdOrPath);
1718
+ if (!stream) throw new Error("Failed to obtain download stream");
1719
+ const chunks = [];
1720
+ for await (const chunk of stream) {
1721
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1722
+ }
1723
+ return Buffer.concat(chunks).toString("utf-8");
1724
+ }
1725
+ /**
1726
+ * Reads file content and parses as JSON
1727
+ */
1728
+ async getJson(fileIdOrPath) {
1729
+ const text = await this.getText(fileIdOrPath);
1730
+ return JSON.parse(text);
1731
+ }
1732
+ /**
1733
+ * Deletes a file or moves it to trash
1734
+ */
1735
+ async delete(fileIdOrPath, permanent = false) {
1736
+ const fileId = await this.resolveId(fileIdOrPath);
1737
+ const raw = await this.getRawClient();
1738
+ if (permanent) {
1739
+ await withRetry(async () => {
1740
+ await raw.files.delete({ fileId, supportsAllDrives: true });
1741
+ });
1742
+ } else {
1743
+ await withRetry(async () => {
1744
+ await raw.files.update({
1745
+ fileId,
1746
+ requestBody: { trashed: true },
1747
+ supportsAllDrives: true
1748
+ });
1749
+ });
1750
+ }
1751
+ if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
1752
+ this.pathResolverInstance.invalidatePath(fileIdOrPath);
1753
+ }
1754
+ }
1755
+ /**
1756
+ * Move item to trash
1757
+ */
1758
+ async trash(fileIdOrPath) {
1759
+ return this.delete(fileIdOrPath, false);
1760
+ }
1761
+ /**
1762
+ * Restore item from trash
1763
+ */
1764
+ async restore(fileId) {
1765
+ const raw = await this.getRawClient();
1766
+ await withRetry(async () => {
1767
+ await raw.files.update({
1768
+ fileId,
1769
+ requestBody: { trashed: false },
1770
+ supportsAllDrives: true
1771
+ });
1772
+ });
1773
+ }
1774
+ /**
1775
+ * Move file to a different folder
1776
+ */
1777
+ async move(fileIdOrPath, newParentIdOrPath) {
1778
+ const fileId = await this.resolveId(fileIdOrPath);
1779
+ const newParentId = await this.resolveId(newParentIdOrPath, true);
1780
+ const raw = await this.getRawClient();
1781
+ const file = await this.getFile(fileId);
1782
+ const previousParents = (file.parents || []).join(",");
1783
+ const res = await withRetry(async () => {
1784
+ return await raw.files.update({
1785
+ fileId,
1786
+ addParents: newParentId,
1787
+ removeParents: previousParents,
1788
+ fields: "id, name, parents",
1789
+ supportsAllDrives: true
1790
+ });
1791
+ });
1792
+ if (this.pathResolverInstance) {
1793
+ this.pathResolverInstance.clearCache();
1794
+ }
1795
+ return res.data;
1796
+ }
1797
+ /**
1798
+ * Copies a file
1799
+ */
1800
+ async copy(fileIdOrPath, options = {}) {
1801
+ const fileId = await this.resolveId(fileIdOrPath);
1802
+ const raw = await this.getRawClient();
1803
+ let parentId = options.parent;
1804
+ if (parentId && parentId.startsWith("/")) {
1805
+ parentId = await this.mkdirp(parentId);
1806
+ }
1807
+ const requestBody = {};
1808
+ if (options.name) requestBody.name = options.name;
1809
+ if (parentId) requestBody.parents = [parentId];
1810
+ const res = await withRetry(async () => {
1811
+ return await raw.files.copy({
1812
+ fileId,
1813
+ requestBody,
1814
+ fields: "id, name, mimeType, webViewLink",
1815
+ supportsAllDrives: true
1816
+ });
1817
+ });
1818
+ return res.data;
1819
+ }
1820
+ /**
1821
+ * Renames a file
1822
+ */
1823
+ async rename(fileIdOrPath, newName) {
1824
+ const fileId = await this.resolveId(fileIdOrPath);
1825
+ const raw = await this.getRawClient();
1826
+ const res = await withRetry(async () => {
1827
+ return await raw.files.update({
1828
+ fileId,
1829
+ requestBody: { name: newName },
1830
+ fields: "id, name, mimeType",
1831
+ supportsAllDrives: true
1832
+ });
1833
+ });
1834
+ if (this.pathResolverInstance) {
1835
+ this.pathResolverInstance.clearCache();
1836
+ }
1837
+ return res.data;
1838
+ }
1839
+ // ==========================================
1840
+ // SHARING & PERMISSIONS
1841
+ // ==========================================
1842
+ /**
1843
+ * Share file with user, group, domain, or anyone
1844
+ */
1845
+ async share(fileIdOrPath, options = {}) {
1846
+ const fileId = await this.resolveId(fileIdOrPath);
1847
+ const raw = await this.getRawClient();
1848
+ const requestBody = {
1849
+ role: options.role || "reader",
1850
+ type: options.type || (options.emailAddress ? "user" : "anyone"),
1851
+ emailAddress: options.emailAddress,
1852
+ domain: options.domain
1853
+ };
1854
+ const res = await withRetry(async () => {
1855
+ return await raw.permissions.create({
1856
+ fileId,
1857
+ requestBody,
1858
+ sendNotificationEmail: options.sendNotificationEmail,
1859
+ emailMessage: options.emailMessage,
1860
+ transferOwnership: options.transferOwnership,
1861
+ supportsAllDrives: true,
1862
+ fields: "id, role, type, emailAddress"
1863
+ });
1864
+ });
1865
+ return res.data;
1866
+ }
1867
+ /**
1868
+ * Quickly make a file public to anyone with the link
1869
+ */
1870
+ async sharePublic(fileIdOrPath, role = "reader") {
1871
+ const fileId = await this.resolveId(fileIdOrPath);
1872
+ await this.share(fileId, { role, type: "anyone" });
1873
+ const file = await this.getFile(fileId);
1874
+ return {
1875
+ fileId,
1876
+ previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,
1877
+ directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`
1878
+ };
1879
+ }
1880
+ /**
1881
+ * Returns sharing links for a file
1882
+ */
1883
+ async getShareableLink(fileIdOrPath) {
1884
+ const fileId = await this.resolveId(fileIdOrPath);
1885
+ const file = await this.getFile(fileId);
1886
+ return {
1887
+ previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,
1888
+ directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`
1889
+ };
1890
+ }
1891
+ // ==========================================
1892
+ // QUERY BUILDER
1893
+ // ==========================================
1894
+ /**
1895
+ * Returns a fluent search query builder
1896
+ */
1897
+ query() {
1898
+ if (!this.driveClient) {
1899
+ throw new Error("DriveKit not initialized. Call await drive.init() first, or use an async method.");
1900
+ }
1901
+ return new DriveQueryBuilder(this.driveClient);
1902
+ }
1903
+ // ==========================================
1904
+ // FOLDER SYNC & BATCH UPLOAD
1905
+ // ==========================================
1906
+ /**
1907
+ * Recursively uploads a local folder to a Google Drive path with high concurrency
1908
+ */
1909
+ async syncFolder(localDir, remotePathOrId, options = {}) {
1910
+ await this.init();
1911
+ const startTime = Date.now();
1912
+ const concurrency = options.concurrency || this.options.concurrency || 4;
1913
+ const pool = new ConcurrencyPool(concurrency);
1914
+ const targetFolderId = await this.resolveId(remotePathOrId, true);
1915
+ const result = {
1916
+ uploaded: [],
1917
+ skipped: [],
1918
+ failed: [],
1919
+ totalBytes: 0,
1920
+ durationMs: 0
1921
+ };
1922
+ const collectFiles = async (dir, base) => {
1923
+ const entries = await fs5.promises.readdir(dir, { withFileTypes: true });
1924
+ const files = [];
1925
+ for (const entry of entries) {
1926
+ const fullPath = path4.join(dir, entry.name);
1927
+ const relPath = path4.join(base, entry.name);
1928
+ if (entry.isDirectory()) {
1929
+ const sub = await collectFiles(fullPath, relPath);
1930
+ files.push(...sub);
1931
+ } else if (entry.isFile()) {
1932
+ const stat = await fs5.promises.stat(fullPath);
1933
+ files.push({ fullPath, relPath, size: stat.size });
1934
+ }
1935
+ }
1936
+ return files;
1937
+ };
1938
+ const allFiles = await collectFiles(localDir, "");
1939
+ const remoteDirCache = /* @__PURE__ */ new Map();
1940
+ remoteDirCache.set("", targetFolderId);
1941
+ const ensureRemoteSubdir = async (relDir) => {
1942
+ if (remoteDirCache.has(relDir)) {
1943
+ return remoteDirCache.get(relDir);
1944
+ }
1945
+ const parts = relDir.split(path4.sep).filter(Boolean);
1946
+ let currentParent = targetFolderId;
1947
+ let currentRel = "";
1948
+ for (const part of parts) {
1949
+ currentRel = currentRel ? path4.join(currentRel, part) : part;
1950
+ if (remoteDirCache.has(currentRel)) {
1951
+ currentParent = remoteDirCache.get(currentRel);
1952
+ continue;
1953
+ }
1954
+ const existing = await this.query().inFolder(currentParent).nameEquals(part).isFolder().notTrashed().first();
1955
+ if (existing?.id) {
1956
+ currentParent = existing.id;
1957
+ } else {
1958
+ const raw = await this.getRawClient();
1959
+ const created = await withRetry(async () => {
1960
+ return await raw.files.create({
1961
+ requestBody: {
1962
+ name: part,
1963
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
1964
+ parents: [currentParent]
1965
+ },
1966
+ fields: "id",
1967
+ supportsAllDrives: true
1968
+ });
1969
+ });
1970
+ currentParent = created.data.id;
1971
+ }
1972
+ remoteDirCache.set(currentRel, currentParent);
1973
+ }
1974
+ return currentParent;
1975
+ };
1976
+ await pool.map(allFiles, async (fileItem) => {
1977
+ try {
1978
+ const relDir = path4.dirname(fileItem.relPath);
1979
+ const fileName = path4.basename(fileItem.relPath);
1980
+ const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
1981
+ if (options.onFileStart) {
1982
+ options.onFileStart(fileItem.fullPath, fileItem.relPath);
1983
+ }
1984
+ const uploadedFile = await this.upload({
1985
+ source: fileItem.fullPath,
1986
+ name: fileName,
1987
+ parent: parentFolderId,
1988
+ overwrite: options.overwrite ?? false
1989
+ });
1990
+ result.uploaded.push({
1991
+ localPath: fileItem.fullPath,
1992
+ fileId: uploadedFile.id,
1993
+ name: fileName
1994
+ });
1995
+ result.totalBytes += fileItem.size;
1996
+ if (options.onFileComplete) {
1997
+ options.onFileComplete(fileItem.fullPath, uploadedFile.id);
1998
+ }
1999
+ } catch (err) {
2000
+ result.failed.push({
2001
+ localPath: fileItem.fullPath,
2002
+ error: err
2003
+ });
2004
+ }
2005
+ });
2006
+ result.durationMs = Date.now() - startTime;
2007
+ return result;
2008
+ }
2009
+ // ==========================================
2010
+ // STORAGE & QUOTA
2011
+ // ==========================================
2012
+ /**
2013
+ * Retrieves Google Drive storage quota usage and limits
2014
+ */
2015
+ async getStorageQuota() {
2016
+ const raw = await this.getRawClient();
2017
+ const res = await withRetry(async () => {
2018
+ return await raw.about.get({
2019
+ fields: "storageQuota, user"
2020
+ });
2021
+ });
2022
+ const quota = res.data.storageQuota || {};
2023
+ const limit = quota.limit ? parseInt(quota.limit, 10) : null;
2024
+ const usage = quota.usage ? parseInt(quota.usage, 10) : 0;
2025
+ const usageInDrive = quota.usageInDrive ? parseInt(quota.usageInDrive, 10) : 0;
2026
+ const usageInDriveTrash = quota.usageInDriveTrash ? parseInt(quota.usageInDriveTrash, 10) : 0;
2027
+ const percentUsed = limit && limit > 0 ? Math.round(usage / limit * 1e3) / 10 : null;
2028
+ return {
2029
+ user: res.data.user,
2030
+ limit,
2031
+ usage,
2032
+ usageInDrive,
2033
+ usageInDriveTrash,
2034
+ percentUsed,
2035
+ formattedUsage: formatBytes(usage),
2036
+ formattedLimit: limit ? formatBytes(limit) : "Unlimited"
2037
+ };
2038
+ }
2039
+ // ==========================================
2040
+ // CHANGE WATCHER (REAL-TIME EVENTS)
2041
+ // ==========================================
2042
+ /**
2043
+ * Watches Google Drive or a specific folder for real-time changes, creations, and deletions
2044
+ */
2045
+ async watch(folderIdOrPath, options = {}) {
2046
+ await this.init();
2047
+ let folderId = void 0;
2048
+ if (folderIdOrPath && folderIdOrPath !== "/") {
2049
+ folderId = await this.resolveId(folderIdOrPath);
2050
+ }
2051
+ const watcher = new DriveWatcher(this.driveClient, {
2052
+ ...options,
2053
+ folderId
2054
+ });
2055
+ await watcher.start();
2056
+ return watcher;
2057
+ }
2058
+ // ==========================================
2059
+ // STORAGE CLEANER & DUPLICATE FINDER
2060
+ // ==========================================
2061
+ /**
2062
+ * Finds the largest files consuming Google Drive storage
2063
+ */
2064
+ async findLargestFiles(limit = 10) {
2065
+ await this.init();
2066
+ const cleaner = new StorageCleaner(this.driveClient);
2067
+ return await cleaner.findLargestFiles(limit);
2068
+ }
2069
+ /**
2070
+ * Finds duplicate files (by MD5 hash or exact file name)
2071
+ */
2072
+ async findDuplicates(options) {
2073
+ await this.init();
2074
+ const cleaner = new StorageCleaner(this.driveClient);
2075
+ return await cleaner.findDuplicates(options);
2076
+ }
2077
+ /**
2078
+ * Empties the entire trash bin in Google Drive
2079
+ */
2080
+ async emptyTrash() {
2081
+ await this.init();
2082
+ const cleaner = new StorageCleaner(this.driveClient);
2083
+ await cleaner.emptyTrash();
2084
+ }
2085
+ // ==========================================
2086
+ // SMART PULL & TWO-WAY SYNC
2087
+ // ==========================================
2088
+ /**
2089
+ * Pulls (downloads) an entire remote Google Drive directory down to a local folder with MD5 deduplication
2090
+ */
2091
+ async pull(remoteFolderIdOrPath, localDestinationDir, options = {}) {
2092
+ await this.init();
2093
+ const folderId = await this.resolveId(remoteFolderIdOrPath);
2094
+ const engine = new SmartSyncEngine(this.driveClient);
2095
+ return await engine.pullFolder(folderId, localDestinationDir, options);
2096
+ }
2097
+ /**
2098
+ * Calculates local file MD5 hash for integrity and deduplication checks
2099
+ */
2100
+ static async calculateFileMd5(filePath) {
2101
+ return await calculateFileMd5(filePath);
2102
+ }
2103
+ /**
2104
+ * Interactive 1-click browser OAuth login flow
2105
+ */
2106
+ static async loginWithBrowser(options) {
2107
+ return await loginWithBrowser(options);
2108
+ }
2109
+ };
2110
+
2111
+ // src/index.ts
2112
+ async function createDrive(options) {
2113
+ const instance = new DriveKit(options);
2114
+ await instance.init();
2115
+ return instance;
2116
+ }
2117
+ var index_default = DriveKit;
2118
+ export {
2119
+ ConcurrencyPool,
2120
+ DEFAULT_CHUNK_SIZE,
2121
+ DEFAULT_EXPORT_MIMES,
2122
+ DEFAULT_SCOPES,
2123
+ Downloader,
2124
+ DriveAuthError,
2125
+ DriveAuthenticator,
2126
+ DriveKit,
2127
+ DriveKitError,
2128
+ DriveNotFoundError,
2129
+ DriveQueryBuilder,
2130
+ DriveRateLimitError,
2131
+ DriveUploadError,
2132
+ DriveWatcher,
2133
+ GOOGLE_WORKSPACE_MIME_TYPES,
2134
+ MIN_CHUNK_SIZE,
2135
+ MULTIPART_THRESHOLD,
2136
+ PathResolver,
2137
+ ResumableUploader,
2138
+ SmartSyncEngine,
2139
+ StorageCleaner,
2140
+ calculateFileMd5,
2141
+ createDrive,
2142
+ index_default as default,
2143
+ formatBytes,
2144
+ formatDuration,
2145
+ formatSpeed,
2146
+ getExtensionForMime,
2147
+ isGoogleWorkspaceDoc,
2148
+ isRetryableError,
2149
+ loginWithBrowser,
2150
+ lookupMimeType,
2151
+ withRetry
2152
+ };
2153
+ //# sourceMappingURL=index.js.map