drivekit 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -325,8 +325,8 @@ var init_path_resolver = __esm({
325
325
  /**
326
326
  * Gets cache key for a path
327
327
  */
328
- getCacheKey(path9) {
329
- return `${this.rootFolderId}:${this.normalizePath(path9)}`;
328
+ getCacheKey(path10) {
329
+ return `${this.rootFolderId}:${this.normalizePath(path10)}`;
330
330
  }
331
331
  /**
332
332
  * Clears the path cache
@@ -340,8 +340,8 @@ var init_path_resolver = __esm({
340
340
  /**
341
341
  * Invalidate a single path from cache
342
342
  */
343
- invalidatePath(path9) {
344
- const norm = this.normalizePath(path9);
343
+ invalidatePath(path10) {
344
+ const norm = this.normalizePath(path10);
345
345
  const key = this.getCacheKey(norm);
346
346
  this.cache.delete(key);
347
347
  if (this.metadataCache) {
@@ -452,13 +452,14 @@ var init_path_resolver = __esm({
452
452
  file = sharedResponse.data.files?.[0];
453
453
  }
454
454
  if (file && file.id) {
455
+ const segmentParentId = currentParentId;
455
456
  currentParentId = file.id;
456
457
  if (this.metadataCache) {
457
458
  this.metadataCache.upsertFile({
458
459
  id: file.id,
459
460
  name: file.name || segment,
460
461
  mimeType: file.mimeType || "",
461
- parentId: currentParentId,
462
+ parentId: segmentParentId,
462
463
  path: currentPath,
463
464
  trashed: false
464
465
  });
@@ -496,13 +497,14 @@ var init_path_resolver = __esm({
496
497
  if (!newFolder.id) {
497
498
  throw new Error(`Failed to create folder "${segment}" under parent "${currentParentId}"`);
498
499
  }
500
+ const segmentParentId = currentParentId;
499
501
  currentParentId = newFolder.id;
500
502
  if (this.metadataCache) {
501
503
  this.metadataCache.upsertFile({
502
504
  id: newFolder.id,
503
505
  name: segment,
504
506
  mimeType: GOOGLE_WORKSPACE_MIME_TYPES.FOLDER,
505
- parentId: currentParentId,
507
+ parentId: segmentParentId,
506
508
  path: currentPath,
507
509
  trashed: false
508
510
  });
@@ -1902,6 +1904,7 @@ var init_resource_refs = __esm({
1902
1904
  });
1903
1905
 
1904
1906
  // src/core/plugins.ts
1907
+ import path5 from "path";
1905
1908
  var PluginManager;
1906
1909
  var init_plugins = __esm({
1907
1910
  "src/core/plugins.ts"() {
@@ -1909,10 +1912,36 @@ var init_plugins = __esm({
1909
1912
  init_esm_shims();
1910
1913
  PluginManager = class {
1911
1914
  plugins = [];
1915
+ /**
1916
+ * Register a plugin. If a plugin with the same name already exists,
1917
+ * it replaces the old one to avoid duplicate side-effects.
1918
+ */
1912
1919
  use(plugin) {
1920
+ this.plugins = this.plugins.filter((p) => p.name !== plugin.name);
1913
1921
  this.plugins.push(plugin);
1914
1922
  return this;
1915
1923
  }
1924
+ /**
1925
+ * Unregister a plugin by its name.
1926
+ * Returns true if a plugin was found and removed, false otherwise.
1927
+ */
1928
+ unuse(pluginName) {
1929
+ const initialLen = this.plugins.length;
1930
+ this.plugins = this.plugins.filter((p) => p.name !== pluginName);
1931
+ return this.plugins.length < initialLen;
1932
+ }
1933
+ /**
1934
+ * Check if a plugin with given name is currently active
1935
+ */
1936
+ has(pluginName) {
1937
+ return this.plugins.some((p) => p.name === pluginName);
1938
+ }
1939
+ /**
1940
+ * Returns all currently registered plugins
1941
+ */
1942
+ getPlugins() {
1943
+ return [...this.plugins];
1944
+ }
1916
1945
  async runBeforeUpload(options) {
1917
1946
  let current = { ...options };
1918
1947
  for (const plugin of this.plugins) {
@@ -1959,7 +1988,7 @@ var init_plugins = __esm({
1959
1988
 
1960
1989
  // src/core/cache.ts
1961
1990
  import os from "os";
1962
- import path5 from "path";
1991
+ import path6 from "path";
1963
1992
  import fs5 from "fs";
1964
1993
  var SqliteMetadataCache, MemoryMetadataCache;
1965
1994
  var init_cache = __esm({
@@ -1975,14 +2004,14 @@ var init_cache = __esm({
1975
2004
  if (customPath) {
1976
2005
  this.dbPath = customPath;
1977
2006
  } else {
1978
- const dir = path5.join(os.homedir(), ".drivekit");
2007
+ const dir = path6.join(os.homedir(), ".drivekit");
1979
2008
  if (!fs5.existsSync(dir)) {
1980
2009
  try {
1981
2010
  fs5.mkdirSync(dir, { recursive: true });
1982
2011
  } catch {
1983
2012
  }
1984
2013
  }
1985
- this.dbPath = path5.join(dir, "cache.db");
2014
+ this.dbPath = path6.join(dir, "cache.db");
1986
2015
  }
1987
2016
  }
1988
2017
  init() {
@@ -2000,7 +2029,7 @@ var init_cache = __esm({
2000
2029
  CREATE TABLE IF NOT EXISTS files (
2001
2030
  id TEXT PRIMARY KEY,
2002
2031
  name TEXT NOT NULL,
2003
- mimeType TEXT NOT NULL,
2032
+ mimeType TEXT,
2004
2033
  size INTEGER,
2005
2034
  parentId TEXT,
2006
2035
  path TEXT,
@@ -2086,7 +2115,7 @@ var init_cache = __esm({
2086
2115
  stmt.run(
2087
2116
  entry.id,
2088
2117
  entry.name,
2089
- entry.mimeType,
2118
+ entry.mimeType ?? null,
2090
2119
  entry.size ?? null,
2091
2120
  entry.parentId ?? null,
2092
2121
  entry.path ?? null,
@@ -2122,6 +2151,30 @@ var init_cache = __esm({
2122
2151
  const stmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2123
2152
  stmt.run(id);
2124
2153
  }
2154
+ pruneMissing(activeIds) {
2155
+ if (this.fallbackMemory) {
2156
+ return this.fallbackMemory.pruneMissing(activeIds);
2157
+ }
2158
+ if (!this.initialized || !this.db || activeIds.length === 0) return 0;
2159
+ const idSet = new Set(activeIds);
2160
+ const rows = this.db.prepare("SELECT id FROM files").all();
2161
+ let pruned = 0;
2162
+ this.db.exec("BEGIN TRANSACTION;");
2163
+ try {
2164
+ const deleteStmt = this.db.prepare("DELETE FROM files WHERE id = ?");
2165
+ for (const row of rows) {
2166
+ if (!idSet.has(row.id)) {
2167
+ deleteStmt.run(row.id);
2168
+ pruned++;
2169
+ }
2170
+ }
2171
+ this.db.exec("COMMIT;");
2172
+ return pruned;
2173
+ } catch (e) {
2174
+ this.db.exec("ROLLBACK;");
2175
+ throw e;
2176
+ }
2177
+ }
2125
2178
  clear() {
2126
2179
  if (this.fallbackMemory) {
2127
2180
  this.fallbackMemory.clear();
@@ -2252,6 +2305,17 @@ var init_cache = __esm({
2252
2305
  deleteFile(id) {
2253
2306
  this.files.delete(id);
2254
2307
  }
2308
+ pruneMissing(activeIds) {
2309
+ const idSet = new Set(activeIds);
2310
+ let pruned = 0;
2311
+ for (const id of Array.from(this.files.keys())) {
2312
+ if (!idSet.has(id)) {
2313
+ this.files.delete(id);
2314
+ pruned++;
2315
+ }
2316
+ }
2317
+ return pruned;
2318
+ }
2255
2319
  clear() {
2256
2320
  this.files.clear();
2257
2321
  this.meta.clear();
@@ -2292,17 +2356,42 @@ var init_cache = __esm({
2292
2356
  // src/server/webdav.ts
2293
2357
  var webdav_exports = {};
2294
2358
  __export(webdav_exports, {
2359
+ escapeXml: () => escapeXml,
2295
2360
  startWebDAVServer: () => startWebDAVServer
2296
2361
  });
2297
2362
  import http2 from "http";
2298
2363
  import url from "url";
2299
- import path6 from "path";
2364
+ import path7 from "path";
2365
+ function escapeXml(unsafe) {
2366
+ return unsafe.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;");
2367
+ }
2300
2368
  async function startWebDAVServer(drive2, options = {}) {
2301
2369
  const port = options.port || 8080;
2302
2370
  const host = options.host || "127.0.0.1";
2303
2371
  await drive2.init();
2304
2372
  const server = http2.createServer(async (req, res) => {
2305
2373
  try {
2374
+ if (options.auth?.username && options.auth?.password) {
2375
+ const authHeader = req.headers["authorization"];
2376
+ if (!authHeader || !authHeader.startsWith("Basic ")) {
2377
+ res.writeHead(401, {
2378
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2379
+ "Content-Type": "text/plain"
2380
+ });
2381
+ res.end("Authentication required");
2382
+ return;
2383
+ }
2384
+ const credentials = Buffer.from(authHeader.replace("Basic ", ""), "base64").toString("utf8");
2385
+ const [user, pass] = credentials.split(":");
2386
+ if (user !== options.auth.username || pass !== options.auth.password) {
2387
+ res.writeHead(401, {
2388
+ "WWW-Authenticate": 'Basic realm="DriveKit WebDAV"',
2389
+ "Content-Type": "text/plain"
2390
+ });
2391
+ res.end("Invalid credentials");
2392
+ return;
2393
+ }
2394
+ }
2306
2395
  const parsedUrl = url.parse(req.url || "/", true);
2307
2396
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2308
2397
  const virtualPath = decodedPath === "" ? "/" : decodedPath;
@@ -2311,7 +2400,8 @@ async function startWebDAVServer(drive2, options = {}) {
2311
2400
  res.writeHead(200, {
2312
2401
  DAV: "1, 2",
2313
2402
  Allow: "OPTIONS, GET, HEAD, POST, PUT, DELETE, MKCOL, MOVE, COPY, PROPFIND",
2314
- "MS-Author-Via": "DAV"
2403
+ "MS-Author-Via": "DAV",
2404
+ "Accept-Ranges": "bytes"
2315
2405
  });
2316
2406
  res.end();
2317
2407
  return;
@@ -2329,7 +2419,7 @@ async function startWebDAVServer(drive2, options = {}) {
2329
2419
  case "HEAD": {
2330
2420
  if (virtualPath === "/" || virtualPath === "") {
2331
2421
  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>");
2422
+ res.end("<h1>DriveKit WebDAV Server Running</h1><p>Connect via Finder, File Explorer, or WebDAV client.</p>");
2333
2423
  return;
2334
2424
  }
2335
2425
  try {
@@ -2339,15 +2429,42 @@ async function startWebDAVServer(drive2, options = {}) {
2339
2429
  res.end("Cannot GET a directory");
2340
2430
  return;
2341
2431
  }
2342
- const stream = await drive2.createReadStream(virtualPath);
2343
- res.writeHead(200, {
2344
- "Content-Type": file.mimeType || "application/octet-stream",
2345
- "Content-Length": file.size || void 0
2346
- });
2347
- if (req.method === "HEAD") {
2348
- res.end();
2432
+ const fileSize = file.size ? parseInt(file.size, 10) : void 0;
2433
+ const rangeHeader = req.headers["range"];
2434
+ if (rangeHeader && rangeHeader.startsWith("bytes=") && fileSize !== void 0) {
2435
+ const parts = rangeHeader.replace("bytes=", "").split("-");
2436
+ const start = parseInt(parts[0], 10);
2437
+ const end = parts[1] ? parseInt(parts[1], 10) : fileSize - 1;
2438
+ if (isNaN(start) || start >= fileSize || end !== void 0 && end >= fileSize) {
2439
+ res.writeHead(416, { "Content-Range": `bytes */${fileSize}` });
2440
+ res.end();
2441
+ return;
2442
+ }
2443
+ const stream = await drive2.createReadStream(virtualPath, { start, end });
2444
+ const chunkLength = end - start + 1;
2445
+ res.writeHead(206, {
2446
+ "Content-Type": file.mimeType || "application/octet-stream",
2447
+ "Content-Range": `bytes ${start}-${end}/${fileSize}`,
2448
+ "Content-Length": chunkLength,
2449
+ "Accept-Ranges": "bytes"
2450
+ });
2451
+ if (req.method === "HEAD") {
2452
+ res.end();
2453
+ } else {
2454
+ stream.pipe(res);
2455
+ }
2349
2456
  } else {
2350
- stream.pipe(res);
2457
+ const stream = await drive2.createReadStream(virtualPath);
2458
+ res.writeHead(200, {
2459
+ "Content-Type": file.mimeType || "application/octet-stream",
2460
+ "Content-Length": file.size || void 0,
2461
+ "Accept-Ranges": "bytes"
2462
+ });
2463
+ if (req.method === "HEAD") {
2464
+ res.end();
2465
+ } else {
2466
+ stream.pipe(res);
2467
+ }
2351
2468
  }
2352
2469
  } catch (e) {
2353
2470
  res.writeHead(404, { "Content-Type": "text/plain" });
@@ -2356,27 +2473,29 @@ async function startWebDAVServer(drive2, options = {}) {
2356
2473
  return;
2357
2474
  }
2358
2475
  case "PUT": {
2359
- const remoteDir = path6.dirname(virtualPath);
2360
- const fileName = path6.basename(virtualPath);
2476
+ const remoteDir = path7.dirname(virtualPath);
2361
2477
  await drive2.mkdirp(remoteDir);
2362
- const chunks = [];
2363
- req.on("data", (chunk) => chunks.push(chunk));
2364
- req.on("end", async () => {
2365
- try {
2366
- const buffer = Buffer.concat(chunks);
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");
2478
+ let existed = false;
2479
+ try {
2480
+ const existingFile = await drive2.getFile(virtualPath);
2481
+ if (existingFile && existingFile.id) {
2482
+ existed = true;
2378
2483
  }
2379
- });
2484
+ } catch {
2485
+ existed = false;
2486
+ }
2487
+ try {
2488
+ const uploadStream = await drive2.createWriteStream(virtualPath, {
2489
+ overwrite: true
2490
+ });
2491
+ req.pipe(uploadStream);
2492
+ await uploadStream.done;
2493
+ res.writeHead(existed ? 204 : 201, { "Content-Type": "text/plain" });
2494
+ res.end(existed ? "" : "Created");
2495
+ } catch (err) {
2496
+ res.writeHead(500, { "Content-Type": "text/plain" });
2497
+ res.end(err.message || "Upload failed");
2498
+ }
2380
2499
  return;
2381
2500
  }
2382
2501
  case "MKCOL": {
@@ -2408,14 +2527,24 @@ async function startWebDAVServer(drive2, options = {}) {
2408
2527
  res.end("Destination header missing");
2409
2528
  return;
2410
2529
  }
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
2530
  try {
2416
- await drive2.move(virtualPath, newParent);
2417
- if (newName !== path6.basename(virtualPath)) {
2418
- await drive2.rename(destPath, newName);
2531
+ const file = await drive2.getFile(virtualPath);
2532
+ if (!file?.id) {
2533
+ res.writeHead(404, { "Content-Type": "text/plain" });
2534
+ res.end("Source file not found");
2535
+ return;
2536
+ }
2537
+ const destUrl = url.parse(destination);
2538
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2539
+ const newName = path7.basename(destPath);
2540
+ const newParentDir = path7.dirname(destPath);
2541
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2542
+ const currentParentDir = path7.dirname(virtualPath);
2543
+ if (newParentDir !== currentParentDir) {
2544
+ await drive2.move(file.id, newParentFolderId);
2545
+ }
2546
+ if (newName !== path7.basename(virtualPath)) {
2547
+ await drive2.rename(file.id, newName);
2419
2548
  }
2420
2549
  res.writeHead(201);
2421
2550
  res.end("Moved");
@@ -2425,6 +2554,34 @@ async function startWebDAVServer(drive2, options = {}) {
2425
2554
  }
2426
2555
  return;
2427
2556
  }
2557
+ case "COPY": {
2558
+ const destination = req.headers["destination"];
2559
+ if (!destination || typeof destination !== "string") {
2560
+ res.writeHead(400, { "Content-Type": "text/plain" });
2561
+ res.end("Destination header missing");
2562
+ return;
2563
+ }
2564
+ try {
2565
+ const file = await drive2.getFile(virtualPath);
2566
+ if (!file?.id) {
2567
+ res.writeHead(404, { "Content-Type": "text/plain" });
2568
+ res.end("Source file not found");
2569
+ return;
2570
+ }
2571
+ const destUrl = url.parse(destination);
2572
+ const destPath = decodeURIComponent(destUrl.pathname || "");
2573
+ const newName = path7.basename(destPath);
2574
+ const newParentDir = path7.dirname(destPath);
2575
+ const newParentFolderId = await drive2.mkdirp(newParentDir);
2576
+ await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2577
+ res.writeHead(201);
2578
+ res.end("Copied");
2579
+ } catch (err) {
2580
+ res.writeHead(500, { "Content-Type": "text/plain" });
2581
+ res.end(err.message);
2582
+ }
2583
+ return;
2584
+ }
2428
2585
  default: {
2429
2586
  res.writeHead(501, { "Content-Type": "text/plain" });
2430
2587
  res.end("Method Not Implemented");
@@ -2494,13 +2651,14 @@ ${responses.join("\n")}
2494
2651
  }
2495
2652
  function renderWebDAVResponse(href, isDir, size, modifiedTime) {
2496
2653
  const encodedHref = encodeURI(href);
2654
+ const displayName = escapeXml(path7.basename(href) || "root");
2497
2655
  const resourceType = isDir ? "<D:collection/>" : "";
2498
2656
  const dateFormatted = new Date(modifiedTime).toUTCString();
2499
2657
  return ` <D:response>
2500
2658
  <D:href>${encodedHref}</D:href>
2501
2659
  <D:propstat>
2502
2660
  <D:prop>
2503
- <D:displayname>${path6.basename(href) || "root"}</D:displayname>
2661
+ <D:displayname>${displayName}</D:displayname>
2504
2662
  <D:resourcetype>${resourceType}</D:resourcetype>
2505
2663
  <D:getcontentlength>${isDir ? "0" : size}</D:getcontentlength>
2506
2664
  <D:getlastmodified>${dateFormatted}</D:getlastmodified>
@@ -2523,7 +2681,7 @@ __export(client_exports, {
2523
2681
  DriveKit: () => DriveKit
2524
2682
  });
2525
2683
  import fs6 from "fs";
2526
- import path7 from "path";
2684
+ import path8 from "path";
2527
2685
  import { drive } from "@googleapis/drive";
2528
2686
  var DriveKit;
2529
2687
  var init_client = __esm({
@@ -2676,8 +2834,9 @@ var init_client = __esm({
2676
2834
  * Lists contents of a folder (by folder ID or path)
2677
2835
  */
2678
2836
  async ls(folderIdOrPath = "/") {
2679
- if (folderIdOrPath === "/" || folderIdOrPath === "root") {
2680
- return await this.query().raw("'root' in parents or sharedWithMe = true").notTrashed().orderBy("folder,name").list();
2837
+ if (folderIdOrPath === "/" || folderIdOrPath === "root" || folderIdOrPath === this.rootFolderId) {
2838
+ const parentFilter = this.rootFolderId === "root" ? "'root' in parents or sharedWithMe = true" : `'${this.rootFolderId}' in parents`;
2839
+ return await this.query().raw(parentFilter).notTrashed().orderBy("folder,name").list();
2681
2840
  }
2682
2841
  const folderId = await this.resolveId(folderIdOrPath);
2683
2842
  return await this.query().inFolder(folderId).notTrashed().orderBy("folder,name").list();
@@ -2720,7 +2879,7 @@ var init_client = __esm({
2720
2879
  }
2721
2880
  }
2722
2881
  if (existingId) {
2723
- const fileName = targetName || path7.basename(opts.source);
2882
+ const fileName = targetName || path8.basename(opts.source);
2724
2883
  const raw = await this.getRawClient();
2725
2884
  const copyRes = await withRetry(async () => {
2726
2885
  return await raw.files.copy({
@@ -3007,8 +3166,8 @@ var init_client = __esm({
3007
3166
  const entries = await fs6.promises.readdir(dir, { withFileTypes: true });
3008
3167
  const files = [];
3009
3168
  for (const entry of entries) {
3010
- const fullPath = path7.join(dir, entry.name);
3011
- const relPath = path7.join(base, entry.name);
3169
+ const fullPath = path8.join(dir, entry.name);
3170
+ const relPath = path8.join(base, entry.name);
3012
3171
  if (entry.isDirectory()) {
3013
3172
  const sub = await collectFiles(fullPath, relPath);
3014
3173
  files.push(...sub);
@@ -3026,11 +3185,11 @@ var init_client = __esm({
3026
3185
  if (remoteDirCache.has(relDir)) {
3027
3186
  return remoteDirCache.get(relDir);
3028
3187
  }
3029
- const parts = relDir.split(path7.sep).filter(Boolean);
3188
+ const parts = relDir.split(path8.sep).filter(Boolean);
3030
3189
  let currentParent = targetFolderId;
3031
3190
  let currentRel = "";
3032
3191
  for (const part of parts) {
3033
- currentRel = currentRel ? path7.join(currentRel, part) : part;
3192
+ currentRel = currentRel ? path8.join(currentRel, part) : part;
3034
3193
  if (remoteDirCache.has(currentRel)) {
3035
3194
  currentParent = remoteDirCache.get(currentRel);
3036
3195
  continue;
@@ -3059,8 +3218,8 @@ var init_client = __esm({
3059
3218
  };
3060
3219
  await pool.map(allFiles, async (fileItem) => {
3061
3220
  try {
3062
- const relDir = path7.dirname(fileItem.relPath);
3063
- const fileName = path7.basename(fileItem.relPath);
3221
+ const relDir = path8.dirname(fileItem.relPath);
3222
+ const fileName = path8.basename(fileItem.relPath);
3064
3223
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3065
3224
  if (options.onFileStart) {
3066
3225
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3196,8 +3355,15 @@ var init_client = __esm({
3196
3355
  await this.init();
3197
3356
  const { PassThrough } = await import("stream");
3198
3357
  const passThrough = new PassThrough();
3199
- const remoteDir = path7.dirname(remotePath);
3200
- const fileName = options.name || options.filename || path7.basename(remotePath);
3358
+ let resolveDone;
3359
+ let rejectDone;
3360
+ const donePromise = new Promise((resolve, reject) => {
3361
+ resolveDone = resolve;
3362
+ rejectDone = reject;
3363
+ });
3364
+ passThrough.done = donePromise;
3365
+ const remoteDir = path8.dirname(remotePath);
3366
+ const fileName = options.name || options.filename || path8.basename(remotePath);
3201
3367
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3202
3368
  const mimeType = options.mimeType || "application/octet-stream";
3203
3369
  const raw = this.driveClient;
@@ -3214,9 +3380,10 @@ var init_client = __esm({
3214
3380
  fields: "id, name, mimeType, size, md5Checksum",
3215
3381
  supportsAllDrives: true
3216
3382
  }).then((res) => {
3217
- if (res.data.id && this.metadataCacheInstance) {
3383
+ const file = res.data;
3384
+ if (file.id && this.metadataCacheInstance) {
3218
3385
  this.metadataCacheInstance.upsertFile({
3219
- id: res.data.id,
3386
+ id: file.id,
3220
3387
  name: fileName,
3221
3388
  mimeType,
3222
3389
  parentId: targetParentId,
@@ -3224,8 +3391,10 @@ var init_client = __esm({
3224
3391
  trashed: false
3225
3392
  });
3226
3393
  }
3394
+ resolveDone(file);
3227
3395
  }).catch((err) => {
3228
3396
  passThrough.destroy(err);
3397
+ rejectDone(err);
3229
3398
  });
3230
3399
  return passThrough;
3231
3400
  }
@@ -3266,6 +3435,7 @@ var init_client = __esm({
3266
3435
  const client = this.driveClient;
3267
3436
  let pageToken = void 0;
3268
3437
  let totalScanned = 0;
3438
+ const rawFiles = [];
3269
3439
  do {
3270
3440
  const res = await withRetry(async () => {
3271
3441
  return await client.files.list({
@@ -3279,21 +3449,49 @@ var init_client = __esm({
3279
3449
  });
3280
3450
  });
3281
3451
  const files = res.data.files || [];
3282
- const entries = files.map((f) => ({
3283
- id: f.id,
3284
- name: f.name || "untitled",
3285
- mimeType: f.mimeType || "",
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;
3452
+ for (const f of files) {
3453
+ if (f.id) rawFiles.push(f);
3454
+ }
3455
+ totalScanned += files.length;
3294
3456
  options?.onProgress?.(totalScanned);
3295
3457
  pageToken = res.data.nextPageToken || void 0;
3296
3458
  } while (pageToken);
3459
+ const fileMap = /* @__PURE__ */ new Map();
3460
+ for (const f of rawFiles) {
3461
+ fileMap.set(f.id, f);
3462
+ }
3463
+ const pathMemo = /* @__PURE__ */ new Map();
3464
+ const rootId = this.rootFolderId;
3465
+ function computePath(id, visited = /* @__PURE__ */ new Set()) {
3466
+ if (pathMemo.has(id)) return pathMemo.get(id);
3467
+ if (visited.has(id)) return "";
3468
+ visited.add(id);
3469
+ const f = fileMap.get(id);
3470
+ if (!f || !f.name) return "";
3471
+ const parentId = f.parents?.[0];
3472
+ if (!parentId || parentId === "root" || parentId === rootId) {
3473
+ const p = `/${f.name}`;
3474
+ pathMemo.set(id, p);
3475
+ return p;
3476
+ }
3477
+ const parentPath = computePath(parentId, visited);
3478
+ const fullPath = parentPath ? `${parentPath}/${f.name}` : `/${f.name}`;
3479
+ pathMemo.set(id, fullPath);
3480
+ return fullPath;
3481
+ }
3482
+ const entries = rawFiles.map((f) => ({
3483
+ id: f.id,
3484
+ name: f.name || "untitled",
3485
+ mimeType: f.mimeType || "",
3486
+ size: f.size ? parseInt(f.size, 10) : void 0,
3487
+ parentId: f.parents?.[0],
3488
+ path: computePath(f.id),
3489
+ md5Checksum: f.md5Checksum || void 0,
3490
+ trashed: !!f.trashed,
3491
+ modifiedTime: f.modifiedTime || void 0
3492
+ }));
3493
+ this.metadataCacheInstance.upsertFiles(entries);
3494
+ this.metadataCacheInstance.pruneMissing(rawFiles.map((f) => f.id));
3297
3495
  this.metadataCacheInstance.setMeta("last_sync_timestamp", (/* @__PURE__ */ new Date()).toISOString());
3298
3496
  return this.metadataCacheInstance.getStats();
3299
3497
  }
@@ -3410,7 +3608,7 @@ init_esm_shims();
3410
3608
  init_client();
3411
3609
  init_format();
3412
3610
  import fs7 from "fs";
3413
- import path8 from "path";
3611
+ import path9 from "path";
3414
3612
  import { Command } from "commander";
3415
3613
  import chalk2 from "chalk";
3416
3614
  import ora from "ora";
@@ -3571,7 +3769,14 @@ ${chalk.cyan("\u{1F517} Getting shareable link for:")} ${chalk.bold(item.name)}.
3571
3769
 
3572
3770
  // src/cli.ts
3573
3771
  var program = new Command();
3574
- program.name("drivekit").description(chalk2.bold.cyan("\u26A1 DriveKit CLI: High-speed, flexible Google Drive tool for developers")).version("1.0.0").option("-k, --key <path>", "Path to service account JSON key file").option("-t, --token <token>", "Google OAuth2 Bearer access token");
3772
+ var pkgVersion = "1.1.1";
3773
+ try {
3774
+ const pkgPath = new URL("../package.json", import.meta.url);
3775
+ const pkg = JSON.parse(fs7.readFileSync(pkgPath, "utf8"));
3776
+ if (pkg.version) pkgVersion = pkg.version;
3777
+ } catch {
3778
+ }
3779
+ 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
3780
  function getAuthConfig(cmdOptions) {
3576
3781
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
3577
3782
  const accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
@@ -3648,7 +3853,7 @@ program.command("upload <localFile> [remotePath]").description("Upload a file wi
3648
3853
  console.error(chalk2.red(`\u274C Local file not found: ${localFile}`));
3649
3854
  process.exit(1);
3650
3855
  }
3651
- const fileName = path8.basename(localFile);
3856
+ const fileName = path9.basename(localFile);
3652
3857
  const spinner = ora(`Preparing upload: ${fileName}...`).start();
3653
3858
  try {
3654
3859
  const client = await getClient(options);
@@ -3912,7 +4117,7 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
3912
4117
  if (result.tokens.refresh_token) {
3913
4118
  console.log(`Refresh Token: ${chalk2.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
3914
4119
  }
3915
- const outPath = path8.resolve("./gdrive-tokens.json");
4120
+ const outPath = path9.resolve("./gdrive-tokens.json");
3916
4121
  fs7.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
3917
4122
  console.log(`\u{1F4BE} Saved tokens to: ${chalk2.bold(outPath)}
3918
4123
  `);
@@ -3990,19 +4195,25 @@ program.command("shared-drives").description("List accessible Google Workspace S
3990
4195
  process.exit(1);
3991
4196
  }
3992
4197
  });
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) => {
4198
+ 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
4199
  try {
3995
4200
  const client = await getClient(options);
3996
4201
  const port = parseInt(options.port, 10) || 8080;
3997
4202
  const host = options.host || "127.0.0.1";
4203
+ const auth = options.username ? { username: options.username, password: options.password || "" } : void 0;
3998
4204
  console.log(chalk2.bold.cyan("\n\u26A1 DriveKit WebDAV Server"));
3999
4205
  console.log("Starting local WebDAV bridge to Google Drive...\n");
4000
- const serverInstance = await client.serveWebDAV({ port, host });
4206
+ const serverInstance = await client.serveWebDAV({ port, host, auth });
4001
4207
  console.log(chalk2.bold.green(`\u{1F680} Server active at: ${chalk2.underline(serverInstance.url)}`));
4208
+ if (auth) {
4209
+ console.log(chalk2.yellow(`\u{1F512} Basic Authentication: ENABLED (User: ${auth.username})`));
4210
+ } else {
4211
+ console.log(chalk2.dim("\u{1F513} Authentication: Anonymous (Localhost only recommended)"));
4212
+ }
4002
4213
  console.log(chalk2.white("\n\u{1F4CC} How to mount on macOS Finder:"));
4003
4214
  console.log(` 1. Open Finder and press ${chalk2.bold.cyan("Cmd + K")} (Connect to Server)`);
4004
4215
  console.log(` 2. Enter: ${chalk2.bold.yellow(serverInstance.url)}`);
4005
- console.log(` 3. Click ${chalk2.bold("Connect")} (Connect as Guest)
4216
+ console.log(` 3. Click ${chalk2.bold("Connect")}${auth ? ` and log in as ${auth.username}` : " (Connect as Guest)"}
4006
4217
  `);
4007
4218
  console.log(chalk2.white("\u{1F4CC} How to mount on Windows:"));
4008
4219
  console.log(` 1. Open File Explorer -> This PC -> "Map network drive"`);