drivekit 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.cjs ADDED
@@ -0,0 +1,2645 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __esm = (fn, res) => function __init() {
9
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
10
+ };
11
+ var __export = (target, all) => {
12
+ for (var name in all)
13
+ __defProp(target, name, { get: all[name], enumerable: true });
14
+ };
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
32
+
33
+ // node_modules/tsup/assets/cjs_shims.js
34
+ var init_cjs_shims = __esm({
35
+ "node_modules/tsup/assets/cjs_shims.js"() {
36
+ "use strict";
37
+ }
38
+ });
39
+
40
+ // src/errors.ts
41
+ var DriveKitError, DriveAuthError, DriveNotFoundError, DriveRateLimitError, DriveUploadError;
42
+ var init_errors = __esm({
43
+ "src/errors.ts"() {
44
+ "use strict";
45
+ init_cjs_shims();
46
+ DriveKitError = class extends Error {
47
+ code;
48
+ originalError;
49
+ constructor(message, code = "DRIVEKIT_ERROR", originalError) {
50
+ super(message);
51
+ this.name = "DriveKitError";
52
+ this.code = code;
53
+ this.originalError = originalError;
54
+ Object.setPrototypeOf(this, new.target.prototype);
55
+ }
56
+ };
57
+ DriveAuthError = class extends DriveKitError {
58
+ constructor(message, originalError) {
59
+ super(message, "AUTH_ERROR", originalError);
60
+ this.name = "DriveAuthError";
61
+ }
62
+ };
63
+ DriveNotFoundError = class extends DriveKitError {
64
+ resourceIdOrPath;
65
+ constructor(resourceIdOrPath, message) {
66
+ super(message || `Resource not found: "${resourceIdOrPath}"`, "NOT_FOUND");
67
+ this.name = "DriveNotFoundError";
68
+ this.resourceIdOrPath = resourceIdOrPath;
69
+ }
70
+ };
71
+ DriveRateLimitError = class extends DriveKitError {
72
+ retryAfterSeconds;
73
+ constructor(message, retryAfterSeconds, originalError) {
74
+ super(message, "RATE_LIMIT_EXCEEDED", originalError);
75
+ this.name = "DriveRateLimitError";
76
+ this.retryAfterSeconds = retryAfterSeconds;
77
+ }
78
+ };
79
+ DriveUploadError = class extends DriveKitError {
80
+ bytesUploaded;
81
+ totalBytes;
82
+ constructor(message, bytesUploaded, totalBytes, originalError) {
83
+ super(message, "UPLOAD_ERROR", originalError);
84
+ this.name = "DriveUploadError";
85
+ this.bytesUploaded = bytesUploaded;
86
+ this.totalBytes = totalBytes;
87
+ }
88
+ };
89
+ }
90
+ });
91
+
92
+ // src/auth/authenticator.ts
93
+ var import_node_fs, import_drive, DEFAULT_SCOPES, DriveAuthenticator;
94
+ var init_authenticator = __esm({
95
+ "src/auth/authenticator.ts"() {
96
+ "use strict";
97
+ init_cjs_shims();
98
+ import_node_fs = __toESM(require("fs"), 1);
99
+ import_drive = require("@googleapis/drive");
100
+ init_errors();
101
+ DEFAULT_SCOPES = [
102
+ "https://www.googleapis.com/auth/drive"
103
+ ];
104
+ DriveAuthenticator = class {
105
+ config;
106
+ authClient = null;
107
+ constructor(config = {}) {
108
+ this.config = config;
109
+ }
110
+ /**
111
+ * Initializes and returns an authenticated Google client
112
+ */
113
+ async getAuthClient() {
114
+ if (this.authClient) {
115
+ return this.authClient;
116
+ }
117
+ try {
118
+ const scopes = this.config.scopes || DEFAULT_SCOPES;
119
+ if (this.config.accessToken) {
120
+ const oauth2Client = new import_drive.auth.OAuth2();
121
+ oauth2Client.setCredentials({ access_token: this.config.accessToken });
122
+ this.authClient = oauth2Client;
123
+ return this.authClient;
124
+ }
125
+ if (this.config.oauth2Client) {
126
+ this.authClient = this.config.oauth2Client;
127
+ return this.authClient;
128
+ }
129
+ if (this.config.oauth) {
130
+ const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
131
+ const oauth2Client = new import_drive.auth.OAuth2(clientId, clientSecret, redirectUri);
132
+ if (refreshToken) {
133
+ oauth2Client.setCredentials({ refresh_token: refreshToken });
134
+ }
135
+ this.authClient = oauth2Client;
136
+ return this.authClient;
137
+ }
138
+ const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
139
+ if (keyFile) {
140
+ if (!import_node_fs.default.existsSync(keyFile)) {
141
+ throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
142
+ }
143
+ const auth2 = new import_drive.auth.GoogleAuth({
144
+ keyFile,
145
+ scopes
146
+ });
147
+ this.authClient = auth2;
148
+ return this.authClient;
149
+ }
150
+ const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
151
+ if (creds) {
152
+ const auth2 = new import_drive.auth.GoogleAuth({
153
+ credentials: creds,
154
+ scopes
155
+ });
156
+ this.authClient = auth2;
157
+ return this.authClient;
158
+ }
159
+ const auth = new import_drive.auth.GoogleAuth({ scopes });
160
+ this.authClient = auth;
161
+ return this.authClient;
162
+ } catch (err) {
163
+ if (err instanceof DriveAuthError) throw err;
164
+ throw new DriveAuthError(`Failed to authenticate with Google Drive: ${err.message}`, err);
165
+ }
166
+ }
167
+ /**
168
+ * Helper to generate OAuth2 Consent URL for user authorization
169
+ */
170
+ static generateAuthUrl(options) {
171
+ const oauth2Client = new import_drive.auth.OAuth2(
172
+ options.clientId,
173
+ options.clientSecret,
174
+ options.redirectUri || "urn:ietf:wg:oauth:2.0:oob"
175
+ );
176
+ return oauth2Client.generateAuthUrl({
177
+ access_type: "offline",
178
+ prompt: "consent",
179
+ scope: options.scopes || DEFAULT_SCOPES
180
+ });
181
+ }
182
+ /**
183
+ * Helper to exchange authorization code for tokens
184
+ */
185
+ static async exchangeCodeForTokens(options) {
186
+ const oauth2Client = new import_drive.auth.OAuth2(
187
+ options.clientId,
188
+ options.clientSecret,
189
+ options.redirectUri || "urn:ietf:wg:oauth:2.0:oob"
190
+ );
191
+ const { tokens } = await oauth2Client.getToken(options.code);
192
+ return tokens;
193
+ }
194
+ };
195
+ }
196
+ });
197
+
198
+ // src/utils/mime.ts
199
+ function lookupMimeType(filePath) {
200
+ const detected = import_mime_types.default.lookup(filePath);
201
+ return detected || "application/octet-stream";
202
+ }
203
+ function getExtensionForMime(mimeType) {
204
+ const ext = import_mime_types.default.extension(mimeType);
205
+ return ext ? `.${ext}` : "";
206
+ }
207
+ function isGoogleWorkspaceDoc(mimeType) {
208
+ if (!mimeType) return false;
209
+ return mimeType.startsWith("application/vnd.google-apps.") && mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.FOLDER && mimeType !== GOOGLE_WORKSPACE_MIME_TYPES.SHORTCUT;
210
+ }
211
+ var import_mime_types, GOOGLE_WORKSPACE_MIME_TYPES, DEFAULT_EXPORT_MIMES;
212
+ var init_mime = __esm({
213
+ "src/utils/mime.ts"() {
214
+ "use strict";
215
+ init_cjs_shims();
216
+ import_mime_types = __toESM(require("mime-types"), 1);
217
+ GOOGLE_WORKSPACE_MIME_TYPES = {
218
+ DOCUMENT: "application/vnd.google-apps.document",
219
+ SPREADSHEET: "application/vnd.google-apps.spreadsheet",
220
+ PRESENTATION: "application/vnd.google-apps.presentation",
221
+ DRAWING: "application/vnd.google-apps.drawing",
222
+ FORM: "application/vnd.google-apps.form",
223
+ SCRIPT: "application/vnd.google-apps.script",
224
+ FOLDER: "application/vnd.google-apps.folder",
225
+ SHORTCUT: "application/vnd.google-apps.shortcut"
226
+ };
227
+ DEFAULT_EXPORT_MIMES = {
228
+ [GOOGLE_WORKSPACE_MIME_TYPES.DOCUMENT]: {
229
+ mimeType: "application/pdf",
230
+ extension: ".pdf"
231
+ },
232
+ [GOOGLE_WORKSPACE_MIME_TYPES.SPREADSHEET]: {
233
+ mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
234
+ extension: ".xlsx"
235
+ },
236
+ [GOOGLE_WORKSPACE_MIME_TYPES.PRESENTATION]: {
237
+ mimeType: "application/pdf",
238
+ extension: ".pdf"
239
+ },
240
+ [GOOGLE_WORKSPACE_MIME_TYPES.DRAWING]: {
241
+ mimeType: "image/png",
242
+ extension: ".png"
243
+ }
244
+ };
245
+ }
246
+ });
247
+
248
+ // src/utils/retry.ts
249
+ function isRetryableError(error) {
250
+ if (!error) return false;
251
+ const status = error.status || error.statusCode || error.response?.status;
252
+ if (status && DEFAULT_RETRYABLE_STATUSES.has(status)) {
253
+ return true;
254
+ }
255
+ const message = (error.message || "").toLowerCase();
256
+ 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")) {
257
+ return true;
258
+ }
259
+ const errors = error.errors || error.response?.data?.error?.errors;
260
+ if (Array.isArray(errors)) {
261
+ for (const e of errors) {
262
+ if (e.reason === "rateLimitExceeded" || e.reason === "userRateLimitExceeded" || e.reason === "backendError") {
263
+ return true;
264
+ }
265
+ }
266
+ }
267
+ return false;
268
+ }
269
+ async function withRetry(fn, options = {}) {
270
+ const maxRetries = options.maxRetries ?? 5;
271
+ const baseDelayMs = options.baseDelayMs ?? 1e3;
272
+ const maxDelayMs = options.maxDelayMs ?? 32e3;
273
+ const shouldRetry = options.shouldRetry ?? isRetryableError;
274
+ let attempt = 0;
275
+ while (true) {
276
+ try {
277
+ return await fn();
278
+ } catch (error) {
279
+ attempt++;
280
+ if (attempt > maxRetries || !shouldRetry(error)) {
281
+ if (error?.status === 429 || error?.response?.status === 429) {
282
+ throw new DriveRateLimitError(
283
+ `Drive API rate limit exceeded after ${attempt} attempts.`,
284
+ void 0,
285
+ error
286
+ );
287
+ }
288
+ throw error;
289
+ }
290
+ const calculatedDelay = Math.min(maxDelayMs, baseDelayMs * Math.pow(2, attempt));
291
+ const jitterDelay = Math.floor(Math.random() * calculatedDelay);
292
+ await new Promise((resolve) => setTimeout(resolve, jitterDelay));
293
+ }
294
+ }
295
+ }
296
+ var DEFAULT_RETRYABLE_STATUSES;
297
+ var init_retry = __esm({
298
+ "src/utils/retry.ts"() {
299
+ "use strict";
300
+ init_cjs_shims();
301
+ init_errors();
302
+ DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
303
+ }
304
+ });
305
+
306
+ // src/core/path-resolver.ts
307
+ var PathResolver;
308
+ var init_path_resolver = __esm({
309
+ "src/core/path-resolver.ts"() {
310
+ "use strict";
311
+ init_cjs_shims();
312
+ init_mime();
313
+ init_errors();
314
+ init_retry();
315
+ PathResolver = class {
316
+ drive;
317
+ rootFolderId;
318
+ cache = /* @__PURE__ */ new Map();
319
+ cacheTTL;
320
+ enableCache;
321
+ constructor(drive2, rootFolderId = "root", options) {
322
+ this.drive = drive2;
323
+ this.rootFolderId = rootFolderId;
324
+ this.enableCache = options?.enableCache ?? true;
325
+ this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
326
+ }
327
+ /**
328
+ * Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
329
+ */
330
+ normalizePath(rawPath) {
331
+ if (!rawPath || rawPath.trim() === "" || rawPath === "/") {
332
+ return "/";
333
+ }
334
+ const parts = rawPath.split("/").map((p) => p.trim()).filter(Boolean);
335
+ return `/${parts.join("/")}`;
336
+ }
337
+ /**
338
+ * Gets cache key for a path
339
+ */
340
+ getCacheKey(path6) {
341
+ return `${this.rootFolderId}:${this.normalizePath(path6)}`;
342
+ }
343
+ /**
344
+ * Clears the path cache
345
+ */
346
+ clearCache() {
347
+ this.cache.clear();
348
+ }
349
+ /**
350
+ * Invalidate a single path from cache
351
+ */
352
+ invalidatePath(path6) {
353
+ const key = this.getCacheKey(path6);
354
+ this.cache.delete(key);
355
+ }
356
+ /**
357
+ * Resolves a path to a Google Drive item (file or folder).
358
+ * If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
359
+ */
360
+ async resolve(virtualPath, options = {}) {
361
+ const norm = this.normalizePath(virtualPath);
362
+ if (norm === "/") {
363
+ return {
364
+ id: this.rootFolderId,
365
+ name: "root",
366
+ isFolder: true,
367
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
368
+ };
369
+ }
370
+ if (this.enableCache) {
371
+ const cached = this.cache.get(this.getCacheKey(norm));
372
+ if (cached && cached.expiresAt > Date.now()) {
373
+ return {
374
+ id: cached.id,
375
+ name: cached.name,
376
+ isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
377
+ mimeType: cached.mimeType
378
+ };
379
+ }
380
+ }
381
+ const segments = norm.split("/").filter(Boolean);
382
+ let currentParentId = this.rootFolderId;
383
+ let currentPath = "";
384
+ for (let i = 0; i < segments.length; i++) {
385
+ const segment = segments[i];
386
+ const isLast = i === segments.length - 1;
387
+ currentPath += `/${segment}`;
388
+ if (this.enableCache) {
389
+ const cached = this.cache.get(this.getCacheKey(currentPath));
390
+ if (cached && cached.expiresAt > Date.now()) {
391
+ currentParentId = cached.id;
392
+ if (isLast) {
393
+ return {
394
+ id: cached.id,
395
+ name: cached.name,
396
+ isFolder: cached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
397
+ mimeType: cached.mimeType
398
+ };
399
+ }
400
+ continue;
401
+ }
402
+ }
403
+ const escapedName = segment.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
404
+ const q = `'${currentParentId}' in parents and name = '${escapedName}' and trashed = false`;
405
+ const response = await withRetry(async () => {
406
+ return await this.drive.files.list({
407
+ q,
408
+ fields: "files(id, name, mimeType, parents)",
409
+ pageSize: 1,
410
+ spaces: "drive",
411
+ supportsAllDrives: true,
412
+ includeItemsFromAllDrives: true
413
+ });
414
+ });
415
+ let file = response.data.files?.[0];
416
+ if (!file && currentParentId === this.rootFolderId) {
417
+ const sharedQ = `name = '${escapedName}' and trashed = false`;
418
+ const sharedResponse = await withRetry(async () => {
419
+ return await this.drive.files.list({
420
+ q: sharedQ,
421
+ fields: "files(id, name, mimeType, parents)",
422
+ pageSize: 1,
423
+ spaces: "drive",
424
+ supportsAllDrives: true,
425
+ includeItemsFromAllDrives: true
426
+ });
427
+ });
428
+ file = sharedResponse.data.files?.[0];
429
+ }
430
+ if (file && file.id) {
431
+ currentParentId = file.id;
432
+ if (this.enableCache) {
433
+ this.cache.set(this.getCacheKey(currentPath), {
434
+ id: file.id,
435
+ name: file.name || segment,
436
+ mimeType: file.mimeType || "",
437
+ expiresAt: Date.now() + this.cacheTTL
438
+ });
439
+ }
440
+ if (isLast) {
441
+ return {
442
+ id: file.id,
443
+ name: file.name || segment,
444
+ isFolder: file.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
445
+ mimeType: file.mimeType || ""
446
+ };
447
+ }
448
+ } else {
449
+ if (options.createIfMissing) {
450
+ const createRes = await withRetry(async () => {
451
+ return await this.drive.files.create({
452
+ requestBody: {
453
+ name: segment,
454
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
455
+ parents: [currentParentId]
456
+ },
457
+ fields: "id, name, mimeType",
458
+ supportsAllDrives: true
459
+ });
460
+ });
461
+ const newFolder = createRes.data;
462
+ if (!newFolder.id) {
463
+ throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
464
+ }
465
+ currentParentId = newFolder.id;
466
+ if (this.enableCache) {
467
+ this.cache.set(this.getCacheKey(currentPath), {
468
+ id: newFolder.id,
469
+ name: segment,
470
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
471
+ expiresAt: Date.now() + this.cacheTTL
472
+ });
473
+ }
474
+ if (isLast) {
475
+ return {
476
+ id: newFolder.id,
477
+ name: segment,
478
+ isFolder: true,
479
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
480
+ };
481
+ }
482
+ } else {
483
+ throw new DriveNotFoundError(
484
+ virtualPath,
485
+ `Path segment "${segment}" not found in path "${virtualPath}" under folder ID "${currentParentId}"`
486
+ );
487
+ }
488
+ }
489
+ }
490
+ throw new DriveNotFoundError(virtualPath);
491
+ }
492
+ /**
493
+ * Ensures that a directory structure exists (like mkdir -p).
494
+ */
495
+ async mkdirp(virtualPath) {
496
+ const res = await this.resolve(virtualPath, { createIfMissing: true });
497
+ return res.id;
498
+ }
499
+ };
500
+ }
501
+ });
502
+
503
+ // src/utils/format.ts
504
+ function formatBytes(bytes, decimals = 2) {
505
+ if (bytes === 0) return "0 B";
506
+ const k = 1024;
507
+ const dm = decimals < 0 ? 0 : decimals;
508
+ const sizes = ["B", "KB", "MB", "GB", "TB", "PB"];
509
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
510
+ return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`;
511
+ }
512
+ function formatSpeed(bytesPerSecond) {
513
+ return `${formatBytes(bytesPerSecond)}/s`;
514
+ }
515
+ var init_format = __esm({
516
+ "src/utils/format.ts"() {
517
+ "use strict";
518
+ init_cjs_shims();
519
+ }
520
+ });
521
+
522
+ // src/core/resumable-uploader.ts
523
+ var import_node_fs2, import_node_path, MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
524
+ var init_resumable_uploader = __esm({
525
+ "src/core/resumable-uploader.ts"() {
526
+ "use strict";
527
+ init_cjs_shims();
528
+ import_node_fs2 = __toESM(require("fs"), 1);
529
+ import_node_path = __toESM(require("path"), 1);
530
+ init_errors();
531
+ init_format();
532
+ init_mime();
533
+ init_retry();
534
+ MIN_CHUNK_SIZE = 256 * 1024;
535
+ DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
536
+ MULTIPART_THRESHOLD = 5 * 1024 * 1024;
537
+ ResumableUploader = class {
538
+ drive;
539
+ defaultChunkSize;
540
+ constructor(drive2, defaultChunkSize = DEFAULT_CHUNK_SIZE) {
541
+ this.drive = drive2;
542
+ this.defaultChunkSize = Math.max(
543
+ MIN_CHUNK_SIZE,
544
+ Math.floor(defaultChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE
545
+ );
546
+ }
547
+ /**
548
+ * Uploads a file with automatic selection of direct multipart (small files)
549
+ * or resumable chunked upload with progress events (large files).
550
+ */
551
+ async upload(options) {
552
+ if (typeof options.source === "string") {
553
+ return await this.uploadFromPath(options.source, options);
554
+ } else if (Buffer.isBuffer(options.source)) {
555
+ return await this.uploadFromBuffer(options.source, options);
556
+ } else {
557
+ return await this.uploadFromStream(options.source, options);
558
+ }
559
+ }
560
+ /**
561
+ * Upload from local file path with memory-efficient chunked streaming
562
+ */
563
+ async uploadFromPath(filePath, options) {
564
+ if (!import_node_fs2.default.existsSync(filePath)) {
565
+ throw new Error(`File does not exist at path: "${filePath}"`);
566
+ }
567
+ const stat = await import_node_fs2.default.promises.stat(filePath);
568
+ const totalBytes = stat.size;
569
+ const fileName = options.name || import_node_path.default.basename(filePath);
570
+ const mimeType = options.mimeType || lookupMimeType(filePath);
571
+ return await this.chunkedUpload({
572
+ filePath,
573
+ totalBytes,
574
+ fileName,
575
+ mimeType,
576
+ options
577
+ });
578
+ }
579
+ /**
580
+ * Upload from in-memory Buffer
581
+ */
582
+ async uploadFromBuffer(buffer, options) {
583
+ const totalBytes = buffer.length;
584
+ const fileName = options.name || "untitled";
585
+ const mimeType = options.mimeType || "application/octet-stream";
586
+ return await this.chunkedUploadBuffer({
587
+ buffer,
588
+ totalBytes,
589
+ fileName,
590
+ mimeType,
591
+ options
592
+ });
593
+ }
594
+ /**
595
+ * Upload from generic Readable Stream
596
+ */
597
+ async uploadFromStream(stream, options) {
598
+ const fileName = options.name || "untitled";
599
+ const mimeType = options.mimeType || "application/octet-stream";
600
+ return await this.directUpload(stream, {
601
+ ...options,
602
+ name: fileName,
603
+ mimeType
604
+ });
605
+ }
606
+ /**
607
+ * Fast direct upload using googleapis multipart
608
+ */
609
+ async directUpload(stream, options) {
610
+ const requestBody = {
611
+ name: options.name,
612
+ mimeType: options.mimeType,
613
+ description: options.description,
614
+ properties: options.properties,
615
+ appProperties: options.appProperties
616
+ };
617
+ if (options.parent) {
618
+ requestBody.parents = [options.parent];
619
+ }
620
+ const res = await withRetry(async () => {
621
+ return await this.drive.files.create({
622
+ requestBody,
623
+ media: {
624
+ mimeType: options.mimeType,
625
+ body: stream
626
+ },
627
+ fields: "id, name, mimeType, size, webViewLink, webContentLink, createdTime, modifiedTime",
628
+ supportsAllDrives: true
629
+ });
630
+ });
631
+ return res.data;
632
+ }
633
+ /**
634
+ * Chunked resumable upload for local files with low memory footprint
635
+ */
636
+ async chunkedUpload(params) {
637
+ const { filePath, totalBytes, fileName, mimeType, options } = params;
638
+ const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
639
+ const sessionUrl = await this.initiateResumableSession({
640
+ fileName,
641
+ mimeType,
642
+ totalBytes,
643
+ parent: options.parent,
644
+ description: options.description,
645
+ properties: options.properties,
646
+ appProperties: options.appProperties
647
+ });
648
+ const fd = await import_node_fs2.default.promises.open(filePath, "r");
649
+ let bytesSent = 0;
650
+ const startTime = Date.now();
651
+ const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
652
+ let chunkIndex = 0;
653
+ try {
654
+ while (bytesSent < totalBytes) {
655
+ chunkIndex++;
656
+ const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
657
+ const buffer = Buffer.alloc(currentChunkSize);
658
+ await fd.read(buffer, 0, currentChunkSize, bytesSent);
659
+ const rangeStart = bytesSent;
660
+ const rangeEnd = bytesSent + currentChunkSize - 1;
661
+ const chunkResult = await this.uploadChunkWithRetry({
662
+ sessionUrl,
663
+ buffer,
664
+ rangeStart,
665
+ rangeEnd,
666
+ totalBytes
667
+ });
668
+ bytesSent += currentChunkSize;
669
+ if (options.onProgress) {
670
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
671
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
672
+ const remainingBytes = totalBytes - bytesSent;
673
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
674
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
675
+ options.onProgress({
676
+ bytesSent,
677
+ totalBytes,
678
+ percentage,
679
+ bytesPerSecond,
680
+ speedFormatted: formatSpeed(bytesPerSecond),
681
+ estimatedTimeRemainingSeconds,
682
+ chunkIndex,
683
+ totalChunks
684
+ });
685
+ }
686
+ if (chunkResult.isComplete && chunkResult.file) {
687
+ return chunkResult.file;
688
+ }
689
+ }
690
+ } finally {
691
+ await fd.close();
692
+ }
693
+ throw new DriveUploadError("Resumable upload loop ended without completion response", bytesSent, totalBytes);
694
+ }
695
+ /**
696
+ * Chunked resumable upload for memory buffers
697
+ */
698
+ async chunkedUploadBuffer(params) {
699
+ const { buffer, totalBytes, fileName, mimeType, options } = params;
700
+ const chunkSize = options.chunkSize ? Math.max(MIN_CHUNK_SIZE, Math.floor(options.chunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE) : this.defaultChunkSize;
701
+ const sessionUrl = await this.initiateResumableSession({
702
+ fileName,
703
+ mimeType,
704
+ totalBytes,
705
+ parent: options.parent,
706
+ description: options.description,
707
+ properties: options.properties,
708
+ appProperties: options.appProperties
709
+ });
710
+ let bytesSent = 0;
711
+ const startTime = Date.now();
712
+ const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
713
+ let chunkIndex = 0;
714
+ while (bytesSent < totalBytes) {
715
+ chunkIndex++;
716
+ const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
717
+ const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
718
+ const rangeStart = bytesSent;
719
+ const rangeEnd = bytesSent + currentChunkSize - 1;
720
+ const chunkResult = await this.uploadChunkWithRetry({
721
+ sessionUrl,
722
+ buffer: chunk,
723
+ rangeStart,
724
+ rangeEnd,
725
+ totalBytes
726
+ });
727
+ bytesSent += currentChunkSize;
728
+ if (options.onProgress) {
729
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
730
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
731
+ const remainingBytes = totalBytes - bytesSent;
732
+ const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
733
+ const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
734
+ options.onProgress({
735
+ bytesSent,
736
+ totalBytes,
737
+ percentage,
738
+ bytesPerSecond,
739
+ speedFormatted: formatSpeed(bytesPerSecond),
740
+ estimatedTimeRemainingSeconds,
741
+ chunkIndex,
742
+ totalChunks
743
+ });
744
+ }
745
+ if (chunkResult.isComplete && chunkResult.file) {
746
+ return chunkResult.file;
747
+ }
748
+ }
749
+ throw new DriveUploadError("Resumable buffer upload ended without completion", bytesSent, totalBytes);
750
+ }
751
+ /**
752
+ * Request an upload session URI from Google Drive API
753
+ */
754
+ async initiateResumableSession(meta) {
755
+ const authClient = this.drive.context._options.auth;
756
+ const headers = {
757
+ "X-Upload-Content-Type": meta.mimeType,
758
+ "X-Upload-Content-Length": meta.totalBytes.toString(),
759
+ "Content-Type": "application/json; charset=UTF-8"
760
+ };
761
+ const metadata = {
762
+ name: meta.fileName,
763
+ mimeType: meta.mimeType,
764
+ description: meta.description,
765
+ properties: meta.properties,
766
+ appProperties: meta.appProperties
767
+ };
768
+ if (meta.parent) {
769
+ metadata.parents = [meta.parent];
770
+ }
771
+ const res = await withRetry(async () => {
772
+ return await authClient.request({
773
+ url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
774
+ method: "POST",
775
+ headers,
776
+ data: metadata
777
+ });
778
+ });
779
+ const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
780
+ if (!sessionUrl) {
781
+ throw new DriveUploadError("Failed to initiate resumable upload session: No Location header in response");
782
+ }
783
+ return sessionUrl;
784
+ }
785
+ /**
786
+ * Upload a chunk with exponential backoff on network failures
787
+ */
788
+ async uploadChunkWithRetry(params) {
789
+ const { sessionUrl, buffer, rangeStart, rangeEnd, totalBytes } = params;
790
+ const authClient = this.drive.context._options.auth;
791
+ const headers = {
792
+ "Content-Length": buffer.length.toString(),
793
+ "Content-Range": `bytes ${rangeStart}-${rangeEnd}/${totalBytes}`
794
+ };
795
+ return await withRetry(async () => {
796
+ try {
797
+ const res = await authClient.request({
798
+ url: sessionUrl,
799
+ method: "PUT",
800
+ headers,
801
+ data: buffer,
802
+ validateStatus: (status) => status >= 200 && status < 300 || status === 308
803
+ });
804
+ if (res.status === 200 || res.status === 201) {
805
+ return { isComplete: true, file: res.data };
806
+ }
807
+ if (res.status === 308) {
808
+ return { isComplete: false };
809
+ }
810
+ throw new DriveUploadError(`Unexpected response status ${res.status} during chunk upload`);
811
+ } catch (err) {
812
+ if (err.status === 308) {
813
+ return { isComplete: false };
814
+ }
815
+ const msg = err.message || err.response?.data?.error?.message || "";
816
+ if (msg.includes("Service Accounts do not have storage quota") || msg.includes("storageQuotaExceeded")) {
817
+ throw new DriveUploadError(
818
+ "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.",
819
+ params.rangeStart,
820
+ params.totalBytes,
821
+ err
822
+ );
823
+ }
824
+ throw err;
825
+ }
826
+ });
827
+ }
828
+ };
829
+ }
830
+ });
831
+
832
+ // src/core/downloader.ts
833
+ var import_node_fs3, import_node_path2, import_promises, import_node_stream, Downloader;
834
+ var init_downloader = __esm({
835
+ "src/core/downloader.ts"() {
836
+ "use strict";
837
+ init_cjs_shims();
838
+ import_node_fs3 = __toESM(require("fs"), 1);
839
+ import_node_path2 = __toESM(require("path"), 1);
840
+ import_promises = require("stream/promises");
841
+ import_node_stream = require("stream");
842
+ init_mime();
843
+ init_format();
844
+ init_retry();
845
+ Downloader = class {
846
+ drive;
847
+ constructor(drive2) {
848
+ this.drive = drive2;
849
+ }
850
+ /**
851
+ * Downloads a file from Google Drive to local destination path or returns a readable stream.
852
+ */
853
+ async download(fileId, options = {}) {
854
+ const metaRes = await withRetry(async () => {
855
+ return await this.drive.files.get({
856
+ fileId,
857
+ fields: "id, name, mimeType, size",
858
+ supportsAllDrives: true
859
+ });
860
+ });
861
+ const file = metaRes.data;
862
+ const name = file.name || "downloaded-file";
863
+ const mimeType = file.mimeType || "application/octet-stream";
864
+ const totalBytes = file.size ? parseInt(file.size, 10) : void 0;
865
+ let downloadStream;
866
+ let finalFileName = name;
867
+ if (isGoogleWorkspaceDoc(mimeType)) {
868
+ const exportConfig = DEFAULT_EXPORT_MIMES[mimeType] || {
869
+ mimeType: "application/pdf",
870
+ extension: ".pdf"
871
+ };
872
+ const targetMime = options.exportMimeType || exportConfig.mimeType;
873
+ const ext = getExtensionForMime(targetMime) || exportConfig.extension;
874
+ if (!finalFileName.endsWith(ext)) {
875
+ finalFileName = `${finalFileName}${ext}`;
876
+ }
877
+ const res = await withRetry(async () => {
878
+ return await this.drive.files.export(
879
+ { fileId, mimeType: targetMime },
880
+ { responseType: "stream" }
881
+ );
882
+ });
883
+ downloadStream = res.data;
884
+ } else {
885
+ const res = await withRetry(async () => {
886
+ return await this.drive.files.get(
887
+ { fileId, alt: "media", supportsAllDrives: true },
888
+ { responseType: "stream" }
889
+ );
890
+ });
891
+ downloadStream = res.data;
892
+ }
893
+ let bytesRead = 0;
894
+ const startTime = Date.now();
895
+ const progressTracker = new import_node_stream.Transform({
896
+ transform(chunk, encoding, callback) {
897
+ bytesRead += chunk.length;
898
+ if (options.onProgress) {
899
+ const elapsedSecs = (Date.now() - startTime) / 1e3;
900
+ const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesRead / elapsedSecs) : 0;
901
+ const percentage = totalBytes ? Math.min(100, Math.round(bytesRead / totalBytes * 1e3) / 10) : void 0;
902
+ options.onProgress({
903
+ bytesRead,
904
+ totalBytes,
905
+ percentage,
906
+ bytesPerSecond,
907
+ speedFormatted: formatSpeed(bytesPerSecond)
908
+ });
909
+ }
910
+ callback(null, chunk);
911
+ }
912
+ });
913
+ const monitoredStream = downloadStream.pipe(progressTracker);
914
+ if (options.destination) {
915
+ let destPath = options.destination;
916
+ if (import_node_fs3.default.existsSync(destPath) && import_node_fs3.default.statSync(destPath).isDirectory()) {
917
+ destPath = import_node_path2.default.join(destPath, finalFileName);
918
+ }
919
+ await import_node_fs3.default.promises.mkdir(import_node_path2.default.dirname(destPath), { recursive: true });
920
+ const writeStream = import_node_fs3.default.createWriteStream(destPath);
921
+ await (0, import_promises.pipeline)(monitoredStream, writeStream);
922
+ return {
923
+ filePath: destPath,
924
+ name: finalFileName,
925
+ mimeType,
926
+ size: bytesRead
927
+ };
928
+ }
929
+ return {
930
+ stream: monitoredStream,
931
+ name: finalFileName,
932
+ mimeType,
933
+ size: totalBytes
934
+ };
935
+ }
936
+ };
937
+ }
938
+ });
939
+
940
+ // src/core/query-builder.ts
941
+ var DriveQueryBuilder;
942
+ var init_query_builder = __esm({
943
+ "src/core/query-builder.ts"() {
944
+ "use strict";
945
+ init_cjs_shims();
946
+ init_mime();
947
+ init_retry();
948
+ DriveQueryBuilder = class {
949
+ drive;
950
+ conditions = [];
951
+ orderClauses = [];
952
+ limitNumber = 100;
953
+ requestedFields = "nextPageToken, files(id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, shared)";
954
+ spaces = "drive";
955
+ constructor(drive2) {
956
+ this.drive = drive2;
957
+ }
958
+ /**
959
+ * Escape single quotes and backslashes for Google Drive search queries
960
+ */
961
+ escape(str) {
962
+ return str.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
963
+ }
964
+ /**
965
+ * Filter: Exact file name match
966
+ */
967
+ nameEquals(name) {
968
+ this.conditions.push(`name = '${this.escape(name)}'`);
969
+ return this;
970
+ }
971
+ /**
972
+ * Filter: File name contains substring
973
+ */
974
+ nameContains(substring) {
975
+ this.conditions.push(`name contains '${this.escape(substring)}'`);
976
+ return this;
977
+ }
978
+ /**
979
+ * Filter: Specific MIME type
980
+ */
981
+ mimeType(mime2) {
982
+ this.conditions.push(`mimeType = '${this.escape(mime2)}'`);
983
+ return this;
984
+ }
985
+ /**
986
+ * Filter: Only folders
987
+ */
988
+ isFolder() {
989
+ this.conditions.push(`mimeType = '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);
990
+ return this;
991
+ }
992
+ /**
993
+ * Filter: Exclude folders (only files)
994
+ */
995
+ isFile() {
996
+ this.conditions.push(`mimeType != '${GOOGLE_WORKSPACE_MIME_TYPES.FOLDER}'`);
997
+ return this;
998
+ }
999
+ /**
1000
+ * Filter: Direct parent folder ID
1001
+ */
1002
+ inFolder(folderId) {
1003
+ this.conditions.push(`'${this.escape(folderId)}' in parents`);
1004
+ return this;
1005
+ }
1006
+ /**
1007
+ * Filter: Items not in trash (default recommended)
1008
+ */
1009
+ notTrashed() {
1010
+ this.conditions.push("trashed = false");
1011
+ return this;
1012
+ }
1013
+ /**
1014
+ * Filter: Only trashed items
1015
+ */
1016
+ onlyTrashed() {
1017
+ this.conditions.push("trashed = true");
1018
+ return this;
1019
+ }
1020
+ /**
1021
+ * Filter: Starred items
1022
+ */
1023
+ starred(isStarred = true) {
1024
+ this.conditions.push(`starred = ${isStarred}`);
1025
+ return this;
1026
+ }
1027
+ /**
1028
+ * Filter: Shared with current user
1029
+ */
1030
+ sharedWithMe() {
1031
+ this.conditions.push("sharedWithMe = true");
1032
+ return this;
1033
+ }
1034
+ /**
1035
+ * Filter: Modified after timestamp or Date
1036
+ */
1037
+ modifiedAfter(date) {
1038
+ const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();
1039
+ this.conditions.push(`modifiedTime > '${iso}'`);
1040
+ return this;
1041
+ }
1042
+ /**
1043
+ * Filter: Modified before timestamp or Date
1044
+ */
1045
+ modifiedBefore(date) {
1046
+ const iso = date instanceof Date ? date.toISOString() : new Date(date).toISOString();
1047
+ this.conditions.push(`modifiedTime < '${iso}'`);
1048
+ return this;
1049
+ }
1050
+ /**
1051
+ * Filter: Full-text search across content and name
1052
+ */
1053
+ fullText(term) {
1054
+ this.conditions.push(`fullText contains '${this.escape(term)}'`);
1055
+ return this;
1056
+ }
1057
+ /**
1058
+ * Custom raw query condition
1059
+ */
1060
+ raw(condition) {
1061
+ this.conditions.push(`(${condition})`);
1062
+ return this;
1063
+ }
1064
+ /**
1065
+ * Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
1066
+ */
1067
+ orderBy(order) {
1068
+ this.orderClauses.push(order);
1069
+ return this;
1070
+ }
1071
+ /**
1072
+ * Maximum items to retrieve per page or query
1073
+ */
1074
+ pageSize(size) {
1075
+ this.limitNumber = Math.min(1e3, Math.max(1, size));
1076
+ return this;
1077
+ }
1078
+ /**
1079
+ * Custom fields to return from Drive API
1080
+ */
1081
+ fields(fieldsString) {
1082
+ this.requestedFields = fieldsString;
1083
+ return this;
1084
+ }
1085
+ /**
1086
+ * Compiles the full query string
1087
+ */
1088
+ toQueryString() {
1089
+ return this.conditions.join(" and ");
1090
+ }
1091
+ /**
1092
+ * Executes query and returns array of matching files
1093
+ */
1094
+ async list() {
1095
+ const q = this.toQueryString();
1096
+ const orderBy = this.orderClauses.join(", ");
1097
+ const res = await withRetry(async () => {
1098
+ return await this.drive.files.list({
1099
+ q: q || void 0,
1100
+ orderBy: orderBy || void 0,
1101
+ pageSize: this.limitNumber,
1102
+ fields: this.requestedFields,
1103
+ spaces: this.spaces,
1104
+ supportsAllDrives: true,
1105
+ includeItemsFromAllDrives: true
1106
+ });
1107
+ });
1108
+ return res.data.files || [];
1109
+ }
1110
+ /**
1111
+ * Returns the first matching file, or null if not found
1112
+ */
1113
+ async first() {
1114
+ const originalLimit = this.limitNumber;
1115
+ this.limitNumber = 1;
1116
+ const items = await this.list();
1117
+ this.limitNumber = originalLimit;
1118
+ return items[0] || null;
1119
+ }
1120
+ /**
1121
+ * Counts matching items (up to 1000)
1122
+ */
1123
+ async count() {
1124
+ const items = await this.list();
1125
+ return items.length;
1126
+ }
1127
+ /**
1128
+ * Async iterator to stream all pages automatically without loading all into memory
1129
+ */
1130
+ async *[Symbol.asyncIterator]() {
1131
+ const q = this.toQueryString();
1132
+ const orderBy = this.orderClauses.join(", ");
1133
+ let pageToken = void 0;
1134
+ do {
1135
+ const res = await withRetry(async () => {
1136
+ return await this.drive.files.list({
1137
+ q: q || void 0,
1138
+ orderBy: orderBy || void 0,
1139
+ pageSize: this.limitNumber,
1140
+ pageToken,
1141
+ fields: this.requestedFields,
1142
+ spaces: this.spaces,
1143
+ supportsAllDrives: true,
1144
+ includeItemsFromAllDrives: true
1145
+ });
1146
+ });
1147
+ const files = res.data.files || [];
1148
+ for (const file of files) {
1149
+ yield file;
1150
+ }
1151
+ pageToken = res.data.nextPageToken || void 0;
1152
+ } while (pageToken);
1153
+ }
1154
+ };
1155
+ }
1156
+ });
1157
+
1158
+ // src/core/concurrency-pool.ts
1159
+ var ConcurrencyPool;
1160
+ var init_concurrency_pool = __esm({
1161
+ "src/core/concurrency-pool.ts"() {
1162
+ "use strict";
1163
+ init_cjs_shims();
1164
+ ConcurrencyPool = class {
1165
+ concurrency;
1166
+ running = 0;
1167
+ queue = [];
1168
+ constructor(concurrency = 4) {
1169
+ this.concurrency = Math.max(1, concurrency);
1170
+ }
1171
+ /**
1172
+ * Run a task when a slot becomes available
1173
+ */
1174
+ async run(task) {
1175
+ if (this.running >= this.concurrency) {
1176
+ await new Promise((resolve) => {
1177
+ this.queue.push(async () => {
1178
+ resolve();
1179
+ });
1180
+ });
1181
+ }
1182
+ this.running++;
1183
+ try {
1184
+ return await task();
1185
+ } finally {
1186
+ this.running--;
1187
+ if (this.queue.length > 0) {
1188
+ const next = this.queue.shift();
1189
+ if (next) next();
1190
+ }
1191
+ }
1192
+ }
1193
+ /**
1194
+ * Run all tasks in parallel bounded by concurrency limit
1195
+ */
1196
+ async all(tasks) {
1197
+ return Promise.all(tasks.map((task) => this.run(task)));
1198
+ }
1199
+ /**
1200
+ * Execute an array of items concurrently through an async mapper
1201
+ */
1202
+ async map(items, fn) {
1203
+ return Promise.all(items.map((item, index) => this.run(() => fn(item, index))));
1204
+ }
1205
+ };
1206
+ }
1207
+ });
1208
+
1209
+ // src/core/watcher.ts
1210
+ var import_node_events, DriveWatcher;
1211
+ var init_watcher = __esm({
1212
+ "src/core/watcher.ts"() {
1213
+ "use strict";
1214
+ init_cjs_shims();
1215
+ import_node_events = require("events");
1216
+ init_retry();
1217
+ DriveWatcher = class extends import_node_events.EventEmitter {
1218
+ drive;
1219
+ options;
1220
+ timer = null;
1221
+ isRunning = false;
1222
+ pageToken = null;
1223
+ constructor(drive2, options = {}) {
1224
+ super();
1225
+ this.drive = drive2;
1226
+ this.options = {
1227
+ intervalMs: 5e3,
1228
+ ...options
1229
+ };
1230
+ }
1231
+ /**
1232
+ * Starts listening for changes
1233
+ */
1234
+ async start() {
1235
+ if (this.isRunning) return this;
1236
+ this.isRunning = true;
1237
+ if (!this.pageToken) {
1238
+ const tokenRes = await withRetry(async () => {
1239
+ return await this.drive.changes.getStartPageToken({
1240
+ supportsAllDrives: true
1241
+ });
1242
+ });
1243
+ this.pageToken = tokenRes.data.startPageToken || null;
1244
+ }
1245
+ this.poll();
1246
+ return this;
1247
+ }
1248
+ /**
1249
+ * Stops listening
1250
+ */
1251
+ stop() {
1252
+ this.isRunning = false;
1253
+ if (this.timer) {
1254
+ clearTimeout(this.timer);
1255
+ this.timer = null;
1256
+ }
1257
+ this.emit("stop");
1258
+ }
1259
+ /**
1260
+ * Internal polling cycle
1261
+ */
1262
+ async poll() {
1263
+ if (!this.isRunning) return;
1264
+ try {
1265
+ if (!this.pageToken) {
1266
+ const tokenRes = await withRetry(async () => {
1267
+ return await this.drive.changes.getStartPageToken({
1268
+ supportsAllDrives: true
1269
+ });
1270
+ });
1271
+ this.pageToken = tokenRes.data.startPageToken || null;
1272
+ }
1273
+ let nextPageToken = this.pageToken;
1274
+ do {
1275
+ const res = await withRetry(async () => {
1276
+ return await this.drive.changes.list({
1277
+ pageToken: nextPageToken,
1278
+ fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
1279
+ supportsAllDrives: true,
1280
+ includeItemsFromAllDrives: true
1281
+ });
1282
+ });
1283
+ const changes = res.data.changes || [];
1284
+ for (const change of changes) {
1285
+ if (!change.fileId) continue;
1286
+ if (this.options.folderId && change.file) {
1287
+ const parents = change.file.parents || [];
1288
+ if (!parents.includes(this.options.folderId)) {
1289
+ continue;
1290
+ }
1291
+ }
1292
+ let eventType = "modify";
1293
+ if (change.removed || change.file?.trashed) {
1294
+ eventType = "delete";
1295
+ } else if (change.file?.createdTime && change.file?.modifiedTime) {
1296
+ const created = new Date(change.file.createdTime).getTime();
1297
+ const modified = new Date(change.file.modifiedTime).getTime();
1298
+ if (Math.abs(modified - created) < 2e3) {
1299
+ eventType = "create";
1300
+ }
1301
+ }
1302
+ const eventPayload = {
1303
+ type: eventType,
1304
+ fileId: change.fileId,
1305
+ file: change.file || void 0,
1306
+ removed: change.removed || false,
1307
+ time: change.time ? new Date(change.time) : /* @__PURE__ */ new Date()
1308
+ };
1309
+ this.emit("change", eventPayload);
1310
+ this.emit(eventType, eventPayload);
1311
+ }
1312
+ if (res.data.newStartPageToken) {
1313
+ this.pageToken = res.data.newStartPageToken;
1314
+ break;
1315
+ }
1316
+ nextPageToken = res.data.nextPageToken || null;
1317
+ } while (nextPageToken);
1318
+ } catch (err) {
1319
+ this.emit("error", err);
1320
+ } finally {
1321
+ if (this.isRunning) {
1322
+ this.timer = setTimeout(() => this.poll(), this.options.intervalMs);
1323
+ }
1324
+ }
1325
+ }
1326
+ };
1327
+ }
1328
+ });
1329
+
1330
+ // src/core/storage-cleaner.ts
1331
+ var StorageCleaner;
1332
+ var init_storage_cleaner = __esm({
1333
+ "src/core/storage-cleaner.ts"() {
1334
+ "use strict";
1335
+ init_cjs_shims();
1336
+ init_retry();
1337
+ init_format();
1338
+ StorageCleaner = class {
1339
+ drive;
1340
+ constructor(drive2) {
1341
+ this.drive = drive2;
1342
+ }
1343
+ /**
1344
+ * Finds the largest files occupying space in the Google Drive account
1345
+ */
1346
+ async findLargestFiles(limit = 10) {
1347
+ const res = await withRetry(async () => {
1348
+ return await this.drive.files.list({
1349
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1350
+ orderBy: "quotaBytesUsed desc",
1351
+ pageSize: Math.min(100, Math.max(1, limit)),
1352
+ fields: "files(id, name, size, mimeType, modifiedTime, webViewLink, quotaBytesUsed)",
1353
+ supportsAllDrives: true,
1354
+ includeItemsFromAllDrives: true
1355
+ });
1356
+ });
1357
+ const files = res.data.files || [];
1358
+ return files.map((f) => {
1359
+ const sizeBytes = parseInt(f.size || f.quotaBytesUsed || "0", 10);
1360
+ return {
1361
+ id: f.id,
1362
+ name: f.name || "untitled",
1363
+ size: sizeBytes,
1364
+ formattedSize: formatBytes(sizeBytes),
1365
+ mimeType: f.mimeType || "unknown",
1366
+ modifiedTime: f.modifiedTime || void 0,
1367
+ webViewLink: f.webViewLink || void 0
1368
+ };
1369
+ });
1370
+ }
1371
+ /**
1372
+ * Scans Google Drive and detects duplicate files (by MD5 hash or exact name)
1373
+ */
1374
+ async findDuplicates(options = {}) {
1375
+ const mode = options.by || "name";
1376
+ const maxScan = options.maxScan || 1e3;
1377
+ const res = await withRetry(async () => {
1378
+ return await this.drive.files.list({
1379
+ q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
1380
+ pageSize: Math.min(1e3, maxScan),
1381
+ fields: "files(id, name, size, md5Checksum, modifiedTime)",
1382
+ supportsAllDrives: true,
1383
+ includeItemsFromAllDrives: true
1384
+ });
1385
+ });
1386
+ const files = res.data.files || [];
1387
+ const map = /* @__PURE__ */ new Map();
1388
+ for (const f of files) {
1389
+ if (!f.id) continue;
1390
+ const key = mode === "md5" && f.md5Checksum ? f.md5Checksum : f.name || "";
1391
+ if (!key) continue;
1392
+ if (!map.has(key)) {
1393
+ map.set(key, []);
1394
+ }
1395
+ map.get(key).push(f);
1396
+ }
1397
+ const duplicates = [];
1398
+ for (const [key, group] of map.entries()) {
1399
+ if (group.length > 1) {
1400
+ let totalSize = 0;
1401
+ const mappedFiles = group.map((item) => {
1402
+ const s = parseInt(item.size || "0", 10);
1403
+ totalSize += s;
1404
+ return {
1405
+ id: item.id,
1406
+ name: item.name,
1407
+ size: s,
1408
+ modifiedTime: item.modifiedTime,
1409
+ md5Checksum: item.md5Checksum
1410
+ };
1411
+ });
1412
+ duplicates.push({
1413
+ name: key,
1414
+ count: group.length,
1415
+ totalSize,
1416
+ formattedTotalSize: formatBytes(totalSize),
1417
+ files: mappedFiles
1418
+ });
1419
+ }
1420
+ }
1421
+ return duplicates.sort((a, b) => b.totalSize - a.totalSize);
1422
+ }
1423
+ /**
1424
+ * Empties the entire trash in Google Drive
1425
+ */
1426
+ async emptyTrash() {
1427
+ await withRetry(async () => {
1428
+ await this.drive.files.emptyTrash({});
1429
+ });
1430
+ }
1431
+ };
1432
+ }
1433
+ });
1434
+
1435
+ // src/core/smart-sync.ts
1436
+ async function calculateFileMd5(filePath) {
1437
+ return new Promise((resolve, reject) => {
1438
+ const hash = import_node_crypto.default.createHash("md5");
1439
+ const stream = import_node_fs4.default.createReadStream(filePath);
1440
+ stream.on("data", (chunk) => hash.update(chunk));
1441
+ stream.on("end", () => resolve(hash.digest("hex")));
1442
+ stream.on("error", reject);
1443
+ });
1444
+ }
1445
+ var import_node_fs4, import_node_path3, import_node_crypto, SmartSyncEngine;
1446
+ var init_smart_sync = __esm({
1447
+ "src/core/smart-sync.ts"() {
1448
+ "use strict";
1449
+ init_cjs_shims();
1450
+ import_node_fs4 = __toESM(require("fs"), 1);
1451
+ import_node_path3 = __toESM(require("path"), 1);
1452
+ import_node_crypto = __toESM(require("crypto"), 1);
1453
+ init_concurrency_pool();
1454
+ init_downloader();
1455
+ init_retry();
1456
+ SmartSyncEngine = class {
1457
+ drive;
1458
+ downloader;
1459
+ constructor(drive2) {
1460
+ this.drive = drive2;
1461
+ this.downloader = new Downloader(drive2);
1462
+ }
1463
+ /**
1464
+ * Pulls (downloads) an entire Google Drive folder tree to a local directory
1465
+ */
1466
+ async pullFolder(remoteFolderId, localDestinationDir, options = {}) {
1467
+ const startTime = Date.now();
1468
+ const concurrency = options.concurrency || 4;
1469
+ const pool = new ConcurrencyPool(concurrency);
1470
+ const result = {
1471
+ downloaded: [],
1472
+ skipped: [],
1473
+ failed: [],
1474
+ totalBytes: 0,
1475
+ durationMs: 0
1476
+ };
1477
+ await import_node_fs4.default.promises.mkdir(localDestinationDir, { recursive: true });
1478
+ const collectRemoteItems = async (folderId, relPath) => {
1479
+ const items = [];
1480
+ let pageToken = void 0;
1481
+ do {
1482
+ const res = await withRetry(async () => {
1483
+ return await this.drive.files.list({
1484
+ q: `'${folderId}' in parents and trashed = false`,
1485
+ fields: "nextPageToken, files(id, name, mimeType, size, md5Checksum)",
1486
+ pageSize: 500,
1487
+ supportsAllDrives: true,
1488
+ includeItemsFromAllDrives: true
1489
+ });
1490
+ });
1491
+ const files = res.data.files || [];
1492
+ for (const file of files) {
1493
+ if (!file.id || !file.name) continue;
1494
+ const isFolder = file.mimeType === "application/vnd.google-apps.folder";
1495
+ const fileRel = relPath ? import_node_path3.default.join(relPath, file.name) : file.name;
1496
+ if (isFolder) {
1497
+ const sub = await collectRemoteItems(file.id, fileRel);
1498
+ items.push(...sub);
1499
+ } else {
1500
+ items.push({
1501
+ id: file.id,
1502
+ name: file.name,
1503
+ isFolder: false,
1504
+ relPath: fileRel,
1505
+ size: parseInt(file.size || "0", 10),
1506
+ md5Checksum: file.md5Checksum
1507
+ });
1508
+ }
1509
+ }
1510
+ pageToken = res.data.nextPageToken || void 0;
1511
+ } while (pageToken);
1512
+ return items;
1513
+ };
1514
+ const remoteFiles = await collectRemoteItems(remoteFolderId, "");
1515
+ await pool.map(remoteFiles, async (remoteItem) => {
1516
+ const localFilePath = import_node_path3.default.join(localDestinationDir, remoteItem.relPath);
1517
+ if (!options.overwrite && import_node_fs4.default.existsSync(localFilePath)) {
1518
+ const localStat = await import_node_fs4.default.promises.stat(localFilePath);
1519
+ if (remoteItem.md5Checksum) {
1520
+ const localMd5 = await calculateFileMd5(localFilePath);
1521
+ if (localMd5.toLowerCase() === remoteItem.md5Checksum.toLowerCase()) {
1522
+ result.skipped.push({
1523
+ remoteId: remoteItem.id,
1524
+ remoteName: remoteItem.name,
1525
+ reason: "Identical MD5 checksum matches local file"
1526
+ });
1527
+ return;
1528
+ }
1529
+ } else if (localStat.size === remoteItem.size && remoteItem.size > 0) {
1530
+ result.skipped.push({
1531
+ remoteId: remoteItem.id,
1532
+ remoteName: remoteItem.name,
1533
+ reason: "Identical file size exists locally"
1534
+ });
1535
+ return;
1536
+ }
1537
+ }
1538
+ try {
1539
+ if (options.onFileStart) {
1540
+ options.onFileStart(remoteItem.name, remoteItem.relPath);
1541
+ }
1542
+ await this.downloader.download(remoteItem.id, {
1543
+ destination: localFilePath
1544
+ });
1545
+ result.downloaded.push({
1546
+ remoteId: remoteItem.id,
1547
+ remoteName: remoteItem.name,
1548
+ localPath: localFilePath,
1549
+ size: remoteItem.size
1550
+ });
1551
+ result.totalBytes += remoteItem.size;
1552
+ if (options.onFileComplete) {
1553
+ options.onFileComplete(remoteItem.name, localFilePath);
1554
+ }
1555
+ } catch (err) {
1556
+ result.failed.push({
1557
+ remoteId: remoteItem.id,
1558
+ remoteName: remoteItem.name,
1559
+ error: err
1560
+ });
1561
+ }
1562
+ });
1563
+ result.durationMs = Date.now() - startTime;
1564
+ return result;
1565
+ }
1566
+ };
1567
+ }
1568
+ });
1569
+
1570
+ // src/auth/browser-login.ts
1571
+ async function loginWithBrowser(options) {
1572
+ const port = options.port || 3e3;
1573
+ const redirectUri = `http://localhost:${port}/oauth2callback`;
1574
+ const scopes = options.scopes || DEFAULT_SCOPES;
1575
+ const oauth2Client = new import_drive2.auth.OAuth2(
1576
+ options.clientId,
1577
+ options.clientSecret,
1578
+ redirectUri
1579
+ );
1580
+ const authUrl = oauth2Client.generateAuthUrl({
1581
+ access_type: "offline",
1582
+ prompt: "consent",
1583
+ scope: scopes
1584
+ });
1585
+ return new Promise((resolve, reject) => {
1586
+ const server = import_node_http.default.createServer(async (req, res) => {
1587
+ try {
1588
+ const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
1589
+ if (reqUrl.pathname === "/oauth2callback") {
1590
+ const code = reqUrl.searchParams.get("code");
1591
+ const error = reqUrl.searchParams.get("error");
1592
+ if (error) {
1593
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1594
+ res.end(`<h2>\u274C Authorization Failed</h2><p>${error}</p>`);
1595
+ server.close();
1596
+ return reject(new Error(`OAuth error: ${error}`));
1597
+ }
1598
+ if (!code) {
1599
+ res.writeHead(400, { "Content-Type": "text/html; charset=utf-8" });
1600
+ res.end("<h2>\u274C Missing authorization code</h2>");
1601
+ return;
1602
+ }
1603
+ const { tokens } = await oauth2Client.getToken(code);
1604
+ oauth2Client.setCredentials(tokens);
1605
+ res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
1606
+ res.end(`
1607
+ <!DOCTYPE html>
1608
+ <html lang="en">
1609
+ <head>
1610
+ <meta charset="UTF-8">
1611
+ <title>DriveKit Authentication</title>
1612
+ <style>
1613
+ body {
1614
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
1615
+ display: flex;
1616
+ align-items: center;
1617
+ justify-content: center;
1618
+ height: 100vh;
1619
+ margin: 0;
1620
+ background: #0f172a;
1621
+ color: #f8fafc;
1622
+ }
1623
+ .card {
1624
+ text-align: center;
1625
+ padding: 40px;
1626
+ background: #1e293b;
1627
+ border-radius: 16px;
1628
+ box-shadow: 0 10px 25px rgba(0,0,0,0.5);
1629
+ }
1630
+ .badge {
1631
+ font-size: 48px;
1632
+ margin-bottom: 12px;
1633
+ }
1634
+ h1 { color: #38bdf8; margin: 0 0 10px 0; }
1635
+ p { color: #94a3b8; font-size: 16px; }
1636
+ </style>
1637
+ </head>
1638
+ <body>
1639
+ <div class="card">
1640
+ <div class="badge">\u26A1</div>
1641
+ <h1>Authentication Successful!</h1>
1642
+ <p>DriveKit is now connected to your Google Drive account.</p>
1643
+ <p>You can close this window and return to your terminal.</p>
1644
+ </div>
1645
+ </body>
1646
+ </html>
1647
+ `);
1648
+ server.close();
1649
+ resolve({ tokens, client: oauth2Client });
1650
+ }
1651
+ } catch (err) {
1652
+ res.writeHead(500, { "Content-Type": "text/html; charset=utf-8" });
1653
+ res.end(`<h2>\u274C Server Error</h2><p>${err.message}</p>`);
1654
+ server.close();
1655
+ reject(err);
1656
+ }
1657
+ });
1658
+ server.listen(port, () => {
1659
+ const openCmd = process.platform === "darwin" ? `open "${authUrl}"` : process.platform === "win32" ? `start "" "${authUrl}"` : `xdg-open "${authUrl}"`;
1660
+ (0, import_node_child_process.exec)(openCmd, (err) => {
1661
+ if (err) {
1662
+ console.log(`
1663
+ Please open the following URL in your browser to sign in:
1664
+ ${authUrl}
1665
+ `);
1666
+ }
1667
+ });
1668
+ });
1669
+ server.on("error", (err) => {
1670
+ reject(err);
1671
+ });
1672
+ });
1673
+ }
1674
+ var import_node_http, import_node_child_process, import_drive2;
1675
+ var init_browser_login = __esm({
1676
+ "src/auth/browser-login.ts"() {
1677
+ "use strict";
1678
+ init_cjs_shims();
1679
+ import_node_http = __toESM(require("http"), 1);
1680
+ import_node_child_process = require("child_process");
1681
+ import_drive2 = require("@googleapis/drive");
1682
+ init_authenticator();
1683
+ }
1684
+ });
1685
+
1686
+ // src/core/client.ts
1687
+ var client_exports = {};
1688
+ __export(client_exports, {
1689
+ DriveKit: () => DriveKit
1690
+ });
1691
+ var import_node_fs5, import_node_path4, import_drive3, DriveKit;
1692
+ var init_client = __esm({
1693
+ "src/core/client.ts"() {
1694
+ "use strict";
1695
+ init_cjs_shims();
1696
+ import_node_fs5 = __toESM(require("fs"), 1);
1697
+ import_node_path4 = __toESM(require("path"), 1);
1698
+ import_drive3 = require("@googleapis/drive");
1699
+ init_authenticator();
1700
+ init_path_resolver();
1701
+ init_resumable_uploader();
1702
+ init_downloader();
1703
+ init_query_builder();
1704
+ init_concurrency_pool();
1705
+ init_watcher();
1706
+ init_storage_cleaner();
1707
+ init_smart_sync();
1708
+ init_browser_login();
1709
+ init_retry();
1710
+ init_format();
1711
+ init_mime();
1712
+ DriveKit = class {
1713
+ options;
1714
+ authenticator;
1715
+ driveClient = null;
1716
+ pathResolverInstance = null;
1717
+ uploaderInstance = null;
1718
+ downloaderInstance = null;
1719
+ rootFolderId;
1720
+ constructor(options = {}) {
1721
+ this.options = options;
1722
+ this.rootFolderId = options.rootFolderId || "root";
1723
+ this.authenticator = new DriveAuthenticator(options.auth);
1724
+ }
1725
+ /**
1726
+ * Initializes the Google Drive API client (lazy-loaded if not called explicitly)
1727
+ */
1728
+ async init() {
1729
+ if (!this.driveClient) {
1730
+ const auth = await this.authenticator.getAuthClient();
1731
+ this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
1732
+ this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
1733
+ enableCache: this.options.enablePathCache ?? true,
1734
+ cacheTTL: this.options.pathCacheTTL
1735
+ });
1736
+ this.uploaderInstance = new ResumableUploader(
1737
+ this.driveClient,
1738
+ this.options.uploadChunkSize || DEFAULT_CHUNK_SIZE
1739
+ );
1740
+ this.downloaderInstance = new Downloader(this.driveClient);
1741
+ }
1742
+ return this;
1743
+ }
1744
+ /**
1745
+ * Access the underlying official `@googleapis/drive` instance for raw API calls
1746
+ */
1747
+ async getRawClient() {
1748
+ await this.init();
1749
+ return this.driveClient;
1750
+ }
1751
+ async getResolver() {
1752
+ await this.init();
1753
+ return this.pathResolverInstance;
1754
+ }
1755
+ async getUploader() {
1756
+ await this.init();
1757
+ return this.uploaderInstance;
1758
+ }
1759
+ async getDownloader() {
1760
+ await this.init();
1761
+ return this.downloaderInstance;
1762
+ }
1763
+ /**
1764
+ * Resolves a target string that could be either an ID or a virtual path (starting with '/')
1765
+ */
1766
+ async resolveId(idOrPath, autoCreateDir = false) {
1767
+ if (idOrPath.startsWith("/")) {
1768
+ const resolver = await this.getResolver();
1769
+ const res = await resolver.resolve(idOrPath, { createIfMissing: autoCreateDir });
1770
+ return res.id;
1771
+ }
1772
+ return idOrPath;
1773
+ }
1774
+ // ==========================================
1775
+ // DIRECTORY & PATH OPERATIONS
1776
+ // ==========================================
1777
+ /**
1778
+ * Creates a folder structure recursively, similar to `mkdir -p`.
1779
+ * @param virtualPath Path like "/Documents/Projects/2026"
1780
+ * @returns Folder ID of the created or existing directory
1781
+ */
1782
+ async mkdirp(virtualPath) {
1783
+ const resolver = await this.getResolver();
1784
+ return await resolver.mkdirp(virtualPath);
1785
+ }
1786
+ /**
1787
+ * Resolves a virtual path to its Drive metadata
1788
+ */
1789
+ async resolvePath(virtualPath) {
1790
+ const resolver = await this.getResolver();
1791
+ return await resolver.resolve(virtualPath);
1792
+ }
1793
+ /**
1794
+ * Check if a file or folder exists (by ID or virtual path)
1795
+ */
1796
+ async exists(idOrPath) {
1797
+ try {
1798
+ if (idOrPath.startsWith("/")) {
1799
+ await this.resolvePath(idOrPath);
1800
+ return true;
1801
+ }
1802
+ const raw = await this.getRawClient();
1803
+ await raw.files.get({ fileId: idOrPath, fields: "id, trashed" });
1804
+ return true;
1805
+ } catch (err) {
1806
+ if (err.status === 404 || err.code === "NOT_FOUND") {
1807
+ return false;
1808
+ }
1809
+ throw err;
1810
+ }
1811
+ }
1812
+ /**
1813
+ * Lists contents of a folder (by folder ID or path)
1814
+ */
1815
+ async ls(folderIdOrPath = "/") {
1816
+ if (folderIdOrPath === "/" || folderIdOrPath === "root") {
1817
+ return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
1818
+ }
1819
+ const folderId = await this.resolveId(folderIdOrPath);
1820
+ return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
1821
+ }
1822
+ // ==========================================
1823
+ // FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
1824
+ // ==========================================
1825
+ /**
1826
+ * Powerful upload method:
1827
+ * - Supports local paths, Buffers, or Streams
1828
+ * - Automatically uses high-speed resumable chunked upload for large files
1829
+ * - Parent can be a folder ID OR a virtual path (e.g. '/Backups/2026')
1830
+ * - Real-time progress callback: % complete, transfer speed (MB/s), ETA
1831
+ */
1832
+ async upload(options) {
1833
+ const uploader = await this.getUploader();
1834
+ let parentId = options.parent;
1835
+ if (parentId && parentId.startsWith("/")) {
1836
+ parentId = await this.mkdirp(parentId);
1837
+ }
1838
+ if (options.overwrite && options.name && parentId) {
1839
+ const existing = await this.query().inFolder(parentId).nameEquals(options.name).notTrashed().first();
1840
+ if (existing?.id) {
1841
+ await this.delete(existing.id, true);
1842
+ }
1843
+ }
1844
+ return await uploader.upload({
1845
+ ...options,
1846
+ parent: parentId
1847
+ });
1848
+ }
1849
+ /**
1850
+ * Downloads a file from Google Drive:
1851
+ * - Automatic conversion for Google Docs, Sheets, and Slides
1852
+ * - Progress events
1853
+ * - Saves directly to file or returns Readable Stream
1854
+ */
1855
+ async download(fileIdOrPath, options = {}) {
1856
+ const fileId = await this.resolveId(fileIdOrPath);
1857
+ const downloader = await this.getDownloader();
1858
+ return await downloader.download(fileId, options);
1859
+ }
1860
+ /**
1861
+ * Gets file metadata
1862
+ */
1863
+ async getFile(fileIdOrPath) {
1864
+ const fileId = await this.resolveId(fileIdOrPath);
1865
+ const raw = await this.getRawClient();
1866
+ const res = await withRetry(async () => {
1867
+ return await raw.files.get({
1868
+ fileId,
1869
+ fields: "id, name, mimeType, size, modifiedTime, createdTime, parents, trashed, webViewLink, webContentLink, description, properties, shared",
1870
+ supportsAllDrives: true
1871
+ });
1872
+ });
1873
+ return res.data;
1874
+ }
1875
+ /**
1876
+ * Reads file content as UTF-8 string
1877
+ */
1878
+ async getText(fileIdOrPath) {
1879
+ const { stream } = await this.download(fileIdOrPath);
1880
+ if (!stream) throw new Error("Failed to obtain download stream");
1881
+ const chunks = [];
1882
+ for await (const chunk of stream) {
1883
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
1884
+ }
1885
+ return Buffer.concat(chunks).toString("utf-8");
1886
+ }
1887
+ /**
1888
+ * Reads file content and parses as JSON
1889
+ */
1890
+ async getJson(fileIdOrPath) {
1891
+ const text = await this.getText(fileIdOrPath);
1892
+ return JSON.parse(text);
1893
+ }
1894
+ /**
1895
+ * Deletes a file or moves it to trash
1896
+ */
1897
+ async delete(fileIdOrPath, permanent = false) {
1898
+ const fileId = await this.resolveId(fileIdOrPath);
1899
+ const raw = await this.getRawClient();
1900
+ if (permanent) {
1901
+ await withRetry(async () => {
1902
+ await raw.files.delete({ fileId, supportsAllDrives: true });
1903
+ });
1904
+ } else {
1905
+ await withRetry(async () => {
1906
+ await raw.files.update({
1907
+ fileId,
1908
+ requestBody: { trashed: true },
1909
+ supportsAllDrives: true
1910
+ });
1911
+ });
1912
+ }
1913
+ if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
1914
+ this.pathResolverInstance.invalidatePath(fileIdOrPath);
1915
+ }
1916
+ }
1917
+ /**
1918
+ * Move item to trash
1919
+ */
1920
+ async trash(fileIdOrPath) {
1921
+ return this.delete(fileIdOrPath, false);
1922
+ }
1923
+ /**
1924
+ * Restore item from trash
1925
+ */
1926
+ async restore(fileId) {
1927
+ const raw = await this.getRawClient();
1928
+ await withRetry(async () => {
1929
+ await raw.files.update({
1930
+ fileId,
1931
+ requestBody: { trashed: false },
1932
+ supportsAllDrives: true
1933
+ });
1934
+ });
1935
+ }
1936
+ /**
1937
+ * Move file to a different folder
1938
+ */
1939
+ async move(fileIdOrPath, newParentIdOrPath) {
1940
+ const fileId = await this.resolveId(fileIdOrPath);
1941
+ const newParentId = await this.resolveId(newParentIdOrPath, true);
1942
+ const raw = await this.getRawClient();
1943
+ const file = await this.getFile(fileId);
1944
+ const previousParents = (file.parents || []).join(",");
1945
+ const res = await withRetry(async () => {
1946
+ return await raw.files.update({
1947
+ fileId,
1948
+ addParents: newParentId,
1949
+ removeParents: previousParents,
1950
+ fields: "id, name, parents",
1951
+ supportsAllDrives: true
1952
+ });
1953
+ });
1954
+ if (this.pathResolverInstance) {
1955
+ this.pathResolverInstance.clearCache();
1956
+ }
1957
+ return res.data;
1958
+ }
1959
+ /**
1960
+ * Copies a file
1961
+ */
1962
+ async copy(fileIdOrPath, options = {}) {
1963
+ const fileId = await this.resolveId(fileIdOrPath);
1964
+ const raw = await this.getRawClient();
1965
+ let parentId = options.parent;
1966
+ if (parentId && parentId.startsWith("/")) {
1967
+ parentId = await this.mkdirp(parentId);
1968
+ }
1969
+ const requestBody = {};
1970
+ if (options.name) requestBody.name = options.name;
1971
+ if (parentId) requestBody.parents = [parentId];
1972
+ const res = await withRetry(async () => {
1973
+ return await raw.files.copy({
1974
+ fileId,
1975
+ requestBody,
1976
+ fields: "id, name, mimeType, webViewLink",
1977
+ supportsAllDrives: true
1978
+ });
1979
+ });
1980
+ return res.data;
1981
+ }
1982
+ /**
1983
+ * Renames a file
1984
+ */
1985
+ async rename(fileIdOrPath, newName) {
1986
+ const fileId = await this.resolveId(fileIdOrPath);
1987
+ const raw = await this.getRawClient();
1988
+ const res = await withRetry(async () => {
1989
+ return await raw.files.update({
1990
+ fileId,
1991
+ requestBody: { name: newName },
1992
+ fields: "id, name, mimeType",
1993
+ supportsAllDrives: true
1994
+ });
1995
+ });
1996
+ if (this.pathResolverInstance) {
1997
+ this.pathResolverInstance.clearCache();
1998
+ }
1999
+ return res.data;
2000
+ }
2001
+ // ==========================================
2002
+ // SHARING & PERMISSIONS
2003
+ // ==========================================
2004
+ /**
2005
+ * Share file with user, group, domain, or anyone
2006
+ */
2007
+ async share(fileIdOrPath, options = {}) {
2008
+ const fileId = await this.resolveId(fileIdOrPath);
2009
+ const raw = await this.getRawClient();
2010
+ const requestBody = {
2011
+ role: options.role || "reader",
2012
+ type: options.type || (options.emailAddress ? "user" : "anyone"),
2013
+ emailAddress: options.emailAddress,
2014
+ domain: options.domain
2015
+ };
2016
+ const res = await withRetry(async () => {
2017
+ return await raw.permissions.create({
2018
+ fileId,
2019
+ requestBody,
2020
+ sendNotificationEmail: options.sendNotificationEmail,
2021
+ emailMessage: options.emailMessage,
2022
+ transferOwnership: options.transferOwnership,
2023
+ supportsAllDrives: true,
2024
+ fields: "id, role, type, emailAddress"
2025
+ });
2026
+ });
2027
+ return res.data;
2028
+ }
2029
+ /**
2030
+ * Quickly make a file public to anyone with the link
2031
+ */
2032
+ async sharePublic(fileIdOrPath, role = "reader") {
2033
+ const fileId = await this.resolveId(fileIdOrPath);
2034
+ await this.share(fileId, { role, type: "anyone" });
2035
+ const file = await this.getFile(fileId);
2036
+ return {
2037
+ fileId,
2038
+ previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,
2039
+ directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`
2040
+ };
2041
+ }
2042
+ /**
2043
+ * Returns sharing links for a file
2044
+ */
2045
+ async getShareableLink(fileIdOrPath) {
2046
+ const fileId = await this.resolveId(fileIdOrPath);
2047
+ const file = await this.getFile(fileId);
2048
+ return {
2049
+ previewLink: file.webViewLink || `https://drive.google.com/file/d/${fileId}/view`,
2050
+ directDownloadLink: `https://drive.google.com/uc?export=download&id=${fileId}`
2051
+ };
2052
+ }
2053
+ // ==========================================
2054
+ // QUERY BUILDER
2055
+ // ==========================================
2056
+ /**
2057
+ * Returns a fluent search query builder
2058
+ */
2059
+ query() {
2060
+ if (!this.driveClient) {
2061
+ throw new Error("DriveKit not initialized. Call await drive.init() first, or use an async method.");
2062
+ }
2063
+ return new DriveQueryBuilder(this.driveClient);
2064
+ }
2065
+ // ==========================================
2066
+ // FOLDER SYNC & BATCH UPLOAD
2067
+ // ==========================================
2068
+ /**
2069
+ * Recursively uploads a local folder to a Google Drive path with high concurrency
2070
+ */
2071
+ async syncFolder(localDir, remotePathOrId, options = {}) {
2072
+ await this.init();
2073
+ const startTime = Date.now();
2074
+ const concurrency = options.concurrency || this.options.concurrency || 4;
2075
+ const pool = new ConcurrencyPool(concurrency);
2076
+ const targetFolderId = await this.resolveId(remotePathOrId, true);
2077
+ const result = {
2078
+ uploaded: [],
2079
+ skipped: [],
2080
+ failed: [],
2081
+ totalBytes: 0,
2082
+ durationMs: 0
2083
+ };
2084
+ const collectFiles = async (dir, base) => {
2085
+ const entries = await import_node_fs5.default.promises.readdir(dir, { withFileTypes: true });
2086
+ const files = [];
2087
+ for (const entry of entries) {
2088
+ const fullPath = import_node_path4.default.join(dir, entry.name);
2089
+ const relPath = import_node_path4.default.join(base, entry.name);
2090
+ if (entry.isDirectory()) {
2091
+ const sub = await collectFiles(fullPath, relPath);
2092
+ files.push(...sub);
2093
+ } else if (entry.isFile()) {
2094
+ const stat = await import_node_fs5.default.promises.stat(fullPath);
2095
+ files.push({ fullPath, relPath, size: stat.size });
2096
+ }
2097
+ }
2098
+ return files;
2099
+ };
2100
+ const allFiles = await collectFiles(localDir, "");
2101
+ const remoteDirCache = /* @__PURE__ */ new Map();
2102
+ remoteDirCache.set("", targetFolderId);
2103
+ const ensureRemoteSubdir = async (relDir) => {
2104
+ if (remoteDirCache.has(relDir)) {
2105
+ return remoteDirCache.get(relDir);
2106
+ }
2107
+ const parts = relDir.split(import_node_path4.default.sep).filter(Boolean);
2108
+ let currentParent = targetFolderId;
2109
+ let currentRel = "";
2110
+ for (const part of parts) {
2111
+ currentRel = currentRel ? import_node_path4.default.join(currentRel, part) : part;
2112
+ if (remoteDirCache.has(currentRel)) {
2113
+ currentParent = remoteDirCache.get(currentRel);
2114
+ continue;
2115
+ }
2116
+ const existing = await this.query().inFolder(currentParent).nameEquals(part).isFolder().notTrashed().first();
2117
+ if (existing?.id) {
2118
+ currentParent = existing.id;
2119
+ } else {
2120
+ const raw = await this.getRawClient();
2121
+ const created = await withRetry(async () => {
2122
+ return await raw.files.create({
2123
+ requestBody: {
2124
+ name: part,
2125
+ mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
2126
+ parents: [currentParent]
2127
+ },
2128
+ fields: "id",
2129
+ supportsAllDrives: true
2130
+ });
2131
+ });
2132
+ currentParent = created.data.id;
2133
+ }
2134
+ remoteDirCache.set(currentRel, currentParent);
2135
+ }
2136
+ return currentParent;
2137
+ };
2138
+ await pool.map(allFiles, async (fileItem) => {
2139
+ try {
2140
+ const relDir = import_node_path4.default.dirname(fileItem.relPath);
2141
+ const fileName = import_node_path4.default.basename(fileItem.relPath);
2142
+ const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
2143
+ if (options.onFileStart) {
2144
+ options.onFileStart(fileItem.fullPath, fileItem.relPath);
2145
+ }
2146
+ const uploadedFile = await this.upload({
2147
+ source: fileItem.fullPath,
2148
+ name: fileName,
2149
+ parent: parentFolderId,
2150
+ overwrite: options.overwrite ?? false
2151
+ });
2152
+ result.uploaded.push({
2153
+ localPath: fileItem.fullPath,
2154
+ fileId: uploadedFile.id,
2155
+ name: fileName
2156
+ });
2157
+ result.totalBytes += fileItem.size;
2158
+ if (options.onFileComplete) {
2159
+ options.onFileComplete(fileItem.fullPath, uploadedFile.id);
2160
+ }
2161
+ } catch (err) {
2162
+ result.failed.push({
2163
+ localPath: fileItem.fullPath,
2164
+ error: err
2165
+ });
2166
+ }
2167
+ });
2168
+ result.durationMs = Date.now() - startTime;
2169
+ return result;
2170
+ }
2171
+ // ==========================================
2172
+ // STORAGE & QUOTA
2173
+ // ==========================================
2174
+ /**
2175
+ * Retrieves Google Drive storage quota usage and limits
2176
+ */
2177
+ async getStorageQuota() {
2178
+ const raw = await this.getRawClient();
2179
+ const res = await withRetry(async () => {
2180
+ return await raw.about.get({
2181
+ fields: "storageQuota, user"
2182
+ });
2183
+ });
2184
+ const quota = res.data.storageQuota || {};
2185
+ const limit = quota.limit ? parseInt(quota.limit, 10) : null;
2186
+ const usage = quota.usage ? parseInt(quota.usage, 10) : 0;
2187
+ const usageInDrive = quota.usageInDrive ? parseInt(quota.usageInDrive, 10) : 0;
2188
+ const usageInDriveTrash = quota.usageInDriveTrash ? parseInt(quota.usageInDriveTrash, 10) : 0;
2189
+ const percentUsed = limit && limit > 0 ? Math.round(usage / limit * 1e3) / 10 : null;
2190
+ return {
2191
+ user: res.data.user,
2192
+ limit,
2193
+ usage,
2194
+ usageInDrive,
2195
+ usageInDriveTrash,
2196
+ percentUsed,
2197
+ formattedUsage: formatBytes(usage),
2198
+ formattedLimit: limit ? formatBytes(limit) : "Unlimited"
2199
+ };
2200
+ }
2201
+ // ==========================================
2202
+ // CHANGE WATCHER (REAL-TIME EVENTS)
2203
+ // ==========================================
2204
+ /**
2205
+ * Watches Google Drive or a specific folder for real-time changes, creations, and deletions
2206
+ */
2207
+ async watch(folderIdOrPath, options = {}) {
2208
+ await this.init();
2209
+ let folderId = void 0;
2210
+ if (folderIdOrPath && folderIdOrPath !== "/") {
2211
+ folderId = await this.resolveId(folderIdOrPath);
2212
+ }
2213
+ const watcher = new DriveWatcher(this.driveClient, {
2214
+ ...options,
2215
+ folderId
2216
+ });
2217
+ await watcher.start();
2218
+ return watcher;
2219
+ }
2220
+ // ==========================================
2221
+ // STORAGE CLEANER & DUPLICATE FINDER
2222
+ // ==========================================
2223
+ /**
2224
+ * Finds the largest files consuming Google Drive storage
2225
+ */
2226
+ async findLargestFiles(limit = 10) {
2227
+ await this.init();
2228
+ const cleaner = new StorageCleaner(this.driveClient);
2229
+ return await cleaner.findLargestFiles(limit);
2230
+ }
2231
+ /**
2232
+ * Finds duplicate files (by MD5 hash or exact file name)
2233
+ */
2234
+ async findDuplicates(options) {
2235
+ await this.init();
2236
+ const cleaner = new StorageCleaner(this.driveClient);
2237
+ return await cleaner.findDuplicates(options);
2238
+ }
2239
+ /**
2240
+ * Empties the entire trash bin in Google Drive
2241
+ */
2242
+ async emptyTrash() {
2243
+ await this.init();
2244
+ const cleaner = new StorageCleaner(this.driveClient);
2245
+ await cleaner.emptyTrash();
2246
+ }
2247
+ // ==========================================
2248
+ // SMART PULL & TWO-WAY SYNC
2249
+ // ==========================================
2250
+ /**
2251
+ * Pulls (downloads) an entire remote Google Drive directory down to a local folder with MD5 deduplication
2252
+ */
2253
+ async pull(remoteFolderIdOrPath, localDestinationDir, options = {}) {
2254
+ await this.init();
2255
+ const folderId = await this.resolveId(remoteFolderIdOrPath);
2256
+ const engine = new SmartSyncEngine(this.driveClient);
2257
+ return await engine.pullFolder(folderId, localDestinationDir, options);
2258
+ }
2259
+ /**
2260
+ * Calculates local file MD5 hash for integrity and deduplication checks
2261
+ */
2262
+ static async calculateFileMd5(filePath) {
2263
+ return await calculateFileMd5(filePath);
2264
+ }
2265
+ /**
2266
+ * Interactive 1-click browser OAuth login flow
2267
+ */
2268
+ static async loginWithBrowser(options) {
2269
+ return await loginWithBrowser(options);
2270
+ }
2271
+ };
2272
+ }
2273
+ });
2274
+
2275
+ // src/cli.ts
2276
+ var cli_exports = {};
2277
+ __export(cli_exports, {
2278
+ runCLI: () => runCLI
2279
+ });
2280
+ module.exports = __toCommonJS(cli_exports);
2281
+ init_cjs_shims();
2282
+ var import_node_fs6 = __toESM(require("fs"), 1);
2283
+ var import_node_path5 = __toESM(require("path"), 1);
2284
+ var import_commander = require("commander");
2285
+ var import_chalk = __toESM(require("chalk"), 1);
2286
+ var import_ora = __toESM(require("ora"), 1);
2287
+ init_client();
2288
+ init_format();
2289
+ var program = new import_commander.Command();
2290
+ program.name("drivekit").description(import_chalk.default.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
2291
+ function getAuthConfig(cmdOptions) {
2292
+ const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
2293
+ const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
2294
+ return {
2295
+ keyFilePath,
2296
+ accessToken
2297
+ };
2298
+ }
2299
+ async function getClient(cmdOptions) {
2300
+ const globalOpts = program.opts();
2301
+ const mergedOpts = { ...globalOpts, ...cmdOptions };
2302
+ const auth = getAuthConfig(mergedOpts);
2303
+ const client = new DriveKit({ auth });
2304
+ await client.init();
2305
+ return client;
2306
+ }
2307
+ program.command("quota").description("Show Google Drive storage usage & quota").action(async (options) => {
2308
+ const spinner = (0, import_ora.default)("Fetching storage quota...").start();
2309
+ try {
2310
+ const client = await getClient(options);
2311
+ const quota = await client.getStorageQuota();
2312
+ spinner.stop();
2313
+ console.log(import_chalk.default.bold.cyan("\n\u{1F4CA} Google Drive Storage Quota:"));
2314
+ if (quota.user?.displayName) {
2315
+ console.log(`\u{1F464} User: ${import_chalk.default.yellow(quota.user.displayName)} (${quota.user.emailAddress})`);
2316
+ }
2317
+ console.log(`\u{1F4BE} Total Usage: ${import_chalk.default.green(quota.formattedUsage)} / ${import_chalk.default.blue(quota.formattedLimit)}`);
2318
+ if (quota.percentUsed !== null) {
2319
+ console.log(`\u{1F4C8} Usage %: ${import_chalk.default.bold(quota.percentUsed + "%")}`);
2320
+ }
2321
+ console.log(`\u{1F4C1} In Drive: ${formatBytes(quota.usageInDrive)}`);
2322
+ console.log(`\u{1F5D1}\uFE0F In Trash: ${formatBytes(quota.usageInDriveTrash)}
2323
+ `);
2324
+ } catch (err) {
2325
+ spinner.fail(import_chalk.default.red(`Failed to fetch quota: ${err.message}`));
2326
+ process.exit(1);
2327
+ }
2328
+ });
2329
+ program.command("ls [folder]").description("List files and folders (by virtual path or folder ID, default: root)").action(async (folder = "/", options) => {
2330
+ const spinner = (0, import_ora.default)(`Listing contents of ${folder}...`).start();
2331
+ try {
2332
+ const client = await getClient(options);
2333
+ const items = await client.ls(folder);
2334
+ spinner.stop();
2335
+ if (items.length === 0) {
2336
+ console.log(import_chalk.default.dim(`(Folder ${folder} is empty)`));
2337
+ return;
2338
+ }
2339
+ console.log(import_chalk.default.bold.cyan(`
2340
+ \u{1F4C1} Contents of "${folder}":
2341
+ `));
2342
+ for (const item of items) {
2343
+ const isDir = item.mimeType === "application/vnd.google-apps.folder";
2344
+ const icon = isDir ? "\u{1F4C1}" : "\u{1F4C4}";
2345
+ const nameFormatted = isDir ? import_chalk.default.bold.blue(item.name) : import_chalk.default.white(item.name);
2346
+ const sizeFormatted = item.size ? import_chalk.default.dim(`[${formatBytes(parseInt(item.size, 10))}]`) : import_chalk.default.dim(isDir ? "[DIR]" : "[Google Doc]");
2347
+ const idFormatted = import_chalk.default.dim(`(ID: ${item.id})`);
2348
+ console.log(` ${icon} ${nameFormatted.padEnd(40)} ${sizeFormatted.padEnd(16)} ${idFormatted}`);
2349
+ }
2350
+ console.log(`
2351
+ Total items: ${import_chalk.default.green(items.length)}
2352
+ `);
2353
+ } catch (err) {
2354
+ spinner.fail(import_chalk.default.red(`Failed to list items: ${err.message}`));
2355
+ process.exit(1);
2356
+ }
2357
+ });
2358
+ program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").action(async (localFile, remotePath = "/", options) => {
2359
+ if (!import_node_fs6.default.existsSync(localFile)) {
2360
+ console.error(import_chalk.default.red(`\u274C Local file not found: ${localFile}`));
2361
+ process.exit(1);
2362
+ }
2363
+ const fileName = import_node_path5.default.basename(localFile);
2364
+ const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
2365
+ try {
2366
+ const client = await getClient(options);
2367
+ spinner.stop();
2368
+ const startTime = Date.now();
2369
+ const res = await client.upload({
2370
+ source: localFile,
2371
+ name: fileName,
2372
+ parent: remotePath,
2373
+ overwrite: options.overwrite,
2374
+ onProgress: (p) => {
2375
+ process.stdout.write(
2376
+ `\r\u{1F680} Uploading: ${import_chalk.default.cyan(p.percentage + "%")} | Speed: ${import_chalk.default.green(p.speedFormatted)} | ETA: ${import_chalk.default.yellow(p.estimatedTimeRemainingSeconds + "s")} [${formatBytes(p.bytesSent)} / ${formatBytes(p.totalBytes)}]`
2377
+ );
2378
+ }
2379
+ });
2380
+ process.stdout.write("\n");
2381
+ const durationSecs = ((Date.now() - startTime) / 1e3).toFixed(1);
2382
+ console.log(import_chalk.default.green(`
2383
+ \u2705 Upload completed successfully in ${durationSecs}s!`));
2384
+ console.log(`\u{1F4C4} Name: ${import_chalk.default.bold(res.name)}`);
2385
+ console.log(`\u{1F194} ID: ${import_chalk.default.cyan(res.id)}`);
2386
+ if (res.webViewLink) {
2387
+ console.log(`\u{1F517} Link: ${import_chalk.default.underline(res.webViewLink)}`);
2388
+ }
2389
+ console.log("");
2390
+ } catch (err) {
2391
+ spinner.fail(import_chalk.default.red(`Upload failed: ${err.message}`));
2392
+ process.exit(1);
2393
+ }
2394
+ });
2395
+ program.command("download <fileIdOrPath> [destination]").description("Download a file from Google Drive").action(async (fileIdOrPath, destination = ".", options) => {
2396
+ const spinner = (0, import_ora.default)(`Fetching file ${fileIdOrPath}...`).start();
2397
+ try {
2398
+ const client = await getClient(options);
2399
+ spinner.stop();
2400
+ const res = await client.download(fileIdOrPath, {
2401
+ destination,
2402
+ onProgress: (p) => {
2403
+ const pct = p.percentage !== void 0 ? `${p.percentage}%` : `${formatBytes(p.bytesRead)}`;
2404
+ process.stdout.write(
2405
+ `\r\u2B07\uFE0F Downloading: ${import_chalk.default.cyan(pct)} | Speed: ${import_chalk.default.green(p.speedFormatted)}`
2406
+ );
2407
+ }
2408
+ });
2409
+ process.stdout.write("\n");
2410
+ console.log(import_chalk.default.green(`
2411
+ \u2705 Download completed!`));
2412
+ console.log(`\u{1F4C2} Saved to: ${import_chalk.default.bold(res.filePath)}`);
2413
+ if (res.size) {
2414
+ console.log(`\u{1F4E6} Size: ${formatBytes(res.size)}`);
2415
+ }
2416
+ console.log("");
2417
+ } catch (err) {
2418
+ spinner.fail(import_chalk.default.red(`Download failed: ${err.message}`));
2419
+ process.exit(1);
2420
+ }
2421
+ });
2422
+ program.command("share <fileIdOrPath> [email]").description("Share file publicly or with a specific email").action(async (fileIdOrPath, email, options) => {
2423
+ const spinner = (0, import_ora.default)(`Updating permissions for ${fileIdOrPath}...`).start();
2424
+ try {
2425
+ const client = await getClient(options);
2426
+ if (email) {
2427
+ await client.share(fileIdOrPath, {
2428
+ role: "reader",
2429
+ type: "user",
2430
+ emailAddress: email
2431
+ });
2432
+ spinner.succeed(import_chalk.default.green(`File shared with ${email} as reader!`));
2433
+ } else {
2434
+ const links = await client.sharePublic(fileIdOrPath);
2435
+ spinner.succeed(import_chalk.default.green(`File is now publicly accessible to anyone with the link!`));
2436
+ console.log(`\u{1F517} Preview Link: ${import_chalk.default.underline(links.previewLink)}`);
2437
+ console.log(`\u{1F4E5} Direct Download Link: ${import_chalk.default.underline(links.directDownloadLink)}
2438
+ `);
2439
+ }
2440
+ } catch (err) {
2441
+ spinner.fail(import_chalk.default.red(`Sharing failed: ${err.message}`));
2442
+ process.exit(1);
2443
+ }
2444
+ });
2445
+ program.command("delete <fileIdOrPath>").description("Move a file/folder to trash, or delete permanently with --permanent").option("-p, --permanent", "Permanently delete instead of moving to trash").action(async (fileIdOrPath, options) => {
2446
+ const actionName = options.permanent ? "Permanently deleting" : "Moving to trash";
2447
+ const spinner = (0, import_ora.default)(`${actionName} ${fileIdOrPath}...`).start();
2448
+ try {
2449
+ const client = await getClient(options);
2450
+ await client.delete(fileIdOrPath, options.permanent);
2451
+ spinner.succeed(import_chalk.default.green(`Success! ${fileIdOrPath} has been ${options.permanent ? "permanently deleted" : "moved to trash"}.`));
2452
+ } catch (err) {
2453
+ spinner.fail(import_chalk.default.red(`Failed: ${err.message}`));
2454
+ process.exit(1);
2455
+ }
2456
+ });
2457
+ program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
2458
+ if (!import_node_fs6.default.existsSync(localDir)) {
2459
+ console.error(import_chalk.default.red(`\u274C Local directory not found: ${localDir}`));
2460
+ process.exit(1);
2461
+ }
2462
+ const concurrency = parseInt(options.concurrency, 10) || 4;
2463
+ console.log(import_chalk.default.bold.cyan(`
2464
+ \u26A1 Starting recursive sync:`));
2465
+ console.log(`\u{1F4C2} Local: ${localDir}`);
2466
+ console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
2467
+ console.log(`\u{1F680} Concurrency: ${concurrency} parallel streams
2468
+ `);
2469
+ const spinner = (0, import_ora.default)("Scanning and synchronizing...").start();
2470
+ try {
2471
+ const client = await getClient(options);
2472
+ spinner.stop();
2473
+ const result = await client.syncFolder(localDir, remoteFolder, {
2474
+ concurrency,
2475
+ overwrite: options.overwrite,
2476
+ onFileStart: (_, rel) => {
2477
+ console.log(` \u2B06\uFE0F Uploading: ${import_chalk.default.dim(rel)}`);
2478
+ },
2479
+ onFileComplete: (_, fileId) => {
2480
+ console.log(` ${import_chalk.default.green("\u2713 Completed")} ${import_chalk.default.dim(`(ID: ${fileId})`)}`);
2481
+ }
2482
+ });
2483
+ console.log(import_chalk.default.bold.green(`
2484
+ \u{1F389} Sync Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2485
+ console.log(`\u2705 Uploaded: ${import_chalk.default.green(result.uploaded.length)} files (${formatBytes(result.totalBytes)})`);
2486
+ if (result.failed.length > 0) {
2487
+ console.log(`\u274C Failed: ${import_chalk.default.red(result.failed.length)} files`);
2488
+ for (const f of result.failed) {
2489
+ console.log(` - ${f.localPath}: ${import_chalk.default.red(f.error.message)}`);
2490
+ }
2491
+ }
2492
+ console.log("");
2493
+ } catch (err) {
2494
+ spinner.fail(import_chalk.default.red(`Sync failed: ${err.message}`));
2495
+ process.exit(1);
2496
+ }
2497
+ });
2498
+ program.command("pull <remoteFolder> <localDir>").description("Download an entire remote Google Drive folder down to local directory with MD5 deduplication").option("-c, --concurrency <number>", "Parallel downloads", "4").option("-o, --overwrite", "Overwrite local files even if identical").action(async (remoteFolder, localDir, options) => {
2499
+ const concurrency = parseInt(options.concurrency, 10) || 4;
2500
+ console.log(import_chalk.default.bold.cyan(`
2501
+ \u2B07\uFE0F Starting smart pull:`));
2502
+ console.log(`\u2601\uFE0F Remote: ${remoteFolder}`);
2503
+ console.log(`\u{1F4C2} Local: ${localDir}`);
2504
+ console.log(`\u{1F680} Concurrency: ${concurrency} parallel streams
2505
+ `);
2506
+ const spinner = (0, import_ora.default)("Scanning remote files...").start();
2507
+ try {
2508
+ const client = await getClient(options);
2509
+ spinner.stop();
2510
+ const result = await client.pull(remoteFolder, localDir, {
2511
+ concurrency,
2512
+ overwrite: options.overwrite,
2513
+ onFileStart: (name, rel) => {
2514
+ console.log(` \u2B07\uFE0F Downloading: ${import_chalk.default.dim(rel)}`);
2515
+ },
2516
+ onFileComplete: (name) => {
2517
+ console.log(` ${import_chalk.default.green("\u2713 Saved")} ${name}`);
2518
+ }
2519
+ });
2520
+ console.log(import_chalk.default.bold.green(`
2521
+ \u{1F389} Pull Finished in ${(result.durationMs / 1e3).toFixed(1)}s!`));
2522
+ console.log(`\u2705 Downloaded: ${import_chalk.default.green(result.downloaded.length)} files (${formatBytes(result.totalBytes)})`);
2523
+ if (result.skipped.length > 0) {
2524
+ console.log(`\u23ED\uFE0F Skipped: ${import_chalk.default.yellow(result.skipped.length)} identical files`);
2525
+ }
2526
+ if (result.failed.length > 0) {
2527
+ console.log(`\u274C Failed: ${import_chalk.default.red(result.failed.length)} files`);
2528
+ }
2529
+ console.log("");
2530
+ } catch (err) {
2531
+ spinner.fail(import_chalk.default.red(`Pull failed: ${err.message}`));
2532
+ process.exit(1);
2533
+ }
2534
+ });
2535
+ program.command("clean").description("Storage management: find largest files, detect duplicates, or empty trash").option("-l, --largest [count]", "Show the largest space-consuming files", "10").option("-d, --duplicates", "Find duplicate files").option("--empty-trash", "Empty entire Google Drive trash bin").action(async (options) => {
2536
+ try {
2537
+ const client = await getClient(options);
2538
+ if (options.emptyTrash) {
2539
+ const spinner2 = (0, import_ora.default)("Emptying trash bin...").start();
2540
+ await client.emptyTrash();
2541
+ spinner2.succeed(import_chalk.default.green("Trash bin emptied successfully!"));
2542
+ return;
2543
+ }
2544
+ if (options.duplicates) {
2545
+ const spinner2 = (0, import_ora.default)("Scanning for duplicate files...").start();
2546
+ const duplicates = await client.findDuplicates({ by: "name" });
2547
+ spinner2.stop();
2548
+ if (duplicates.length === 0) {
2549
+ console.log(import_chalk.default.green("\n\u2728 No duplicate files found!"));
2550
+ return;
2551
+ }
2552
+ console.log(import_chalk.default.bold.yellow(`
2553
+ \u26A0\uFE0F Found ${duplicates.length} duplicate groups:
2554
+ `));
2555
+ for (const g of duplicates) {
2556
+ console.log(`\u{1F4C4} "${import_chalk.default.bold(g.name)}" (${import_chalk.default.cyan(g.count + " copies")} - total: ${import_chalk.default.magenta(g.formattedTotalSize)})`);
2557
+ for (const f of g.files) {
2558
+ console.log(` - ID: ${import_chalk.default.dim(f.id)} [${formatBytes(f.size)}] modified: ${import_chalk.default.dim(f.modifiedTime || "unknown")}`);
2559
+ }
2560
+ }
2561
+ console.log("");
2562
+ return;
2563
+ }
2564
+ const limit = parseInt(options.largest, 10) || 10;
2565
+ const spinner = (0, import_ora.default)(`Finding top ${limit} largest files...`).start();
2566
+ const largest = await client.findLargestFiles(limit);
2567
+ spinner.stop();
2568
+ console.log(import_chalk.default.bold.cyan(`
2569
+ \u{1F4CA} Top ${largest.length} Largest Files in Drive:
2570
+ `));
2571
+ for (let i = 0; i < largest.length; i++) {
2572
+ const f = largest[i];
2573
+ console.log(` ${import_chalk.default.bold(i + 1 + ".")} ${import_chalk.default.white(f.name.padEnd(35))} ${import_chalk.default.green(f.formattedSize.padEnd(12))} ID: ${import_chalk.default.dim(f.id)}`);
2574
+ }
2575
+ console.log("");
2576
+ } catch (err) {
2577
+ console.error(import_chalk.default.red(`Clean operation failed: ${err.message}`));
2578
+ process.exit(1);
2579
+ }
2580
+ });
2581
+ program.command("watch [folder]").description("Watch Google Drive or a specific folder for real-time changes").option("-i, --interval <ms>", "Polling interval in milliseconds", "5000").action(async (folder = "/", options) => {
2582
+ const intervalMs = parseInt(options.interval, 10) || 5e3;
2583
+ console.log(import_chalk.default.bold.cyan(`
2584
+ \u{1F440} Watching for changes in "${folder}" (polling every ${intervalMs / 1e3}s)...`));
2585
+ console.log(import_chalk.default.dim("Press Ctrl+C to stop watching.\n"));
2586
+ try {
2587
+ const client = await getClient(options);
2588
+ const watcher = await client.watch(folder === "/" ? void 0 : folder, { intervalMs });
2589
+ watcher.on("create", (e) => {
2590
+ console.log(`${import_chalk.default.green("[CREATED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
2591
+ });
2592
+ watcher.on("modify", (e) => {
2593
+ console.log(`${import_chalk.default.yellow("[MODIFIED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
2594
+ });
2595
+ watcher.on("delete", (e) => {
2596
+ console.log(`${import_chalk.default.red("[DELETED]")} ${import_chalk.default.bold(e.file?.name || e.fileId)} ${import_chalk.default.dim(`(ID: ${e.fileId})`)}`);
2597
+ });
2598
+ watcher.on("error", (err) => {
2599
+ console.error(import_chalk.default.red(`[WATCHER ERROR] ${err.message}`));
2600
+ });
2601
+ process.on("SIGINT", () => {
2602
+ watcher.stop();
2603
+ console.log(import_chalk.default.yellow("\nWatcher stopped. Goodbye!"));
2604
+ process.exit(0);
2605
+ });
2606
+ } catch (err) {
2607
+ console.error(import_chalk.default.red(`Failed to start watcher: ${err.message}`));
2608
+ process.exit(1);
2609
+ }
2610
+ });
2611
+ program.command("login").description("Interactive 1-click browser OAuth2 sign-in").requiredOption("--client-id <id>", "Google OAuth2 Client ID").requiredOption("--client-secret <secret>", "Google OAuth2 Client Secret").option("-p, --port <port>", "Local callback port", "3000").action(async (options) => {
2612
+ console.log(import_chalk.default.bold.cyan("\n\u26A1 DriveKit Interactive Login"));
2613
+ console.log("Opening your browser for one-click Google OAuth sign-in...\n");
2614
+ try {
2615
+ const { DriveKit: DriveKit2 } = await Promise.resolve().then(() => (init_client(), client_exports));
2616
+ const result = await DriveKit2.loginWithBrowser({
2617
+ clientId: options.clientId,
2618
+ clientSecret: options.clientSecret,
2619
+ port: parseInt(options.port, 10) || 3e3
2620
+ });
2621
+ console.log(import_chalk.default.bold.green("\n\u{1F389} Login successful!"));
2622
+ console.log(`Access Token: ${import_chalk.default.cyan(result.tokens.access_token?.slice(0, 25) + "...")}`);
2623
+ if (result.tokens.refresh_token) {
2624
+ console.log(`Refresh Token: ${import_chalk.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
2625
+ }
2626
+ const outPath = import_node_path5.default.resolve("./gdrive-tokens.json");
2627
+ import_node_fs6.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
2628
+ console.log(`\u{1F4BE} Saved tokens to: ${import_chalk.default.bold(outPath)}
2629
+ `);
2630
+ } catch (err) {
2631
+ console.error(import_chalk.default.red(`Login failed: ${err.message}`));
2632
+ process.exit(1);
2633
+ }
2634
+ });
2635
+ function runCLI() {
2636
+ program.parse(process.argv);
2637
+ }
2638
+ if (process.argv[1] && process.argv[1].endsWith("cli.js")) {
2639
+ runCLI();
2640
+ }
2641
+ // Annotate the CommonJS export names for ESM import in node:
2642
+ 0 && (module.exports = {
2643
+ runCLI
2644
+ });
2645
+ //# sourceMappingURL=cli.cjs.map