@d0whc3r/node-gdrive 3.4.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,802 @@
1
+ import e, * as t from "node:fs";
2
+ import n from "node:os";
3
+ import r from "node:path";
4
+ import { pipeline as i } from "node:stream/promises";
5
+ import { drive as a } from "@googleapis/drive";
6
+ import { ZipArchive as o } from "archiver";
7
+ import s from "dayjs";
8
+ import c from "mime-types";
9
+ import l from "node:crypto";
10
+ import u from "node:http";
11
+ import { styleText as d } from "node:util";
12
+ import { CodeChallengeMethod as f, GoogleAuth as p, OAuth2Client as m } from "google-auth-library";
13
+ // \0rolldown/runtime.js
14
+ var h = Object.create, g = Object.defineProperty, _ = Object.getOwnPropertyDescriptor, v = Object.getOwnPropertyNames, y = Object.getPrototypeOf, b = Object.prototype.hasOwnProperty, x = (e, t) => () => (t || (e((t = { exports: {} }).exports, t, t.exports), e = null), t.exports), S = (e, t, n, r) => {
15
+ if (t && typeof t == "object" || typeof t == "function") for (var i = v(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !b.call(e, s) && s !== n && g(e, s, {
16
+ get: ((e) => t[e]).bind(null, s),
17
+ enumerable: !(r = _(t, s)) || r.enumerable
18
+ });
19
+ return e;
20
+ }, C = /* @__PURE__ */ ((e, t, n) => (n = e == null ? {} : h(y(e)), S(t || !e || !e.__esModule || !b.call(e, "default") ? g(n, "default", {
21
+ value: e,
22
+ enumerable: !0
23
+ }) : n, e)))((/* @__PURE__ */ x(((e, t, n) => {
24
+ (function(n, r) {
25
+ typeof e == "object" && t !== void 0 ? t.exports = r() : typeof define == "function" && define.amd ? define(r) : (n = typeof globalThis < "u" ? globalThis : n || self).dayjs_plugin_isSameOrBefore = r();
26
+ })(n, (function() {
27
+ return function(e, t) {
28
+ t.prototype.isSameOrBefore = function(e, t) {
29
+ return this.isSame(e, t) || this.isBefore(e, t);
30
+ };
31
+ };
32
+ }));
33
+ })))()), w = class {
34
+ static _tokenFile;
35
+ static _credentialsFile;
36
+ static _serviceAccountFile;
37
+ static _tag;
38
+ static get TOKEN_FILE() {
39
+ return this._tokenFile ?? process.env.TOKEN_FILE ?? "./secrets/token.json";
40
+ }
41
+ static set TOKEN_FILE(e) {
42
+ this._tokenFile = e;
43
+ }
44
+ static get CREDENTIALS_FILE() {
45
+ return this._credentialsFile ?? process.env.CREDENTIALS_FILE ?? "./secrets/credentials.json";
46
+ }
47
+ static set CREDENTIALS_FILE(e) {
48
+ this._credentialsFile = e;
49
+ }
50
+ static get SERVICE_ACCOUNT_FILE() {
51
+ return this._serviceAccountFile ?? process.env.SERVICE_ACCOUNT_FILE ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
52
+ }
53
+ static set SERVICE_ACCOUNT_FILE(e) {
54
+ this._serviceAccountFile = e;
55
+ }
56
+ static get BACKUP_ENCRYPTION_KEY() {
57
+ return process.env.BACKUP_ENCRYPTION_KEY || void 0;
58
+ }
59
+ static get TAG() {
60
+ return this._tag ?? "[node-gdrive]";
61
+ }
62
+ static set TAG(e) {
63
+ this._tag = e;
64
+ }
65
+ static reset() {
66
+ this._tokenFile = void 0, this._credentialsFile = void 0, this._serviceAccountFile = void 0, this._tag = void 0;
67
+ }
68
+ }, T = ["https://www.googleapis.com/auth/drive"], E = class {
69
+ ready = !0;
70
+ scopes;
71
+ tokenFile;
72
+ credentialsFile;
73
+ serviceAccountFile;
74
+ useADC;
75
+ logger;
76
+ _oAuth2Client;
77
+ _googleAuth;
78
+ constructor(e = {}) {
79
+ this.tokenFile = e.tokenFile ?? w.TOKEN_FILE, this.credentialsFile = e.credentialsFile ?? w.CREDENTIALS_FILE, this.serviceAccountFile = e.serviceAccountFile ?? w.SERVICE_ACCOUNT_FILE, this.useADC = e.useADC ?? !1, this.scopes = e.scopes ?? T, this.logger = e.logger ?? console, this.serviceAccountFile ? t.existsSync(this.serviceAccountFile) || (this.ready = !1, this.logger.error(d(["bold", "red"], `${w.TAG} ERROR: Service account file not found in ${this.serviceAccountFile}`))) : !this.useADC && !this.existsCredentials && (this.ready = !1, this.logger.error(d(["bold", "red"], `${w.TAG} ERROR: Credentials file not found in ${this.credentialsFile}`)));
80
+ }
81
+ get isServiceAccountOrADC() {
82
+ return !!this.serviceAccountFile || this.useADC;
83
+ }
84
+ get existsToken() {
85
+ return t.existsSync(this.tokenFile);
86
+ }
87
+ get existsCredentials() {
88
+ return t.existsSync(this.credentialsFile);
89
+ }
90
+ async initiate() {
91
+ if (!this.ready) {
92
+ let e = this.serviceAccountFile ?? this.credentialsFile;
93
+ throw Error(`${w.TAG} Credentials file not found in ${e}`);
94
+ }
95
+ return this.isServiceAccountOrADC ? (this.googleAuthClient(), !0) : this.existsToken ? (this.oAuth2Client(!0), !0) : this.generateAccessToken();
96
+ }
97
+ getAuthClient() {
98
+ return this.isServiceAccountOrADC ? this.googleAuthClient() : this.oAuth2Client(!0);
99
+ }
100
+ googleAuthClient() {
101
+ if (!this._googleAuth) {
102
+ if (this.serviceAccountFile) {
103
+ let e = JSON.parse(t.readFileSync(this.serviceAccountFile, "utf8"));
104
+ this._googleAuth = new p({
105
+ credentials: e,
106
+ scopes: this.scopes
107
+ });
108
+ } else this._googleAuth = new p({ scopes: this.scopes });
109
+ }
110
+ return this._googleAuth;
111
+ }
112
+ oAuth2Client(e = !0, n) {
113
+ if (!this._oAuth2Client) {
114
+ let r = JSON.parse(t.readFileSync(this.credentialsFile, "utf8")), i = r.installed ?? r.web;
115
+ if (!i) throw Error(`${w.TAG} Invalid credentials file format in ${this.credentialsFile}`);
116
+ let { client_secret: a, client_id: o, redirect_uris: s } = i;
117
+ if (this._oAuth2Client = new m(o, a, n ?? s?.[0] ?? "http://127.0.0.1"), this.attachTokenListener(this._oAuth2Client), e && this.existsToken) {
118
+ let e = JSON.parse(t.readFileSync(this.tokenFile, "utf8"));
119
+ this._oAuth2Client.setCredentials(e);
120
+ }
121
+ }
122
+ return this._oAuth2Client;
123
+ }
124
+ attachTokenListener(e) {
125
+ e.on("tokens", (e) => {
126
+ try {
127
+ let n = {};
128
+ this.existsToken && (n = JSON.parse(t.readFileSync(this.tokenFile, "utf8")));
129
+ let r = {
130
+ ...n,
131
+ ...e,
132
+ refresh_token: e.refresh_token ?? n.refresh_token
133
+ };
134
+ this.persistTokenSync(r);
135
+ } catch (e) {
136
+ this.logger.warn(`${w.TAG} Failed to persist refreshed token:`, e);
137
+ }
138
+ });
139
+ }
140
+ persistTokenSync(e) {
141
+ t.mkdirSync(r.dirname(this.tokenFile), {
142
+ recursive: !0,
143
+ mode: 448
144
+ }), t.writeFileSync(this.tokenFile, JSON.stringify(e, null, 2), { mode: 384 }), t.chmodSync(this.tokenFile, 384);
145
+ }
146
+ async generateAccessToken() {
147
+ let e = l.randomBytes(16).toString("hex"), t = l.randomBytes(32).toString("base64url"), n = l.createHash("sha256").update(t).digest("base64url");
148
+ return new Promise((r, i) => {
149
+ let a = u.createServer(), o = !1, s = (e) => {
150
+ o || (o = !0, a.close(), e());
151
+ };
152
+ a.on("error", (e) => {
153
+ s(() => i(Error(`${w.TAG} OAuth loopback server failed`, { cause: e })));
154
+ }), a.on("request", (n, o) => {
155
+ (async () => {
156
+ try {
157
+ let c = new URL(n.url ?? "/", "http://127.0.0.1");
158
+ if (c.pathname !== "/oauth2callback") {
159
+ o.writeHead(404, { "Content-Type": "text/plain" }), o.end("Not found");
160
+ return;
161
+ }
162
+ let l = c.searchParams.get("state"), u = c.searchParams.get("code"), d = c.searchParams.get("error");
163
+ if (d) {
164
+ o.writeHead(400, { "Content-Type": "text/plain" }), o.end(`Authorization failed: ${d}`), s(() => i(/* @__PURE__ */ Error(`${w.TAG} OAuth authorization error: ${d}`)));
165
+ return;
166
+ }
167
+ if (!l || l !== e) {
168
+ o.writeHead(400, { "Content-Type": "text/plain" }), o.end("Invalid OAuth state parameter"), s(() => i(/* @__PURE__ */ Error(`${w.TAG} OAuth state mismatch`)));
169
+ return;
170
+ }
171
+ if (!u) {
172
+ o.writeHead(400, { "Content-Type": "text/plain" }), o.end("Missing authorization code"), s(() => i(/* @__PURE__ */ Error(`${w.TAG} Missing OAuth authorization code`)));
173
+ return;
174
+ }
175
+ let f = `http://127.0.0.1:${a.address().port}/oauth2callback`, p = this.oAuth2Client(!1, f), { tokens: m } = await p.getToken({
176
+ code: u,
177
+ codeVerifier: t,
178
+ redirect_uri: f
179
+ });
180
+ p.setCredentials(m), this.persistTokenSync(m), o.writeHead(200, { "Content-Type": "text/plain" }), o.end("Authentication successful! You can close this window."), this.logger.info(`${w.TAG} Token stored to`, this.tokenFile), s(() => r(!0));
181
+ } catch (e) {
182
+ o.writeHead(500, { "Content-Type": "text/plain" }), o.end("Error exchanging OAuth authorization code."), s(() => i(e instanceof Error ? e : Error(String(e))));
183
+ }
184
+ })();
185
+ }), a.listen(0, "127.0.0.1", () => {
186
+ let t = `http://127.0.0.1:${a.address().port}/oauth2callback`, r = this.oAuth2Client(!1, t).generateAuthUrl({
187
+ access_type: "offline",
188
+ prompt: "consent",
189
+ scope: this.scopes,
190
+ redirect_uri: t,
191
+ state: e,
192
+ code_challenge: n,
193
+ code_challenge_method: f.S256
194
+ });
195
+ this.logger.info(`${w.TAG} Authorize this app by visiting this url:`, r);
196
+ });
197
+ });
198
+ }
199
+ }, D = Buffer.from("NGDE", "ascii"), O = 1, k = 16, A = 12, j = 16, M = 32, N = D.length + 1 + k + A;
200
+ function P(e, t) {
201
+ if (!e) throw Error("Encryption passphrase must not be empty");
202
+ return l.scryptSync(e, t, M);
203
+ }
204
+ function F(e, t) {
205
+ let n = l.randomBytes(k), r = l.randomBytes(A), i = P(t, n), a = l.createCipheriv("aes-256-gcm", i, r), o = Buffer.concat([a.update(e), a.final()]), s = a.getAuthTag();
206
+ return Buffer.concat([
207
+ D,
208
+ Buffer.from([O]),
209
+ n,
210
+ r,
211
+ o,
212
+ s
213
+ ]);
214
+ }
215
+ function I(e, t) {
216
+ if (e.length < N + j) throw Error("Encrypted payload is too short or corrupted");
217
+ if (!e.subarray(0, D.length).equals(D)) throw Error("Invalid encrypted file header");
218
+ let n = e[D.length];
219
+ if (n !== O) throw Error(`Unsupported encryption format version: ${String(n)}`);
220
+ let r = D.length + 1, i = r + k, a = e.subarray(r, i), o = e.subarray(i, N), s = e.subarray(N, e.length - j), c = e.subarray(e.length - j), u = P(t, a), d = l.createDecipheriv("aes-256-gcm", u, o);
221
+ return d.setAuthTag(c), Buffer.concat([d.update(s), d.final()]);
222
+ }
223
+ async function L(t, n, a) {
224
+ let o = l.randomBytes(k), s = l.randomBytes(A), c = P(a, o), u = Buffer.concat([
225
+ D,
226
+ Buffer.from([O]),
227
+ o,
228
+ s
229
+ ]);
230
+ e.mkdirSync(r.dirname(n), {
231
+ recursive: !0,
232
+ mode: 448
233
+ });
234
+ let d = l.createCipheriv("aes-256-gcm", c, s), f = e.createReadStream(t), p = e.createWriteStream(n, { mode: 384 });
235
+ try {
236
+ p.write(u), await i(f, d, p, { end: !1 });
237
+ let e = d.getAuthTag();
238
+ return await new Promise((t, n) => {
239
+ p.once("error", n), p.end(e, () => t());
240
+ }), n;
241
+ } catch (r) {
242
+ throw f.destroy(), p.destroy(), e.rmSync(n, { force: !0 }), Error(`Failed to encrypt file "${t}"`, { cause: r });
243
+ }
244
+ }
245
+ async function R(t, n, a) {
246
+ let o = e.statSync(t);
247
+ if (o.size < N + j) throw Error("Encrypted file is too short or corrupted");
248
+ let s = e.openSync(t, "r"), c = Buffer.alloc(N), u = Buffer.alloc(j);
249
+ try {
250
+ e.readSync(s, c, 0, N, 0), e.readSync(s, u, 0, j, o.size - j);
251
+ } finally {
252
+ e.closeSync(s);
253
+ }
254
+ if (!c.subarray(0, D.length).equals(D)) throw Error("Invalid encrypted file header");
255
+ let d = c[D.length];
256
+ if (d !== O) throw Error(`Unsupported encryption format version: ${String(d)}`);
257
+ let f = D.length + 1, p = f + k, m = c.subarray(f, p), h = c.subarray(p, N), g = P(a, m), _ = l.createDecipheriv("aes-256-gcm", g, h);
258
+ _.setAuthTag(u), e.mkdirSync(r.dirname(n), {
259
+ recursive: !0,
260
+ mode: 448
261
+ });
262
+ let v = o.size - N - j, y = e.createWriteStream(n, { mode: 384 });
263
+ try {
264
+ if (v === 0) {
265
+ let e = _.final();
266
+ await new Promise((t, n) => {
267
+ y.once("error", n), y.end(e, () => t());
268
+ });
269
+ } else {
270
+ let n = e.createReadStream(t, {
271
+ start: N,
272
+ end: o.size - j - 1
273
+ });
274
+ await i(n, _, y);
275
+ }
276
+ return n;
277
+ } catch (r) {
278
+ throw y.destroy(), e.rmSync(n, { force: !0 }), Error(`Failed to decrypt file "${t}"`, { cause: r });
279
+ }
280
+ }
281
+ // src/retry.ts
282
+ var z = /* @__PURE__ */ new Set([
283
+ 429,
284
+ 500,
285
+ 502,
286
+ 503,
287
+ 504
288
+ ]), B = /* @__PURE__ */ new Set([
289
+ "ECONNRESET",
290
+ "ETIMEDOUT",
291
+ "ENOTFOUND",
292
+ "EAI_AGAIN",
293
+ "EPIPE",
294
+ "UND_ERR_CONNECT_TIMEOUT"
295
+ ]);
296
+ function V(e) {
297
+ return new Promise((t) => {
298
+ setTimeout(t, e);
299
+ });
300
+ }
301
+ function H(e) {
302
+ if (!e || typeof e != "object") return !1;
303
+ let t = e, n = typeof t.status == "number" ? t.status : typeof t.code == "number" ? t.code : typeof t.response?.status == "number" ? t.response.status : void 0;
304
+ if (n !== void 0 && z.has(n)) return !0;
305
+ let r = typeof t.code == "string" ? t.code : void 0;
306
+ return !!(r && B.has(r));
307
+ }
308
+ async function U(e, t = {}) {
309
+ let { maxRetries: n = 4, baseDelayMs: r = 500, maxDelayMs: i = 16e3, jitter: a = !0, sleep: o = V } = t, s = 0;
310
+ for (;;) try {
311
+ return await e();
312
+ } catch (e) {
313
+ if (s >= n || !H(e)) throw e;
314
+ let t = Math.min(i, r * 2 ** s), c = a ? Math.round(t * (.5 + Math.random() * .5)) : t;
315
+ s += 1, await o(c);
316
+ }
317
+ }
318
+ // src/types.ts
319
+ var W = /* @__PURE__ */ "appProperties.capabilities.contentHints.createdTime.description.explicitlyTrashed.fileExtension.folderColorRgb.fullFileExtension.hasAugmentedPermissions.hasThumbnail.headRevisionId.iconLink.id.imageMediaMetadata.isAppAuthorized.lastModifyingUser.md5Checksum.mimeType.modifiedByMe.modifiedByMeTime.modifiedTime.name.originalFilename.ownedByMe.owners.parents.properties.quotaBytesUsed.shared.sharedWithMeTime.sharingUser.size.spaces.starred.teamDriveId.thumbnailLink.thumbnailVersion.trashed.trashedTime.trashingUser.version.videoMediaMetadata.viewedByMe.viewedByMeTime.viewersCanCopyContent.webContentLink.webViewLink.writersCanShare".split(".");
320
+ // src/index.ts
321
+ s.extend(C.default);
322
+ var G = new Set(W), K = /^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/, q = {
323
+ s: "second",
324
+ second: "second",
325
+ seconds: "second",
326
+ m: "minute",
327
+ minute: "minute",
328
+ minutes: "minute",
329
+ h: "hour",
330
+ hour: "hour",
331
+ hours: "hour",
332
+ d: "day",
333
+ day: "day",
334
+ days: "day",
335
+ w: "week",
336
+ week: "week",
337
+ weeks: "week",
338
+ M: "month",
339
+ month: "month",
340
+ months: "month",
341
+ y: "year",
342
+ year: "year",
343
+ years: "year"
344
+ };
345
+ function J(e) {
346
+ return e.replaceAll("\\", "\\\\").replaceAll("'", "\\'");
347
+ }
348
+ function Y(e) {
349
+ let t = K.exec(e);
350
+ if (!t) throw Error(`${w.TAG} Invalid timeSpace "${e}". Expected "<number><unit>" where unit is one of: s, m, h, d, w, M, y, second(s), minute(s), hour(s), day(s), week(s), month(s), year(s).`);
351
+ let n = Number(t[1]), r = q[t[2]];
352
+ if (!Number.isFinite(n) || n <= 0 || !r) throw Error(`${w.TAG} Invalid timeSpace "${e}": amount must be a positive integer.`);
353
+ return {
354
+ amount: n,
355
+ unit: r
356
+ };
357
+ }
358
+ async function X(e, t, n) {
359
+ let r = Math.max(1, Math.floor(t)), i = Array.from({ length: e.length }), a = 0;
360
+ async function o() {
361
+ for (; a < e.length;) {
362
+ let t = a;
363
+ a += 1, i[t] = await n(e[t]);
364
+ }
365
+ }
366
+ let s = Array.from({ length: Math.min(r, e.length) }, () => o());
367
+ return await Promise.all(s), i;
368
+ }
369
+ var Z = class {
370
+ DEFAULT_FIELDS = [
371
+ "createdTime",
372
+ "id",
373
+ "md5Checksum",
374
+ "mimeType",
375
+ "name",
376
+ "parents",
377
+ "trashed"
378
+ ];
379
+ MIME_FOLDER = "application/vnd.google-apps.folder";
380
+ gdriveAuth;
381
+ injectedAuth;
382
+ sharedDriveId;
383
+ defaultDryRun;
384
+ defaultConcurrency;
385
+ defaultCompressionLevel;
386
+ defaultOnProgress;
387
+ retryOptions;
388
+ logger;
389
+ _drive;
390
+ _initPromise;
391
+ constructor(e = {}) {
392
+ this.logger = e.logger ?? console, this.sharedDriveId = e.sharedDriveId, this.defaultDryRun = e.dryRun ?? !1, this.defaultConcurrency = e.concurrency ?? 4, this.defaultCompressionLevel = e.compressionLevel ?? 6, this.defaultOnProgress = e.onProgress, this.retryOptions = e.retry ?? {}, e.drive && (this._drive = e.drive), e.auth && (this.injectedAuth = e.auth), !e.drive && !e.auth && (this.gdriveAuth = new E({
393
+ credentialsFile: e.credentialsFile,
394
+ tokenFile: e.tokenFile,
395
+ serviceAccountFile: e.serviceAccountFile,
396
+ useADC: e.useADC,
397
+ scopes: e.scopes,
398
+ logger: this.logger
399
+ }));
400
+ }
401
+ ensureInitiated() {
402
+ return this._drive || this.injectedAuth ? Promise.resolve(!0) : (this._initPromise ||= this.gdriveAuth.initiate().catch((e) => {
403
+ throw this._initPromise = void 0, e;
404
+ }), this._initPromise);
405
+ }
406
+ get auth() {
407
+ return this.injectedAuth ? this.injectedAuth : this.gdriveAuth.getAuthClient();
408
+ }
409
+ get drive() {
410
+ return this._drive ||= a({
411
+ version: "v3",
412
+ auth: this.auth
413
+ }), this._drive;
414
+ }
415
+ get sharedDriveListParams() {
416
+ return this.sharedDriveId ? {
417
+ supportsAllDrives: !0,
418
+ includeItemsFromAllDrives: !0,
419
+ corpora: "drive",
420
+ driveId: this.sharedDriveId
421
+ } : {};
422
+ }
423
+ get sharedDriveItemParams() {
424
+ return this.sharedDriveId ? { supportsAllDrives: !0 } : {};
425
+ }
426
+ get rootParentId() {
427
+ return this.sharedDriveId ?? "root";
428
+ }
429
+ isFolder(e) {
430
+ if (Object.hasOwn(e, "mimeType")) return e.mimeType === this.MIME_FOLDER;
431
+ }
432
+ isDeleted(e) {
433
+ return Object.hasOwn(e, "trashed") ? !!e.trashed : !1;
434
+ }
435
+ async listFiles(e, t = 1e3, n) {
436
+ await this.ensureInitiated();
437
+ let r;
438
+ if (!e) r = this.DEFAULT_FIELDS;
439
+ else if (e === !0) r = W;
440
+ else {
441
+ for (let t of e) if (!G.has(t)) throw Error(`${w.TAG} Invalid Drive file field: "${t}"`);
442
+ r = e;
443
+ }
444
+ let i = {
445
+ pageSize: t,
446
+ fields: `kind, nextPageToken, incompleteSearch, files(${r.join(", ")})`,
447
+ prettyPrint: !1,
448
+ ...this.sharedDriveListParams
449
+ };
450
+ return n && (i.q = n), this.getListFiles(i);
451
+ }
452
+ async getFile(e) {
453
+ if (await this.ensureInitiated(), !e) throw this.genericError(/* @__PURE__ */ Error(`${w.TAG} File id not found`));
454
+ let t = {
455
+ fileId: e,
456
+ ...this.sharedDriveItemParams
457
+ };
458
+ try {
459
+ let { data: e } = await U(() => this.drive.files.get(t), this.retryOptions);
460
+ return e;
461
+ } catch (e) {
462
+ throw this.genericError(e);
463
+ }
464
+ }
465
+ async downloadFile(t, n, a = {}) {
466
+ if (await this.ensureInitiated(), !t) throw Error(`${w.TAG} File id or name is required for download`);
467
+ let o = t;
468
+ if (a.folderName) {
469
+ let e = await this.findFolderId(a.folderName, !1), n = await this.findFile(t, e);
470
+ if (!n?.id) throw Error(`${w.TAG} File "${t}" not found in folder "${a.folderName}"`);
471
+ o = n.id;
472
+ } else try {
473
+ let e = await U(() => this.drive.files.get({
474
+ fileId: t,
475
+ fields: "id, name, mimeType",
476
+ ...this.sharedDriveItemParams
477
+ }), this.retryOptions);
478
+ e.data.id && (o = e.data.id);
479
+ } catch {
480
+ let e = await this.findFile(t);
481
+ if (!e?.id) throw Error(`${w.TAG} File "${t}" not found`);
482
+ o = e.id;
483
+ }
484
+ e.mkdirSync(r.dirname(r.resolve(n)), { recursive: !0 });
485
+ let s, c = a.decryptKey ? (s = this.createPrivateTempDir(), r.join(s, "download.enc")) : n;
486
+ try {
487
+ let t = await U(() => this.drive.files.get({
488
+ fileId: o,
489
+ alt: "media",
490
+ ...this.sharedDriveItemParams
491
+ }, { responseType: "stream" }), this.retryOptions), r = e.createWriteStream(c, { mode: a.decryptKey ? 384 : 420 });
492
+ return await i(t.data, r), a.decryptKey && await R(c, n, a.decryptKey), n;
493
+ } catch (t) {
494
+ throw a.decryptKey || e.rmSync(n, { force: !0 }), this.genericError(t);
495
+ } finally {
496
+ s && e.rmSync(s, {
497
+ recursive: !0,
498
+ force: !0
499
+ });
500
+ }
501
+ }
502
+ async emptyTrash() {
503
+ return await this.ensureInitiated(), U(() => this.drive.files.emptyTrash(), this.retryOptions);
504
+ }
505
+ async deleteFile(e) {
506
+ if (await this.ensureInitiated(), e.id) try {
507
+ let { data: t } = await U(() => this.drive.files.delete({
508
+ fileId: e.id,
509
+ ...this.sharedDriveItemParams
510
+ }), this.retryOptions);
511
+ return e.name && this.logger.warn(`${w.TAG} Deleted ${e.isFolder ? "folder" : "file"}: ${e.name}`), t;
512
+ } catch (e) {
513
+ throw this.genericError(e);
514
+ }
515
+ }
516
+ async uploadFile(t, n, i = {}) {
517
+ await this.ensureInitiated();
518
+ let { create: a = !0, replace: o = !1, encryptKey: s } = i, l = i.dryRun ?? this.defaultDryRun, u = i.onProgress ?? this.defaultOnProgress, d = r.basename(t), f = s && !d.endsWith(".enc") ? `${d}.enc` : d, p = {
519
+ name: f,
520
+ mimeType: s ? "application/octet-stream" : c.contentType(d) || void 0
521
+ }, m = await this.getUploadFolderId(n || !1, a, p, l);
522
+ if (l) return this.logger.info(`${w.TAG} [dry-run] Would upload "${f}"${n && typeof n == "string" ? ` to "${n}"` : ""}`), this.parseFileMeta(p);
523
+ await this.replaceExistingFile(o, f, m);
524
+ let h, g = t;
525
+ s && (h = this.createPrivateTempDir(), g = r.join(h, f), await L(t, g, s));
526
+ try {
527
+ let t = e.statSync(g).size, { data: n } = await U(async () => {
528
+ let n = e.createReadStream(g);
529
+ n.on("error", (e) => {
530
+ this.logger.error(`${w.TAG} Read stream error for "${g}":`, e);
531
+ });
532
+ let r = {
533
+ requestBody: p,
534
+ media: { body: n },
535
+ fields: `kind, ${this.DEFAULT_FIELDS.join(", ")}`,
536
+ ...this.sharedDriveItemParams
537
+ }, i = (e) => {
538
+ let n = t === 0 ? 100 : Math.min(100, e.bytesRead / t * 100);
539
+ u?.({
540
+ fileName: f,
541
+ bytesRead: e.bytesRead,
542
+ totalBytes: t,
543
+ percentage: n
544
+ }), n >= 100 && this.logger.warn(`${w.TAG} Upload ${f}: ${Math.round(n)}% complete`);
545
+ };
546
+ try {
547
+ return await this.drive.files.create(r, { onUploadProgress: i });
548
+ } finally {
549
+ n.destroy();
550
+ }
551
+ }, this.retryOptions);
552
+ return this.parseFileMeta(n);
553
+ } catch (e) {
554
+ throw this.genericError(e);
555
+ } finally {
556
+ h && e.rmSync(h, {
557
+ recursive: !0,
558
+ force: !0
559
+ });
560
+ }
561
+ }
562
+ async uploadStream(t, n, a, o = {}) {
563
+ await this.ensureInitiated();
564
+ let s = this.sanitizeFilename(n), c = this.createPrivateTempDir(), l = r.join(c, s);
565
+ try {
566
+ let n = e.createWriteStream(l, { mode: 384 });
567
+ return await i(t, n), await this.uploadFile(l, a, o);
568
+ } finally {
569
+ e.rmSync(c, {
570
+ recursive: !0,
571
+ force: !0
572
+ });
573
+ }
574
+ }
575
+ async uploadFiles(t, n, i = {}) {
576
+ await this.ensureInitiated();
577
+ let { compress: a, replace: o, create: c, dryRun: l, encryptKey: u, onProgress: d, exclude: f, followSymlinks: p = !1 } = i, m = i.concurrency ?? this.defaultConcurrency, h = i.compressionLevel ?? this.defaultCompressionLevel, g = Array.isArray(t) ? t : [t], _ = this.expandFileInputs(g, {
578
+ exclude: f,
579
+ followSymlinks: p
580
+ }), v, y = _;
581
+ try {
582
+ if (a) {
583
+ let e = typeof a == "string" ? a : `zipped_${s().format("YYYY-MM-DD.HHmmss")}.zip`, { zipPath: t, tempDir: n } = await this.compressFiles(_, e, {
584
+ compressionLevel: h,
585
+ followSymlinks: p
586
+ });
587
+ v = n, y = [t];
588
+ }
589
+ n && typeof n == "string" && y.length > 0 && !(l ?? this.defaultDryRun) && await this.findFolderId(n, c ?? !0);
590
+ let e = {};
591
+ return await X(y, m, async (t) => {
592
+ let i = await this.uploadFile(t, n, {
593
+ replace: o,
594
+ create: c,
595
+ dryRun: l,
596
+ encryptKey: u,
597
+ onProgress: d
598
+ }), a = i.name || r.basename(t);
599
+ e[a] = i;
600
+ }), e;
601
+ } finally {
602
+ v && e.rmSync(v, {
603
+ recursive: !0,
604
+ force: !0
605
+ });
606
+ }
607
+ }
608
+ async cleanOlder(e, t, n = {}) {
609
+ let { amount: r, unit: i } = Y(e);
610
+ await this.ensureInitiated();
611
+ let a = "";
612
+ return t && (a = await this.findFolderId(t, !1)), this.deleteOlder(r, i, a, n);
613
+ }
614
+ expandFileInputs(t, n) {
615
+ let { exclude: i = [], followSymlinks: a = !1 } = n, o = [], s = (t) => {
616
+ if (t.includes("*")) {
617
+ let n = e.globSync(t, { exclude: i });
618
+ for (let e of n) s(e);
619
+ return;
620
+ }
621
+ if (i.some((e) => r.matchesGlob(t, e) || r.matchesGlob(r.basename(t), e))) return;
622
+ let n = e.lstatSync(t);
623
+ if (n.isSymbolicLink() && !a) this.logger.warn(`${w.TAG} Skipping symlink: ${t}`);
624
+ else if ((n.isSymbolicLink() ? e.statSync(t) : n).isDirectory()) {
625
+ let n = e.readdirSync(t).map((e) => r.join(t, e));
626
+ for (let e of n) s(e);
627
+ } else o.push(t);
628
+ };
629
+ for (let e of t) s(e);
630
+ return o;
631
+ }
632
+ async getListFiles(e) {
633
+ let t = [], n;
634
+ try {
635
+ do {
636
+ let r = n ? {
637
+ ...e,
638
+ pageToken: n
639
+ } : { ...e }, { data: i } = await U(() => this.drive.files.list(r), this.retryOptions);
640
+ i.files?.length && t.push(...i.files), n = i.nextPageToken ?? void 0;
641
+ } while (n);
642
+ return this.parseFilesMeta(t);
643
+ } catch (e) {
644
+ throw this.genericError(e);
645
+ }
646
+ }
647
+ async replaceExistingFile(e, t, n) {
648
+ let r = await this.findFile(t, n);
649
+ if (r) {
650
+ if (!e) throw Error(`${w.TAG} File "${t}" already exists and will not be replaced`);
651
+ this.logger.warn(`${w.TAG} File "${t}" already exists and will be deleted before upload`), await this.deleteFile(r);
652
+ }
653
+ }
654
+ async getUploadFolderId(e, t, n, r = !1) {
655
+ if (e && typeof e == "string") {
656
+ let i = await this.findFolderId(e, t && !r);
657
+ return n.parents = [i], i;
658
+ }
659
+ return this.sharedDriveId && (n.parents = [this.sharedDriveId]), "";
660
+ }
661
+ async deleteOlder(e, t, n, r = {}) {
662
+ let i = r.dryRun ?? this.defaultDryRun, a = Math.max(0, r.keepLast ?? 0), o = r.concurrency ?? this.defaultConcurrency, c = s().subtract(e, t), l = [`mimeType != '${this.MIME_FOLDER}'`, "trashed = false"];
663
+ n && l.push(`'${J(n)}' in parents`), a === 0 && l.push(`createdTime <= '${c.toISOString()}'`);
664
+ let u = (await this.listFiles(void 0, 1e3, l.join(" and "))).filter((e) => !e.isDeleted && !e.isFolder).filter((e) => !n || !!e.parents?.includes(n)).sort((e, t) => {
665
+ let n = e.createdTime ? s(e.createdTime).valueOf() : 0;
666
+ return (t.createdTime ? s(t.createdTime).valueOf() : 0) - n;
667
+ }), d = (a > 0 ? u.slice(a) : u).filter((e) => e.createdTime && s(e.createdTime).isSameOrBefore(c));
668
+ if (i) {
669
+ for (let e of d) this.logger.info(`${w.TAG} [dry-run] Would delete file: ${e.name ?? e.id ?? "unknown"}`);
670
+ return d;
671
+ }
672
+ return await X(d, o, async (e) => {
673
+ await this.deleteFile(e);
674
+ }), d;
675
+ }
676
+ parseFileMeta(e) {
677
+ return {
678
+ ...e,
679
+ isDeleted: this.isDeleted(e),
680
+ isFolder: !!this.isFolder(e)
681
+ };
682
+ }
683
+ parseFilesMeta(e) {
684
+ return e.map((e) => this.parseFileMeta(e));
685
+ }
686
+ genericError(e) {
687
+ return this.logger.error(`${w.TAG} The API returned an error: ${String(e)}`), e;
688
+ }
689
+ inFlightFolders = /* @__PURE__ */ new Map();
690
+ findFolderId(e, t = !1) {
691
+ let n = `${e}::${t}`, r = this.inFlightFolders.get(n);
692
+ if (r) return r;
693
+ let i = this.resolveFolderId(e, t).finally(() => {
694
+ this.inFlightFolders.delete(n);
695
+ });
696
+ return this.inFlightFolders.set(n, i), i;
697
+ }
698
+ async resolveFolderId(e, t = !1) {
699
+ let n = e.split("/").map((e) => e.trim()).filter(Boolean);
700
+ if (n.length === 0) throw Error(`${w.TAG} Invalid folder path "${e}"`);
701
+ let r = this.rootParentId;
702
+ for (let i of n) {
703
+ let n = [
704
+ `name = '${J(i)}'`,
705
+ `mimeType = '${this.MIME_FOLDER}'`,
706
+ "trashed = false",
707
+ `'${J(r)}' in parents`
708
+ ].join(" and "), a = (await this.listFiles(void 0, 100, n)).find((e) => e.isFolder && !e.isDeleted && e.name === i && e.id);
709
+ if (a?.id) r = a.id;
710
+ else if (t) {
711
+ let e = await this.createFolder(i, r);
712
+ if (!e.id) throw Error(`${w.TAG} Failed to create folder "${i}"`);
713
+ r = e.id;
714
+ } else throw Error(`${w.TAG} Folder "${e}" does not exist and will not be created`);
715
+ }
716
+ return r;
717
+ }
718
+ async findFile(e, t) {
719
+ let n = t || this.rootParentId, r = [
720
+ `name = '${J(e)}'`,
721
+ `mimeType != '${this.MIME_FOLDER}'`,
722
+ "trashed = false",
723
+ `'${J(n)}' in parents`
724
+ ].join(" and ");
725
+ return (await this.listFiles(void 0, 100, r)).find((n) => !n.isFolder && !n.isDeleted && n.name === e && (!t || !!n.parents?.includes(t))) ?? null;
726
+ }
727
+ async createFolder(e, t) {
728
+ let n = {
729
+ name: e,
730
+ mimeType: this.MIME_FOLDER
731
+ };
732
+ t && t !== "root" && (n.parents = [t]);
733
+ try {
734
+ let { data: t } = await U(() => this.drive.files.create({
735
+ requestBody: n,
736
+ fields: "id",
737
+ ...this.sharedDriveItemParams
738
+ }), this.retryOptions);
739
+ return t?.id && this.logger.warn(`${w.TAG} Created folder "${e}" with id: "${t.id}"`), t;
740
+ } catch (e) {
741
+ throw this.genericError(e);
742
+ }
743
+ }
744
+ createPrivateTempDir() {
745
+ let t = e.mkdtempSync(r.join(n.tmpdir(), "node-gdrive-"));
746
+ return e.chmodSync(t, 448), t;
747
+ }
748
+ sanitizeFilename(e) {
749
+ let t = r.basename(e);
750
+ if (!t || t === "." || t === "..") throw Error(`${w.TAG} Invalid output filename: "${e}"`);
751
+ return t;
752
+ }
753
+ compressFiles(t, n, i = {}) {
754
+ let a = this.sanitizeFilename(n), s = this.createPrivateTempDir(), c = r.join(s, a), l = i.compressionLevel ?? this.defaultCompressionLevel, u = i.followSymlinks ?? !1;
755
+ return new Promise((n, i) => {
756
+ let a = e.createWriteStream(c, { mode: 384 }), d = [], f = !1, p = (t) => {
757
+ if (!f) {
758
+ f = !0;
759
+ for (let e of d) e.destroy();
760
+ a.destroy(), e.rmSync(s, {
761
+ recursive: !0,
762
+ force: !0
763
+ }), i(t instanceof Error ? t : Error(String(t)));
764
+ }
765
+ }, m = new o({ zlib: { level: l } });
766
+ a.on("error", (e) => {
767
+ p(e);
768
+ }), a.on("close", () => {
769
+ f || (f = !0, n({
770
+ zipPath: c,
771
+ tempDir: s
772
+ }));
773
+ }), m.on("warning", (e) => {
774
+ this.logger.warn(`${w.TAG} Warning compressing file`, e), e.code !== "ENOENT" && p(e);
775
+ }), m.on("error", (e) => {
776
+ this.logger.error(`${w.TAG} Error compressing file`, e), p(e);
777
+ }), m.pipe(a);
778
+ try {
779
+ for (let n of t) {
780
+ let t = e.lstatSync(n);
781
+ if (t.isSymbolicLink() && !u) this.logger.warn(`${w.TAG} Skipping symlink: ${n}`);
782
+ else if ((t.isSymbolicLink() ? e.statSync(n) : t).isDirectory()) m.directory(n, r.basename(n));
783
+ else {
784
+ let t = r.basename(n), i = e.createReadStream(n);
785
+ i.on("error", (e) => {
786
+ p(e);
787
+ }), m.append(i, { name: t }), d.push(i);
788
+ }
789
+ }
790
+ } catch (e) {
791
+ p(e);
792
+ return;
793
+ }
794
+ m.finalize().catch((e) => {
795
+ p(e);
796
+ }).finally(() => {
797
+ for (let e of d) e.destroy();
798
+ });
799
+ });
800
+ }
801
+ };
802
+ export { E as Auth, w as Config, Z as GDrive, W as allFileTypes, I as decryptBuffer, R as decryptFile, F as encryptBuffer, L as encryptFile, J as escapeDriveQuery, H as isRetryableError, Y as parseTimeSpace, U as withRetry };