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