drivekit 1.1.2 → 1.2.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/dist/cli.cjs CHANGED
@@ -364,8 +364,8 @@ var init_path_resolver = __esm({
364
364
  /**
365
365
  * Gets cache key for a path
366
366
  */
367
- getCacheKey(path9) {
368
- return `${this.rootFolderId}:${this.normalizePath(path9)}`;
367
+ getCacheKey(path11) {
368
+ return `${this.rootFolderId}:${this.normalizePath(path11)}`;
369
369
  }
370
370
  /**
371
371
  * Clears the path cache
@@ -379,8 +379,8 @@ var init_path_resolver = __esm({
379
379
  /**
380
380
  * Invalidate a single path from cache
381
381
  */
382
- invalidatePath(path9) {
383
- const norm = this.normalizePath(path9);
382
+ invalidatePath(path11) {
383
+ const norm = this.normalizePath(path11);
384
384
  const key = this.getCacheKey(norm);
385
385
  this.cache.delete(key);
386
386
  if (this.metadataCache) {
@@ -1977,6 +1977,10 @@ var init_resource_refs = __esm({
1977
1977
  async getLink() {
1978
1978
  return await this.drive.getShareableLink(this.pathOrId);
1979
1979
  }
1980
+ /** Access historical revisions & version control for this file */
1981
+ get revisions() {
1982
+ return this.drive.getRevisions(this.pathOrId);
1983
+ }
1980
1984
  /** Returns a ReadableStream for this file, optionally with byte Range requests */
1981
1985
  async createReadStream(options) {
1982
1986
  return await this.drive.createReadStream(this.pathOrId, options);
@@ -2467,57 +2471,1256 @@ var init_cache = __esm({
2467
2471
  upsertFiles(entries) {
2468
2472
  for (const e of entries) this.upsertFile(e);
2469
2473
  }
2470
- deleteFile(id) {
2471
- this.files.delete(id);
2474
+ deleteFile(id) {
2475
+ this.files.delete(id);
2476
+ }
2477
+ pruneMissing(activeIds) {
2478
+ const idSet = new Set(activeIds);
2479
+ let pruned = 0;
2480
+ for (const id of Array.from(this.files.keys())) {
2481
+ if (!idSet.has(id)) {
2482
+ this.files.delete(id);
2483
+ pruned++;
2484
+ }
2485
+ }
2486
+ return pruned;
2487
+ }
2488
+ clear() {
2489
+ this.files.clear();
2490
+ this.meta.clear();
2491
+ }
2492
+ getMeta(key) {
2493
+ return this.meta.get(key) || null;
2494
+ }
2495
+ setMeta(key, value) {
2496
+ this.meta.set(key, value);
2497
+ }
2498
+ getStats() {
2499
+ let fileCount = 0;
2500
+ let folderCount = 0;
2501
+ let totalSizeBytes = 0;
2502
+ for (const f of this.files.values()) {
2503
+ if (f.trashed) continue;
2504
+ if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2505
+ else {
2506
+ fileCount++;
2507
+ totalSizeBytes += f.size || 0;
2508
+ }
2509
+ }
2510
+ return {
2511
+ fileCount,
2512
+ folderCount,
2513
+ totalSizeBytes,
2514
+ lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2515
+ databasePath: ":memory:"
2516
+ };
2517
+ }
2518
+ close() {
2519
+ this.clear();
2520
+ }
2521
+ };
2522
+ }
2523
+ });
2524
+
2525
+ // src/crypto/encryption.ts
2526
+ function deriveKey(password, salt) {
2527
+ return import_node_crypto2.default.pbkdf2Sync(password, salt, PBKDF2_ROUNDS, 32, "sha512");
2528
+ }
2529
+ var import_node_crypto2, import_node_stream3, MAGIC_HEADER, MAGIC_STREAM_HEADER, SALT_LENGTH, IV_LENGTH, TAG_LENGTH, PBKDF2_ROUNDS, DriveKitCrypto;
2530
+ var init_encryption = __esm({
2531
+ "src/crypto/encryption.ts"() {
2532
+ "use strict";
2533
+ init_cjs_shims();
2534
+ import_node_crypto2 = __toESM(require("crypto"), 1);
2535
+ import_node_stream3 = require("stream");
2536
+ MAGIC_HEADER = Buffer.from("DKENC1", "utf8");
2537
+ MAGIC_STREAM_HEADER = Buffer.from("DKENCS", "utf8");
2538
+ SALT_LENGTH = 16;
2539
+ IV_LENGTH = 12;
2540
+ TAG_LENGTH = 16;
2541
+ PBKDF2_ROUNDS = 1e5;
2542
+ DriveKitCrypto = class {
2543
+ config;
2544
+ constructor(config) {
2545
+ if (!config.password && !config.key) {
2546
+ throw new Error("DriveKitCrypto requires either a password or a 32-byte key.");
2547
+ }
2548
+ if (config.key && config.key.length !== 32) {
2549
+ throw new Error(`DriveKitCrypto raw key must be exactly 32 bytes, got ${config.key.length} bytes.`);
2550
+ }
2551
+ this.config = config;
2552
+ }
2553
+ /**
2554
+ * Encrypts a Buffer using AES-256-GCM.
2555
+ * Format: [MAGIC (6B)][SALT (16B)][IV (12B)][TAG (16B)][CIPHERTEXT]
2556
+ */
2557
+ encryptBuffer(data) {
2558
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
2559
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
2560
+ const key = this.config.key || deriveKey(this.config.password, salt);
2561
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
2562
+ const ciphertext = Buffer.concat([cipher.update(data), cipher.final()]);
2563
+ const tag = cipher.getAuthTag();
2564
+ return Buffer.concat([MAGIC_HEADER, salt, iv, tag, ciphertext]);
2565
+ }
2566
+ /**
2567
+ * Decrypts a Buffer previously encrypted with encryptBuffer or createEncryptStream.
2568
+ */
2569
+ decryptBuffer(encryptedData) {
2570
+ if (encryptedData.length < MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH + TAG_LENGTH) {
2571
+ throw new Error("Encrypted payload is too short to be valid DriveKit ciphertext.");
2572
+ }
2573
+ const magic = encryptedData.subarray(0, MAGIC_HEADER.length);
2574
+ const isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2575
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2576
+ if (!isStreamFormat && !isBufferFormat) {
2577
+ throw new Error("Invalid magic header: file was not encrypted by DriveKit or is corrupted.");
2578
+ }
2579
+ const salt = encryptedData.subarray(6, 6 + SALT_LENGTH);
2580
+ const iv = encryptedData.subarray(6 + SALT_LENGTH, 6 + SALT_LENGTH + IV_LENGTH);
2581
+ const key = this.config.key || deriveKey(this.config.password, salt);
2582
+ let tag;
2583
+ let ciphertext;
2584
+ if (isStreamFormat) {
2585
+ tag = encryptedData.subarray(encryptedData.length - TAG_LENGTH);
2586
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, encryptedData.length - TAG_LENGTH);
2587
+ } else {
2588
+ tag = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH, 6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2589
+ ciphertext = encryptedData.subarray(6 + SALT_LENGTH + IV_LENGTH + TAG_LENGTH);
2590
+ }
2591
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
2592
+ decipher.setAuthTag(tag);
2593
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2594
+ }
2595
+ /**
2596
+ * Creates an encryption Transform stream that prepends stream header and appends GCM auth tag
2597
+ */
2598
+ createEncryptStream() {
2599
+ const salt = import_node_crypto2.default.randomBytes(SALT_LENGTH);
2600
+ const iv = import_node_crypto2.default.randomBytes(IV_LENGTH);
2601
+ const key = this.config.key || deriveKey(this.config.password, salt);
2602
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
2603
+ let headerPushed = false;
2604
+ return new import_node_stream3.Transform({
2605
+ transform(chunk, _encoding, callback) {
2606
+ if (!headerPushed) {
2607
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2608
+ headerPushed = true;
2609
+ }
2610
+ const encrypted = cipher.update(chunk);
2611
+ if (encrypted.length > 0) {
2612
+ this.push(encrypted);
2613
+ }
2614
+ callback();
2615
+ },
2616
+ flush(callback) {
2617
+ if (!headerPushed) {
2618
+ this.push(Buffer.concat([MAGIC_STREAM_HEADER, salt, iv]));
2619
+ headerPushed = true;
2620
+ }
2621
+ const finalChunk = cipher.final();
2622
+ const tag = cipher.getAuthTag();
2623
+ this.push(Buffer.concat([finalChunk, tag]));
2624
+ callback();
2625
+ }
2626
+ });
2627
+ }
2628
+ /**
2629
+ * Creates a decryption Transform stream that verifies magic header and validates GCM authentication tag
2630
+ */
2631
+ createDecryptStream() {
2632
+ const HEADER_BASE_LEN = MAGIC_HEADER.length + SALT_LENGTH + IV_LENGTH;
2633
+ let headerBuffer = Buffer.alloc(0);
2634
+ let decipher = null;
2635
+ let isStreamFormat = false;
2636
+ let pendingTail = Buffer.alloc(0);
2637
+ const self = this;
2638
+ return new import_node_stream3.Transform({
2639
+ transform(chunk, _encoding, callback) {
2640
+ try {
2641
+ let data = chunk;
2642
+ if (!decipher) {
2643
+ headerBuffer = Buffer.concat([headerBuffer, data]);
2644
+ if (headerBuffer.length < HEADER_BASE_LEN) {
2645
+ return callback();
2646
+ }
2647
+ const magic = headerBuffer.subarray(0, MAGIC_HEADER.length);
2648
+ isStreamFormat = magic.equals(MAGIC_STREAM_HEADER);
2649
+ const isBufferFormat = magic.equals(MAGIC_HEADER);
2650
+ if (!isStreamFormat && !isBufferFormat) {
2651
+ return callback(new Error("Invalid magic header: stream was not encrypted by DriveKit or is corrupted."));
2652
+ }
2653
+ const salt = headerBuffer.subarray(MAGIC_HEADER.length, MAGIC_HEADER.length + SALT_LENGTH);
2654
+ const iv = headerBuffer.subarray(MAGIC_HEADER.length + SALT_LENGTH, HEADER_BASE_LEN);
2655
+ const key = self.config.key || deriveKey(self.config.password, salt);
2656
+ decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
2657
+ if (isBufferFormat) {
2658
+ if (headerBuffer.length < HEADER_BASE_LEN + TAG_LENGTH) {
2659
+ return callback();
2660
+ }
2661
+ const tag = headerBuffer.subarray(HEADER_BASE_LEN, HEADER_BASE_LEN + TAG_LENGTH);
2662
+ decipher.setAuthTag(tag);
2663
+ data = headerBuffer.subarray(HEADER_BASE_LEN + TAG_LENGTH);
2664
+ headerBuffer = Buffer.alloc(0);
2665
+ } else {
2666
+ data = headerBuffer.subarray(HEADER_BASE_LEN);
2667
+ headerBuffer = Buffer.alloc(0);
2668
+ }
2669
+ }
2670
+ if (data.length > 0) {
2671
+ if (isStreamFormat) {
2672
+ pendingTail = Buffer.concat([pendingTail, data]);
2673
+ if (pendingTail.length > TAG_LENGTH) {
2674
+ const toProcess = pendingTail.subarray(0, pendingTail.length - TAG_LENGTH);
2675
+ pendingTail = pendingTail.subarray(pendingTail.length - TAG_LENGTH);
2676
+ const decryptedChunk = decipher.update(toProcess);
2677
+ if (decryptedChunk.length > 0) {
2678
+ this.push(decryptedChunk);
2679
+ }
2680
+ }
2681
+ } else {
2682
+ const decryptedChunk = decipher.update(data);
2683
+ if (decryptedChunk.length > 0) {
2684
+ this.push(decryptedChunk);
2685
+ }
2686
+ }
2687
+ }
2688
+ callback();
2689
+ } catch (err) {
2690
+ callback(err);
2691
+ }
2692
+ },
2693
+ flush(callback) {
2694
+ try {
2695
+ if (!decipher) {
2696
+ return callback(new Error("Encrypted stream is too short: missing header."));
2697
+ }
2698
+ if (isStreamFormat) {
2699
+ if (pendingTail.length !== TAG_LENGTH) {
2700
+ return callback(new Error("Encrypted stream is truncated: missing authentication tag."));
2701
+ }
2702
+ decipher.setAuthTag(pendingTail);
2703
+ }
2704
+ const finalChunk = decipher.final();
2705
+ if (finalChunk.length > 0) {
2706
+ this.push(finalChunk);
2707
+ }
2708
+ callback();
2709
+ } catch (err) {
2710
+ callback(new Error(`Authentication failed: corrupted data or invalid authentication tag (${err.message})`));
2711
+ }
2712
+ }
2713
+ });
2714
+ }
2715
+ /**
2716
+ * Encrypts a filename into a safe base64url string
2717
+ */
2718
+ encryptFilename(plainName) {
2719
+ const iv = import_node_crypto2.default.randomBytes(12);
2720
+ const salt = import_node_crypto2.default.randomBytes(8);
2721
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2722
+ const cipher = import_node_crypto2.default.createCipheriv("aes-256-gcm", key, iv);
2723
+ const encrypted = Buffer.concat([cipher.update(Buffer.from(plainName, "utf8")), cipher.final()]);
2724
+ const tag = cipher.getAuthTag();
2725
+ const payload = Buffer.concat([salt, iv, tag, encrypted]);
2726
+ return `dk_${payload.toString("base64url")}.enc`;
2727
+ }
2728
+ /**
2729
+ * Decrypts a filename generated by encryptFilename
2730
+ */
2731
+ decryptFilename(encryptedName) {
2732
+ if (!encryptedName.startsWith("dk_") || !encryptedName.endsWith(".enc")) {
2733
+ return encryptedName;
2734
+ }
2735
+ try {
2736
+ const raw = encryptedName.slice(3, -4);
2737
+ const payload = Buffer.from(raw, "base64url");
2738
+ if (payload.length < 8 + 12 + 16) return encryptedName;
2739
+ const salt = payload.subarray(0, 8);
2740
+ const iv = payload.subarray(8, 20);
2741
+ const tag = payload.subarray(20, 36);
2742
+ const ciphertext = payload.subarray(36);
2743
+ const key = this.config.key || deriveKey(this.config.password, Buffer.concat([salt, salt]));
2744
+ const decipher = import_node_crypto2.default.createDecipheriv("aes-256-gcm", key, iv);
2745
+ decipher.setAuthTag(tag);
2746
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
2747
+ return decrypted.toString("utf8");
2748
+ } catch {
2749
+ return encryptedName;
2750
+ }
2751
+ }
2752
+ };
2753
+ }
2754
+ });
2755
+
2756
+ // src/core/revisions.ts
2757
+ var DriveFileRevisions;
2758
+ var init_revisions = __esm({
2759
+ "src/core/revisions.ts"() {
2760
+ "use strict";
2761
+ init_cjs_shims();
2762
+ init_retry();
2763
+ DriveFileRevisions = class {
2764
+ drive;
2765
+ pathOrId;
2766
+ idResolver;
2767
+ constructor(drive2, pathOrId, idResolver) {
2768
+ this.drive = drive2;
2769
+ this.pathOrId = pathOrId;
2770
+ this.idResolver = idResolver;
2771
+ }
2772
+ async getId() {
2773
+ if (this.idResolver && (this.pathOrId.startsWith("/") || this.pathOrId.includes("/"))) {
2774
+ return await this.idResolver(this.pathOrId);
2775
+ }
2776
+ return this.pathOrId;
2777
+ }
2778
+ /**
2779
+ * Lists all historical revisions of the file
2780
+ */
2781
+ async list() {
2782
+ const fileId = await this.getId();
2783
+ const res = await withRetry(async () => {
2784
+ return await this.drive.revisions.list({
2785
+ fileId,
2786
+ fields: "revisions(id, mimeType, modifiedTime, keepForever, size, originalFilename)"
2787
+ });
2788
+ });
2789
+ const revs = res.data.revisions || [];
2790
+ return revs.map((r) => ({
2791
+ id: r.id,
2792
+ mimeType: r.mimeType || void 0,
2793
+ modifiedTime: r.modifiedTime || void 0,
2794
+ keepForever: r.keepForever ?? false,
2795
+ size: r.size ? parseInt(r.size, 10) : void 0,
2796
+ originalFilename: r.originalFilename || void 0
2797
+ }));
2798
+ }
2799
+ /**
2800
+ * Gets metadata for a specific revision
2801
+ */
2802
+ async get(revisionId) {
2803
+ const fileId = await this.getId();
2804
+ const res = await withRetry(async () => {
2805
+ return await this.drive.revisions.get({
2806
+ fileId,
2807
+ revisionId,
2808
+ fields: "id, mimeType, modifiedTime, keepForever, size, originalFilename"
2809
+ });
2810
+ });
2811
+ const r = res.data;
2812
+ return {
2813
+ id: r.id,
2814
+ mimeType: r.mimeType || void 0,
2815
+ modifiedTime: r.modifiedTime || void 0,
2816
+ keepForever: r.keepForever ?? false,
2817
+ size: r.size ? parseInt(r.size, 10) : void 0,
2818
+ originalFilename: r.originalFilename || void 0
2819
+ };
2820
+ }
2821
+ /**
2822
+ * Pins or unpins a revision so Google Drive never automatically purges it after 30 days
2823
+ */
2824
+ async keepForever(revisionId, keep = true) {
2825
+ const fileId = await this.getId();
2826
+ const res = await withRetry(async () => {
2827
+ return await this.drive.revisions.update({
2828
+ fileId,
2829
+ revisionId,
2830
+ requestBody: {
2831
+ keepForever: keep
2832
+ },
2833
+ fields: "id, keepForever, modifiedTime"
2834
+ });
2835
+ });
2836
+ return {
2837
+ id: res.data.id,
2838
+ keepForever: res.data.keepForever ?? keep,
2839
+ modifiedTime: res.data.modifiedTime || void 0
2840
+ };
2841
+ }
2842
+ /**
2843
+ * Deletes a specific historical revision
2844
+ */
2845
+ async delete(revisionId) {
2846
+ const fileId = await this.getId();
2847
+ await withRetry(async () => {
2848
+ return await this.drive.revisions.delete({
2849
+ fileId,
2850
+ revisionId
2851
+ });
2852
+ });
2853
+ }
2854
+ /**
2855
+ * Gets a readable stream of a specific historical revision
2856
+ */
2857
+ async getStream(revisionId) {
2858
+ const fileId = await this.getId();
2859
+ const res = await withRetry(async () => {
2860
+ return await this.drive.revisions.get(
2861
+ { fileId, revisionId, alt: "media" },
2862
+ { responseType: "stream" }
2863
+ );
2864
+ });
2865
+ return res.data;
2866
+ }
2867
+ /**
2868
+ * Restores the file content to a specific previous revision
2869
+ */
2870
+ async restore(revisionId) {
2871
+ const fileId = await this.getId();
2872
+ const stream = await this.getStream(revisionId);
2873
+ const meta = await this.get(revisionId);
2874
+ await withRetry(async () => {
2875
+ return await this.drive.files.update({
2876
+ fileId,
2877
+ media: {
2878
+ mimeType: meta.mimeType || "application/octet-stream",
2879
+ body: stream
2880
+ }
2881
+ });
2882
+ });
2883
+ }
2884
+ };
2885
+ }
2886
+ });
2887
+
2888
+ // src/core/bidirectional-sync.ts
2889
+ var import_node_fs6, import_node_path6, BidirectionalSyncEngine;
2890
+ var init_bidirectional_sync = __esm({
2891
+ "src/core/bidirectional-sync.ts"() {
2892
+ "use strict";
2893
+ init_cjs_shims();
2894
+ import_node_fs6 = __toESM(require("fs"), 1);
2895
+ import_node_path6 = __toESM(require("path"), 1);
2896
+ init_smart_sync();
2897
+ BidirectionalSyncEngine = class {
2898
+ drive;
2899
+ ledger = /* @__PURE__ */ new Map();
2900
+ constructor(drive2) {
2901
+ this.drive = drive2;
2902
+ }
2903
+ /**
2904
+ * Performs a two-way synchronization cycle between local and remote directories
2905
+ */
2906
+ async sync(options) {
2907
+ const startTime = Date.now();
2908
+ const {
2909
+ localDir,
2910
+ remoteDir,
2911
+ conflictStrategy = "rename-conflict",
2912
+ deleteMissing = false,
2913
+ dryRun = false,
2914
+ onProgress
2915
+ } = options;
2916
+ const result = {
2917
+ uploaded: [],
2918
+ downloaded: [],
2919
+ deletedLocal: [],
2920
+ deletedRemote: [],
2921
+ conflicts: [],
2922
+ skipped: [],
2923
+ durationMs: 0
2924
+ };
2925
+ if (!import_node_fs6.default.existsSync(localDir)) {
2926
+ await import_node_fs6.default.promises.mkdir(localDir, { recursive: true });
2927
+ }
2928
+ const remoteFolderId = await this.drive.mkdirp(remoteDir);
2929
+ const localFiles = await this.scanLocalDir(localDir);
2930
+ const remoteFiles = await this.scanRemoteDir(remoteFolderId, "");
2931
+ const allPaths = /* @__PURE__ */ new Set([
2932
+ ...localFiles.keys(),
2933
+ ...remoteFiles.keys(),
2934
+ ...this.ledger.keys()
2935
+ ]);
2936
+ for (const relPath of allPaths) {
2937
+ const resolvedLocal = import_node_path6.default.resolve(localDir, relPath);
2938
+ const resolvedRoot = import_node_path6.default.resolve(localDir);
2939
+ if (!resolvedLocal.startsWith(resolvedRoot + import_node_path6.default.sep) && resolvedLocal !== resolvedRoot) {
2940
+ throw new Error(`Security Violation: Path traversal detected in sync path: "${relPath}"`);
2941
+ }
2942
+ const local = localFiles.get(relPath);
2943
+ const remote = remoteFiles.get(relPath);
2944
+ const prev = this.ledger.get(relPath);
2945
+ if (local && remote) {
2946
+ const localChanged = !prev || local.md5 !== prev.localMd5 || Math.abs(local.mtime - prev.localMtime) > 1e3;
2947
+ const remoteChanged = !prev || remote.md5 !== prev.remoteMd5 || Math.abs(remote.mtime - prev.remoteMtime) > 1e3;
2948
+ if (local.md5 === remote.md5) {
2949
+ result.skipped.push(relPath);
2950
+ onProgress?.({ action: "skip-identical", relPath });
2951
+ this.ledger.set(relPath, {
2952
+ relPath,
2953
+ localMtime: local.mtime,
2954
+ remoteMtime: remote.mtime,
2955
+ localMd5: local.md5,
2956
+ remoteMd5: remote.md5,
2957
+ remoteId: remote.id
2958
+ });
2959
+ continue;
2960
+ }
2961
+ if (localChanged && !remoteChanged) {
2962
+ if (!dryRun) {
2963
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2964
+ const freshRemote = await this.drive.getFile(remote.id);
2965
+ this.updateLedger(relPath, local, freshRemote);
2966
+ }
2967
+ result.uploaded.push(relPath);
2968
+ onProgress?.({ action: "upload", relPath, details: "Local modification propagated" });
2969
+ continue;
2970
+ }
2971
+ if (remoteChanged && !localChanged) {
2972
+ if (!dryRun) {
2973
+ await this.downloadFile(remote.id, local.fullPath);
2974
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
2975
+ this.ledger.set(relPath, {
2976
+ relPath,
2977
+ localMtime: freshStat.mtimeMs,
2978
+ remoteMtime: remote.mtime,
2979
+ localMd5: remote.md5,
2980
+ remoteMd5: remote.md5,
2981
+ remoteId: remote.id
2982
+ });
2983
+ }
2984
+ result.downloaded.push(relPath);
2985
+ onProgress?.({ action: "download", relPath, details: "Remote modification propagated" });
2986
+ continue;
2987
+ }
2988
+ result.conflicts.push(relPath);
2989
+ onProgress?.({ action: "conflict-resolved", relPath, details: `Strategy: ${conflictStrategy}` });
2990
+ if (!dryRun) {
2991
+ if (conflictStrategy === "prefer-local") {
2992
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
2993
+ const freshRemote = await this.drive.getFile(remote.id);
2994
+ this.updateLedger(relPath, local, freshRemote);
2995
+ result.uploaded.push(relPath);
2996
+ } else if (conflictStrategy === "prefer-cloud") {
2997
+ await this.downloadFile(remote.id, local.fullPath);
2998
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
2999
+ this.ledger.set(relPath, {
3000
+ relPath,
3001
+ localMtime: freshStat.mtimeMs,
3002
+ remoteMtime: remote.mtime,
3003
+ localMd5: remote.md5,
3004
+ remoteMd5: remote.md5,
3005
+ remoteId: remote.id
3006
+ });
3007
+ result.downloaded.push(relPath);
3008
+ } else if (conflictStrategy === "keep-newer") {
3009
+ if (local.mtime >= remote.mtime) {
3010
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3011
+ const freshRemote = await this.drive.getFile(remote.id);
3012
+ this.updateLedger(relPath, local, freshRemote);
3013
+ result.uploaded.push(relPath);
3014
+ } else {
3015
+ await this.downloadFile(remote.id, local.fullPath);
3016
+ const freshStat = await import_node_fs6.default.promises.stat(local.fullPath);
3017
+ this.ledger.set(relPath, {
3018
+ relPath,
3019
+ localMtime: freshStat.mtimeMs,
3020
+ remoteMtime: remote.mtime,
3021
+ localMd5: remote.md5,
3022
+ remoteMd5: remote.md5,
3023
+ remoteId: remote.id
3024
+ });
3025
+ result.downloaded.push(relPath);
3026
+ }
3027
+ } else {
3028
+ const ext = import_node_path6.default.extname(relPath);
3029
+ const base = relPath.slice(0, relPath.length - ext.length);
3030
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3031
+ const conflictRelPath = `${base} (Conflict ${timestamp})${ext}`;
3032
+ const conflictFullPath = import_node_path6.default.join(localDir, conflictRelPath);
3033
+ await this.downloadFile(remote.id, conflictFullPath);
3034
+ await this.uploadFile(local.fullPath, remoteDir, relPath);
3035
+ const freshRemote = await this.drive.getFile(remote.id);
3036
+ this.updateLedger(relPath, local, freshRemote);
3037
+ }
3038
+ }
3039
+ continue;
3040
+ }
3041
+ if (local && !remote) {
3042
+ if (prev && deleteMissing) {
3043
+ if (!dryRun) {
3044
+ await import_node_fs6.default.promises.unlink(local.fullPath);
3045
+ this.ledger.delete(relPath);
3046
+ }
3047
+ result.deletedLocal.push(relPath);
3048
+ onProgress?.({ action: "delete-local", relPath, details: "Deleted remotely" });
3049
+ } else {
3050
+ if (!dryRun) {
3051
+ const uploadedFile = await this.uploadFile(local.fullPath, remoteDir, relPath);
3052
+ this.updateLedger(relPath, local, uploadedFile);
3053
+ }
3054
+ result.uploaded.push(relPath);
3055
+ onProgress?.({ action: "upload", relPath, details: "New local file" });
3056
+ }
3057
+ continue;
3058
+ }
3059
+ if (!local && remote) {
3060
+ if (prev && deleteMissing) {
3061
+ if (!dryRun) {
3062
+ await this.drive.delete(remote.id, true);
3063
+ this.ledger.delete(relPath);
3064
+ }
3065
+ result.deletedRemote.push(relPath);
3066
+ onProgress?.({ action: "delete-remote", relPath, details: "Deleted locally" });
3067
+ } else {
3068
+ if (!dryRun) {
3069
+ const localDest = import_node_path6.default.join(localDir, relPath);
3070
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(localDest), { recursive: true });
3071
+ await this.downloadFile(remote.id, localDest);
3072
+ const stat = await import_node_fs6.default.promises.stat(localDest);
3073
+ this.ledger.set(relPath, {
3074
+ relPath,
3075
+ localMtime: stat.mtimeMs,
3076
+ remoteMtime: remote.mtime,
3077
+ localMd5: remote.md5,
3078
+ remoteMd5: remote.md5,
3079
+ remoteId: remote.id
3080
+ });
3081
+ }
3082
+ result.downloaded.push(relPath);
3083
+ onProgress?.({ action: "download", relPath, details: "New remote file" });
3084
+ }
3085
+ continue;
3086
+ }
3087
+ if (prev && !local && !remote) {
3088
+ this.ledger.delete(relPath);
3089
+ }
3090
+ }
3091
+ result.durationMs = Date.now() - startTime;
3092
+ return result;
3093
+ }
3094
+ async scanLocalDir(dir, baseDir = dir) {
3095
+ const map = /* @__PURE__ */ new Map();
3096
+ if (!import_node_fs6.default.existsSync(dir)) return map;
3097
+ const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
3098
+ for (const entry of entries) {
3099
+ const fullPath = import_node_path6.default.join(dir, entry.name);
3100
+ if (entry.isDirectory()) {
3101
+ const sub = await this.scanLocalDir(fullPath, baseDir);
3102
+ for (const [k, v] of sub) map.set(k, v);
3103
+ } else if (entry.isFile()) {
3104
+ const rel = import_node_path6.default.relative(baseDir, fullPath).replace(/\\/g, "/");
3105
+ const stat = await import_node_fs6.default.promises.stat(fullPath);
3106
+ const md5 = await calculateFileMd5(fullPath);
3107
+ map.set(rel, { fullPath, mtime: stat.mtimeMs, md5 });
3108
+ }
3109
+ }
3110
+ return map;
3111
+ }
3112
+ async scanRemoteDir(folderId, relPrefix) {
3113
+ const map = /* @__PURE__ */ new Map();
3114
+ const items = await this.drive.query().inFolder(folderId).notTrashed().list();
3115
+ for (const item of items) {
3116
+ if (!item.id || !item.name) continue;
3117
+ const cleanName = import_node_path6.default.basename(item.name.replace(/\\/g, "/")).replace(/\0/g, "");
3118
+ if (!cleanName || cleanName === "." || cleanName === "..") continue;
3119
+ const relPath = relPrefix ? `${relPrefix}/${cleanName}` : cleanName;
3120
+ if (item.mimeType === "application/vnd.google-apps.folder") {
3121
+ const sub = await this.scanRemoteDir(item.id, relPath);
3122
+ for (const [k, v] of sub) map.set(k, v);
3123
+ } else {
3124
+ const mtime = item.modifiedTime ? new Date(item.modifiedTime).getTime() : 0;
3125
+ map.set(relPath, {
3126
+ id: item.id,
3127
+ name: item.name,
3128
+ mtime,
3129
+ md5: item.md5Checksum || ""
3130
+ });
3131
+ }
3132
+ }
3133
+ return map;
3134
+ }
3135
+ async uploadFile(localPath, remoteDir, relPath) {
3136
+ const remoteSubDir = import_node_path6.default.dirname(relPath);
3137
+ const targetFolder = remoteSubDir === "." ? remoteDir : `${remoteDir}/${remoteSubDir}`;
3138
+ return await this.drive.upload({
3139
+ source: localPath,
3140
+ name: import_node_path6.default.basename(relPath),
3141
+ parent: targetFolder,
3142
+ overwrite: true
3143
+ });
3144
+ }
3145
+ async downloadFile(fileId, destPath) {
3146
+ await import_node_fs6.default.promises.mkdir(import_node_path6.default.dirname(destPath), { recursive: true });
3147
+ await this.drive.download(fileId, { destination: destPath });
3148
+ }
3149
+ updateLedger(relPath, local, remote) {
3150
+ this.ledger.set(relPath, {
3151
+ relPath,
3152
+ localMtime: local.mtime,
3153
+ remoteMtime: remote.modifiedTime ? new Date(remote.modifiedTime).getTime() : Date.now(),
3154
+ localMd5: local.md5,
3155
+ remoteMd5: remote.md5Checksum || local.md5,
3156
+ remoteId: remote.id
3157
+ });
3158
+ }
3159
+ };
3160
+ }
3161
+ });
3162
+
3163
+ // src/server/s3-gateway.ts
3164
+ var import_node_http3, import_node_path7, import_node_url, S3GatewayServer;
3165
+ var init_s3_gateway = __esm({
3166
+ "src/server/s3-gateway.ts"() {
3167
+ "use strict";
3168
+ init_cjs_shims();
3169
+ import_node_http3 = __toESM(require("http"), 1);
3170
+ import_node_path7 = __toESM(require("path"), 1);
3171
+ import_node_url = require("url");
3172
+ S3GatewayServer = class {
3173
+ drive;
3174
+ options;
3175
+ server = null;
3176
+ constructor(drive2, options = {}) {
3177
+ this.drive = drive2;
3178
+ this.options = {
3179
+ port: options.port || 9e3,
3180
+ host: options.host || "127.0.0.1",
3181
+ bucketRoot: options.bucketRoot || "/",
3182
+ ...options
3183
+ };
3184
+ }
3185
+ /**
3186
+ * Starts the S3 gateway HTTP server
3187
+ */
3188
+ async start() {
3189
+ return new Promise((resolve, reject) => {
3190
+ this.server = import_node_http3.default.createServer(async (req, res) => {
3191
+ try {
3192
+ await this.handleRequest(req, res);
3193
+ } catch (err) {
3194
+ this.sendXmlError(res, 500, "InternalError", err.message || "Internal S3 Gateway Error");
3195
+ }
3196
+ });
3197
+ this.server.on("error", reject);
3198
+ this.server.listen(this.options.port, this.options.host, () => {
3199
+ resolve({ port: this.options.port, host: this.options.host });
3200
+ });
3201
+ });
3202
+ }
3203
+ /**
3204
+ * Stops the S3 gateway HTTP server
3205
+ */
3206
+ async stop() {
3207
+ return new Promise((resolve) => {
3208
+ if (this.server) {
3209
+ this.server.close(() => resolve());
3210
+ } else {
3211
+ resolve();
3212
+ }
3213
+ });
3214
+ }
3215
+ async handleRequest(req, res) {
3216
+ const parsed = (0, import_node_url.parse)(req.url || "/", true);
3217
+ const rawPathname = decodeURIComponent(parsed.pathname || "/");
3218
+ const pathname = import_node_path7.default.posix.normalize(rawPathname);
3219
+ if (rawPathname.includes("..") || pathname.includes("..") || pathname === ".") {
3220
+ this.sendXmlError(res, 400, "InvalidURI", "Path traversal characters are not permitted");
3221
+ return;
3222
+ }
3223
+ const method = req.method?.toUpperCase() || "GET";
3224
+ if (this.options.accessKeyId) {
3225
+ const authHeader = req.headers["authorization"];
3226
+ if (!authHeader || !authHeader.includes(this.options.accessKeyId)) {
3227
+ res.setHeader("WWW-Authenticate", "AWS4-HMAC-SHA256");
3228
+ this.sendXmlError(res, 403, "AccessDenied", "Invalid or missing AWS credentials");
3229
+ return;
3230
+ }
3231
+ }
3232
+ const segments = pathname.split("/").filter(Boolean);
3233
+ if (segments.some((s) => s === ".." || s === ".")) {
3234
+ this.sendXmlError(res, 400, "InvalidURI", "Invalid path segment");
3235
+ return;
3236
+ }
3237
+ if (segments.length === 0) {
3238
+ if (method === "GET") {
3239
+ await this.handleListBuckets(res);
3240
+ return;
3241
+ }
3242
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on root");
3243
+ return;
3244
+ }
3245
+ const bucket = segments[0];
3246
+ const key = segments.slice(1).join("/");
3247
+ if (!key) {
3248
+ if (method === "GET") {
3249
+ const prefix = parsed.query.prefix || "";
3250
+ await this.handleListObjects(bucket, prefix, res);
3251
+ return;
3252
+ }
3253
+ if (method === "PUT") {
3254
+ await this.drive.mkdirp(`/${bucket}`);
3255
+ res.statusCode = 200;
3256
+ res.end();
3257
+ return;
3258
+ }
3259
+ this.sendXmlError(res, 405, "MethodNotAllowed", "Method not allowed on bucket");
3260
+ return;
3261
+ }
3262
+ const remotePath = `/${bucket}/${key}`;
3263
+ if (method === "HEAD") {
3264
+ try {
3265
+ const file = await this.drive.getFile(remotePath);
3266
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3267
+ res.setHeader("Content-Length", file.size || "0");
3268
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3269
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3270
+ res.statusCode = 200;
3271
+ res.end();
3272
+ } catch {
3273
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3274
+ }
3275
+ return;
3276
+ }
3277
+ if (method === "GET") {
3278
+ try {
3279
+ const file = await this.drive.getFile(remotePath);
3280
+ const range = req.headers["range"];
3281
+ let options = void 0;
3282
+ if (range && range.startsWith("bytes=")) {
3283
+ const parts = range.replace("bytes=", "").split("-");
3284
+ options = {
3285
+ start: parts[0] ? parseInt(parts[0], 10) : 0,
3286
+ end: parts[1] ? parseInt(parts[1], 10) : void 0
3287
+ };
3288
+ res.statusCode = 206;
3289
+ const end = options.end !== void 0 ? options.end : parseInt(file.size || "0", 10) - 1;
3290
+ res.setHeader("Content-Range", `bytes ${options.start}-${end}/${file.size}`);
3291
+ } else {
3292
+ res.statusCode = 200;
3293
+ }
3294
+ res.setHeader("Content-Type", file.mimeType || "application/octet-stream");
3295
+ res.setHeader("Content-Length", file.size || "0");
3296
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3297
+ if (file.modifiedTime) res.setHeader("Last-Modified", new Date(file.modifiedTime).toUTCString());
3298
+ const stream = await this.drive.createReadStream(remotePath, options);
3299
+ stream.pipe(res);
3300
+ } catch {
3301
+ this.sendXmlError(res, 404, "NoSuchKey", "The specified key does not exist");
3302
+ }
3303
+ return;
3304
+ }
3305
+ if (method === "PUT") {
3306
+ const upload = await this.drive.createWriteStream(remotePath);
3307
+ req.pipe(upload);
3308
+ try {
3309
+ const file = await upload.done;
3310
+ res.setHeader("ETag", `"${file.md5Checksum || file.id}"`);
3311
+ res.statusCode = 200;
3312
+ res.end();
3313
+ } catch (err) {
3314
+ this.sendXmlError(res, 500, "InternalError", err.message);
3315
+ }
3316
+ return;
3317
+ }
3318
+ if (method === "DELETE") {
3319
+ try {
3320
+ const file = await this.drive.resolvePath(remotePath);
3321
+ await this.drive.delete(file.id, true);
3322
+ res.statusCode = 204;
3323
+ res.end();
3324
+ } catch {
3325
+ res.statusCode = 204;
3326
+ res.end();
3327
+ }
3328
+ return;
3329
+ }
3330
+ this.sendXmlError(res, 405, "MethodNotAllowed", `HTTP method ${method} not allowed`);
3331
+ }
3332
+ async handleListBuckets(res) {
3333
+ const items = await this.drive.ls("/");
3334
+ const folders = items.filter((i) => i.mimeType === "application/vnd.google-apps.folder");
3335
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListAllMyBucketsResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3336
+ xml += " <Buckets>\n";
3337
+ for (const f of folders) {
3338
+ xml += " <Bucket>\n";
3339
+ xml += ` <Name>${this.escapeXml(f.name || "bucket")}</Name>
3340
+ `;
3341
+ xml += ` <CreationDate>${f.createdTime || (/* @__PURE__ */ new Date()).toISOString()}</CreationDate>
3342
+ `;
3343
+ xml += " </Bucket>\n";
3344
+ }
3345
+ xml += " </Buckets>\n</ListAllMyBucketsResult>";
3346
+ res.setHeader("Content-Type", "application/xml");
3347
+ res.statusCode = 200;
3348
+ res.end(xml);
3349
+ }
3350
+ async handleListObjects(bucket, prefix, res) {
3351
+ const targetPath = `/${bucket}${prefix ? `/${prefix}` : ""}`;
3352
+ let items = [];
3353
+ try {
3354
+ items = await this.drive.ls(targetPath);
3355
+ } catch {
3356
+ items = [];
3357
+ }
3358
+ let xml = '<?xml version="1.0" encoding="UTF-8"?>\n<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">\n';
3359
+ xml += ` <Name>${this.escapeXml(bucket)}</Name>
3360
+ `;
3361
+ xml += ` <Prefix>${this.escapeXml(prefix)}</Prefix>
3362
+ `;
3363
+ xml += " <IsTruncated>false</IsTruncated>\n";
3364
+ for (const item of items) {
3365
+ if (item.mimeType === "application/vnd.google-apps.folder") continue;
3366
+ const key = prefix ? `${prefix}/${item.name}` : item.name;
3367
+ xml += " <Contents>\n";
3368
+ xml += ` <Key>${this.escapeXml(key)}</Key>
3369
+ `;
3370
+ xml += ` <LastModified>${item.modifiedTime || (/* @__PURE__ */ new Date()).toISOString()}</LastModified>
3371
+ `;
3372
+ xml += ` <ETag>"${item.md5Checksum || item.id}"</ETag>
3373
+ `;
3374
+ xml += ` <Size>${item.size || 0}</Size>
3375
+ `;
3376
+ xml += " <StorageClass>STANDARD</StorageClass>\n";
3377
+ xml += " </Contents>\n";
3378
+ }
3379
+ xml += "</ListBucketResult>";
3380
+ res.setHeader("Content-Type", "application/xml");
3381
+ res.statusCode = 200;
3382
+ res.end(xml);
3383
+ }
3384
+ sendXmlError(res, status, code, message) {
3385
+ const xml = `<?xml version="1.0" encoding="UTF-8"?>
3386
+ <Error>
3387
+ <Code>${this.escapeXml(code)}</Code>
3388
+ <Message>${this.escapeXml(message)}</Message>
3389
+ </Error>`;
3390
+ res.setHeader("Content-Type", "application/xml");
3391
+ res.statusCode = status;
3392
+ res.end(xml);
3393
+ }
3394
+ escapeXml(unsafe) {
3395
+ return unsafe.replace(/[<>&'"]/g, (c) => {
3396
+ switch (c) {
3397
+ case "<":
3398
+ return "&lt;";
3399
+ case ">":
3400
+ return "&gt;";
3401
+ case "&":
3402
+ return "&amp;";
3403
+ case "'":
3404
+ return "&apos;";
3405
+ case '"':
3406
+ return "&quot;";
3407
+ default:
3408
+ return c;
3409
+ }
3410
+ });
3411
+ }
3412
+ };
3413
+ }
3414
+ });
3415
+
3416
+ // src/core/security-auditor.ts
3417
+ var SecurityAuditor;
3418
+ var init_security_auditor = __esm({
3419
+ "src/core/security-auditor.ts"() {
3420
+ "use strict";
3421
+ init_cjs_shims();
3422
+ init_retry();
3423
+ SecurityAuditor = class {
3424
+ drive;
3425
+ constructor(drive2) {
3426
+ this.drive = drive2;
3427
+ }
3428
+ /**
3429
+ * Scans Google Drive files and audits their permission grants
3430
+ */
3431
+ async audit(options = {}) {
3432
+ const limit = options.scanLimit || 500;
3433
+ const allowedDomains = new Set((options.allowedDomains || []).map((d) => d.toLowerCase()));
3434
+ const issues = [];
3435
+ let publicCount = 0;
3436
+ let domainCount = 0;
3437
+ let externalCount = 0;
3438
+ let scannedTotal = 0;
3439
+ let pageToken = void 0;
3440
+ do {
3441
+ const res = await withRetry(async () => {
3442
+ return await this.drive.files.list({
3443
+ q: "trashed = false",
3444
+ fields: "nextPageToken, files(id, name, mimeType, webViewLink, shared, permissions(id, type, role, emailAddress, domain))",
3445
+ pageSize: Math.min(100, limit - scannedTotal),
3446
+ supportsAllDrives: true,
3447
+ includeItemsFromAllDrives: true,
3448
+ pageToken
3449
+ });
3450
+ });
3451
+ const files = res.data.files || [];
3452
+ for (const file of files) {
3453
+ if (!file.id || !file.name) continue;
3454
+ scannedTotal++;
3455
+ const perms = file.permissions || [];
3456
+ for (const p of perms) {
3457
+ if (p.type === "anyone") {
3458
+ publicCount++;
3459
+ const isCritical = ["writer", "owner", "organizer", "fileOrganizer"].includes(p.role || "");
3460
+ issues.push({
3461
+ fileId: file.id,
3462
+ fileName: file.name,
3463
+ risk: isCritical ? "CRITICAL" : "HIGH",
3464
+ reason: `Publicly accessible to anyone (${p.role} access)`,
3465
+ permissionId: p.id,
3466
+ type: p.type,
3467
+ role: p.role || "reader",
3468
+ webViewLink: file.webViewLink || void 0
3469
+ });
3470
+ continue;
3471
+ }
3472
+ if (p.type === "domain") {
3473
+ domainCount++;
3474
+ issues.push({
3475
+ fileId: file.id,
3476
+ fileName: file.name,
3477
+ risk: "MEDIUM",
3478
+ reason: `Shared with entire organization domain (${p.domain})`,
3479
+ permissionId: p.id,
3480
+ type: p.type,
3481
+ role: p.role || "reader",
3482
+ domain: p.domain || void 0,
3483
+ webViewLink: file.webViewLink || void 0
3484
+ });
3485
+ continue;
3486
+ }
3487
+ if (p.type === "user" && p.emailAddress && allowedDomains.size > 0) {
3488
+ const userDomain = p.emailAddress.split("@")[1]?.toLowerCase();
3489
+ if (userDomain && !allowedDomains.has(userDomain)) {
3490
+ externalCount++;
3491
+ issues.push({
3492
+ fileId: file.id,
3493
+ fileName: file.name,
3494
+ risk: "HIGH",
3495
+ reason: `Shared with external user outside allowed domains: ${p.emailAddress}`,
3496
+ permissionId: p.id,
3497
+ type: p.type,
3498
+ role: p.role || "reader",
3499
+ emailAddress: p.emailAddress,
3500
+ webViewLink: file.webViewLink || void 0
3501
+ });
3502
+ }
3503
+ }
3504
+ }
3505
+ }
3506
+ pageToken = res.data.nextPageToken || void 0;
3507
+ } while (pageToken && scannedTotal < limit);
3508
+ return {
3509
+ totalScanned: scannedTotal,
3510
+ publicFilesCount: publicCount,
3511
+ domainSharedCount: domainCount,
3512
+ externalSharesCount: externalCount,
3513
+ issues,
3514
+ scannedAt: (/* @__PURE__ */ new Date()).toISOString()
3515
+ };
2472
3516
  }
2473
- pruneMissing(activeIds) {
2474
- const idSet = new Set(activeIds);
2475
- let pruned = 0;
2476
- for (const id of Array.from(this.files.keys())) {
2477
- if (!idSet.has(id)) {
2478
- this.files.delete(id);
2479
- pruned++;
3517
+ /**
3518
+ * Revokes public 'anyone' permissions on specified files
3519
+ */
3520
+ async revokePublicAccess(fileIds) {
3521
+ const revoked = [];
3522
+ const errors = [];
3523
+ for (const fileId of fileIds) {
3524
+ try {
3525
+ const fileRes = await withRetry(async () => {
3526
+ return await this.drive.files.get({
3527
+ fileId,
3528
+ fields: "id, permissions(id, type)",
3529
+ supportsAllDrives: true
3530
+ });
3531
+ });
3532
+ const publicPerms = (fileRes.data.permissions || []).filter((p) => p.type === "anyone");
3533
+ for (const p of publicPerms) {
3534
+ if (p.id) {
3535
+ await withRetry(async () => {
3536
+ return await this.drive.permissions.delete({
3537
+ fileId,
3538
+ permissionId: p.id,
3539
+ supportsAllDrives: true
3540
+ });
3541
+ });
3542
+ }
3543
+ }
3544
+ revoked.push(fileId);
3545
+ } catch (err) {
3546
+ errors.push({ fileId, error: err.message });
2480
3547
  }
2481
3548
  }
2482
- return pruned;
2483
- }
2484
- clear() {
2485
- this.files.clear();
2486
- this.meta.clear();
3549
+ return { revoked, errors };
2487
3550
  }
2488
- getMeta(key) {
2489
- return this.meta.get(key) || null;
3551
+ };
3552
+ }
3553
+ });
3554
+
3555
+ // src/core/semantic-search.ts
3556
+ function levenshtein(a, b) {
3557
+ const an = a.length;
3558
+ const bn = b.length;
3559
+ if (an === 0) return bn;
3560
+ if (bn === 0) return an;
3561
+ const matrix = Array.from({ length: bn + 1 }, (_, i) => [i]);
3562
+ for (let j = 0; j <= an; j++) matrix[0][j] = j;
3563
+ for (let i = 1; i <= bn; i++) {
3564
+ for (let j = 1; j <= an; j++) {
3565
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
3566
+ matrix[i][j] = matrix[i - 1][j - 1];
3567
+ } else {
3568
+ matrix[i][j] = Math.min(
3569
+ matrix[i - 1][j - 1] + 1,
3570
+ // substitution
3571
+ matrix[i][j - 1] + 1,
3572
+ // insertion
3573
+ matrix[i - 1][j] + 1
3574
+ // deletion
3575
+ );
2490
3576
  }
2491
- setMeta(key, value) {
2492
- this.meta.set(key, value);
3577
+ }
3578
+ }
3579
+ return matrix[bn][an];
3580
+ }
3581
+ function cosineSimilarity(vecA, vecB) {
3582
+ if (vecA.length !== vecB.length || vecA.length === 0) return 0;
3583
+ let dot = 0;
3584
+ let normA = 0;
3585
+ let normB = 0;
3586
+ for (let i = 0; i < vecA.length; i++) {
3587
+ dot += vecA[i] * vecB[i];
3588
+ normA += vecA[i] * vecA[i];
3589
+ normB += vecB[i] * vecB[i];
3590
+ }
3591
+ if (normA === 0 || normB === 0) return 0;
3592
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
3593
+ }
3594
+ var SmartSearchEngine;
3595
+ var init_semantic_search = __esm({
3596
+ "src/core/semantic-search.ts"() {
3597
+ "use strict";
3598
+ init_cjs_shims();
3599
+ SmartSearchEngine = class {
3600
+ drive;
3601
+ constructor(drive2) {
3602
+ this.drive = drive2;
2493
3603
  }
2494
- getStats() {
2495
- let fileCount = 0;
2496
- let folderCount = 0;
2497
- let totalSizeBytes = 0;
2498
- for (const f of this.files.values()) {
2499
- if (f.trashed) continue;
2500
- if (f.mimeType === "application/vnd.google-apps.folder") folderCount++;
2501
- else {
2502
- fileCount++;
2503
- totalSizeBytes += f.size || 0;
3604
+ /**
3605
+ * Searches Drive using tokenized fuzzy matching and optional semantic embeddings
3606
+ */
3607
+ async search(query, options = {}) {
3608
+ const limit = options.limit || 20;
3609
+ const minScore = options.minScore ?? 0.3;
3610
+ const queryTokens = query.toLowerCase().split(/\s+/).filter(Boolean);
3611
+ if (queryTokens.length === 0) return [];
3612
+ let candidates = [];
3613
+ if (options.parent) {
3614
+ candidates = await this.drive.ls(options.parent);
3615
+ } else {
3616
+ candidates = await this.drive.query().notTrashed().pageSize(100).list();
3617
+ }
3618
+ let queryVector = null;
3619
+ if (options.embedder) {
3620
+ try {
3621
+ queryVector = await options.embedder(query);
3622
+ } catch {
3623
+ queryVector = null;
2504
3624
  }
2505
3625
  }
2506
- return {
2507
- fileCount,
2508
- folderCount,
2509
- totalSizeBytes,
2510
- lastSyncTime: this.meta.get("last_sync_timestamp") || null,
2511
- databasePath: ":memory:"
2512
- };
2513
- }
2514
- close() {
2515
- this.clear();
3626
+ const scored = [];
3627
+ for (const file of candidates) {
3628
+ const fileName = (file.name || "").toLowerCase();
3629
+ const desc = (file.description || "").toLowerCase();
3630
+ const matchedOn = [];
3631
+ let nameScore = 0;
3632
+ let descScore = 0;
3633
+ let semanticScore = 0;
3634
+ if (fileName.includes(query.toLowerCase())) {
3635
+ nameScore = 0.95;
3636
+ matchedOn.push("name");
3637
+ } else {
3638
+ let tokensMatched = 0;
3639
+ for (const token of queryTokens) {
3640
+ if (fileName.includes(token)) {
3641
+ tokensMatched += 1;
3642
+ continue;
3643
+ }
3644
+ const words = fileName.split(/[\s._-]+/);
3645
+ for (const word of words) {
3646
+ const dist = levenshtein(token, word);
3647
+ const maxLen = Math.max(token.length, word.length);
3648
+ if (maxLen > 3 && dist <= 2) {
3649
+ tokensMatched += 1 - dist / maxLen;
3650
+ break;
3651
+ }
3652
+ }
3653
+ }
3654
+ nameScore = tokensMatched / queryTokens.length;
3655
+ if (nameScore > 0.4) matchedOn.push("name");
3656
+ }
3657
+ if (desc) {
3658
+ if (desc.includes(query.toLowerCase())) {
3659
+ descScore = 0.8;
3660
+ matchedOn.push("description");
3661
+ }
3662
+ }
3663
+ if (queryVector && options.embedder) {
3664
+ try {
3665
+ const fileVector = await options.embedder(`${file.name} ${file.description || ""}`);
3666
+ semanticScore = cosineSimilarity(queryVector, fileVector);
3667
+ if (semanticScore > 0.6) matchedOn.push("semantic");
3668
+ } catch {
3669
+ }
3670
+ }
3671
+ const totalScore = Math.min(1, nameScore * 0.7 + descScore * 0.15 + semanticScore * 0.15);
3672
+ if (totalScore >= minScore) {
3673
+ scored.push({
3674
+ file,
3675
+ score: Math.round(totalScore * 100) / 100,
3676
+ matchedOn: matchedOn.length > 0 ? matchedOn : ["name"]
3677
+ });
3678
+ }
3679
+ }
3680
+ scored.sort((a, b) => b.score - a.score);
3681
+ return scored.slice(0, limit);
2516
3682
  }
2517
3683
  };
2518
3684
  }
2519
3685
  });
2520
3686
 
3687
+ // src/utils/compression.ts
3688
+ async function compressBuffer(buffer, algorithm = "gzip") {
3689
+ switch (algorithm) {
3690
+ case "brotli":
3691
+ return await brotliCompressAsync(buffer);
3692
+ case "deflate":
3693
+ return await (0, import_node_util.promisify)(import_node_zlib.default.deflate)(buffer);
3694
+ case "gzip":
3695
+ default:
3696
+ return await gzipAsync(buffer);
3697
+ }
3698
+ }
3699
+ async function decompressBuffer(buffer, algorithm = "gzip") {
3700
+ switch (algorithm) {
3701
+ case "brotli":
3702
+ return await brotliDecompressAsync(buffer);
3703
+ case "deflate":
3704
+ return await (0, import_node_util.promisify)(import_node_zlib.default.inflate)(buffer);
3705
+ case "gzip":
3706
+ default:
3707
+ return await gunzipAsync(buffer);
3708
+ }
3709
+ }
3710
+ var import_node_zlib, import_node_util, gzipAsync, gunzipAsync, brotliCompressAsync, brotliDecompressAsync;
3711
+ var init_compression = __esm({
3712
+ "src/utils/compression.ts"() {
3713
+ "use strict";
3714
+ init_cjs_shims();
3715
+ import_node_zlib = __toESM(require("zlib"), 1);
3716
+ import_node_util = require("util");
3717
+ gzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gzip);
3718
+ gunzipAsync = (0, import_node_util.promisify)(import_node_zlib.default.gunzip);
3719
+ brotliCompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliCompress);
3720
+ brotliDecompressAsync = (0, import_node_util.promisify)(import_node_zlib.default.brotliDecompress);
3721
+ }
3722
+ });
3723
+
2521
3724
  // src/server/webdav.ts
2522
3725
  var webdav_exports = {};
2523
3726
  __export(webdav_exports, {
@@ -2531,7 +3734,7 @@ async function startWebDAVServer(drive2, options = {}) {
2531
3734
  const port = options.port || 8080;
2532
3735
  const host = options.host || "127.0.0.1";
2533
3736
  await drive2.init();
2534
- const server = import_node_http3.default.createServer(async (req, res) => {
3737
+ const server = import_node_http4.default.createServer(async (req, res) => {
2535
3738
  try {
2536
3739
  if (options.auth?.username && options.auth?.password) {
2537
3740
  const authHeader = req.headers["authorization"];
@@ -2554,10 +3757,11 @@ async function startWebDAVServer(drive2, options = {}) {
2554
3757
  return;
2555
3758
  }
2556
3759
  }
2557
- const parsedUrl = import_node_url.default.parse(req.url || "/", true);
3760
+ const parsedUrl = import_node_url2.default.parse(req.url || "/", true);
2558
3761
  const decodedPath = decodeURIComponent(parsedUrl.pathname || "/");
2559
- const virtualPath = decodedPath === "" ? "/" : decodedPath;
2560
- const baseName = import_node_path6.default.basename(virtualPath);
3762
+ const normalizedPath = import_node_path8.default.posix.normalize(decodedPath);
3763
+ const virtualPath = normalizedPath.startsWith("/") ? normalizedPath : `/${normalizedPath}`;
3764
+ const baseName = import_node_path8.default.basename(virtualPath);
2561
3765
  if (baseName.startsWith("._") || baseName === ".DS_Store" || baseName === ".Trashes" || baseName === ".Spotlight-V100" || baseName === ".fseventsd") {
2562
3766
  res.writeHead(404, { "Content-Type": "text/plain" });
2563
3767
  res.end("Not Found");
@@ -2646,7 +3850,7 @@ async function startWebDAVServer(drive2, options = {}) {
2646
3850
  return;
2647
3851
  }
2648
3852
  case "PUT": {
2649
- const remoteDir = import_node_path6.default.dirname(virtualPath);
3853
+ const remoteDir = import_node_path8.default.dirname(virtualPath);
2650
3854
  await drive2.mkdirp(remoteDir);
2651
3855
  let existed = false;
2652
3856
  try {
@@ -2707,16 +3911,16 @@ async function startWebDAVServer(drive2, options = {}) {
2707
3911
  res.end("Source file not found");
2708
3912
  return;
2709
3913
  }
2710
- const destUrl = import_node_url.default.parse(destination);
3914
+ const destUrl = import_node_url2.default.parse(destination);
2711
3915
  const destPath = decodeURIComponent(destUrl.pathname || "");
2712
- const newName = import_node_path6.default.basename(destPath);
2713
- const newParentDir = import_node_path6.default.dirname(destPath);
3916
+ const newName = import_node_path8.default.basename(destPath);
3917
+ const newParentDir = import_node_path8.default.dirname(destPath);
2714
3918
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2715
- const currentParentDir = import_node_path6.default.dirname(virtualPath);
3919
+ const currentParentDir = import_node_path8.default.dirname(virtualPath);
2716
3920
  if (newParentDir !== currentParentDir) {
2717
3921
  await drive2.move(file.id, newParentFolderId);
2718
3922
  }
2719
- if (newName !== import_node_path6.default.basename(virtualPath)) {
3923
+ if (newName !== import_node_path8.default.basename(virtualPath)) {
2720
3924
  await drive2.rename(file.id, newName);
2721
3925
  }
2722
3926
  res.writeHead(201);
@@ -2741,10 +3945,10 @@ async function startWebDAVServer(drive2, options = {}) {
2741
3945
  res.end("Source file not found");
2742
3946
  return;
2743
3947
  }
2744
- const destUrl = import_node_url.default.parse(destination);
3948
+ const destUrl = import_node_url2.default.parse(destination);
2745
3949
  const destPath = decodeURIComponent(destUrl.pathname || "");
2746
- const newName = import_node_path6.default.basename(destPath);
2747
- const newParentDir = import_node_path6.default.dirname(destPath);
3950
+ const newName = import_node_path8.default.basename(destPath);
3951
+ const newParentDir = import_node_path8.default.dirname(destPath);
2748
3952
  const newParentFolderId = await drive2.mkdirp(newParentDir);
2749
3953
  await drive2.copy(file.id, { parent: newParentFolderId, name: newName });
2750
3954
  res.writeHead(201);
@@ -2809,8 +4013,8 @@ async function handlePropfind(drive2, virtualPath, depth) {
2809
4013
  if (seenNames.has(childName)) {
2810
4014
  const count = seenNames.get(childName) + 1;
2811
4015
  seenNames.set(childName, count);
2812
- const ext = import_node_path6.default.extname(childName);
2813
- const base = import_node_path6.default.basename(childName, ext);
4016
+ const ext = import_node_path8.default.extname(childName);
4017
+ const base = import_node_path8.default.basename(childName, ext);
2814
4018
  childName = `${base} (${count})${ext}`;
2815
4019
  } else {
2816
4020
  seenNames.set(childName, 0);
@@ -2841,7 +4045,7 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
2841
4045
  cleanHref += "/";
2842
4046
  }
2843
4047
  const encodedHref = encodeURI(cleanHref);
2844
- const displayName = escapeXml(import_node_path6.default.basename(href) || "root");
4048
+ const displayName = escapeXml(import_node_path8.default.basename(href) || "root");
2845
4049
  const resourceType = isDir ? "<D:collection/>" : "";
2846
4050
  const dateFormatted = new Date(modifiedTime).toUTCString();
2847
4051
  const contentTypeTag = !isDir && mimeType ? `
@@ -2859,14 +4063,14 @@ function renderWebDAVResponse(href, isDir, size, modifiedTime, mimeType) {
2859
4063
  </D:propstat>
2860
4064
  </D:response>`;
2861
4065
  }
2862
- var import_node_http3, import_node_url, import_node_path6;
4066
+ var import_node_http4, import_node_url2, import_node_path8;
2863
4067
  var init_webdav = __esm({
2864
4068
  "src/server/webdav.ts"() {
2865
4069
  "use strict";
2866
4070
  init_cjs_shims();
2867
- import_node_http3 = __toESM(require("http"), 1);
2868
- import_node_url = __toESM(require("url"), 1);
2869
- import_node_path6 = __toESM(require("path"), 1);
4071
+ import_node_http4 = __toESM(require("http"), 1);
4072
+ import_node_url2 = __toESM(require("url"), 1);
4073
+ import_node_path8 = __toESM(require("path"), 1);
2870
4074
  }
2871
4075
  });
2872
4076
 
@@ -2875,13 +4079,14 @@ var client_exports = {};
2875
4079
  __export(client_exports, {
2876
4080
  DriveKit: () => DriveKit
2877
4081
  });
2878
- var import_node_fs6, import_node_path7, import_drive3, DriveKit;
4082
+ var import_node_fs7, import_node_path9, import_node_crypto3, import_drive3, DriveKit;
2879
4083
  var init_client = __esm({
2880
4084
  "src/core/client.ts"() {
2881
4085
  "use strict";
2882
4086
  init_cjs_shims();
2883
- import_node_fs6 = __toESM(require("fs"), 1);
2884
- import_node_path7 = __toESM(require("path"), 1);
4087
+ import_node_fs7 = __toESM(require("fs"), 1);
4088
+ import_node_path9 = __toESM(require("path"), 1);
4089
+ import_node_crypto3 = __toESM(require("crypto"), 1);
2885
4090
  import_drive3 = require("@googleapis/drive");
2886
4091
  init_authenticator();
2887
4092
  init_path_resolver();
@@ -2900,6 +4105,13 @@ var init_client = __esm({
2900
4105
  init_mime();
2901
4106
  init_cache();
2902
4107
  init_http_agent();
4108
+ init_encryption();
4109
+ init_revisions();
4110
+ init_bidirectional_sync();
4111
+ init_s3_gateway();
4112
+ init_security_auditor();
4113
+ init_semantic_search();
4114
+ init_compression();
2903
4115
  DriveKit = class _DriveKit {
2904
4116
  options;
2905
4117
  authenticator;
@@ -2908,12 +4120,34 @@ var init_client = __esm({
2908
4120
  uploaderInstance = null;
2909
4121
  downloaderInstance = null;
2910
4122
  metadataCacheInstance = null;
4123
+ cryptoInstance = null;
2911
4124
  rootFolderId;
2912
4125
  pluginManager = new PluginManager();
2913
4126
  constructor(options = {}) {
2914
4127
  this.options = options;
2915
4128
  this.rootFolderId = options.rootFolderId || "root";
2916
4129
  this.authenticator = new DriveAuthenticator(options.auth);
4130
+ if (options.encryption) {
4131
+ this.cryptoInstance = new DriveKitCrypto(options.encryption);
4132
+ }
4133
+ }
4134
+ /**
4135
+ * Access the client-side AES-256-GCM encryption engine
4136
+ */
4137
+ get crypto() {
4138
+ if (!this.cryptoInstance) {
4139
+ throw new Error("Encryption is not configured on this DriveKit instance. Pass { encryption: { password: ... } } in options.");
4140
+ }
4141
+ return this.cryptoInstance;
4142
+ }
4143
+ /**
4144
+ * Access historical revisions & version control for a file
4145
+ */
4146
+ getRevisions(fileIdOrPath) {
4147
+ if (!this.driveClient) {
4148
+ throw new Error("DriveKit is not initialized. Call await drive.init() first.");
4149
+ }
4150
+ return new DriveFileRevisions(this.driveClient, fileIdOrPath, (p) => this.resolveId(p));
2917
4151
  }
2918
4152
  /**
2919
4153
  * Registers a middleware plugin into DriveKit lifecycle
@@ -3093,58 +4327,89 @@ var init_client = __esm({
3093
4327
  if (parentId && parentId.startsWith("/")) {
3094
4328
  parentId = await this.mkdirp(parentId);
3095
4329
  }
3096
- const targetName = opts.name || opts.filename || (typeof opts.source === "string" ? import_node_path7.default.basename(opts.source) : void 0);
3097
- if (opts.overwrite && targetName && parentId) {
4330
+ let uploadOpts = { ...opts };
4331
+ if (uploadOpts.compress) {
4332
+ const algo = typeof uploadOpts.compress === "string" ? uploadOpts.compress : "gzip";
4333
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4334
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4335
+ uploadOpts.source = await compressBuffer(plainBuf, algo);
4336
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4337
+ uploadOpts.source = await compressBuffer(uploadOpts.source, algo);
4338
+ }
4339
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_compressed: algo };
4340
+ }
4341
+ if ((uploadOpts.encrypt || this.options.encryption) && this.cryptoInstance) {
4342
+ const origName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "encrypted.bin");
4343
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4344
+ const plainBuf = await import_node_fs7.default.promises.readFile(uploadOpts.source);
4345
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(plainBuf);
4346
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4347
+ uploadOpts.source = this.cryptoInstance.encryptBuffer(uploadOpts.source);
4348
+ }
4349
+ if (this.options.encryption?.encryptFilenames) {
4350
+ uploadOpts.name = this.cryptoInstance.encryptFilename(origName);
4351
+ }
4352
+ uploadOpts.appProperties = { ...uploadOpts.appProperties, drivekit_encrypted: "true" };
4353
+ }
4354
+ const targetName = uploadOpts.name || uploadOpts.filename || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : void 0);
4355
+ if (uploadOpts.overwrite && targetName && parentId) {
3098
4356
  const existing = await this.query().inFolder(parentId).nameEquals(targetName).notTrashed().first();
3099
4357
  if (existing?.id) {
3100
4358
  await this.delete(existing.id, true);
3101
4359
  }
3102
4360
  }
3103
- if (opts.deduplicate && typeof opts.source === "string" && import_node_fs6.default.existsSync(opts.source)) {
3104
- const localMd5 = await calculateFileMd5(opts.source);
3105
- let existingId;
3106
- if (this.metadataCacheInstance) {
3107
- const cached = this.metadataCacheInstance.findByMd5(localMd5);
3108
- if (cached) existingId = cached.id;
4361
+ if (uploadOpts.deduplicate) {
4362
+ let localMd5;
4363
+ if (typeof uploadOpts.source === "string" && import_node_fs7.default.existsSync(uploadOpts.source)) {
4364
+ localMd5 = await calculateFileMd5(uploadOpts.source);
4365
+ } else if (Buffer.isBuffer(uploadOpts.source)) {
4366
+ localMd5 = import_node_crypto3.default.createHash("md5").update(uploadOpts.source).digest("hex");
3109
4367
  }
3110
- if (!existingId) {
3111
- const found = await this.query().md5(localMd5).notTrashed().first();
3112
- if (found?.id) {
3113
- existingId = found.id;
4368
+ if (localMd5) {
4369
+ let existingId;
4370
+ if (this.metadataCacheInstance) {
4371
+ const cached = this.metadataCacheInstance.findByMd5(localMd5);
4372
+ if (cached) existingId = cached.id;
3114
4373
  }
3115
- }
3116
- if (existingId) {
3117
- const fileName = targetName || import_node_path7.default.basename(opts.source);
3118
- const raw = await this.getRawClient();
3119
- const copyRes = await withRetry(async () => {
3120
- return await raw.files.copy({
3121
- fileId: existingId,
3122
- requestBody: {
3123
- name: fileName,
3124
- parents: parentId ? [parentId] : void 0,
3125
- description: opts.description
3126
- },
3127
- fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
3128
- supportsAllDrives: true
3129
- });
3130
- });
3131
- const file = copyRes.data;
3132
- if (this.metadataCacheInstance && file.id) {
3133
- this.metadataCacheInstance.upsertFile({
3134
- id: file.id,
3135
- name: file.name || fileName,
3136
- mimeType: file.mimeType || "",
3137
- size: file.size ? parseInt(file.size, 10) : void 0,
3138
- parentId,
3139
- md5Checksum: localMd5,
3140
- trashed: false
4374
+ if (!existingId) {
4375
+ const found = await this.query().md5(localMd5).notTrashed().first();
4376
+ if (found?.id) {
4377
+ existingId = found.id;
4378
+ }
4379
+ }
4380
+ if (existingId) {
4381
+ const fileName = targetName || (typeof uploadOpts.source === "string" ? import_node_path9.default.basename(uploadOpts.source) : "file.bin");
4382
+ const raw = await this.getRawClient();
4383
+ const copyRes = await withRetry(async () => {
4384
+ return await raw.files.copy({
4385
+ fileId: existingId,
4386
+ requestBody: {
4387
+ name: fileName,
4388
+ parents: parentId ? [parentId] : void 0,
4389
+ description: uploadOpts.description
4390
+ },
4391
+ fields: "id, name, mimeType, size, modifiedTime, md5Checksum",
4392
+ supportsAllDrives: true
4393
+ });
3141
4394
  });
4395
+ const file = copyRes.data;
4396
+ if (this.metadataCacheInstance && file.id) {
4397
+ this.metadataCacheInstance.upsertFile({
4398
+ id: file.id,
4399
+ name: file.name || fileName,
4400
+ mimeType: file.mimeType || "",
4401
+ size: file.size ? parseInt(file.size, 10) : void 0,
4402
+ parentId,
4403
+ md5Checksum: localMd5,
4404
+ trashed: false
4405
+ });
4406
+ }
4407
+ return await this.pluginManager.runAfterUpload(file);
3142
4408
  }
3143
- return await this.pluginManager.runAfterUpload(file);
3144
4409
  }
3145
4410
  }
3146
4411
  const uploaded = await uploader.upload({
3147
- ...opts,
4412
+ ...uploadOpts,
3148
4413
  name: targetName,
3149
4414
  parent: parentId
3150
4415
  });
@@ -3182,6 +4447,16 @@ var init_client = __esm({
3182
4447
  const processedOpts = await this.pluginManager.runBeforeDownload(fileId, mergedOpts);
3183
4448
  const downloader = await this.getDownloader();
3184
4449
  const result = await downloader.download(fileId, processedOpts);
4450
+ if (processedOpts.decrypt && this.cryptoInstance && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4451
+ const encrypted = await import_node_fs7.default.promises.readFile(result.filePath);
4452
+ const decrypted = this.cryptoInstance.decryptBuffer(encrypted);
4453
+ await import_node_fs7.default.promises.writeFile(result.filePath, decrypted);
4454
+ }
4455
+ if (processedOpts.decompress && result.filePath && import_node_fs7.default.existsSync(result.filePath)) {
4456
+ const comp = await import_node_fs7.default.promises.readFile(result.filePath);
4457
+ const decomp = await decompressBuffer(comp);
4458
+ await import_node_fs7.default.promises.writeFile(result.filePath, decomp);
4459
+ }
3185
4460
  return await this.pluginManager.runAfterDownload(result);
3186
4461
  }
3187
4462
  /**
@@ -3315,10 +4590,7 @@ var init_client = __esm({
3315
4590
  async copy(fileIdOrPath, options = {}) {
3316
4591
  const fileId = await this.resolveId(fileIdOrPath);
3317
4592
  const raw = await this.getRawClient();
3318
- let parentId = options.parent;
3319
- if (parentId && parentId.startsWith("/")) {
3320
- parentId = await this.mkdirp(parentId);
3321
- }
4593
+ const parentId = options.parent ? await this.resolveId(options.parent, true) : void 0;
3322
4594
  const requestBody = {};
3323
4595
  if (options.name) requestBody.name = options.name;
3324
4596
  if (parentId) requestBody.parents = [parentId];
@@ -3445,16 +4717,16 @@ var init_client = __esm({
3445
4717
  durationMs: 0
3446
4718
  };
3447
4719
  const collectFiles = async (dir, base) => {
3448
- const entries = await import_node_fs6.default.promises.readdir(dir, { withFileTypes: true });
4720
+ const entries = await import_node_fs7.default.promises.readdir(dir, { withFileTypes: true });
3449
4721
  const files = [];
3450
4722
  for (const entry of entries) {
3451
- const fullPath = import_node_path7.default.join(dir, entry.name);
3452
- const relPath = import_node_path7.default.join(base, entry.name);
4723
+ const fullPath = import_node_path9.default.join(dir, entry.name);
4724
+ const relPath = import_node_path9.default.join(base, entry.name);
3453
4725
  if (entry.isDirectory()) {
3454
4726
  const sub = await collectFiles(fullPath, relPath);
3455
4727
  files.push(...sub);
3456
4728
  } else if (entry.isFile()) {
3457
- const stat = await import_node_fs6.default.promises.stat(fullPath);
4729
+ const stat = await import_node_fs7.default.promises.stat(fullPath);
3458
4730
  files.push({ fullPath, relPath, size: stat.size });
3459
4731
  }
3460
4732
  }
@@ -3467,11 +4739,11 @@ var init_client = __esm({
3467
4739
  if (remoteDirCache.has(relDir)) {
3468
4740
  return remoteDirCache.get(relDir);
3469
4741
  }
3470
- const parts = relDir.split(import_node_path7.default.sep).filter(Boolean);
4742
+ const parts = relDir.split(import_node_path9.default.sep).filter(Boolean);
3471
4743
  let currentParent = targetFolderId;
3472
4744
  let currentRel = "";
3473
4745
  for (const part of parts) {
3474
- currentRel = currentRel ? import_node_path7.default.join(currentRel, part) : part;
4746
+ currentRel = currentRel ? import_node_path9.default.join(currentRel, part) : part;
3475
4747
  if (remoteDirCache.has(currentRel)) {
3476
4748
  currentParent = remoteDirCache.get(currentRel);
3477
4749
  continue;
@@ -3500,8 +4772,8 @@ var init_client = __esm({
3500
4772
  };
3501
4773
  await pool.map(allFiles, async (fileItem) => {
3502
4774
  try {
3503
- const relDir = import_node_path7.default.dirname(fileItem.relPath);
3504
- const fileName = import_node_path7.default.basename(fileItem.relPath);
4775
+ const relDir = import_node_path9.default.dirname(fileItem.relPath);
4776
+ const fileName = import_node_path9.default.basename(fileItem.relPath);
3505
4777
  const parentFolderId = await ensureRemoteSubdir(relDir === "." ? "" : relDir);
3506
4778
  if (options.onFileStart) {
3507
4779
  options.onFileStart(fileItem.fullPath, fileItem.relPath);
@@ -3644,8 +4916,8 @@ var init_client = __esm({
3644
4916
  rejectDone = reject;
3645
4917
  });
3646
4918
  passThrough.done = donePromise;
3647
- const remoteDir = import_node_path7.default.dirname(remotePath);
3648
- const fileName = options.name || options.filename || import_node_path7.default.basename(remotePath);
4919
+ const remoteDir = import_node_path9.default.dirname(remotePath);
4920
+ const fileName = options.name || options.filename || import_node_path9.default.basename(remotePath);
3649
4921
  const targetParentId = remoteDir === "." || remoteDir === "/" ? this.rootFolderId : await this.mkdirp(remoteDir);
3650
4922
  const mimeType = options.mimeType || "application/octet-stream";
3651
4923
  const raw = this.driveClient;
@@ -3878,6 +5150,47 @@ var init_client = __esm({
3878
5150
  const { startWebDAVServer: startWebDAVServer2 } = await Promise.resolve().then(() => (init_webdav(), webdav_exports));
3879
5151
  return await startWebDAVServer2(this, options);
3880
5152
  }
5153
+ /**
5154
+ * Performs an intelligent two-way bidirectional sync between local and Google Drive directories
5155
+ */
5156
+ async syncBiDirectional(options) {
5157
+ await this.init();
5158
+ const engine = new BidirectionalSyncEngine(this);
5159
+ return await engine.sync(options);
5160
+ }
5161
+ /**
5162
+ * Starts an embedded S3-compatible HTTP gateway server
5163
+ */
5164
+ async serveS3(options = {}) {
5165
+ await this.init();
5166
+ const gateway = new S3GatewayServer(this, options);
5167
+ await gateway.start();
5168
+ return gateway;
5169
+ }
5170
+ /**
5171
+ * Scans Google Drive files and generates a security & permission audit report
5172
+ */
5173
+ async auditPermissions(options = {}) {
5174
+ await this.init();
5175
+ const auditor = new SecurityAuditor(this.driveClient);
5176
+ return await auditor.audit(options);
5177
+ }
5178
+ /**
5179
+ * Revokes public 'anyone' link permissions from the given files
5180
+ */
5181
+ async revokePublicPermissions(fileIds) {
5182
+ await this.init();
5183
+ const auditor = new SecurityAuditor(this.driveClient);
5184
+ return await auditor.revokePublicAccess(fileIds);
5185
+ }
5186
+ /**
5187
+ * Multi-word fuzzy and semantic search across files
5188
+ */
5189
+ async searchSmart(query, options = {}) {
5190
+ await this.init();
5191
+ const engine = new SmartSearchEngine(this);
5192
+ return await engine.search(query, options);
5193
+ }
3881
5194
  /**
3882
5195
  * Calculates local file MD5 hash for integrity and deduplication checks
3883
5196
  */
@@ -3901,8 +5214,8 @@ __export(cli_exports, {
3901
5214
  });
3902
5215
  module.exports = __toCommonJS(cli_exports);
3903
5216
  init_cjs_shims();
3904
- var import_node_fs7 = __toESM(require("fs"), 1);
3905
- var import_node_path8 = __toESM(require("path"), 1);
5217
+ var import_node_fs8 = __toESM(require("fs"), 1);
5218
+ var import_node_path10 = __toESM(require("path"), 1);
3906
5219
  var import_commander = require("commander");
3907
5220
  var import_chalk2 = __toESM(require("chalk"), 1);
3908
5221
  var import_ora = __toESM(require("ora"), 1);
@@ -4065,10 +5378,10 @@ ${import_chalk.default.cyan("\u{1F517} Getting shareable link for:")} ${import_c
4065
5378
 
4066
5379
  // src/cli.ts
4067
5380
  var program = new import_commander.Command();
4068
- var pkgVersion = "1.1.2";
5381
+ var pkgVersion = "1.2.0";
4069
5382
  try {
4070
5383
  const pkgPath = new URL("../package.json", importMetaUrl);
4071
- const pkg = JSON.parse(import_node_fs7.default.readFileSync(pkgPath, "utf8"));
5384
+ const pkg = JSON.parse(import_node_fs8.default.readFileSync(pkgPath, "utf8"));
4072
5385
  if (pkg.version) pkgVersion = pkg.version;
4073
5386
  } catch {
4074
5387
  }
@@ -4077,10 +5390,10 @@ function getAuthConfig(cmdOptions) {
4077
5390
  const keyFilePath = cmdOptions.key || process.env.GOOGLE_APPLICATION_CREDENTIALS || process.env.GDRIVE_SERVICE_ACCOUNT_PATH;
4078
5391
  let accessToken = cmdOptions.token || process.env.GDRIVE_ACCESS_TOKEN;
4079
5392
  if (!keyFilePath && !accessToken) {
4080
- const tokensFile = import_node_path8.default.resolve(process.cwd(), "gdrive-tokens.json");
4081
- if (import_node_fs7.default.existsSync(tokensFile)) {
5393
+ const tokensFile = import_node_path10.default.resolve(process.cwd(), "gdrive-tokens.json");
5394
+ if (import_node_fs8.default.existsSync(tokensFile)) {
4082
5395
  try {
4083
- const tokens = JSON.parse(import_node_fs7.default.readFileSync(tokensFile, "utf8"));
5396
+ const tokens = JSON.parse(import_node_fs8.default.readFileSync(tokensFile, "utf8"));
4084
5397
  if (tokens.access_token) {
4085
5398
  accessToken = tokens.access_token;
4086
5399
  }
@@ -4157,11 +5470,11 @@ program.command("explore [folder]").description("Interactive terminal keyboard f
4157
5470
  }
4158
5471
  });
4159
5472
  program.command("upload <localFile> [remotePath]").description("Upload a file with high speed and live progress tracking").option("-o, --overwrite", "Overwrite remote file if it exists").option("-d, --dedup", "Enable instant cloud deduplication via MD5 hash check").action(async (localFile, remotePath = "/", options) => {
4160
- if (!import_node_fs7.default.existsSync(localFile)) {
5473
+ if (!import_node_fs8.default.existsSync(localFile)) {
4161
5474
  console.error(import_chalk2.default.red(`\u274C Local file not found: ${localFile}`));
4162
5475
  process.exit(1);
4163
5476
  }
4164
- const fileName = import_node_path8.default.basename(localFile);
5477
+ const fileName = import_node_path10.default.basename(localFile);
4165
5478
  const spinner = (0, import_ora.default)(`Preparing upload: ${fileName}...`).start();
4166
5479
  try {
4167
5480
  const client = await getClient(options);
@@ -4257,7 +5570,7 @@ program.command("delete <fileIdOrPath>").description("Move a file/folder to tras
4257
5570
  }
4258
5571
  });
4259
5572
  program.command("sync <localDir> <remoteFolder>").description("Sync a local directory to Google Drive recursively with high concurrency").option("-c, --concurrency <number>", "Number of parallel uploads", "4").option("-o, --overwrite", "Overwrite files if they already exist").action(async (localDir, remoteFolder, options) => {
4260
- if (!import_node_fs7.default.existsSync(localDir)) {
5573
+ if (!import_node_fs8.default.existsSync(localDir)) {
4261
5574
  console.error(import_chalk2.default.red(`\u274C Local directory not found: ${localDir}`));
4262
5575
  process.exit(1);
4263
5576
  }
@@ -4425,8 +5738,8 @@ program.command("login").description("Interactive 1-click browser OAuth2 sign-in
4425
5738
  if (result.tokens.refresh_token) {
4426
5739
  console.log(`Refresh Token: ${import_chalk2.default.green(result.tokens.refresh_token?.slice(0, 25) + "...")}`);
4427
5740
  }
4428
- const outPath = import_node_path8.default.resolve("./gdrive-tokens.json");
4429
- import_node_fs7.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
5741
+ const outPath = import_node_path10.default.resolve("./gdrive-tokens.json");
5742
+ import_node_fs8.default.writeFileSync(outPath, JSON.stringify(result.tokens, null, 2), "utf8");
4430
5743
  console.log(`\u{1F4BE} Saved tokens to: ${import_chalk2.default.bold(outPath)}
4431
5744
  `);
4432
5745
  } catch (err) {
@@ -4538,6 +5851,186 @@ program.command("serve").description("Start embedded WebDAV server to mount Driv
4538
5851
  process.exit(1);
4539
5852
  }
4540
5853
  });
5854
+ program.command("sync-2way <localDir> <remoteDir>").description("Two-way bidirectional synchronization with conflict resolution").option("-s, --strategy <strategy>", "Conflict strategy: rename-conflict, keep-newer, prefer-cloud, prefer-local", "rename-conflict").option("--delete-missing", "Propagate deletions in both directions").option("--dry-run", "Preview changes without modifying any files").action(async (localDir, remoteDir, options) => {
5855
+ console.log(import_chalk2.default.bold.cyan(`
5856
+ \u{1F504} Two-Way Sync: "${localDir}" \u21C4 "${remoteDir}"`));
5857
+ console.log(`Conflict Strategy: ${import_chalk2.default.yellow(options.strategy)} | Delete Missing: ${options.deleteMissing ? import_chalk2.default.red("YES") : import_chalk2.default.dim("NO")}
5858
+ `);
5859
+ try {
5860
+ const client = await getClient(options);
5861
+ const res = await client.syncBiDirectional({
5862
+ localDir: import_node_path10.default.resolve(localDir),
5863
+ remoteDir,
5864
+ conflictStrategy: options.strategy,
5865
+ deleteMissing: !!options.deleteMissing,
5866
+ dryRun: !!options.dryRun,
5867
+ onProgress: (ev) => {
5868
+ const actionColors = {
5869
+ upload: import_chalk2.default.green("[UPLOAD]"),
5870
+ download: import_chalk2.default.blue("[DOWNLOAD]"),
5871
+ "delete-local": import_chalk2.default.red("[DELETE LOCAL]"),
5872
+ "delete-remote": import_chalk2.default.red("[DELETE REMOTE]"),
5873
+ "conflict-resolved": import_chalk2.default.yellow("[CONFLICT]"),
5874
+ "skip-identical": import_chalk2.default.dim("[IDENTICAL]")
5875
+ };
5876
+ const prefix = actionColors[ev.action] || `[${ev.action}]`;
5877
+ console.log(` ${prefix} ${import_chalk2.default.white(ev.relPath)} ${ev.details ? import_chalk2.default.dim(`(${ev.details})`) : ""}`);
5878
+ }
5879
+ });
5880
+ console.log(import_chalk2.default.bold.green(`
5881
+ \u2705 Two-Way Sync Completed in ${(res.durationMs / 1e3).toFixed(2)}s!`));
5882
+ console.log(` \u2B06\uFE0F Uploaded: ${import_chalk2.default.bold(res.uploaded.length)}`);
5883
+ console.log(` \u2B07\uFE0F Downloaded: ${import_chalk2.default.bold(res.downloaded.length)}`);
5884
+ console.log(` \u{1F5D1}\uFE0F Deleted Local: ${import_chalk2.default.bold(res.deletedLocal.length)}`);
5885
+ console.log(` \u{1F5D1}\uFE0F Deleted Remote:${import_chalk2.default.bold(res.deletedRemote.length)}`);
5886
+ console.log(` \u26A1 Conflicts: ${import_chalk2.default.bold(res.conflicts.length)}`);
5887
+ console.log(` \u23ED\uFE0F Identical: ${import_chalk2.default.bold(res.skipped.length)}
5888
+ `);
5889
+ } catch (err) {
5890
+ console.error(import_chalk2.default.red(`
5891
+ Two-Way sync failed: ${err.message}`));
5892
+ process.exit(1);
5893
+ }
5894
+ });
5895
+ program.command("serve-s3").description("Start S3-compatible HTTP gateway server to treat Drive as an S3 Bucket").option("-p, --port <port>", "Port number to listen on", "9000").option("-h, --host <host>", "Host address to bind to", "127.0.0.1").option("-b, --bucket-root <path>", "Virtual path root for S3 buckets", "/").option("--key <accessKey>", "Optional S3 access key ID").option("--secret <secretKey>", "Optional S3 secret access key").action(async (options) => {
5896
+ try {
5897
+ const client = await getClient(options);
5898
+ const port = parseInt(options.port, 10) || 9e3;
5899
+ const host = options.host || "127.0.0.1";
5900
+ console.log(import_chalk2.default.bold.cyan("\n\u{1F4E6} DriveKit S3-Compatible Gateway"));
5901
+ console.log("Starting S3 REST API bridge to Google Drive...\n");
5902
+ const gateway = await client.serveS3({
5903
+ port,
5904
+ host,
5905
+ bucketRoot: options.bucketRoot,
5906
+ accessKeyId: options.key,
5907
+ secretAccessKey: options.secret
5908
+ });
5909
+ console.log(import_chalk2.default.bold.green(`\u{1F680} S3 Gateway active at: ${import_chalk2.default.underline(`http://${host}:${port}`)}`));
5910
+ console.log(import_chalk2.default.white("\n\u{1F4CC} Connect with AWS CLI:"));
5911
+ console.log(import_chalk2.default.yellow(` aws s3 ls --endpoint-url http://${host}:${port}`));
5912
+ console.log(import_chalk2.default.white("\u{1F4CC} Connect with MinIO client:"));
5913
+ console.log(import_chalk2.default.yellow(` mc alias set drivekit http://${host}:${port} ${options.key || "dummy"} ${options.secret || "dummy"}
5914
+ `));
5915
+ console.log(import_chalk2.default.dim("Press Ctrl+C to stop the S3 Gateway.\n"));
5916
+ process.on("SIGINT", async () => {
5917
+ await gateway.stop();
5918
+ console.log(import_chalk2.default.yellow("\nS3 Gateway stopped. Goodbye!"));
5919
+ process.exit(0);
5920
+ });
5921
+ } catch (err) {
5922
+ console.error(import_chalk2.default.red(`Failed to start S3 gateway: ${err.message}`));
5923
+ process.exit(1);
5924
+ }
5925
+ });
5926
+ program.command("audit").description("Audit Drive security & permissions: detect public leaks and external shares").option("-l, --limit <count>", "Maximum files to scan", "200").option("--allowed-domains <domains>", "Comma-separated allowed organization domains").option("--revoke-public", 'Automatically revoke public "anyone" links').action(async (options) => {
5927
+ const spinner = (0, import_ora.default)("Auditing Google Drive permissions...").start();
5928
+ try {
5929
+ const client = await getClient(options);
5930
+ const limit = parseInt(options.limit, 10) || 200;
5931
+ const allowedDomains = options.allowedDomains ? options.allowedDomains.split(",").map((d) => d.trim()) : [];
5932
+ const report = await client.auditPermissions({ scanLimit: limit, allowedDomains });
5933
+ spinner.stop();
5934
+ console.log(import_chalk2.default.bold.cyan("\n\u{1F6E1}\uFE0F Google Drive Security & Permission Audit Report"));
5935
+ console.log(`Scanned files: ${import_chalk2.default.bold(report.totalScanned)} | Audit time: ${import_chalk2.default.dim(report.scannedAt)}
5936
+ `);
5937
+ console.log(`\u{1F310} Publicly Accessible (Anyone with Link): ${report.publicFilesCount > 0 ? import_chalk2.default.bold.red(report.publicFilesCount) : import_chalk2.default.green("0")}`);
5938
+ console.log(`\u{1F3E2} Organization Domain Shares: ${import_chalk2.default.yellow(report.domainSharedCount)}`);
5939
+ console.log(`\u{1F464} External Collaborators: ${report.externalSharesCount > 0 ? import_chalk2.default.bold.yellow(report.externalSharesCount) : import_chalk2.default.green("0")}
5940
+ `);
5941
+ if (report.issues.length > 0) {
5942
+ console.log(import_chalk2.default.bold.yellow("\u26A0\uFE0F Detected Security Issues:"));
5943
+ for (const issue of report.issues.slice(0, 30)) {
5944
+ const riskColor = issue.risk === "CRITICAL" ? import_chalk2.default.bold.bgRed : issue.risk === "HIGH" ? import_chalk2.default.red : import_chalk2.default.yellow;
5945
+ console.log(` ${riskColor(`[${issue.risk}]`)} ${import_chalk2.default.bold(issue.fileName)}`);
5946
+ console.log(` \u21B3 Reason: ${issue.reason}`);
5947
+ if (issue.webViewLink) console.log(` \u21B3 URL: ${import_chalk2.default.dim(issue.webViewLink)}`);
5948
+ }
5949
+ if (report.issues.length > 30) {
5950
+ console.log(import_chalk2.default.dim(`
5951
+ ... and ${report.issues.length - 30} more issues.`));
5952
+ }
5953
+ console.log("");
5954
+ } else {
5955
+ console.log(import_chalk2.default.green("\u2728 No critical security leaks detected!\n"));
5956
+ }
5957
+ if (options.revokePublic && report.publicFilesCount > 0) {
5958
+ const publicFileIds = Array.from(new Set(report.issues.filter((i) => i.type === "anyone").map((i) => i.fileId)));
5959
+ const revSpinner = (0, import_ora.default)(`Revoking public access on ${publicFileIds.length} files...`).start();
5960
+ const revRes = await client.revokePublicPermissions(publicFileIds);
5961
+ revSpinner.succeed(import_chalk2.default.green(`Successfully revoked public access on ${revRes.revoked.length} files!`));
5962
+ }
5963
+ } catch (err) {
5964
+ spinner.fail(import_chalk2.default.red(`Security audit failed: ${err.message}`));
5965
+ process.exit(1);
5966
+ }
5967
+ });
5968
+ program.command("revisions <fileIdOrPath>").description("List and manage historical file revisions").option("--keep-forever <revId>", "Pin a revision to prevent automatic purging after 30 days").option("--restore <revId>", "Restore file to a specific previous revision").action(async (fileIdOrPath, options) => {
5969
+ try {
5970
+ const client = await getClient(options);
5971
+ const revsManager = client.getRevisions(fileIdOrPath);
5972
+ if (options.keepForever) {
5973
+ const spinner2 = (0, import_ora.default)(`Pinning revision ${options.keepForever}...`).start();
5974
+ await revsManager.keepForever(options.keepForever, true);
5975
+ spinner2.succeed(import_chalk2.default.green(`Revision ${options.keepForever} is now pinned forever!`));
5976
+ return;
5977
+ }
5978
+ if (options.restore) {
5979
+ const spinner2 = (0, import_ora.default)(`Restoring file to revision ${options.restore}...`).start();
5980
+ await revsManager.restore(options.restore);
5981
+ spinner2.succeed(import_chalk2.default.green(`File content successfully restored to revision ${options.restore}!`));
5982
+ return;
5983
+ }
5984
+ const spinner = (0, import_ora.default)("Fetching revision history...").start();
5985
+ const revisions = await revsManager.list();
5986
+ spinner.stop();
5987
+ console.log(import_chalk2.default.bold.cyan(`
5988
+ \u{1F4DC} Revision History for "${fileIdOrPath}" (${revisions.length} versions):
5989
+ `));
5990
+ for (const r of revisions) {
5991
+ const pinned = r.keepForever ? import_chalk2.default.green("\u{1F4CC} [PINNED]") : import_chalk2.default.dim("[EXPIRABLE]");
5992
+ console.log(` ID: ${import_chalk2.default.bold.yellow(r.id.padEnd(20))} Modified: ${import_chalk2.default.white(r.modifiedTime || "unknown")} ${pinned} ${r.size ? formatBytes(r.size) : ""}`);
5993
+ }
5994
+ console.log("");
5995
+ } catch (err) {
5996
+ console.error(import_chalk2.default.red(`Failed to manage revisions: ${err.message}`));
5997
+ process.exit(1);
5998
+ }
5999
+ });
6000
+ program.command("search <query>").description("Search Google Drive files by name, description, or fuzzy matching").option("--smart", "Use multi-word fuzzy relevance scoring").option("-l, --limit <count>", "Maximum results to return", "20").action(async (query, options) => {
6001
+ const spinner = (0, import_ora.default)(`Searching for "${query}"...`).start();
6002
+ try {
6003
+ const client = await getClient(options);
6004
+ const limit = parseInt(options.limit, 10) || 20;
6005
+ if (options.smart) {
6006
+ const results = await client.searchSmart(query, { limit });
6007
+ spinner.stop();
6008
+ console.log(import_chalk2.default.bold.cyan(`
6009
+ \u{1F50D} Smart Search Results for "${query}" (${results.length}):
6010
+ `));
6011
+ for (const res of results) {
6012
+ const scorePercent = Math.round(res.score * 100);
6013
+ const scoreColor = scorePercent >= 80 ? import_chalk2.default.green : scorePercent >= 50 ? import_chalk2.default.yellow : import_chalk2.default.dim;
6014
+ console.log(` ${scoreColor(`[${scorePercent}%]`)} ${import_chalk2.default.bold(res.file.name)} ${import_chalk2.default.dim(`(Matched on: ${res.matchedOn.join(", ")})`)}`);
6015
+ console.log(` \u21B3 ID: ${import_chalk2.default.dim(res.file.id)} | Size: ${formatBytes(res.file.size ? parseInt(res.file.size, 10) : 0)}`);
6016
+ }
6017
+ console.log("");
6018
+ return;
6019
+ }
6020
+ const files = await client.query().nameContains(query).notTrashed().pageSize(limit).list();
6021
+ spinner.stop();
6022
+ console.log(import_chalk2.default.bold.cyan(`
6023
+ \u{1F50D} Found ${files.length} matching files:
6024
+ `));
6025
+ for (const f of files) {
6026
+ console.log(` \u{1F4C4} ${import_chalk2.default.white((f.name || "untitled").padEnd(35))} ${import_chalk2.default.dim(`ID: ${f.id}`)} [${formatBytes(f.size ? parseInt(f.size, 10) : 0)}]`);
6027
+ }
6028
+ console.log("");
6029
+ } catch (err) {
6030
+ spinner.fail(import_chalk2.default.red(`Search failed: ${err.message}`));
6031
+ process.exit(1);
6032
+ }
6033
+ });
4541
6034
  function runCLI() {
4542
6035
  program.parse(process.argv);
4543
6036
  }