@d0whc3r/node-s3 1.4.0 → 1.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/dist/s3.es.mjs CHANGED
@@ -5,26 +5,28 @@ import d from "node:os";
5
5
  import f from "node:path";
6
6
  import { pipeline as p } from "node:stream/promises";
7
7
  import { Upload as m } from "@aws-sdk/lib-storage";
8
- import { ZipArchive as h } from "archiver";
9
- import g from "dayjs";
10
- import _ from "mime-types";
11
- import v from "mysqldump";
12
- import y from "node:crypto";
13
- import { Transform as b } from "node:stream";
8
+ import { ZipArchive as ee } from "archiver";
9
+ import h from "dayjs";
10
+ import te from "mime-types";
11
+ import g from "mysqldump";
12
+ import _ from "node:crypto";
13
+ import { PassThrough as v, Transform as y } from "node:stream";
14
+ import { spawn as b } from "node:child_process";
15
+ import { DatabaseSync as ne, backup as x } from "node:sqlite";
14
16
  // src/config.ts
15
- function x(e, t) {
17
+ function S(e, t) {
16
18
  return e === void 0 || e.trim() === "" ? t : [
17
19
  "true",
18
20
  "1",
19
21
  "yes"
20
22
  ].includes(e.trim().toLowerCase());
21
23
  }
22
- function S(e, t) {
24
+ function C(e, t) {
23
25
  if (e === void 0 || e.trim() === "") return t;
24
26
  let n = Number(e);
25
27
  return Number.isNaN(n) ? t : n;
26
28
  }
27
- var C = class {
29
+ var w = class {
28
30
  static API_VERSION = "2006-03-01";
29
31
  static TAG = "[node-s3]";
30
32
  static overrides = {};
@@ -68,19 +70,19 @@ var C = class {
68
70
  this.overrides.SESSION_TOKEN = e;
69
71
  }
70
72
  static get MAX_RETRIES() {
71
- return "MAX_RETRIES" in this.overrides ? this.overrides.MAX_RETRIES : S(process.env.MAX_RETRIES, 3);
73
+ return "MAX_RETRIES" in this.overrides ? this.overrides.MAX_RETRIES : C(process.env.MAX_RETRIES, 3);
72
74
  }
73
75
  static set MAX_RETRIES(e) {
74
76
  this.overrides.MAX_RETRIES = e;
75
77
  }
76
78
  static get FORCE_PATH_STYLE() {
77
- return "FORCE_PATH_STYLE" in this.overrides ? this.overrides.FORCE_PATH_STYLE : x(process.env.FORCE_PATH_STYLE, !0);
79
+ return "FORCE_PATH_STYLE" in this.overrides ? this.overrides.FORCE_PATH_STYLE : S(process.env.FORCE_PATH_STYLE, !0);
78
80
  }
79
81
  static set FORCE_PATH_STYLE(e) {
80
82
  this.overrides.FORCE_PATH_STYLE = e;
81
83
  }
82
84
  static get SSL_ENABLED() {
83
- return "SSL_ENABLED" in this.overrides ? this.overrides.SSL_ENABLED : x(process.env.SSL_ENABLED, !0);
85
+ return "SSL_ENABLED" in this.overrides ? this.overrides.SSL_ENABLED : S(process.env.SSL_ENABLED, !0);
84
86
  }
85
87
  static set SSL_ENABLED(e) {
86
88
  this.overrides.SSL_ENABLED = e;
@@ -98,7 +100,7 @@ var C = class {
98
100
  this.overrides.MYSQL_HOST = e;
99
101
  }
100
102
  static get MYSQL_PORT() {
101
- return "MYSQL_PORT" in this.overrides ? this.overrides.MYSQL_PORT : S(process.env.MYSQL_PORT, 3306);
103
+ return "MYSQL_PORT" in this.overrides ? this.overrides.MYSQL_PORT : C(process.env.MYSQL_PORT, 3306);
102
104
  }
103
105
  static set MYSQL_PORT(e) {
104
106
  this.overrides.MYSQL_PORT = e;
@@ -121,24 +123,21 @@ var C = class {
121
123
  static set MYSQL_DATABASE(e) {
122
124
  this.overrides.MYSQL_DATABASE = e;
123
125
  }
124
- };
125
- // src/s3/buckets.ts
126
- function w(e) {
126
+ }, T = /* @__PURE__ */ new Set([
127
+ "NotFound",
128
+ "NoSuchBucket",
129
+ "NoSuchKey",
130
+ "404"
131
+ ]);
132
+ function E(e) {
127
133
  if (!e || typeof e != "object") return !1;
128
134
  let t = e;
129
- if (t.$metadata?.httpStatusCode === 404) return !0;
130
- let n = [
131
- "NotFound",
132
- "NoSuchBucket",
133
- "NoSuchKey",
134
- "404"
135
- ];
136
- return !!(t.name && n.includes(t.name) || t.Code && n.includes(t.Code));
135
+ return t.$metadata?.httpStatusCode === 404 || !!(t.name && T.has(t.name) || t.Code && T.has(t.Code));
137
136
  }
138
- function T(e, t) {
139
- return e instanceof Error ? Error(`${C.TAG} ${t}: ${e.message}`, { cause: e }) : Error(`${C.TAG} ${t}: ${String(e)}`, { cause: e });
137
+ function D(e, t) {
138
+ return e instanceof Error ? Error(`${w.TAG} ${t}: ${e.message}`, { cause: e }) : Error(`${w.TAG} ${t}: ${String(e)}`, { cause: e });
140
139
  }
141
- var E = class {
140
+ var re = class {
142
141
  s3Sdk;
143
142
  deleteAllContentFn;
144
143
  constructor(e, t) {
@@ -148,14 +147,14 @@ var E = class {
148
147
  try {
149
148
  return (await this.s3Sdk.send(new o({}))).Buckets || [];
150
149
  } catch (e) {
151
- throw T(e, "Failed to list buckets");
150
+ throw D(e, "Failed to list buckets");
152
151
  }
153
152
  }
154
153
  async createBucket(t) {
155
154
  try {
156
155
  return await this.s3Sdk.send(new e({ Bucket: t }));
157
156
  } catch (e) {
158
- throw T(e, `Failed to create bucket "${t}"`);
157
+ throw D(e, `Failed to create bucket "${t}"`);
159
158
  }
160
159
  }
161
160
  async removeBucket(e, n = !1) {
@@ -163,31 +162,31 @@ var E = class {
163
162
  return await this.s3Sdk.send(new t({ Bucket: e })), !0;
164
163
  } catch (t) {
165
164
  if (n && this.deleteAllContentFn) return await this.deleteAllContentFn(e), this.removeBucket(e, !1);
166
- throw T(t, `Failed to remove bucket "${e}"`);
165
+ throw D(t, `Failed to remove bucket "${e}"`);
167
166
  }
168
167
  }
169
168
  async bucketExist(e) {
170
169
  try {
171
170
  return await this.s3Sdk.send(new i({ Bucket: e })), !0;
172
171
  } catch (t) {
173
- if (w(t)) return !1;
174
- throw T(t, `Failed to check bucket "${e}"`);
172
+ if (E(t)) return !1;
173
+ throw D(t, `Failed to check bucket "${e}"`);
175
174
  }
176
175
  }
177
- }, D = Buffer.from("NS3E", "ascii"), O = 1, k = 16, A = 12, j = 32, M = 16, N = D.length + 1 + k + A;
178
- function P(e) {
179
- if (!e) throw Error(`${C.TAG} Encryption key must be a non-empty string`);
176
+ }, O = Buffer.from("NS3E", "ascii"), k = 1, A = 16, j = 12, M = 32, N = 16, P = O.length + 1 + A + j;
177
+ function F(e) {
178
+ if (!e) throw Error(`${w.TAG} Encryption key must be a non-empty string`);
180
179
  let t = null, n = (n) => {
181
- let i = y.randomBytes(k), a = y.randomBytes(A);
182
- y.scrypt(e, i, j, (e, o) => {
183
- e ? n(e) : (t = y.createCipheriv("aes-256-gcm", o, a), r.push(Buffer.concat([
184
- D,
185
- Buffer.from([O]),
180
+ let i = _.randomBytes(A), a = _.randomBytes(j);
181
+ _.scrypt(e, i, M, (e, o) => {
182
+ e ? n(e) : (t = _.createCipheriv("aes-256-gcm", o, a), r.push(Buffer.concat([
183
+ O,
184
+ Buffer.from([k]),
186
185
  i,
187
186
  a
188
187
  ])), n());
189
188
  });
190
- }, r = new b({
189
+ }, r = new y({
191
190
  transform(e, r, i) {
192
191
  let a = () => {
193
192
  try {
@@ -217,17 +216,17 @@ function P(e) {
217
216
  });
218
217
  return r;
219
218
  }
220
- function F(e) {
221
- if (!e) throw Error(`${C.TAG} Decryption key must be a non-empty string`);
219
+ function I(e) {
220
+ if (!e) throw Error(`${w.TAG} Decryption key must be a non-empty string`);
222
221
  let t = Buffer.alloc(0), n = Buffer.alloc(0), r = null;
223
- return new b({
222
+ return new y({
224
223
  transform(i, a, o) {
225
224
  let s = (e) => {
226
225
  try {
227
226
  let t = n.length > 0 ? Buffer.concat([n, e]) : e;
228
- if (t.length > M) {
229
- let e = t.subarray(0, t.length - M);
230
- n = t.subarray(t.length - M);
227
+ if (t.length > N) {
228
+ let e = t.subarray(0, t.length - N);
229
+ n = t.subarray(t.length - N);
231
230
  let i = r.update(e);
232
231
  i.length > 0 && this.push(i);
233
232
  } else n = t;
@@ -240,39 +239,39 @@ function F(e) {
240
239
  s(i);
241
240
  return;
242
241
  }
243
- if (t = t.length > 0 ? Buffer.concat([t, i]) : i, t.length < N) {
242
+ if (t = t.length > 0 ? Buffer.concat([t, i]) : i, t.length < P) {
244
243
  o();
245
244
  return;
246
245
  }
247
- if (!t.subarray(0, D.length).equals(D)) {
248
- o(/* @__PURE__ */ Error(`${C.TAG} Invalid encrypted stream header`));
246
+ if (!t.subarray(0, O.length).equals(O)) {
247
+ o(/* @__PURE__ */ Error(`${w.TAG} Invalid encrypted stream header`));
249
248
  return;
250
249
  }
251
- let c = t[D.length];
252
- if (c !== O) {
253
- o(/* @__PURE__ */ Error(`${C.TAG} Unsupported encryption format version: ${c}`));
250
+ let c = t[O.length];
251
+ if (c !== k) {
252
+ o(/* @__PURE__ */ Error(`${w.TAG} Unsupported encryption format version: ${c}`));
254
253
  return;
255
254
  }
256
- let l = D.length + 1, u = l + k, d = t.subarray(l, u), f = t.subarray(u, N), p = t.subarray(N);
257
- t = Buffer.alloc(0), y.scrypt(e, d, j, (e, t) => {
258
- e ? o(e) : (r = y.createDecipheriv("aes-256-gcm", t, f), s(p));
255
+ let l = O.length + 1, u = l + A, d = t.subarray(l, u), f = t.subarray(u, P), p = t.subarray(P);
256
+ t = Buffer.alloc(0), _.scrypt(e, d, M, (e, t) => {
257
+ e ? o(e) : (r = _.createDecipheriv("aes-256-gcm", t, f), s(p));
259
258
  });
260
259
  },
261
260
  flush(e) {
262
- if (!r) e(/* @__PURE__ */ Error(`${C.TAG} Encrypted stream is truncated or empty`));
263
- else if (n.length !== M) e(/* @__PURE__ */ Error(`${C.TAG} Encrypted stream is missing authentication tag`));
261
+ if (!r) e(/* @__PURE__ */ Error(`${w.TAG} Encrypted stream is truncated or empty`));
262
+ else if (n.length !== N) e(/* @__PURE__ */ Error(`${w.TAG} Encrypted stream is missing authentication tag`));
264
263
  else try {
265
264
  r.setAuthTag(n);
266
265
  let t = r.final();
267
266
  t.length > 0 && this.push(t), e();
268
267
  } catch (t) {
269
- e(Error(`${C.TAG} Decryption failed: invalid key or corrupted data`, { cause: t }));
268
+ e(Error(`${w.TAG} Decryption failed: invalid key or corrupted data`, { cause: t }));
270
269
  }
271
270
  }
272
271
  });
273
272
  }
274
273
  // src/s3/files.ts
275
- var I = /^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|years?)$/, L = {
274
+ var ie = /^(\d+)([a-zA-Z]+)$/, ae = {
276
275
  s: "second",
277
276
  second: "second",
278
277
  seconds: "second",
@@ -294,45 +293,44 @@ var I = /^(\d+)(s|m|h|d|w|M|y|seconds?|minutes?|hours?|days?|weeks?|months?|year
294
293
  y: "year",
295
294
  year: "year",
296
295
  years: "year"
297
- }, R = 1e3, z = 4, B = 6;
298
- function V(...e) {
296
+ }, L = 1e3, oe = 4, se = 6;
297
+ function R(...e) {
299
298
  let t = [];
300
299
  for (let n of e) {
301
300
  if (!n) continue;
302
- let e = n.replace(/\\/g, "/");
301
+ let e = n.replaceAll("\\", "/");
303
302
  for (let r of e.split("/")) if (r && r !== ".") {
304
- if (r === "..") throw Error(`${C.TAG} Invalid S3 key segment ".." in "${n}"`);
303
+ if (r === "..") throw Error(`${w.TAG} Invalid S3 key segment ".." in "${n}"`);
305
304
  t.push(r);
306
305
  }
307
306
  }
308
307
  return f.posix.join(...t);
309
308
  }
310
- function H(e) {
309
+ function ce(e) {
311
310
  if (!e) return;
312
- let t = V(e);
311
+ let t = R(e);
313
312
  return t ? `${t}/` : void 0;
314
313
  }
315
- function U(e) {
314
+ function le(e) {
316
315
  let t = e.search(/[*?[{]/);
317
316
  if (t === -1) return e;
318
317
  let n = e.slice(0, t);
319
318
  return n ? n.endsWith("/") || n.endsWith("\\") ? n.slice(0, -1) || "." : f.dirname(n) : ".";
320
319
  }
321
- function W(e, t) {
320
+ function z(e, t) {
322
321
  if (!t.length) return !1;
323
- let n = e.replace(/\\/g, "/"), r = f.posix.basename(n);
322
+ let n = e.replaceAll("\\", "/"), r = f.posix.basename(n);
324
323
  return t.some((e) => f.matchesGlob(n, e) || f.matchesGlob(r, e));
325
324
  }
326
- async function G(e, t, n) {
325
+ async function B(e, t, n) {
327
326
  let r = Array.from({ length: e.length }), i = Math.max(1, Math.min(t, e.length)), a = 0, o = async () => {
328
- for (; a < e.length;) {
329
- let t = a;
330
- a += 1, r[t] = await n(e[t]);
331
- }
327
+ if (a >= e.length) return;
328
+ let t = a;
329
+ a += 1, r[t] = await n(e[t]), await o();
332
330
  };
333
331
  return await Promise.all(Array.from({ length: i }, () => o())), r;
334
332
  }
335
- var K = class {
333
+ var V = class {
336
334
  s3Sdk;
337
335
  defaultUploadOptions = {
338
336
  create: !0,
@@ -346,42 +344,41 @@ var K = class {
346
344
  this.s3Sdk = e, this.ensureBucketFn = t.ensureBucket, this.logger = t.logger ?? console, this.defaultDryRun = t.dryRun ?? !1, this.defaultOnProgress = t.onProgress;
347
345
  }
348
346
  async getFiles(e, t) {
349
- let n = t ? H(t) : void 0, r = [], i;
347
+ let n = t ? ce(t) : void 0, r = [], i = async (t) => {
348
+ let a = await this.s3Sdk.send(new s({
349
+ Bucket: e,
350
+ ...n ? { Prefix: n } : {},
351
+ ...t ? { ContinuationToken: t } : {}
352
+ }));
353
+ a.Contents && r.push(...a.Contents), a.IsTruncated && a.NextContinuationToken && await i(a.NextContinuationToken);
354
+ };
350
355
  try {
351
- do {
352
- let t = await this.s3Sdk.send(new s({
353
- Bucket: e,
354
- ...n ? { Prefix: n } : {},
355
- ...i ? { ContinuationToken: i } : {}
356
- }));
357
- t.Contents && r.push(...t.Contents), i = t.IsTruncated ? t.NextContinuationToken : void 0;
358
- } while (i);
359
- return r;
356
+ return await i(), r;
360
357
  } catch (t) {
361
- throw T(t, `Failed to list files in bucket "${e}"`);
358
+ throw D(t, `Failed to list files in bucket "${e}"`);
362
359
  }
363
360
  }
364
361
  async fileInfo(e, t) {
365
- let n = V(t);
362
+ let n = R(t);
366
363
  try {
367
364
  return await this.s3Sdk.send(new a({
368
365
  Bucket: e,
369
366
  Key: n
370
367
  }));
371
368
  } catch (t) {
372
- throw T(t, `Failed to get info for "${n}" in bucket "${e}"`);
369
+ throw D(t, `Failed to get info for "${n}" in bucket "${e}"`);
373
370
  }
374
371
  }
375
372
  async fileExist(e, t) {
376
- let n = V(t);
373
+ let n = R(t);
377
374
  try {
378
375
  return await this.s3Sdk.send(new a({
379
376
  Bucket: e,
380
377
  Key: n
381
378
  })), !0;
382
379
  } catch (t) {
383
- if (w(t)) return !1;
384
- throw T(t, `Failed to check existence of "${n}" in bucket "${e}"`);
380
+ if (E(t)) return !1;
381
+ throw D(t, `Failed to check existence of "${n}" in bucket "${e}"`);
385
382
  }
386
383
  }
387
384
  async deleteAllContent(e) {
@@ -389,11 +386,11 @@ var K = class {
389
386
  return this.deleteFiles(e, t);
390
387
  }
391
388
  async uploadFile(e, t, n, r) {
392
- let i = f.basename(t), a = V(n, i), o = {
389
+ let i = f.basename(t), a = R(n, i), o = {
393
390
  ...this.defaultUploadOptions,
394
391
  ...r
395
392
  };
396
- if (o.dryRun ?? this.defaultDryRun) return this.logger.info?.(`${C.TAG} [dry-run] Would upload "${t}" to "s3://${e}/${a}"`), {
393
+ if (o.dryRun ?? this.defaultDryRun) return this.logger.info?.(`${w.TAG} [dry-run] Would upload "${t}" to "s3://${e}/${a}"`), {
397
394
  Bucket: e,
398
395
  Key: a,
399
396
  $metadata: {}
@@ -407,21 +404,21 @@ var K = class {
407
404
  }
408
405
  async uploadStream(e, t, n, r, i) {
409
406
  let a = f.basename(n);
410
- if (!a || a === "." || a === "..") throw Error(`${C.TAG} Invalid upload filename: "${n}"`);
411
- let o = V(r, a), s = _.contentType(a) || void 0, c = {
407
+ if (!a || a === "." || a === "..") throw Error(`${w.TAG} Invalid upload filename: "${n}"`);
408
+ let o = R(r, a), s = te.contentType(a) || void 0, c = {
412
409
  ...this.defaultUploadOptions,
413
410
  ...i
414
411
  };
415
- if (c.dryRun ?? this.defaultDryRun) return this.logger.info?.(`${C.TAG} [dry-run] Would upload stream "${a}" to "s3://${e}/${o}"`), {
412
+ if (c.dryRun ?? this.defaultDryRun) return this.logger.info?.(`${w.TAG} [dry-run] Would upload stream "${a}" to "s3://${e}/${o}"`), {
416
413
  Bucket: e,
417
414
  Key: o,
418
415
  $metadata: {}
419
416
  };
420
417
  let l = this.getExpire(c);
421
- if (c.skipBucketCheck || await this.createIfNeeded(c, e), !await this.canBeReplaced(c, e, o)) throw Error(`${C.TAG} File "${o}" already exists in bucket "${e}" and will not be replaced`);
418
+ if (c.skipBucketCheck || await this.createIfNeeded(c, e), !await this.canBeReplaced(c, e, o)) throw Error(`${w.TAG} File "${o}" already exists in bucket "${e}" and will not be replaced`);
422
419
  let u = t, d;
423
420
  if (c.encryptKey) {
424
- let e = P(c.encryptKey);
421
+ let e = F(c.encryptKey);
425
422
  t.on("error", (t) => {
426
423
  e.destroy(t);
427
424
  }), u = t.pipe(e), d = u;
@@ -451,7 +448,7 @@ var K = class {
451
448
  });
452
449
  }), await t.done();
453
450
  } catch (t) {
454
- throw T(t, `Failed to upload "${o}" to bucket "${e}"`);
451
+ throw D(t, `Failed to upload "${o}" to bucket "${e}"`);
455
452
  } finally {
456
453
  d?.destroy();
457
454
  }
@@ -460,7 +457,9 @@ var K = class {
460
457
  let i = Array.isArray(t) ? t : [t], a = {
461
458
  ...this.defaultUploadOptions,
462
459
  ...r
463
- }, o = a.dryRun ?? this.defaultDryRun, s = a.exclude ? Array.isArray(a.exclude) ? a.exclude : [a.exclude] : [], c = a.followSymlinks ?? !1;
460
+ }, o = a.dryRun ?? this.defaultDryRun, s = [];
461
+ a.exclude && (s = Array.isArray(a.exclude) ? a.exclude : [a.exclude]);
462
+ let c = a.followSymlinks ?? !1;
464
463
  !a.skipBucketCheck && !o && await this.createIfNeeded(a, e);
465
464
  let l = {
466
465
  replace: a.replace,
@@ -477,7 +476,7 @@ var K = class {
477
476
  skipBucketCheck: !0
478
477
  };
479
478
  if (a.compress) {
480
- let t = typeof a.compress == "string" ? a.compress : `zipped_${g().format("YYYY-MM-DD.HHmmss")}.zip`, { filePath: r, tmpDir: o } = await this.compressFiles(i, t, {
479
+ let t = typeof a.compress == "string" ? a.compress : `zipped_${h().format("YYYY-MM-DD.HHmmss")}.zip`, { filePath: r, tmpDir: o } = await this.compressFiles(i, t, {
481
480
  compressionLevel: a.compressionLevel,
482
481
  followSymlinks: c,
483
482
  exclude: s
@@ -492,7 +491,7 @@ var K = class {
492
491
  });
493
492
  }
494
493
  }
495
- let d = await this.collectUploadTasks(i, n, a.baseDir, c, s), f = a.concurrency ?? z, p = {}, m = await G(d, f, async (t) => {
494
+ let d = await this.collectUploadTasks(i, n, a.baseDir, c, s), f = a.concurrency ?? oe, p = {}, m = await B(d, f, async (t) => {
496
495
  let n = await this.uploadFile(e, t.file, t.folderName, l);
497
496
  return {
498
497
  file: t.file,
@@ -503,30 +502,30 @@ var K = class {
503
502
  return p;
504
503
  }
505
504
  async downloadFile(e, t, n, i = {}) {
506
- let a = V(t);
505
+ let a = R(t);
507
506
  try {
508
507
  let t = await this.s3Sdk.send(new r({
509
508
  Bucket: e,
510
509
  Key: a
511
510
  }));
512
- if (!t.Body) throw Error(`${C.TAG} Empty response body for "${a}"`);
511
+ if (!t.Body) throw Error(`${w.TAG} Empty response body for "${a}"`);
513
512
  await u.mkdir(f.dirname(f.resolve(n)), { recursive: !0 });
514
513
  let o = t.Body, s = l.createWriteStream(n);
515
514
  if (i.decryptKey) {
516
- let e = F(i.decryptKey);
515
+ let e = I(i.decryptKey);
517
516
  await p(o, e, s);
518
517
  } else await p(o, s);
519
518
  return n;
520
519
  } catch (t) {
521
- throw T(t, `Failed to download "${a}" from bucket "${e}"`);
520
+ throw D(t, `Failed to download "${a}" from bucket "${e}"`);
522
521
  }
523
522
  }
524
523
  async cleanOlder(e, t, n, r = {}) {
525
- let { value: i, unit: a } = this.getTimeSpace(t), o = g().subtract(i, a), s = (await this.getFiles(e, n)).filter((e) => !!(e.Key && e.LastModified));
524
+ let { value: i, unit: a } = this.getTimeSpace(t), o = h().subtract(i, a), s = (await this.getFiles(e, n)).filter((e) => !!(e.Key && e.LastModified));
526
525
  s.sort((e, t) => (t.LastModified?.getTime() ?? 0) - (e.LastModified?.getTime() ?? 0));
527
- let c = r.keepLast ?? 0, l = (c > 0 ? s.slice(c) : s).filter((e) => g(e.LastModified).isBefore(o)).map((e) => ({ Key: e.Key }));
526
+ let c = r.keepLast ?? 0, l = (c > 0 ? s.slice(c) : s).filter((e) => h(e.LastModified).isBefore(o)).map((e) => ({ Key: e.Key }));
528
527
  if (r.dryRun ?? this.defaultDryRun) {
529
- for (let e of l) e.Key && this.logger.info?.(`${C.TAG} [dry-run] Would delete file: ${e.Key}`);
528
+ for (let e of l) e.Key && this.logger.info?.(`${w.TAG} [dry-run] Would delete file: ${e.Key}`);
530
529
  return {
531
530
  Deleted: l.map((e) => ({ Key: e.Key })),
532
531
  Errors: [],
@@ -536,9 +535,9 @@ var K = class {
536
535
  return this.deleteFiles(e, l);
537
536
  }
538
537
  async createDumpFile() {
539
- let e = C.MYSQL_HOST, t = C.MYSQL_PORT, n = C.MYSQL_USER, r = C.MYSQL_PASSWORD, i = C.MYSQL_DATABASE;
540
- if (!n || !r || !i) throw Error(`${C.TAG} Error in mysql-dump environment variables not defined: $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT`);
541
- let { dump: a } = await v({ connection: {
538
+ let e = w.MYSQL_HOST, t = w.MYSQL_PORT, n = w.MYSQL_USER, r = w.MYSQL_PASSWORD, i = w.MYSQL_DATABASE;
539
+ if (!n || !r || !i) throw Error(`${w.TAG} Error in mysql-dump environment variables not defined: $MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT`);
540
+ let { dump: a } = await g({ connection: {
542
541
  host: e,
543
542
  port: t,
544
543
  user: n,
@@ -546,77 +545,72 @@ var K = class {
546
545
  database: i
547
546
  } }), o = await u.mkdtemp(f.join(d.tmpdir(), "node-s3-dump-"));
548
547
  await u.chmod(o, 448);
549
- let s = f.join(o, `mysqldump-${g().format("YYYY-MM-DD.HHmmss")}.sql`), c = Object.values(a).map((e) => e && e.replace(/^# /gm, "-- ")).join("\n\n");
548
+ let s = f.join(o, `mysqldump-${h().format("YYYY-MM-DD.HHmmss")}.sql`), c = Object.values(a).map((e) => e?.replace(/^# /gm, "-- ")).join("\n\n");
550
549
  return await u.writeFile(s, c, { mode: 384 }), s;
551
550
  }
552
551
  async deleteFiles(e, t) {
553
552
  let r = t.filter((e) => !!e.Key);
554
- if (!r.length) return this.logger.info?.(`${C.TAG} No files deleted`), {
553
+ if (!r.length) return this.logger.info?.(`${w.TAG} No files deleted`), {
555
554
  Deleted: [],
556
555
  Errors: [],
557
556
  $metadata: {}
558
557
  };
559
- let i = [], a = [], o = {};
558
+ let i = [];
559
+ for (let e = 0; e < r.length; e += L) i.push(r.slice(e, e + L));
560
+ let a;
560
561
  try {
561
- for (let t = 0; t < r.length; t += R) {
562
- let s = { Objects: r.slice(t, t + R) }, c = await this.s3Sdk.send(new n({
562
+ a = await Promise.all(i.map((t) => {
563
+ let r = { Objects: t };
564
+ return this.s3Sdk.send(new n({
563
565
  Bucket: e,
564
- Delete: s
566
+ Delete: r
565
567
  }));
566
- if (o = c.$metadata, c.Deleted?.length) {
567
- i.push(...c.Deleted);
568
- for (let e of c.Deleted) e.Key && this.logger.warn?.(`${C.TAG} Deleted file: ${e.Key}`);
569
- }
570
- c.Errors?.length && a.push(...c.Errors);
571
- }
568
+ }));
572
569
  } catch (t) {
573
- throw T(t, `Failed to delete files from bucket "${e}"`);
570
+ throw D(t, `Failed to delete files from bucket "${e}"`);
574
571
  }
575
- if (a.length > 0) {
576
- let t = a.map((e) => `${e.Key ?? "unknown"} (${e.Code ?? "Error"}: ${e.Message ?? "unknown error"})`).join("; ");
577
- throw Error(`${C.TAG} Failed to delete ${a.length} file(s) from bucket "${e}": ${t}`);
572
+ let o = [], s = [], c = {};
573
+ for (let e of a) c = e.$metadata, this.collectDeleteBatchResults(e, o, s);
574
+ if (s.length > 0) {
575
+ let t = s.map((e) => `${e.Key ?? "unknown"} (${e.Code ?? "Error"}: ${e.Message ?? "unknown error"})`).join("; ");
576
+ throw Error(`${w.TAG} Failed to delete ${s.length} file(s) from bucket "${e}": ${t}`);
578
577
  }
579
- return i.length || this.logger.info?.(`${C.TAG} No files deleted`), {
580
- Deleted: i,
581
- Errors: a,
582
- $metadata: o
578
+ return o.length || this.logger.info?.(`${w.TAG} No files deleted`), {
579
+ Deleted: o,
580
+ Errors: s,
581
+ $metadata: c
583
582
  };
584
583
  }
584
+ collectDeleteBatchResults(e, t, n) {
585
+ if (e.Deleted?.length) {
586
+ t.push(...e.Deleted);
587
+ for (let t of e.Deleted) t.Key && this.logger.warn?.(`${w.TAG} Deleted file: ${t.Key}`);
588
+ }
589
+ e.Errors?.length && n.push(...e.Errors);
590
+ }
585
591
  async collectUploadTasks(e, t, n, r, i) {
586
- let a = [];
587
- for (let o of e) {
588
- if (o.includes("*")) {
589
- let e = U(o), s = l.globSync(o), c = this.extractBaseDir(e, n, t), u = await this.collectUploadTasks(s, c, e, r, i);
590
- a.push(...u);
591
- continue;
592
- }
593
- let e = await u.lstat(o);
594
- if (e.isSymbolicLink()) {
595
- if (!r) {
596
- this.logger.warn?.(`${C.TAG} Skipping symlink: ${o}`);
597
- continue;
598
- }
599
- if ((await u.stat(o)).isDirectory()) {
600
- let e = (await u.readdir(o)).map((e) => f.join(o, e)), s = this.extractBaseDir(o, n, t), c = await this.collectUploadTasks(e, s, o, r, i);
601
- a.push(...c);
602
- continue;
603
- }
604
- } else if (e.isDirectory()) {
605
- let e = (await u.readdir(o)).map((e) => f.join(o, e)), s = this.extractBaseDir(o, n, t), c = await this.collectUploadTasks(e, s, o, r, i);
606
- a.push(...c);
607
- continue;
608
- }
609
- W(o, i) || a.push({
610
- file: o,
611
- folderName: t
612
- });
592
+ return (await Promise.all(e.map((e) => this.collectTasksForEntry(e, t, n, r, i)))).flat();
593
+ }
594
+ async collectTasksForEntry(e, t, n, r, i) {
595
+ if (e.includes("*")) {
596
+ let a = le(e), o = l.globSync(e), s = this.extractBaseDir(a, n, t);
597
+ return this.collectUploadTasks(o, s, a, r, i);
613
598
  }
614
- return a;
599
+ let a = await u.lstat(e);
600
+ if (a.isSymbolicLink() && !r) return this.logger.warn?.(`${w.TAG} Skipping symlink: ${e}`), [];
601
+ if ((a.isSymbolicLink() ? await u.stat(e) : a).isDirectory()) {
602
+ let a = (await u.readdir(e)).map((t) => f.join(e, t)), o = this.extractBaseDir(e, n, t);
603
+ return this.collectUploadTasks(a, o, e, r, i);
604
+ }
605
+ return z(e, i) ? [] : [{
606
+ file: e,
607
+ folderName: t
608
+ }];
615
609
  }
616
610
  extractBaseDir(e, t, n) {
617
611
  if (!t) return n;
618
612
  let r = f.relative(t, e);
619
- return !r || r === "." ? n : V(n, r);
613
+ return !r || r === "." ? n : R(n, r);
620
614
  }
621
615
  async canBeReplaced(e, t, n) {
622
616
  return !(!e.replace && await this.fileExist(t, n));
@@ -628,63 +622,441 @@ var K = class {
628
622
  if (e.expireDate) return e.expireDate;
629
623
  if (e.expire) {
630
624
  let { value: t, unit: n } = this.getTimeSpace(e.expire);
631
- return g().add(t, n).toDate();
625
+ return h().add(t, n).toDate();
632
626
  }
633
627
  }
634
628
  getTimeSpace(e) {
635
- let t = I.exec(e);
636
- if (!t) throw Error(`${C.TAG} Invalid time definition "${e}". Expected format like "30s", "15m", "24h", "7d", "2w", "1M", or "1y"`);
637
- let n = Number(t[1]), r = L[t[2]];
638
- if (!r || Number.isNaN(n)) throw Error(`${C.TAG} Invalid time unit in "${e}"`);
629
+ let t = ie.exec(e), n = t ? ae[t[2]] : void 0;
630
+ if (!t || !n) throw Error(`${w.TAG} Invalid time definition "${e}". Expected format like "30s", "15m", "24h", "7d", "2w", "1M", or "1y"`);
631
+ let r = Number(t[1]);
632
+ if (Number.isNaN(r)) throw TypeError(`${w.TAG} Invalid time unit in "${e}"`);
639
633
  return {
640
- value: n,
641
- unit: r
634
+ value: r,
635
+ unit: n
642
636
  };
643
637
  }
638
+ appendFileToArchive(e, t, n) {
639
+ if (t.includes("*")) {
640
+ e.glob(t, n.excludePatterns.length ? { ignore: n.excludePatterns } : void 0);
641
+ return;
642
+ }
643
+ let r = l.lstatSync(t);
644
+ if (r.isSymbolicLink() && !n.followSymlinks) {
645
+ this.logger.warn?.(`${w.TAG} Skipping symlink in archive: ${t}`);
646
+ return;
647
+ }
648
+ if ((r.isSymbolicLink() ? l.statSync(t) : r).isDirectory()) {
649
+ e.directory(t, !1, (e) => !z(e.name, n.excludePatterns) && e);
650
+ return;
651
+ }
652
+ if (z(t, n.excludePatterns)) return;
653
+ let i = f.basename(t), a = l.createReadStream(t);
654
+ a.on("error", n.fail), e.append(a, { name: i }), n.readStreams.push(a);
655
+ }
644
656
  compressFiles(e, t, n = {}) {
645
657
  let r = f.basename(t);
646
- if (!r || r === "." || r === ".." || r.includes("*")) return Promise.reject(/* @__PURE__ */ Error(`${C.TAG} Invalid archive filename: "${t}"`));
658
+ if (!r || r === "." || r === ".." || r.includes("*")) return Promise.reject(/* @__PURE__ */ Error(`${w.TAG} Invalid archive filename: "${t}"`));
647
659
  let i = l.mkdtempSync(f.join(d.tmpdir(), "node-s3-"));
648
660
  l.chmodSync(i, 448);
649
661
  let a = f.join(i, r), o = n.followSymlinks ?? !1, s = n.exclude ?? [];
650
662
  return new Promise((t, r) => {
651
- let c = l.createWriteStream(a, { mode: 384 }), u = [], d = !1, p = (e) => {
663
+ let c = l.createWriteStream(a, { mode: 384 }), u = [], d = !1, f = (e) => {
652
664
  d || (d = !0, u.forEach((e) => e.destroy()), c.destroy(), l.rmSync(i, {
653
665
  recursive: !0,
654
666
  force: !0
655
667
  }), r(e instanceof Error ? e : Error(String(e))));
656
- }, m = new h({ zlib: { level: n.compressionLevel ?? B } });
668
+ }, p = new ee({ zlib: { level: n.compressionLevel ?? se } });
657
669
  c.on("close", () => {
658
670
  d || (d = !0, t({
659
671
  filePath: a,
660
672
  tmpDir: i
661
673
  })), c.destroy();
662
- }), c.on("error", p), m.on("warning", (e) => {
663
- this.logger.warn?.(`${C.TAG} Warning compressing file`, e), e.code !== "ENOENT" && p(e);
664
- }), m.on("error", p), m.pipe(c);
674
+ }), c.on("error", f), p.on("warning", (e) => {
675
+ this.logger.warn?.(`${w.TAG} Warning compressing file`, e), e.code !== "ENOENT" && f(e);
676
+ }), p.on("error", f), p.pipe(c);
665
677
  try {
666
- for (let t of e) if (t.includes("*")) m.glob(t, s.length ? { ignore: s } : void 0);
667
- else {
668
- let e = l.lstatSync(t);
669
- if (e.isSymbolicLink() && !o) {
670
- this.logger.warn?.(`${C.TAG} Skipping symlink in archive: ${t}`);
671
- continue;
672
- }
673
- if ((e.isSymbolicLink() ? l.statSync(t) : e).isDirectory()) m.directory(t, !1, (e) => !W(e.name, s) && e);
674
- else {
675
- if (W(t, s)) continue;
676
- let e = f.basename(t), n = l.createReadStream(t);
677
- n.on("error", p), m.append(n, { name: e }), u.push(n);
678
- }
679
- }
678
+ for (let t of e) this.appendFileToArchive(p, t, {
679
+ followSymlinks: o,
680
+ excludePatterns: s,
681
+ readStreams: u,
682
+ fail: f
683
+ });
680
684
  } catch (e) {
681
- p(e);
685
+ f(e);
682
686
  return;
683
687
  }
684
- m.finalize().catch(p);
688
+ p.finalize().catch(f);
689
+ });
690
+ }
691
+ }, H = 16384;
692
+ function U(e) {
693
+ let t = (process.env.PATH || "").split(f.delimiter).filter(Boolean), n = process.platform === "win32" ? (process.env.PATHEXT || ".EXE;.CMD;.BAT").split(";") : [""];
694
+ for (let r of e) if (r.includes(f.sep) || r.includes("/")) {
695
+ if (W(r)) return r;
696
+ } else for (let e of t) for (let t of n) {
697
+ let n = f.join(e, `${r}${t}`);
698
+ if (W(n)) return n;
699
+ }
700
+ }
701
+ function W(e) {
702
+ try {
703
+ return l.statSync(e).isFile() ? (l.accessSync(e, l.constants.X_OK), !0) : !1;
704
+ } catch {
705
+ return !1;
706
+ }
707
+ }
708
+ function G(e) {
709
+ return e.replace(/([a-zA-Z][a-zA-Z0-9+.-]*:\/\/[^:@/\s]+):([^@/\s]+)@/g, "$1:***@");
710
+ }
711
+ function K(e) {
712
+ return e.replace(/[^a-zA-Z0-9._-]/g, "_").replace(/^_+|_+$/g, "") || "db";
713
+ }
714
+ function q(e) {
715
+ let t = b(e.binary, e.args, {
716
+ env: e.env ? {
717
+ ...process.env,
718
+ ...e.env
719
+ } : process.env,
720
+ stdio: [
721
+ "ignore",
722
+ "pipe",
723
+ "pipe"
724
+ ],
725
+ shell: !1
726
+ }), n = new v(), r = [], i = 0, a, o = () => (a ||= Promise.resolve(e.onCleanup?.()), a);
727
+ t.stderr.on("data", (e) => {
728
+ if (i < H) {
729
+ let t = H - i;
730
+ r.push(e.subarray(0, t)), i += Math.min(e.length, t);
731
+ }
732
+ }), t.stdout.pipe(n, { end: !1 });
733
+ let s = !1, c, l, u = new Promise((e, t) => {
734
+ c = e, l = t;
735
+ });
736
+ u.catch(() => void 0);
737
+ let d = (e) => {
738
+ s || (s = !0, o(), n.destroyed || n.destroy(e), l(e));
739
+ };
740
+ return t.on("error", (t) => {
741
+ t.code === "ENOENT" ? d(/* @__PURE__ */ Error(`${e.tag} "${e.binary}" not found in PATH. ${e.installHint}`)) : d(/* @__PURE__ */ Error(`${e.tag} Failed to start "${e.binary}": ${t.message}`));
742
+ }), t.on("close", (t, i) => {
743
+ if (s) return;
744
+ if (t === 0) {
745
+ s = !0, o(), n.end(), c();
746
+ return;
747
+ }
748
+ let a = Buffer.concat(r).toString("utf8").trim(), l = a ? `: ${G(a)}` : "", u = i ? `terminated by signal ${i}` : `exited with code ${t ?? "unknown"}`;
749
+ d(/* @__PURE__ */ Error(`${e.tag} ${e.binary} ${u}${l}`));
750
+ }), {
751
+ kind: "stream",
752
+ engine: e.engine,
753
+ filename: e.filename,
754
+ mimeType: e.mimeType,
755
+ stream: n,
756
+ wait: () => u,
757
+ cleanup: async () => {
758
+ !s && !t.killed && t.kill("SIGTERM"), n.destroyed || n.destroy(), await o();
759
+ }
760
+ };
761
+ }
762
+ // src/db/providers/mongodb.ts
763
+ function ue(e) {
764
+ return !!(e && /^mongodb(?:\+srv)?:\/\//i.test(e));
765
+ }
766
+ function J(e) {
767
+ return JSON.stringify(e);
768
+ }
769
+ var de = {
770
+ engine: "mongodb",
771
+ aliases: ["mongo"],
772
+ async dump(e) {
773
+ let t = e.tag ?? "[db]", n = U(["mongodump"]);
774
+ if (!n) throw Error(`${t} "mongodump" not found in PATH. Install mongodb-database-tools or use the :db Docker image.`);
775
+ let r = e.url || process.env.MONGODB_URI || (ue(process.env.DATABASE_URL) ? process.env.DATABASE_URL : void 0), i = ["--archive"], a = "mongodb", o = "";
776
+ if (r) {
777
+ let t = "";
778
+ try {
779
+ t = new URL(r).pathname.replace(/^\/+/, "");
780
+ } catch {}
781
+ a = e.database || t || "mongodb", o = `uri: ${J(r)}\n`, e.database && i.push("--db", e.database);
782
+ } else {
783
+ let n = e.host || process.env.MONGO_HOST || "localhost", r = e.port ?? (process.env.MONGO_PORT ? Number(process.env.MONGO_PORT) : 27017), s = e.user || process.env.MONGO_USER || "", c = e.password ?? process.env.MONGO_PASSWORD ?? "", l = e.database || process.env.MONGO_DATABASE || "", u = process.env.MONGO_AUTH_DB || "";
784
+ if (!l && !e.host && !process.env.MONGO_HOST) throw Error(`${t} Missing MongoDB configuration. Set $MONGODB_URI (or $MONGO_DATABASE / $MONGO_HOST / --db-url).`);
785
+ a = l || "all", i.push("--host", n, "--port", String(r)), l && i.push("--db", l), s && i.push("--username", s), u && i.push("--authenticationDatabase", u), c && (o = `password: ${J(c)}\n`);
786
+ }
787
+ let s;
788
+ if (o) {
789
+ s = await u.mkdtemp(f.join(d.tmpdir(), "db-mongo-cfg-")), await u.chmod(s, 448);
790
+ let e = f.join(s, "mongodump.conf");
791
+ await u.writeFile(e, o, { mode: 384 }), i.push(`--config=${e}`);
792
+ }
793
+ return e.extraArgs?.length && i.push(...e.extraArgs), q({
794
+ engine: "mongodb",
795
+ binary: n,
796
+ args: i,
797
+ filename: e.filename || `mongodump-${K(a)}-${h().format("YYYY-MM-DD.HHmmss")}.archive`,
798
+ mimeType: "application/octet-stream",
799
+ tag: t,
800
+ installHint: "Install mongodb-database-tools or use the :db Docker image.",
801
+ onCleanup: async () => {
802
+ s && await u.rm(s, {
803
+ recursive: !0,
804
+ force: !0
805
+ });
806
+ }
807
+ });
808
+ }
809
+ };
810
+ // src/db/providers/mysql.ts
811
+ function fe(e) {
812
+ return !!(e && /^(?:mysql|mariadb):\/\//i.test(e));
813
+ }
814
+ function pe(e, t) {
815
+ let n = e.url || (fe(process.env.DATABASE_URL) ? process.env.DATABASE_URL : void 0);
816
+ if (n) {
817
+ let r = new URL(n), i = e.host || r.hostname || "localhost", a = e.port ?? (r.port ? Number(r.port) : 3306), o = e.user || decodeURIComponent(r.username || ""), s = e.password ?? decodeURIComponent(r.password || ""), c = e.database || r.pathname.replace(/^\/+/, "");
818
+ if (!o || !c) throw Error(`${t} Invalid MySQL/MariaDB URL: username and database name are required.`);
819
+ return {
820
+ host: i,
821
+ port: a,
822
+ user: o,
823
+ password: s,
824
+ database: c
825
+ };
826
+ }
827
+ let r = e.host || process.env.MYSQL_HOST || "localhost", i = e.port ?? (process.env.MYSQL_PORT ? Number(process.env.MYSQL_PORT) : 3306), a = e.user || process.env.MYSQL_USER || "", o = e.password ?? process.env.MYSQL_PASSWORD ?? "", s = e.database || process.env.MYSQL_DATABASE || "";
828
+ if (!a || !o || !s) throw Error(`${t} Missing required MySQL environment variables ($MYSQL_USER, $MYSQL_PASSWORD, $MYSQL_DATABASE, $MYSQL_HOST, $MYSQL_PORT) or --db-url.`);
829
+ return {
830
+ host: r,
831
+ port: i,
832
+ user: a,
833
+ password: o,
834
+ database: s
835
+ };
836
+ }
837
+ async function me(e, t) {
838
+ let { dump: n } = await g({ connection: {
839
+ host: e.host,
840
+ port: e.port,
841
+ user: e.user,
842
+ password: e.password,
843
+ database: e.database
844
+ } }), r = await u.mkdtemp(f.join(d.tmpdir(), "db-mysql-"));
845
+ await u.chmod(r, 448);
846
+ let i = f.join(r, t), a = Object.values(n).filter((e) => !!e).map((e) => e.replace(/^# /gm, "-- ")).join("\n\n");
847
+ return await u.writeFile(i, a, { mode: 384 }), {
848
+ kind: "file",
849
+ engine: "mysql",
850
+ filename: t,
851
+ mimeType: "application/sql",
852
+ filePath: i,
853
+ tempDir: r,
854
+ cleanup: async () => {
855
+ await u.rm(r, {
856
+ recursive: !0,
857
+ force: !0
858
+ });
859
+ }
860
+ };
861
+ }
862
+ var he = {
863
+ engine: "mysql",
864
+ aliases: ["mariadb"],
865
+ async dump(e) {
866
+ let t = e.tag ?? "[db]", n = pe(e, t), r = e.filename || `mysqldump-${K(n.database)}-${h().format("YYYY-MM-DD.HHmmss")}.sql`, i = U(["mysqldump", "mariadb-dump"]);
867
+ if (!i) return me(n, r);
868
+ let a = [
869
+ "--single-transaction",
870
+ "--quick",
871
+ "--routines",
872
+ "--triggers",
873
+ "-h",
874
+ n.host,
875
+ "-P",
876
+ String(n.port),
877
+ "-u",
878
+ n.user,
879
+ ...e.extraArgs ?? [],
880
+ n.database
881
+ ], o = {};
882
+ return n.password && (o.MYSQL_PWD = n.password), q({
883
+ engine: "mysql",
884
+ binary: i,
885
+ args: a,
886
+ env: o,
887
+ filename: r,
888
+ mimeType: "application/sql",
889
+ tag: t,
890
+ installHint: "Install mariadb-client / mysql-client or use the :db Docker image."
685
891
  });
686
892
  }
687
- }, q = class {
893
+ }, ge = {
894
+ plain: {
895
+ ext: "sql",
896
+ mimeType: "application/sql"
897
+ },
898
+ custom: {
899
+ ext: "dump",
900
+ mimeType: "application/octet-stream"
901
+ },
902
+ tar: {
903
+ ext: "tar",
904
+ mimeType: "application/x-tar"
905
+ }
906
+ };
907
+ function _e(e) {
908
+ return !!(e && /^postgres(?:ql)?:\/\//i.test(e));
909
+ }
910
+ function ve(e) {
911
+ let t = new URL(e), n = t.password ? decodeURIComponent(t.password) : void 0, r = t.pathname.replace(/^\/+/, "") || "postgres";
912
+ return t.password = "", {
913
+ sanitizedDbNameArg: t.toString(),
914
+ password: n,
915
+ database: r
916
+ };
917
+ }
918
+ var ye = {
919
+ engine: "postgres",
920
+ aliases: ["pg", "postgresql"],
921
+ async dump(e) {
922
+ let t = e.tag ?? "[db]", n = e.format ?? "plain", r = ge[n];
923
+ if (!r) throw Error(`${t} Unsupported PostgreSQL dump format "${String(n)}". Expected one of: plain, custom, tar.`);
924
+ let i = U(["pg_dump"]);
925
+ if (!i) throw Error(`${t} "pg_dump" not found in PATH. Install postgresql-client (e.g. apt install postgresql-client / brew install libpq) or use the :db Docker image.`);
926
+ let a = e.url || (_e(process.env.DATABASE_URL) ? process.env.DATABASE_URL : void 0), o = ["--no-password", `--format=${n}`], s = {}, c;
927
+ if (a) {
928
+ let t = ve(a);
929
+ c = e.database || t.database, (e.password ?? t.password) && (s.PGPASSWORD = e.password ?? t.password), o.push(`--dbname=${t.sanitizedDbNameArg}`);
930
+ } else {
931
+ let n = e.host || process.env.PGHOST || "localhost", r = e.port ?? (process.env.PGPORT ? Number(process.env.PGPORT) : 5432), i = e.user || process.env.PGUSER || "", a = e.password ?? process.env.PGPASSWORD, o = e.database || process.env.PGDATABASE || "";
932
+ if (!o) throw Error(`${t} Missing PostgreSQL database configuration. Set $PGDATABASE (or $DATABASE_URL / --db-url).`);
933
+ c = o, s.PGHOST = n, s.PGPORT = String(r), i && (s.PGUSER = i), a !== void 0 && a !== "" && (s.PGPASSWORD = a), s.PGDATABASE = o;
934
+ }
935
+ return e.extraArgs?.length && o.push(...e.extraArgs), q({
936
+ engine: "postgres",
937
+ binary: i,
938
+ args: o,
939
+ env: s,
940
+ filename: e.filename || `pgdump-${K(c)}-${h().format("YYYY-MM-DD.HHmmss")}.${r.ext}`,
941
+ mimeType: r.mimeType,
942
+ tag: t,
943
+ installHint: "Install postgresql-client or use the :db Docker image."
944
+ });
945
+ }
946
+ };
947
+ // src/db/providers/sqlite.ts
948
+ function be(e) {
949
+ return !!(e && /^(?:sqlite3?:|file:)/i.test(e));
950
+ }
951
+ function xe(e, t) {
952
+ let n = e.database || e.url || process.env.SQLITE_PATH || (be(process.env.DATABASE_URL) ? process.env.DATABASE_URL : "");
953
+ if (!n) throw Error(`${t} Missing SQLite database path. Set $SQLITE_PATH (or --db-url sqlite:///path/to/db.sqlite).`);
954
+ let r = n;
955
+ /^sqlite3?:\/\//i.test(n) ? r = decodeURIComponent(n.replace(/^sqlite3?:\/\//i, "")) : /^sqlite3?:/i.test(n) ? r = decodeURIComponent(n.replace(/^sqlite3?:/i, "")) : /^file:/i.test(n) && (r = decodeURIComponent(n.replace(/^file:(\/\/)?/i, "")));
956
+ let i = f.resolve(r);
957
+ if (!l.existsSync(i) || !l.statSync(i).isFile()) throw Error(`${t} SQLite database file not found: "${i}"`);
958
+ return i;
959
+ }
960
+ // src/db/index.ts
961
+ var Y = [
962
+ ye,
963
+ he,
964
+ de,
965
+ {
966
+ engine: "sqlite",
967
+ aliases: ["sqlite3"],
968
+ async dump(e) {
969
+ let t = xe(e, e.tag ?? "[db]"), n = f.basename(t, f.extname(t)), r = e.filename || `sqlite-${K(n)}-${h().format("YYYY-MM-DD.HHmmss")}.sqlite`, i = await u.mkdtemp(f.join(d.tmpdir(), "db-sqlite-"));
970
+ await u.chmod(i, 448);
971
+ let a = f.join(i, r), o = new ne(t, { readOnly: !0 });
972
+ try {
973
+ await x(o, a), await u.chmod(a, 384);
974
+ } catch (e) {
975
+ throw await u.rm(i, {
976
+ recursive: !0,
977
+ force: !0
978
+ }), e;
979
+ } finally {
980
+ o.close();
981
+ }
982
+ return {
983
+ kind: "file",
984
+ engine: "sqlite",
985
+ filename: r,
986
+ mimeType: "application/vnd.sqlite3",
987
+ filePath: a,
988
+ tempDir: i,
989
+ cleanup: async () => {
990
+ await u.rm(i, {
991
+ recursive: !0,
992
+ force: !0
993
+ });
994
+ }
995
+ };
996
+ }
997
+ }
998
+ ], X = /* @__PURE__ */ new Map();
999
+ for (let e of Y) {
1000
+ X.set(e.engine, e);
1001
+ for (let t of e.aliases) X.set(t, e);
1002
+ }
1003
+ var Z = Y.map((e) => e.engine);
1004
+ function Q(e, t = "[db]") {
1005
+ let n = e.trim().toLowerCase(), r = X.get(n);
1006
+ if (!r) throw Error(`${t} Unsupported database engine "${e}". Supported engines: ${Z.join(", ")}.`);
1007
+ return r.engine;
1008
+ }
1009
+ function $(e, t = "[db]") {
1010
+ let n = e.trim();
1011
+ if (/^postgres(?:ql)?:\/\//i.test(n)) return "postgres";
1012
+ if (/^(?:mysql|mariadb):\/\//i.test(n)) return "mysql";
1013
+ if (/^mongodb(?:\+srv)?:\/\//i.test(n)) return "mongodb";
1014
+ if (/^(?:sqlite3?:|file:)/i.test(n)) return "sqlite";
1015
+ throw Error(`${t} Could not detect database engine from URL. Supported schemes: postgresql://, mysql://, mariadb://, mongodb://, sqlite://.`);
1016
+ }
1017
+ async function Se(e) {
1018
+ let t = await u.mkdtemp(f.join(d.tmpdir(), `db-${e.engine}-`));
1019
+ await u.chmod(t, 448);
1020
+ let n = f.join(t, f.basename(e.filename));
1021
+ try {
1022
+ let t = l.createWriteStream(n, { mode: 384 });
1023
+ await p(e.stream, t), await e.wait();
1024
+ } catch (n) {
1025
+ throw await e.cleanup(), await u.rm(t, {
1026
+ recursive: !0,
1027
+ force: !0
1028
+ }), n;
1029
+ }
1030
+ return {
1031
+ kind: "file",
1032
+ engine: e.engine,
1033
+ filename: e.filename,
1034
+ mimeType: e.mimeType,
1035
+ filePath: n,
1036
+ tempDir: t,
1037
+ cleanup: async () => {
1038
+ await u.rm(t, {
1039
+ recursive: !0,
1040
+ force: !0
1041
+ });
1042
+ }
1043
+ };
1044
+ }
1045
+ async function Ce(e) {
1046
+ let t = e.tag ?? "[db]", n;
1047
+ if (e.engine) n = Q(e.engine, t);
1048
+ else if (e.url) n = $(e.url, t);
1049
+ else if (process.env.DATABASE_URL) n = $(process.env.DATABASE_URL, t);
1050
+ else throw Error(`${t} Database engine not specified. Pass --db <${Z.join("|")}> or --db-url <uri>.`);
1051
+ let r = await X.get(n).dump({
1052
+ ...e,
1053
+ engine: n,
1054
+ tag: t
1055
+ });
1056
+ return e.preferFile && r.kind === "stream" ? Se(r) : r;
1057
+ }
1058
+ // src/index.ts
1059
+ var we = class {
688
1060
  bucket = "";
689
1061
  endpoint = "";
690
1062
  s3Sdk;
@@ -696,26 +1068,30 @@ var K = class {
696
1068
  }
697
1069
  setConfig(e = {}, t) {
698
1070
  this.s3Sdk && this.ownsClient && this.s3Sdk.destroy();
699
- let n = e.endpoint || C.ENDPOINT || void 0, r = e.accessKeyId || C.ACCESS_KEY || void 0, i = e.secretAccessKey || C.SECRET_KEY || void 0, a = e.sessionToken || C.SESSION_TOKEN || void 0, o = e.region || C.REGION || "us-east-1", s = e.logger ?? console, l = !!(n && /^http:\/\//i.test(n)), u = e.sslEnabled === void 0 ? !l && C.SSL_ENABLED : e.sslEnabled;
700
- l && e.sslEnabled === void 0 && s.warn?.(`${C.TAG} Using insecure HTTP endpoint "${n}"`);
701
- let d = {
702
- region: o,
703
- tls: u,
704
- maxAttempts: (e.maxRetries ?? C.MAX_RETRIES) + 1,
705
- forcePathStyle: e.forcePathStyle === void 0 ? C.FORCE_PATH_STYLE : e.forcePathStyle,
706
- ...n ? { endpoint: n } : {},
707
- ...r && i ? { credentials: {
708
- accessKeyId: r,
709
- secretAccessKey: i,
710
- ...a ? { sessionToken: a } : {}
711
- } } : {}
712
- };
713
- this.bucket = e.bucket === void 0 ? C.BUCKET : e.bucket, this.endpoint = n || "", t ? (this.s3Sdk = t, this.ownsClient = !1) : (this.s3Sdk = new c(d), this.ownsClient = !0), this.s3Files = new K(this.s3Sdk, {
1071
+ let n = e.endpoint || w.ENDPOINT || void 0, r = e.logger ?? console, i = this.buildClientOptions(e, n, r);
1072
+ this.bucket = e.bucket ?? w.BUCKET, this.endpoint = n || "", t ? (this.s3Sdk = t, this.ownsClient = !1) : (this.s3Sdk = new c(i), this.ownsClient = !0), this.s3Files = new V(this.s3Sdk, {
714
1073
  ensureBucket: (e) => this.ensureBucket(e),
715
- logger: s,
1074
+ logger: r,
716
1075
  dryRun: e.dryRun,
717
1076
  onProgress: e.onProgress
718
- }), this.s3Buckets = new E(this.s3Sdk, (e) => this.s3Files.deleteAllContent(e));
1077
+ }), this.s3Buckets = new re(this.s3Sdk, (e) => this.s3Files.deleteAllContent(e));
1078
+ }
1079
+ buildClientOptions(e, t, n) {
1080
+ let r = e.accessKeyId || w.ACCESS_KEY || void 0, i = e.secretAccessKey || w.SECRET_KEY || void 0, a = e.sessionToken || w.SESSION_TOKEN || void 0, o = e.region || w.REGION || "us-east-1", s = !!(t && /^http:\/\//i.test(t)), c = !s && w.SSL_ENABLED, l = e.sslEnabled ?? c;
1081
+ s && e.sslEnabled === void 0 && n.warn?.(`${w.TAG} Using insecure HTTP endpoint "${t}"`);
1082
+ let u = r && i ? {
1083
+ accessKeyId: r,
1084
+ secretAccessKey: i,
1085
+ ...a ? { sessionToken: a } : {}
1086
+ } : void 0;
1087
+ return {
1088
+ region: o,
1089
+ tls: l,
1090
+ maxAttempts: (e.maxRetries ?? w.MAX_RETRIES) + 1,
1091
+ forcePathStyle: e.forcePathStyle ?? w.FORCE_PATH_STYLE,
1092
+ ...t ? { endpoint: t } : {},
1093
+ ...u ? { credentials: u } : {}
1094
+ };
719
1095
  }
720
1096
  destroy() {
721
1097
  this.s3Sdk && this.ownsClient && (this.s3Sdk.destroy(), this.s3Sdk = void 0, this.ownsClient = !1);
@@ -766,7 +1142,7 @@ var K = class {
766
1142
  await this.s3Buckets.bucketExist(e) || await this.s3Buckets.createBucket(e);
767
1143
  }
768
1144
  checkBucket(e) {
769
- if (!e) throw Error(`${C.TAG} Bucket not defined`);
1145
+ if (!e) throw Error(`${w.TAG} Bucket not defined`);
770
1146
  }
771
1147
  };
772
- export { q as S3Wrapper, F as createDecryptStream, P as createEncryptStream, V as normalizeS3Key };
1148
+ export { we as S3Wrapper, Z as SUPPORTED_DB_ENGINES, I as createDecryptStream, F as createEncryptStream, $ as detectDbEngineFromUrl, Ce as dumpDatabase, Q as normalizeDbEngine, R as normalizeS3Key };