@d0whc3r/node-gdrive 3.4.0 → 3.5.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/LICENSE +21 -0
- package/README.md +174 -92
- package/bin/cli.js +2 -2
- package/dist/auth.d.ts +25 -0
- package/dist/config.d.ts +16 -0
- package/dist/crypto.d.ts +4 -0
- package/dist/gdrive.cjs.js +1 -1
- package/dist/gdrive.esm.mjs +802 -0
- package/dist/index.d.ts +65 -48
- package/dist/retry.d.ts +3 -0
- package/dist/types.d.ts +96 -0
- package/package.json +82 -132
- package/dist/gdrive.esm.js +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,50 +1,67 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
import {
|
|
4
|
-
|
|
1
|
+
import type { Readable } from 'node:stream';
|
|
2
|
+
import { drive_v3 } from '@googleapis/drive';
|
|
3
|
+
import { ManipulateType } from 'dayjs';
|
|
4
|
+
import Auth from './auth';
|
|
5
|
+
import Config from './config';
|
|
6
|
+
import { decryptBuffer, decryptFile, encryptBuffer, encryptFile } from './crypto';
|
|
7
|
+
import { isRetryableError, withRetry } from './retry';
|
|
8
|
+
import { CleanOlderOptions, DownloadOptions, FieldsType, GDriveConfig, Schema$File$Modded, UploadOptions, UploadOptionsBasic, UploadStreamOptions } from './types';
|
|
9
|
+
export declare function escapeDriveQuery(value: string): string;
|
|
10
|
+
export declare function parseTimeSpace(timeSpace: string): {
|
|
11
|
+
amount: number;
|
|
12
|
+
unit: ManipulateType;
|
|
13
|
+
};
|
|
5
14
|
export declare class GDrive {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
15
|
+
readonly DEFAULT_FIELDS: FieldsType[];
|
|
16
|
+
private readonly MIME_FOLDER;
|
|
17
|
+
private readonly gdriveAuth?;
|
|
18
|
+
private readonly injectedAuth?;
|
|
19
|
+
private readonly sharedDriveId?;
|
|
20
|
+
private readonly defaultDryRun;
|
|
21
|
+
private readonly defaultConcurrency;
|
|
22
|
+
private readonly defaultCompressionLevel;
|
|
23
|
+
private readonly defaultOnProgress?;
|
|
24
|
+
private readonly retryOptions;
|
|
25
|
+
private readonly logger;
|
|
26
|
+
private _drive?;
|
|
27
|
+
private _initPromise?;
|
|
28
|
+
constructor(config?: GDriveConfig);
|
|
29
|
+
private ensureInitiated;
|
|
30
|
+
private get auth();
|
|
31
|
+
private get drive();
|
|
32
|
+
private get sharedDriveListParams();
|
|
33
|
+
private get sharedDriveItemParams();
|
|
34
|
+
private get rootParentId();
|
|
35
|
+
isFolder(file: drive_v3.Schema$File): boolean | undefined;
|
|
36
|
+
isDeleted(file: drive_v3.Schema$File): boolean;
|
|
37
|
+
listFiles(fields?: boolean | FieldsType[], pageSize?: number, q?: string): Promise<Schema$File$Modded[]>;
|
|
38
|
+
getFile(fileId?: string | null): Promise<drive_v3.Schema$File>;
|
|
39
|
+
downloadFile(fileIdOrName: string, destPath: string, options?: DownloadOptions): Promise<string>;
|
|
40
|
+
emptyTrash(): Promise<{
|
|
41
|
+
status: number;
|
|
42
|
+
data: unknown;
|
|
43
|
+
}>;
|
|
44
|
+
deleteFile(file: Schema$File$Modded): Promise<unknown>;
|
|
45
|
+
uploadFile(file: string, folderName?: string | boolean, options?: UploadOptionsBasic): Promise<Schema$File$Modded>;
|
|
46
|
+
uploadStream(stream: Readable, fileName: string, folderName?: string | boolean, options?: UploadStreamOptions): Promise<Schema$File$Modded>;
|
|
47
|
+
uploadFiles(files: string | string[], folderName?: string | boolean, options?: UploadOptions): Promise<Record<string, Schema$File$Modded>>;
|
|
48
|
+
cleanOlder(timeSpace: string, folderName?: string, options?: CleanOlderOptions): Promise<Schema$File$Modded[]>;
|
|
49
|
+
private expandFileInputs;
|
|
50
|
+
private getListFiles;
|
|
51
|
+
private replaceExistingFile;
|
|
52
|
+
private getUploadFolderId;
|
|
53
|
+
private deleteOlder;
|
|
54
|
+
private parseFileMeta;
|
|
55
|
+
private parseFilesMeta;
|
|
56
|
+
private genericError;
|
|
57
|
+
private readonly inFlightFolders;
|
|
58
|
+
private findFolderId;
|
|
59
|
+
private resolveFolderId;
|
|
60
|
+
private findFile;
|
|
61
|
+
private createFolder;
|
|
62
|
+
private createPrivateTempDir;
|
|
63
|
+
private sanitizeFilename;
|
|
64
|
+
private compressFiles;
|
|
35
65
|
}
|
|
36
|
-
export
|
|
37
|
-
export
|
|
38
|
-
isDeleted: boolean;
|
|
39
|
-
isFolder: boolean;
|
|
40
|
-
parentFolder?: string;
|
|
41
|
-
}
|
|
42
|
-
export interface UploadOptions extends UploadOptionsBasic {
|
|
43
|
-
compress?: string | boolean;
|
|
44
|
-
}
|
|
45
|
-
export interface UploadOptionsBasic {
|
|
46
|
-
create?: boolean;
|
|
47
|
-
replace?: boolean;
|
|
48
|
-
}
|
|
49
|
-
|
|
50
|
-
export {};
|
|
66
|
+
export { Auth, Config, decryptBuffer, decryptFile, encryptBuffer, encryptFile, isRetryableError, withRetry };
|
|
67
|
+
export * from './types';
|
package/dist/retry.d.ts
ADDED
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import type { drive_v3 } from '@googleapis/drive';
|
|
2
|
+
import type { GoogleAuth, OAuth2Client } from 'google-auth-library';
|
|
3
|
+
export type Params$Resource$Files$Get = drive_v3.Params$Resource$Files$Get;
|
|
4
|
+
export type Params$Resource$Files$List = drive_v3.Params$Resource$Files$List;
|
|
5
|
+
export type Params$Resource$Files$Create = drive_v3.Params$Resource$Files$Create;
|
|
6
|
+
export type Params$Resource$Files$Delete = drive_v3.Params$Resource$Files$Delete;
|
|
7
|
+
export declare const allFileTypes: readonly ['appProperties', 'capabilities', 'contentHints', 'createdTime', 'description', 'explicitlyTrashed', 'fileExtension', 'folderColorRgb', 'fullFileExtension', 'hasAugmentedPermissions', 'hasThumbnail', 'headRevisionId', 'iconLink', 'id', 'imageMediaMetadata', 'isAppAuthorized', 'lastModifyingUser', 'md5Checksum', 'mimeType', 'modifiedByMe', 'modifiedByMeTime', 'modifiedTime', 'name', 'originalFilename', 'ownedByMe', 'owners', 'parents', 'properties', 'quotaBytesUsed', 'shared', 'sharedWithMeTime', 'sharingUser', 'size', 'spaces', 'starred', 'teamDriveId', 'thumbnailLink', 'thumbnailVersion', 'trashed', 'trashedTime', 'trashingUser', 'version', 'videoMediaMetadata', 'viewedByMe', 'viewedByMeTime', 'viewersCanCopyContent', 'webContentLink', 'webViewLink', 'writersCanShare'];
|
|
8
|
+
export type FieldsType = (typeof allFileTypes)[number];
|
|
9
|
+
export interface Schema$File$Modded extends drive_v3.Schema$File {
|
|
10
|
+
isDeleted: boolean;
|
|
11
|
+
isFolder: boolean;
|
|
12
|
+
parentFolder?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface Logger {
|
|
15
|
+
info: (...args: unknown[]) => void;
|
|
16
|
+
warn: (...args: unknown[]) => void;
|
|
17
|
+
error: (...args: unknown[]) => void;
|
|
18
|
+
}
|
|
19
|
+
export interface UploadProgressEvent {
|
|
20
|
+
fileName: string;
|
|
21
|
+
bytesRead: number;
|
|
22
|
+
totalBytes: number;
|
|
23
|
+
percentage: number;
|
|
24
|
+
}
|
|
25
|
+
export interface RetryOptions {
|
|
26
|
+
maxRetries?: number;
|
|
27
|
+
baseDelayMs?: number;
|
|
28
|
+
maxDelayMs?: number;
|
|
29
|
+
jitter?: boolean;
|
|
30
|
+
sleep?: (ms: number) => Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
export interface AuthConfig {
|
|
33
|
+
credentialsFile?: string;
|
|
34
|
+
tokenFile?: string;
|
|
35
|
+
serviceAccountFile?: string;
|
|
36
|
+
useADC?: boolean;
|
|
37
|
+
scopes?: string[];
|
|
38
|
+
logger?: Logger;
|
|
39
|
+
}
|
|
40
|
+
export interface GDriveConfig extends AuthConfig {
|
|
41
|
+
sharedDriveId?: string;
|
|
42
|
+
dryRun?: boolean;
|
|
43
|
+
concurrency?: number;
|
|
44
|
+
compressionLevel?: number;
|
|
45
|
+
onProgress?: (event: UploadProgressEvent) => void;
|
|
46
|
+
retry?: RetryOptions;
|
|
47
|
+
auth?: OAuth2Client | GoogleAuth;
|
|
48
|
+
drive?: drive_v3.Drive;
|
|
49
|
+
}
|
|
50
|
+
export interface UploadOptionsBasic {
|
|
51
|
+
create?: boolean;
|
|
52
|
+
replace?: boolean;
|
|
53
|
+
dryRun?: boolean;
|
|
54
|
+
encryptKey?: string;
|
|
55
|
+
onProgress?: (event: UploadProgressEvent) => void;
|
|
56
|
+
}
|
|
57
|
+
export interface UploadOptions extends UploadOptionsBasic {
|
|
58
|
+
compress?: string | boolean;
|
|
59
|
+
compressionLevel?: number;
|
|
60
|
+
exclude?: string[];
|
|
61
|
+
followSymlinks?: boolean;
|
|
62
|
+
concurrency?: number;
|
|
63
|
+
}
|
|
64
|
+
export interface UploadStreamOptions extends UploadOptionsBasic {
|
|
65
|
+
mimeType?: string;
|
|
66
|
+
size?: number;
|
|
67
|
+
}
|
|
68
|
+
export interface CleanOlderOptions {
|
|
69
|
+
dryRun?: boolean;
|
|
70
|
+
keepLast?: number;
|
|
71
|
+
concurrency?: number;
|
|
72
|
+
}
|
|
73
|
+
export interface DownloadOptions {
|
|
74
|
+
decryptKey?: string;
|
|
75
|
+
folderName?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface Installed {
|
|
78
|
+
client_id: string;
|
|
79
|
+
project_id?: string;
|
|
80
|
+
auth_uri?: string;
|
|
81
|
+
token_uri?: string;
|
|
82
|
+
auth_provider_x509_cert_url?: string;
|
|
83
|
+
client_secret: string;
|
|
84
|
+
redirect_uris?: string[];
|
|
85
|
+
}
|
|
86
|
+
export interface CredentialsFile {
|
|
87
|
+
installed?: Installed;
|
|
88
|
+
web?: Installed;
|
|
89
|
+
}
|
|
90
|
+
export interface TokenFile {
|
|
91
|
+
access_token?: string | null;
|
|
92
|
+
refresh_token?: string | null;
|
|
93
|
+
scope?: string;
|
|
94
|
+
token_type?: string | null;
|
|
95
|
+
expiry_date?: number | null;
|
|
96
|
+
}
|
package/package.json
CHANGED
|
@@ -1,10 +1,21 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@d0whc3r/node-gdrive",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.5.0",
|
|
4
|
+
"keywords": [
|
|
5
|
+
"backup",
|
|
6
|
+
"compress",
|
|
7
|
+
"copy",
|
|
8
|
+
"drive",
|
|
9
|
+
"gdrive",
|
|
10
|
+
"google",
|
|
11
|
+
"googleapi",
|
|
12
|
+
"node",
|
|
13
|
+
"upload"
|
|
14
|
+
],
|
|
4
15
|
"license": "MIT",
|
|
5
16
|
"author": {
|
|
6
|
-
"email": "d0whc3r@gmail.com",
|
|
7
17
|
"name": "d0whc3r",
|
|
18
|
+
"email": "d0whc3r@gmail.com",
|
|
8
19
|
"url": "https://github.com/d0whc3r"
|
|
9
20
|
},
|
|
10
21
|
"repository": {
|
|
@@ -19,146 +30,85 @@
|
|
|
19
30
|
"bin"
|
|
20
31
|
],
|
|
21
32
|
"main": "dist/gdrive.cjs.js",
|
|
22
|
-
"module": "dist/gdrive.esm.
|
|
33
|
+
"module": "dist/gdrive.esm.mjs",
|
|
23
34
|
"types": "dist/index.d.ts",
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
|
|
35
|
+
"exports": {
|
|
36
|
+
".": {
|
|
37
|
+
"types": "./dist/index.d.ts",
|
|
38
|
+
"import": "./dist/gdrive.esm.mjs",
|
|
39
|
+
"require": "./dist/gdrive.cjs.js"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"registry": "https://registry.npmjs.org"
|
|
45
|
+
},
|
|
35
46
|
"scripts": {
|
|
36
|
-
"
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"build:
|
|
43
|
-
"build:
|
|
44
|
-
"build:
|
|
45
|
-
"
|
|
46
|
-
"build
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
"
|
|
51
|
-
"
|
|
52
|
-
"
|
|
53
|
-
"
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"coverage:codecovs": "curl -s https://codecov.io/bash | bash",
|
|
58
|
-
"coverage:coveralls": "cat ./coverage/lcov.info | coveralls",
|
|
59
|
-
"coverage:codacy": "wget -q https://coverage.codacy.com/get.sh && bash get.sh report -l typescript -r coverage/lcov.info",
|
|
60
|
-
"postversion": "git push --follow-tags",
|
|
61
|
-
"eslint": "eslint -c .eslintrc.js --ext .ts,.js src cli",
|
|
62
|
-
"eslint:fix": "yarn eslint --fix",
|
|
63
|
-
"format": "pretty-quick \"{src,cli}/**/*.ts\" --write --staged",
|
|
64
|
-
"commit": "git-cz",
|
|
47
|
+
"clean": "node -e \"import('node:fs').then(fs => ['dist','bin','build','coverage','node-gdrive','node-gdrive.exe'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))\"",
|
|
48
|
+
"cli:dev": "node --env-file=.env cli/cli.ts",
|
|
49
|
+
"cli": "node cli/cli.ts",
|
|
50
|
+
"typecheck": "tsc --noEmit",
|
|
51
|
+
"build:clean": "node -e \"import('node:fs').then(fs => ['dist','bin'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))\"",
|
|
52
|
+
"build:lib": "vite build --config vite.config.mts",
|
|
53
|
+
"build:cli": "vite build --config vite.cli.config.mts",
|
|
54
|
+
"build:dts": "tsc -p tsconfig.build.json --emitDeclarationOnly",
|
|
55
|
+
"build:base": "pnpm build:clean && pnpm build:lib && pnpm build:cli && pnpm build:dts",
|
|
56
|
+
"build:sea": "vite build --config vite.sea.config.mts && node scripts/build-sea.mjs",
|
|
57
|
+
"build": "pnpm build:base && pnpm build:sea",
|
|
58
|
+
"test": "vitest run",
|
|
59
|
+
"test:unit": "vitest run --exclude tests/gdrive.integration.spec.ts",
|
|
60
|
+
"test:integration": "vitest run tests/gdrive.integration.spec.ts",
|
|
61
|
+
"test:watch": "vitest",
|
|
62
|
+
"test:coverage": "vitest run --coverage",
|
|
63
|
+
"lint": "oxlint",
|
|
64
|
+
"lint:fix": "oxlint --fix",
|
|
65
|
+
"format": "oxfmt --write",
|
|
66
|
+
"format:check": "oxfmt --check",
|
|
67
|
+
"prepare": "husky",
|
|
65
68
|
"semantic-release": "semantic-release"
|
|
66
69
|
},
|
|
67
70
|
"dependencies": {
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"command-line-args": "
|
|
71
|
-
"command-line-usage": "
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"mime-types": "
|
|
75
|
-
"
|
|
76
|
-
"mysqldump": "3.2.0"
|
|
71
|
+
"@googleapis/drive": "^27.1.0",
|
|
72
|
+
"archiver": "^8.0.0",
|
|
73
|
+
"command-line-args": "^6.0.2",
|
|
74
|
+
"command-line-usage": "^7.0.4",
|
|
75
|
+
"dayjs": "^1.11.23",
|
|
76
|
+
"google-auth-library": "^11.3.4",
|
|
77
|
+
"mime-types": "^3.0.2",
|
|
78
|
+
"mysqldump": "^3.2.0"
|
|
77
79
|
},
|
|
78
80
|
"devDependencies": {
|
|
79
|
-
"@
|
|
80
|
-
"@
|
|
81
|
-
"@
|
|
82
|
-
"@
|
|
83
|
-
"@
|
|
84
|
-
"@
|
|
85
|
-
"@
|
|
86
|
-
"@
|
|
87
|
-
"@
|
|
88
|
-
"@types/
|
|
89
|
-
"@types/command-line-
|
|
90
|
-
"@types/
|
|
91
|
-
"@types/
|
|
92
|
-
"@
|
|
93
|
-
"
|
|
94
|
-
"
|
|
95
|
-
"
|
|
96
|
-
"
|
|
97
|
-
"
|
|
98
|
-
"
|
|
99
|
-
"
|
|
100
|
-
"
|
|
101
|
-
"coveralls": "3.1.0",
|
|
102
|
-
"cz-conventional-changelog": "3.2.0",
|
|
103
|
-
"dotenv": "8.2.0",
|
|
104
|
-
"dotenv-cli": "3.2.0",
|
|
105
|
-
"dts-bundle-generator": "5.0.0",
|
|
106
|
-
"esbuild": "0.5.21",
|
|
107
|
-
"eslint": "7.4.0",
|
|
108
|
-
"eslint-config-prettier": "6.11.0",
|
|
109
|
-
"eslint-plugin-prettier": "3.1.4",
|
|
110
|
-
"eslint-plugin-sonarjs": "0.5.0",
|
|
111
|
-
"find-node-modules": "2.0.0",
|
|
112
|
-
"google-auth-library": "6.0.2",
|
|
113
|
-
"husky": "4.2.5",
|
|
114
|
-
"jest": "26.1.0",
|
|
115
|
-
"jest-chain": "1.1.5",
|
|
116
|
-
"jest-extended": "0.11.5",
|
|
117
|
-
"jest-junit": "11.0.1",
|
|
118
|
-
"jest-sonar-reporter": "2.0.0",
|
|
119
|
-
"lint-staged": "10.2.11",
|
|
120
|
-
"mock-stdin": "1.0.0",
|
|
121
|
-
"nock": "13.0.2",
|
|
122
|
-
"npm-run-all": "4.1.5",
|
|
123
|
-
"pkg": "4.4.9",
|
|
124
|
-
"prettier": "2.0.5",
|
|
125
|
-
"pretty-quick": "2.0.1",
|
|
126
|
-
"regenerator-runtime": "0.13.5",
|
|
127
|
-
"rimraf": "3.0.2",
|
|
128
|
-
"rollup": "2.19.0",
|
|
129
|
-
"rollup-plugin-auto-external": "2.0.0",
|
|
130
|
-
"rollup-plugin-esbuild": "2.1.0",
|
|
131
|
-
"rollup-plugin-node-builtins": "2.1.2",
|
|
132
|
-
"semantic-release": "^17.1.1",
|
|
133
|
-
"sonar-scanner": "3.1.0",
|
|
134
|
-
"ts-jest": "26.1.1",
|
|
135
|
-
"ts-node": "8.10.2",
|
|
136
|
-
"tsconfig-paths": "3.9.0",
|
|
137
|
-
"typescript": "3.9.6"
|
|
138
|
-
},
|
|
139
|
-
"jestSonar": {
|
|
140
|
-
"reportPath": "coverage",
|
|
141
|
-
"reportFile": "test-report.xml"
|
|
142
|
-
},
|
|
143
|
-
"jest-junit": {
|
|
144
|
-
"outputDirectory": "./coverage",
|
|
145
|
-
"outputName": "./junit.xml"
|
|
146
|
-
},
|
|
147
|
-
"husky": {
|
|
148
|
-
"hooks": {
|
|
149
|
-
"pre-commit": "yarn eslint:fix && lint-staged",
|
|
150
|
-
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
|
|
151
|
-
}
|
|
81
|
+
"@commitlint/cli": "^21.2.4",
|
|
82
|
+
"@commitlint/config-conventional": "^21.2.4",
|
|
83
|
+
"@semantic-release/changelog": "^7.0.0",
|
|
84
|
+
"@semantic-release/commit-analyzer": "^13.0.1",
|
|
85
|
+
"@semantic-release/git": "^11.0.1",
|
|
86
|
+
"@semantic-release/github": "^12.0.11",
|
|
87
|
+
"@semantic-release/npm": "^13.2.0",
|
|
88
|
+
"@semantic-release/release-notes-generator": "^14.1.1",
|
|
89
|
+
"@types/archiver": "^8.0.0",
|
|
90
|
+
"@types/command-line-args": "^5.2.3",
|
|
91
|
+
"@types/command-line-usage": "^5.0.4",
|
|
92
|
+
"@types/mime-types": "^3.0.1",
|
|
93
|
+
"@types/node": "^26.6.10",
|
|
94
|
+
"@vitest/coverage-v8": "^5.1.2",
|
|
95
|
+
"husky": "^9.1.7",
|
|
96
|
+
"lint-staged": "^17.6.2",
|
|
97
|
+
"oxfmt": "^0.80.0",
|
|
98
|
+
"oxlint": "^1.95.0",
|
|
99
|
+
"semantic-release": "^26.0.1",
|
|
100
|
+
"typescript": "^7.0.2",
|
|
101
|
+
"vite": "^8.3.8",
|
|
102
|
+
"vitest": "^5.1.2"
|
|
152
103
|
},
|
|
153
104
|
"lint-staged": {
|
|
154
|
-
"{src,cli}/**/*.ts": [
|
|
155
|
-
"
|
|
105
|
+
"{src,cli,tests}/**/*.ts": [
|
|
106
|
+
"pnpm lint:fix",
|
|
107
|
+
"pnpm format"
|
|
156
108
|
]
|
|
157
109
|
},
|
|
158
|
-
"
|
|
159
|
-
"
|
|
110
|
+
"engines": {
|
|
111
|
+
"node": ">=26.0.0"
|
|
160
112
|
},
|
|
161
|
-
"
|
|
162
|
-
"path": "node_modules/cz-conventional-changelog"
|
|
163
|
-
}
|
|
113
|
+
"packageManager": "pnpm@12.16.1"
|
|
164
114
|
}
|
package/dist/gdrive.esm.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{google as t,drive_v3 as q}from"googleapis";import m,{existsSync as r,mkdirSync as z,readFileSync as u,writeFile as A}from"fs";import B from"mime-types";import n,{isAbsolute as C,resolve as D,sep as E}from"path";import F from"archiver";import s from"moment";import v from"glob";import G from"readline";import w from"colors";import H from"os";class f{}f.TOKEN_FILE=process.env.TOKEN_FILE||"./secrets/token.json",f.CREDENTIALS_FILE=process.env.CREDENTIALS_FILE||"./secrets/credentials.json",f.TAG="[node-gdrive]";class I{static mkdirp(a){const c=E,d=C(a)?c:"",b=a.split(c).reduce((j,i)=>{const e=D(j,i);return r(e)||z(e),e},d);console.info(`${f.TAG} Result file ${b}`)}}class J{constructor(){this.ready=!0,this.SCOPES=["https://www.googleapis.com/auth/drive","https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive.metadata","https://www.googleapis.com/auth/drive.metadata.readonly"],this.TOKEN_FILE=f.TOKEN_FILE,this.CREDENTIALS_FILE=f.CREDENTIALS_FILE,this.existsCredentials||(this.ready=!1,console.error(w.bold(`${f.TAG} ERROR: Credentials file not found in ${this.CREDENTIALS_FILE}`).red))}get existsToken(){return r(this.TOKEN_FILE)}get existsCredentials(){return r(this.CREDENTIALS_FILE)}async initiate(){return this.ready?this.existsToken?Promise.resolve(!0):this.generateAccessToken():Promise.reject(!1)}oAuth2Client(a=!0){if(!this._oAuth2Client){const c=JSON.parse(u(this.CREDENTIALS_FILE,"utf8")),{client_secret:d,client_id:b,redirect_uris:j}=c.installed;this._oAuth2Client=new t.auth.OAuth2(b,d,j[0]);if(a){const i=JSON.parse(u(this.TOKEN_FILE,"utf8"));this._oAuth2Client.setCredentials(i)}}return this._oAuth2Client}generateAccessToken(){return new Promise((a,c)=>{const d=this.oAuth2Client(!1).generateAuthUrl({access_type:"offline",scope:this.SCOPES});console.log(`${f.TAG} Authorize this app by visiting this url:`,d);const b=G.createInterface({input:process.stdin,output:process.stdout});b.question(`${f.TAG} Enter the code from that page here: `,j=>{b.close(),this.oAuthGetToken(j,{resolve:a,reject:c})})})}oAuthGetToken(a,c){this.oAuth2Client(!1).getToken(a).then(({tokens:d})=>{this.oAuth2Client(!1).setCredentials(d),this.writeToken(d,c)}).catch(d=>(console.error(w.bold(`${f.TAG} Error retrieving access token`).red,d.message),c.reject(d)))}writeToken(a,{resolve:c,reject:d}){A(this.TOKEN_FILE,JSON.stringify(a),b=>{b?(console.error(b),void d(b)):(console.log(`${f.TAG} Token stored to`,this.TOKEN_FILE),void c(!0))})}}var X=q.Params$Resource$Files$Get,Y=q.Params$Resource$Files$List,Z=q.Params$Resource$Files$Create;const K=["appProperties","capabilities","contentHints","createdTime","description","explicitlyTrashed","fileExtension","folderColorRgb","fullFileExtension","hasAugmentedPermissions","hasThumbnail","headRevisionId","iconLink","id","imageMediaMetadata","isAppAuthorized","lastModifyingUser","md5Checksum","mimeType","modifiedByMe","modifiedByMeTime","modifiedTime","name","originalFilename","ownedByMe","owners","parents","properties","quotaBytesUsed","shared","sharedWithMeTime","sharingUser","size","spaces","starred","teamDriveId","thumbnailLink","thumbnailVersion","trashed","trashedTime","trashingUser","version","videoMediaMetadata","viewedByMe","viewedByMeTime","viewersCanCopyContent","webContentLink","webViewLink","writersCanShare"];class L{constructor(){this.DEFAULT_FIELDS=["createdTime","id","md5Checksum","mimeType","name","parents","trashed"],this.MIME_FOLDER="application/vnd.google-apps.folder",this.gdriveAuth=new J(),this.initiated=this.gdriveAuth.initiate(),this.initiated.catch(()=>{const a=`${f.TAG} ERROR! could not get credentials file. GDrive will not work`;throw console.error(a),new Error(a)})}get auth(){return this.gdriveAuth.oAuth2Client(!0)}get drive(){return t.drive({version:"v3",auth:this.auth})}isFolder(a){return Object.prototype.hasOwnProperty.call(a,"mimeType")?a.mimeType===this.MIME_FOLDER:void 0}isDeleted(a){return Object.prototype.hasOwnProperty.call(a,"trashed")?!!a.trashed:!1}async listFiles(a,c=50){await this.initiated,a?a===!0&&(a=K):a=this.DEFAULT_FIELDS;const d={pageSize:c,fields:`kind, nextPageToken, incompleteSearch, files(${a.join(", ")})`,prettyPrint:!0,includeTeamDriveItems:!1};return this.getListFiles(d)}async getFile(a){await this.initiated;if(!a)return Promise.reject(this.genericError(new Error("File id not found")));const c={fileId:a},d=this.drive.files.get(c).then(({data:b})=>b);return d.catch(b=>{this.genericError(b)}),d}async emptyTrash(){return await this.initiated,this.drive.files.emptyTrash()}async deleteFile(a){await this.initiated;if(a.id){const c=this.drive.files.delete({fileId:a.id}).then(({data:d})=>(a.name&&console.warn(`${f.TAG} Deleted ${a.isFolder?"folder":"file"}: ${a.name}`),d));return c.catch(d=>{this.genericError(d)}),c}}async uploadFile(a,c,d={}){await this.initiated;const{create:b=!0,replace:j=!1}=d,i=n.basename(a),e=B.contentType(i)||void 0,l={name:i,mimeType:e};let g=null;try{g=await this.getUploadFolderId(c||!1,b,l)}catch(k){return Promise.reject(k)}try{await this.replaceExistingFolder(j,i,g)}catch(k){return Promise.reject(k)}const h=m.createReadStream(a),o={requestBody:l,media:{body:h},fields:`kind, ${this.DEFAULT_FIELDS.join(", ")}`},p=m.statSync(a).size,M=k=>{const y=k.bytesRead/p*100;y===100&&console.warn(`${f.TAG} Upload ${i}: ${Math.round(y)}% complete`)},x=this.drive.files.create(o,{onUploadProgress:M}).then(({data:k})=>this.parseFileMeta(k)).finally(()=>{h.destroy()});return x.catch(k=>{this.genericError(k)}),x}async uploadFiles(a,c,d={}){await this.initiated;const{compress:b,replace:j,create:i}=d;Array.isArray(a)||(a=[a]);let e=a;if(b){let g=b;typeof g!=="string"&&(g=`zipped_${s().format("YYYY-MM-DD.HHmmss")}.zip`);const h=await this.compressFiles(a,g);e=[h]}const l={};for(const g of e)if(g.includes("*"))await this.uploadFiles(v.sync(g),c,d);else if(m.lstatSync(g).isDirectory())await this.uploadFiles(v.sync(`${g}/*`),c,d);else{const h=n.basename(g),o=await this.uploadFile(g,c,{replace:j,create:i});l[h]=this.parseFileMeta(o)}return l}async cleanOlder(a,c){const d=/([0-9]+)(\w+)/.exec(a);if(!d)return console.error(`${f.TAG} Unknown timesSpace "${a}"`),Promise.reject(!1);await this.initiated;let b="";if(c)try{b=await this.findFolderId(c,!1)}catch(j){return console.error("Could not find folder",c,j),Promise.reject(!1)}await this.deleteOlder(d,b)}getListFiles(a,c=[]){const d=this.drive.files.list(a).then(async({data:b})=>(c=c.concat(b.files),b.nextPageToken?(a.pageToken=b.nextPageToken,this.getListFiles(a,c)):c)).then(b=>this.parseFilesMeta(b));return d.catch(b=>{this.genericError(b)}),d}async replaceExistingFolder(a,c,d){if(a!==void 0){const b=await this.findFile(c,d);if(b)if(a)console.warn(`${f.TAG} File "${c}" already exists and will be deleted before upload`),await this.deleteFile(b);else throw new Error(`${f.TAG} File "${c}" already exists and will not be replaced`)}}async getUploadFolderId(a,c,d){let b="";if(a&&typeof a==="string"){b=await this.findFolderId(a,c===void 0?!0:c);if(b)d.parents=[b];else return Promise.reject(new Error(`${f.TAG} Folder "${a}" does not exists and will not be created`))}return Promise.resolve(b)}async deleteOlder(a,c){const d=await this.listFiles();if(d&&d.length){const[,b,j]=a,i=d.filter(e=>!c||c&&!e.isFolder).filter(e=>!c||c&&e.parents&&e.parents.includes(c)).map(e=>({...e,toDelete:s(e.createdTime||void 0).isSameOrBefore(s().subtract(+b,j))})).filter(e=>e.toDelete);if(i&&i.length)for(const e of i)await this.deleteFile(e)}}parseFileMeta(a){return{...a,isDeleted:this.isDeleted(a),isFolder:!!this.isFolder(a)}}parseFilesMeta(a){return[...a].map(c=>this.parseFileMeta(c))}genericError(a){return console.error(`${f.TAG} The API returned an error: ${a}`),a}async findFolderId(a,c=!1){const d=(await this.listFiles()).filter(b=>b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).map(b=>b.id);if(d&&d.length)return Promise.resolve(d[0]||"");if(c){const b=await this.createFolder(a);return Promise.resolve(b.id||"")}return Promise.reject(!1)}async findFile(a,c){const d=(await this.listFiles()).filter(b=>!b.isFolder).filter(b=>!b.isDeleted).filter(b=>b.name===a).filter(b=>!c||b.parents&&b.parents.some(j=>j===c));return d&&d.length?d[0]:null}async createFolder(a){const c=this.drive.files.create({requestBody:{name:a,mimeType:this.MIME_FOLDER},fields:"id"}).then(({data:b})=>b);c.catch(b=>{this.genericError(b)});const d=await c;return d?.id&&console.warn(`${f.TAG} Created folder "${a}" with id: "${d.id}"`),d}compressFiles(a,c){return new Promise((d,b)=>{const j=H.tmpdir(),i=n.resolve(j,c);I.mkdirp(n.dirname(i));const e=m.createWriteStream(i),l=[],g=F("zip",{zlib:{level:9}});e.on("close",()=>{d(i),e.destroy()}),e.on("end",()=>{d(i),e.destroy()}),g.on("warning",h=>{console.warn(`${f.TAG} Warning compressing file`,h),h.code!=="ENOENT"&&b(h)}),g.on("error",h=>{console.error(`${f.TAG} Error compressing file`),b(h)}),g.pipe(e),a.forEach(h=>{if(h.includes("*"))g.glob(h);else if(m.lstatSync(h).isDirectory())g.directory(h,!1);else{const o=n.basename(h),p=m.createReadStream(h);g.append(p,{name:o}),l.push(p)}}),g.finalize().finally(()=>{l.forEach(h=>{h.destroy()})})})}}export{L as GDrive};
|