@d0paminedriven/fs 6.1.0 → 6.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.
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  MimeService
3
- } from "./chunk-EHOBCDHE.js";
3
+ } from "./chunk-O4BKLMFV.js";
4
4
  import {
5
5
  unitsObj
6
- } from "./chunk-4X5DVWVM.js";
6
+ } from "./chunk-MXEE2WS7.js";
7
7
  import {
8
8
  __name
9
9
  } from "./chunk-7QVYU63E.js";
@@ -12,6 +12,7 @@ import {
12
12
  import { execSync } from "child_process";
13
13
  import fsSync from "fs";
14
14
  import fsAsync from "fs/promises";
15
+ import { tmpdir } from "os";
15
16
  import { join, relative, resolve } from "path";
16
17
  import * as dotenv from "dotenv";
17
18
  import expand from "dotenv-expand";
@@ -21,6 +22,7 @@ var Fs = class extends MimeService {
21
22
  constructor(cwd) {
22
23
  super();
23
24
  this.cwd = cwd;
25
+ cwd ??= process.cwd();
24
26
  }
25
27
  static {
26
28
  __name(this, "Fs");
@@ -28,6 +30,12 @@ var Fs = class extends MimeService {
28
30
  get myEnv() {
29
31
  return dotenv.config({ processEnv: {} });
30
32
  }
33
+ get tmpDir() {
34
+ return tmpdir();
35
+ }
36
+ get tmpDirRelative() {
37
+ return relative(this.cwd, tmpdir());
38
+ }
31
39
  parseDotEnv() {
32
40
  return expand.expand(this.myEnv);
33
41
  }
@@ -141,7 +149,11 @@ var Fs = class extends MimeService {
141
149
  *
142
150
  * @returns an array of strings representing the contents of the directory
143
151
  */
144
- readDir(path, options = { recursive: true }) {
152
+ readDir(path, options = {
153
+ recursive: true,
154
+ withFileTypes: false,
155
+ encoding: "utf-8"
156
+ }) {
145
157
  if (this.isRootPathTargeted(path)) {
146
158
  return this.handleBuffStrArrUnion(
147
159
  fsSync.readdirSync(resolve(join(this.cwd, "./")), { ...options })
@@ -302,6 +314,9 @@ var Fs = class extends MimeService {
302
314
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
303
315
  fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
304
316
  ), "fileToBuffer");
317
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
318
+ return await fsAsync.readFile(relative(this.cwd, path));
319
+ }, "fileToBufferAsync");
305
320
  dirContainsDir(readDir, targetDir, options) {
306
321
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
307
322
  }
@@ -318,10 +333,11 @@ var Fs = class extends MimeService {
318
333
  };
319
334
  }
320
335
  async assetToBufferView(path) {
321
- const response = await fetch(path);
336
+ const response = await fetch(path, { method: "GET" });
322
337
  if (!response.ok) {
323
338
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
324
339
  }
340
+ console.log(Object.fromEntries(Array.from(response.headers.entries())));
325
341
  const reader = response.body?.getReader();
326
342
  if (reader) {
327
343
  const chunks = Array.of();
@@ -388,13 +404,37 @@ var Fs = class extends MimeService {
388
404
  return console.error(err);
389
405
  }
390
406
  }
391
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
407
+ /**
408
+ *
409
+ * @param inputUrl remote url to fetch data from
410
+ * @param outputPath desired output path relative to the cwd
411
+ * @param useDetectedExtension optional, defaults to true
412
+ *
413
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
414
+ *
415
+ * 🚫 'public/assets/image-1'
416
+ *
417
+ * ✅ 'public/assets/image-1.png'
418
+ *
419
+ * @description
420
+ * This method is designed for large files that may not fit into memory.
421
+ * It streams the data directly to disk instead of loading it all into memory.
422
+ */
423
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
392
424
  const MAX_SAFE_IN_MEMORY_MB = 100;
393
425
  try {
394
- const head = await fetch(inputUrl, { method: "HEAD" });
426
+ const isGithubRaw = inputUrl.startsWith(
427
+ "https://raw.githubusercontent.com"
428
+ );
429
+ const head = await fetch(inputUrl, {
430
+ method: isGithubRaw ? "GET" : "HEAD"
431
+ });
395
432
  const contentLength = head.headers.get("content-length");
396
433
  const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
397
- const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
434
+ let outputPath = outputPathI;
435
+ const assetTypeViaUrl = this.assetType(inputUrl);
436
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
437
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
398
438
  this.generateDirIfDNE(this.pathHandler(formattedPath), {
399
439
  recursive: true
400
440
  });
@@ -425,6 +465,149 @@ var Fs = class extends MimeService {
425
465
  console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
426
466
  }
427
467
  }
468
+ findBox(buffer, type, start = 0, end = buffer.length) {
469
+ let pos = start;
470
+ while (pos < end) {
471
+ let boxSize = buffer.readUInt32BE(pos);
472
+ let boxType = buffer.toString("ascii", pos + 4, pos + 8);
473
+ let hdrSize = 8;
474
+ if (boxSize === 1) {
475
+ boxSize = Number(buffer.readBigUInt64BE(pos + 8));
476
+ hdrSize = 16;
477
+ } else if (boxSize === 0) {
478
+ boxSize = end - pos;
479
+ }
480
+ if (boxType === type) {
481
+ return { pos: pos + hdrSize, size: boxSize - hdrSize };
482
+ }
483
+ pos += boxSize;
484
+ }
485
+ return null;
486
+ }
487
+ async getImageSize(filePath) {
488
+ const buffer = await this.fileToBufferAsync(filePath);
489
+ if (buffer?.length >= 24 && buffer?.[0] === 137 && buffer?.[1] === 80 && buffer?.[2] === 78 && buffer?.[3] === 71 && buffer?.[4] === 13 && buffer?.[5] === 10 && buffer?.[6] === 26 && buffer?.[7] === 10) {
490
+ if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
491
+ throw new Error("IHDR Chunk of png not found or incorrect.");
492
+ }
493
+ return {
494
+ width: buffer.readUInt32BE(16),
495
+ height: buffer.readUInt32BE(20),
496
+ type: "png"
497
+ };
498
+ }
499
+ if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
500
+ let pos = 2;
501
+ while (pos < buffer.length - 10) {
502
+ if (buffer[pos] !== 255) {
503
+ throw new Error("Invalid JPEG file");
504
+ }
505
+ const marker = buffer[pos + 1];
506
+ if (marker === 218) break;
507
+ const segmentSize = buffer.readUInt16BE(pos + 2);
508
+ if (!marker) {
509
+ throw new Error("no marker for jpeg");
510
+ }
511
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
512
+ return {
513
+ width: buffer.readUInt16BE(pos + 7),
514
+ height: buffer.readUInt16BE(pos + 5),
515
+ type: "jpeg"
516
+ };
517
+ }
518
+ pos += segmentSize + 2;
519
+ }
520
+ throw new Error("No dimensions found in JPEG file");
521
+ }
522
+ const gifHeader = buffer.toString("ascii", 0, 6);
523
+ if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
524
+ return {
525
+ width: buffer.readUInt16LE(6),
526
+ height: buffer.readUInt16LE(8),
527
+ type: "gif"
528
+ };
529
+ }
530
+ if (buffer.length >= 26 && buffer[0] === 66 && buffer[1] === 77) {
531
+ return {
532
+ width: buffer.readInt32LE(18),
533
+ height: Math.abs(buffer.readInt32LE(22)),
534
+ type: "bmp"
535
+ };
536
+ }
537
+ if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
538
+ const chunkType = buffer.toString("ascii", 12, 16);
539
+ if (chunkType === "VP8X") {
540
+ let widthSubtractOne = 0;
541
+ let heightSubtractOne = 0;
542
+ if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
543
+ widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
544
+ }
545
+ if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
546
+ heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
547
+ }
548
+ return {
549
+ width: widthSubtractOne + 1,
550
+ height: heightSubtractOne + 1,
551
+ type: "webp"
552
+ };
553
+ } else if (chunkType === "VP8 ") {
554
+ const dataStart = 20;
555
+ if (buffer[dataStart + 3] !== 157 || buffer[dataStart + 4] !== 1 || buffer[dataStart + 5] !== 42) {
556
+ throw new Error("Invalid VP8 keyframe");
557
+ }
558
+ const width = buffer.readUInt16LE(dataStart + 6) & 16383;
559
+ const height = buffer.readUInt16LE(dataStart + 8) & 16383;
560
+ return {
561
+ width,
562
+ height,
563
+ type: "webp"
564
+ };
565
+ } else if (chunkType === "VP8L") {
566
+ const dataStart = 20;
567
+ if (buffer[dataStart] !== 47) {
568
+ throw new Error("Invalid VP8L signature");
569
+ }
570
+ const bits = buffer.readUInt32LE(dataStart + 1);
571
+ if (bits >>> 29 !== 0) {
572
+ throw new Error("Invalid VP8L version");
573
+ }
574
+ const width = 1 + (bits & 16383);
575
+ const height = 1 + (bits >> 14 & 16383);
576
+ return {
577
+ width,
578
+ height,
579
+ type: "webp"
580
+ };
581
+ }
582
+ throw new Error("Unsupported WebP chunk");
583
+ }
584
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
585
+ const ftyp = this.findBox(buffer, "ftyp");
586
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
587
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
588
+ if (!brands.includes("avif") && !brands.includes("avis"))
589
+ throw new Error("Not an AVIF file");
590
+ const meta = this.findBox(buffer, "meta");
591
+ if (!meta) throw new Error("Invalid AVIF: No meta");
592
+ const metaSubStart = meta.pos + 4;
593
+ const metaSubEnd = meta.pos + meta.size;
594
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
595
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
596
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
597
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
598
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
599
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
600
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
601
+ const width = buffer.readUInt32BE(ispe.pos + 4);
602
+ const height = buffer.readUInt32BE(ispe.pos + 8);
603
+ return {
604
+ width,
605
+ height,
606
+ type: "avif"
607
+ };
608
+ }
609
+ throw new Error("Unsupported image format or invalid file");
610
+ }
428
611
  /**
429
612
  *
430
613
  * @access package-private
@@ -451,9 +634,232 @@ var Fs = class extends MimeService {
451
634
  return await sharp(target).toFormat(format, { quality }).toBuffer();
452
635
  }
453
636
  }
637
+ /**
638
+ * Write data to a file in the system's tmp directory
639
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
640
+ * @param data The data to write
641
+ * @param options Optional write stream options
642
+ * @returns The full path to the written file
643
+ * @example
644
+ * ```ts
645
+ * const fs = new Fs(process.cwd());
646
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
647
+ * // Or with a subdirectory:
648
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
649
+ * ```
650
+ */
651
+ writeTmp(filename, data, options) {
652
+ const fullPath = resolve(this.tmpDir, filename);
653
+ Promise.resolve(this.withWs(fullPath, data, options));
654
+ }
655
+ /**
656
+ * Read a file from the tmp directory
657
+ * @param filename The filename to read (can include subdirectories)
658
+ * @returns Buffer containing the file data
659
+ * @example
660
+ * ```ts
661
+ * const fs = new Fs(process.cwd());
662
+ * const data = fs.readTmp("session-data.json");
663
+ * const parsed = JSON.parse(data.toString("utf-8"));
664
+ * ```
665
+ */
666
+ readTmp(filename) {
667
+ const fullPath = resolve(this.tmpDir, filename);
668
+ if (!this.exists(fullPath)) {
669
+ throw new Error(`Tmp file not found: ${filename}`);
670
+ }
671
+ return this.fileToBuffer(fullPath);
672
+ }
673
+ /**
674
+ * Scan the tmp directory for files matching a pattern
675
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
676
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
677
+ * @returns Array of matching file paths relative to tmp directory
678
+ * @example
679
+ * ```ts
680
+ * const fs = new Fs(process.cwd());
681
+ * // Get all img-probe files
682
+ * const imgFiles = fs.scanTmp("img-probe");
683
+ * // Get all files in tmp (non-recursive)
684
+ * const allFiles = fs.scanTmp();
685
+ * ```
686
+ */
687
+ scanTmp(pattern, options = {
688
+ recursive: false,
689
+ withFileTypes: false,
690
+ encoding: "utf-8"
691
+ }) {
692
+ const dirs = resolve(this.tmpDir);
693
+ const tmpContents = this.readDir(dirs, options);
694
+ if (!pattern) {
695
+ return tmpContents;
696
+ }
697
+ if (typeof pattern === "string") {
698
+ return tmpContents.filter((t) => t.includes(pattern));
699
+ }
700
+ return tmpContents.filter((path) => {
701
+ return pattern.test(path);
702
+ });
703
+ }
704
+ /**
705
+ * Extract specific files from tmp directory to a target location
706
+ * @param pattern Pattern to match files (e.g., "img-probe")
707
+ * @param targetDir Target directory to extract files to
708
+ * @param options Options for extraction behavior
709
+ * @returns Array of extracted file paths
710
+ * @example
711
+ * ```ts
712
+ * const fs = new Fs(process.cwd());
713
+ * // Extract all img-probe files to ./output
714
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
715
+ * // Extract with custom behavior
716
+ * fs.extractFromTmp("session-", "./sessions", {
717
+ * preserveStructure: true,
718
+ * cleanupAfter: true
719
+ * });
720
+ * ```
721
+ */
722
+ extractFromTmp(pattern, targetDir, options) {
723
+ const {
724
+ preserveStructure = false,
725
+ cleanupAfter = false,
726
+ overwrite = true
727
+ } = options ?? {};
728
+ const matchingFiles = this.scanTmp(pattern);
729
+ const extracted = [];
730
+ for (const file of matchingFiles) {
731
+ const sourcePath = resolve(this.tmpDir, file);
732
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
733
+ if (!lastSegment) continue;
734
+ const targetPath = preserveStructure ? resolve(targetDir, file) : resolve(targetDir, lastSegment);
735
+ if (this.exists(targetPath) && !overwrite) {
736
+ console.warn(`Skipping existing file: ${targetPath}`);
737
+ continue;
738
+ }
739
+ const data = this.fileToBuffer(sourcePath);
740
+ this.withWs(targetPath, data);
741
+ extracted.push(targetPath);
742
+ if (cleanupAfter) {
743
+ this.rmFile(sourcePath);
744
+ }
745
+ }
746
+ return extracted;
747
+ }
748
+ /**
749
+ * Clean up tmp files matching a pattern
750
+ * @param pattern Pattern to match files for deletion
751
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
752
+ * @returns Number of files removed
753
+ * @example
754
+ * ```ts
755
+ * const fs = new Fs(process.cwd());
756
+ * // Remove all img-probe files
757
+ * fs.cleanupTmp("img-probe");
758
+ * // Remove session files older than 1 hour
759
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
760
+ * ```
761
+ */
762
+ cleanupTmp(pattern, maxAge) {
763
+ const matchingFiles = this.scanTmp(pattern);
764
+ let removed = 0;
765
+ for (const file of matchingFiles) {
766
+ const fullPath = resolve(this.tmpDir, file);
767
+ try {
768
+ const stats = fsSync.statSync(fullPath);
769
+ if (maxAge) {
770
+ const age = Date.now() - stats.mtimeMs;
771
+ if (age < maxAge) {
772
+ continue;
773
+ }
774
+ }
775
+ if (stats.isDirectory()) {
776
+ this.rmDirSync(fullPath);
777
+ } else {
778
+ this.rmFile(fullPath);
779
+ }
780
+ removed++;
781
+ } catch (err) {
782
+ console.warn(`Failed to remove tmp file ${file}:`, err);
783
+ }
784
+ }
785
+ return removed;
786
+ }
787
+ rmTmpFile(filename) {
788
+ const tmpPath = resolve(this.tmpDir, filename);
789
+ this.rmFile(tmpPath);
790
+ }
791
+ /**
792
+ * Generate a unique tmp filename with optional prefix
793
+ * @param prefix Optional prefix for the filename
794
+ * @param extension Optional file extension (without dot)
795
+ * @returns Unique filename
796
+ * @example
797
+ * ```ts
798
+ * const fs = new Fs(process.cwd());
799
+ * const filename = fs.uniqueTmpName("img-probe", "png");
800
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
801
+ * ```
802
+ */
803
+ uniqueTmpName(prefix, extension) {
804
+ const timestamp = Date.now();
805
+ const random = Math.random().toString(36).substring(2, 8);
806
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
807
+ return extension ? `${parts}.${extension}` : parts;
808
+ }
809
+ /**
810
+ * Async generator for cleaning tmp files with batched removal
811
+ * @param pattern Pattern to match files for deletion
812
+ * @param batchSize Number of files to remove per batch (default 10)
813
+ * @yields Progress information during cleanup
814
+ * @returns Final cleanup summary
815
+ * @example
816
+ * ```ts
817
+ * const fs = new Fs(process.cwd());
818
+ * // Clean up with progress tracking
819
+ * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
820
+ * console.log(progress);
821
+ * }
822
+ * ```
823
+ */
824
+ async *cleanTmpGenerator(pattern, batchSize = 10) {
825
+ const files = this.scanTmp(pattern);
826
+ const batches = await this.arrToArrOfArrs({
827
+ arrToFragment: files,
828
+ arrOfArrsAggregator: [],
829
+ interval: batchSize
830
+ });
831
+ let totalRemoved = 0;
832
+ for (const [index, batch] of batches.entries()) {
833
+ yield {
834
+ action: "removing",
835
+ batch: [...batch],
836
+ batchNumber: index + 1,
837
+ totalBatches: batches.length,
838
+ totalFound: files.length,
839
+ removed: totalRemoved
840
+ };
841
+ for (const file of batch) {
842
+ this.rmTmpFile(file);
843
+ totalRemoved++;
844
+ }
845
+ yield {
846
+ action: "batch-complete",
847
+ batchNumber: index + 1,
848
+ batchSize: batch.length,
849
+ totalRemoved,
850
+ remaining: files.length - totalRemoved
851
+ };
852
+ }
853
+ return {
854
+ action: "complete",
855
+ totalRemoved,
856
+ totalBatches: batches.length,
857
+ pattern: pattern.toString()
858
+ };
859
+ }
454
860
  };
455
861
 
456
862
  export {
457
863
  Fs
458
864
  };
459
- //# sourceMappingURL=chunk-XIAKCF2X.js.map
865
+ //# sourceMappingURL=chunk-Y3TLKN7F.js.map