drivekit 0.0.0-stage → 1.0.0

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