drivekit 1.1.0 → 1.1.2
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/README.ar.md +31 -13
- package/README.md +10 -4
- package/dist/cli.cjs +661 -163
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +651 -156
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +683 -186
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +112 -12
- package/dist/index.d.ts +112 -12
- package/dist/index.js +679 -185
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -75,6 +75,31 @@ var init_errors = __esm({
|
|
|
75
75
|
}
|
|
76
76
|
});
|
|
77
77
|
|
|
78
|
+
// src/utils/http-agent.ts
|
|
79
|
+
import https from "https";
|
|
80
|
+
import http from "http";
|
|
81
|
+
function getOptimizedHttpsAgent(options) {
|
|
82
|
+
if (!sharedHttpsAgent) {
|
|
83
|
+
sharedHttpsAgent = new https.Agent({
|
|
84
|
+
keepAlive: options?.keepAlive ?? true,
|
|
85
|
+
maxSockets: options?.maxSockets ?? 64,
|
|
86
|
+
maxFreeSockets: options?.maxFreeSockets ?? 32,
|
|
87
|
+
keepAliveMsecs: options?.keepAliveMsecs ?? 6e4,
|
|
88
|
+
timeout: options?.timeout ?? 3e4,
|
|
89
|
+
noDelay: true
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
return sharedHttpsAgent;
|
|
93
|
+
}
|
|
94
|
+
var sharedHttpsAgent;
|
|
95
|
+
var init_http_agent = __esm({
|
|
96
|
+
"src/utils/http-agent.ts"() {
|
|
97
|
+
"use strict";
|
|
98
|
+
init_esm_shims();
|
|
99
|
+
sharedHttpsAgent = null;
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
|
|
78
103
|
// src/auth/authenticator.ts
|
|
79
104
|
import fs from "fs";
|
|
80
105
|
import { auth as googleAuth } from "@googleapis/drive";
|
|
@@ -84,6 +109,7 @@ var init_authenticator = __esm({
|
|
|
84
109
|
"use strict";
|
|
85
110
|
init_esm_shims();
|
|
86
111
|
init_errors();
|
|
112
|
+
init_http_agent();
|
|
87
113
|
DEFAULT_SCOPES = [
|
|
88
114
|
"https://www.googleapis.com/auth/drive"
|
|
89
115
|
];
|
|
@@ -106,44 +132,39 @@ var init_authenticator = __esm({
|
|
|
106
132
|
const oauth2Client = new googleAuth.OAuth2();
|
|
107
133
|
oauth2Client.setCredentials({ access_token: this.config.accessToken });
|
|
108
134
|
this.authClient = oauth2Client;
|
|
109
|
-
|
|
110
|
-
}
|
|
111
|
-
if (this.config.oauth2Client) {
|
|
135
|
+
} else if (this.config.oauth2Client) {
|
|
112
136
|
this.authClient = this.config.oauth2Client;
|
|
113
|
-
|
|
114
|
-
}
|
|
115
|
-
if (this.config.oauth) {
|
|
137
|
+
} else if (this.config.oauth) {
|
|
116
138
|
const { clientId, clientSecret, redirectUri = "http://localhost:3000/oauth2callback", refreshToken } = this.config.oauth;
|
|
117
139
|
const oauth2Client = new googleAuth.OAuth2(clientId, clientSecret, redirectUri);
|
|
118
140
|
if (refreshToken) {
|
|
119
141
|
oauth2Client.setCredentials({ refresh_token: refreshToken });
|
|
120
142
|
}
|
|
121
143
|
this.authClient = oauth2Client;
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
if (keyFile) {
|
|
126
|
-
if (!fs.existsSync(keyFile)) {
|
|
144
|
+
} else if (this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS) {
|
|
145
|
+
const keyFile = this.config.keyFilePath || process.env.GDRIVE_SERVICE_ACCOUNT_PATH || process.env.GOOGLE_APPLICATION_CREDENTIALS;
|
|
146
|
+
if (keyFile && !fs.existsSync(keyFile)) {
|
|
127
147
|
throw new DriveAuthError(`Service account file not found at: ${keyFile}`);
|
|
128
148
|
}
|
|
129
|
-
const
|
|
149
|
+
const auth = new googleAuth.GoogleAuth({
|
|
130
150
|
keyFile,
|
|
131
151
|
scopes
|
|
132
152
|
});
|
|
133
|
-
this.authClient =
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
if (creds) {
|
|
138
|
-
const auth2 = new googleAuth.GoogleAuth({
|
|
153
|
+
this.authClient = auth;
|
|
154
|
+
} else if (this.config.credentials || process.env.GDRIVE_CREDENTIALS_JSON) {
|
|
155
|
+
const creds = this.config.credentials || (process.env.GDRIVE_CREDENTIALS_JSON ? JSON.parse(process.env.GDRIVE_CREDENTIALS_JSON) : null);
|
|
156
|
+
const auth = new googleAuth.GoogleAuth({
|
|
139
157
|
credentials: creds,
|
|
140
158
|
scopes
|
|
141
159
|
});
|
|
142
|
-
this.authClient =
|
|
143
|
-
|
|
160
|
+
this.authClient = auth;
|
|
161
|
+
} else {
|
|
162
|
+
const auth = new googleAuth.GoogleAuth({ scopes });
|
|
163
|
+
this.authClient = auth;
|
|
164
|
+
}
|
|
165
|
+
if (this.authClient?.transporter?.defaults) {
|
|
166
|
+
this.authClient.transporter.defaults.agent = getOptimizedHttpsAgent();
|
|
144
167
|
}
|
|
145
|
-
const auth = new googleAuth.GoogleAuth({ scopes });
|
|
146
|
-
this.authClient = auth;
|
|
147
168
|
return this.authClient;
|
|
148
169
|
} catch (err) {
|
|
149
170
|
if (err instanceof DriveAuthError) throw err;
|
|
@@ -302,6 +323,7 @@ var init_path_resolver = __esm({
|
|
|
302
323
|
drive;
|
|
303
324
|
rootFolderId;
|
|
304
325
|
cache = /* @__PURE__ */ new Map();
|
|
326
|
+
inFlightResolves = /* @__PURE__ */ new Map();
|
|
305
327
|
cacheTTL;
|
|
306
328
|
enableCache;
|
|
307
329
|
metadataCache;
|
|
@@ -325,8 +347,8 @@ var init_path_resolver = __esm({
|
|
|
325
347
|
/**
|
|
326
348
|
* Gets cache key for a path
|
|
327
349
|
*/
|
|
328
|
-
getCacheKey(
|
|
329
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
350
|
+
getCacheKey(path10) {
|
|
351
|
+
return `${this.rootFolderId}:${this.normalizePath(path10)}`;
|
|
330
352
|
}
|
|
331
353
|
/**
|
|
332
354
|
* Clears the path cache
|
|
@@ -340,8 +362,8 @@ var init_path_resolver = __esm({
|
|
|
340
362
|
/**
|
|
341
363
|
* Invalidate a single path from cache
|
|
342
364
|
*/
|
|
343
|
-
invalidatePath(
|
|
344
|
-
const norm = this.normalizePath(
|
|
365
|
+
invalidatePath(path10) {
|
|
366
|
+
const norm = this.normalizePath(path10);
|
|
345
367
|
const key = this.getCacheKey(norm);
|
|
346
368
|
this.cache.delete(key);
|
|
347
369
|
if (this.metadataCache) {
|
|
@@ -354,6 +376,7 @@ var init_path_resolver = __esm({
|
|
|
354
376
|
/**
|
|
355
377
|
* Resolves a path to a Google Drive item (file or folder).
|
|
356
378
|
* If createIfMissing is true, any missing intermediate directories will be automatically created (like mkdir -p).
|
|
379
|
+
* Incorporates in-flight request coalescing to deduplicate concurrent resolutions of identical paths.
|
|
357
380
|
*/
|
|
358
381
|
async resolve(virtualPath, options = {}) {
|
|
359
382
|
const norm = this.normalizePath(virtualPath);
|
|
@@ -387,6 +410,20 @@ var init_path_resolver = __esm({
|
|
|
387
410
|
};
|
|
388
411
|
}
|
|
389
412
|
}
|
|
413
|
+
const flightKey = `${this.rootFolderId}:${norm}:${options.createIfMissing ? "create" : "read"}`;
|
|
414
|
+
const inFlight = this.inFlightResolves.get(flightKey);
|
|
415
|
+
if (inFlight) {
|
|
416
|
+
return await inFlight;
|
|
417
|
+
}
|
|
418
|
+
const task = this.doResolve(virtualPath, norm, options);
|
|
419
|
+
this.inFlightResolves.set(flightKey, task);
|
|
420
|
+
try {
|
|
421
|
+
return await task;
|
|
422
|
+
} finally {
|
|
423
|
+
this.inFlightResolves.delete(flightKey);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
async doResolve(virtualPath, norm, options) {
|
|
390
427
|
const segments = norm.split("/").filter(Boolean);
|
|
391
428
|
let currentParentId = this.rootFolderId;
|
|
392
429
|
let currentPath = "";
|
|
@@ -438,7 +475,7 @@ var init_path_resolver = __esm({
|
|
|
438
475
|
});
|
|
439
476
|
let file = response.data.files?.[0];
|
|
440
477
|
if (!file && currentParentId === this.rootFolderId) {
|
|
441
|
-
const sharedQ = `name = '${escapedName}' and trashed = false`;
|
|
478
|
+
const sharedQ = `name = '${escapedName}' and sharedWithMe = true and trashed = false`;
|
|
442
479
|
const sharedResponse = await withRetry(async () => {
|
|
443
480
|
return await this.drive.files.list({
|
|
444
481
|
q: sharedQ,
|
|
@@ -452,13 +489,14 @@ var init_path_resolver = __esm({
|
|
|
452
489
|
file = sharedResponse.data.files?.[0];
|
|
453
490
|
}
|
|
454
491
|
if (file && file.id) {
|
|
492
|
+
const segmentParentId = currentParentId;
|
|
455
493
|
currentParentId = file.id;
|
|
456
494
|
if (this.metadataCache) {
|
|
457
495
|
this.metadataCache.upsertFile({
|
|
458
496
|
id: file.id,
|
|
459
497
|
name: file.name || segment,
|
|
460
498
|
mimeType: file.mimeType || "",
|
|
461
|
-
parentId:
|
|
499
|
+
parentId: segmentParentId,
|
|
462
500
|
path: currentPath,
|
|
463
501
|
trashed: false
|
|
464
502
|
});
|
|
@@ -496,13 +534,14 @@ var init_path_resolver = __esm({
|
|
|
496
534
|
if (!newFolder.id) {
|
|
497
535
|
throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
|
|
498
536
|
}
|
|
537
|
+
const segmentParentId = currentParentId;
|
|
499
538
|
currentParentId = newFolder.id;
|
|
500
539
|
if (this.metadataCache) {
|
|
501
540
|
this.metadataCache.upsertFile({
|
|
502
541
|
id: newFolder.id,
|
|
503
542
|
name: segment,
|
|
504
543
|
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
505
|
-
parentId:
|
|
544
|
+
parentId: segmentParentId,
|
|
506
545
|
path: currentPath,
|
|
507
546
|
trashed: false
|
|
508
547
|
});
|
|
@@ -566,6 +605,7 @@ var init_format = __esm({
|
|
|
566
605
|
// src/core/resumable-uploader.ts
|
|
567
606
|
import fs2 from "fs";
|
|
568
607
|
import path2 from "path";
|
|
608
|
+
import { Transform } from "stream";
|
|
569
609
|
var MIN_CHUNK_SIZE, DEFAULT_CHUNK_SIZE, MULTIPART_THRESHOLD, ResumableUploader;
|
|
570
610
|
var init_resumable_uploader = __esm({
|
|
571
611
|
"src/core/resumable-uploader.ts"() {
|
|
@@ -575,6 +615,7 @@ var init_resumable_uploader = __esm({
|
|
|
575
615
|
init_format();
|
|
576
616
|
init_mime();
|
|
577
617
|
init_retry();
|
|
618
|
+
init_http_agent();
|
|
578
619
|
MIN_CHUNK_SIZE = 256 * 1024;
|
|
579
620
|
DEFAULT_CHUNK_SIZE = 8 * 1024 * 1024;
|
|
580
621
|
MULTIPART_THRESHOLD = 5 * 1024 * 1024;
|
|
@@ -612,6 +653,15 @@ var init_resumable_uploader = __esm({
|
|
|
612
653
|
const totalBytes = stat.size;
|
|
613
654
|
const fileName = options.name || path2.basename(filePath);
|
|
614
655
|
const mimeType = options.mimeType || lookupMimeType(filePath);
|
|
656
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
657
|
+
const readStream = fs2.createReadStream(filePath, { highWaterMark: 1024 * 1024 });
|
|
658
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(readStream, totalBytes, options.onProgress) : readStream;
|
|
659
|
+
return await this.directUpload(stream, {
|
|
660
|
+
...options,
|
|
661
|
+
name: fileName,
|
|
662
|
+
mimeType
|
|
663
|
+
});
|
|
664
|
+
}
|
|
615
665
|
return await this.chunkedUpload({
|
|
616
666
|
filePath,
|
|
617
667
|
totalBytes,
|
|
@@ -627,6 +677,16 @@ var init_resumable_uploader = __esm({
|
|
|
627
677
|
const totalBytes = buffer.length;
|
|
628
678
|
const fileName = options.name || "untitled";
|
|
629
679
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
680
|
+
if (totalBytes <= MULTIPART_THRESHOLD) {
|
|
681
|
+
const { Readable } = await import("stream");
|
|
682
|
+
const baseStream = Readable.from(totalBytes === 0 ? [] : [buffer]);
|
|
683
|
+
const stream = options.onProgress ? this.wrapStreamWithProgress(baseStream, totalBytes, options.onProgress) : baseStream;
|
|
684
|
+
return await this.directUpload(stream, {
|
|
685
|
+
...options,
|
|
686
|
+
name: fileName,
|
|
687
|
+
mimeType
|
|
688
|
+
});
|
|
689
|
+
}
|
|
630
690
|
return await this.chunkedUploadBuffer({
|
|
631
691
|
buffer,
|
|
632
692
|
totalBytes,
|
|
@@ -647,6 +707,50 @@ var init_resumable_uploader = __esm({
|
|
|
647
707
|
mimeType
|
|
648
708
|
});
|
|
649
709
|
}
|
|
710
|
+
/**
|
|
711
|
+
* Calculates optimal chunk size based on file size for maximum throughput.
|
|
712
|
+
*/
|
|
713
|
+
computeAdaptiveChunkSize(totalBytes, explicitChunkSize) {
|
|
714
|
+
if (explicitChunkSize) {
|
|
715
|
+
return Math.max(MIN_CHUNK_SIZE, Math.floor(explicitChunkSize / MIN_CHUNK_SIZE) * MIN_CHUNK_SIZE);
|
|
716
|
+
}
|
|
717
|
+
if (totalBytes > 128 * 1024 * 1024) {
|
|
718
|
+
return 32 * 1024 * 1024;
|
|
719
|
+
}
|
|
720
|
+
if (totalBytes > 32 * 1024 * 1024) {
|
|
721
|
+
return 16 * 1024 * 1024;
|
|
722
|
+
}
|
|
723
|
+
return this.defaultChunkSize;
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Attaches real-time progress monitoring to direct stream uploads.
|
|
727
|
+
*/
|
|
728
|
+
wrapStreamWithProgress(stream, totalBytes, onProgress) {
|
|
729
|
+
let bytesSent = 0;
|
|
730
|
+
const startTime = Date.now();
|
|
731
|
+
const progressTransform = new Transform({
|
|
732
|
+
transform(chunk, _encoding, callback) {
|
|
733
|
+
bytesSent += chunk.length;
|
|
734
|
+
const elapsedSecs = (Date.now() - startTime) / 1e3;
|
|
735
|
+
const bytesPerSecond = elapsedSecs > 0 ? Math.round(bytesSent / elapsedSecs) : 0;
|
|
736
|
+
const remainingBytes = Math.max(0, totalBytes - bytesSent);
|
|
737
|
+
const estimatedTimeRemainingSeconds = bytesPerSecond > 0 ? Math.round(remainingBytes / bytesPerSecond) : 0;
|
|
738
|
+
const percentage = totalBytes > 0 ? Math.min(100, Math.round(bytesSent / totalBytes * 1e3) / 10) : 100;
|
|
739
|
+
onProgress({
|
|
740
|
+
bytesSent,
|
|
741
|
+
totalBytes,
|
|
742
|
+
percentage,
|
|
743
|
+
bytesPerSecond,
|
|
744
|
+
speedFormatted: formatSpeed(bytesPerSecond),
|
|
745
|
+
estimatedTimeRemainingSeconds,
|
|
746
|
+
chunkIndex: 1,
|
|
747
|
+
totalChunks: 1
|
|
748
|
+
});
|
|
749
|
+
callback(null, chunk);
|
|
750
|
+
}
|
|
751
|
+
});
|
|
752
|
+
return stream.pipe(progressTransform);
|
|
753
|
+
}
|
|
650
754
|
/**
|
|
651
755
|
* Fast direct upload using googleapis multipart
|
|
652
756
|
*/
|
|
@@ -679,7 +783,7 @@ var init_resumable_uploader = __esm({
|
|
|
679
783
|
*/
|
|
680
784
|
async chunkedUpload(params) {
|
|
681
785
|
const { filePath, totalBytes, fileName, mimeType, options } = params;
|
|
682
|
-
const chunkSize =
|
|
786
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
683
787
|
const sessionUrl = await this.initiateResumableSession({
|
|
684
788
|
fileName,
|
|
685
789
|
mimeType,
|
|
@@ -744,7 +848,7 @@ var init_resumable_uploader = __esm({
|
|
|
744
848
|
*/
|
|
745
849
|
async chunkedUploadBuffer(params) {
|
|
746
850
|
const { buffer, totalBytes, fileName, mimeType, options } = params;
|
|
747
|
-
const chunkSize =
|
|
851
|
+
const chunkSize = this.computeAdaptiveChunkSize(totalBytes, options.chunkSize);
|
|
748
852
|
const sessionUrl = await this.initiateResumableSession({
|
|
749
853
|
fileName,
|
|
750
854
|
mimeType,
|
|
@@ -823,7 +927,8 @@ var init_resumable_uploader = __esm({
|
|
|
823
927
|
url: "https://www.googleapis.com/upload/drive/v3/files?uploadType=resumable&supportsAllDrives=true",
|
|
824
928
|
method: "POST",
|
|
825
929
|
headers,
|
|
826
|
-
data: metadata
|
|
930
|
+
data: metadata,
|
|
931
|
+
agent: getOptimizedHttpsAgent()
|
|
827
932
|
});
|
|
828
933
|
});
|
|
829
934
|
const sessionUrl = res.headers?.get ? res.headers.get("location") : res.headers?.location || res.headers?.["location"];
|
|
@@ -849,6 +954,7 @@ var init_resumable_uploader = __esm({
|
|
|
849
954
|
method: "PUT",
|
|
850
955
|
headers,
|
|
851
956
|
data: buffer,
|
|
957
|
+
agent: getOptimizedHttpsAgent(),
|
|
852
958
|
validateStatus: (status) => status >= 200 && status < 300 || status === 308
|
|
853
959
|
});
|
|
854
960
|
if (res.status === 200 || res.status === 201) {
|
|
@@ -883,7 +989,7 @@ var init_resumable_uploader = __esm({
|
|
|
883
989
|
import fs3 from "fs";
|
|
884
990
|
import path3 from "path";
|
|
885
991
|
import { pipeline } from "stream/promises";
|
|
886
|
-
import { Transform } from "stream";
|
|
992
|
+
import { Transform as Transform2 } from "stream";
|
|
887
993
|
var Downloader;
|
|
888
994
|
var init_downloader = __esm({
|
|
889
995
|
"src/core/downloader.ts"() {
|
|
@@ -901,17 +1007,22 @@ var init_downloader = __esm({
|
|
|
901
1007
|
* Downloads a file from Google Drive to local destination path or returns a readable stream.
|
|
902
1008
|
*/
|
|
903
1009
|
async download(fileId, options = {}) {
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
1010
|
+
let name = options.metadata?.name;
|
|
1011
|
+
let mimeType = options.metadata?.mimeType;
|
|
1012
|
+
let totalBytes = options.metadata?.size;
|
|
1013
|
+
if (!name || !mimeType) {
|
|
1014
|
+
const metaRes = await withRetry(async () => {
|
|
1015
|
+
return await this.drive.files.get({
|
|
1016
|
+
fileId,
|
|
1017
|
+
fields: "id, name, mimeType, size",
|
|
1018
|
+
supportsAllDrives: true
|
|
1019
|
+
});
|
|
909
1020
|
});
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
1021
|
+
const file = metaRes.data;
|
|
1022
|
+
name = file.name || "downloaded-file";
|
|
1023
|
+
mimeType = file.mimeType || "application/octet-stream";
|
|
1024
|
+
totalBytes = file.size ? parseInt(file.size, 10) : void 0;
|
|
1025
|
+
}
|
|
915
1026
|
let downloadStream;
|
|
916
1027
|
let finalFileName = name;
|
|
917
1028
|
if (isGoogleWorkspaceDoc(mimeType)) {
|
|
@@ -942,7 +1053,7 @@ var init_downloader = __esm({
|
|
|
942
1053
|
}
|
|
943
1054
|
let bytesRead = 0;
|
|
944
1055
|
const startTime = Date.now();
|
|
945
|
-
const progressTracker = new
|
|
1056
|
+
const progressTracker = new Transform2({
|
|
946
1057
|
transform(chunk, encoding, callback) {
|
|
947
1058
|
bytesRead += chunk.length;
|
|
948
1059
|
if (options.onProgress) {
|
|
@@ -967,7 +1078,7 @@ var init_downloader = __esm({
|
|
|
967
1078
|
destPath = path3.join(destPath, finalFileName);
|
|
968
1079
|
}
|
|
969
1080
|
await fs3.promises.mkdir(path3.dirname(destPath), { recursive: true });
|
|
970
|
-
const writeStream = fs3.createWriteStream(destPath);
|
|
1081
|
+
const writeStream = fs3.createWriteStream(destPath, { highWaterMark: 1024 * 1024 });
|
|
971
1082
|
await pipeline(monitoredStream, writeStream);
|
|
972
1083
|
return {
|
|
973
1084
|
filePath: destPath,
|
|
@@ -1218,6 +1329,7 @@ var init_query_builder = __esm({
|
|
|
1218
1329
|
const q = this.toQueryString();
|
|
1219
1330
|
const orderBy = this.orderClauses.join(", ");
|
|
1220
1331
|
let pageToken = void 0;
|
|
1332
|
+
const effectiveFields = this.requestedFields.includes("nextPageToken") ? this.requestedFields : `nextPageToken, ${this.requestedFields}`;
|
|
1221
1333
|
do {
|
|
1222
1334
|
const res = await withRetry(async () => {
|
|
1223
1335
|
return await this.drive.files.list({
|
|
@@ -1225,7 +1337,7 @@ var init_query_builder = __esm({
|
|
|
1225
1337
|
orderBy: orderBy || void 0,
|
|
1226
1338
|
pageSize: this.limitNumber,
|
|
1227
1339
|
pageToken,
|
|
1228
|
-
fields:
|
|
1340
|
+
fields: effectiveFields,
|
|
1229
1341
|
spaces: this.spaces,
|
|
1230
1342
|
supportsAllDrives: true,
|
|
1231
1343
|
includeItemsFromAllDrives: true
|
|
@@ -1362,7 +1474,7 @@ var init_watcher = __esm({
|
|
|
1362
1474
|
const res = await withRetry(async () => {
|
|
1363
1475
|
return await this.drive.changes.list({
|
|
1364
1476
|
pageToken: nextPageToken,
|
|
1365
|
-
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, modifiedTime, parents, trashed))",
|
|
1477
|
+
fields: "nextPageToken, newStartPageToken, changes(changeType, fileId, removed, time, file(id, name, mimeType, size, createdTime, modifiedTime, parents, trashed))",
|
|
1366
1478
|
supportsAllDrives: true,
|
|
1367
1479
|
includeItemsFromAllDrives: true
|
|
1368
1480
|
});
|
|
@@ -1461,16 +1573,24 @@ var init_storage_cleaner = __esm({
|
|
|
1461
1573
|
async findDuplicates(options = {}) {
|
|
1462
1574
|
const mode = options.by || "name";
|
|
1463
1575
|
const maxScan = options.maxScan || 1e3;
|
|
1464
|
-
const
|
|
1465
|
-
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1576
|
+
const files = [];
|
|
1577
|
+
let pageToken = void 0;
|
|
1578
|
+
do {
|
|
1579
|
+
const remaining = maxScan - files.length;
|
|
1580
|
+
if (remaining <= 0) break;
|
|
1581
|
+
const res = await withRetry(async () => {
|
|
1582
|
+
return await this.drive.files.list({
|
|
1583
|
+
q: 'trashed = false and mimeType != "application/vnd.google-apps.folder"',
|
|
1584
|
+
pageSize: Math.min(1e3, remaining),
|
|
1585
|
+
pageToken,
|
|
1586
|
+
fields: "nextPageToken, files(id, name, size, md5Checksum, modifiedTime)",
|
|
1587
|
+
supportsAllDrives: true,
|
|
1588
|
+
includeItemsFromAllDrives: true
|
|
1589
|
+
});
|
|
1471
1590
|
});
|
|
1472
|
-
|
|
1473
|
-
|
|
1591
|
+
files.push(...res.data.files || []);
|
|
1592
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
1593
|
+
} while (pageToken && files.length < maxScan);
|
|
1474
1594
|
const map = /* @__PURE__ */ new Map();
|
|
1475
1595
|
for (const f of files) {
|
|
1476
1596
|
if (!f.id) continue;
|
|
@@ -1655,7 +1775,7 @@ var init_smart_sync = __esm({
|
|
|
1655
1775
|
});
|
|
1656
1776
|
|
|
1657
1777
|
// src/auth/browser-login.ts
|
|
1658
|
-
import
|
|
1778
|
+
import http2 from "http";
|
|
1659
1779
|
import { exec } from "child_process";
|
|
1660
1780
|
import { auth as googleAuth2 } from "@googleapis/drive";
|
|
1661
1781
|
async function loginWithBrowser(options) {
|
|
@@ -1673,7 +1793,7 @@ async function loginWithBrowser(options) {
|
|
|
1673
1793
|
scope: scopes
|
|
1674
1794
|
});
|
|
1675
1795
|
return new Promise((resolve, reject) => {
|
|
1676
|
-
const server =
|
|
1796
|
+
const server = http2.createServer(async (req, res) => {
|
|
1677
1797
|
try {
|
|
1678
1798
|
const reqUrl = new URL(req.url || "/", `http://localhost:${port}`);
|
|
1679
1799
|
if (reqUrl.pathname === "/oauth2callback") {
|
|
@@ -1757,7 +1877,11 @@ ${authUrl}
|
|
|
1757
1877
|
});
|
|
1758
1878
|
});
|
|
1759
1879
|
server.on("error", (err) => {
|
|
1760
|
-
|
|
1880
|
+
if (err.code === "EADDRINUSE") {
|
|
1881
|
+
reject(new Error(`Port ${port} is already in use by another process. Please specify an alternate port with --port <number>.`));
|
|
1882
|
+
} else {
|
|
1883
|
+
reject(err);
|
|
1884
|
+
}
|
|
1761
1885
|
});
|
|
1762
1886
|
});
|
|
1763
1887
|
}
|
|
@@ -1902,6 +2026,7 @@ var init_resource_refs = __esm({
|
|
|
1902
2026
|
});
|
|
1903
2027
|
|
|
1904
2028
|
// src/core/plugins.ts
|
|
2029
|
+
import path5 from "path";
|
|
1905
2030
|
var PluginManager;
|
|
1906
2031
|
var init_plugins = __esm({
|
|
1907
2032
|
"src/core/plugins.ts"() {
|
|
@@ -1909,10 +2034,36 @@ var init_plugins = __esm({
|
|
|
1909
2034
|
init_esm_shims();
|
|
1910
2035
|
PluginManager = class {
|
|
1911
2036
|
plugins = [];
|
|
2037
|
+
/**
|
|
2038
|
+
* Register a plugin. If a plugin with the same name already exists,
|
|
2039
|
+
* it replaces the old one to avoid duplicate side-effects.
|
|
2040
|
+
*/
|
|
1912
2041
|
use(plugin) {
|
|
2042
|
+
this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
|
|
1913
2043
|
this.plugins.push(plugin);
|
|
1914
2044
|
return this;
|
|
1915
2045
|
}
|
|
2046
|
+
/**
|
|
2047
|
+
* Unregister a plugin by its name.
|
|
2048
|
+
* Returns true if a plugin was found and removed, false otherwise.
|
|
2049
|
+
*/
|
|
2050
|
+
unuse(pluginName) {
|
|
2051
|
+
const initialLen = this.plugins.length;
|
|
2052
|
+
this.plugins = this.plugins.filter((p) => p.name !== pluginName);
|
|
2053
|
+
return this.plugins.length < initialLen;
|
|
2054
|
+
}
|
|
2055
|
+
/**
|
|
2056
|
+
* Check if a plugin with given name is currently active
|
|
2057
|
+
*/
|
|
2058
|
+
has(pluginName) {
|
|
2059
|
+
return this.plugins.some((p) => p.name === pluginName);
|
|
2060
|
+
}
|
|
2061
|
+
/**
|
|
2062
|
+
* Returns all currently registered plugins
|
|
2063
|
+
*/
|
|
2064
|
+
getPlugins() {
|
|
2065
|
+
return [...this.plugins];
|
|
2066
|
+
}
|
|
1916
2067
|
async runBeforeUpload(options) {
|
|
1917
2068
|
let current = { ...options };
|
|
1918
2069
|
for (const plugin of this.plugins) {
|
|
@@ -1959,7 +2110,7 @@ var init_plugins = __esm({
|
|
|
1959
2110
|
|
|
1960
2111
|
// src/core/cache.ts
|
|
1961
2112
|
import os from "os";
|
|
1962
|
-
import
|
|
2113
|
+
import path6 from "path";
|
|
1963
2114
|
import fs5 from "fs";
|
|
1964
2115
|
var SqliteMetadataCache, MemoryMetadataCache;
|
|
1965
2116
|
var init_cache = __esm({
|
|
@@ -1975,14 +2126,14 @@ var init_cache = __esm({
|
|
|
1975
2126
|
if (customPath) {
|
|
1976
2127
|
this.dbPath = customPath;
|
|
1977
2128
|
} else {
|
|
1978
|
-
const dir =
|
|
2129
|
+
const dir = path6.join(os.homedir(), ".drivekit");
|
|
1979
2130
|
if (!fs5.existsSync(dir)) {
|
|
1980
2131
|
try {
|
|
1981
2132
|
fs5.mkdirSync(dir, { recursive: true });
|
|
1982
2133
|
} catch {
|
|
1983
2134
|
}
|
|
1984
2135
|
}
|
|
1985
|
-
this.dbPath =
|
|
2136
|
+
this.dbPath = path6.join(dir, "cache.db");
|
|
1986
2137
|
}
|
|
1987
2138
|
}
|
|
1988
2139
|
init() {
|
|
@@ -2000,7 +2151,7 @@ var init_cache = __esm({
|
|
|
2000
2151
|
CREATE TABLE IF NOT EXISTS files (
|
|
2001
2152
|
id TEXT PRIMARY KEY,
|
|
2002
2153
|
name TEXT NOT NULL,
|
|
2003
|
-
mimeType TEXT
|
|
2154
|
+
mimeType TEXT,
|
|
2004
2155
|
size INTEGER,
|
|
2005
2156
|
parentId TEXT,
|
|
2006
2157
|
path TEXT,
|
|
@@ -2086,7 +2237,7 @@ var init_cache = __esm({
|
|
|
2086
2237
|
stmt.run(
|
|
2087
2238
|
entry.id,
|
|
2088
2239
|
entry.name,
|
|
2089
|
-
entry.mimeType,
|
|
2240
|
+
entry.mimeType ?? null,
|
|
2090
2241
|
entry.size ?? null,
|
|
2091
2242
|
entry.parentId ?? null,
|
|
2092
2243
|
entry.path ?? null,
|
|
@@ -2102,10 +2253,35 @@ var init_cache = __esm({
|
|
|
2102
2253
|
return;
|
|
2103
2254
|
}
|
|
2104
2255
|
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2256
|
+
const stmt = this.db.prepare(`
|
|
2257
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2258
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2259
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2260
|
+
name = excluded.name,
|
|
2261
|
+
mimeType = excluded.mimeType,
|
|
2262
|
+
size = excluded.size,
|
|
2263
|
+
parentId = excluded.parentId,
|
|
2264
|
+
path = COALESCE(excluded.path, files.path),
|
|
2265
|
+
md5Checksum = excluded.md5Checksum,
|
|
2266
|
+
trashed = excluded.trashed,
|
|
2267
|
+
modifiedTime = excluded.modifiedTime,
|
|
2268
|
+
updatedAt = excluded.updatedAt
|
|
2269
|
+
`);
|
|
2105
2270
|
this.db.exec("BEGIN TRANSACTION;");
|
|
2106
2271
|
try {
|
|
2107
2272
|
for (const entry of entries) {
|
|
2108
|
-
|
|
2273
|
+
stmt.run(
|
|
2274
|
+
entry.id,
|
|
2275
|
+
entry.name,
|
|
2276
|
+
entry.mimeType ?? null,
|
|
2277
|
+
entry.size ?? null,
|
|
2278
|
+
entry.parentId ?? null,
|
|
2279
|
+
entry.path ?? null,
|
|
2280
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2281
|
+
entry.trashed ? 1 : 0,
|
|
2282
|
+
entry.modifiedTime ?? null,
|
|
2283
|
+
entry.updatedAt ?? Date.now()
|
|
2284
|
+
);
|
|
2109
2285
|
}
|
|
2110
2286
|
this.db.exec("COMMIT;");
|
|
2111
2287
|
} catch (e) {
|
|
@@ -2122,6 +2298,30 @@ var init_cache = __esm({
|
|
|
2122
2298
|
const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2123
2299
|
stmt.run(id);
|
|
2124
2300
|
}
|
|
2301
|
+
pruneMissing(activeIds) {
|
|
2302
|
+
if (this.fallbackMemory) {
|
|
2303
|
+
return this.fallbackMemory.pruneMissing(activeIds);
|
|
2304
|
+
}
|
|
2305
|
+
if (!this.initialized || !this.db || activeIds.length === 0) return 0;
|
|
2306
|
+
const idSet = new Set(activeIds);
|
|
2307
|
+
const rows = this.db.prepare("SELECT id FROM files").all();
|
|
2308
|
+
let pruned = 0;
|
|
2309
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2310
|
+
try {
|
|
2311
|
+
const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2312
|
+
for (const row of rows) {
|
|
2313
|
+
if (!idSet.has(row.id)) {
|
|
2314
|
+
deleteStmt.run(row.id);
|
|
2315
|
+
pruned++;
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
this.db.exec("COMMIT;");
|
|
2319
|
+
return pruned;
|
|
2320
|
+
} catch (e) {
|
|
2321
|
+
this.db.exec("ROLLBACK;");
|
|
2322
|
+
throw e;
|
|
2323
|
+
}
|
|
2324
|
+
}
|
|
2125
2325
|
clear() {
|
|
2126
2326
|
if (this.fallbackMemory) {
|
|
2127
2327
|
this.fallbackMemory.clear();
|
|
@@ -2252,6 +2452,17 @@ var init_cache = __esm({
|
|
|
2252
2452
|
deleteFile(id) {
|
|
2253
2453
|
this.files.delete(id);
|
|
2254
2454
|
}
|
|
2455
|
+
pruneMissing(activeIds) {
|
|
2456
|
+
const idSet = new Set(activeIds);
|
|
2457
|
+
let pruned = 0;
|
|
2458
|
+
for (const id of Array.from(this.files.keys())) {
|
|
2459
|
+
if (!idSet.has(id)) {
|
|
2460
|
+
this.files.delete(id);
|
|
2461
|
+
pruned++;
|
|
2462
|
+
}
|
|
2463
|
+
}
|
|
2464
|
+
return pruned;
|
|
2465
|
+
}
|
|
2255
2466
|
clear() {
|
|
2256
2467
|
this.files.clear();
|
|
2257
2468
|
this.meta.clear();
|
|
@@ -2292,26 +2503,58 @@ var init_cache = __esm({
|
|
|
2292
2503
|
// src/server/webdav.ts
|
|
2293
2504
|
var webdav_exports = {};
|
|
2294
2505
|
__export(webdav_exports, {
|
|
2506
|
+
escapeXml: () => escapeXml,
|
|
2295
2507
|
startWebDAVServer: () => startWebDAVServer
|
|
2296
2508
|
});
|
|
2297
|
-
import
|
|
2509
|
+
import http3 from "http";
|
|
2298
2510
|
import url from "url";
|
|
2299
|
-
import
|
|
2511
|
+
import path7 from "path";
|
|
2512
|
+
function escapeXml(unsafe) {
|
|
2513
|
+
return unsafe.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
2514
|
+
}
|
|
2300
2515
|
async function startWebDAVServer(drive2, options = {}) {
|
|
2301
2516
|
const port = options.port || 8080;
|
|
2302
2517
|
const host = options.host || "127.0.0.1";
|
|
2303
2518
|
await drive2.init();
|
|
2304
|
-
const server =
|
|
2519
|
+
const server = http3.createServer(async (req, res) => {
|
|
2305
2520
|
try {
|
|
2521
|
+
if (options.auth?.username && options.auth?.password) {
|
|
2522
|
+
const authHeader = req.headers["authorization"];
|
|
2523
|
+
if (!authHeader || !authHeader.startsWith("Basic ")) {
|
|
2524
|
+
res.writeHead(401, {
|
|
2525
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
2526
|
+
"Content-Type": "text/plain"
|
|
2527
|
+
});
|
|
2528
|
+
res.end("Authentication required");
|
|
2529
|
+
return;
|
|
2530
|
+
}
|
|
2531
|
+
const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
|
|
2532
|
+
const [user, pass] = credentials.split(":");
|
|
2533
|
+
if (user !== options.auth.username || pass !== options.auth.password) {
|
|
2534
|
+
res.writeHead(401, {
|
|
2535
|
+
"WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
|
|
2536
|
+
"Content-Type": "text/plain"
|
|
2537
|
+
});
|
|
2538
|
+
res.end("Invalid credentials");
|
|
2539
|
+
return;
|
|
2540
|
+
}
|
|
2541
|
+
}
|
|
2306
2542
|
const parsedUrl = url.parse(req.url || "/", true);
|
|
2307
2543
|
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
2308
2544
|
const virtualPath = decodedPath === "" ? "/" : decodedPath;
|
|
2545
|
+
const baseName = path7.basename(virtualPath);
|
|
2546
|
+
if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
|
|
2547
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2548
|
+
res.end("Not Found");
|
|
2549
|
+
return;
|
|
2550
|
+
}
|
|
2309
2551
|
switch (req.method) {
|
|
2310
2552
|
case "OPTIONS": {
|
|
2311
2553
|
res.writeHead(200, {
|
|
2312
2554
|
DAV: "1, 2",
|
|
2313
2555
|
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
2314
|
-
"MS-Author-Via": "DAV"
|
|
2556
|
+
"MS-Author-Via": "DAV",
|
|
2557
|
+
"Accept-Ranges": "bytes"
|
|
2315
2558
|
});
|
|
2316
2559
|
res.end();
|
|
2317
2560
|
return;
|
|
@@ -2319,6 +2562,11 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2319
2562
|
case "PROPFIND": {
|
|
2320
2563
|
const depth = req.headers["depth"] || "1";
|
|
2321
2564
|
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
2565
|
+
if (xml === null) {
|
|
2566
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2567
|
+
res.end("Not Found");
|
|
2568
|
+
return;
|
|
2569
|
+
}
|
|
2322
2570
|
res.writeHead(207, {
|
|
2323
2571
|
"Content-Type": "application/xml; charset=utf-8"
|
|
2324
2572
|
});
|
|
@@ -2329,7 +2577,7 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2329
2577
|
case "HEAD": {
|
|
2330
2578
|
if (virtualPath === "/" || virtualPath === "") {
|
|
2331
2579
|
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
2332
|
-
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
|
|
2580
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
|
|
2333
2581
|
return;
|
|
2334
2582
|
}
|
|
2335
2583
|
try {
|
|
@@ -2339,15 +2587,42 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2339
2587
|
res.end("Cannot GET a directory");
|
|
2340
2588
|
return;
|
|
2341
2589
|
}
|
|
2342
|
-
const
|
|
2343
|
-
|
|
2344
|
-
|
|
2345
|
-
"
|
|
2346
|
-
|
|
2347
|
-
|
|
2348
|
-
|
|
2590
|
+
const fileSize = file.size ? parseInt(file.size, 10) : void 0;
|
|
2591
|
+
const rangeHeader = req.headers["range"];
|
|
2592
|
+
if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
|
|
2593
|
+
const parts = rangeHeader.replace("bytes=", "").split("-");
|
|
2594
|
+
const start = parseInt(parts[0], 10);
|
|
2595
|
+
const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
|
|
2596
|
+
if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
|
|
2597
|
+
res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
|
|
2598
|
+
res.end();
|
|
2599
|
+
return;
|
|
2600
|
+
}
|
|
2601
|
+
const stream = await drive2.createReadStream(virtualPath, { start, end });
|
|
2602
|
+
const chunkLength = end - start + 1;
|
|
2603
|
+
res.writeHead(206, {
|
|
2604
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
2605
|
+
"Content-Range": `bytes ${start}-${end}/${fileSize}`,
|
|
2606
|
+
"Content-Length": chunkLength,
|
|
2607
|
+
"Accept-Ranges": "bytes"
|
|
2608
|
+
});
|
|
2609
|
+
if (req.method === "HEAD") {
|
|
2610
|
+
res.end();
|
|
2611
|
+
} else {
|
|
2612
|
+
stream.pipe(res);
|
|
2613
|
+
}
|
|
2349
2614
|
} else {
|
|
2350
|
-
stream.
|
|
2615
|
+
const stream = await drive2.createReadStream(virtualPath);
|
|
2616
|
+
res.writeHead(200, {
|
|
2617
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
2618
|
+
"Content-Length": file.size || void 0,
|
|
2619
|
+
"Accept-Ranges": "bytes"
|
|
2620
|
+
});
|
|
2621
|
+
if (req.method === "HEAD") {
|
|
2622
|
+
res.end();
|
|
2623
|
+
} else {
|
|
2624
|
+
stream.pipe(res);
|
|
2625
|
+
}
|
|
2351
2626
|
}
|
|
2352
2627
|
} catch (e) {
|
|
2353
2628
|
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
@@ -2356,27 +2631,29 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2356
2631
|
return;
|
|
2357
2632
|
}
|
|
2358
2633
|
case "PUT": {
|
|
2359
|
-
const remoteDir =
|
|
2360
|
-
const fileName = path6.basename(virtualPath);
|
|
2634
|
+
const remoteDir = path7.dirname(virtualPath);
|
|
2361
2635
|
await drive2.mkdirp(remoteDir);
|
|
2362
|
-
|
|
2363
|
-
|
|
2364
|
-
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
await drive2.upload({
|
|
2368
|
-
source: buffer,
|
|
2369
|
-
filename: fileName,
|
|
2370
|
-
parent: remoteDir,
|
|
2371
|
-
overwrite: true
|
|
2372
|
-
});
|
|
2373
|
-
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
2374
|
-
res.end("Created");
|
|
2375
|
-
} catch (err) {
|
|
2376
|
-
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2377
|
-
res.end(err.message || "Upload failed");
|
|
2636
|
+
let existed = false;
|
|
2637
|
+
try {
|
|
2638
|
+
const existingFile = await drive2.getFile(virtualPath);
|
|
2639
|
+
if (existingFile && existingFile.id) {
|
|
2640
|
+
existed = true;
|
|
2378
2641
|
}
|
|
2379
|
-
}
|
|
2642
|
+
} catch {
|
|
2643
|
+
existed = false;
|
|
2644
|
+
}
|
|
2645
|
+
try {
|
|
2646
|
+
const uploadStream = await drive2.createWriteStream(virtualPath, {
|
|
2647
|
+
overwrite: true
|
|
2648
|
+
});
|
|
2649
|
+
req.pipe(uploadStream);
|
|
2650
|
+
await uploadStream.done;
|
|
2651
|
+
res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
|
|
2652
|
+
res.end(existed ? "" : "Created");
|
|
2653
|
+
} catch (err) {
|
|
2654
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2655
|
+
res.end(err.message || "Upload failed");
|
|
2656
|
+
}
|
|
2380
2657
|
return;
|
|
2381
2658
|
}
|
|
2382
2659
|
case "MKCOL": {
|
|
@@ -2408,14 +2685,24 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2408
2685
|
res.end("Destination header missing");
|
|
2409
2686
|
return;
|
|
2410
2687
|
}
|
|
2411
|
-
const destUrl = url.parse(destination);
|
|
2412
|
-
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2413
|
-
const newName = path6.basename(destPath);
|
|
2414
|
-
const newParent = path6.dirname(destPath);
|
|
2415
2688
|
try {
|
|
2416
|
-
await drive2.
|
|
2417
|
-
if (
|
|
2418
|
-
|
|
2689
|
+
const file = await drive2.getFile(virtualPath);
|
|
2690
|
+
if (!file?.id) {
|
|
2691
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2692
|
+
res.end("Source file not found");
|
|
2693
|
+
return;
|
|
2694
|
+
}
|
|
2695
|
+
const destUrl = url.parse(destination);
|
|
2696
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2697
|
+
const newName = path7.basename(destPath);
|
|
2698
|
+
const newParentDir = path7.dirname(destPath);
|
|
2699
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2700
|
+
const currentParentDir = path7.dirname(virtualPath);
|
|
2701
|
+
if (newParentDir !== currentParentDir) {
|
|
2702
|
+
await drive2.move(file.id, newParentFolderId);
|
|
2703
|
+
}
|
|
2704
|
+
if (newName !== path7.basename(virtualPath)) {
|
|
2705
|
+
await drive2.rename(file.id, newName);
|
|
2419
2706
|
}
|
|
2420
2707
|
res.writeHead(201);
|
|
2421
2708
|
res.end("Moved");
|
|
@@ -2425,6 +2712,34 @@ async function startWebDAVServer(drive2, options = {}) {
|
|
|
2425
2712
|
}
|
|
2426
2713
|
return;
|
|
2427
2714
|
}
|
|
2715
|
+
case "COPY": {
|
|
2716
|
+
const destination = req.headers["destination"];
|
|
2717
|
+
if (!destination || typeof destination !== "string") {
|
|
2718
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
2719
|
+
res.end("Destination header missing");
|
|
2720
|
+
return;
|
|
2721
|
+
}
|
|
2722
|
+
try {
|
|
2723
|
+
const file = await drive2.getFile(virtualPath);
|
|
2724
|
+
if (!file?.id) {
|
|
2725
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
2726
|
+
res.end("Source file not found");
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
const destUrl = url.parse(destination);
|
|
2730
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
2731
|
+
const newName = path7.basename(destPath);
|
|
2732
|
+
const newParentDir = path7.dirname(destPath);
|
|
2733
|
+
const newParentFolderId = await drive2.mkdirp(newParentDir);
|
|
2734
|
+
await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
|
|
2735
|
+
res.writeHead(201);
|
|
2736
|
+
res.end("Copied");
|
|
2737
|
+
} catch (err) {
|
|
2738
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
2739
|
+
res.end(err.message);
|
|
2740
|
+
}
|
|
2741
|
+
return;
|
|
2742
|
+
}
|
|
2428
2743
|
default: {
|
|
2429
2744
|
res.writeHead(501, { "Content-Type": "text/plain" });
|
|
2430
2745
|
res.end("Method Not Implemented");
|
|
@@ -2462,25 +2777,38 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
2462
2777
|
virtualPath,
|
|
2463
2778
|
isFolder,
|
|
2464
2779
|
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
2465
|
-
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2780
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
2781
|
+
selfItem.mimeType || void 0
|
|
2466
2782
|
)
|
|
2467
2783
|
);
|
|
2468
2784
|
} catch {
|
|
2469
|
-
return
|
|
2785
|
+
return null;
|
|
2470
2786
|
}
|
|
2471
2787
|
}
|
|
2472
2788
|
if (isFolder && depth !== "0") {
|
|
2473
2789
|
try {
|
|
2474
2790
|
const children = await drive2.ls(virtualPath);
|
|
2791
|
+
const seenNames = /* @__PURE__ */ new Map();
|
|
2475
2792
|
for (const child of children) {
|
|
2793
|
+
let childName = child.name || "untitled";
|
|
2794
|
+
if (seenNames.has(childName)) {
|
|
2795
|
+
const count = seenNames.get(childName) + 1;
|
|
2796
|
+
seenNames.set(childName, count);
|
|
2797
|
+
const ext = path7.extname(childName);
|
|
2798
|
+
const base = path7.basename(childName, ext);
|
|
2799
|
+
childName = `${base} (${count})${ext}`;
|
|
2800
|
+
} else {
|
|
2801
|
+
seenNames.set(childName, 0);
|
|
2802
|
+
}
|
|
2476
2803
|
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
2477
|
-
const childPath = virtualPath === "/" ? `/${
|
|
2804
|
+
const childPath = virtualPath === "/" ? `/${childName}` : `${virtualPath}/${childName}`;
|
|
2478
2805
|
responses.push(
|
|
2479
2806
|
renderWebDAVResponse(
|
|
2480
2807
|
childPath,
|
|
2481
2808
|
childIsFolder,
|
|
2482
2809
|
child.size ? parseInt(child.size, 10) : 0,
|
|
2483
|
-
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
2810
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString(),
|
|
2811
|
+
child.mimeType || void 0
|
|
2484
2812
|
)
|
|
2485
2813
|
);
|
|
2486
2814
|
}
|
|
@@ -2492,19 +2820,25 @@ async function handlePropfind(drive2, virtualPath, depth) {
|
|
|
2492
2820
|
${responses.join("\n")}
|
|
2493
2821
|
</D:multistatus>`;
|
|
2494
2822
|
}
|
|
2495
|
-
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
2496
|
-
|
|
2823
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
|
|
2824
|
+
let cleanHref = href;
|
|
2825
|
+
if (isDir && !cleanHref.endsWith("/")) {
|
|
2826
|
+
cleanHref += "/";
|
|
2827
|
+
}
|
|
2828
|
+
const encodedHref = encodeURI(cleanHref);
|
|
2829
|
+
const displayName = escapeXml(path7.basename(href) || "root");
|
|
2497
2830
|
const resourceType = isDir ? "<D:collection/>" : "";
|
|
2498
2831
|
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
2832
|
+
const contentTypeTag = !isDir && mimeType ? `
|
|
2833
|
+
<D:getcontenttype>${escapeXml(mimeType)}</D:getcontenttype>` : "";
|
|
2499
2834
|
return ` <D:response>
|
|
2500
2835
|
<D:href>${encodedHref}</D:href>
|
|
2501
2836
|
<D:propstat>
|
|
2502
2837
|
<D:prop>
|
|
2503
|
-
<D:displayname>${
|
|
2838
|
+
<D:displayname>${displayName}</D:displayname>
|
|
2504
2839
|
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
2505
2840
|
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
2506
|
-
<D:getlastmodified>${dateFormatted}</D:getlastmodified
|
|
2507
|
-
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2841
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>${contentTypeTag}
|
|
2508
2842
|
</D:prop>
|
|
2509
2843
|
<D:status>HTTP/1.1 200 OK</D:status>
|
|
2510
2844
|
</D:propstat>
|
|
@@ -2523,7 +2857,7 @@ __export(client_exports, {
|
|
|
2523
2857
|
DriveKit: () => DriveKit
|
|
2524
2858
|
});
|
|
2525
2859
|
import fs6 from "fs";
|
|
2526
|
-
import
|
|
2860
|
+
import path8 from "path";
|
|
2527
2861
|
import { drive } from "@googleapis/drive";
|
|
2528
2862
|
var DriveKit;
|
|
2529
2863
|
var init_client = __esm({
|
|
@@ -2546,6 +2880,7 @@ var init_client = __esm({
|
|
|
2546
2880
|
init_format();
|
|
2547
2881
|
init_mime();
|
|
2548
2882
|
init_cache();
|
|
2883
|
+
init_http_agent();
|
|
2549
2884
|
DriveKit = class _DriveKit {
|
|
2550
2885
|
options;
|
|
2551
2886
|
authenticator;
|
|
@@ -2568,6 +2903,18 @@ var init_client = __esm({
|
|
|
2568
2903
|
this.pluginManager.use(plugin);
|
|
2569
2904
|
return this;
|
|
2570
2905
|
}
|
|
2906
|
+
/**
|
|
2907
|
+
* Unregisters a middleware plugin by name
|
|
2908
|
+
*/
|
|
2909
|
+
unuse(pluginName) {
|
|
2910
|
+
return this.pluginManager.unuse(pluginName);
|
|
2911
|
+
}
|
|
2912
|
+
/**
|
|
2913
|
+
* Access the underlying plugin manager instance
|
|
2914
|
+
*/
|
|
2915
|
+
get plugins() {
|
|
2916
|
+
return this.pluginManager;
|
|
2917
|
+
}
|
|
2571
2918
|
/**
|
|
2572
2919
|
* Returns a fluent, chained reference to a specific file
|
|
2573
2920
|
*/
|
|
@@ -2586,7 +2933,8 @@ var init_client = __esm({
|
|
|
2586
2933
|
async init() {
|
|
2587
2934
|
if (!this.driveClient) {
|
|
2588
2935
|
const auth = await this.authenticator.getAuthClient();
|
|
2589
|
-
|
|
2936
|
+
const agent = getOptimizedHttpsAgent();
|
|
2937
|
+
this.driveClient = drive({ version: "v3", auth, agent });
|
|
2590
2938
|
if (this.options.enablePersistentCache !== false) {
|
|
2591
2939
|
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2592
2940
|
this.metadataCacheInstance.init();
|
|
@@ -2673,14 +3021,41 @@ var init_client = __esm({
|
|
|
2673
3021
|
}
|
|
2674
3022
|
}
|
|
2675
3023
|
/**
|
|
2676
|
-
* Lists contents of a folder (by folder ID or path)
|
|
3024
|
+
* Lists contents of a folder (by folder ID or path) with opportunistic tree caching
|
|
2677
3025
|
*/
|
|
2678
3026
|
async ls(folderIdOrPath = "/") {
|
|
2679
|
-
|
|
2680
|
-
|
|
3027
|
+
let parentFolderId;
|
|
3028
|
+
let normalizedPath = null;
|
|
3029
|
+
let files;
|
|
3030
|
+
if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
|
|
3031
|
+
parentFolderId = this.rootFolderId;
|
|
3032
|
+
normalizedPath = "/";
|
|
3033
|
+
const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
|
|
3034
|
+
files = await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
|
|
3035
|
+
} else {
|
|
3036
|
+
if (folderIdOrPath.startsWith("/")) {
|
|
3037
|
+
normalizedPath = folderIdOrPath.replace(/\/+$/, "") || "/";
|
|
3038
|
+
parentFolderId = await this.resolveId(normalizedPath);
|
|
3039
|
+
} else {
|
|
3040
|
+
parentFolderId = folderIdOrPath;
|
|
3041
|
+
}
|
|
3042
|
+
files = await this.query().inFolder(parentFolderId).notTrashed().orderBy("folder,name").list();
|
|
2681
3043
|
}
|
|
2682
|
-
|
|
2683
|
-
|
|
3044
|
+
if (this.metadataCacheInstance && files.length > 0) {
|
|
3045
|
+
const cacheEntries = files.filter((f) => !!f.id).map((f) => ({
|
|
3046
|
+
id: f.id,
|
|
3047
|
+
name: f.name || "untitled",
|
|
3048
|
+
mimeType: f.mimeType || "",
|
|
3049
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3050
|
+
parentId: parentFolderId,
|
|
3051
|
+
path: normalizedPath ? `${normalizedPath === "/" ? "" : normalizedPath}/${f.name}` : void 0,
|
|
3052
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
3053
|
+
modifiedTime: f.modifiedTime || void 0,
|
|
3054
|
+
trashed: false
|
|
3055
|
+
}));
|
|
3056
|
+
this.metadataCacheInstance.upsertFiles(cacheEntries);
|
|
3057
|
+
}
|
|
3058
|
+
return files;
|
|
2684
3059
|
}
|
|
2685
3060
|
// ==========================================
|
|
2686
3061
|
// FILE OPERATIONS (UPLOAD, DOWNLOAD, GET)
|
|
@@ -2699,7 +3074,7 @@ var init_client = __esm({
|
|
|
2699
3074
|
if (parentId && parentId.startsWith("/")) {
|
|
2700
3075
|
parentId = await this.mkdirp(parentId);
|
|
2701
3076
|
}
|
|
2702
|
-
const targetName = opts.name || opts.filename;
|
|
3077
|
+
const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? path8.basename(opts.source) : void 0);
|
|
2703
3078
|
if (opts.overwrite && targetName && parentId) {
|
|
2704
3079
|
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
2705
3080
|
if (existing?.id) {
|
|
@@ -2720,7 +3095,7 @@ var init_client = __esm({
|
|
|
2720
3095
|
}
|
|
2721
3096
|
}
|
|
2722
3097
|
if (existingId) {
|
|
2723
|
-
const fileName = targetName ||
|
|
3098
|
+
const fileName = targetName || path8.basename(opts.source);
|
|
2724
3099
|
const raw = await this.getRawClient();
|
|
2725
3100
|
const copyRes = await withRetry(async () => {
|
|
2726
3101
|
return await raw.files.copy({
|
|
@@ -2755,12 +3130,14 @@ var init_client = __esm({
|
|
|
2755
3130
|
parent: parentId
|
|
2756
3131
|
});
|
|
2757
3132
|
if (this.metadataCacheInstance && uploaded.id) {
|
|
3133
|
+
const virtualPath = typeof opts.parent === "string" && opts.parent.startsWith("/") ? `${opts.parent === "/" ? "" : opts.parent}/${uploaded.name || targetName || "untitled"}` : void 0;
|
|
2758
3134
|
this.metadataCacheInstance.upsertFile({
|
|
2759
3135
|
id: uploaded.id,
|
|
2760
3136
|
name: uploaded.name || targetName || "untitled",
|
|
2761
3137
|
mimeType: uploaded.mimeType || "",
|
|
2762
3138
|
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2763
3139
|
parentId,
|
|
3140
|
+
path: virtualPath,
|
|
2764
3141
|
trashed: false
|
|
2765
3142
|
});
|
|
2766
3143
|
}
|
|
@@ -2771,16 +3148,25 @@ var init_client = __esm({
|
|
|
2771
3148
|
* - Automatic conversion for Google Docs, Sheets, and Slides
|
|
2772
3149
|
* - Progress events
|
|
2773
3150
|
* - Saves directly to file or returns Readable Stream
|
|
3151
|
+
* - Leverages local metadata cache to bypass redundant Google API roundtrips
|
|
2774
3152
|
*/
|
|
2775
3153
|
async download(fileIdOrPath, options = {}) {
|
|
2776
3154
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
2777
|
-
|
|
3155
|
+
let cachedMeta = options.metadata;
|
|
3156
|
+
if (!cachedMeta && this.metadataCacheInstance) {
|
|
3157
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
3158
|
+
if (cached && cached.name && cached.mimeType) {
|
|
3159
|
+
cachedMeta = { name: cached.name, mimeType: cached.mimeType, size: cached.size };
|
|
3160
|
+
}
|
|
3161
|
+
}
|
|
3162
|
+
const mergedOpts = cachedMeta ? { ...options, metadata: cachedMeta } : options;
|
|
3163
|
+
const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
|
|
2778
3164
|
const downloader = await this.getDownloader();
|
|
2779
3165
|
const result = await downloader.download(fileId, processedOpts);
|
|
2780
3166
|
return await this.pluginManager.runAfterDownload(result);
|
|
2781
3167
|
}
|
|
2782
3168
|
/**
|
|
2783
|
-
* Gets file metadata
|
|
3169
|
+
* Gets file metadata and updates the local metadata cache
|
|
2784
3170
|
*/
|
|
2785
3171
|
async getFile(fileIdOrPath) {
|
|
2786
3172
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
@@ -2792,7 +3178,20 @@ var init_client = __esm({
|
|
|
2792
3178
|
supportsAllDrives: true
|
|
2793
3179
|
});
|
|
2794
3180
|
});
|
|
2795
|
-
|
|
3181
|
+
const file = res.data;
|
|
3182
|
+
if (this.metadataCacheInstance && file.id) {
|
|
3183
|
+
this.metadataCacheInstance.upsertFile({
|
|
3184
|
+
id: file.id,
|
|
3185
|
+
name: file.name || "",
|
|
3186
|
+
mimeType: file.mimeType || "",
|
|
3187
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
3188
|
+
parentId: file.parents?.[0],
|
|
3189
|
+
path: fileIdOrPath.startsWith("/") ? fileIdOrPath : void 0,
|
|
3190
|
+
modifiedTime: file.modifiedTime || void 0,
|
|
3191
|
+
trashed: file.trashed || false
|
|
3192
|
+
});
|
|
3193
|
+
}
|
|
3194
|
+
return file;
|
|
2796
3195
|
}
|
|
2797
3196
|
/**
|
|
2798
3197
|
* Reads file content as UTF-8 string
|
|
@@ -2835,6 +3234,9 @@ var init_client = __esm({
|
|
|
2835
3234
|
if (this.pathResolverInstance && fileIdOrPath.startsWith("/")) {
|
|
2836
3235
|
this.pathResolverInstance.invalidatePath(fileIdOrPath);
|
|
2837
3236
|
}
|
|
3237
|
+
if (this.metadataCacheInstance) {
|
|
3238
|
+
this.metadataCacheInstance.deleteFile(fileId);
|
|
3239
|
+
}
|
|
2838
3240
|
}
|
|
2839
3241
|
/**
|
|
2840
3242
|
* Move item to trash
|
|
@@ -2876,6 +3278,16 @@ var init_client = __esm({
|
|
|
2876
3278
|
if (this.pathResolverInstance) {
|
|
2877
3279
|
this.pathResolverInstance.clearCache();
|
|
2878
3280
|
}
|
|
3281
|
+
if (this.metadataCacheInstance) {
|
|
3282
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
3283
|
+
if (cached) {
|
|
3284
|
+
this.metadataCacheInstance.upsertFile({
|
|
3285
|
+
...cached,
|
|
3286
|
+
parentId: newParentId,
|
|
3287
|
+
path: void 0
|
|
3288
|
+
});
|
|
3289
|
+
}
|
|
3290
|
+
}
|
|
2879
3291
|
return res.data;
|
|
2880
3292
|
}
|
|
2881
3293
|
/**
|
|
@@ -2918,6 +3330,16 @@ var init_client = __esm({
|
|
|
2918
3330
|
if (this.pathResolverInstance) {
|
|
2919
3331
|
this.pathResolverInstance.clearCache();
|
|
2920
3332
|
}
|
|
3333
|
+
if (this.metadataCacheInstance) {
|
|
3334
|
+
const cached = this.metadataCacheInstance.getById(fileId);
|
|
3335
|
+
if (cached) {
|
|
3336
|
+
this.metadataCacheInstance.upsertFile({
|
|
3337
|
+
...cached,
|
|
3338
|
+
name: newName,
|
|
3339
|
+
path: void 0
|
|
3340
|
+
});
|
|
3341
|
+
}
|
|
3342
|
+
}
|
|
2921
3343
|
return res.data;
|
|
2922
3344
|
}
|
|
2923
3345
|
// ==========================================
|
|
@@ -3007,8 +3429,8 @@ var init_client = __esm({
|
|
|
3007
3429
|
const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
|
|
3008
3430
|
const files = [];
|
|
3009
3431
|
for (const entry of entries) {
|
|
3010
|
-
const fullPath =
|
|
3011
|
-
const relPath =
|
|
3432
|
+
const fullPath = path8.join(dir, entry.name);
|
|
3433
|
+
const relPath = path8.join(base, entry.name);
|
|
3012
3434
|
if (entry.isDirectory()) {
|
|
3013
3435
|
const sub = await collectFiles(fullPath, relPath);
|
|
3014
3436
|
files.push(...sub);
|
|
@@ -3026,11 +3448,11 @@ var init_client = __esm({
|
|
|
3026
3448
|
if (remoteDirCache.has(relDir)) {
|
|
3027
3449
|
return remoteDirCache.get(relDir);
|
|
3028
3450
|
}
|
|
3029
|
-
const parts = relDir.split(
|
|
3451
|
+
const parts = relDir.split(path8.sep).filter(Boolean);
|
|
3030
3452
|
let currentParent = targetFolderId;
|
|
3031
3453
|
let currentRel = "";
|
|
3032
3454
|
for (const part of parts) {
|
|
3033
|
-
currentRel = currentRel ?
|
|
3455
|
+
currentRel = currentRel ? path8.join(currentRel, part) : part;
|
|
3034
3456
|
if (remoteDirCache.has(currentRel)) {
|
|
3035
3457
|
currentParent = remoteDirCache.get(currentRel);
|
|
3036
3458
|
continue;
|
|
@@ -3059,8 +3481,8 @@ var init_client = __esm({
|
|
|
3059
3481
|
};
|
|
3060
3482
|
await pool.map(allFiles, async (fileItem) => {
|
|
3061
3483
|
try {
|
|
3062
|
-
const relDir =
|
|
3063
|
-
const fileName =
|
|
3484
|
+
const relDir = path8.dirname(fileItem.relPath);
|
|
3485
|
+
const fileName = path8.basename(fileItem.relPath);
|
|
3064
3486
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
3065
3487
|
if (options.onFileStart) {
|
|
3066
3488
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -3195,9 +3617,16 @@ var init_client = __esm({
|
|
|
3195
3617
|
async createWriteStream(remotePath, options = {}) {
|
|
3196
3618
|
await this.init();
|
|
3197
3619
|
const { PassThrough } = await import("stream");
|
|
3198
|
-
const passThrough = new PassThrough();
|
|
3199
|
-
|
|
3200
|
-
|
|
3620
|
+
const passThrough = new PassThrough({ highWaterMark: 1024 * 1024 });
|
|
3621
|
+
let resolveDone;
|
|
3622
|
+
let rejectDone;
|
|
3623
|
+
const donePromise = new Promise((resolve, reject) => {
|
|
3624
|
+
resolveDone = resolve;
|
|
3625
|
+
rejectDone = reject;
|
|
3626
|
+
});
|
|
3627
|
+
passThrough.done = donePromise;
|
|
3628
|
+
const remoteDir = path8.dirname(remotePath);
|
|
3629
|
+
const fileName = options.name || options.filename || path8.basename(remotePath);
|
|
3201
3630
|
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3202
3631
|
const mimeType = options.mimeType || "application/octet-stream";
|
|
3203
3632
|
const raw = this.driveClient;
|
|
@@ -3214,9 +3643,10 @@ var init_client = __esm({
|
|
|
3214
3643
|
fields: "id, name, mimeType, size, md5Checksum",
|
|
3215
3644
|
supportsAllDrives: true
|
|
3216
3645
|
}).then((res) => {
|
|
3217
|
-
|
|
3646
|
+
const file = res.data;
|
|
3647
|
+
if (file.id && this.metadataCacheInstance) {
|
|
3218
3648
|
this.metadataCacheInstance.upsertFile({
|
|
3219
|
-
id:
|
|
3649
|
+
id: file.id,
|
|
3220
3650
|
name: fileName,
|
|
3221
3651
|
mimeType,
|
|
3222
3652
|
parentId: targetParentId,
|
|
@@ -3224,14 +3654,22 @@ var init_client = __esm({
|
|
|
3224
3654
|
trashed: false
|
|
3225
3655
|
});
|
|
3226
3656
|
}
|
|
3657
|
+
resolveDone(file);
|
|
3227
3658
|
}).catch((err) => {
|
|
3228
3659
|
passThrough.destroy(err);
|
|
3660
|
+
rejectDone(err);
|
|
3229
3661
|
});
|
|
3230
3662
|
return passThrough;
|
|
3231
3663
|
}
|
|
3232
3664
|
// ==========================================
|
|
3233
3665
|
// METADATA CACHE OPERATIONS
|
|
3234
3666
|
// ==========================================
|
|
3667
|
+
/**
|
|
3668
|
+
* Synchronous getter for the active metadata cache instance
|
|
3669
|
+
*/
|
|
3670
|
+
get cache() {
|
|
3671
|
+
return this.metadataCacheInstance;
|
|
3672
|
+
}
|
|
3235
3673
|
/**
|
|
3236
3674
|
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3237
3675
|
*/
|
|
@@ -3254,6 +3692,9 @@ var init_client = __esm({
|
|
|
3254
3692
|
if (this.pathResolverInstance) {
|
|
3255
3693
|
this.pathResolverInstance.clearCache();
|
|
3256
3694
|
}
|
|
3695
|
+
if (this.metadataCacheInstance) {
|
|
3696
|
+
this.metadataCacheInstance.clear();
|
|
3697
|
+
}
|
|
3257
3698
|
}
|
|
3258
3699
|
/**
|
|
3259
3700
|
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
@@ -3266,6 +3707,7 @@ var init_client = __esm({
|
|
|
3266
3707
|
const client = this.driveClient;
|
|
3267
3708
|
let pageToken = void 0;
|
|
3268
3709
|
let totalScanned = 0;
|
|
3710
|
+
const rawFiles = [];
|
|
3269
3711
|
do {
|
|
3270
3712
|
const res = await withRetry(async () => {
|
|
3271
3713
|
return await client.files.list({
|
|
@@ -3279,21 +3721,49 @@ var init_client = __esm({
|
|
|
3279
3721
|
});
|
|
3280
3722
|
});
|
|
3281
3723
|
const files = res.data.files || [];
|
|
3282
|
-
const
|
|
3283
|
-
|
|
3284
|
-
|
|
3285
|
-
|
|
3286
|
-
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3287
|
-
parentId: f.parents?.[0],
|
|
3288
|
-
md5Checksum: f.md5Checksum || void 0,
|
|
3289
|
-
trashed: !!f.trashed,
|
|
3290
|
-
modifiedTime: f.modifiedTime || void 0
|
|
3291
|
-
}));
|
|
3292
|
-
this.metadataCacheInstance.upsertFiles(entries);
|
|
3293
|
-
totalScanned += entries.length;
|
|
3724
|
+
for (const f of files) {
|
|
3725
|
+
if (f.id) rawFiles.push(f);
|
|
3726
|
+
}
|
|
3727
|
+
totalScanned += files.length;
|
|
3294
3728
|
options?.onProgress?.(totalScanned);
|
|
3295
3729
|
pageToken = res.data.nextPageToken || void 0;
|
|
3296
3730
|
} while (pageToken);
|
|
3731
|
+
const fileMap = /* @__PURE__ */ new Map();
|
|
3732
|
+
for (const f of rawFiles) {
|
|
3733
|
+
fileMap.set(f.id, f);
|
|
3734
|
+
}
|
|
3735
|
+
const pathMemo = /* @__PURE__ */ new Map();
|
|
3736
|
+
const rootId = this.rootFolderId;
|
|
3737
|
+
function computePath(id, visited = /* @__PURE__ */ new Set()) {
|
|
3738
|
+
if (pathMemo.has(id)) return pathMemo.get(id);
|
|
3739
|
+
if (visited.has(id)) return "";
|
|
3740
|
+
visited.add(id);
|
|
3741
|
+
const f = fileMap.get(id);
|
|
3742
|
+
if (!f || !f.name) return "";
|
|
3743
|
+
const parentId = f.parents?.[0];
|
|
3744
|
+
if (!parentId || parentId === "root" || parentId === rootId) {
|
|
3745
|
+
const p = `/${f.name}`;
|
|
3746
|
+
pathMemo.set(id, p);
|
|
3747
|
+
return p;
|
|
3748
|
+
}
|
|
3749
|
+
const parentPath = computePath(parentId, visited);
|
|
3750
|
+
const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
|
|
3751
|
+
pathMemo.set(id, fullPath);
|
|
3752
|
+
return fullPath;
|
|
3753
|
+
}
|
|
3754
|
+
const entries = rawFiles.map((f) => ({
|
|
3755
|
+
id: f.id,
|
|
3756
|
+
name: f.name || "untitled",
|
|
3757
|
+
mimeType: f.mimeType || "",
|
|
3758
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3759
|
+
parentId: f.parents?.[0],
|
|
3760
|
+
path: computePath(f.id),
|
|
3761
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
3762
|
+
trashed: !!f.trashed,
|
|
3763
|
+
modifiedTime: f.modifiedTime || void 0
|
|
3764
|
+
}));
|
|
3765
|
+
this.metadataCacheInstance.upsertFiles(entries);
|
|
3766
|
+
this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
|
|
3297
3767
|
this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
|
|
3298
3768
|
return this.metadataCacheInstance.getStats();
|
|
3299
3769
|
}
|
|
@@ -3410,7 +3880,7 @@ init_esm_shims();
|
|
|
3410
3880
|
init_client();
|
|
3411
3881
|
init_format();
|
|
3412
3882
|
import fs7 from "fs";
|
|
3413
|
-
import
|
|
3883
|
+
import path9 from "path";
|
|
3414
3884
|
import { Command } from "commander";
|
|
3415
3885
|
import chalk2 from "chalk";
|
|
3416
3886
|
import ora from "ora";
|
|
@@ -3571,10 +4041,29 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
|
|
|
3571
4041
|
|
|
3572
4042
|
// src/cli.ts
|
|
3573
4043
|
var program = new Command();
|
|
3574
|
-
|
|
4044
|
+
var pkgVersion = "1.1.2";
|
|
4045
|
+
try {
|
|
4046
|
+
const pkgPath = new URL("../package.json", import.meta.url);
|
|
4047
|
+
const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
|
|
4048
|
+
if (pkg.version) pkgVersion = pkg.version;
|
|
4049
|
+
} catch {
|
|
4050
|
+
}
|
|
4051
|
+
program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version(pkgVersion).option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
|
|
3575
4052
|
function getAuthConfig(cmdOptions) {
|
|
3576
4053
|
const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
|
|
3577
|
-
|
|
4054
|
+
let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
|
|
4055
|
+
if (!keyFilePath && !accessToken) {
|
|
4056
|
+
const tokensFile = path9.resolve(process.cwd(), "gdrive-tokens.json");
|
|
4057
|
+
if (fs7.existsSync(tokensFile)) {
|
|
4058
|
+
try {
|
|
4059
|
+
const tokens = JSON.parse(fs7.readFileSync(tokensFile, "utf8"));
|
|
4060
|
+
if (tokens.access_token) {
|
|
4061
|
+
accessToken = tokens.access_token;
|
|
4062
|
+
}
|
|
4063
|
+
} catch {
|
|
4064
|
+
}
|
|
4065
|
+
}
|
|
4066
|
+
}
|
|
3578
4067
|
return {
|
|
3579
4068
|
keyFilePath,
|
|
3580
4069
|
accessToken
|
|
@@ -3648,7 +4137,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
|
|
|
3648
4137
|
console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
|
|
3649
4138
|
process.exit(1);
|
|
3650
4139
|
}
|
|
3651
|
-
const fileName =
|
|
4140
|
+
const fileName = path9.basename(localFile);
|
|
3652
4141
|
const spinner = ora(`Preparing upload: ${fileName}...`).start();
|
|
3653
4142
|
try {
|
|
3654
4143
|
const client = await getClient(options);
|
|
@@ -3912,7 +4401,7 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
|
|
|
3912
4401
|
if (result.tokens.refresh_token) {
|
|
3913
4402
|
console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
|
|
3914
4403
|
}
|
|
3915
|
-
const outPath =
|
|
4404
|
+
const outPath = path9.resolve("./gdrive-tokens.json");
|
|
3916
4405
|
fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
|
|
3917
4406
|
console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
|
|
3918
4407
|
`);
|
|
@@ -3990,19 +4479,25 @@ program.command("shared-drives").description("List accessible Google Workspace S
|
|
|
3990
4479
|
process.exit(1);
|
|
3991
4480
|
}
|
|
3992
4481
|
});
|
|
3993
|
-
program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").action(async (options) => {
|
|
4482
|
+
program.command("serve").description("Start embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer").option("-p, --port <port>", "Port number to listen on", "8080").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-u, --username <username>", "HTTP Basic auth username").option("-P, --password <password>", "HTTP Basic auth password").action(async (options) => {
|
|
3994
4483
|
try {
|
|
3995
4484
|
const client = await getClient(options);
|
|
3996
4485
|
const port = parseInt(options.port, 10) || 8080;
|
|
3997
4486
|
const host = options.host || "127.0.0.1";
|
|
4487
|
+
const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
|
|
3998
4488
|
console.log(chalk2.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
|
|
3999
4489
|
console.log("Starting local WebDAV bridge to Google Drive...\n");
|
|
4000
|
-
const serverInstance = await client.serveWebDAV({ port, host });
|
|
4490
|
+
const serverInstance = await client.serveWebDAV({ port, host, auth });
|
|
4001
4491
|
console.log(chalk2.bold.green(`\u{1F680} Server active at: ${chalk2.underline(serverInstance.url)}`));
|
|
4492
|
+
if (auth) {
|
|
4493
|
+
console.log(chalk2.yellow(`\u{1F512} Basic Authentication: ENABLED (User: ${auth.username})`));
|
|
4494
|
+
} else {
|
|
4495
|
+
console.log(chalk2.dim("\u{1F513} Authentication: Anonymous (Localhost only recommended)"));
|
|
4496
|
+
}
|
|
4002
4497
|
console.log(chalk2.white("\n\u{1F4CC} How to mount on macOS Finder:"));
|
|
4003
4498
|
console.log(` 1. Open Finder and press ${chalk2.bold.cyan("Cmd + K")} (Connect to Server)`);
|
|
4004
4499
|
console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}`);
|
|
4005
|
-
console.log(` 3. Click ${chalk2.bold("Connect")} (Connect as Guest)
|
|
4500
|
+
console.log(` 3. Click ${chalk2.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
|
|
4006
4501
|
`);
|
|
4007
4502
|
console.log(chalk2.white("\u{1F4CC} How to mount on Windows:"));
|
|
4008
4503
|
console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);
|