@d0whc3r/node-s3 1.3.12 → 1.4.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 +226 -72
- package/bin/cli.js +2 -2
- package/dist/config.d.ts +36 -0
- package/dist/crypto.d.ts +3 -0
- package/dist/index.d.ts +31 -44
- package/dist/s3/buckets.d.ts +12 -0
- package/dist/s3/files.d.ts +37 -0
- package/dist/s3.cjs.js +2 -2
- package/dist/s3.es.mjs +772 -3
- package/dist/types.d.ts +55 -0
- package/package.json +81 -133
- package/CHANGELOG.md +0 -64
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2020-present d0whc3r
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,110 +1,264 @@
|
|
|
1
|
+
# node-s3
|
|
1
2
|
|
|
2
|
-
|
|
3
|
+
CLI and Node.js library to back up, restore, encrypt, and prune files on **AWS S3**, **Cloudflare R2**, **Backblaze B2**, **MinIO**, and any S3-compatible storage—works via **Docker**, **npx/npm**, or as a **standalone binary** (Linux, macOS, Windows).
|
|
3
4
|
|
|
4
|
-
|
|
5
|
+
[](https://github.com/d0whc3r/node-s3/actions/workflows/nodejs.yml)
|
|
6
|
+
[](https://www.npmjs.com/package/@d0whc3r/node-s3)
|
|
7
|
+
[](https://hub.docker.com/r/d0whc3r/s3)
|
|
8
|
+
[](https://nodejs.org/)
|
|
9
|
+
[](./LICENSE)
|
|
5
10
|
|
|
6
|
-
|
|
11
|
+
---
|
|
7
12
|
|
|
8
|
-
|
|
9
|
-
[](https://github.com/d0whc3r/node-s3)
|
|
13
|
+
## Ways to Run
|
|
10
14
|
|
|
11
|
-
|
|
12
|
-
[](https://www.codacy.com/manual/d0whc3r/node-s3?utm_source=github.com&utm_medium=referral&utm_content=d0whc3r/node-s3&utm_campaign=Badge_Grade)
|
|
15
|
+
### 1. Docker (No Node.js required)
|
|
13
16
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
[](https://sonarcloud.io/dashboard?id=d0whc3r_node-s3)
|
|
17
|
-
[](https://sonarcloud.io/dashboard?id=d0whc3r_node-s3)
|
|
18
|
-
[](https://sonarcloud.io/dashboard?id=d0whc3r_node-s3)
|
|
17
|
+
```bash
|
|
18
|
+
docker run --rm d0whc3r/s3 --help
|
|
19
19
|
|
|
20
|
-
|
|
21
|
-
|
|
20
|
+
# Back up a local directory into S3
|
|
21
|
+
docker run --rm \
|
|
22
|
+
-e AWS_ACCESS_KEY_ID -e AWS_SECRET_ACCESS_KEY -e AWS_REGION -e BUCKET \
|
|
23
|
+
-v "$PWD/data:/data:ro" \
|
|
24
|
+
d0whc3r/s3 -b /data -z backup.zip -f daily -c -r
|
|
25
|
+
```
|
|
22
26
|
|
|
23
|
-
|
|
24
|
-
[](https://hub.docker.com/r/d0whc3r/s3)
|
|
25
|
-
[](https://hub.docker.com/r/d0whc3r/s3)
|
|
27
|
+
### 2. npx / npm (Node.js >= 26)
|
|
26
28
|
|
|
27
|
-
|
|
29
|
+
```bash
|
|
30
|
+
# Run on demand
|
|
31
|
+
npx @d0whc3r/node-s3 --help
|
|
28
32
|
|
|
29
|
-
|
|
33
|
+
# Or install globally
|
|
34
|
+
npm install -g @d0whc3r/node-s3
|
|
35
|
+
node-s3 --help
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### 3. Standalone Binary (No Node.js required)
|
|
30
39
|
|
|
31
|
-
|
|
40
|
+
Download the prebuilt `node-s3` (Linux / macOS) or `node-s3.exe` (Windows) executable from [GitHub Releases](https://github.com/d0whc3r/node-s3/releases) and run it directly:
|
|
32
41
|
|
|
33
|
-
|
|
42
|
+
```bash
|
|
43
|
+
chmod +x ./node-s3
|
|
44
|
+
./node-s3 --help
|
|
45
|
+
```
|
|
34
46
|
|
|
35
|
-
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Provider Setup Examples
|
|
50
|
+
|
|
51
|
+
### AWS S3
|
|
36
52
|
|
|
37
53
|
```bash
|
|
38
|
-
|
|
54
|
+
export AWS_ACCESS_KEY_ID="AKIA..."
|
|
55
|
+
export AWS_SECRET_ACCESS_KEY="..."
|
|
56
|
+
export AWS_REGION="eu-central-1"
|
|
57
|
+
|
|
58
|
+
node-s3 --bucket my-backups -b ./data -z backup.zip --storage-class STANDARD_IA --sse AES256
|
|
39
59
|
```
|
|
40
60
|
|
|
41
|
-
|
|
61
|
+
### Cloudflare R2
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
export AWS_ENDPOINT_URL="https://<account-id>.r2.cloudflarestorage.com"
|
|
65
|
+
export AWS_ACCESS_KEY_ID="..."
|
|
66
|
+
export AWS_SECRET_ACCESS_KEY="..."
|
|
67
|
+
export AWS_REGION="auto"
|
|
42
68
|
|
|
43
|
-
-
|
|
44
|
-
|
|
45
|
-
- `SECRET_KEY`: Secret key to use (required)
|
|
46
|
-
- `BUCKET`: Bucket name to connect (it could be created using `-c` or it could be defined in commandline with `--bucket`)
|
|
47
|
-
- `MAX_RETRIES`: Maximum retry connections when fail (optional, example: 3)
|
|
48
|
-
- `FORCE_PATH_STYLE`: Force path style (optional, example: true)
|
|
49
|
-
- `SSL_ENABLED`: Enable ssl connection to endpoint (optional, example: false)
|
|
69
|
+
node-s3 --bucket my-r2-bucket -l
|
|
70
|
+
```
|
|
50
71
|
|
|
51
|
-
|
|
72
|
+
### Backblaze B2
|
|
52
73
|
|
|
53
|
-
|
|
74
|
+
```bash
|
|
75
|
+
export AWS_ENDPOINT_URL="https://s3.us-west-004.backblazeb2.com"
|
|
76
|
+
export AWS_ACCESS_KEY_ID="..."
|
|
77
|
+
export AWS_SECRET_ACCESS_KEY="..."
|
|
78
|
+
export AWS_REGION="us-west-004"
|
|
54
79
|
|
|
55
|
-
|
|
80
|
+
node-s3 --bucket my-b2-bucket -b ./archive.tar.gz -f daily
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
### MinIO (Local / Self-Hosted)
|
|
56
84
|
|
|
57
85
|
```bash
|
|
58
|
-
|
|
86
|
+
export ENDPOINT="http://localhost:9000"
|
|
87
|
+
export ACCESS_KEY="minioadmin"
|
|
88
|
+
export SECRET_KEY="minioadmin"
|
|
89
|
+
export SSL_ENABLED="false"
|
|
90
|
+
|
|
91
|
+
node-s3 --bucket local-backups -c -b "./files/*"
|
|
59
92
|
```
|
|
60
93
|
|
|
61
|
-
|
|
94
|
+
---
|
|
95
|
+
|
|
96
|
+
## Common Usage Examples
|
|
62
97
|
|
|
63
98
|
```bash
|
|
64
|
-
|
|
99
|
+
# List objects (optionally scoped to a folder prefix, or as JSON for scripts)
|
|
100
|
+
node-s3 --bucket my-bucket -l -f daily --json
|
|
101
|
+
|
|
102
|
+
# Back up a folder with exclusions, ZIP, and client-side AES-256-GCM encryption
|
|
103
|
+
BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
|
|
104
|
+
node-s3 --bucket my-bucket -b "src/*" --exclude "*.spec.ts" -z src.zip -f backups --encrypt -c -r
|
|
105
|
+
|
|
106
|
+
# Download and decrypt a backup
|
|
107
|
+
BACKUP_ENCRYPTION_KEY="my-strong-passphrase" \
|
|
108
|
+
node-s3 --bucket my-bucket --download backups/src.zip -o ./restored.zip --encrypt
|
|
109
|
+
|
|
110
|
+
# Pipe a PostgreSQL dump directly to S3 without writing to disk
|
|
111
|
+
pg_dump mydb | node-s3 --bucket my-bucket --stdin --name mydb.sql -f postgres --encrypt
|
|
112
|
+
|
|
113
|
+
# Preview retention cleanup safely before deleting anything
|
|
114
|
+
node-s3 --bucket my-bucket -d daily=30d --keep-last 5 --dry-run
|
|
115
|
+
|
|
116
|
+
# Nightly cron job: MySQL dump + zip + encrypt + prune older than 14 days (keep at least 5)
|
|
117
|
+
node-s3 --bucket my-bucket -m -z -f mysql --encrypt && \
|
|
118
|
+
node-s3 --bucket my-bucket -d mysql=14d --keep-last 5
|
|
65
119
|
```
|
|
66
120
|
|
|
67
|
-
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
## Environment Variables
|
|
124
|
+
|
|
125
|
+
Precedence: **CLI flags / constructor options > `AWS_*` variables > legacy variables > defaults**.
|
|
126
|
+
|
|
127
|
+
| Variable | Legacy Alias | Description | Default |
|
|
128
|
+
| ---------------------------------------------------------------------------- | ------------ | ---------------------------------------- | ---------------- |
|
|
129
|
+
| `AWS_ENDPOINT_URL` | `ENDPOINT` | Custom S3-compatible endpoint URL | AWS S3 default |
|
|
130
|
+
| `AWS_ACCESS_KEY_ID` | `ACCESS_KEY` | Access key ID | — |
|
|
131
|
+
| `AWS_SECRET_ACCESS_KEY` | `SECRET_KEY` | Secret access key | — |
|
|
132
|
+
| `AWS_SESSION_TOKEN` | — | Temporary STS session token | — |
|
|
133
|
+
| `AWS_REGION` | — | S3 region (`auto` for Cloudflare R2) | `us-east-1` |
|
|
134
|
+
| `BUCKET` | — | Default target bucket name | — |
|
|
135
|
+
| `MAX_RETRIES` | — | Retry attempts on transient S3 errors | `3` |
|
|
136
|
+
| `FORCE_PATH_STYLE` | — | Path-style URLs (`true`/`false`) | `true` |
|
|
137
|
+
| `SSL_ENABLED` | — | Enforce TLS (`true`/`false`) | `true` |
|
|
138
|
+
| `BACKUP_ENCRYPTION_KEY` | — | Passphrase for `--encrypt` (AES-256-GCM) | — |
|
|
139
|
+
| `MYSQL_HOST`, `MYSQL_PORT`, `MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE` | — | MySQL connection for `--mysql` | `localhost:3306` |
|
|
140
|
+
|
|
141
|
+
See [example.env](./example.env) for a ready-to-copy template.
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
## CLI Options
|
|
146
|
+
|
|
147
|
+
| Flag | Alias | Description |
|
|
148
|
+
| ----------------------- | ----- | -------------------------------------------------------------------------- |
|
|
149
|
+
| `--bucket <name>` | — | Target S3 bucket (overrides `$BUCKET`) |
|
|
150
|
+
| `--endpoint <url>` | `-e` | Custom S3 endpoint URL |
|
|
151
|
+
| `--region <region>` | — | S3 region (overrides `$AWS_REGION`) |
|
|
152
|
+
| `--list` | `-l` | List objects in bucket (filterable with `-f`) |
|
|
153
|
+
| `--backup <file*>` | `-b` | Upload files, directories, or globs (repeatable) |
|
|
154
|
+
| `--download <key>` | — | Download a remote object key |
|
|
155
|
+
| `--output <path>` | `-o` | Local destination path for `--download` |
|
|
156
|
+
| `--folder <prefix>` | `-f` | Remote folder prefix for upload, list, or delete |
|
|
157
|
+
| `--zip [filename.zip]` | `-z` | Compress backup files into a ZIP archive |
|
|
158
|
+
| `--exclude <glob>` | — | Exclude files matching glob pattern (repeatable) |
|
|
159
|
+
| `--replace` | `-r` | Overwrite remote object if it already exists |
|
|
160
|
+
| `--create` | `-c` | Create destination bucket if it does not exist |
|
|
161
|
+
| `--delete <rule>` | `-d` | Delete files older than duration (`folder=7d` or `7d`, repeatable) |
|
|
162
|
+
| `--keep-last <N>` | — | Always preserve the N newest matching files when deleting |
|
|
163
|
+
| `--dry-run` | — | Preview uploads/deletions without modifying S3 |
|
|
164
|
+
| `--encrypt` | — | Encrypt on upload / decrypt on download using `$BACKUP_ENCRYPTION_KEY` |
|
|
165
|
+
| `--stdin` | — | Read upload payload from standard input (requires `--name`) |
|
|
166
|
+
| `--name <filename>` | — | Object filename when using `--stdin` |
|
|
167
|
+
| `--mysql` | `-m` | Create and upload a MySQL dump using `$MYSQL_*` env vars |
|
|
168
|
+
| `--storage-class <cls>` | — | S3 storage class (e.g. `STANDARD_IA`, `GLACIER_IR`, `INTELLIGENT_TIERING`) |
|
|
169
|
+
| `--sse <algo>` | — | Server-side encryption (`AES256` or `aws:kms`) |
|
|
170
|
+
| `--kms-key-id <id>` | — | KMS Key ID when using `--sse aws:kms` |
|
|
171
|
+
| `--acl <acl>` | — | Canned ACL (e.g. `private`, `public-read`) |
|
|
172
|
+
| `--expire <duration>` | — | Set object `Expires` header relative to now (e.g. `30d`, `12h`) |
|
|
173
|
+
| `--json` | — | Output machine-readable JSON (ideal for CI/scripts) |
|
|
174
|
+
| `--quiet` | `-q` | Suppress informational logs |
|
|
175
|
+
| `--version` | `-v` | Print CLI version |
|
|
176
|
+
| `--help` | `-h` | Print usage guide |
|
|
177
|
+
|
|
178
|
+
### Valid Duration Units (`-d` / `--expire`)
|
|
179
|
+
|
|
180
|
+
| Unit | Meaning | Example |
|
|
181
|
+
| ---- | ------- | ------- |
|
|
182
|
+
| `s` | Seconds | `30s` |
|
|
183
|
+
| `m` | Minutes | `15m` |
|
|
184
|
+
| `h` | Hours | `24h` |
|
|
185
|
+
| `d` | Days | `7d` |
|
|
186
|
+
| `w` | Weeks | `2w` |
|
|
187
|
+
| `M` | Months | `1M` |
|
|
188
|
+
| `y` | Years | `1y` |
|
|
189
|
+
|
|
190
|
+
> Unrecognized units are rejected immediately to prevent accidental deletions.
|
|
191
|
+
|
|
192
|
+
### Exit Codes
|
|
193
|
+
|
|
194
|
+
- `0`: Success (or `--help` / `--version`).
|
|
195
|
+
- `1`: Runtime or S3 API error.
|
|
196
|
+
- `2`: Invalid CLI arguments or missing required options.
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
## Using as a Node.js Library
|
|
68
201
|
|
|
69
202
|
```bash
|
|
70
|
-
npm install
|
|
71
|
-
node-s3 -h
|
|
203
|
+
npm install @d0whc3r/node-s3
|
|
72
204
|
```
|
|
73
205
|
|
|
206
|
+
### ESM / TypeScript
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
import { S3Wrapper } from '@d0whc3r/node-s3';
|
|
210
|
+
|
|
211
|
+
const s3 = new S3Wrapper({
|
|
212
|
+
endpoint: 'https://s3.eu-central-1.amazonaws.com',
|
|
213
|
+
region: 'eu-central-1',
|
|
214
|
+
bucket: 'my-backups',
|
|
215
|
+
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
|
|
216
|
+
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
try {
|
|
220
|
+
// Upload with progress callback, client-side encryption, and S3 storage class
|
|
221
|
+
await s3.uploadFile('./dump.sql', 'daily', {
|
|
222
|
+
replace: true,
|
|
223
|
+
storageClass: 'STANDARD_IA',
|
|
224
|
+
serverSideEncryption: 'AES256',
|
|
225
|
+
encryptKey: process.env.BACKUP_ENCRYPTION_KEY,
|
|
226
|
+
onProgress: ({ loaded, total, key }) => {
|
|
227
|
+
console.log(`${key}: ${loaded}/${total ?? '?'} bytes`);
|
|
228
|
+
}
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
// Download and decrypt
|
|
232
|
+
await s3.downloadFile('daily/dump.sql', './restored.sql', {
|
|
233
|
+
decryptKey: process.env.BACKUP_ENCRYPTION_KEY
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
// Delete files older than 30 days while keeping at least the 5 newest
|
|
237
|
+
await s3.cleanOlder('30d', 'daily', undefined, { keepLast: 5 });
|
|
238
|
+
} finally {
|
|
239
|
+
s3.destroy();
|
|
240
|
+
}
|
|
74
241
|
```
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
-z, --zip zipname.zip Zip backup files
|
|
86
|
-
-r, --replace Replace files if already exists when backup upload
|
|
87
|
-
-c, --create Create destination upload bucket
|
|
88
|
-
-f, --folder foldername Folder name to upload file/s
|
|
89
|
-
-d, --delete foldername=duration OR duration Clean files older than duration in foldername
|
|
90
|
-
-m, --mysql Mysql backup using environment variables to connect mysql server
|
|
91
|
-
($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)
|
|
92
|
-
-h, --help Print this usage guide.
|
|
93
|
-
|
|
94
|
-
Examples
|
|
95
|
-
|
|
96
|
-
1. List files in "sample" bucket. $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -l
|
|
97
|
-
2. Backup multiple files to "backupFolder" folder. $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -b src/index.ts -b images/logo.png -f
|
|
98
|
-
backupFolder
|
|
99
|
-
3. Backup files using wildcard to "backup" folder. $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -b src/* -b images/* -f backup
|
|
100
|
-
4. Backup files using wildcard and zip into "zipped" folder, bucket will be created if it doesn't exists. $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -b src/* -b images/* -z -f zipped.zip -c
|
|
101
|
-
5. Backup files using wildcard and zip using "allfiles.zip" as filename into "zipped" folder, bucket will $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -b src/* -b images/* -z allfiles.zip -f
|
|
102
|
-
be created if it doesn't exists and zipfile will be replaced if it exists zipped -c -r
|
|
103
|
-
6. Delete files in "uploads" folder older than 2days and files in "monthly" folder older than 1month $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -d uploads=2d -d monthly=1M
|
|
104
|
-
7. Delete files in "uploads" folder older than 1minute $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -f uploads -d 1m
|
|
105
|
-
8. Generate mysql dump file zip it and upload to "mysql-backup" folder $ node-s3 -e http://s3.eu-central-1.amazonaws.com --bucket sample -f mysql-backup -m -z
|
|
242
|
+
|
|
243
|
+
### CommonJS
|
|
244
|
+
|
|
245
|
+
```js
|
|
246
|
+
const { S3Wrapper } = require('@d0whc3r/node-s3');
|
|
247
|
+
|
|
248
|
+
const s3 = new S3Wrapper({ bucket: 'my-backups' });
|
|
249
|
+
s3.getFiles(undefined, 'daily')
|
|
250
|
+
.then((files) => console.log(files))
|
|
251
|
+
.finally(() => s3.destroy());
|
|
106
252
|
```
|
|
107
253
|
|
|
254
|
+
---
|
|
255
|
+
|
|
108
256
|
## Alternatives
|
|
109
257
|
|
|
110
|
-
|
|
258
|
+
Go implementation with a similar interface: [go-s3](https://github.com/d0whc3r/go-s3).
|
|
259
|
+
|
|
260
|
+
## Contributing, Security & License
|
|
261
|
+
|
|
262
|
+
- Want to contribute or build from source? See [CONTRIBUTING.md](./CONTRIBUTING.md).
|
|
263
|
+
- Found a security issue? See [SECURITY.md](./SECURITY.md).
|
|
264
|
+
- Released under the [MIT License](./LICENSE).
|
package/bin/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var commandLineArgs=require("command-line-args"),commandLineUsage=require("command-line-usage"),path2=require("path"),mime=require("mime-types"),dayjs2=require("dayjs"),fs2=require("fs"),os2=require("os"),mkdirp2=require("mkdirp"),archiver2=require("archiver"),glob2=require("glob"),mysqldump2=require("mysqldump"),awsSdk=require("aws-sdk"),colors2=require("colors");function _interopDefaultLegacy(a){return a&&typeof a==="object"&&"default"in a?a:{default:a}}var commandLineArgs__default=_interopDefaultLegacy(commandLineArgs),commandLineUsage__default=_interopDefaultLegacy(commandLineUsage),path2__default=_interopDefaultLegacy(path2),mime__default=_interopDefaultLegacy(mime),dayjs2__default=_interopDefaultLegacy(dayjs2),fs2__default=_interopDefaultLegacy(fs2),os2__default=_interopDefaultLegacy(os2),mkdirp2__default=_interopDefaultLegacy(mkdirp2),archiver2__default=_interopDefaultLegacy(archiver2),glob2__default=_interopDefaultLegacy(glob2),mysqldump2__default=_interopDefaultLegacy(mysqldump2),colors2__default=_interopDefaultLegacy(colors2);const optionDefinitions=[{name:"endpoint",alias:"e",typeLabel:"{underline url} ",multiple:!1,type:String,description:"Destination url (can be defined by $ENDPOINT env variable)"},{name:"bucket",typeLabel:"{underline bucket} ",multiple:!1,type:String,description:"Destination bucket (can be defined by $BUCKET env variable)"},{name:"list",alias:"l",multiple:!1,type:Boolean,description:"List all files"},{name:"backup",alias:"b",typeLabel:"{underline file*} ",defaultOption:!0,multiple:!0,type:String,description:"Backup files"},{name:"zip",alias:"z",typeLabel:"{underline zipname.zip}",multiple:!1,type:String,description:"Zip backup files"},{name:"replace",alias:"r",multiple:!1,type:Boolean,description:"Replace files if already exists when backup upload"},{name:"create",alias:"c",multiple:!1,type:Boolean,description:"Create destination upload bucket"},{name:"folder",alias:"f",typeLabel:"{underline foldername}",multiple:!1,type:String,description:"Folder name to upload file/s"},{name:"delete",alias:"d",typeLabel:"{underline foldername=duration} OR {underline duration}",multiple:!0,type:String,description:"Clean files older than duration in foldername"},{name:"mysql",alias:"m",multiple:!1,type:Boolean,description:"Mysql backup using environment variables to connect mysql server ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)"},{name:"help",alias:"h",description:"Print this usage guide.",type:Boolean}];let cliOptions={};try{cliOptions=commandLineArgs__default.default(optionDefinitions)}catch(a){console.error("[-] Error:",a.message),process.exit(1)}if(cliOptions.help||!Object.keys(cliOptions).length){const a="node-s3",b=`${a} -e http://s3.eu-central-1.amazonaws.com --bucket sample`,c=[{header:`Help for ${a}`,content:`Usage of npm {italic ${a}} in command line.`},{header:"Options",optionList:optionDefinitions},{header:"Examples",content:[{desc:'1. List files in "sample" bucket.',example:`$ ${b} -l`},{desc:'2. Backup multiple files to "backupFolder" folder.',example:`$ ${b} -b src/index.ts -b images/logo.png -f backupFolder`},{desc:'3. Backup files using wildcard to "backup" folder.',example:`$ ${b} -b src/* -b images/* -f backup`},{desc:`4. Backup files using wildcard and zip into "zipped" folder, bucket will be created if it doesn't exists.`,example:`$ ${b} -b src/* -b images/* -z -f zipped.zip -c`},{desc:`5. Backup files using wildcard and zip using "allfiles.zip" as filename into "zipped" folder, bucket will be created if it doesn't exists and zipfile will be replaced if it exists`,example:`$ ${b} -b src/* -b images/* -z allfiles.zip -f zipped -c -r`},{desc:'6. Delete files in "uploads" folder older than 2days and files in "monthly" folder older than 1month',example:`$ ${b} -d uploads=2d -d monthly=1M`},{desc:'7. Delete files in "uploads" folder older than 1minute',example:`$ ${b} -f uploads -d 1m`},{desc:'8. Generate mysql dump file zip it and upload to "mysql-backup" folder',example:`$ ${b} -f mysql-backup -m -z`}]}];console.info(commandLineUsage__default.default(c)),process.exit(0)}class S3WrapperBuckets{constructor(a){this.s3Sdk=a}setFileWrapper(a){this.s3Files=a}getBuckets(){return new Promise((a,b)=>{this.s3Sdk.listBuckets((c,d)=>{c?b(c.message):a(d.Buckets||[])})})}createBucket(a){return new Promise((b,c)=>{this.s3Sdk.createBucket({Bucket:a},(d,f)=>{d?c(d.message):b(f)})})}removeBucket(a,b=!1){return new Promise((c,d)=>{this.s3Sdk.deleteBucket({Bucket:a},f=>{f?b&&this.s3Files?this.s3Files.deleteAllContent(a).then(()=>{this.removeBucket(a,b).then(c).catch(d)}).catch(d):d(f.message):c(!0)})})}bucketExist(a){return new Promise(b=>{this.s3Sdk.headBucket({Bucket:a},c=>{c?b(!1):b(!0)})})}}class Config{}Config.API_VERSION="2006-03-01",Config.ENDPOINT=process.env.ENDPOINT||"",Config.BUCKET=process.env.BUCKET||"",Config.ACCESS_KEY=process.env.ACCESS_KEY||"",Config.SECRET_KEY=process.env.SECRET_KEY||"",Config.MAX_RETRIES=+(process.env.MAX_RETRIES||3),Config.FORCE_PATH_STYLE=[!0,1,"true"].includes(process.env.FORCE_PATH_STYLE||!0),Config.SSL_ENABLED=[!0,1,"true"].includes(process.env.SSL_ENABLED||!1),Config.TAG="[node-s3]",Config.MYSQL_HOST=process.env.MYSQL_HOST||"localhost",Config.MYSQL_PORT=+(process.env.MYSQL_PORT||3306),Config.MYSQL_USER=process.env.MYSQL_USER||"",Config.MYSQL_PASSWORD=process.env.MYSQL_PASSWORD||"",Config.MYSQL_DATABASE=process.env.MYSQL_DATABASE||"";var __assign=Object.assign,__async=(a,b,c)=>new Promise((d,f)=>{var h=e=>{try{i(c.next(e))}catch(g){f(g)}},j=e=>{try{i(c.throw(e))}catch(g){f(g)}},i=e=>e.done?d(e.value):Promise.resolve(e.value).then(h,j);i((c=c.apply(a,b)).next())});class S3WrapperFiles{constructor(a){this.s3Sdk=a,this.defaultUploadOptions={create:!0,replace:!1}}setBucketWrapper(a){this.s3Buckets=a}getFiles(a){return new Promise((b,c)=>{this.s3Sdk.listObjects({Bucket:a},(d,f)=>{d?c(d.message):b(f.Contents||[])})})}fileInfo(a,b){return new Promise((c,d)=>{this.s3Sdk.getObject({Bucket:a,Key:b},(f,h)=>{f?d(f.message):c(h)})})}fileExist(a,b){return new Promise(c=>{this.fileInfo(a,b).then(()=>c(!0)).catch(()=>c(!1))})}deleteAllContent(a){return __async(this,[],function*(){const b=(yield this.getFiles(a)).map(c=>({Key:c.Key}));return this.deleteFiles(a,b)})}uploadFile(a,b,c,d){return __async(this,[],function*(){let f,h,j,i;try{const e=path2__default.default.basename(b);f=[c,e].filter(Boolean).join("/"),h=mime__default.default.contentType(e)||void 0;const g=__assign(__assign({},this.defaultUploadOptions),d||{});j=this.getExpire(g),yield this.createIfNeeded(g,a),i=yield this.canBeReplaced(g,a,f)}catch(e){return Promise.reject(e)}return new Promise((e,g)=>{if(!i)return g(Error(`${Config.TAG} File "${f}" already exists in bucket "${a}" and will not be replaced`));const l=fs2__default.default.createReadStream(b),k={Key:f,Bucket:a,Body:l,Expires:j,ContentType:h};this.s3Sdk.upload(k,(m,n)=>{l.destroy(),m?g(m.message):e(n)})})})}uploadFiles(a,b,c,d={}){return __async(this,[],function*(){const{compress:f,replace:h,create:j,expire:i,expireDate:e}=d;Array.isArray(b)||(b=[b]);let g=b;if(f){let k=f;typeof k!=="string"&&(k=`zipped_${dayjs2__default.default().format("YYYY-MM-DD.HHmmss")}.zip`);const m=yield this.compressFiles(b,k);g=[m]}let l={};for(const k of g)if(k.includes("*")){const m=yield this.uploadFiles(a,glob2__default.default.sync(k),c,d);l=__assign(__assign({},l),m)}else if(fs2__default.default.lstatSync(k).isDirectory()){const m=yield this.uploadFiles(a,glob2__default.default.sync(`${k}/*`),c,d);l=__assign(__assign({},l),m)}else l[k]=yield this.uploadFile(a,k,c,{replace:h,create:j,expireDate:e,expire:i});return l})}cleanOlder(a,b,c){return __async(this,[],function*(){const{value:d,unit:f}=this.getTimeSpace(b),h=dayjs2__default.default().subtract(d,f),j=yield this.getFilesInFolder(a,c),i=j.filter(e=>!!e.LastModified&&dayjs2__default.default(e.LastModified).isBefore(h)).map(e=>({Key:e.Key}));return this.deleteFiles(a,i)})}createDumpFile(){const a=Config.MYSQL_HOST,b=Config.MYSQL_PORT,c=Config.MYSQL_USER,d=Config.MYSQL_PASSWORD,f=Config.MYSQL_DATABASE;if(!c||!d||!f)throw new Error(`${Config.TAG} Error in mysql-dump environment variables not defined: $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT`);return mysqldump2__default.default({connection:{host:a,port:b,user:c,password:d,database:f}}).then(({dump:h})=>{const j=os2__default.default.tmpdir(),i=path2__default.default.join(j,`mysqldump-${dayjs2__default.default().format("YYYY-MM-DD.HHmmss")}.sql`);mkdirp2__default.default.sync(path2__default.default.dirname(i));const e=Object.values(h).map(g=>g&&g.replace(/^# /gm,"-- ")).join(`
|
|
2
|
+
var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,s)=>(s=n==null?{}:e(i(n)),o(r||!n||!n.__esModule||!a.call(n,`default`)?t(s,`default`,{value:n,enumerable:!0}):s,n));let c=require("command-line-args");c=s(c);let l=require("command-line-usage");l=s(l);let u=require("node:fs/promises");u=s(u);let d=require("node:path");d=s(d);let f=require("@aws-sdk/client-s3"),p=require("node:fs");p=s(p);let m=require("node:os");m=s(m);let h=require("node:stream/promises"),g=require("@aws-sdk/lib-storage"),_=require("archiver"),v=require("dayjs");v=s(v);let y=require("mime-types");y=s(y);let b=require("mysqldump");b=s(b);let x=require("node:crypto");x=s(x);let S=require("node:stream");var C={name:`@d0whc3r/node-s3`,version:`1.3.13`,keywords:[`aws`,`backup`,`compress`,`copy`,`node`,`s3`,`upload`],license:`MIT`,author:{name:`d0whc3r`,email:`d0whc3r@gmail.com`,url:`https://github.com/d0whc3r`},repository:{type:`git`,url:`https://github.com/d0whc3r/node-s3.git`},bin:{"node-s3":`./bin/cli.js`},files:[`dist`,`bin`],main:`dist/s3.cjs.js`,module:`dist/s3.es.mjs`,types:`dist/index.d.ts`,exports:{".":{types:`./dist/index.d.ts`,import:`./dist/s3.es.mjs`,require:`./dist/s3.cjs.js`}},publishConfig:{access:`public`,registry:`https://registry.npmjs.org`},scripts:{clean:`node -e "import('node:fs').then(fs => ['dist','bin','build','coverage','node-s3','node-s3.exe'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"cli:dev":`node --env-file=.env cli/cli.ts`,cli:`node cli/cli.ts`,typecheck:`tsc --noEmit`,"build:clean":`node -e "import('node:fs').then(fs => ['dist','bin'].forEach(p => fs.rmSync(p, {recursive:true,force:true})))"`,"build:lib":`vite build --config vite.config.mts`,"build:cli":`vite build --config vite.cli.config.mts`,"build:dts":`tsc -p tsconfig.build.json --emitDeclarationOnly`,"build:base":`pnpm build:clean && pnpm build:lib && pnpm build:cli && pnpm build:dts`,"build:sea":`vite build --config vite.sea.config.mts && node scripts/build-sea.mjs`,build:`pnpm build:base && pnpm build:sea`,test:`vitest run`,"test:unit":`vitest run tests/*.unit.spec.ts`,"test:integration":`vitest run tests/*.integration.spec.ts`,"test:watch":`vitest`,"test:coverage":`vitest run --coverage`,lint:`oxlint`,"lint:fix":`oxlint --fix`,format:`oxfmt --write`,"format:check":`oxfmt --check`,prepare:`husky`,"semantic-release":`semantic-release`},dependencies:{"@aws-sdk/client-s3":`^3.1177.0`,"@aws-sdk/lib-storage":`^3.1177.0`,archiver:`^8.0.0`,"command-line-args":`^6.0.2`,"command-line-usage":`^7.0.4`,dayjs:`^1.11.23`,"mime-types":`^3.0.2`,mysqldump:`^3.2.0`},devDependencies:{"@commitlint/cli":`^21.2.4`,"@commitlint/config-conventional":`^21.2.4`,"@semantic-release/changelog":`^7.0.0`,"@semantic-release/commit-analyzer":`^13.0.1`,"@semantic-release/git":`^11.0.1`,"@semantic-release/github":`^12.0.11`,"@semantic-release/npm":`^13.2.0`,"@semantic-release/release-notes-generator":`^14.1.1`,"@types/archiver":`^8.0.0`,"@types/command-line-args":`^5.2.3`,"@types/command-line-usage":`^5.0.4`,"@types/mime-types":`^3.0.1`,"@types/node":`^26.6.10`,"@vitest/coverage-v8":`^5.1.2`,"aws-sdk-client-mock":`^4.1.0`,husky:`^9.1.7`,"lint-staged":`^17.6.2`,oxfmt:`^0.80.0`,oxlint:`^1.95.0`,"semantic-release":`^26.0.1`,typescript:`^7.0.2`,vite:`^8.3.8`,vitest:`^5.1.2`},"lint-staged":{"{src,cli,tests}/**/*.ts":[`pnpm lint:fix`,`pnpm format`]},engines:{node:`>=26.0.0`},packageManager:`pnpm@12.16.1`},w=[{name:`endpoint`,alias:`e`,typeLabel:`{underline url}`,multiple:!1,type:String,description:`Destination URL (or $AWS_ENDPOINT_URL / $ENDPOINT env variable)`},{name:`bucket`,typeLabel:`{underline bucket}`,multiple:!1,type:String,description:`Destination bucket (or $BUCKET env variable)`},{name:`region`,typeLabel:`{underline region}`,multiple:!1,type:String,description:`AWS/S3 region (or $AWS_REGION env variable, default: us-east-1)`},{name:`list`,alias:`l`,multiple:!1,type:Boolean,description:`List all files (optionally filtered by --folder)`},{name:`backup`,alias:`b`,typeLabel:`{underline file*}`,defaultOption:!0,multiple:!0,type:String,description:`Backup files, directories, or globs`},{name:`download`,typeLabel:`{underline key}`,multiple:!1,type:String,description:`Download an object by S3 key`},{name:`output`,alias:`o`,typeLabel:`{underline path}`,multiple:!1,type:String,description:`Local destination path for --download`},{name:`zip`,alias:`z`,typeLabel:`{underline zipname.zip}`,multiple:!1,type:String,description:`Zip backup files before uploading`},{name:`replace`,alias:`r`,multiple:!1,type:Boolean,description:`Replace files if they already exist on upload`},{name:`create`,alias:`c`,multiple:!1,type:Boolean,description:`Create destination bucket if it does not exist`},{name:`folder`,alias:`f`,typeLabel:`{underline foldername}`,multiple:!1,type:String,description:`Folder prefix in the bucket`},{name:`delete`,alias:`d`,typeLabel:`{underline foldername=duration} OR {underline duration}`,multiple:!0,type:String,description:`Clean files older than duration (e.g. 7d, 24h, 1M) in foldername`},{name:`keep-last`,typeLabel:`{underline N}`,multiple:!1,type:Number,description:`Keep the newest N files when running --delete`},{name:`mysql`,alias:`m`,multiple:!1,type:Boolean,description:`MySQL backup using environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT)`},{name:`stdin`,multiple:!1,type:Boolean,description:`Read upload content from stdin (requires --name)`},{name:`name`,typeLabel:`{underline filename}`,multiple:!1,type:String,description:`Destination filename when using --stdin`},{name:`encrypt`,multiple:!1,type:Boolean,description:`Encrypt uploads / decrypt downloads with AES-256-GCM using $BACKUP_ENCRYPTION_KEY`},{name:`storage-class`,typeLabel:`{underline class}`,multiple:!1,type:String,description:`S3 storage class (e.g. STANDARD, STANDARD_IA, GLACIER, DEEP_ARCHIVE)`},{name:`sse`,typeLabel:`{underline algorithm}`,multiple:!1,type:String,description:`Server-side encryption algorithm (e.g. AES256, aws:kms)`},{name:`kms-key-id`,typeLabel:`{underline id}`,multiple:!1,type:String,description:`KMS key ID for aws:kms server-side encryption`},{name:`acl`,typeLabel:`{underline acl}`,multiple:!1,type:String,description:`Canned ACL (e.g. private, public-read)`},{name:`expire`,typeLabel:`{underline duration}`,multiple:!1,type:String,description:`Object expiration duration (e.g. 7d, 1M)`},{name:`exclude`,typeLabel:`{underline glob}`,multiple:!0,type:String,description:`Exclude glob pattern(s) during backup (repeatable)`},{name:`dry-run`,multiple:!1,type:Boolean,description:`Preview upload/delete operations without modifying S3`},{name:`json`,multiple:!1,type:Boolean,description:`Output machine-readable JSON`},{name:`quiet`,alias:`q`,multiple:!1,type:Boolean,description:`Suppress informational logs`},{name:`version`,alias:`v`,multiple:!1,type:Boolean,description:`Print CLI version`},{name:`help`,alias:`h`,description:`Print this usage guide`,type:Boolean}];function T(e){let t=(0,c.default)(w,e===void 0?void 0:{argv:e}),n={};return t.help!==void 0&&(n.help=!!t.help),t.version!==void 0&&(n.version=!!t.version),t.endpoint!==void 0&&(n.endpoint=String(t.endpoint)),t.bucket!==void 0&&(n.bucket=String(t.bucket)),t.region!==void 0&&(n.region=String(t.region)),t.list!==void 0&&(n.list=!!t.list),t.backup!==void 0&&(n.backup=Array.isArray(t.backup)?t.backup:[String(t.backup)]),t.download!==void 0&&(n.download=String(t.download)),t.output!==void 0&&(n.output=String(t.output)),t.folder!==void 0&&(n.folder=String(t.folder)),`zip`in t&&(n.zip=t.zip===null?null:String(t.zip)),t.create!==void 0&&(n.create=!!t.create),t.replace!==void 0&&(n.replace=!!t.replace),t.delete!==void 0&&(n.delete=Array.isArray(t.delete)?t.delete:[String(t.delete)]),t[`keep-last`]!==void 0&&(n.keepLast=Number(t[`keep-last`])),t.mysql!==void 0&&(n.mysql=!!t.mysql),t.stdin!==void 0&&(n.stdin=!!t.stdin),t.name!==void 0&&(n.name=String(t.name)),t.encrypt!==void 0&&(n.encrypt=!!t.encrypt),t[`storage-class`]!==void 0&&(n.storageClass=String(t[`storage-class`])),t.sse!==void 0&&(n.sse=String(t.sse)),t[`kms-key-id`]!==void 0&&(n.kmsKeyId=String(t[`kms-key-id`])),t.acl!==void 0&&(n.acl=String(t.acl)),t.expire!==void 0&&(n.expire=String(t.expire)),t.exclude!==void 0&&(n.exclude=Array.isArray(t.exclude)?t.exclude:[String(t.exclude)]),t[`dry-run`]!==void 0&&(n.dryRun=!!t[`dry-run`]),t.json!==void 0&&(n.json=!!t.json),t.quiet!==void 0&&(n.quiet=!!t.quiet),n}function E(){let e=`node-s3`,t=`${e} -e https://s3.eu-central-1.amazonaws.com --bucket sample`,n=[{header:`Help for ${e}`,content:`Usage of {italic ${e}} in command line.`},{header:`Options`,optionList:w},{header:`Examples`,content:[{desc:`1. List files in "sample" bucket.`,example:`$ ${t} -l`},{desc:`2. Backup multiple files to "backupFolder" folder.`,example:`$ ${t} -b src/index.ts -b images/logo.png -f backupFolder`},{desc:`3. Backup files using wildcard and exclude patterns.`,example:`$ ${t} -b "src/*" --exclude "*.test.ts" -f backup`},{desc:`4. Backup and zip with AES-256-GCM encryption.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${t} -b "src/*" -z allfiles.zip -f zipped --encrypt -c -r`},{desc:`5. Download and decrypt a backup.`,example:`$ BACKUP_ENCRYPTION_KEY=secret ${t} --download zipped/allfiles.zip -o ./restore.zip --encrypt`},{desc:`6. Delete files older than 7 days while keeping the 3 newest.`,example:`$ ${t} -d uploads=7d --keep-last 3`},{desc:`7. Stream stdin directly to S3.`,example:`$ pg_dump mydb | ${t} --stdin --name mydb.sql -f db-backups`},{desc:`8. Generate MySQL dump, zip it and upload to "mysql-backup" folder.`,example:`$ ${t} -f mysql-backup -m -z`}]}];return(0,l.default)(n)}function D(e,t){return e===void 0||e.trim()===``?t:[`true`,`1`,`yes`].includes(e.trim().toLowerCase())}function O(e,t){if(e===void 0||e.trim()===``)return t;let n=Number(e);return Number.isNaN(n)?t:n}var k=class{static API_VERSION=`2006-03-01`;static TAG=`[node-s3]`;static overrides={};static resetOverrides(){this.overrides={}}static get ENDPOINT(){return`ENDPOINT`in this.overrides?this.overrides.ENDPOINT:process.env.AWS_ENDPOINT_URL||process.env.ENDPOINT||``}static set ENDPOINT(e){this.overrides.ENDPOINT=e}static get BUCKET(){return`BUCKET`in this.overrides?this.overrides.BUCKET:process.env.BUCKET||``}static set BUCKET(e){this.overrides.BUCKET=e}static get REGION(){return`REGION`in this.overrides?this.overrides.REGION:process.env.AWS_REGION||process.env.AWS_DEFAULT_REGION||`us-east-1`}static set REGION(e){this.overrides.REGION=e}static get ACCESS_KEY(){return`ACCESS_KEY`in this.overrides?this.overrides.ACCESS_KEY:process.env.AWS_ACCESS_KEY_ID||process.env.ACCESS_KEY||``}static set ACCESS_KEY(e){this.overrides.ACCESS_KEY=e}static get SECRET_KEY(){return`SECRET_KEY`in this.overrides?this.overrides.SECRET_KEY:process.env.AWS_SECRET_ACCESS_KEY||process.env.SECRET_KEY||``}static set SECRET_KEY(e){this.overrides.SECRET_KEY=e}static get SESSION_TOKEN(){return`SESSION_TOKEN`in this.overrides?this.overrides.SESSION_TOKEN:process.env.AWS_SESSION_TOKEN||``}static set SESSION_TOKEN(e){this.overrides.SESSION_TOKEN=e}static get MAX_RETRIES(){return`MAX_RETRIES`in this.overrides?this.overrides.MAX_RETRIES:O(process.env.MAX_RETRIES,3)}static set MAX_RETRIES(e){this.overrides.MAX_RETRIES=e}static get FORCE_PATH_STYLE(){return`FORCE_PATH_STYLE`in this.overrides?this.overrides.FORCE_PATH_STYLE:D(process.env.FORCE_PATH_STYLE,!0)}static set FORCE_PATH_STYLE(e){this.overrides.FORCE_PATH_STYLE=e}static get SSL_ENABLED(){return`SSL_ENABLED`in this.overrides?this.overrides.SSL_ENABLED:D(process.env.SSL_ENABLED,!0)}static set SSL_ENABLED(e){this.overrides.SSL_ENABLED=e}static get BACKUP_ENCRYPTION_KEY(){return`BACKUP_ENCRYPTION_KEY`in this.overrides?this.overrides.BACKUP_ENCRYPTION_KEY:process.env.BACKUP_ENCRYPTION_KEY||``}static set BACKUP_ENCRYPTION_KEY(e){this.overrides.BACKUP_ENCRYPTION_KEY=e}static get MYSQL_HOST(){return`MYSQL_HOST`in this.overrides?this.overrides.MYSQL_HOST:process.env.MYSQL_HOST||`localhost`}static set MYSQL_HOST(e){this.overrides.MYSQL_HOST=e}static get MYSQL_PORT(){return`MYSQL_PORT`in this.overrides?this.overrides.MYSQL_PORT:O(process.env.MYSQL_PORT,3306)}static set MYSQL_PORT(e){this.overrides.MYSQL_PORT=e}static get MYSQL_USER(){return`MYSQL_USER`in this.overrides?this.overrides.MYSQL_USER:process.env.MYSQL_USER||``}static set MYSQL_USER(e){this.overrides.MYSQL_USER=e}static get MYSQL_PASSWORD(){return`MYSQL_PASSWORD`in this.overrides?this.overrides.MYSQL_PASSWORD:process.env.MYSQL_PASSWORD||``}static set MYSQL_PASSWORD(e){this.overrides.MYSQL_PASSWORD=e}static get MYSQL_DATABASE(){return`MYSQL_DATABASE`in this.overrides?this.overrides.MYSQL_DATABASE:process.env.MYSQL_DATABASE||``}static set MYSQL_DATABASE(e){this.overrides.MYSQL_DATABASE=e}};function A(e){if(!e||typeof e!=`object`)return!1;let t=e;if(t.$metadata?.httpStatusCode===404)return!0;let n=[`NotFound`,`NoSuchBucket`,`NoSuchKey`,`404`];return!!(t.name&&n.includes(t.name)||t.Code&&n.includes(t.Code))}function j(e,t){return e instanceof Error?Error(`${k.TAG} ${t}: ${e.message}`,{cause:e}):Error(`${k.TAG} ${t}: ${String(e)}`,{cause:e})}var M=class{s3Sdk;deleteAllContentFn;constructor(e,t){this.s3Sdk=e,this.deleteAllContentFn=t}async getBuckets(){try{return(await this.s3Sdk.send(new f.ListBucketsCommand({}))).Buckets||[]}catch(e){throw j(e,`Failed to list buckets`)}}async createBucket(e){try{return await this.s3Sdk.send(new f.CreateBucketCommand({Bucket:e}))}catch(t){throw j(t,`Failed to create bucket "${e}"`)}}async removeBucket(e,t=!1){try{return await this.s3Sdk.send(new f.DeleteBucketCommand({Bucket:e})),!0}catch(n){if(t&&this.deleteAllContentFn)return await this.deleteAllContentFn(e),this.removeBucket(e,!1);throw j(n,`Failed to remove bucket "${e}"`)}}async bucketExist(e){try{return await this.s3Sdk.send(new f.HeadBucketCommand({Bucket:e})),!0}catch(t){if(A(t))return!1;throw j(t,`Failed to check bucket "${e}"`)}}},N=Buffer.from(`NS3E`,`ascii`),P=1,F=16,I=12,L=32,R=16,z=N.length+1+F+I;function B(e){if(!e)throw Error(`${k.TAG} Encryption key must be a non-empty string`);let t=null,n=n=>{let i=x.default.randomBytes(F),a=x.default.randomBytes(I);x.default.scrypt(e,i,L,(e,o)=>{e?n(e):(t=x.default.createCipheriv(`aes-256-gcm`,o,a),r.push(Buffer.concat([N,Buffer.from([P]),i,a])),n())})},r=new S.Transform({transform(e,r,i){let a=()=>{try{let n=t.update(e);n.length>0&&this.push(n),i()}catch(e){i(e instanceof Error?e:Error(String(e)))}};t?a():n(e=>{e?i(e):a()})},flush(e){let r=()=>{try{let n=t.final();n.length>0&&this.push(n),this.push(t.getAuthTag()),e()}catch(t){e(t instanceof Error?t:Error(String(t)))}};t?r():n(t=>{t?e(t):r()})}});return r}function V(e){if(!e)throw Error(`${k.TAG} Decryption key must be a non-empty string`);let t=Buffer.alloc(0),n=Buffer.alloc(0),r=null;return new S.Transform({transform(i,a,o){let s=e=>{try{let t=n.length>0?Buffer.concat([n,e]):e;if(t.length>R){let e=t.subarray(0,t.length-R);n=t.subarray(t.length-R);let i=r.update(e);i.length>0&&this.push(i)}else n=t;o()}catch(e){o(e instanceof Error?e:Error(String(e)))}};if(r){s(i);return}if(t=t.length>0?Buffer.concat([t,i]):i,t.length<z){o();return}if(!t.subarray(0,N.length).equals(N)){o(Error(`${k.TAG} Invalid encrypted stream header`));return}let c=t[N.length];if(c!==P){o(Error(`${k.TAG} Unsupported encryption format version: ${c}`));return}let l=N.length+1,u=l+F,d=t.subarray(l,u),f=t.subarray(u,z),p=t.subarray(z);t=Buffer.alloc(0),x.default.scrypt(e,d,L,(e,t)=>{e?o(e):(r=x.default.createDecipheriv(`aes-256-gcm`,t,f),s(p))})},flush(e){if(!r)e(Error(`${k.TAG} Encrypted stream is truncated or empty`));else if(n.length!==R)e(Error(`${k.TAG} Encrypted stream is missing authentication tag`));else try{r.setAuthTag(n);let t=r.final();t.length>0&&this.push(t),e()}catch(t){e(Error(`${k.TAG} Decryption failed: invalid key or corrupted data`,{cause:t}))}}})}var H=/^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/,U={s:`second`,second:`second`,seconds:`second`,m:`minute`,minute:`minute`,minutes:`minute`,h:`hour`,hour:`hour`,hours:`hour`,d:`day`,day:`day`,days:`day`,w:`week`,week:`week`,weeks:`week`,M:`month`,month:`month`,months:`month`,y:`year`,year:`year`,years:`year`},W=1e3,G=4,K=6;function q(...e){let t=[];for(let n of e){if(!n)continue;let e=n.replace(/\\/g,`/`);for(let r of e.split(`/`))if(r&&r!==`.`){if(r===`..`)throw Error(`${k.TAG} Invalid S3 key segment ".." in "${n}"`);t.push(r)}}return d.default.posix.join(...t)}function J(e){if(!e)return;let t=q(e);return t?`${t}/`:void 0}function Y(e){let t=e.search(/[*?[{]/);if(t===-1)return e;let n=e.slice(0,t);return n?n.endsWith(`/`)||n.endsWith(`\\`)?n.slice(0,-1)||`.`:d.default.dirname(n):`.`}function X(e,t){if(!t.length)return!1;let n=e.replace(/\\/g,`/`),r=d.default.posix.basename(n);return t.some(e=>d.default.matchesGlob(n,e)||d.default.matchesGlob(r,e))}async function Z(e,t,n){let r=Array.from({length:e.length}),i=Math.max(1,Math.min(t,e.length)),a=0,o=async()=>{for(;a<e.length;){let t=a;a+=1,r[t]=await n(e[t])}};return await Promise.all(Array.from({length:i},()=>o())),r}var Q=class{s3Sdk;defaultUploadOptions={create:!0,replace:!1};ensureBucketFn;logger;defaultDryRun;defaultOnProgress;constructor(e,t={}){this.s3Sdk=e,this.ensureBucketFn=t.ensureBucket,this.logger=t.logger??console,this.defaultDryRun=t.dryRun??!1,this.defaultOnProgress=t.onProgress}async getFiles(e,t){let n=t?J(t):void 0,r=[],i;try{do{let t=await this.s3Sdk.send(new f.ListObjectsV2Command({Bucket:e,...n?{Prefix:n}:{},...i?{ContinuationToken:i}:{}}));t.Contents&&r.push(...t.Contents),i=t.IsTruncated?t.NextContinuationToken:void 0}while(i);return r}catch(t){throw j(t,`Failed to list files in bucket "${e}"`)}}async fileInfo(e,t){let n=q(t);try{return await this.s3Sdk.send(new f.HeadObjectCommand({Bucket:e,Key:n}))}catch(t){throw j(t,`Failed to get info for "${n}" in bucket "${e}"`)}}async fileExist(e,t){let n=q(t);try{return await this.s3Sdk.send(new f.HeadObjectCommand({Bucket:e,Key:n})),!0}catch(t){if(A(t))return!1;throw j(t,`Failed to check existence of "${n}" in bucket "${e}"`)}}async deleteAllContent(e){let t=(await this.getFiles(e)).filter(e=>!!e.Key).map(e=>({Key:e.Key}));return this.deleteFiles(e,t)}async uploadFile(e,t,n,r){let i=d.default.basename(t),a=q(n,i),o={...this.defaultUploadOptions,...r};if(o.dryRun??this.defaultDryRun)return this.logger.info?.(`${k.TAG} [dry-run] Would upload "${t}" to "s3://${e}/${a}"`),{Bucket:e,Key:a,$metadata:{}};let s=p.default.createReadStream(t);try{return await this.uploadStream(e,s,i,n,o)}finally{s.destroy()}}async uploadStream(e,t,n,r,i){let a=d.default.basename(n);if(!a||a===`.`||a===`..`)throw Error(`${k.TAG} Invalid upload filename: "${n}"`);let o=q(r,a),s=y.default.contentType(a)||void 0,c={...this.defaultUploadOptions,...i};if(c.dryRun??this.defaultDryRun)return this.logger.info?.(`${k.TAG} [dry-run] Would upload stream "${a}" to "s3://${e}/${o}"`),{Bucket:e,Key:o,$metadata:{}};let l=this.getExpire(c);if(c.skipBucketCheck||await this.createIfNeeded(c,e),!await this.canBeReplaced(c,e,o))throw Error(`${k.TAG} File "${o}" already exists in bucket "${e}" and will not be replaced`);let u=t,f;if(c.encryptKey){let e=B(c.encryptKey);t.on(`error`,t=>{e.destroy(t)}),u=t.pipe(e),f=u}let p=c.onProgress??this.defaultOnProgress;try{let t=new g.Upload({client:this.s3Sdk,params:{Key:o,Bucket:e,Body:u,Expires:l,ContentType:s,...c.storageClass?{StorageClass:c.storageClass}:{},...c.acl?{ACL:c.acl}:{},...c.serverSideEncryption?{ServerSideEncryption:c.serverSideEncryption}:{},...c.kmsKeyId?{SSEKMSKeyId:c.kmsKeyId}:{}}});return p&&t.on(`httpUploadProgress`,e=>{p({loaded:e.loaded,total:e.total,part:e.part,key:o})}),await t.done()}catch(t){throw j(t,`Failed to upload "${o}" to bucket "${e}"`)}finally{f?.destroy()}}async uploadFiles(e,t,n,r={}){let i=Array.isArray(t)?t:[t],a={...this.defaultUploadOptions,...r},o=a.dryRun??this.defaultDryRun,s=a.exclude?Array.isArray(a.exclude)?a.exclude:[a.exclude]:[],c=a.followSymlinks??!1;!a.skipBucketCheck&&!o&&await this.createIfNeeded(a,e);let l={replace:a.replace,create:a.create,expire:a.expire,expireDate:a.expireDate,storageClass:a.storageClass,acl:a.acl,serverSideEncryption:a.serverSideEncryption,kmsKeyId:a.kmsKeyId,dryRun:a.dryRun,encryptKey:a.encryptKey,onProgress:a.onProgress,skipBucketCheck:!0};if(a.compress){let t=typeof a.compress==`string`?a.compress:`zipped_${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.zip`,{filePath:r,tmpDir:o}=await this.compressFiles(i,t,{compressionLevel:a.compressionLevel,followSymlinks:c,exclude:s});try{let t=await this.uploadFile(e,r,n,l);return{[r]:t}}finally{await u.default.rm(o,{recursive:!0,force:!0})}}let d=await this.collectUploadTasks(i,n,a.baseDir,c,s),f=a.concurrency??G,p={},m=await Z(d,f,async t=>{let n=await this.uploadFile(e,t.file,t.folderName,l);return{file:t.file,response:n}});for(let e of m)p[e.file]=e.response;return p}async downloadFile(e,t,n,r={}){let i=q(t);try{let t=await this.s3Sdk.send(new f.GetObjectCommand({Bucket:e,Key:i}));if(!t.Body)throw Error(`${k.TAG} Empty response body for "${i}"`);await u.default.mkdir(d.default.dirname(d.default.resolve(n)),{recursive:!0});let a=t.Body,o=p.default.createWriteStream(n);if(r.decryptKey){let e=V(r.decryptKey);await(0,h.pipeline)(a,e,o)}else await(0,h.pipeline)(a,o);return n}catch(t){throw j(t,`Failed to download "${i}" from bucket "${e}"`)}}async cleanOlder(e,t,n,r={}){let{value:i,unit:a}=this.getTimeSpace(t),o=(0,v.default)().subtract(i,a),s=(await this.getFiles(e,n)).filter(e=>!!(e.Key&&e.LastModified));s.sort((e,t)=>(t.LastModified?.getTime()??0)-(e.LastModified?.getTime()??0));let c=r.keepLast??0,l=(c>0?s.slice(c):s).filter(e=>(0,v.default)(e.LastModified).isBefore(o)).map(e=>({Key:e.Key}));if(r.dryRun??this.defaultDryRun){for(let e of l)e.Key&&this.logger.info?.(`${k.TAG} [dry-run] Would delete file: ${e.Key}`);return{Deleted:l.map(e=>({Key:e.Key})),Errors:[],$metadata:{}}}return this.deleteFiles(e,l)}async createDumpFile(){let e=k.MYSQL_HOST,t=k.MYSQL_PORT,n=k.MYSQL_USER,r=k.MYSQL_PASSWORD,i=k.MYSQL_DATABASE;if(!n||!r||!i)throw Error(`${k.TAG} Error in mysql-dump environment variables not defined: $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT`);let{dump:a}=await(0,b.default)({connection:{host:e,port:t,user:n,password:r,database:i}}),o=await u.default.mkdtemp(d.default.join(m.default.tmpdir(),`node-s3-dump-`));await u.default.chmod(o,448);let s=d.default.join(o,`mysqldump-${(0,v.default)().format(`YYYY-MM-DD.HHmmss`)}.sql`),c=Object.values(a).map(e=>e&&e.replace(/^# /gm,`-- `)).join(`
|
|
3
3
|
|
|
4
|
-
`);return
|
|
4
|
+
`);return await u.default.writeFile(s,c,{mode:384}),s}async deleteFiles(e,t){let n=t.filter(e=>!!e.Key);if(!n.length)return this.logger.info?.(`${k.TAG} No files deleted`),{Deleted:[],Errors:[],$metadata:{}};let r=[],i=[],a={};try{for(let t=0;t<n.length;t+=W){let o={Objects:n.slice(t,t+W)},s=await this.s3Sdk.send(new f.DeleteObjectsCommand({Bucket:e,Delete:o}));if(a=s.$metadata,s.Deleted?.length){r.push(...s.Deleted);for(let e of s.Deleted)e.Key&&this.logger.warn?.(`${k.TAG} Deleted file: ${e.Key}`)}s.Errors?.length&&i.push(...s.Errors)}}catch(t){throw j(t,`Failed to delete files from bucket "${e}"`)}if(i.length>0){let t=i.map(e=>`${e.Key??`unknown`} (${e.Code??`Error`}: ${e.Message??`unknown error`})`).join(`; `);throw Error(`${k.TAG} Failed to delete ${i.length} file(s) from bucket "${e}": ${t}`)}return r.length||this.logger.info?.(`${k.TAG} No files deleted`),{Deleted:r,Errors:i,$metadata:a}}async collectUploadTasks(e,t,n,r,i){let a=[];for(let o of e){if(o.includes(`*`)){let e=Y(o),s=p.default.globSync(o),c=this.extractBaseDir(e,n,t),l=await this.collectUploadTasks(s,c,e,r,i);a.push(...l);continue}let e=await u.default.lstat(o);if(e.isSymbolicLink()){if(!r){this.logger.warn?.(`${k.TAG} Skipping symlink: ${o}`);continue}if((await u.default.stat(o)).isDirectory()){let e=(await u.default.readdir(o)).map(e=>d.default.join(o,e)),s=this.extractBaseDir(o,n,t),c=await this.collectUploadTasks(e,s,o,r,i);a.push(...c);continue}}else if(e.isDirectory()){let e=(await u.default.readdir(o)).map(e=>d.default.join(o,e)),s=this.extractBaseDir(o,n,t),c=await this.collectUploadTasks(e,s,o,r,i);a.push(...c);continue}X(o,i)||a.push({file:o,folderName:t})}return a}extractBaseDir(e,t,n){if(!t)return n;let r=d.default.relative(t,e);return!r||r===`.`?n:q(n,r)}async canBeReplaced(e,t,n){return!(!e.replace&&await this.fileExist(t,n))}async createIfNeeded(e,t){e.create&&this.ensureBucketFn&&await this.ensureBucketFn(t)}getExpire(e){if(e.expireDate)return e.expireDate;if(e.expire){let{value:t,unit:n}=this.getTimeSpace(e.expire);return(0,v.default)().add(t,n).toDate()}}getTimeSpace(e){let t=H.exec(e);if(!t)throw Error(`${k.TAG} Invalid time definition "${e}". Expected format like "30s", "15m", "24h", "7d", "2w", "1M", or "1y"`);let n=Number(t[1]),r=U[t[2]];if(!r||Number.isNaN(n))throw Error(`${k.TAG} Invalid time unit in "${e}"`);return{value:n,unit:r}}compressFiles(e,t,n={}){let r=d.default.basename(t);if(!r||r===`.`||r===`..`||r.includes(`*`))return Promise.reject(Error(`${k.TAG} Invalid archive filename: "${t}"`));let i=p.default.mkdtempSync(d.default.join(m.default.tmpdir(),`node-s3-`));p.default.chmodSync(i,448);let a=d.default.join(i,r),o=n.followSymlinks??!1,s=n.exclude??[];return new Promise((t,r)=>{let c=p.default.createWriteStream(a,{mode:384}),l=[],u=!1,f=e=>{u||(u=!0,l.forEach(e=>e.destroy()),c.destroy(),p.default.rmSync(i,{recursive:!0,force:!0}),r(e instanceof Error?e:Error(String(e))))},m=new _.ZipArchive({zlib:{level:n.compressionLevel??K}});c.on(`close`,()=>{u||(u=!0,t({filePath:a,tmpDir:i})),c.destroy()}),c.on(`error`,f),m.on(`warning`,e=>{this.logger.warn?.(`${k.TAG} Warning compressing file`,e),e.code!==`ENOENT`&&f(e)}),m.on(`error`,f),m.pipe(c);try{for(let t of e)if(t.includes(`*`))m.glob(t,s.length?{ignore:s}:void 0);else{let e=p.default.lstatSync(t);if(e.isSymbolicLink()&&!o){this.logger.warn?.(`${k.TAG} Skipping symlink in archive: ${t}`);continue}if((e.isSymbolicLink()?p.default.statSync(t):e).isDirectory())m.directory(t,!1,e=>!X(e.name,s)&&e);else{if(X(t,s))continue;let e=d.default.basename(t),n=p.default.createReadStream(t);n.on(`error`,f),m.append(n,{name:e}),l.push(n)}}}catch(e){f(e);return}m.finalize().catch(f)})}},$=class{bucket=``;endpoint=``;s3Sdk;ownsClient=!1;s3Buckets;s3Files;constructor(e={},t){this.setConfig(e,t)}setConfig(e={},t){this.s3Sdk&&this.ownsClient&&this.s3Sdk.destroy();let n=e.endpoint||k.ENDPOINT||void 0,r=e.accessKeyId||k.ACCESS_KEY||void 0,i=e.secretAccessKey||k.SECRET_KEY||void 0,a=e.sessionToken||k.SESSION_TOKEN||void 0,o=e.region||k.REGION||`us-east-1`,s=e.logger??console,c=!!(n&&/^http:\/\//i.test(n)),l=e.sslEnabled===void 0?!c&&k.SSL_ENABLED:e.sslEnabled;c&&e.sslEnabled===void 0&&s.warn?.(`${k.TAG} Using insecure HTTP endpoint "${n}"`);let u={region:o,tls:l,maxAttempts:(e.maxRetries??k.MAX_RETRIES)+1,forcePathStyle:e.forcePathStyle===void 0?k.FORCE_PATH_STYLE:e.forcePathStyle,...n?{endpoint:n}:{},...r&&i?{credentials:{accessKeyId:r,secretAccessKey:i,...a?{sessionToken:a}:{}}}:{}};this.bucket=e.bucket===void 0?k.BUCKET:e.bucket,this.endpoint=n||``,t?(this.s3Sdk=t,this.ownsClient=!1):(this.s3Sdk=new f.S3Client(u),this.ownsClient=!0),this.s3Files=new Q(this.s3Sdk,{ensureBucket:e=>this.ensureBucket(e),logger:s,dryRun:e.dryRun,onProgress:e.onProgress}),this.s3Buckets=new M(this.s3Sdk,e=>this.s3Files.deleteAllContent(e))}destroy(){this.s3Sdk&&this.ownsClient&&(this.s3Sdk.destroy(),this.s3Sdk=void 0,this.ownsClient=!1)}getBuckets(){return this.s3Buckets.getBuckets()}createBucket(e=this.bucket){return this.checkBucket(e),this.s3Buckets.createBucket(e)}removeBucket(e=!1,t=this.bucket){return this.checkBucket(t),this.s3Buckets.removeBucket(t,e)}bucketExist(e=this.bucket){return this.checkBucket(e),this.s3Buckets.bucketExist(e)}getFiles(e=this.bucket,t){return this.checkBucket(e),this.s3Files.getFiles(e,t)}fileInfo(e,t=this.bucket){return this.checkBucket(t),this.s3Files.fileInfo(t,e)}fileExist(e,t=this.bucket){return this.checkBucket(t),this.s3Files.fileExist(t,e)}uploadFile(e,t,n,r=this.bucket){return this.checkBucket(r),this.s3Files.uploadFile(r,e,t,n)}uploadFiles(e,t,n,r=this.bucket){return this.checkBucket(r),this.s3Files.uploadFiles(r,e,t,n)}uploadStream(e,t,n,r,i=this.bucket){return this.checkBucket(i),this.s3Files.uploadStream(i,e,t,n,r)}downloadFile(e,t,n,r=this.bucket){return this.checkBucket(r),this.s3Files.downloadFile(r,e,t,n)}deleteAllContent(e=this.bucket){return this.checkBucket(e),this.s3Files.deleteAllContent(e)}cleanOlder(e,t,n=this.bucket,r){return this.checkBucket(n),this.s3Files.cleanOlder(n,e,t,r)}createDumpFile(){return this.s3Files.createDumpFile()}async ensureBucket(e){await this.s3Buckets.bucketExist(e)||await this.s3Buckets.createBucket(e)}checkBucket(e){if(!e)throw Error(`${k.TAG} Bucket not defined`)}},ee=class{opts;s3Wrapper;isQuiet;isJson;constructor(e,t){if(this.opts=e,this.isJson=!!e.json,this.isQuiet=!!(e.quiet||e.json),t)this.s3Wrapper=t;else{let t=this.isQuiet?{info:()=>void 0,warn:()=>void 0,error:console.error}:console;this.s3Wrapper=new $({endpoint:e.endpoint,bucket:e.bucket,region:e.region,dryRun:e.dryRun,logger:t})}}async parseOptions(){let e={};return this.opts.backup?.length&&(e.backup=await this.backup(this.opts.backup)),this.opts.stdin&&(e.stdin=await this.backupStdin()),this.opts.download&&(e.download=await this.download(this.opts.download,this.opts.output)),this.opts.delete?.length&&(e.delete=await this.delete(this.opts.delete,this.opts.folder)),this.opts.mysql&&(e.mysql=await this.dumpMysql()),this.opts.list&&(e.list=await this.showList()),this.isJson&&console.info(JSON.stringify(e,null,2)),e}async showList(){let e=await this.s3Wrapper.getFiles(void 0,this.opts.folder);return this.isQuiet||(e.length?(console.info(`${k.TAG} File list in bucket "${this.s3Wrapper.bucket}": ${e.length}`),this.beautifulFiles(e)):console.info(`${k.TAG} No files found in bucket "${this.s3Wrapper.bucket}"`)),e}async delete(e,t){let n=(Array.isArray(e)?e:[e]).map(e=>{let n=this.parseDelete(e);return{folder:n.folder||t||void 0,timeSpace:n.timeSpace}}),r=[];for(let e of n){let t=await this.s3Wrapper.cleanOlder(e.timeSpace,e.folder,void 0,{dryRun:this.opts.dryRun,keepLast:this.opts.keepLast});r.push(t)}return r}async backup(e,t={}){let n={...this.opts,...t},r=Array.isArray(e)?e:[e],i=this.resolveEncryptionKey(n.encrypt),a={compress:n.zip||n.zip===null,replace:n.replace,create:n.create,storageClass:n.storageClass,acl:n.acl,serverSideEncryption:n.sse,kmsKeyId:n.kmsKeyId,expire:n.expire,exclude:n.exclude,dryRun:n.dryRun,encryptKey:i};return this.s3Wrapper.uploadFiles(r,n.folder||void 0,a)}async backupStdin(e=process.stdin){if(!this.opts.name)throw Error(`${k.TAG} --name <filename> is required when using --stdin`);let t=this.resolveEncryptionKey(this.opts.encrypt);return this.s3Wrapper.uploadStream(e,this.opts.name,this.opts.folder||void 0,{replace:this.opts.replace,create:this.opts.create,storageClass:this.opts.storageClass,acl:this.opts.acl,serverSideEncryption:this.opts.sse,kmsKeyId:this.opts.kmsKeyId,expire:this.opts.expire,dryRun:this.opts.dryRun,encryptKey:t})}async download(e,t){let n=t||d.default.basename(e),r=this.resolveEncryptionKey(this.opts.encrypt),i=await this.s3Wrapper.downloadFile(e,n,{decryptKey:r});return this.isQuiet||console.info(`${k.TAG} Downloaded "${e}" to "${i}"`),i}async dumpMysql(e={}){let t=await this.s3Wrapper.createDumpFile();try{return await this.backup(t,e)}finally{await u.default.rm(d.default.dirname(t),{recursive:!0,force:!0})}}resolveEncryptionKey(e){if(!e)return;let t=k.BACKUP_ENCRYPTION_KEY;if(!t)throw Error(`${k.TAG} --encrypt requires the $BACKUP_ENCRYPTION_KEY environment variable to be set`);return t}parseDelete(e){let t=e.indexOf(`=`);return t===-1?{folder:null,timeSpace:e}:{folder:e.slice(0,t),timeSpace:e.slice(t+1)}}beautifulFiles(e){let t=e.map(e=>e.Key).filter(e=>!!e);t.sort(),t.forEach(e=>{console.info(e)})}};function te(e){return!!(e.list||e.backup?.length||e.delete?.length||e.mysql||e.download||e.stdin)}async function ne(){let e=T();e.version?console.info(C.version):e.help||!te(e)?console.info(E()):await new ee(e).parseOptions()}ne().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(`[-] Error: ${t}`),process.exitCode=1});
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
export declare class Config {
|
|
2
|
+
static API_VERSION: string;
|
|
3
|
+
static TAG: string;
|
|
4
|
+
private static overrides;
|
|
5
|
+
static resetOverrides(): void;
|
|
6
|
+
static get ENDPOINT(): string;
|
|
7
|
+
static set ENDPOINT(value: string);
|
|
8
|
+
static get BUCKET(): string;
|
|
9
|
+
static set BUCKET(value: string);
|
|
10
|
+
static get REGION(): string;
|
|
11
|
+
static set REGION(value: string);
|
|
12
|
+
static get ACCESS_KEY(): string;
|
|
13
|
+
static set ACCESS_KEY(value: string);
|
|
14
|
+
static get SECRET_KEY(): string;
|
|
15
|
+
static set SECRET_KEY(value: string);
|
|
16
|
+
static get SESSION_TOKEN(): string;
|
|
17
|
+
static set SESSION_TOKEN(value: string);
|
|
18
|
+
static get MAX_RETRIES(): number;
|
|
19
|
+
static set MAX_RETRIES(value: number);
|
|
20
|
+
static get FORCE_PATH_STYLE(): boolean;
|
|
21
|
+
static set FORCE_PATH_STYLE(value: boolean);
|
|
22
|
+
static get SSL_ENABLED(): boolean;
|
|
23
|
+
static set SSL_ENABLED(value: boolean);
|
|
24
|
+
static get BACKUP_ENCRYPTION_KEY(): string;
|
|
25
|
+
static set BACKUP_ENCRYPTION_KEY(value: string);
|
|
26
|
+
static get MYSQL_HOST(): string;
|
|
27
|
+
static set MYSQL_HOST(value: string);
|
|
28
|
+
static get MYSQL_PORT(): number;
|
|
29
|
+
static set MYSQL_PORT(value: number);
|
|
30
|
+
static get MYSQL_USER(): string;
|
|
31
|
+
static set MYSQL_USER(value: string);
|
|
32
|
+
static get MYSQL_PASSWORD(): string;
|
|
33
|
+
static set MYSQL_PASSWORD(value: string);
|
|
34
|
+
static get MYSQL_DATABASE(): string;
|
|
35
|
+
static set MYSQL_DATABASE(value: string);
|
|
36
|
+
}
|
package/dist/crypto.d.ts
ADDED
package/dist/index.d.ts
CHANGED
|
@@ -1,46 +1,33 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
import { S3 } from 'aws-sdk';
|
|
6
|
-
|
|
7
|
-
export interface S3Config {
|
|
8
|
-
endpoint?: string;
|
|
9
|
-
bucket?: string;
|
|
10
|
-
region?: string;
|
|
11
|
-
maxRetries?: number;
|
|
12
|
-
forcePathStyle?: boolean;
|
|
13
|
-
sslEnabled?: boolean;
|
|
14
|
-
}
|
|
15
|
-
export interface UploadOptionsBasic {
|
|
16
|
-
create?: boolean;
|
|
17
|
-
replace?: boolean;
|
|
18
|
-
expire?: string;
|
|
19
|
-
expireDate?: Date;
|
|
20
|
-
}
|
|
21
|
-
export interface UploadOptions extends UploadOptionsBasic {
|
|
22
|
-
compress?: string | boolean;
|
|
23
|
-
}
|
|
1
|
+
import { Readable } from 'node:stream';
|
|
2
|
+
import { S3Client } from '@aws-sdk/client-s3';
|
|
3
|
+
import { CleanOlderOptions, DownloadOptions, S3Config, UploadOptions, UploadOptionsBasic } from './types';
|
|
24
4
|
export declare class S3Wrapper {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
5
|
+
bucket: string;
|
|
6
|
+
endpoint: string;
|
|
7
|
+
private s3Sdk?;
|
|
8
|
+
private ownsClient;
|
|
9
|
+
private s3Buckets;
|
|
10
|
+
private s3Files;
|
|
11
|
+
constructor(config?: S3Config, s3Client?: S3Client);
|
|
12
|
+
setConfig(config?: S3Config, s3Client?: S3Client): void;
|
|
13
|
+
destroy(): void;
|
|
14
|
+
getBuckets(): Promise<import("@aws-sdk/client-s3").Bucket[]>;
|
|
15
|
+
createBucket(bucket?: string): Promise<import("@aws-sdk/client-s3").CreateBucketCommandOutput>;
|
|
16
|
+
removeBucket(force?: boolean, bucket?: string): Promise<boolean>;
|
|
17
|
+
bucketExist(bucket?: string): Promise<boolean>;
|
|
18
|
+
getFiles(bucket?: string, prefix?: string): Promise<import("@aws-sdk/client-s3")._Object[]>;
|
|
19
|
+
fileInfo(name: string, bucket?: string): Promise<import("@aws-sdk/client-s3").HeadObjectCommandOutput>;
|
|
20
|
+
fileExist(name: string, bucket?: string): Promise<boolean>;
|
|
21
|
+
uploadFile(file: string, folderName?: string, options?: UploadOptionsBasic, bucket?: string): Promise<import("@aws-sdk/client-s3").CompleteMultipartUploadCommandOutput>;
|
|
22
|
+
uploadFiles(files: string | string[], folderName?: string, options?: UploadOptions, bucket?: string): Promise<Record<string, import("@aws-sdk/client-s3").CompleteMultipartUploadCommandOutput>>;
|
|
23
|
+
uploadStream(stream: Readable, filename: string, folderName?: string, options?: UploadOptionsBasic, bucket?: string): Promise<import("@aws-sdk/client-s3").CompleteMultipartUploadCommandOutput>;
|
|
24
|
+
downloadFile(key: string, destPath: string, options?: DownloadOptions, bucket?: string): Promise<string>;
|
|
25
|
+
deleteAllContent(bucket?: string): Promise<import("@aws-sdk/client-s3").DeleteObjectsCommandOutput>;
|
|
26
|
+
cleanOlder(timeSpace: string, folderName?: string, bucket?: string, options?: CleanOlderOptions): Promise<import("@aws-sdk/client-s3").DeleteObjectsCommandOutput>;
|
|
27
|
+
createDumpFile(): Promise<string>;
|
|
28
|
+
private ensureBucket;
|
|
29
|
+
private checkBucket;
|
|
44
30
|
}
|
|
45
|
-
|
|
46
|
-
export {};
|
|
31
|
+
export { createDecryptStream, createEncryptStream } from './crypto';
|
|
32
|
+
export { normalizeS3Key } from './s3/files';
|
|
33
|
+
export * from './types';
|