drivekit 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.ar.md +18 -2
- package/README.md +17 -5
- package/dist/cli.cjs +1514 -106
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +1518 -105
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +1432 -22
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +352 -8
- package/dist/index.d.ts +352 -8
- package/dist/index.js +1444 -30
- package/dist/index.js.map +1 -1
- package/package.json +2 -10
package/dist/index.cjs
CHANGED
|
@@ -5,6 +5,9 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
|
5
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
6
|
var __getProtoOf = Object.getPrototypeOf;
|
|
7
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
8
11
|
var __export = (target, all) => {
|
|
9
12
|
for (var name in all)
|
|
10
13
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
@@ -27,6 +30,242 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
27
30
|
));
|
|
28
31
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
32
|
|
|
33
|
+
// node_modules/tsup/assets/cjs_shims.js
|
|
34
|
+
var init_cjs_shims = __esm({
|
|
35
|
+
"node_modules/tsup/assets/cjs_shims.js"() {
|
|
36
|
+
"use strict";
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
// src/server/webdav.ts
|
|
41
|
+
var webdav_exports = {};
|
|
42
|
+
__export(webdav_exports, {
|
|
43
|
+
startWebDAVServer: () => startWebDAVServer
|
|
44
|
+
});
|
|
45
|
+
async function startWebDAVServer(drive2, options = {}) {
|
|
46
|
+
const port = options.port || 8080;
|
|
47
|
+
const host = options.host || "127.0.0.1";
|
|
48
|
+
await drive2.init();
|
|
49
|
+
const server = import_node_http2.default.createServer(async (req, res) => {
|
|
50
|
+
try {
|
|
51
|
+
const parsedUrl = import_node_url.default.parse(req.url || "/", true);
|
|
52
|
+
const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
|
|
53
|
+
const virtualPath = decodedPath === "" ? "/" : decodedPath;
|
|
54
|
+
switch (req.method) {
|
|
55
|
+
case "OPTIONS": {
|
|
56
|
+
res.writeHead(200, {
|
|
57
|
+
DAV: "1, 2",
|
|
58
|
+
Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
|
|
59
|
+
"MS-Author-Via": "DAV"
|
|
60
|
+
});
|
|
61
|
+
res.end();
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
case "PROPFIND": {
|
|
65
|
+
const depth = req.headers["depth"] || "1";
|
|
66
|
+
const xml = await handlePropfind(drive2, virtualPath, depth);
|
|
67
|
+
res.writeHead(207, {
|
|
68
|
+
"Content-Type": "application/xml; charset=utf-8"
|
|
69
|
+
});
|
|
70
|
+
res.end(xml);
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
case "GET":
|
|
74
|
+
case "HEAD": {
|
|
75
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
76
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
|
|
77
|
+
res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder or WebDAV client.</p>");
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
try {
|
|
81
|
+
const file = await drive2.getFile(virtualPath);
|
|
82
|
+
if (file.mimeType === "application/vnd.google-apps.folder") {
|
|
83
|
+
res.writeHead(405, { "Content-Type": "text/plain" });
|
|
84
|
+
res.end("Cannot GET a directory");
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
const stream = await drive2.createReadStream(virtualPath);
|
|
88
|
+
res.writeHead(200, {
|
|
89
|
+
"Content-Type": file.mimeType || "application/octet-stream",
|
|
90
|
+
"Content-Length": file.size || void 0
|
|
91
|
+
});
|
|
92
|
+
if (req.method === "HEAD") {
|
|
93
|
+
res.end();
|
|
94
|
+
} else {
|
|
95
|
+
stream.pipe(res);
|
|
96
|
+
}
|
|
97
|
+
} catch (e) {
|
|
98
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
99
|
+
res.end("File Not Found");
|
|
100
|
+
}
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
case "PUT": {
|
|
104
|
+
const remoteDir = import_node_path5.default.dirname(virtualPath);
|
|
105
|
+
const fileName = import_node_path5.default.basename(virtualPath);
|
|
106
|
+
await drive2.mkdirp(remoteDir);
|
|
107
|
+
const chunks = [];
|
|
108
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
109
|
+
req.on("end", async () => {
|
|
110
|
+
try {
|
|
111
|
+
const buffer = Buffer.concat(chunks);
|
|
112
|
+
await drive2.upload({
|
|
113
|
+
source: buffer,
|
|
114
|
+
filename: fileName,
|
|
115
|
+
parent: remoteDir,
|
|
116
|
+
overwrite: true
|
|
117
|
+
});
|
|
118
|
+
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
119
|
+
res.end("Created");
|
|
120
|
+
} catch (err) {
|
|
121
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
122
|
+
res.end(err.message || "Upload failed");
|
|
123
|
+
}
|
|
124
|
+
});
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
case "MKCOL": {
|
|
128
|
+
try {
|
|
129
|
+
await drive2.mkdirp(virtualPath);
|
|
130
|
+
res.writeHead(201, { "Content-Type": "text/plain" });
|
|
131
|
+
res.end("Collection Created");
|
|
132
|
+
} catch (err) {
|
|
133
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
134
|
+
res.end(err.message);
|
|
135
|
+
}
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
case "DELETE": {
|
|
139
|
+
try {
|
|
140
|
+
await drive2.delete(virtualPath, true);
|
|
141
|
+
res.writeHead(204);
|
|
142
|
+
res.end();
|
|
143
|
+
} catch (err) {
|
|
144
|
+
res.writeHead(404, { "Content-Type": "text/plain" });
|
|
145
|
+
res.end("Not Found");
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
case "MOVE": {
|
|
150
|
+
const destination = req.headers["destination"];
|
|
151
|
+
if (!destination || typeof destination !== "string") {
|
|
152
|
+
res.writeHead(400, { "Content-Type": "text/plain" });
|
|
153
|
+
res.end("Destination header missing");
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const destUrl = import_node_url.default.parse(destination);
|
|
157
|
+
const destPath = decodeURIComponent(destUrl.pathname || "");
|
|
158
|
+
const newName = import_node_path5.default.basename(destPath);
|
|
159
|
+
const newParent = import_node_path5.default.dirname(destPath);
|
|
160
|
+
try {
|
|
161
|
+
await drive2.move(virtualPath, newParent);
|
|
162
|
+
if (newName !== import_node_path5.default.basename(virtualPath)) {
|
|
163
|
+
await drive2.rename(destPath, newName);
|
|
164
|
+
}
|
|
165
|
+
res.writeHead(201);
|
|
166
|
+
res.end("Moved");
|
|
167
|
+
} catch (err) {
|
|
168
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
169
|
+
res.end(err.message);
|
|
170
|
+
}
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
default: {
|
|
174
|
+
res.writeHead(501, { "Content-Type": "text/plain" });
|
|
175
|
+
res.end("Method Not Implemented");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
} catch (globalErr) {
|
|
179
|
+
res.writeHead(500, { "Content-Type": "text/plain" });
|
|
180
|
+
res.end(`Internal Server Error: ${globalErr.message}`);
|
|
181
|
+
}
|
|
182
|
+
});
|
|
183
|
+
return new Promise((resolve) => {
|
|
184
|
+
server.listen(port, host, () => {
|
|
185
|
+
const serverUrl = `http://${host}:${port}`;
|
|
186
|
+
resolve({
|
|
187
|
+
server,
|
|
188
|
+
url: serverUrl,
|
|
189
|
+
close: () => new Promise((resClose) => server.close(() => resClose()))
|
|
190
|
+
});
|
|
191
|
+
});
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
async function handlePropfind(drive2, virtualPath, depth) {
|
|
195
|
+
const responses = [];
|
|
196
|
+
let isFolder = false;
|
|
197
|
+
let selfItem = null;
|
|
198
|
+
if (virtualPath === "/" || virtualPath === "") {
|
|
199
|
+
isFolder = true;
|
|
200
|
+
responses.push(renderWebDAVResponse("/", true, 0, (/* @__PURE__ */ new Date()).toISOString()));
|
|
201
|
+
} else {
|
|
202
|
+
try {
|
|
203
|
+
selfItem = await drive2.getFile(virtualPath);
|
|
204
|
+
isFolder = selfItem.mimeType === "application/vnd.google-apps.folder";
|
|
205
|
+
responses.push(
|
|
206
|
+
renderWebDAVResponse(
|
|
207
|
+
virtualPath,
|
|
208
|
+
isFolder,
|
|
209
|
+
selfItem.size ? parseInt(selfItem.size, 10) : 0,
|
|
210
|
+
selfItem.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
211
|
+
)
|
|
212
|
+
);
|
|
213
|
+
} catch {
|
|
214
|
+
return `<?xml version="1.0" encoding="utf-8"?><D:multistatus xmlns:D="DAV:"></D:multistatus>`;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
if (isFolder && depth !== "0") {
|
|
218
|
+
try {
|
|
219
|
+
const children = await drive2.ls(virtualPath);
|
|
220
|
+
for (const child of children) {
|
|
221
|
+
const childIsFolder = child.mimeType === "application/vnd.google-apps.folder";
|
|
222
|
+
const childPath = virtualPath === "/" ? `/${child.name}` : `${virtualPath}/${child.name}`;
|
|
223
|
+
responses.push(
|
|
224
|
+
renderWebDAVResponse(
|
|
225
|
+
childPath,
|
|
226
|
+
childIsFolder,
|
|
227
|
+
child.size ? parseInt(child.size, 10) : 0,
|
|
228
|
+
child.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()
|
|
229
|
+
)
|
|
230
|
+
);
|
|
231
|
+
}
|
|
232
|
+
} catch {
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return `<?xml version="1.0" encoding="utf-8"?>
|
|
236
|
+
<D:multistatus xmlns:D="DAV:">
|
|
237
|
+
${responses.join("\n")}
|
|
238
|
+
</D:multistatus>`;
|
|
239
|
+
}
|
|
240
|
+
function renderWebDAVResponse(href, isDir, size, modifiedTime) {
|
|
241
|
+
const encodedHref = encodeURI(href);
|
|
242
|
+
const resourceType = isDir ? "<D:collection/>" : "";
|
|
243
|
+
const dateFormatted = new Date(modifiedTime).toUTCString();
|
|
244
|
+
return ` <D:response>
|
|
245
|
+
<D:href>${encodedHref}</D:href>
|
|
246
|
+
<D:propstat>
|
|
247
|
+
<D:prop>
|
|
248
|
+
<D:displayname>${import_node_path5.default.basename(href) || "root"}</D:displayname>
|
|
249
|
+
<D:resourcetype>${resourceType}</D:resourcetype>
|
|
250
|
+
<D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
|
|
251
|
+
<D:getlastmodified>${dateFormatted}</D:getlastmodified>
|
|
252
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
253
|
+
</D:prop>
|
|
254
|
+
<D:status>HTTP/1.1 200 OK</D:status>
|
|
255
|
+
</D:propstat>
|
|
256
|
+
</D:response>`;
|
|
257
|
+
}
|
|
258
|
+
var import_node_http2, import_node_url, import_node_path5;
|
|
259
|
+
var init_webdav = __esm({
|
|
260
|
+
"src/server/webdav.ts"() {
|
|
261
|
+
"use strict";
|
|
262
|
+
init_cjs_shims();
|
|
263
|
+
import_node_http2 = __toESM(require("http"), 1);
|
|
264
|
+
import_node_url = __toESM(require("url"), 1);
|
|
265
|
+
import_node_path5 = __toESM(require("path"), 1);
|
|
266
|
+
}
|
|
267
|
+
});
|
|
268
|
+
|
|
30
269
|
// src/index.ts
|
|
31
270
|
var index_exports = {};
|
|
32
271
|
__export(index_exports, {
|
|
@@ -37,6 +276,8 @@ __export(index_exports, {
|
|
|
37
276
|
Downloader: () => Downloader,
|
|
38
277
|
DriveAuthError: () => DriveAuthError,
|
|
39
278
|
DriveAuthenticator: () => DriveAuthenticator,
|
|
279
|
+
DriveFileRef: () => DriveFileRef,
|
|
280
|
+
DriveFolderRef: () => DriveFolderRef,
|
|
40
281
|
DriveKit: () => DriveKit,
|
|
41
282
|
DriveKitError: () => DriveKitError,
|
|
42
283
|
DriveNotFoundError: () => DriveNotFoundError,
|
|
@@ -47,35 +288,49 @@ __export(index_exports, {
|
|
|
47
288
|
GOOGLE_WORKSPACE_MIME_TYPES: () => GOOGLE_WORKSPACE_MIME_TYPES,
|
|
48
289
|
MIN_CHUNK_SIZE: () => MIN_CHUNK_SIZE,
|
|
49
290
|
MULTIPART_THRESHOLD: () => MULTIPART_THRESHOLD,
|
|
291
|
+
MemoryMetadataCache: () => MemoryMetadataCache,
|
|
50
292
|
PathResolver: () => PathResolver,
|
|
293
|
+
PluginManager: () => PluginManager,
|
|
51
294
|
ResumableUploader: () => ResumableUploader,
|
|
52
295
|
SmartSyncEngine: () => SmartSyncEngine,
|
|
296
|
+
SqliteMetadataCache: () => SqliteMetadataCache,
|
|
53
297
|
StorageCleaner: () => StorageCleaner,
|
|
54
298
|
calculateFileMd5: () => calculateFileMd5,
|
|
299
|
+
createAutoNamePlugin: () => createAutoNamePlugin,
|
|
55
300
|
createDrive: () => createDrive,
|
|
301
|
+
createWebhookPlugin: () => createWebhookPlugin,
|
|
56
302
|
default: () => index_default,
|
|
57
303
|
formatBytes: () => formatBytes,
|
|
58
304
|
formatDuration: () => formatDuration,
|
|
59
305
|
formatSpeed: () => formatSpeed,
|
|
60
306
|
getExtensionForMime: () => getExtensionForMime,
|
|
307
|
+
getFileIcon: () => getFileIcon,
|
|
61
308
|
isGoogleWorkspaceDoc: () => isGoogleWorkspaceDoc,
|
|
62
309
|
isRetryableError: () => isRetryableError,
|
|
63
310
|
loginWithBrowser: () => loginWithBrowser,
|
|
64
311
|
lookupMimeType: () => lookupMimeType,
|
|
312
|
+
renderFileRow: () => renderFileRow,
|
|
313
|
+
runInteractiveExplorer: () => runInteractiveExplorer,
|
|
314
|
+
startWebDAVServer: () => startWebDAVServer,
|
|
315
|
+
terminalLink: () => terminalLink,
|
|
65
316
|
withRetry: () => withRetry
|
|
66
317
|
});
|
|
67
318
|
module.exports = __toCommonJS(index_exports);
|
|
319
|
+
init_cjs_shims();
|
|
68
320
|
|
|
69
321
|
// src/core/client.ts
|
|
70
|
-
|
|
71
|
-
var
|
|
322
|
+
init_cjs_shims();
|
|
323
|
+
var import_node_fs6 = __toESM(require("fs"), 1);
|
|
324
|
+
var import_node_path6 = __toESM(require("path"), 1);
|
|
72
325
|
var import_drive3 = require("@googleapis/drive");
|
|
73
326
|
|
|
74
327
|
// src/auth/authenticator.ts
|
|
328
|
+
init_cjs_shims();
|
|
75
329
|
var import_node_fs = __toESM(require("fs"), 1);
|
|
76
330
|
var import_drive = require("@googleapis/drive");
|
|
77
331
|
|
|
78
332
|
// src/errors.ts
|
|
333
|
+
init_cjs_shims();
|
|
79
334
|
var DriveKitError = class extends Error {
|
|
80
335
|
code;
|
|
81
336
|
originalError;
|
|
@@ -216,7 +471,11 @@ var DriveAuthenticator = class {
|
|
|
216
471
|
}
|
|
217
472
|
};
|
|
218
473
|
|
|
474
|
+
// src/core/path-resolver.ts
|
|
475
|
+
init_cjs_shims();
|
|
476
|
+
|
|
219
477
|
// src/utils/mime.ts
|
|
478
|
+
init_cjs_shims();
|
|
220
479
|
var import_mime_types = __toESM(require("mime-types"), 1);
|
|
221
480
|
var GOOGLE_WORKSPACE_MIME_TYPES = {
|
|
222
481
|
DOCUMENT: "application/vnd.google-apps.document",
|
|
@@ -260,6 +519,7 @@ function isGoogleWorkspaceDoc(mimeType) {
|
|
|
260
519
|
}
|
|
261
520
|
|
|
262
521
|
// src/utils/retry.ts
|
|
522
|
+
init_cjs_shims();
|
|
263
523
|
var DEFAULT_RETRYABLE_STATUSES = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
264
524
|
function isRetryableError(error) {
|
|
265
525
|
if (!error) return false;
|
|
@@ -316,11 +576,13 @@ var PathResolver = class {
|
|
|
316
576
|
cache = /* @__PURE__ */ new Map();
|
|
317
577
|
cacheTTL;
|
|
318
578
|
enableCache;
|
|
579
|
+
metadataCache;
|
|
319
580
|
constructor(drive2, rootFolderId = "root", options) {
|
|
320
581
|
this.drive = drive2;
|
|
321
582
|
this.rootFolderId = rootFolderId;
|
|
322
583
|
this.enableCache = options?.enableCache ?? true;
|
|
323
584
|
this.cacheTTL = options?.cacheTTL ?? 5 * 60 * 1e3;
|
|
585
|
+
this.metadataCache = options?.metadataCache;
|
|
324
586
|
}
|
|
325
587
|
/**
|
|
326
588
|
* Normalizes a virtual path (e.g. "///Backups//2026/" -> "/Backups/2026")
|
|
@@ -335,21 +597,31 @@ var PathResolver = class {
|
|
|
335
597
|
/**
|
|
336
598
|
* Gets cache key for a path
|
|
337
599
|
*/
|
|
338
|
-
getCacheKey(
|
|
339
|
-
return `${this.rootFolderId}:${this.normalizePath(
|
|
600
|
+
getCacheKey(path7) {
|
|
601
|
+
return `${this.rootFolderId}:${this.normalizePath(path7)}`;
|
|
340
602
|
}
|
|
341
603
|
/**
|
|
342
604
|
* Clears the path cache
|
|
343
605
|
*/
|
|
344
606
|
clearCache() {
|
|
345
607
|
this.cache.clear();
|
|
608
|
+
if (this.metadataCache) {
|
|
609
|
+
this.metadataCache.clear();
|
|
610
|
+
}
|
|
346
611
|
}
|
|
347
612
|
/**
|
|
348
613
|
* Invalidate a single path from cache
|
|
349
614
|
*/
|
|
350
|
-
invalidatePath(
|
|
351
|
-
const
|
|
615
|
+
invalidatePath(path7) {
|
|
616
|
+
const norm = this.normalizePath(path7);
|
|
617
|
+
const key = this.getCacheKey(norm);
|
|
352
618
|
this.cache.delete(key);
|
|
619
|
+
if (this.metadataCache) {
|
|
620
|
+
const item = this.metadataCache.getByPath(norm);
|
|
621
|
+
if (item) {
|
|
622
|
+
this.metadataCache.deleteFile(item.id);
|
|
623
|
+
}
|
|
624
|
+
}
|
|
353
625
|
}
|
|
354
626
|
/**
|
|
355
627
|
* Resolves a path to a Google Drive item (file or folder).
|
|
@@ -365,6 +637,17 @@ var PathResolver = class {
|
|
|
365
637
|
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER
|
|
366
638
|
};
|
|
367
639
|
}
|
|
640
|
+
if (this.metadataCache) {
|
|
641
|
+
const persistentCached = this.metadataCache.getByPath(norm);
|
|
642
|
+
if (persistentCached) {
|
|
643
|
+
return {
|
|
644
|
+
id: persistentCached.id,
|
|
645
|
+
name: persistentCached.name,
|
|
646
|
+
isFolder: persistentCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
647
|
+
mimeType: persistentCached.mimeType
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
}
|
|
368
651
|
if (this.enableCache) {
|
|
369
652
|
const cached = this.cache.get(this.getCacheKey(norm));
|
|
370
653
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -383,6 +666,21 @@ var PathResolver = class {
|
|
|
383
666
|
const segment = segments[i];
|
|
384
667
|
const isLast = i === segments.length - 1;
|
|
385
668
|
currentPath += `/${segment}`;
|
|
669
|
+
if (this.metadataCache) {
|
|
670
|
+
const pCached = this.metadataCache.getByPath(currentPath);
|
|
671
|
+
if (pCached) {
|
|
672
|
+
currentParentId = pCached.id;
|
|
673
|
+
if (isLast) {
|
|
674
|
+
return {
|
|
675
|
+
id: pCached.id,
|
|
676
|
+
name: pCached.name,
|
|
677
|
+
isFolder: pCached.mimeType === GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
678
|
+
mimeType: pCached.mimeType
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
continue;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
386
684
|
if (this.enableCache) {
|
|
387
685
|
const cached = this.cache.get(this.getCacheKey(currentPath));
|
|
388
686
|
if (cached && cached.expiresAt > Date.now()) {
|
|
@@ -427,6 +725,16 @@ var PathResolver = class {
|
|
|
427
725
|
}
|
|
428
726
|
if (file && file.id) {
|
|
429
727
|
currentParentId = file.id;
|
|
728
|
+
if (this.metadataCache) {
|
|
729
|
+
this.metadataCache.upsertFile({
|
|
730
|
+
id: file.id,
|
|
731
|
+
name: file.name || segment,
|
|
732
|
+
mimeType: file.mimeType || "",
|
|
733
|
+
parentId: currentParentId,
|
|
734
|
+
path: currentPath,
|
|
735
|
+
trashed: false
|
|
736
|
+
});
|
|
737
|
+
}
|
|
430
738
|
if (this.enableCache) {
|
|
431
739
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
432
740
|
id: file.id,
|
|
@@ -461,6 +769,16 @@ var PathResolver = class {
|
|
|
461
769
|
throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
|
|
462
770
|
}
|
|
463
771
|
currentParentId = newFolder.id;
|
|
772
|
+
if (this.metadataCache) {
|
|
773
|
+
this.metadataCache.upsertFile({
|
|
774
|
+
id: newFolder.id,
|
|
775
|
+
name: segment,
|
|
776
|
+
mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
|
|
777
|
+
parentId: currentParentId,
|
|
778
|
+
path: currentPath,
|
|
779
|
+
trashed: false
|
|
780
|
+
});
|
|
781
|
+
}
|
|
464
782
|
if (this.enableCache) {
|
|
465
783
|
this.cache.set(this.getCacheKey(currentPath), {
|
|
466
784
|
id: newFolder.id,
|
|
@@ -497,10 +815,12 @@ var PathResolver = class {
|
|
|
497
815
|
};
|
|
498
816
|
|
|
499
817
|
// src/core/resumable-uploader.ts
|
|
818
|
+
init_cjs_shims();
|
|
500
819
|
var import_node_fs2 = __toESM(require("fs"), 1);
|
|
501
820
|
var import_node_path = __toESM(require("path"), 1);
|
|
502
821
|
|
|
503
822
|
// src/utils/format.ts
|
|
823
|
+
init_cjs_shims();
|
|
504
824
|
function formatBytes(bytes, decimals = 2) {
|
|
505
825
|
if (bytes === 0) return "0 B";
|
|
506
826
|
const k = 1024;
|
|
@@ -646,6 +966,9 @@ var ResumableUploader = class {
|
|
|
646
966
|
let chunkIndex = 0;
|
|
647
967
|
try {
|
|
648
968
|
while (bytesSent < totalBytes) {
|
|
969
|
+
if (options.signal?.aborted) {
|
|
970
|
+
throw new Error("Upload aborted by user signal");
|
|
971
|
+
}
|
|
649
972
|
chunkIndex++;
|
|
650
973
|
const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
|
|
651
974
|
const buffer = Buffer.alloc(currentChunkSize);
|
|
@@ -706,6 +1029,9 @@ var ResumableUploader = class {
|
|
|
706
1029
|
const totalChunks = Math.ceil(totalBytes / chunkSize) || 1;
|
|
707
1030
|
let chunkIndex = 0;
|
|
708
1031
|
while (bytesSent < totalBytes) {
|
|
1032
|
+
if (options.signal?.aborted) {
|
|
1033
|
+
throw new Error("Upload aborted by user signal");
|
|
1034
|
+
}
|
|
709
1035
|
chunkIndex++;
|
|
710
1036
|
const currentChunkSize = Math.min(chunkSize, totalBytes - bytesSent);
|
|
711
1037
|
const chunk = buffer.subarray(bytesSent, bytesSent + currentChunkSize);
|
|
@@ -822,6 +1148,7 @@ var ResumableUploader = class {
|
|
|
822
1148
|
};
|
|
823
1149
|
|
|
824
1150
|
// src/core/downloader.ts
|
|
1151
|
+
init_cjs_shims();
|
|
825
1152
|
var import_node_fs3 = __toESM(require("fs"), 1);
|
|
826
1153
|
var import_node_path2 = __toESM(require("path"), 1);
|
|
827
1154
|
var import_promises = require("stream/promises");
|
|
@@ -917,9 +1244,28 @@ var Downloader = class {
|
|
|
917
1244
|
size: totalBytes
|
|
918
1245
|
};
|
|
919
1246
|
}
|
|
1247
|
+
/**
|
|
1248
|
+
* Returns a raw ReadableStream for the file, supporting HTTP Range requests for partial content / streaming.
|
|
1249
|
+
*/
|
|
1250
|
+
async createReadStream(fileId, options) {
|
|
1251
|
+
const headers = {};
|
|
1252
|
+
if (options?.start !== void 0 || options?.end !== void 0) {
|
|
1253
|
+
const start = options.start ?? 0;
|
|
1254
|
+
const end = options.end !== void 0 ? options.end : "";
|
|
1255
|
+
headers["Range"] = `bytes=${start}-${end}`;
|
|
1256
|
+
}
|
|
1257
|
+
const res = await withRetry(async () => {
|
|
1258
|
+
return await this.drive.files.get(
|
|
1259
|
+
{ fileId, alt: "media", supportsAllDrives: true },
|
|
1260
|
+
{ responseType: "stream", headers }
|
|
1261
|
+
);
|
|
1262
|
+
});
|
|
1263
|
+
return res.data;
|
|
1264
|
+
}
|
|
920
1265
|
};
|
|
921
1266
|
|
|
922
1267
|
// src/core/query-builder.ts
|
|
1268
|
+
init_cjs_shims();
|
|
923
1269
|
var DriveQueryBuilder = class {
|
|
924
1270
|
drive;
|
|
925
1271
|
conditions = [];
|
|
@@ -1036,6 +1382,19 @@ var DriveQueryBuilder = class {
|
|
|
1036
1382
|
this.conditions.push(`(${condition})`);
|
|
1037
1383
|
return this;
|
|
1038
1384
|
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Custom raw query condition (alias for raw)
|
|
1387
|
+
*/
|
|
1388
|
+
custom(condition) {
|
|
1389
|
+
return this.raw(condition);
|
|
1390
|
+
}
|
|
1391
|
+
/**
|
|
1392
|
+
* Filter: Exact MD5 checksum match
|
|
1393
|
+
*/
|
|
1394
|
+
md5(checksum) {
|
|
1395
|
+
this.conditions.push(`md5Checksum = '${this.escape(checksum)}'`);
|
|
1396
|
+
return this;
|
|
1397
|
+
}
|
|
1039
1398
|
/**
|
|
1040
1399
|
* Sort ordering (e.g. 'modifiedTime desc', 'name', 'folder,modifiedTime desc')
|
|
1041
1400
|
*/
|
|
@@ -1082,6 +1441,12 @@ var DriveQueryBuilder = class {
|
|
|
1082
1441
|
});
|
|
1083
1442
|
return res.data.files || [];
|
|
1084
1443
|
}
|
|
1444
|
+
/**
|
|
1445
|
+
* Executes query and returns array of matching files (alias for list)
|
|
1446
|
+
*/
|
|
1447
|
+
async execute() {
|
|
1448
|
+
return await this.list();
|
|
1449
|
+
}
|
|
1085
1450
|
/**
|
|
1086
1451
|
* Returns the first matching file, or null if not found
|
|
1087
1452
|
*/
|
|
@@ -1129,6 +1494,7 @@ var DriveQueryBuilder = class {
|
|
|
1129
1494
|
};
|
|
1130
1495
|
|
|
1131
1496
|
// src/core/concurrency-pool.ts
|
|
1497
|
+
init_cjs_shims();
|
|
1132
1498
|
var ConcurrencyPool = class {
|
|
1133
1499
|
concurrency;
|
|
1134
1500
|
running = 0;
|
|
@@ -1173,6 +1539,7 @@ var ConcurrencyPool = class {
|
|
|
1173
1539
|
};
|
|
1174
1540
|
|
|
1175
1541
|
// src/core/watcher.ts
|
|
1542
|
+
init_cjs_shims();
|
|
1176
1543
|
var import_node_events = require("events");
|
|
1177
1544
|
var DriveWatcher = class extends import_node_events.EventEmitter {
|
|
1178
1545
|
drive;
|
|
@@ -1286,6 +1653,7 @@ var DriveWatcher = class extends import_node_events.EventEmitter {
|
|
|
1286
1653
|
};
|
|
1287
1654
|
|
|
1288
1655
|
// src/core/storage-cleaner.ts
|
|
1656
|
+
init_cjs_shims();
|
|
1289
1657
|
var StorageCleaner = class {
|
|
1290
1658
|
drive;
|
|
1291
1659
|
constructor(drive2) {
|
|
@@ -1382,6 +1750,7 @@ var StorageCleaner = class {
|
|
|
1382
1750
|
};
|
|
1383
1751
|
|
|
1384
1752
|
// src/core/smart-sync.ts
|
|
1753
|
+
init_cjs_shims();
|
|
1385
1754
|
var import_node_fs4 = __toESM(require("fs"), 1);
|
|
1386
1755
|
var import_node_path3 = __toESM(require("path"), 1);
|
|
1387
1756
|
var import_node_crypto = __toESM(require("crypto"), 1);
|
|
@@ -1507,6 +1876,7 @@ var SmartSyncEngine = class {
|
|
|
1507
1876
|
};
|
|
1508
1877
|
|
|
1509
1878
|
// src/auth/browser-login.ts
|
|
1879
|
+
init_cjs_shims();
|
|
1510
1880
|
var import_node_http = __toESM(require("http"), 1);
|
|
1511
1881
|
var import_node_child_process = require("child_process");
|
|
1512
1882
|
var import_drive2 = require("@googleapis/drive");
|
|
@@ -1614,20 +1984,614 @@ ${authUrl}
|
|
|
1614
1984
|
});
|
|
1615
1985
|
}
|
|
1616
1986
|
|
|
1987
|
+
// src/core/resource-refs.ts
|
|
1988
|
+
init_cjs_shims();
|
|
1989
|
+
var DriveFileRef = class {
|
|
1990
|
+
drive;
|
|
1991
|
+
pathOrId;
|
|
1992
|
+
constructor(drive2, pathOrId) {
|
|
1993
|
+
this.drive = drive2;
|
|
1994
|
+
this.pathOrId = pathOrId;
|
|
1995
|
+
}
|
|
1996
|
+
/** Gets file metadata */
|
|
1997
|
+
async get() {
|
|
1998
|
+
return await this.drive.getFile(this.pathOrId);
|
|
1999
|
+
}
|
|
2000
|
+
/** Checks if the file exists */
|
|
2001
|
+
async exists() {
|
|
2002
|
+
return await this.drive.exists(this.pathOrId);
|
|
2003
|
+
}
|
|
2004
|
+
/** Reads file as UTF-8 string */
|
|
2005
|
+
async getText() {
|
|
2006
|
+
return await this.drive.getText(this.pathOrId);
|
|
2007
|
+
}
|
|
2008
|
+
/** Reads and parses JSON file */
|
|
2009
|
+
async getJson() {
|
|
2010
|
+
return await this.drive.getJson(this.pathOrId);
|
|
2011
|
+
}
|
|
2012
|
+
/** Downloads the file to destination */
|
|
2013
|
+
async download(optionsOrDestination) {
|
|
2014
|
+
const opts = typeof optionsOrDestination === "string" ? { destination: optionsOrDestination } : optionsOrDestination;
|
|
2015
|
+
return await this.drive.download(this.pathOrId, opts);
|
|
2016
|
+
}
|
|
2017
|
+
/** Moves the file to a new folder path or ID */
|
|
2018
|
+
async moveTo(newParentPathOrId) {
|
|
2019
|
+
return await this.drive.move(this.pathOrId, newParentPathOrId);
|
|
2020
|
+
}
|
|
2021
|
+
/** Copies the file to a target directory */
|
|
2022
|
+
async copyTo(parentPathOrId, newName) {
|
|
2023
|
+
return await this.drive.copy(this.pathOrId, { parent: parentPathOrId, name: newName });
|
|
2024
|
+
}
|
|
2025
|
+
/** Renames the file */
|
|
2026
|
+
async rename(newName) {
|
|
2027
|
+
return await this.drive.rename(this.pathOrId, newName);
|
|
2028
|
+
}
|
|
2029
|
+
/** Deletes the file (or moves to trash if permanent is false) */
|
|
2030
|
+
async delete(permanent = false) {
|
|
2031
|
+
return await this.drive.delete(this.pathOrId, permanent);
|
|
2032
|
+
}
|
|
2033
|
+
/** Moves file to trash */
|
|
2034
|
+
async trash() {
|
|
2035
|
+
return await this.drive.trash(this.pathOrId);
|
|
2036
|
+
}
|
|
2037
|
+
/** Shares file */
|
|
2038
|
+
async share(options) {
|
|
2039
|
+
return await this.drive.share(this.pathOrId, options);
|
|
2040
|
+
}
|
|
2041
|
+
/** Makes file publicly accessible */
|
|
2042
|
+
async sharePublic(role = "reader") {
|
|
2043
|
+
return await this.drive.sharePublic(this.pathOrId, role);
|
|
2044
|
+
}
|
|
2045
|
+
/** Gets public/preview links */
|
|
2046
|
+
async getLink() {
|
|
2047
|
+
return await this.drive.getShareableLink(this.pathOrId);
|
|
2048
|
+
}
|
|
2049
|
+
/** Returns a ReadableStream for this file, optionally with byte Range requests */
|
|
2050
|
+
async createReadStream(options) {
|
|
2051
|
+
return await this.drive.createReadStream(this.pathOrId, options);
|
|
2052
|
+
}
|
|
2053
|
+
/** Grants access to a specific email with custom role and notification */
|
|
2054
|
+
async grantAccess(options) {
|
|
2055
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
2056
|
+
}
|
|
2057
|
+
/** Revokes access by permission ID or user email */
|
|
2058
|
+
async revokeAccess(permissionIdOrEmail) {
|
|
2059
|
+
return await this.drive.revokeAccess(this.pathOrId, permissionIdOrEmail);
|
|
2060
|
+
}
|
|
2061
|
+
/** Lists all granted permissions on this file */
|
|
2062
|
+
async listPermissions() {
|
|
2063
|
+
return await this.drive.listPermissions(this.pathOrId);
|
|
2064
|
+
}
|
|
2065
|
+
};
|
|
2066
|
+
var DriveFolderRef = class {
|
|
2067
|
+
drive;
|
|
2068
|
+
pathOrId;
|
|
2069
|
+
constructor(drive2, pathOrId) {
|
|
2070
|
+
this.drive = drive2;
|
|
2071
|
+
this.pathOrId = pathOrId;
|
|
2072
|
+
}
|
|
2073
|
+
/** Lists contents of this folder */
|
|
2074
|
+
async ls() {
|
|
2075
|
+
return await this.drive.ls(this.pathOrId);
|
|
2076
|
+
}
|
|
2077
|
+
/** Ensures this folder and subpaths exist (mkdir -p) */
|
|
2078
|
+
async mkdirp(subPath) {
|
|
2079
|
+
const target = subPath ? this.pathOrId.endsWith("/") ? `${this.pathOrId}${subPath}` : `${this.pathOrId}/${subPath}` : this.pathOrId;
|
|
2080
|
+
return await this.drive.mkdirp(target);
|
|
2081
|
+
}
|
|
2082
|
+
/** Uploads a file directly into this folder */
|
|
2083
|
+
async upload(source, options = {}) {
|
|
2084
|
+
return await this.drive.upload({
|
|
2085
|
+
...options,
|
|
2086
|
+
source,
|
|
2087
|
+
parent: this.pathOrId
|
|
2088
|
+
});
|
|
2089
|
+
}
|
|
2090
|
+
/** Synchronizes a local directory into this remote folder */
|
|
2091
|
+
async syncFrom(localDir, options = {}) {
|
|
2092
|
+
return await this.drive.syncFolder(localDir, this.pathOrId, options);
|
|
2093
|
+
}
|
|
2094
|
+
/** Pulls this remote folder down to local directory */
|
|
2095
|
+
async pullTo(localDestinationDir, options = {}) {
|
|
2096
|
+
return await this.drive.pull(this.pathOrId, localDestinationDir, options);
|
|
2097
|
+
}
|
|
2098
|
+
/** Watches this folder for real-time changes */
|
|
2099
|
+
async watch(options = {}) {
|
|
2100
|
+
return await this.drive.watch(this.pathOrId, options);
|
|
2101
|
+
}
|
|
2102
|
+
/** Grants access to this entire folder */
|
|
2103
|
+
async grantAccess(options) {
|
|
2104
|
+
return await this.drive.grantAccess(this.pathOrId, options);
|
|
2105
|
+
}
|
|
2106
|
+
/** Creates a writable stream directly into a file inside this folder */
|
|
2107
|
+
async createWriteStream(fileName, options) {
|
|
2108
|
+
const targetPath = this.pathOrId.endsWith("/") ? `${this.pathOrId}${fileName}` : `${this.pathOrId}/${fileName}`;
|
|
2109
|
+
return await this.drive.createWriteStream(targetPath, options);
|
|
2110
|
+
}
|
|
2111
|
+
};
|
|
2112
|
+
|
|
2113
|
+
// src/core/plugins.ts
|
|
2114
|
+
init_cjs_shims();
|
|
2115
|
+
var PluginManager = class {
|
|
2116
|
+
plugins = [];
|
|
2117
|
+
use(plugin) {
|
|
2118
|
+
this.plugins.push(plugin);
|
|
2119
|
+
return this;
|
|
2120
|
+
}
|
|
2121
|
+
async runBeforeUpload(options) {
|
|
2122
|
+
let current = { ...options };
|
|
2123
|
+
for (const plugin of this.plugins) {
|
|
2124
|
+
if (plugin.beforeUpload) {
|
|
2125
|
+
const modified = await plugin.beforeUpload(current);
|
|
2126
|
+
if (modified) current = modified;
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
return current;
|
|
2130
|
+
}
|
|
2131
|
+
async runAfterUpload(file) {
|
|
2132
|
+
let current = file;
|
|
2133
|
+
for (const plugin of this.plugins) {
|
|
2134
|
+
if (plugin.afterUpload) {
|
|
2135
|
+
const modified = await plugin.afterUpload(current);
|
|
2136
|
+
if (modified) current = modified;
|
|
2137
|
+
}
|
|
2138
|
+
}
|
|
2139
|
+
return current;
|
|
2140
|
+
}
|
|
2141
|
+
async runBeforeDownload(fileId, options) {
|
|
2142
|
+
let current = { ...options };
|
|
2143
|
+
for (const plugin of this.plugins) {
|
|
2144
|
+
if (plugin.beforeDownload) {
|
|
2145
|
+
const modified = await plugin.beforeDownload(fileId, current);
|
|
2146
|
+
if (modified) current = modified;
|
|
2147
|
+
}
|
|
2148
|
+
}
|
|
2149
|
+
return current;
|
|
2150
|
+
}
|
|
2151
|
+
async runAfterDownload(result) {
|
|
2152
|
+
let current = result;
|
|
2153
|
+
for (const plugin of this.plugins) {
|
|
2154
|
+
if (plugin.afterDownload) {
|
|
2155
|
+
const modified = await plugin.afterDownload(current);
|
|
2156
|
+
if (modified) current = modified;
|
|
2157
|
+
}
|
|
2158
|
+
}
|
|
2159
|
+
return current;
|
|
2160
|
+
}
|
|
2161
|
+
};
|
|
2162
|
+
function createWebhookPlugin(options) {
|
|
2163
|
+
const events = options.events || ["upload"];
|
|
2164
|
+
return {
|
|
2165
|
+
name: "drivekit-official-webhook",
|
|
2166
|
+
async afterUpload(file) {
|
|
2167
|
+
if (!events.includes("upload")) return;
|
|
2168
|
+
try {
|
|
2169
|
+
await fetch(options.url, {
|
|
2170
|
+
method: "POST",
|
|
2171
|
+
headers: { "Content-Type": "application/json", ...options.headers || {} },
|
|
2172
|
+
body: JSON.stringify({
|
|
2173
|
+
event: "drivekit:upload",
|
|
2174
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2175
|
+
file: {
|
|
2176
|
+
id: file.id,
|
|
2177
|
+
name: file.name,
|
|
2178
|
+
size: file.size,
|
|
2179
|
+
mimeType: file.mimeType
|
|
2180
|
+
}
|
|
2181
|
+
})
|
|
2182
|
+
});
|
|
2183
|
+
} catch (e) {
|
|
2184
|
+
}
|
|
2185
|
+
},
|
|
2186
|
+
async afterDownload(result) {
|
|
2187
|
+
if (!events.includes("download")) return;
|
|
2188
|
+
try {
|
|
2189
|
+
await fetch(options.url, {
|
|
2190
|
+
method: "POST",
|
|
2191
|
+
headers: { "Content-Type": "application/json", ...options.headers || {} },
|
|
2192
|
+
body: JSON.stringify({
|
|
2193
|
+
event: "drivekit:download",
|
|
2194
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
2195
|
+
file: {
|
|
2196
|
+
name: result.name,
|
|
2197
|
+
size: result.size
|
|
2198
|
+
}
|
|
2199
|
+
})
|
|
2200
|
+
});
|
|
2201
|
+
} catch (e) {
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
};
|
|
2205
|
+
}
|
|
2206
|
+
function createAutoNamePlugin(options) {
|
|
2207
|
+
return {
|
|
2208
|
+
name: "drivekit-official-autoname",
|
|
2209
|
+
beforeUpload(opts) {
|
|
2210
|
+
let name = opts.filename;
|
|
2211
|
+
if (!name && typeof opts.source === "string") {
|
|
2212
|
+
const pathModule2 = require("path");
|
|
2213
|
+
name = pathModule2.basename(opts.source);
|
|
2214
|
+
}
|
|
2215
|
+
if (!name) return opts;
|
|
2216
|
+
const pathModule = require("path");
|
|
2217
|
+
const ext = pathModule.extname(name);
|
|
2218
|
+
const base = pathModule.basename(name, ext);
|
|
2219
|
+
let finalName = base;
|
|
2220
|
+
if (options.prefix) finalName = `${options.prefix}${finalName}`;
|
|
2221
|
+
if (options.appendTimestamp) {
|
|
2222
|
+
finalName = `${finalName}_${Date.now()}`;
|
|
2223
|
+
}
|
|
2224
|
+
if (options.suffix) finalName = `${finalName}${options.suffix}`;
|
|
2225
|
+
finalName = `${finalName}${ext}`;
|
|
2226
|
+
return {
|
|
2227
|
+
...opts,
|
|
2228
|
+
filename: finalName
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
};
|
|
2232
|
+
}
|
|
2233
|
+
|
|
2234
|
+
// src/core/cache.ts
|
|
2235
|
+
init_cjs_shims();
|
|
2236
|
+
var import_node_os = __toESM(require("os"), 1);
|
|
2237
|
+
var import_node_path4 = __toESM(require("path"), 1);
|
|
2238
|
+
var import_node_fs5 = __toESM(require("fs"), 1);
|
|
2239
|
+
var SqliteMetadataCache = class {
|
|
2240
|
+
db = null;
|
|
2241
|
+
dbPath;
|
|
2242
|
+
initialized = false;
|
|
2243
|
+
fallbackMemory;
|
|
2244
|
+
constructor(customPath) {
|
|
2245
|
+
if (customPath) {
|
|
2246
|
+
this.dbPath = customPath;
|
|
2247
|
+
} else {
|
|
2248
|
+
const dir = import_node_path4.default.join(import_node_os.default.homedir(), ".drivekit");
|
|
2249
|
+
if (!import_node_fs5.default.existsSync(dir)) {
|
|
2250
|
+
try {
|
|
2251
|
+
import_node_fs5.default.mkdirSync(dir, { recursive: true });
|
|
2252
|
+
} catch {
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
this.dbPath = import_node_path4.default.join(dir, "cache.db");
|
|
2256
|
+
}
|
|
2257
|
+
}
|
|
2258
|
+
init() {
|
|
2259
|
+
if (this.initialized) return;
|
|
2260
|
+
try {
|
|
2261
|
+
const { DatabaseSync } = require("sqlite");
|
|
2262
|
+
if (!DatabaseSync) {
|
|
2263
|
+
throw new Error("DatabaseSync not available");
|
|
2264
|
+
}
|
|
2265
|
+
this.db = new DatabaseSync(this.dbPath);
|
|
2266
|
+
this.db.exec(`
|
|
2267
|
+
PRAGMA journal_mode = WAL;
|
|
2268
|
+
PRAGMA synchronous = NORMAL;
|
|
2269
|
+
|
|
2270
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
2271
|
+
id TEXT PRIMARY KEY,
|
|
2272
|
+
name TEXT NOT NULL,
|
|
2273
|
+
mimeType TEXT NOT NULL,
|
|
2274
|
+
size INTEGER,
|
|
2275
|
+
parentId TEXT,
|
|
2276
|
+
path TEXT,
|
|
2277
|
+
md5Checksum TEXT,
|
|
2278
|
+
trashed INTEGER DEFAULT 0,
|
|
2279
|
+
modifiedTime TEXT,
|
|
2280
|
+
updatedAt INTEGER
|
|
2281
|
+
);
|
|
2282
|
+
|
|
2283
|
+
CREATE TABLE IF NOT EXISTS meta (
|
|
2284
|
+
key TEXT PRIMARY KEY,
|
|
2285
|
+
value TEXT NOT NULL
|
|
2286
|
+
);
|
|
2287
|
+
|
|
2288
|
+
CREATE INDEX IF NOT EXISTS idx_files_path ON files(path);
|
|
2289
|
+
CREATE INDEX IF NOT EXISTS idx_files_parent ON files(parentId);
|
|
2290
|
+
CREATE INDEX IF NOT EXISTS idx_files_md5 ON files(md5Checksum);
|
|
2291
|
+
CREATE INDEX IF NOT EXISTS idx_files_name ON files(name);
|
|
2292
|
+
`);
|
|
2293
|
+
this.initialized = true;
|
|
2294
|
+
} catch (err) {
|
|
2295
|
+
this.fallbackMemory = new MemoryMetadataCache();
|
|
2296
|
+
this.fallbackMemory.init();
|
|
2297
|
+
this.initialized = true;
|
|
2298
|
+
this.db = null;
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
getById(id) {
|
|
2302
|
+
if (this.fallbackMemory) return this.fallbackMemory.getById(id);
|
|
2303
|
+
if (!this.initialized || !this.db) return null;
|
|
2304
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE id = ?");
|
|
2305
|
+
const row = stmt.get(id);
|
|
2306
|
+
return row ? this.mapRow(row) : null;
|
|
2307
|
+
}
|
|
2308
|
+
getByPath(normalizedPath) {
|
|
2309
|
+
if (this.fallbackMemory) return this.fallbackMemory.getByPath(normalizedPath);
|
|
2310
|
+
if (!this.initialized || !this.db) return null;
|
|
2311
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE path = ? AND trashed = 0 LIMIT 1");
|
|
2312
|
+
const row = stmt.get(normalizedPath);
|
|
2313
|
+
return row ? this.mapRow(row) : null;
|
|
2314
|
+
}
|
|
2315
|
+
getChildren(parentId) {
|
|
2316
|
+
if (this.fallbackMemory) return this.fallbackMemory.getChildren(parentId);
|
|
2317
|
+
if (!this.initialized || !this.db) return [];
|
|
2318
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE parentId = ? AND trashed = 0 ORDER BY name ASC");
|
|
2319
|
+
const rows = stmt.all(parentId);
|
|
2320
|
+
return rows.map((r) => this.mapRow(r));
|
|
2321
|
+
}
|
|
2322
|
+
findByMd5(md5) {
|
|
2323
|
+
if (this.fallbackMemory) return this.fallbackMemory.findByMd5(md5);
|
|
2324
|
+
if (!this.initialized || !this.db || !md5) return null;
|
|
2325
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE md5Checksum = ? AND trashed = 0 LIMIT 1");
|
|
2326
|
+
const row = stmt.get(md5.toLowerCase());
|
|
2327
|
+
return row ? this.mapRow(row) : null;
|
|
2328
|
+
}
|
|
2329
|
+
searchByName(query) {
|
|
2330
|
+
if (this.fallbackMemory) return this.fallbackMemory.searchByName(query);
|
|
2331
|
+
if (!this.initialized || !this.db) return [];
|
|
2332
|
+
const stmt = this.db.prepare("SELECT * FROM files WHERE name LIKE ? AND trashed = 0 LIMIT 50");
|
|
2333
|
+
const rows = stmt.all(`%${query}%`);
|
|
2334
|
+
return rows.map((r) => this.mapRow(r));
|
|
2335
|
+
}
|
|
2336
|
+
upsertFile(entry) {
|
|
2337
|
+
if (this.fallbackMemory) {
|
|
2338
|
+
this.fallbackMemory.upsertFile(entry);
|
|
2339
|
+
return;
|
|
2340
|
+
}
|
|
2341
|
+
if (!this.initialized || !this.db) return;
|
|
2342
|
+
const stmt = this.db.prepare(`
|
|
2343
|
+
INSERT INTO files (id, name, mimeType, size, parentId, path, md5Checksum, trashed, modifiedTime, updatedAt)
|
|
2344
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2345
|
+
ON CONFLICT(id) DO UPDATE SET
|
|
2346
|
+
name = excluded.name,
|
|
2347
|
+
mimeType = excluded.mimeType,
|
|
2348
|
+
size = excluded.size,
|
|
2349
|
+
parentId = excluded.parentId,
|
|
2350
|
+
path = COALESCE(excluded.path, files.path),
|
|
2351
|
+
md5Checksum = excluded.md5Checksum,
|
|
2352
|
+
trashed = excluded.trashed,
|
|
2353
|
+
modifiedTime = excluded.modifiedTime,
|
|
2354
|
+
updatedAt = excluded.updatedAt
|
|
2355
|
+
`);
|
|
2356
|
+
stmt.run(
|
|
2357
|
+
entry.id,
|
|
2358
|
+
entry.name,
|
|
2359
|
+
entry.mimeType,
|
|
2360
|
+
entry.size ?? null,
|
|
2361
|
+
entry.parentId ?? null,
|
|
2362
|
+
entry.path ?? null,
|
|
2363
|
+
entry.md5Checksum ? entry.md5Checksum.toLowerCase() : null,
|
|
2364
|
+
entry.trashed ? 1 : 0,
|
|
2365
|
+
entry.modifiedTime ?? null,
|
|
2366
|
+
entry.updatedAt ?? Date.now()
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
upsertFiles(entries) {
|
|
2370
|
+
if (this.fallbackMemory) {
|
|
2371
|
+
this.fallbackMemory.upsertFiles(entries);
|
|
2372
|
+
return;
|
|
2373
|
+
}
|
|
2374
|
+
if (!this.initialized || !this.db || entries.length === 0) return;
|
|
2375
|
+
this.db.exec("BEGIN TRANSACTION;");
|
|
2376
|
+
try {
|
|
2377
|
+
for (const entry of entries) {
|
|
2378
|
+
this.upsertFile(entry);
|
|
2379
|
+
}
|
|
2380
|
+
this.db.exec("COMMIT;");
|
|
2381
|
+
} catch (e) {
|
|
2382
|
+
this.db.exec("ROLLBACK;");
|
|
2383
|
+
throw e;
|
|
2384
|
+
}
|
|
2385
|
+
}
|
|
2386
|
+
deleteFile(id) {
|
|
2387
|
+
if (this.fallbackMemory) {
|
|
2388
|
+
this.fallbackMemory.deleteFile(id);
|
|
2389
|
+
return;
|
|
2390
|
+
}
|
|
2391
|
+
if (!this.initialized || !this.db) return;
|
|
2392
|
+
const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
|
|
2393
|
+
stmt.run(id);
|
|
2394
|
+
}
|
|
2395
|
+
clear() {
|
|
2396
|
+
if (this.fallbackMemory) {
|
|
2397
|
+
this.fallbackMemory.clear();
|
|
2398
|
+
return;
|
|
2399
|
+
}
|
|
2400
|
+
if (!this.initialized || !this.db) return;
|
|
2401
|
+
this.db.exec("DELETE FROM files; DELETE FROM meta;");
|
|
2402
|
+
}
|
|
2403
|
+
getMeta(key) {
|
|
2404
|
+
if (this.fallbackMemory) return this.fallbackMemory.getMeta(key);
|
|
2405
|
+
if (!this.initialized || !this.db) return null;
|
|
2406
|
+
const stmt = this.db.prepare("SELECT value FROM meta WHERE key = ?");
|
|
2407
|
+
const row = stmt.get(key);
|
|
2408
|
+
return row ? row.value : null;
|
|
2409
|
+
}
|
|
2410
|
+
setMeta(key, value) {
|
|
2411
|
+
if (this.fallbackMemory) {
|
|
2412
|
+
this.fallbackMemory.setMeta(key, value);
|
|
2413
|
+
return;
|
|
2414
|
+
}
|
|
2415
|
+
if (!this.initialized || !this.db) return;
|
|
2416
|
+
const stmt = this.db.prepare(`
|
|
2417
|
+
INSERT INTO meta (key, value) VALUES (?, ?)
|
|
2418
|
+
ON CONFLICT(key) DO UPDATE SET value = excluded.value
|
|
2419
|
+
`);
|
|
2420
|
+
stmt.run(key, value);
|
|
2421
|
+
}
|
|
2422
|
+
getStats() {
|
|
2423
|
+
if (this.fallbackMemory) return this.fallbackMemory.getStats();
|
|
2424
|
+
if (!this.initialized || !this.db) {
|
|
2425
|
+
return {
|
|
2426
|
+
fileCount: 0,
|
|
2427
|
+
folderCount: 0,
|
|
2428
|
+
totalSizeBytes: 0,
|
|
2429
|
+
lastSyncTime: null,
|
|
2430
|
+
databasePath: this.dbPath
|
|
2431
|
+
};
|
|
2432
|
+
}
|
|
2433
|
+
const fileCountRow = this.db.prepare(
|
|
2434
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType != 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2435
|
+
).get();
|
|
2436
|
+
const folderCountRow = this.db.prepare(
|
|
2437
|
+
"SELECT COUNT(*) as count FROM files WHERE mimeType = 'application/vnd.google-apps.folder' AND trashed = 0"
|
|
2438
|
+
).get();
|
|
2439
|
+
const totalSizeRow = this.db.prepare(
|
|
2440
|
+
"SELECT SUM(size) as total FROM files WHERE trashed = 0"
|
|
2441
|
+
).get();
|
|
2442
|
+
const lastSync = this.getMeta("last_sync_timestamp");
|
|
2443
|
+
return {
|
|
2444
|
+
fileCount: fileCountRow?.count || 0,
|
|
2445
|
+
folderCount: folderCountRow?.count || 0,
|
|
2446
|
+
totalSizeBytes: totalSizeRow?.total || 0,
|
|
2447
|
+
lastSyncTime: lastSync,
|
|
2448
|
+
databasePath: this.dbPath
|
|
2449
|
+
};
|
|
2450
|
+
}
|
|
2451
|
+
close() {
|
|
2452
|
+
if (this.fallbackMemory) {
|
|
2453
|
+
this.fallbackMemory.close();
|
|
2454
|
+
this.fallbackMemory = void 0;
|
|
2455
|
+
}
|
|
2456
|
+
if (this.db) {
|
|
2457
|
+
try {
|
|
2458
|
+
this.db.close();
|
|
2459
|
+
} catch {
|
|
2460
|
+
}
|
|
2461
|
+
this.initialized = false;
|
|
2462
|
+
this.db = null;
|
|
2463
|
+
}
|
|
2464
|
+
}
|
|
2465
|
+
mapRow(row) {
|
|
2466
|
+
return {
|
|
2467
|
+
id: row.id,
|
|
2468
|
+
name: row.name,
|
|
2469
|
+
mimeType: row.mimeType,
|
|
2470
|
+
size: row.size != null ? Number(row.size) : void 0,
|
|
2471
|
+
parentId: row.parentId || void 0,
|
|
2472
|
+
path: row.path || void 0,
|
|
2473
|
+
md5Checksum: row.md5Checksum || void 0,
|
|
2474
|
+
trashed: row.trashed === 1,
|
|
2475
|
+
modifiedTime: row.modifiedTime || void 0,
|
|
2476
|
+
updatedAt: row.updatedAt != null ? Number(row.updatedAt) : void 0
|
|
2477
|
+
};
|
|
2478
|
+
}
|
|
2479
|
+
};
|
|
2480
|
+
var MemoryMetadataCache = class {
|
|
2481
|
+
files = /* @__PURE__ */ new Map();
|
|
2482
|
+
meta = /* @__PURE__ */ new Map();
|
|
2483
|
+
init() {
|
|
2484
|
+
}
|
|
2485
|
+
getById(id) {
|
|
2486
|
+
return this.files.get(id) || null;
|
|
2487
|
+
}
|
|
2488
|
+
getByPath(normalizedPath) {
|
|
2489
|
+
for (const f of this.files.values()) {
|
|
2490
|
+
if (f.path === normalizedPath && !f.trashed) return f;
|
|
2491
|
+
}
|
|
2492
|
+
return null;
|
|
2493
|
+
}
|
|
2494
|
+
getChildren(parentId) {
|
|
2495
|
+
const list = [];
|
|
2496
|
+
for (const f of this.files.values()) {
|
|
2497
|
+
if (f.parentId === parentId && !f.trashed) list.push(f);
|
|
2498
|
+
}
|
|
2499
|
+
return list;
|
|
2500
|
+
}
|
|
2501
|
+
findByMd5(md5) {
|
|
2502
|
+
const target = md5.toLowerCase();
|
|
2503
|
+
for (const f of this.files.values()) {
|
|
2504
|
+
if (f.md5Checksum?.toLowerCase() === target && !f.trashed) return f;
|
|
2505
|
+
}
|
|
2506
|
+
return null;
|
|
2507
|
+
}
|
|
2508
|
+
searchByName(query) {
|
|
2509
|
+
const q = query.toLowerCase();
|
|
2510
|
+
const list = [];
|
|
2511
|
+
for (const f of this.files.values()) {
|
|
2512
|
+
if (f.name.toLowerCase().includes(q) && !f.trashed) list.push(f);
|
|
2513
|
+
}
|
|
2514
|
+
return list;
|
|
2515
|
+
}
|
|
2516
|
+
upsertFile(entry) {
|
|
2517
|
+
this.files.set(entry.id, { ...entry, updatedAt: Date.now() });
|
|
2518
|
+
}
|
|
2519
|
+
upsertFiles(entries) {
|
|
2520
|
+
for (const e of entries) this.upsertFile(e);
|
|
2521
|
+
}
|
|
2522
|
+
deleteFile(id) {
|
|
2523
|
+
this.files.delete(id);
|
|
2524
|
+
}
|
|
2525
|
+
clear() {
|
|
2526
|
+
this.files.clear();
|
|
2527
|
+
this.meta.clear();
|
|
2528
|
+
}
|
|
2529
|
+
getMeta(key) {
|
|
2530
|
+
return this.meta.get(key) || null;
|
|
2531
|
+
}
|
|
2532
|
+
setMeta(key, value) {
|
|
2533
|
+
this.meta.set(key, value);
|
|
2534
|
+
}
|
|
2535
|
+
getStats() {
|
|
2536
|
+
let fileCount = 0;
|
|
2537
|
+
let folderCount = 0;
|
|
2538
|
+
let totalSizeBytes = 0;
|
|
2539
|
+
for (const f of this.files.values()) {
|
|
2540
|
+
if (f.trashed) continue;
|
|
2541
|
+
if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
|
|
2542
|
+
else {
|
|
2543
|
+
fileCount++;
|
|
2544
|
+
totalSizeBytes += f.size || 0;
|
|
2545
|
+
}
|
|
2546
|
+
}
|
|
2547
|
+
return {
|
|
2548
|
+
fileCount,
|
|
2549
|
+
folderCount,
|
|
2550
|
+
totalSizeBytes,
|
|
2551
|
+
lastSyncTime: this.meta.get("last_sync_timestamp") || null,
|
|
2552
|
+
databasePath: ":memory:"
|
|
2553
|
+
};
|
|
2554
|
+
}
|
|
2555
|
+
close() {
|
|
2556
|
+
this.clear();
|
|
2557
|
+
}
|
|
2558
|
+
};
|
|
2559
|
+
|
|
1617
2560
|
// src/core/client.ts
|
|
1618
|
-
var DriveKit = class {
|
|
2561
|
+
var DriveKit = class _DriveKit {
|
|
1619
2562
|
options;
|
|
1620
2563
|
authenticator;
|
|
1621
2564
|
driveClient = null;
|
|
1622
2565
|
pathResolverInstance = null;
|
|
1623
2566
|
uploaderInstance = null;
|
|
1624
2567
|
downloaderInstance = null;
|
|
2568
|
+
metadataCacheInstance = null;
|
|
1625
2569
|
rootFolderId;
|
|
2570
|
+
pluginManager = new PluginManager();
|
|
1626
2571
|
constructor(options = {}) {
|
|
1627
2572
|
this.options = options;
|
|
1628
2573
|
this.rootFolderId = options.rootFolderId || "root";
|
|
1629
2574
|
this.authenticator = new DriveAuthenticator(options.auth);
|
|
1630
2575
|
}
|
|
2576
|
+
/**
|
|
2577
|
+
* Registers a middleware plugin into DriveKit lifecycle
|
|
2578
|
+
*/
|
|
2579
|
+
use(plugin) {
|
|
2580
|
+
this.pluginManager.use(plugin);
|
|
2581
|
+
return this;
|
|
2582
|
+
}
|
|
2583
|
+
/**
|
|
2584
|
+
* Returns a fluent, chained reference to a specific file
|
|
2585
|
+
*/
|
|
2586
|
+
file(pathOrId) {
|
|
2587
|
+
return new DriveFileRef(this, pathOrId);
|
|
2588
|
+
}
|
|
2589
|
+
/**
|
|
2590
|
+
* Returns a fluent, chained reference to a specific folder
|
|
2591
|
+
*/
|
|
2592
|
+
folder(pathOrId) {
|
|
2593
|
+
return new DriveFolderRef(this, pathOrId);
|
|
2594
|
+
}
|
|
1631
2595
|
/**
|
|
1632
2596
|
* Initializes the Google Drive API client (lazy-loaded if not called explicitly)
|
|
1633
2597
|
*/
|
|
@@ -1635,9 +2599,14 @@ var DriveKit = class {
|
|
|
1635
2599
|
if (!this.driveClient) {
|
|
1636
2600
|
const auth = await this.authenticator.getAuthClient();
|
|
1637
2601
|
this.driveClient = (0, import_drive3.drive)({ version: "v3", auth });
|
|
2602
|
+
if (this.options.enablePersistentCache !== false) {
|
|
2603
|
+
this.metadataCacheInstance = new SqliteMetadataCache(this.options.cacheDatabasePath);
|
|
2604
|
+
this.metadataCacheInstance.init();
|
|
2605
|
+
}
|
|
1638
2606
|
this.pathResolverInstance = new PathResolver(this.driveClient, this.rootFolderId, {
|
|
1639
2607
|
enableCache: this.options.enablePathCache ?? true,
|
|
1640
|
-
cacheTTL: this.options.pathCacheTTL
|
|
2608
|
+
cacheTTL: this.options.pathCacheTTL,
|
|
2609
|
+
metadataCache: this.metadataCacheInstance || void 0
|
|
1641
2610
|
});
|
|
1642
2611
|
this.uploaderInstance = new ResumableUploader(
|
|
1643
2612
|
this.driveClient,
|
|
@@ -1736,21 +2705,78 @@ var DriveKit = class {
|
|
|
1736
2705
|
* - Real-time progress callback: % complete, transfer speed (MB/s), ETA
|
|
1737
2706
|
*/
|
|
1738
2707
|
async upload(options) {
|
|
2708
|
+
const opts = await this.pluginManager.runBeforeUpload(options);
|
|
1739
2709
|
const uploader = await this.getUploader();
|
|
1740
|
-
let parentId =
|
|
2710
|
+
let parentId = opts.parent;
|
|
1741
2711
|
if (parentId && parentId.startsWith("/")) {
|
|
1742
2712
|
parentId = await this.mkdirp(parentId);
|
|
1743
2713
|
}
|
|
1744
|
-
|
|
1745
|
-
|
|
2714
|
+
const targetName = opts.name || opts.filename;
|
|
2715
|
+
if (opts.overwrite && targetName && parentId) {
|
|
2716
|
+
const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
|
|
1746
2717
|
if (existing?.id) {
|
|
1747
2718
|
await this.delete(existing.id, true);
|
|
1748
2719
|
}
|
|
1749
2720
|
}
|
|
1750
|
-
|
|
1751
|
-
|
|
2721
|
+
if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
|
|
2722
|
+
const localMd5 = await calculateFileMd5(opts.source);
|
|
2723
|
+
let existingId;
|
|
2724
|
+
if (this.metadataCacheInstance) {
|
|
2725
|
+
const cached = this.metadataCacheInstance.findByMd5(localMd5);
|
|
2726
|
+
if (cached) existingId = cached.id;
|
|
2727
|
+
}
|
|
2728
|
+
if (!existingId) {
|
|
2729
|
+
const found = await this.query().md5(localMd5).notTrashed().first();
|
|
2730
|
+
if (found?.id) {
|
|
2731
|
+
existingId = found.id;
|
|
2732
|
+
}
|
|
2733
|
+
}
|
|
2734
|
+
if (existingId) {
|
|
2735
|
+
const fileName = targetName || import_node_path6.default.basename(opts.source);
|
|
2736
|
+
const raw = await this.getRawClient();
|
|
2737
|
+
const copyRes = await withRetry(async () => {
|
|
2738
|
+
return await raw.files.copy({
|
|
2739
|
+
fileId: existingId,
|
|
2740
|
+
requestBody: {
|
|
2741
|
+
name: fileName,
|
|
2742
|
+
parents: parentId ? [parentId] : void 0,
|
|
2743
|
+
description: opts.description
|
|
2744
|
+
},
|
|
2745
|
+
fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
|
|
2746
|
+
supportsAllDrives: true
|
|
2747
|
+
});
|
|
2748
|
+
});
|
|
2749
|
+
const file = copyRes.data;
|
|
2750
|
+
if (this.metadataCacheInstance && file.id) {
|
|
2751
|
+
this.metadataCacheInstance.upsertFile({
|
|
2752
|
+
id: file.id,
|
|
2753
|
+
name: file.name || fileName,
|
|
2754
|
+
mimeType: file.mimeType || "",
|
|
2755
|
+
size: file.size ? parseInt(file.size, 10) : void 0,
|
|
2756
|
+
parentId,
|
|
2757
|
+
md5Checksum: localMd5,
|
|
2758
|
+
trashed: false
|
|
2759
|
+
});
|
|
2760
|
+
}
|
|
2761
|
+
return await this.pluginManager.runAfterUpload(file);
|
|
2762
|
+
}
|
|
2763
|
+
}
|
|
2764
|
+
const uploaded = await uploader.upload({
|
|
2765
|
+
...opts,
|
|
2766
|
+
name: targetName,
|
|
1752
2767
|
parent: parentId
|
|
1753
2768
|
});
|
|
2769
|
+
if (this.metadataCacheInstance && uploaded.id) {
|
|
2770
|
+
this.metadataCacheInstance.upsertFile({
|
|
2771
|
+
id: uploaded.id,
|
|
2772
|
+
name: uploaded.name || targetName || "untitled",
|
|
2773
|
+
mimeType: uploaded.mimeType || "",
|
|
2774
|
+
size: uploaded.size ? parseInt(uploaded.size, 10) : void 0,
|
|
2775
|
+
parentId,
|
|
2776
|
+
trashed: false
|
|
2777
|
+
});
|
|
2778
|
+
}
|
|
2779
|
+
return await this.pluginManager.runAfterUpload(uploaded);
|
|
1754
2780
|
}
|
|
1755
2781
|
/**
|
|
1756
2782
|
* Downloads a file from Google Drive:
|
|
@@ -1760,8 +2786,10 @@ var DriveKit = class {
|
|
|
1760
2786
|
*/
|
|
1761
2787
|
async download(fileIdOrPath, options = {}) {
|
|
1762
2788
|
const fileId = await this.resolveId(fileIdOrPath);
|
|
2789
|
+
const processedOpts = await this.pluginManager.runBeforeDownload(fileId, options);
|
|
1763
2790
|
const downloader = await this.getDownloader();
|
|
1764
|
-
|
|
2791
|
+
const result = await downloader.download(fileId, processedOpts);
|
|
2792
|
+
return await this.pluginManager.runAfterDownload(result);
|
|
1765
2793
|
}
|
|
1766
2794
|
/**
|
|
1767
2795
|
* Gets file metadata
|
|
@@ -1988,16 +3016,16 @@ var DriveKit = class {
|
|
|
1988
3016
|
durationMs: 0
|
|
1989
3017
|
};
|
|
1990
3018
|
const collectFiles = async (dir, base) => {
|
|
1991
|
-
const entries = await
|
|
3019
|
+
const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
|
|
1992
3020
|
const files = [];
|
|
1993
3021
|
for (const entry of entries) {
|
|
1994
|
-
const fullPath =
|
|
1995
|
-
const relPath =
|
|
3022
|
+
const fullPath = import_node_path6.default.join(dir, entry.name);
|
|
3023
|
+
const relPath = import_node_path6.default.join(base, entry.name);
|
|
1996
3024
|
if (entry.isDirectory()) {
|
|
1997
3025
|
const sub = await collectFiles(fullPath, relPath);
|
|
1998
3026
|
files.push(...sub);
|
|
1999
3027
|
} else if (entry.isFile()) {
|
|
2000
|
-
const stat = await
|
|
3028
|
+
const stat = await import_node_fs6.default.promises.stat(fullPath);
|
|
2001
3029
|
files.push({ fullPath, relPath, size: stat.size });
|
|
2002
3030
|
}
|
|
2003
3031
|
}
|
|
@@ -2010,11 +3038,11 @@ var DriveKit = class {
|
|
|
2010
3038
|
if (remoteDirCache.has(relDir)) {
|
|
2011
3039
|
return remoteDirCache.get(relDir);
|
|
2012
3040
|
}
|
|
2013
|
-
const parts = relDir.split(
|
|
3041
|
+
const parts = relDir.split(import_node_path6.default.sep).filter(Boolean);
|
|
2014
3042
|
let currentParent = targetFolderId;
|
|
2015
3043
|
let currentRel = "";
|
|
2016
3044
|
for (const part of parts) {
|
|
2017
|
-
currentRel = currentRel ?
|
|
3045
|
+
currentRel = currentRel ? import_node_path6.default.join(currentRel, part) : part;
|
|
2018
3046
|
if (remoteDirCache.has(currentRel)) {
|
|
2019
3047
|
currentParent = remoteDirCache.get(currentRel);
|
|
2020
3048
|
continue;
|
|
@@ -2043,8 +3071,8 @@ var DriveKit = class {
|
|
|
2043
3071
|
};
|
|
2044
3072
|
await pool.map(allFiles, async (fileItem) => {
|
|
2045
3073
|
try {
|
|
2046
|
-
const relDir =
|
|
2047
|
-
const fileName =
|
|
3074
|
+
const relDir = import_node_path6.default.dirname(fileItem.relPath);
|
|
3075
|
+
const fileName = import_node_path6.default.basename(fileItem.relPath);
|
|
2048
3076
|
const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
|
|
2049
3077
|
if (options.onFileStart) {
|
|
2050
3078
|
options.onFileStart(fileItem.fullPath, fileItem.relPath);
|
|
@@ -2162,6 +3190,217 @@ var DriveKit = class {
|
|
|
2162
3190
|
const engine = new SmartSyncEngine(this.driveClient);
|
|
2163
3191
|
return await engine.pullFolder(folderId, localDestinationDir, options);
|
|
2164
3192
|
}
|
|
3193
|
+
// ==========================================
|
|
3194
|
+
// STREAMS & RANGE REQUESTS
|
|
3195
|
+
// ==========================================
|
|
3196
|
+
/**
|
|
3197
|
+
* Creates a readable stream for a file, supporting partial range requests
|
|
3198
|
+
*/
|
|
3199
|
+
async createReadStream(pathOrId, options) {
|
|
3200
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3201
|
+
const downloader = await this.getDownloader();
|
|
3202
|
+
return await downloader.createReadStream(fileId, options);
|
|
3203
|
+
}
|
|
3204
|
+
/**
|
|
3205
|
+
* Creates a writable stream directly into Google Drive
|
|
3206
|
+
*/
|
|
3207
|
+
async createWriteStream(remotePath, options = {}) {
|
|
3208
|
+
await this.init();
|
|
3209
|
+
const { PassThrough } = await import("stream");
|
|
3210
|
+
const passThrough = new PassThrough();
|
|
3211
|
+
const remoteDir = import_node_path6.default.dirname(remotePath);
|
|
3212
|
+
const fileName = options.name || options.filename || import_node_path6.default.basename(remotePath);
|
|
3213
|
+
const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
|
|
3214
|
+
const mimeType = options.mimeType || "application/octet-stream";
|
|
3215
|
+
const raw = this.driveClient;
|
|
3216
|
+
raw.files.create({
|
|
3217
|
+
requestBody: {
|
|
3218
|
+
name: fileName,
|
|
3219
|
+
parents: [targetParentId],
|
|
3220
|
+
description: options.description
|
|
3221
|
+
},
|
|
3222
|
+
media: {
|
|
3223
|
+
mimeType,
|
|
3224
|
+
body: passThrough
|
|
3225
|
+
},
|
|
3226
|
+
fields: "id, name, mimeType, size, md5Checksum",
|
|
3227
|
+
supportsAllDrives: true
|
|
3228
|
+
}).then((res) => {
|
|
3229
|
+
if (res.data.id && this.metadataCacheInstance) {
|
|
3230
|
+
this.metadataCacheInstance.upsertFile({
|
|
3231
|
+
id: res.data.id,
|
|
3232
|
+
name: fileName,
|
|
3233
|
+
mimeType,
|
|
3234
|
+
parentId: targetParentId,
|
|
3235
|
+
path: remotePath,
|
|
3236
|
+
trashed: false
|
|
3237
|
+
});
|
|
3238
|
+
}
|
|
3239
|
+
}).catch((err) => {
|
|
3240
|
+
passThrough.destroy(err);
|
|
3241
|
+
});
|
|
3242
|
+
return passThrough;
|
|
3243
|
+
}
|
|
3244
|
+
// ==========================================
|
|
3245
|
+
// METADATA CACHE OPERATIONS
|
|
3246
|
+
// ==========================================
|
|
3247
|
+
/**
|
|
3248
|
+
* Returns the active persistent metadata cache instance (SQLite/Memory)
|
|
3249
|
+
*/
|
|
3250
|
+
async getMetadataCache() {
|
|
3251
|
+
await this.init();
|
|
3252
|
+
return this.metadataCacheInstance;
|
|
3253
|
+
}
|
|
3254
|
+
/**
|
|
3255
|
+
* Returns cache statistics (total files, folders, size, last sync)
|
|
3256
|
+
*/
|
|
3257
|
+
async getCacheStats() {
|
|
3258
|
+
await this.init();
|
|
3259
|
+
return this.metadataCacheInstance ? this.metadataCacheInstance.getStats() : null;
|
|
3260
|
+
}
|
|
3261
|
+
/**
|
|
3262
|
+
* Clears the path and metadata cache
|
|
3263
|
+
*/
|
|
3264
|
+
async clearCache() {
|
|
3265
|
+
await this.init();
|
|
3266
|
+
if (this.pathResolverInstance) {
|
|
3267
|
+
this.pathResolverInstance.clearCache();
|
|
3268
|
+
}
|
|
3269
|
+
}
|
|
3270
|
+
/**
|
|
3271
|
+
* Crawls and indexes Google Drive metadata into the local SQLite database for instant 0ms lookups
|
|
3272
|
+
*/
|
|
3273
|
+
async syncCache(options) {
|
|
3274
|
+
await this.init();
|
|
3275
|
+
if (!this.metadataCacheInstance) {
|
|
3276
|
+
throw new Error("Persistent cache is disabled on this DriveKit instance");
|
|
3277
|
+
}
|
|
3278
|
+
const client = this.driveClient;
|
|
3279
|
+
let pageToken = void 0;
|
|
3280
|
+
let totalScanned = 0;
|
|
3281
|
+
do {
|
|
3282
|
+
const res = await withRetry(async () => {
|
|
3283
|
+
return await client.files.list({
|
|
3284
|
+
pageSize: 1e3,
|
|
3285
|
+
pageToken,
|
|
3286
|
+
fields: "nextPageToken, files(id, name, mimeType, size, parents, md5Checksum, trashed, modifiedTime)",
|
|
3287
|
+
spaces: "drive",
|
|
3288
|
+
supportsAllDrives: true,
|
|
3289
|
+
includeItemsFromAllDrives: true,
|
|
3290
|
+
q: "trashed = false"
|
|
3291
|
+
});
|
|
3292
|
+
});
|
|
3293
|
+
const files = res.data.files || [];
|
|
3294
|
+
const entries = files.map((f) => ({
|
|
3295
|
+
id: f.id,
|
|
3296
|
+
name: f.name || "untitled",
|
|
3297
|
+
mimeType: f.mimeType || "",
|
|
3298
|
+
size: f.size ? parseInt(f.size, 10) : void 0,
|
|
3299
|
+
parentId: f.parents?.[0],
|
|
3300
|
+
md5Checksum: f.md5Checksum || void 0,
|
|
3301
|
+
trashed: !!f.trashed,
|
|
3302
|
+
modifiedTime: f.modifiedTime || void 0
|
|
3303
|
+
}));
|
|
3304
|
+
this.metadataCacheInstance.upsertFiles(entries);
|
|
3305
|
+
totalScanned += entries.length;
|
|
3306
|
+
options?.onProgress?.(totalScanned);
|
|
3307
|
+
pageToken = res.data.nextPageToken || void 0;
|
|
3308
|
+
} while (pageToken);
|
|
3309
|
+
this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
|
|
3310
|
+
return this.metadataCacheInstance.getStats();
|
|
3311
|
+
}
|
|
3312
|
+
// ==========================================
|
|
3313
|
+
// SHARED DRIVES & ENTERPRISE PERMISSIONS
|
|
3314
|
+
// ==========================================
|
|
3315
|
+
/**
|
|
3316
|
+
* Lists all Google Workspace Shared Drives accessible by current user or service account
|
|
3317
|
+
*/
|
|
3318
|
+
async listSharedDrives(options = {}) {
|
|
3319
|
+
await this.init();
|
|
3320
|
+
const raw = await this.getRawClient();
|
|
3321
|
+
const res = await withRetry(async () => {
|
|
3322
|
+
return await raw.drives.list({
|
|
3323
|
+
pageSize: options.pageSize || 100,
|
|
3324
|
+
fields: "drives(id, name)"
|
|
3325
|
+
});
|
|
3326
|
+
});
|
|
3327
|
+
return (res.data.drives || []).map((d) => ({ id: d.id, name: d.name }));
|
|
3328
|
+
}
|
|
3329
|
+
/**
|
|
3330
|
+
* Creates a scoped DriveKit client locked to a specific Shared Drive
|
|
3331
|
+
*/
|
|
3332
|
+
sharedDrive(driveId) {
|
|
3333
|
+
return new _DriveKit({
|
|
3334
|
+
...this.options,
|
|
3335
|
+
rootFolderId: driveId
|
|
3336
|
+
});
|
|
3337
|
+
}
|
|
3338
|
+
/**
|
|
3339
|
+
* Grants access to a specific email with custom role and notification
|
|
3340
|
+
*/
|
|
3341
|
+
async grantAccess(pathOrId, options) {
|
|
3342
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3343
|
+
const raw = await this.getRawClient();
|
|
3344
|
+
const res = await withRetry(async () => {
|
|
3345
|
+
return await raw.permissions.create({
|
|
3346
|
+
fileId,
|
|
3347
|
+
requestBody: {
|
|
3348
|
+
type: "user",
|
|
3349
|
+
role: options.role || "reader",
|
|
3350
|
+
emailAddress: options.email
|
|
3351
|
+
},
|
|
3352
|
+
sendNotificationEmail: options.notify ?? true,
|
|
3353
|
+
emailMessage: options.message,
|
|
3354
|
+
fields: "id, type, role, emailAddress, displayName",
|
|
3355
|
+
supportsAllDrives: true
|
|
3356
|
+
});
|
|
3357
|
+
});
|
|
3358
|
+
return res.data;
|
|
3359
|
+
}
|
|
3360
|
+
/**
|
|
3361
|
+
* Revokes access for a specific permission ID or email address
|
|
3362
|
+
*/
|
|
3363
|
+
async revokeAccess(pathOrId, permissionIdOrEmail) {
|
|
3364
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3365
|
+
const raw = await this.getRawClient();
|
|
3366
|
+
let targetId = permissionIdOrEmail;
|
|
3367
|
+
if (permissionIdOrEmail.includes("@")) {
|
|
3368
|
+
const listRes = await this.listPermissions(fileId);
|
|
3369
|
+
const found = listRes.find((p) => p.emailAddress?.toLowerCase() === permissionIdOrEmail.toLowerCase());
|
|
3370
|
+
if (found && found.id) {
|
|
3371
|
+
targetId = found.id;
|
|
3372
|
+
}
|
|
3373
|
+
}
|
|
3374
|
+
await withRetry(async () => {
|
|
3375
|
+
return await raw.permissions.delete({
|
|
3376
|
+
fileId,
|
|
3377
|
+
permissionId: targetId,
|
|
3378
|
+
supportsAllDrives: true
|
|
3379
|
+
});
|
|
3380
|
+
});
|
|
3381
|
+
}
|
|
3382
|
+
/**
|
|
3383
|
+
* Lists all active permissions on a file or folder
|
|
3384
|
+
*/
|
|
3385
|
+
async listPermissions(pathOrId) {
|
|
3386
|
+
const fileId = await this.resolveId(pathOrId);
|
|
3387
|
+
const raw = await this.getRawClient();
|
|
3388
|
+
const res = await withRetry(async () => {
|
|
3389
|
+
return await raw.permissions.list({
|
|
3390
|
+
fileId,
|
|
3391
|
+
fields: "permissions(id, type, role, emailAddress, displayName)",
|
|
3392
|
+
supportsAllDrives: true
|
|
3393
|
+
});
|
|
3394
|
+
});
|
|
3395
|
+
return res.data.permissions || [];
|
|
3396
|
+
}
|
|
3397
|
+
/**
|
|
3398
|
+
* Starts an embedded WebDAV server to mount DriveKit directly in macOS Finder or Windows Explorer
|
|
3399
|
+
*/
|
|
3400
|
+
async serveWebDAV(options) {
|
|
3401
|
+
const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
|
|
3402
|
+
return await startWebDAVServer2(this, options);
|
|
3403
|
+
}
|
|
2165
3404
|
/**
|
|
2166
3405
|
* Calculates local file MD5 hash for integrity and deduplication checks
|
|
2167
3406
|
*/
|
|
@@ -2176,6 +3415,165 @@ var DriveKit = class {
|
|
|
2176
3415
|
}
|
|
2177
3416
|
};
|
|
2178
3417
|
|
|
3418
|
+
// src/types.ts
|
|
3419
|
+
init_cjs_shims();
|
|
3420
|
+
|
|
3421
|
+
// src/index.ts
|
|
3422
|
+
init_webdav();
|
|
3423
|
+
|
|
3424
|
+
// src/cli/terminal-ui.ts
|
|
3425
|
+
init_cjs_shims();
|
|
3426
|
+
var import_node_readline = __toESM(require("readline"), 1);
|
|
3427
|
+
var import_chalk = __toESM(require("chalk"), 1);
|
|
3428
|
+
function terminalLink(text, url2) {
|
|
3429
|
+
return `\x1B]8;;${url2}\x07${text}\x1B]8;;\x07`;
|
|
3430
|
+
}
|
|
3431
|
+
function renderFileRow(item, index) {
|
|
3432
|
+
const isDir = item.mimeType === "application/vnd.google-apps.folder";
|
|
3433
|
+
const icon = isDir ? "\u{1F4C1}" : getFileIcon(item.mimeType || "");
|
|
3434
|
+
const prefix = index !== void 0 ? `${import_chalk.default.dim((index + 1).toString().padStart(2, " ") + ".")} ` : "";
|
|
3435
|
+
let nameFormatted = isDir ? import_chalk.default.bold.blue(item.name || "untitled") : import_chalk.default.white(item.name || "untitled");
|
|
3436
|
+
if (item.webViewLink) {
|
|
3437
|
+
nameFormatted = terminalLink(nameFormatted, item.webViewLink);
|
|
3438
|
+
}
|
|
3439
|
+
const sizeFormatted = item.size ? import_chalk.default.dim(`[${formatBytes(parseInt(item.size, 10)).padStart(9, " ")}]`) : import_chalk.default.dim(isDir ? "[ FOLDER ]" : "[ DOC ]");
|
|
3440
|
+
const idFormatted = import_chalk.default.dim(`ID: ${item.id}`);
|
|
3441
|
+
return `${prefix}${icon} ${nameFormatted.padEnd(45)} ${sizeFormatted} ${idFormatted}`;
|
|
3442
|
+
}
|
|
3443
|
+
function getFileIcon(mimeType) {
|
|
3444
|
+
if (mimeType.includes("pdf")) return "\u{1F4D5}";
|
|
3445
|
+
if (mimeType.includes("image")) return "\u{1F5BC}\uFE0F ";
|
|
3446
|
+
if (mimeType.includes("video")) return "\u{1F3AC}";
|
|
3447
|
+
if (mimeType.includes("audio")) return "\u{1F3B5}";
|
|
3448
|
+
if (mimeType.includes("zip") || mimeType.includes("compressed") || mimeType.includes("tar")) return "\u{1F4E6}";
|
|
3449
|
+
if (mimeType.includes("spreadsheet") || mimeType.includes("excel")) return "\u{1F4CA}";
|
|
3450
|
+
if (mimeType.includes("document") || mimeType.includes("word")) return "\u{1F4DD}";
|
|
3451
|
+
if (mimeType.includes("presentation")) return "\u{1F4FD}\uFE0F ";
|
|
3452
|
+
if (mimeType.includes("json") || mimeType.includes("javascript") || mimeType.includes("typescript")) return "\u2699\uFE0F ";
|
|
3453
|
+
return "\u{1F4C4}";
|
|
3454
|
+
}
|
|
3455
|
+
async function runInteractiveExplorer(client, initialFolder = "/") {
|
|
3456
|
+
let currentFolder = initialFolder;
|
|
3457
|
+
let items = [];
|
|
3458
|
+
let selectedIndex = 0;
|
|
3459
|
+
let history = [];
|
|
3460
|
+
const refreshItems = async () => {
|
|
3461
|
+
items = await client.ls(currentFolder);
|
|
3462
|
+
selectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));
|
|
3463
|
+
};
|
|
3464
|
+
await refreshItems();
|
|
3465
|
+
if (!process.stdin.isTTY) {
|
|
3466
|
+
console.log(import_chalk.default.yellow("Interactive explorer requires a TTY terminal. Listing items instead:"));
|
|
3467
|
+
for (const item of items) {
|
|
3468
|
+
console.log(renderFileRow(item));
|
|
3469
|
+
}
|
|
3470
|
+
return;
|
|
3471
|
+
}
|
|
3472
|
+
import_node_readline.default.emitKeypressEvents(process.stdin);
|
|
3473
|
+
process.stdin.setRawMode(true);
|
|
3474
|
+
const renderScreen = () => {
|
|
3475
|
+
console.clear();
|
|
3476
|
+
console.log(import_chalk.default.bold.cyan("\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557"));
|
|
3477
|
+
console.log(import_chalk.default.bold.cyan("\u2551") + import_chalk.default.bold.yellow(" \u26A1 DriveKit Interactive Terminal Explorer ") + import_chalk.default.bold.cyan("\u2551"));
|
|
3478
|
+
console.log(import_chalk.default.bold.cyan("\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563"));
|
|
3479
|
+
console.log(import_chalk.default.bold.cyan("\u2551") + ` \u{1F4C2} Path: ${import_chalk.default.bold.green(currentFolder.padEnd(72))} ` + import_chalk.default.bold.cyan("\u2551"));
|
|
3480
|
+
console.log(import_chalk.default.bold.cyan("\u255A\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255D"));
|
|
3481
|
+
console.log(import_chalk.default.dim(" [\u2191/\u2193] Navigate \u2022 [Enter] Open Folder \u2022 [B] Back \u2022 [S] Share \u2022 [Q] Exit\n"));
|
|
3482
|
+
if (items.length === 0) {
|
|
3483
|
+
console.log(import_chalk.default.dim(" (This folder is empty)\n"));
|
|
3484
|
+
return;
|
|
3485
|
+
}
|
|
3486
|
+
const pageSize = 12;
|
|
3487
|
+
const startIdx = Math.max(0, Math.min(selectedIndex - Math.floor(pageSize / 2), items.length - pageSize));
|
|
3488
|
+
const endIdx = Math.min(items.length, startIdx + pageSize);
|
|
3489
|
+
for (let i = startIdx; i < endIdx; i++) {
|
|
3490
|
+
const isSelected = i === selectedIndex;
|
|
3491
|
+
const cursor = isSelected ? import_chalk.default.bold.cyan(" \u25BA ") : " ";
|
|
3492
|
+
const row = renderFileRow(items[i]);
|
|
3493
|
+
if (isSelected) {
|
|
3494
|
+
console.log(import_chalk.default.bgHex("#1e293b")(cursor + row));
|
|
3495
|
+
} else {
|
|
3496
|
+
console.log(cursor + row);
|
|
3497
|
+
}
|
|
3498
|
+
}
|
|
3499
|
+
console.log(import_chalk.default.dim(`
|
|
3500
|
+
Item ${selectedIndex + 1} of ${items.length}`));
|
|
3501
|
+
};
|
|
3502
|
+
renderScreen();
|
|
3503
|
+
return new Promise((resolve) => {
|
|
3504
|
+
const onKeypress = async (str, key) => {
|
|
3505
|
+
if (key.ctrl && key.name === "c") {
|
|
3506
|
+
cleanup();
|
|
3507
|
+
process.exit(0);
|
|
3508
|
+
}
|
|
3509
|
+
if (key.name === "q" || key.name === "escape" && history.length === 0) {
|
|
3510
|
+
cleanup();
|
|
3511
|
+
resolve();
|
|
3512
|
+
return;
|
|
3513
|
+
}
|
|
3514
|
+
if (key.name === "up") {
|
|
3515
|
+
selectedIndex = selectedIndex > 0 ? selectedIndex - 1 : items.length - 1;
|
|
3516
|
+
renderScreen();
|
|
3517
|
+
} else if (key.name === "down") {
|
|
3518
|
+
selectedIndex = selectedIndex < items.length - 1 ? selectedIndex + 1 : 0;
|
|
3519
|
+
renderScreen();
|
|
3520
|
+
} else if (key.name === "return") {
|
|
3521
|
+
const item = items[selectedIndex];
|
|
3522
|
+
if (item && item.mimeType === "application/vnd.google-apps.folder") {
|
|
3523
|
+
history.push(currentFolder);
|
|
3524
|
+
currentFolder = currentFolder === "/" ? `/${item.name}` : `${currentFolder}/${item.name}`;
|
|
3525
|
+
selectedIndex = 0;
|
|
3526
|
+
await refreshItems();
|
|
3527
|
+
renderScreen();
|
|
3528
|
+
} else if (item && item.webViewLink) {
|
|
3529
|
+
const { exec: exec2 } = await import("child_process");
|
|
3530
|
+
const openCmd = process.platform === "darwin" ? `open "${item.webViewLink}"` : `xdg-open "${item.webViewLink}"`;
|
|
3531
|
+
exec2(openCmd);
|
|
3532
|
+
renderScreen();
|
|
3533
|
+
}
|
|
3534
|
+
} else if (key.name === "b" || key.name === "backspace") {
|
|
3535
|
+
if (history.length > 0) {
|
|
3536
|
+
currentFolder = history.pop();
|
|
3537
|
+
selectedIndex = 0;
|
|
3538
|
+
await refreshItems();
|
|
3539
|
+
renderScreen();
|
|
3540
|
+
}
|
|
3541
|
+
} else if (str === "s" || str === "S") {
|
|
3542
|
+
const item = items[selectedIndex];
|
|
3543
|
+
if (item && item.id) {
|
|
3544
|
+
process.stdin.pause();
|
|
3545
|
+
console.log(`
|
|
3546
|
+
|
|
3547
|
+
${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_chalk.default.bold(item.name)}...`);
|
|
3548
|
+
try {
|
|
3549
|
+
const links = await client.sharePublic(item.id);
|
|
3550
|
+
console.log(`Preview URL: ${import_chalk.default.underline(links.previewLink)}`);
|
|
3551
|
+
console.log(`Direct Download URL: ${import_chalk.default.underline(links.directDownloadLink)}`);
|
|
3552
|
+
console.log(import_chalk.default.dim("\nPress any key to return to explorer..."));
|
|
3553
|
+
process.stdin.resume();
|
|
3554
|
+
process.stdin.once("data", () => {
|
|
3555
|
+
renderScreen();
|
|
3556
|
+
});
|
|
3557
|
+
} catch (err) {
|
|
3558
|
+
console.error(import_chalk.default.red(`Failed to share: ${err.message}`));
|
|
3559
|
+
setTimeout(renderScreen, 2e3);
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
}
|
|
3563
|
+
};
|
|
3564
|
+
const cleanup = () => {
|
|
3565
|
+
process.stdin.removeListener("keypress", onKeypress);
|
|
3566
|
+
if (process.stdin.setRawMode) {
|
|
3567
|
+
process.stdin.setRawMode(false);
|
|
3568
|
+
}
|
|
3569
|
+
process.stdin.pause();
|
|
3570
|
+
console.clear();
|
|
3571
|
+
console.log(import_chalk.default.green("\u{1F44B} Exited DriveKit explorer."));
|
|
3572
|
+
};
|
|
3573
|
+
process.stdin.on("keypress", onKeypress);
|
|
3574
|
+
});
|
|
3575
|
+
}
|
|
3576
|
+
|
|
2179
3577
|
// src/index.ts
|
|
2180
3578
|
async function createDrive(options) {
|
|
2181
3579
|
const instance = new DriveKit(options);
|
|
@@ -2192,6 +3590,8 @@ var index_default = DriveKit;
|
|
|
2192
3590
|
Downloader,
|
|
2193
3591
|
DriveAuthError,
|
|
2194
3592
|
DriveAuthenticator,
|
|
3593
|
+
DriveFileRef,
|
|
3594
|
+
DriveFolderRef,
|
|
2195
3595
|
DriveKit,
|
|
2196
3596
|
DriveKitError,
|
|
2197
3597
|
DriveNotFoundError,
|
|
@@ -2202,20 +3602,30 @@ var index_default = DriveKit;
|
|
|
2202
3602
|
GOOGLE_WORKSPACE_MIME_TYPES,
|
|
2203
3603
|
MIN_CHUNK_SIZE,
|
|
2204
3604
|
MULTIPART_THRESHOLD,
|
|
3605
|
+
MemoryMetadataCache,
|
|
2205
3606
|
PathResolver,
|
|
3607
|
+
PluginManager,
|
|
2206
3608
|
ResumableUploader,
|
|
2207
3609
|
SmartSyncEngine,
|
|
3610
|
+
SqliteMetadataCache,
|
|
2208
3611
|
StorageCleaner,
|
|
2209
3612
|
calculateFileMd5,
|
|
3613
|
+
createAutoNamePlugin,
|
|
2210
3614
|
createDrive,
|
|
3615
|
+
createWebhookPlugin,
|
|
2211
3616
|
formatBytes,
|
|
2212
3617
|
formatDuration,
|
|
2213
3618
|
formatSpeed,
|
|
2214
3619
|
getExtensionForMime,
|
|
3620
|
+
getFileIcon,
|
|
2215
3621
|
isGoogleWorkspaceDoc,
|
|
2216
3622
|
isRetryableError,
|
|
2217
3623
|
loginWithBrowser,
|
|
2218
3624
|
lookupMimeType,
|
|
3625
|
+
renderFileRow,
|
|
3626
|
+
runInteractiveExplorer,
|
|
3627
|
+
startWebDAVServer,
|
|
3628
|
+
terminalLink,
|
|
2219
3629
|
withRetry
|
|
2220
3630
|
});
|
|
2221
3631
|
//# sourceMappingURL=index.cjs.map
|