gdrivekit 1.0.0 β†’ 1.0.3

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.
Files changed (4) hide show
  1. package/README.md +175 -6
  2. package/dist/index.js +224 -15
  3. package/package.json +21 -7
  4. package/index.ts +0 -3
package/README.md CHANGED
@@ -1,15 +1,184 @@
1
- # googledrive
1
+ ## 🧩 gdrivekit
2
2
 
3
- To install dependencies:
3
+ > **Google Drive file automation in just a few lines of code.**
4
+ > Perform uploads, downloads, folder management, and advanced search operations effortlessly using TypeScript or Node.js.
5
+
6
+ ---
7
+
8
+ ### πŸš€ Features
9
+
10
+ * πŸ“‚ Upload, download, and manage Google Drive files
11
+ * πŸ—‚οΈ Create and organize folders
12
+ * πŸ” Powerful search and filter utilities
13
+ * βš™οΈ Batch file operations
14
+ * ⚑ Minimal setup, lightweight, and easy to use
15
+ * πŸ’‘ Works with Node.js and Bun
16
+
17
+ ---
18
+
19
+ ### πŸ“¦ Installation
4
20
 
5
21
  ```bash
6
- bun install
22
+ npm install gdrivekit
7
23
  ```
8
24
 
9
- To run:
25
+ or
10
26
 
11
27
  ```bash
12
- bun run index.ts
28
+ bun add gdrivekit
29
+ ```
30
+
31
+ ---
32
+
33
+ ### πŸ’» Example Usage
34
+
35
+ ### βš™οΈ One-Time Setup (Token Generation)
36
+
37
+ Before you can use Google Drive operations, you must generate **access and refresh tokens**.
38
+ This only needs to be done **once** β€” the tokens will be stored locally and reused automatically.
39
+
40
+ ```ts
41
+ import { generateCredentialsAndTokens } from "gdrivekit";
42
+
43
+ await generateCredentialsAndTokens({
44
+ clientid: process.env.GOOGLE_CLIENT_ID!,
45
+ projectid: process.env.GOOGLE_PROJECT_ID!,
46
+ clientsecret: process.env.GOOGLE_CLIENT_SECRET!,
47
+ redirecturis: ["http://localhost:3000/oauth2callback"],
48
+ });
49
+ ```
50
+
51
+ βœ… **Run this code once** to authenticate your app and save tokens (usually in `tokens.json`).
52
+ After that, you **don’t need to call it again** unless you delete your tokens or change your Google credentials.
53
+
54
+ ---
55
+
56
+ # πŸ”„ Initializing the Drive Service
57
+
58
+ Once tokens are generated, you can initialize the Google Drive service and perform file operations:
59
+
60
+ ```ts
61
+ import { operations, initDriveService } from "gdrivekit";
62
+
63
+ async function main() {
64
+ initDriveService();
65
+
66
+ // Example: Search files by name
67
+ const files = await operations.searchByName("test");
68
+ console.log(files.data?.files);
69
+ }
70
+
71
+ main();
72
+ ```
73
+
74
+ ---
75
+
76
+ ## 🧠 Available Operations
77
+
78
+ ### πŸ“ **File Operations**
79
+
80
+ | Method | Description |
81
+ | ------------------ | ----------------------------------------- |
82
+ | `uploadFile()` | Upload a new file to Google Drive |
83
+ | `downloadFile()` | Download a file from Drive |
84
+ | `deleteFile()` | Permanently delete a file |
85
+ | `renameFile()` | Rename an existing file |
86
+ | `updateFile()` | Update file metadata or content |
87
+ | `getFileInfo()` | Get details of a specific file |
88
+ | `moveFile()` | Move file to another folder using file ID |
89
+ | `moveFileByName()` | Move file by its name |
90
+ | `copyFile()` | Make a copy of a file in Drive |
91
+
92
+ ---
93
+
94
+ ### πŸ—‚οΈ **Folder Operations**
95
+
96
+ | Method | Description |
97
+ | --------------------- | --------------------------------------- |
98
+ | `createFolder()` | Create a new folder |
99
+ | `deleteFolder()` | Delete an existing folder |
100
+ | `listAllFolders()` | List all folders in Drive |
101
+ | `listFilesInFolder()` | List all files within a specific folder |
102
+
103
+ ---
104
+
105
+ ### πŸ” **Search Operations**
106
+
107
+ | Method | Description |
108
+ | ----------------------- | -------------------------------------- |
109
+ | `searchByName()` | Search files containing a name |
110
+ | `searchByExactName()` | Search files matching exact name |
111
+ | `searchByType()` | Search by file type (e.g., PDF, image) |
112
+ | `searchModifiedAfter()` | Find files modified after a given date |
113
+ | `searchStarredFiles()` | List all starred files |
114
+ | `searchSharedFiles()` | Find files shared with you |
115
+ | `searchByContent()` | Search within file content |
116
+
117
+ ---
118
+
119
+ ### πŸ“‹ **List Operations**
120
+
121
+ | Method | Description |
122
+ | ------------------- | ------------------------------------- |
123
+ | `listFiles()` | List all files in Drive |
124
+ | `listRecentFiles()` | List recently modified or added files |
125
+ | `listPDFs()` | List all PDF files |
126
+ | `listImages()` | List all image files |
127
+
128
+ ---
129
+
130
+ ### 🧩 **Batch Operations**
131
+
132
+ | Method | Description |
133
+ | ------------------------- | ------------------------------------ |
134
+ | `uploadMultipleFiles()` | Upload multiple files at once |
135
+ | `deleteMultipleFiles()` | Delete multiple files simultaneously |
136
+ | `downloadMultipleFiles()` | Download multiple files in parallel |
137
+
138
+ ---
139
+
140
+ ### 🧰 **Utility Operations**
141
+
142
+ | Method | Description |
143
+ | --------------------- | --------------------------- |
144
+ | `fileExists()` | Check if a file exists |
145
+ | `getFolderIdByName()` | Fetch folder ID by its name |
146
+ | `getFileIdByName()` | Fetch file ID by its name |
147
+
148
+ ---
149
+
150
+ ### ⚑ Example: Upload a File
151
+
152
+ ```ts
153
+ await operations.uploadFile({
154
+ name: "report.pdf",
155
+ path: "./files/report.pdf",
156
+ mimeType: "application/pdf",
157
+ });
158
+ ```
159
+
160
+ ---
161
+
162
+ ### ⚑ Example: Search and Download
163
+
164
+ ```ts
165
+ const files = await operations.searchByName("invoice");
166
+ if (files?.data?.files?.length) {
167
+ await operations.downloadFile(files.data.files[0].id, "./downloads/invoice.pdf");
168
+ }
13
169
  ```
14
170
 
15
- This project was created using `bun init` in bun v1.3.0. [Bun](https://bun.com) is a fast all-in-one JavaScript runtime.
171
+ ---
172
+
173
+ ### πŸ§‘β€πŸ’» Author
174
+
175
+ **Vikash Khati**
176
+ [GitHub](https://github.com/vikashkhati007) β€’ [NPM](https://www.npmjs.com/~vikashkhati007)
177
+
178
+ ---
179
+
180
+ ### βš–οΈ License
181
+
182
+ **MIT License** β€” free to use, modify, and distribute.
183
+
184
+ ---
package/dist/index.js CHANGED
@@ -778735,8 +778735,218 @@ __export(exports_operations, {
778735
778735
  copyFile: () => copyFile
778736
778736
  });
778737
778737
 
778738
+ // drivers/services.ts
778739
+ import fs3 from "fs";
778740
+
778741
+ // drivers/GoogleDriveService.ts
778742
+ var import_googleapis = __toESM(require_src8(), 1);
778743
+ import * as fs2 from "fs";
778744
+ import * as path from "path";
778745
+
778746
+ class GoogleDriveService {
778747
+ oauth2Client;
778748
+ drive;
778749
+ constructor(credentials) {
778750
+ const creds = credentials.web || credentials.installed || credentials;
778751
+ const { client_id, client_secret } = creds;
778752
+ const redirect_uri = "redirect_uris" in creds ? creds.redirect_uris[0] : credentials.redirect_uri;
778753
+ this.oauth2Client = new import_googleapis.google.auth.OAuth2(client_id, client_secret, redirect_uri);
778754
+ this.drive = import_googleapis.google.drive({ version: "v3", auth: this.oauth2Client });
778755
+ }
778756
+ setCredentials(tokens) {
778757
+ this.oauth2Client.setCredentials(tokens);
778758
+ this.oauth2Client.on("tokens", (newTokens) => {
778759
+ if (newTokens.refresh_token) {
778760
+ tokens.refresh_token = newTokens.refresh_token;
778761
+ }
778762
+ tokens.access_token = newTokens.access_token;
778763
+ tokens.expiry_date = newTokens.expiry_date;
778764
+ fs2.writeFileSync("./tokens.json", JSON.stringify(tokens, null, 2));
778765
+ console.log("\uD83D\uDD04 Tokens refreshed and saved");
778766
+ });
778767
+ }
778768
+ async listFiles(params = {}) {
778769
+ try {
778770
+ const response = await this.drive.files.list({
778771
+ pageSize: params.pageSize || 10,
778772
+ fields: "nextPageToken, files(id, name, mimeType, size, createdTime, modifiedTime)",
778773
+ q: params.query || undefined,
778774
+ orderBy: params.orderBy || "modifiedTime desc",
778775
+ pageToken: params.pageToken || undefined
778776
+ });
778777
+ return {
778778
+ success: true,
778779
+ data: {
778780
+ files: response.data.files,
778781
+ nextPageToken: response.data.nextPageToken || undefined
778782
+ }
778783
+ };
778784
+ } catch (error) {
778785
+ return {
778786
+ success: false,
778787
+ error: error instanceof Error ? error.message : "Unknown error"
778788
+ };
778789
+ }
778790
+ }
778791
+ async getFileMetadata(fileId) {
778792
+ try {
778793
+ const response = await this.drive.files.get({
778794
+ fileId,
778795
+ fields: "id, name, mimeType, size, createdTime, modifiedTime, parents, webViewLink"
778796
+ });
778797
+ return {
778798
+ success: true,
778799
+ data: response.data
778800
+ };
778801
+ } catch (error) {
778802
+ return {
778803
+ success: false,
778804
+ error: error instanceof Error ? error.message : "Unknown error"
778805
+ };
778806
+ }
778807
+ }
778808
+ async downloadFile(fileId, destPath) {
778809
+ try {
778810
+ const dest = fs2.createWriteStream(destPath);
778811
+ const response = await this.drive.files.get({ fileId, alt: "media" }, { responseType: "stream" });
778812
+ return new Promise((resolve, reject) => {
778813
+ response.data.on("end", () => {
778814
+ resolve({ success: true, data: { path: destPath } });
778815
+ }).on("error", (err) => {
778816
+ reject({ success: false, error: err.message });
778817
+ }).pipe(dest);
778818
+ });
778819
+ } catch (error) {
778820
+ return {
778821
+ success: false,
778822
+ error: error instanceof Error ? error.message : "Unknown error"
778823
+ };
778824
+ }
778825
+ }
778826
+ async uploadFile(filePath, metadata = {}) {
778827
+ try {
778828
+ const fileMetadata = {
778829
+ name: metadata.name || path.basename(filePath),
778830
+ parents: metadata.parents || []
778831
+ };
778832
+ const media = {
778833
+ mimeType: metadata.mimeType,
778834
+ body: fs2.createReadStream(filePath)
778835
+ };
778836
+ const response = await this.drive.files.create({
778837
+ requestBody: fileMetadata,
778838
+ media,
778839
+ fields: "id, name, mimeType, size, webViewLink"
778840
+ });
778841
+ return {
778842
+ success: true,
778843
+ data: response.data
778844
+ };
778845
+ } catch (error) {
778846
+ return {
778847
+ success: false,
778848
+ error: error instanceof Error ? error.message : "Unknown error"
778849
+ };
778850
+ }
778851
+ }
778852
+ async updateFileContent(fileId, filePath) {
778853
+ try {
778854
+ const media = {
778855
+ body: fs2.createReadStream(filePath)
778856
+ };
778857
+ const response = await this.drive.files.update({
778858
+ fileId,
778859
+ media,
778860
+ fields: "id, name, mimeType, modifiedTime"
778861
+ });
778862
+ return {
778863
+ success: true,
778864
+ data: response.data
778865
+ };
778866
+ } catch (error) {
778867
+ return {
778868
+ success: false,
778869
+ error: error instanceof Error ? error.message : "Unknown error"
778870
+ };
778871
+ }
778872
+ }
778873
+ async updateFileMetadata(fileId, metadata) {
778874
+ try {
778875
+ const response = await this.drive.files.update({
778876
+ fileId,
778877
+ requestBody: metadata,
778878
+ fields: "id, name, mimeType, modifiedTime"
778879
+ });
778880
+ return {
778881
+ success: true,
778882
+ data: response.data
778883
+ };
778884
+ } catch (error) {
778885
+ return {
778886
+ success: false,
778887
+ error: error instanceof Error ? error.message : "Unknown error"
778888
+ };
778889
+ }
778890
+ }
778891
+ async deleteFile(fileId) {
778892
+ try {
778893
+ await this.drive.files.delete({
778894
+ fileId
778895
+ });
778896
+ return {
778897
+ success: true,
778898
+ data: { message: "File deleted successfully" }
778899
+ };
778900
+ } catch (error) {
778901
+ return {
778902
+ success: false,
778903
+ error: error instanceof Error ? error.message : "Unknown error"
778904
+ };
778905
+ }
778906
+ }
778907
+ async createFolder(folderName, parentFolderId) {
778908
+ try {
778909
+ const fileMetadata = {
778910
+ name: folderName,
778911
+ mimeType: "application/vnd.google-apps.folder"
778912
+ };
778913
+ if (parentFolderId) {
778914
+ fileMetadata.parents = [parentFolderId];
778915
+ }
778916
+ const response = await this.drive.files.create({
778917
+ requestBody: fileMetadata,
778918
+ fields: "id, name, mimeType"
778919
+ });
778920
+ return {
778921
+ success: true,
778922
+ data: response.data
778923
+ };
778924
+ } catch (error) {
778925
+ return {
778926
+ success: false,
778927
+ error: error instanceof Error ? error.message : "Unknown error"
778928
+ };
778929
+ }
778930
+ }
778931
+ async searchFiles(searchQuery, pageSize = 10) {
778932
+ return this.listFiles({
778933
+ query: searchQuery,
778934
+ pageSize
778935
+ });
778936
+ }
778937
+ }
778938
+
778738
778939
  // drivers/services.ts
778739
778940
  var driveService;
778941
+ async function initDriveService(creds, tokens) {
778942
+ if (!driveService) {
778943
+ const credentials = creds ?? JSON.parse(fs3.readFileSync("./credentials.json", "utf-8"));
778944
+ driveService = new GoogleDriveService(credentials);
778945
+ const tokenData = tokens ?? JSON.parse(fs3.readFileSync("./tokens.json", "utf-8"));
778946
+ driveService.setCredentials(tokenData);
778947
+ }
778948
+ return driveService;
778949
+ }
778740
778950
 
778741
778951
  // types/index.ts
778742
778952
  var MIME_TYPES = {
@@ -778982,8 +779192,8 @@ var driveOperations = {
778982
779192
  };
778983
779193
 
778984
779194
  // auth.ts
778985
- var import_googleapis = __toESM(require_src8(), 1);
778986
- import * as fs2 from "fs";
779195
+ var import_googleapis2 = __toESM(require_src8(), 1);
779196
+ import * as fs4 from "fs";
778987
779197
  import * as http3 from "http";
778988
779198
  import * as url from "url";
778989
779199
  var CREDENTIALS_PATH = "./credentials.json";
@@ -778992,12 +779202,10 @@ async function generateCredentialsAndTokens({
778992
779202
  clientid,
778993
779203
  projectid,
778994
779204
  clientsecret,
778995
- redirecturis = [
778996
- "http://localhost:3000/oauth2callback",
778997
- "http://localhost:3000/oauth2/callback"
778998
- ]
779205
+ redirecturis,
779206
+ javascript_origin
778999
779207
  }) {
779000
- if (!fs2.existsSync(CREDENTIALS_PATH)) {
779208
+ if (!fs4.existsSync(CREDENTIALS_PATH)) {
779001
779209
  const baseCredentials = {
779002
779210
  web: {
779003
779211
  client_id: clientid,
@@ -779006,21 +779214,21 @@ async function generateCredentialsAndTokens({
779006
779214
  token_uri: "https://oauth2.googleapis.com/token",
779007
779215
  auth_provider_x509_cert_url: "https://www.googleapis.com/oauth2/v1/certs",
779008
779216
  client_secret: clientsecret,
779009
- redirect_uris: redirecturis,
779010
- javascript_origins: ["http://localhost:3000"]
779217
+ redirect_uris: redirecturis || ["http://localhost:3000/oauth2callback", "http://localhost:3000/oauth2/callback"],
779218
+ javascript_origins: javascript_origin || ["http://localhost:3000"]
779011
779219
  }
779012
779220
  };
779013
- fs2.writeFileSync(CREDENTIALS_PATH, JSON.stringify(baseCredentials, null, 2));
779221
+ fs4.writeFileSync(CREDENTIALS_PATH, JSON.stringify(baseCredentials, null, 2));
779014
779222
  console.log("βœ… Created credentials.json");
779015
779223
  }
779016
- const credentials = JSON.parse(fs2.readFileSync(CREDENTIALS_PATH, "utf-8"));
779224
+ const credentials = JSON.parse(fs4.readFileSync(CREDENTIALS_PATH, "utf-8"));
779017
779225
  const creds = credentials.web || credentials.installed || credentials;
779018
779226
  const client_id = creds.client_id;
779019
779227
  const client_secret = creds.client_secret;
779020
779228
  const redirect_uri = Array.isArray(creds.redirect_uris) ? creds.redirect_uris[0] : creds.redirect_uri;
779021
- const oauth2Client = new import_googleapis.google.auth.OAuth2(client_id, client_secret, redirect_uri);
779022
- if (fs2.existsSync(TOKENS_PATH)) {
779023
- const tokens = JSON.parse(fs2.readFileSync(TOKENS_PATH, "utf-8"));
779229
+ const oauth2Client = new import_googleapis2.google.auth.OAuth2(client_id, client_secret, redirect_uri);
779230
+ if (fs4.existsSync(TOKENS_PATH)) {
779231
+ const tokens = JSON.parse(fs4.readFileSync(TOKENS_PATH, "utf-8"));
779024
779232
  oauth2Client.setCredentials(tokens);
779025
779233
  console.log("βœ… Using existing tokens from tokens.json");
779026
779234
  return oauth2Client;
@@ -779049,7 +779257,7 @@ async function generateCredentialsAndTokens({
779049
779257
  throw new Error("No authorization code received");
779050
779258
  const { tokens } = await oauth2Client.getToken(code);
779051
779259
  oauth2Client.setCredentials(tokens);
779052
- fs2.writeFileSync(TOKENS_PATH, JSON.stringify(tokens, null, 2));
779260
+ fs4.writeFileSync(TOKENS_PATH, JSON.stringify(tokens, null, 2));
779053
779261
  console.log("βœ… Tokens saved to tokens.json");
779054
779262
  res.writeHead(200, { "Content-Type": "text/html" });
779055
779263
  res.end(`
@@ -779091,5 +779299,6 @@ async function generateCredentialsAndTokens({
779091
779299
  }
779092
779300
  export {
779093
779301
  exports_operations as operations,
779302
+ initDriveService,
779094
779303
  generateCredentialsAndTokens
779095
779304
  };
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "gdrivekit",
3
- "version": "1.0.0",
4
- "description": "A lightweight Bun + TypeScript package for Google Drive OAuth2 authentication and file operations.",
3
+ "version": "1.0.3",
4
+ "description": "A lightweight Google Drive toolkit for File Management. Handle Google Drive operations easily β€” upload, download, and other file operations in a few lines of code.",
5
5
  "type": "module",
6
- "main": "index.ts",
7
- "types": "index.ts",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
8
  "scripts": {
9
9
  "dev": "bun run index.ts",
10
10
  "build": "bun build ./index.ts --outdir dist --target node",
@@ -12,13 +12,27 @@
12
12
  },
13
13
  "keywords": [
14
14
  "google-drive",
15
- "bun",
16
- "typescript",
15
+ "google drive",
16
+ "googledrive",
17
+ "gdrive",
18
+ "drive-api",
17
19
  "googleapis",
18
- "oauth2"
20
+ "google drive api",
21
+ "google drive oauth2",
22
+ "google drive upload",
23
+ "google drive automation",
24
+ "gdrivekit"
19
25
  ],
20
26
  "author": "Vikash Khati",
21
27
  "license": "MIT",
28
+ "repository": {
29
+ "type": "git",
30
+ "url": "https://github.com/vikashkhati007/gdrivekit"
31
+ },
32
+ "homepage": "https://www.npmjs.com/package/gdrivekit",
33
+ "bugs": {
34
+ "url": "https://github.com/vikashkhati007/gdrivekit/issues"
35
+ },
22
36
  "dependencies": {
23
37
  "googleapis": "^164.1.0"
24
38
  },
package/index.ts DELETED
@@ -1,3 +0,0 @@
1
- import * as operations from "./operations";
2
- import { generateCredentialsAndTokens } from "./auth";
3
- export { generateCredentialsAndTokens, operations };