@d0paminedriven/fs 7.0.1 → 7.1.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/index.cjs CHANGED
@@ -32,6 +32,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
32
32
  var index_exports = {};
33
33
  __export(index_exports, {
34
34
  Fs: () => Fs,
35
+ ImageService: () => ImageService,
35
36
  MimeService: () => MimeService,
36
37
  UrlService: () => UrlService,
37
38
  UtilsService: () => UtilsService,
@@ -221,6 +222,7 @@ var extMimeMap = {
221
222
  csh: ["application/x-csh"],
222
223
  css: ["text/css"],
223
224
  csv: ["text/csv"],
225
+ cur: ["image/x-icon"],
224
226
  doc: ["application/msword"],
225
227
  docx: [
226
228
  "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
@@ -237,11 +239,14 @@ var extMimeMap = {
237
239
  hmpg: ["haptics/hmpg"],
238
240
  htm: ["text/html"],
239
241
  html: ["text/html"],
240
- ico: ["image/vnd.microsoft.icon"],
242
+ ico: ["image/vnd.microsoft.icon", "image/x-icon"],
241
243
  ics: ["text/calendar"],
242
244
  ivs: ["haptics/ivs"],
243
245
  ivt: ["haptics/ivs"],
244
246
  jar: ["application/java-archive"],
247
+ jfif: ["image/jpeg"],
248
+ jif: ["image/jpeg"],
249
+ jpe: ["image/jpeg"],
245
250
  jpeg: ["image/jpeg"],
246
251
  jpg: ["image/jpeg"],
247
252
  js: ["application/node", "text/javascript"],
@@ -259,8 +264,10 @@ var extMimeMap = {
259
264
  mjs: ["text/javascript"],
260
265
  mp3: ["audio/mpeg"],
261
266
  mp4: ["video/mp4"],
267
+ mpd: ["application/dash+xml"],
262
268
  mpeg: ["video/mpeg"],
263
269
  mpkg: ["application/vnd.apple.installer+xml"],
270
+ mtlx: ["application/xml"],
264
271
  ndjson: ["application/x-ndjson"],
265
272
  node: ["application/node", "text/javascript"],
266
273
  obj: ["model/obj", "application/octet-stream", "text/plain"],
@@ -276,6 +283,8 @@ var extMimeMap = {
276
283
  png: ["image/png"],
277
284
  pdf: ["application/pdf"],
278
285
  php: ["application/x-httpd-php"],
286
+ pjp: ["image/jpeg"],
287
+ pjpeg: ["image/jpeg"],
279
288
  pkpass: ["application/vnd.apple.pkpass"],
280
289
  ppt: ["application/vnd.ms-powerpoint"],
281
290
  pptx: [
@@ -302,14 +311,16 @@ var extMimeMap = {
302
311
  vtt: ["text/vtt"],
303
312
  wasm: ["application/wasm"],
304
313
  wav: ["audio/wav"],
305
- weba: ["video/webm"],
314
+ weba: ["audio/webm"],
315
+ webm: ["video/webm"],
316
+ webmanifest: ["application/manifest+json"],
306
317
  webp: ["image/webp"],
307
318
  woff: ["font/woff"],
308
319
  woff2: ["font/woff2"],
309
320
  xhtml: ["application/xhtml+xml"],
310
321
  xls: ["application/vnd.ms-excel"],
311
322
  xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
312
- xml: ["application/xml"],
323
+ xml: ["application/xml", "text/xml"],
313
324
  xul: ["application/vnd.mozilla.xul+xml"],
314
325
  yaml: ["application/yaml"],
315
326
  yml: ["application/yaml"],
@@ -319,12 +330,14 @@ var extMimeMap = {
319
330
  "7z": ["application/x-7z-compressed"]
320
331
  };
321
332
  var mimeToExt = {
333
+ "application/dash+xml": ["mpd"],
322
334
  "application/epub+zip": ["epub"],
323
335
  "application/font-sfnt": ["ttf"],
324
336
  "application/gzip": ["gz"],
325
337
  "application/java-archive": ["jar"],
326
338
  "application/json": ["json"],
327
339
  "application/ld+json": ["jsonld"],
340
+ "application/manifest+json": ["webmanifest"],
328
341
  "application/msword": ["doc"],
329
342
  "application/node": ["node", "js"],
330
343
  "application/octet-stream": ["bin", "obj"],
@@ -370,7 +383,7 @@ var mimeToExt = {
370
383
  "application/x-tar": ["tar"],
371
384
  "application/x-zip-compressed": ["zip"],
372
385
  "application/xhtml+xml": ["xhtml"],
373
- "application/xml": ["xml"],
386
+ "application/xml": ["xml", "mtlx"],
374
387
  "application/yaml": ["yml", "yaml"],
375
388
  "application/zip": ["zip"],
376
389
  "audio/aac": ["aac"],
@@ -379,6 +392,7 @@ var mimeToExt = {
379
392
  "audio/mpeg": ["mp3"],
380
393
  "audio/ogg": ["opus", "ogg", "oga"],
381
394
  "audio/wav": ["wav"],
395
+ "audio/webm": ["weba"],
382
396
  "audio/x-midi": ["midi"],
383
397
  "font/otf": ["otf"],
384
398
  "font/ttf": ["ttf"],
@@ -395,7 +409,7 @@ var mimeToExt = {
395
409
  "image/dpx": ["dpx"],
396
410
  "image/emf": ["emf"],
397
411
  "image/gif": ["gif"],
398
- "image/jpeg": ["jpg", "jpeg"],
412
+ "image/jpeg": ["jpg", "jpeg", "jpe", "jif", "jfif", "pjp", "pjpeg"],
399
413
  "image/ktx": ["ktx"],
400
414
  "image/ktx2": ["ktx2"],
401
415
  "image/png": ["png"],
@@ -403,6 +417,7 @@ var mimeToExt = {
403
417
  "image/tiff": ["tiff", "tif"],
404
418
  "image/vnd.microsoft.icon": ["ico"],
405
419
  "image/webp": ["webp"],
420
+ "image/x-icon": ["cur", "ico"],
406
421
  "model/gltf-binary": ["glb"],
407
422
  "model/gltf+json": ["gltf"],
408
423
  "model/obj": ["obj"],
@@ -411,14 +426,15 @@ var mimeToExt = {
411
426
  "text/calendar": ["ics"],
412
427
  "text/css": ["css"],
413
428
  "text/csv": ["csv"],
414
- "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
429
+ "text/event-stream": ["sse"],
415
430
  "text/html": ["html", "htm"],
416
- "text/javascript": ["cjs", "js", "mjs"],
431
+ "text/javascript": ["js", "mjs", "cjs"],
417
432
  "text/markdown": ["md"],
418
433
  "text/plain": ["txt"],
419
434
  "text/rust": ["rs"],
420
435
  "text/typescript": ["ts"],
421
436
  "text/vtt": ["vtt"],
437
+ "text/xml": ["xml"],
422
438
  "text/x-python": ["py"],
423
439
  "video/3gpp": ["3gp"],
424
440
  "video/3gpp2": ["3g2"],
@@ -427,7 +443,7 @@ var mimeToExt = {
427
443
  "video/mpeg": ["mpeg"],
428
444
  "video/ogg": ["ogv"],
429
445
  "video/vnd.dlna.mpeg-tts": ["ts"],
430
- "video/webm": ["weba"],
446
+ "video/webm": ["webm"],
431
447
  "video/x-msvideo": ["avi"]
432
448
  };
433
449
  var MimeService = class extends UrlService {
@@ -477,8 +493,8 @@ var MimeService = class extends UrlService {
477
493
  if (mime === "audio/ogg") return "ogg";
478
494
  return extensions[0];
479
495
  }
480
- if (extensions.length === 5) {
481
- return "sse";
496
+ if (extensions.length === 7) {
497
+ return extensions[0];
482
498
  }
483
499
  return extensions[0];
484
500
  }
@@ -510,495 +526,168 @@ var MimeService = class extends UrlService {
510
526
  }
511
527
  };
512
528
 
513
- // src/types/index.ts
514
- var unitsObj = {
515
- PB: 5,
516
- TB: 4,
517
- GB: 3,
518
- MB: 2,
519
- KB: 1,
520
- B: 0
521
- };
522
-
523
- // src/fs/index.ts
524
- dotenv.config({ quiet: true });
525
- var Fs = class extends MimeService {
526
- constructor(cwd) {
527
- super();
528
- this.cwd = cwd;
529
- cwd ??= process.cwd();
530
- }
529
+ // src/image/index.ts
530
+ var ImageService = class extends MimeService {
531
531
  static {
532
- __name(this, "Fs");
533
- }
534
- get myEnv() {
535
- return dotenv.config({ processEnv: {} });
536
- }
537
- get tmpDir() {
538
- return (0, import_node_os.tmpdir)();
539
- }
540
- get tmpDirRelative() {
541
- return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
532
+ __name(this, "ImageService");
542
533
  }
543
- parseDotEnv() {
544
- return import_dotenv_expand.default.expand(this.myEnv);
545
- }
546
- /**
547
- *
548
- * @param target path to the file or directory to check for existence
549
- * @returns true if the file or directory exists, false otherwise
550
- * @example
551
- * ```ts
552
- * const fs = new Fs(process.cwd());
553
- * const exists = fs.exists("my-file.txt");
554
- * console.log(exists); // true if the file exists, false otherwise
555
- * ```
556
- * @description
557
- * This method checks if a file or directory exists at the specified path input
558
- *
559
- * Additional Note:
560
- *
561
- * say you have a directory that begins with a dot, such as `.turbo`;
562
- *
563
- * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
564
- *
565
- */
566
- exists(target) {
567
- if (!/\//gm.test(target)) {
568
- if (/\./g.test(target)) {
569
- return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
570
- } else {
571
- const statsSync = import_fs.default.statSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)), {
572
- throwIfNoEntry: false
573
- });
574
- const isDir = statsSync?.isDirectory();
575
- if (isDir) {
576
- return isDir;
577
- } else return false;
578
- }
579
- } else {
580
- if (/\./g.test(target)) {
581
- return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
582
- } else {
583
- const statsSync = import_fs.default.statSync((0, import_path.relative)(this.cwd, target), {
584
- throwIfNoEntry: false
585
- });
586
- const isDir = statsSync?.isDirectory();
587
- if (isDir) {
588
- return isDir;
589
- } else return false;
534
+ parseExif(buffer, app1Pos, app1Size) {
535
+ const exifHeader = buffer.toString("ascii", app1Pos + 2, app1Pos + 8);
536
+ if (exifHeader !== "Exif\0\0")
537
+ return { orientation: null, dateTimeOriginal: null };
538
+ let tiffPos = app1Pos + 8;
539
+ const app1End = app1Pos + app1Size;
540
+ if (tiffPos + 10 > app1End)
541
+ return { orientation: null, dateTimeOriginal: null };
542
+ const byteOrder = buffer.toString("ascii", tiffPos, tiffPos + 2);
543
+ const littleEndian = byteOrder === "II";
544
+ const readUInt16 = littleEndian ? buffer.readUInt16LE.bind(buffer) : buffer.readUInt16BE.bind(buffer);
545
+ const readUInt32 = littleEndian ? buffer.readUInt32LE.bind(buffer) : buffer.readUInt32BE.bind(buffer);
546
+ if (readUInt16(tiffPos + 2) !== 42)
547
+ return { orientation: null, dateTimeOriginal: null };
548
+ let ifdOffset = readUInt32(tiffPos + 4);
549
+ tiffPos += ifdOffset;
550
+ const numEntries = readUInt16(tiffPos);
551
+ tiffPos += 2;
552
+ let orientation = null;
553
+ let dateTimeOriginal = null;
554
+ for (let i = 0; i < numEntries; i++) {
555
+ const tag = readUInt16(tiffPos), type = readUInt16(tiffPos + 2), count = readUInt32(tiffPos + 4), valueOffset = tiffPos + 8;
556
+ if (tag === 274 && type === 3 && count === 1) {
557
+ orientation = readUInt16(valueOffset);
558
+ } else if (tag === 36867 && type === 2 && count === 20) {
559
+ const offset = readUInt32(valueOffset);
560
+ if (app1Pos + 2 + offset + 19 > app1End) {
561
+ dateTimeOriginal = null;
562
+ } else {
563
+ dateTimeOriginal = buffer.toString("ascii", app1Pos + 2 + offset, app1Pos + 2 + offset + 19).trim();
564
+ }
590
565
  }
566
+ tiffPos += 12;
591
567
  }
568
+ return { orientation, dateTimeOriginal };
592
569
  }
593
- /**
594
- *
595
- * @param ms milliseconds to wait
596
- * @returns a promise that resolves after the specified number of milliseconds
597
- * @example
598
- * ```ts
599
- * const fs = new Fs(process.cwd());
600
- * await fs.wait(1000); // waits for 1 second
601
- * console.log("Done waiting!");
602
- * ```
603
- *
604
- * Alternatively, you can use it like this:
605
- * ```ts
606
- * const fs = new Fs(process.cwd());
607
- * fs.wait(1000).then(() => { // waits for 1 second
608
- * console.log("Done waiting!");
609
- * // do something after waiting
610
- * });
611
- * ```
612
- *
613
- * @description
614
- * This method is useful for delaying execution in asynchronous code, such as when you need to wait for a file operation to complete or when you want to introduce a delay in a loop.
615
- */
616
- wait(ms) {
617
- return new Promise((resolve2) => setTimeout(resolve2, ms));
618
- }
619
- /**
620
- * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
621
- * @param arr An array or readonly array of strings and/or Buffers
622
- * @returns An array of strings with Buffers converted to UTF-8 strings.
623
- */
624
- handleBuffStrArrUnion(arr) {
625
- return arr.map(
626
- (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
570
+ parseXmpFromAvif(buffer, meta, _ipco) {
571
+ const iinf = this.findBox(
572
+ buffer,
573
+ "iinf",
574
+ meta.pos + 4,
575
+ meta.pos + meta.size
627
576
  );
628
- }
629
- isRootPathTargeted(path) {
630
- if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
631
- return true;
632
- } else return false;
633
- }
634
- /**
635
- *
636
- * @param path path to the directory relative to the cwd
637
- * @param options options for reading the directory, defaults to recursive
638
- *
639
- * The following two examples are equivalent:
640
- *
641
- * @example
642
- * ```ts
643
- * const fs = new Fs(process.cwd());
644
- * const files = fs.readDir("./my-directory", { recursive: true });
645
- * console.log(files);
646
- * ```
647
- * @example
648
- * ```ts
649
- * const fs = new Fs(process.cwd());
650
- * const files = fs.readDir("my-directory", { recursive: true });
651
- * console.log(files);
652
- * ```
653
- *
654
- * @returns an array of strings representing the contents of the directory
655
- */
656
- readDir(path, options = {
657
- recursive: true,
658
- withFileTypes: false,
659
- encoding: "utf-8"
660
- }) {
661
- if (this.isRootPathTargeted(path)) {
662
- return this.handleBuffStrArrUnion(
663
- import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
664
- );
665
- } else {
666
- return this.handleBuffStrArrUnion(
667
- import_fs.default.readdirSync(
668
- (0, import_path.relative)(this.cwd ??= process.cwd(), path),
669
- options
670
- )
671
- );
672
- }
673
- }
674
- executeCommand = /* @__PURE__ */ __name(({
675
- command,
676
- ...options
677
- }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString(
678
- "utf-8"
679
- ), "executeCommand");
680
- existsSync(path) {
681
- return this.exists(path);
682
- }
683
- pathHandler(path) {
684
- return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
685
- }
686
- mkdirSync(path, options) {
687
- return import_fs.default.mkdirSync((0, import_path.relative)(this.cwd, path), options);
688
- }
689
- units = unitsObj;
690
- u = ["B", "KB", "MB", "GB", "TB", "PB"];
691
- autoFileSizeRaw(size) {
692
- let s = typeof size === "bigint" ? Number(size) : size;
693
- let i = 0;
694
- while (s >= 1024 && i < this.u.length - 1) {
695
- s /= 1024;
696
- i++;
697
- }
698
- return { value: s, unit: this.u[i] };
699
- }
700
- getSize(size, target, opts = { decimals: 4, includeUnits: true }) {
701
- const { decimals, includeUnits } = opts;
702
- if (target === "auto") {
703
- const { value, unit } = this.autoFileSizeRaw(size);
704
- const rounded2 = value.toFixed(decimals);
705
- return includeUnits ? `${rounded2} ${unit}` : Number.parseFloat(rounded2);
577
+ if (!iinf) return null;
578
+ let pos = iinf.pos;
579
+ const version = buffer[pos++];
580
+ const itemCount = version === 0 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
581
+ pos += version === 0 ? 2 : 4;
582
+ let xmpItemId;
583
+ for (let i = 0; i < itemCount; i++) {
584
+ const infeStart = pos;
585
+ const infeSize = buffer.readUInt32BE(pos);
586
+ if (buffer.toString("ascii", pos + 4, pos + 8) !== "infe") break;
587
+ pos += 8;
588
+ const infeVersion = buffer?.[pos++];
589
+ if (!infeVersion) return null;
590
+ const itemId = infeVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
591
+ pos += infeVersion < 2 ? 2 : 4;
592
+ pos += 2;
593
+ const itemType = buffer.toString("ascii", pos, pos + 4);
594
+ pos += 4;
595
+ let nameEnd = pos;
596
+ while (buffer[nameEnd] !== 0 && nameEnd < infeStart + infeSize) nameEnd++;
597
+ const _itemName = buffer.toString("ascii", pos, nameEnd);
598
+ pos = nameEnd + 1;
599
+ if (itemType === "mime") {
600
+ let ctEnd = pos;
601
+ while (buffer[ctEnd] !== 0 && ctEnd < infeStart + infeSize) ctEnd++;
602
+ const contentType = buffer.toString("ascii", pos, ctEnd);
603
+ if (contentType === "application/rdf+xml") {
604
+ xmpItemId = itemId;
605
+ break;
606
+ }
607
+ pos = ctEnd + 1;
608
+ }
609
+ pos = infeStart + infeSize;
706
610
  }
707
- const key = target.toUpperCase();
708
- const exp = this.units[key];
709
- const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
710
- let v = 0;
711
- if (typeof size === "bigint" || typeof divisor === "bigint") {
712
- if (typeof size === "bigint" && typeof divisor === "bigint")
713
- v = Number(size / divisor);
714
- else if (typeof size !== "bigint" && typeof divisor === "bigint")
715
- v = size / Number(divisor);
716
- else if (typeof size === "bigint" && typeof divisor !== "bigint")
717
- v = Number(size) / divisor;
718
- } else if (typeof size === "number" && typeof divisor === "number") {
719
- v = size / divisor;
611
+ if (!xmpItemId) return null;
612
+ const iloc = this.findBox(
613
+ buffer,
614
+ "iloc",
615
+ meta.pos + 4,
616
+ meta.pos + meta.size
617
+ );
618
+ if (!iloc) return null;
619
+ pos = iloc.pos;
620
+ const ilocVersion = buffer[pos++];
621
+ const sizes = buffer?.[pos++];
622
+ if (!sizes) return null;
623
+ const offsetSize = sizes >> 4 & 15;
624
+ const lengthSize = sizes & 15;
625
+ let indexSize = 0;
626
+ if (ilocVersion === 1 || ilocVersion === 2) {
627
+ const indexSizes = buffer?.[pos++];
628
+ if (!indexSizes) return null;
629
+ indexSize = indexSizes >> 4 & 15;
720
630
  }
721
- const rounded = v.toFixed(decimals);
722
- return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
723
- }
724
- fileSizeMb(path) {
725
- return import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size / (1024 * 1024);
726
- }
727
- fileSize(path, target, opts) {
728
- if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
729
- else {
730
- return this.getSize(
731
- import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size,
732
- target,
733
- opts
734
- );
631
+ if (!ilocVersion) return null;
632
+ let buffpos = buffer?.[pos++];
633
+ if (!buffpos) return null;
634
+ const baseOffsetSize = ilocVersion < 2 ? 0 : buffpos >> 4 & 15;
635
+ const itemCountIloc = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
636
+ pos += ilocVersion < 2 ? 2 : 4;
637
+ let xmpOffset = 0;
638
+ let xmpLength = 0;
639
+ for (let i = 0; i < itemCountIloc; i++) {
640
+ const curItemId = ilocVersion < 2 ? buffer.readUInt16BE(pos) : buffer.readUInt32BE(pos);
641
+ pos += ilocVersion < 2 ? 2 : 4;
642
+ if (curItemId !== xmpItemId) {
643
+ if (ilocVersion === 1 || ilocVersion === 2) pos += 2;
644
+ pos += 2;
645
+ pos += baseOffsetSize;
646
+ const extentCount2 = buffer.readUInt16BE(pos);
647
+ pos += 2;
648
+ for (let e = 0; e < extentCount2; e++) {
649
+ if (indexSize > 0) pos += indexSize;
650
+ pos += offsetSize + lengthSize;
651
+ }
652
+ continue;
653
+ }
654
+ if (ilocVersion === 1 || ilocVersion === 2) {
655
+ const constructionMethod = buffer.readUInt16BE(pos);
656
+ pos += 2;
657
+ if (constructionMethod !== 0) return null;
658
+ }
659
+ pos += 2;
660
+ const baseOffset = this.readVarSize(buffer, pos, baseOffsetSize);
661
+ pos += baseOffsetSize;
662
+ const extentCount = buffer.readUInt16BE(pos);
663
+ pos += 2;
664
+ if (extentCount !== 1) return null;
665
+ if (indexSize > 0) pos += indexSize;
666
+ const extentOffset = this.readVarSize(buffer, pos, offsetSize);
667
+ pos += offsetSize;
668
+ const extentLength = this.readVarSize(buffer, pos, lengthSize);
669
+ xmpOffset = baseOffset + extentOffset;
670
+ xmpLength = extentLength;
671
+ break;
735
672
  }
673
+ if (xmpOffset === 0 || xmpLength === 0 || xmpOffset + xmpLength > buffer.length)
674
+ return null;
675
+ return buffer.toString("utf8", xmpOffset, xmpOffset + xmpLength);
736
676
  }
737
- generateDirIfDNE(path, options) {
738
- if (this.existsSync(path)) return;
739
- else {
740
- return this.mkdirSync(path, options);
741
- }
742
- }
743
- withWs(path, data, options) {
744
- try {
745
- if (/\//g.test(path) === true) {
746
- return this.generateDirIfDNE(this.pathHandler(path), {
747
- recursive: true
748
- });
749
- } else return path;
750
- } catch (error) {
751
- console.error(
752
- `[withWs error]: `.concat(
753
- typeof error === "string" ? error : JSON.stringify(error, null, 2)
754
- )
755
- );
756
- } finally {
757
- return import_fs.default.createWriteStream(
758
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
759
- typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
760
- ).write(Buffer.from(Buffer.from(data).toJSON().data));
761
- }
762
- }
763
- writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
764
- try {
765
- if (/\//g.test(path) === true)
766
- return this.generateDirIfDNE(this.pathHandler(path), {
767
- recursive: true
768
- });
769
- else return path;
770
- } catch (error) {
771
- console.error(
772
- `[writeFileAsync error]: `.concat(
773
- error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
774
- )
775
- );
776
- } finally {
777
- return await import_promises.default.writeFile(
778
- (0, import_path.relative)(this.cwd ?? process.cwd(), path),
779
- Buffer.from(Buffer.from(data).toJSON().data),
780
- options
781
- );
782
- }
783
- }, "writeFileAsync");
784
- async unlink(path) {
785
- if (this.existsSync(path)) {
786
- return await import_promises.default.unlink((0, import_path.relative)(this.cwd, path));
787
- } else {
788
- throw new Error(`input path ${path} does not exist`);
789
- }
790
- }
791
- rmFile(filePath) {
792
- if (this.exists(filePath)) {
793
- if (this.isRootPathTargeted(filePath)) {
794
- import_fs.default.rmSync((0, import_path.resolve)((0, import_path.join)(this.cwd, filePath)));
795
- } else import_fs.default.rmSync((0, import_path.resolve)(this.cwd, filePath));
796
- } else return;
797
- }
798
- async rmdir(dir, options) {
799
- const resolved = (0, import_path.relative)(this.cwd, dir);
800
- if (this.exists(dir)) {
801
- return import_promises.default.rmdir((0, import_path.relative)(this.cwd, dir), options);
802
- } else {
803
- throw new Error(`directory ${resolved} does not exist`);
804
- }
805
- }
806
- rmDirSync(dir) {
807
- const resolved = (0, import_path.resolve)(this.cwd, dir);
808
- if (this.exists(dir)) {
809
- return import_fs.default.rm(resolved, { force: true, recursive: true }, (err) => {
810
- if (err?.message) {
811
- console.error(err?.message);
812
- }
813
- });
814
- } else {
815
- throw new Error(`directory ${resolved} does not exist`);
816
- }
817
- }
818
- fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
819
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
820
- ), "fileToBuffer");
821
- fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
822
- return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
823
- }, "fileToBufferAsync");
824
- dirContainsDir(readDir, targetDir, options) {
825
- return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
826
- }
827
- async assetToBuffer(path) {
828
- const [fetcher] = await Promise.all([
829
- fetch(path).then((t) => t.arrayBuffer())
830
- ]);
831
- const mime = this.getMimeTypeForPath(path);
832
- const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
833
- const extension = this.assetType(path) ?? "txt";
834
- return {
835
- b64encodedData,
836
- extension
837
- };
838
- }
839
- async assetToBufferView(path) {
840
- const response = await fetch(path, { method: "GET" });
841
- if (!response.ok) {
842
- throw new Error(`Failed to fetch asset: ${response.statusText}`);
843
- }
844
- const reader = response.body?.getReader();
845
- if (reader) {
846
- const chunks = Array.of();
847
- while (true) {
848
- const { done, value } = await reader.read();
849
- if (done) break;
850
- if (value) chunks.push(value);
851
- }
852
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
853
- const completeBuffer = new Uint8Array(totalLength);
854
- let offset = 0;
855
- for (const chunk of chunks) {
856
- completeBuffer.set(chunk, offset);
857
- offset += chunk.length;
858
- }
859
- const mime = this.getMimeTypeForPath(path);
860
- const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
861
- const extension = this.assetType(path);
862
- return { b64encodedData, extension };
863
- } else {
864
- const arrayBuffer = await response.arrayBuffer();
865
- const mime = this.getMimeTypeForPath(path);
866
- const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
867
- const extension = this.assetType(path);
868
- return { b64encodedData, extension };
869
- }
870
- }
871
- formatHelper(f) {
872
- if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
873
- const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
874
- return formatting;
875
- } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
876
- }
877
- cleanDataUrl(props) {
878
- return props.replace(
879
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
880
- ""
881
- );
882
- }
883
- /**
884
- *
885
- * @param inputUrl remote url to fetch data from
886
- * @param outputPath desired output path relative to the cwd
887
- * @param useDetectedExtension optional, defaults to true
888
- *
889
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
890
- *
891
- * 🚫 'public/assets/image-1'
892
- *
893
- * ✅ 'public/assets/image-1.png'
894
- */
895
- async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
896
- try {
897
- const result = await this.assetToBufferView(inputUrl);
898
- const cleanData = this.cleanDataUrl(result.b64encodedData);
899
- const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
900
- if (/\./g.test(formattedPath) === false) {
901
- throw new Error(
902
- "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
903
- );
904
- }
905
- this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
906
- } catch (err) {
907
- return console.error(err);
908
- }
909
- }
910
- parseExif(buffer, app1Pos, _app1Size) {
911
- const exifHeader = buffer.toString("ascii", app1Pos + 2, app1Pos + 8);
912
- if (exifHeader !== "Exif\0\0")
913
- return { orientation: null, dateTimeOriginal: null };
914
- let tiffPos = app1Pos + 8;
915
- const byteOrder = buffer.toString("ascii", tiffPos, tiffPos + 2);
916
- const littleEndian = byteOrder === "II";
917
- const readUInt16 = littleEndian ? buffer.readUInt16LE.bind(buffer) : buffer.readUInt16BE.bind(buffer);
918
- const readUInt32 = littleEndian ? buffer.readUInt32LE.bind(buffer) : buffer.readUInt32BE.bind(buffer);
919
- if (readUInt16(tiffPos + 2) !== 42)
920
- return { orientation: null, dateTimeOriginal: null };
921
- let ifdOffset = readUInt32(tiffPos + 4);
922
- tiffPos += ifdOffset;
923
- const numEntries = readUInt16(tiffPos);
924
- tiffPos += 2;
925
- let orientation = null;
926
- let dateTimeOriginal = null;
927
- for (let i = 0; i < numEntries; i++) {
928
- const tag = readUInt16(tiffPos);
929
- const type = readUInt16(tiffPos + 2);
930
- const count = readUInt32(tiffPos + 4);
931
- const valueOffset = tiffPos + 8;
932
- if (tag === 274 && type === 3 && count === 1) {
933
- orientation = readUInt16(valueOffset);
934
- } else if (tag === 36867 && type === 2 && count === 20) {
935
- const offset = readUInt32(valueOffset);
936
- dateTimeOriginal = buffer.toString("ascii", app1Pos + 2 + offset, app1Pos + 2 + offset + 19).trim();
937
- }
938
- tiffPos += 12;
939
- }
940
- return { orientation, dateTimeOriginal };
941
- }
942
- /**
943
- *
944
- * @param inputUrl remote url to fetch data from
945
- * @param outputPath desired output path relative to the cwd
946
- * @param useDetectedExtension optional, defaults to true
947
- *
948
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
949
- *
950
- * 🚫 'public/assets/image-1'
951
- *
952
- * ✅ 'public/assets/image-1.png'
953
- *
954
- * @description
955
- * This method is designed for large files that may not fit into memory.
956
- * It streams the data directly to disk instead of loading it all into memory.
957
- */
958
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
959
- const MAX_SAFE_IN_MEMORY_MB = 100;
960
- try {
961
- const isGithubRaw = inputUrl.startsWith(
962
- "https://raw.githubusercontent.com"
963
- );
964
- const head = await fetch(inputUrl, {
965
- method: isGithubRaw ? "GET" : "HEAD"
966
- });
967
- const contentLength = head.headers.get("content-length");
968
- const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
969
- let outputPath = outputPathI;
970
- const assetTypeViaUrl = this.assetType(inputUrl);
971
- const contentType = head.headers.get("content-type") ?? "application/octet-stream";
972
- const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
973
- this.generateDirIfDNE(this.pathHandler(formattedPath), {
974
- recursive: true
975
- });
976
- if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
977
- const res = await fetch(inputUrl);
978
- if (!res.ok || !res.body) {
979
- throw new Error(`Failed to fetch asset: ${res.statusText}`);
980
- }
981
- const writeStream = import_fs.default.createWriteStream(
982
- (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
983
- );
984
- const reader = res.body.getReader();
985
- const pump = /* @__PURE__ */ __name(async () => {
986
- while (true) {
987
- const { done, value } = await reader.read();
988
- if (done) break;
989
- writeStream.write(value);
990
- }
991
- writeStream.end();
992
- }, "pump");
993
- await pump();
994
- return;
995
- }
996
- const result = await this.assetToBufferView(inputUrl);
997
- const cleanedData = this.cleanDataUrl(result.b64encodedData);
998
- this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
999
- } catch (err) {
1000
- console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
677
+ readVarSize(buffer, pos, size) {
678
+ if (size === 0) return 0;
679
+ if (size === 1 && buffer?.[pos]) return buffer?.[pos];
680
+ if (size === 2) return buffer.readUInt16BE(pos);
681
+ if (size === 3) {
682
+ let pos1 = buffer?.[pos + 1], pos2 = buffer?.[pos + 2];
683
+ if (buffer?.[pos] && pos1 && pos2) {
684
+ return buffer[pos] << 16 | pos1 << 8 | pos2;
685
+ }
686
+ throw new Error("Invalid var size");
1001
687
  }
688
+ if (size === 4) return buffer.readUInt32BE(pos);
689
+ if (size === 8) return Number(buffer.readBigUInt64BE(pos));
690
+ throw new Error("Invalid var size");
1002
691
  }
1003
692
  findBox(buffer, type, start = 0, end = buffer.length) {
1004
693
  let pos = start;
@@ -1019,8 +708,7 @@ var Fs = class extends MimeService {
1019
708
  }
1020
709
  return null;
1021
710
  }
1022
- async getImageSpecs(filePath) {
1023
- const buffer = await this.fileToBufferAsync(filePath);
711
+ getImageSpecsWorkup(buffer) {
1024
712
  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) {
1025
713
  if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
1026
714
  throw new Error("IHDR Chunk of png not found or incorrect.");
@@ -1313,77 +1001,571 @@ var Fs = class extends MimeService {
1313
1001
  // Can have EXIF chunk, but rare; add if needed
1314
1002
  };
1315
1003
  }
1316
- if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
1317
- const ftyp = this.findBox(buffer, "ftyp");
1318
- if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
1319
- const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
1320
- const isAvif = brands.includes("avif");
1321
- const isAvis = brands.includes("avis");
1322
- if (!isAvif && !isAvis) throw new Error("Not an AVIF file");
1323
- const meta = this.findBox(buffer, "meta");
1324
- if (!meta) throw new Error("Invalid AVIF: No meta");
1325
- const metaSubStart = meta.pos + 4;
1326
- const metaSubEnd = meta.pos + meta.size;
1327
- const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1328
- if (!iprp) throw new Error("Invalid AVIF: No iprp");
1329
- const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1330
- if (!ipco) throw new Error("Invalid AVIF: No ipco");
1331
- const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1332
- if (!ispe) throw new Error("Invalid AVIF: No ispe");
1333
- if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1334
- const width = buffer.readUInt32BE(ispe.pos + 4);
1335
- const height = buffer.readUInt32BE(ispe.pos + 8);
1336
- let colorSpace = "rgb";
1337
- let hasAlpha = false;
1338
- let iccProfile = null;
1339
- const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
1340
- if (colr) {
1341
- const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
1342
- if (colrType === "nclx") {
1343
- const matrix = buffer.readUInt16BE(colr.pos + 6);
1344
- colorSpace = matrix === 2 ? "rgb" : "ycbcr";
1345
- } else if (colrType === "rICC" || colrType === "prof") {
1346
- colorSpace = "unknown";
1347
- iccProfile = "embedded";
1004
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
1005
+ const ftyp = this.findBox(buffer, "ftyp");
1006
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
1007
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
1008
+ const isAvif = brands.includes("avif");
1009
+ const isAvis = brands.includes("avis");
1010
+ if (!isAvif && !isAvis) throw new Error("Not an AVIF file");
1011
+ const meta = this.findBox(buffer, "meta");
1012
+ if (!meta) throw new Error("Invalid AVIF: No meta");
1013
+ const metaSubStart = meta.pos + 4;
1014
+ const metaSubEnd = meta.pos + meta.size;
1015
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1016
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
1017
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1018
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
1019
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1020
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
1021
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1022
+ const width = buffer.readUInt32BE(ispe.pos + 4);
1023
+ const height = buffer.readUInt32BE(ispe.pos + 8);
1024
+ let colorSpace = "rgb";
1025
+ let hasAlpha = false;
1026
+ let iccProfile = null;
1027
+ const colr = this.findBox(buffer, "colr", ipco.pos, ipco.pos + ipco.size);
1028
+ if (colr) {
1029
+ const colrType = buffer.toString("ascii", colr.pos, colr.pos + 4);
1030
+ if (colrType === "nclx") {
1031
+ const matrix = buffer.readUInt16BE(colr.pos + 6);
1032
+ colorSpace = matrix === 2 ? "rgb" : "ycbcr";
1033
+ } else if (colrType === "rICC" || colrType === "prof") {
1034
+ colorSpace = "unknown";
1035
+ iccProfile = "embedded";
1036
+ }
1037
+ }
1038
+ const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
1039
+ if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
1040
+ hasAlpha = true;
1041
+ if (colorSpace === "rgb") {
1042
+ colorSpace = "rgba";
1043
+ } else if (colorSpace === "ycbcr") {
1044
+ colorSpace = "ycck";
1045
+ } else if (colorSpace === "grayscale" || colorSpace === "unknown") {
1046
+ colorSpace = "grayscale-alpha";
1047
+ }
1048
+ }
1049
+ const xmpXml = this.parseXmpFromAvif(buffer, meta, ipco);
1050
+ let exifDateTimeOriginal = null;
1051
+ if (xmpXml) {
1052
+ let dateStart = xmpXml.indexOf('xmp:CreateDate="');
1053
+ if (dateStart === -1)
1054
+ dateStart = xmpXml.indexOf('photoshop:DateCreated="');
1055
+ if (dateStart !== -1) {
1056
+ dateStart += 16;
1057
+ const dateEnd = xmpXml.indexOf('"', dateStart);
1058
+ if (dateEnd !== -1) {
1059
+ exifDateTimeOriginal = xmpXml.substring(dateStart, dateEnd);
1060
+ }
1061
+ }
1062
+ }
1063
+ let frames = 1;
1064
+ let animated = isAvis;
1065
+ if (animated) {
1066
+ const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
1067
+ if (iloc) {
1068
+ const version = buffer?.[iloc.pos] ?? 0;
1069
+ const itemCountPos = iloc.pos + (version < 2 ? 4 : 6);
1070
+ let itemCount = buffer?.readUInt16BE(itemCountPos) ?? 0;
1071
+ if (version >= 2) itemCount = buffer?.readUInt32BE(itemCountPos) ?? 0;
1072
+ frames = Math.max(1, Math.floor(itemCount / (hasAlpha ? 2 : 1)));
1073
+ }
1074
+ }
1075
+ return {
1076
+ width,
1077
+ height,
1078
+ format: "avif",
1079
+ frames,
1080
+ animated,
1081
+ hasAlpha: hasAlpha ? true : null,
1082
+ orientation: null,
1083
+ // Can have 'irot' or 'imir' transforms, but rare
1084
+ aspectRatio: width / height,
1085
+ colorSpace,
1086
+ iccProfile,
1087
+ exifDateTimeOriginal
1088
+ // Can have 'XMP' box, but parse XMP for date if needed
1089
+ };
1090
+ }
1091
+ throw new Error("Unsupported image format or invalid file");
1092
+ }
1093
+ };
1094
+
1095
+ // src/types/index.ts
1096
+ var unitsObj = {
1097
+ PB: 5,
1098
+ TB: 4,
1099
+ GB: 3,
1100
+ MB: 2,
1101
+ KB: 1,
1102
+ B: 0
1103
+ };
1104
+
1105
+ // src/fs/index.ts
1106
+ dotenv.config({ quiet: true });
1107
+ var Fs = class extends ImageService {
1108
+ constructor(cwd) {
1109
+ super();
1110
+ this.cwd = cwd;
1111
+ cwd ??= process.cwd();
1112
+ }
1113
+ static {
1114
+ __name(this, "Fs");
1115
+ }
1116
+ async getImageSpecs(filePath) {
1117
+ const buffer = await this.fileToBufferAsync(filePath);
1118
+ return this.getImageSpecsWorkup(buffer);
1119
+ }
1120
+ async getImageSpecsTmp(target) {
1121
+ const buffer = await this.readTmpAsync(target);
1122
+ return this.getImageSpecsWorkup(buffer);
1123
+ }
1124
+ get myEnv() {
1125
+ return dotenv.config({ processEnv: {} });
1126
+ }
1127
+ get tmpDir() {
1128
+ return (0, import_node_os.tmpdir)();
1129
+ }
1130
+ get tmpDirRelative() {
1131
+ return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
1132
+ }
1133
+ parseDotEnv() {
1134
+ return import_dotenv_expand.default.expand(this.myEnv);
1135
+ }
1136
+ /**
1137
+ *
1138
+ * @param target path to the file or directory to check for existence
1139
+ * @returns true if the file or directory exists, false otherwise
1140
+ * @example
1141
+ * ```ts
1142
+ * const fs = new Fs(process.cwd());
1143
+ * const exists = fs.exists("my-file.txt");
1144
+ * console.log(exists); // true if the file exists, false otherwise
1145
+ * ```
1146
+ * @description
1147
+ * This method checks if a file or directory exists at the specified path input
1148
+ *
1149
+ * Additional Note:
1150
+ *
1151
+ * say you have a directory that begins with a dot, such as `.turbo`;
1152
+ *
1153
+ * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
1154
+ *
1155
+ */
1156
+ exists(target) {
1157
+ if (!/\//gm.test(target)) {
1158
+ if (/\./g.test(target)) {
1159
+ return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
1160
+ } else {
1161
+ const statsSync = import_fs.default.statSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)), {
1162
+ throwIfNoEntry: false
1163
+ });
1164
+ const isDir = statsSync?.isDirectory();
1165
+ if (isDir) {
1166
+ return isDir;
1167
+ } else return false;
1168
+ }
1169
+ } else {
1170
+ if (/\./g.test(target)) {
1171
+ return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
1172
+ } else {
1173
+ const statsSync = import_fs.default.statSync((0, import_path.relative)(this.cwd, target), {
1174
+ throwIfNoEntry: false
1175
+ });
1176
+ const isDir = statsSync?.isDirectory();
1177
+ if (isDir) {
1178
+ return isDir;
1179
+ } else return false;
1180
+ }
1181
+ }
1182
+ }
1183
+ /**
1184
+ *
1185
+ * @param ms milliseconds to wait
1186
+ * @returns a promise that resolves after the specified number of milliseconds
1187
+ * @example
1188
+ * ```ts
1189
+ * const fs = new Fs(process.cwd());
1190
+ * await fs.wait(1000); // waits for 1 second
1191
+ * console.log("Done waiting!");
1192
+ * ```
1193
+ *
1194
+ * Alternatively, you can use it like this:
1195
+ * ```ts
1196
+ * const fs = new Fs(process.cwd());
1197
+ * fs.wait(1000).then(() => { // waits for 1 second
1198
+ * console.log("Done waiting!");
1199
+ * // do something after waiting
1200
+ * });
1201
+ * ```
1202
+ *
1203
+ * @description
1204
+ * This method is useful for delaying execution in asynchronous code, such as when you need to wait for a file operation to complete or when you want to introduce a delay in a loop.
1205
+ */
1206
+ wait(ms) {
1207
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
1208
+ }
1209
+ /**
1210
+ * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
1211
+ * @param arr An array or readonly array of strings and/or Buffers
1212
+ * @returns An array of strings with Buffers converted to UTF-8 strings.
1213
+ */
1214
+ handleBuffStrArrUnion(arr) {
1215
+ return arr.map(
1216
+ (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
1217
+ );
1218
+ }
1219
+ isRootPathTargeted(path) {
1220
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
1221
+ return true;
1222
+ } else return false;
1223
+ }
1224
+ /**
1225
+ *
1226
+ * @param path path to the directory relative to the cwd
1227
+ * @param options options for reading the directory, defaults to recursive
1228
+ *
1229
+ * The following two examples are equivalent:
1230
+ *
1231
+ * @example
1232
+ * ```ts
1233
+ * const fs = new Fs(process.cwd());
1234
+ * const files = fs.readDir("./my-directory", { recursive: true });
1235
+ * console.log(files);
1236
+ * ```
1237
+ * @example
1238
+ * ```ts
1239
+ * const fs = new Fs(process.cwd());
1240
+ * const files = fs.readDir("my-directory", { recursive: true });
1241
+ * console.log(files);
1242
+ * ```
1243
+ *
1244
+ * @returns an array of strings representing the contents of the directory
1245
+ */
1246
+ readDir(path, options = {
1247
+ recursive: true,
1248
+ withFileTypes: false,
1249
+ encoding: "utf-8"
1250
+ }) {
1251
+ if (this.isRootPathTargeted(path)) {
1252
+ return this.handleBuffStrArrUnion(
1253
+ import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
1254
+ );
1255
+ } else {
1256
+ return this.handleBuffStrArrUnion(
1257
+ import_fs.default.readdirSync(
1258
+ (0, import_path.relative)(this.cwd ??= process.cwd(), path),
1259
+ options
1260
+ )
1261
+ );
1262
+ }
1263
+ }
1264
+ executeCommand = /* @__PURE__ */ __name(({
1265
+ command,
1266
+ ...options
1267
+ }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString(
1268
+ "utf-8"
1269
+ ), "executeCommand");
1270
+ existsSync(path) {
1271
+ return this.exists(path);
1272
+ }
1273
+ pathHandler(path) {
1274
+ return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
1275
+ }
1276
+ mkdirSync(path, options) {
1277
+ return import_fs.default.mkdirSync((0, import_path.relative)(this.cwd, path), options);
1278
+ }
1279
+ units = unitsObj;
1280
+ u = ["B", "KB", "MB", "GB", "TB", "PB"];
1281
+ autoFileSizeRaw(size) {
1282
+ let s = typeof size === "bigint" ? Number(size) : size;
1283
+ let i = 0;
1284
+ while (s >= 1024 && i < this.u.length - 1) {
1285
+ s /= 1024;
1286
+ i++;
1287
+ }
1288
+ return { value: s, unit: this.u[i] };
1289
+ }
1290
+ getSize(size, target, opts = { decimals: 4, includeUnits: true }) {
1291
+ const { decimals, includeUnits } = opts;
1292
+ if (target === "auto") {
1293
+ const { value, unit } = this.autoFileSizeRaw(size);
1294
+ const rounded2 = value.toFixed(decimals);
1295
+ return includeUnits ? `${rounded2} ${unit}` : Number.parseFloat(rounded2);
1296
+ }
1297
+ const key = target.toUpperCase();
1298
+ const exp = this.units[key];
1299
+ const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
1300
+ let v = 0;
1301
+ if (typeof size === "bigint" || typeof divisor === "bigint") {
1302
+ if (typeof size === "bigint" && typeof divisor === "bigint")
1303
+ v = Number(size / divisor);
1304
+ else if (typeof size !== "bigint" && typeof divisor === "bigint")
1305
+ v = size / Number(divisor);
1306
+ else if (typeof size === "bigint" && typeof divisor !== "bigint")
1307
+ v = Number(size) / divisor;
1308
+ } else if (typeof size === "number" && typeof divisor === "number") {
1309
+ v = size / divisor;
1310
+ }
1311
+ const rounded = v.toFixed(decimals);
1312
+ return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
1313
+ }
1314
+ fileSizeMb(path) {
1315
+ return import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size / (1024 * 1024);
1316
+ }
1317
+ fileSize(path, target, opts) {
1318
+ if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
1319
+ else {
1320
+ return this.getSize(
1321
+ import_fs.default.statSync((0, import_path.relative)(this.cwd, path)).size,
1322
+ target,
1323
+ opts
1324
+ );
1325
+ }
1326
+ }
1327
+ generateDirIfDNE(path, options) {
1328
+ if (this.existsSync(path)) return;
1329
+ else {
1330
+ return this.mkdirSync(path, options);
1331
+ }
1332
+ }
1333
+ withWs(path, data, options) {
1334
+ try {
1335
+ if (/\//g.test(path) === true) {
1336
+ return this.generateDirIfDNE(this.pathHandler(path), {
1337
+ recursive: true
1338
+ });
1339
+ } else return path;
1340
+ } catch (error) {
1341
+ console.error(
1342
+ `[withWs error]: `.concat(
1343
+ typeof error === "string" ? error : JSON.stringify(error, null, 2)
1344
+ )
1345
+ );
1346
+ } finally {
1347
+ return import_fs.default.createWriteStream(
1348
+ (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1349
+ typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
1350
+ ).write(Buffer.from(Buffer.from(data).toJSON().data));
1351
+ }
1352
+ }
1353
+ writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
1354
+ try {
1355
+ if (/\//g.test(path) === true)
1356
+ return this.generateDirIfDNE(this.pathHandler(path), {
1357
+ recursive: true
1358
+ });
1359
+ else return path;
1360
+ } catch (error) {
1361
+ console.error(
1362
+ `[writeFileAsync error]: `.concat(
1363
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
1364
+ )
1365
+ );
1366
+ } finally {
1367
+ return await import_promises.default.writeFile(
1368
+ (0, import_path.relative)(this.cwd ?? process.cwd(), path),
1369
+ Buffer.from(Buffer.from(data).toJSON().data),
1370
+ options
1371
+ );
1372
+ }
1373
+ }, "writeFileAsync");
1374
+ async unlink(path) {
1375
+ if (this.existsSync(path)) {
1376
+ return await import_promises.default.unlink((0, import_path.relative)(this.cwd, path));
1377
+ } else {
1378
+ throw new Error(`input path ${path} does not exist`);
1379
+ }
1380
+ }
1381
+ rmFile(filePath) {
1382
+ if (this.exists(filePath)) {
1383
+ if (this.isRootPathTargeted(filePath)) {
1384
+ import_fs.default.rmSync((0, import_path.resolve)((0, import_path.join)(this.cwd, filePath)));
1385
+ } else import_fs.default.rmSync((0, import_path.resolve)(this.cwd, filePath));
1386
+ } else return;
1387
+ }
1388
+ async rmdir(dir, options) {
1389
+ const resolved = (0, import_path.relative)(this.cwd, dir);
1390
+ if (this.exists(dir)) {
1391
+ return import_promises.default.rmdir((0, import_path.relative)(this.cwd, dir), options);
1392
+ } else {
1393
+ throw new Error(`directory ${resolved} does not exist`);
1394
+ }
1395
+ }
1396
+ rmDirSync(dir) {
1397
+ const resolved = (0, import_path.resolve)(this.cwd, dir);
1398
+ if (this.exists(dir)) {
1399
+ return import_fs.default.rm(resolved, { force: true, recursive: true }, (err) => {
1400
+ if (err?.message) {
1401
+ console.error(err?.message);
1348
1402
  }
1403
+ });
1404
+ } else {
1405
+ throw new Error(`directory ${resolved} does not exist`);
1406
+ }
1407
+ }
1408
+ fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
1409
+ import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
1410
+ ), "fileToBuffer");
1411
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
1412
+ return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
1413
+ }, "fileToBufferAsync");
1414
+ dirContainsDir(readDir, targetDir, options) {
1415
+ return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
1416
+ }
1417
+ async assetToBuffer(path) {
1418
+ const [fetcher] = await Promise.all([
1419
+ fetch(path).then((t) => t.arrayBuffer())
1420
+ ]);
1421
+ const mime = this.getMimeTypeForPath(path);
1422
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
1423
+ const extension = this.assetType(path) ?? "txt";
1424
+ return {
1425
+ b64encodedData,
1426
+ extension
1427
+ };
1428
+ }
1429
+ async assetToBufferView(path) {
1430
+ const response = await fetch(path, { method: "GET" });
1431
+ if (!response.ok) {
1432
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
1433
+ }
1434
+ const reader = response.body?.getReader();
1435
+ if (reader) {
1436
+ const chunks = Array.of();
1437
+ while (true) {
1438
+ const { done, value } = await reader.read();
1439
+ if (done) break;
1440
+ if (value) chunks.push(value);
1349
1441
  }
1350
- const auxC = this.findBox(buffer, "auxC", ipco.pos, ipco.pos + ipco.size);
1351
- if (auxC && buffer.toString("ascii", auxC.pos, auxC.pos + auxC.size).includes("alpha")) {
1352
- hasAlpha = true;
1353
- if (colorSpace === "rgb" || colorSpace === "ycbcr") {
1354
- colorSpace = colorSpace === "rgb" ? "rgba" : "ycck";
1355
- } else if (colorSpace === "unknown") {
1356
- colorSpace = "grayscale-alpha";
1357
- }
1442
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
1443
+ const completeBuffer = new Uint8Array(totalLength);
1444
+ let offset = 0;
1445
+ for (const chunk of chunks) {
1446
+ completeBuffer.set(chunk, offset);
1447
+ offset += chunk.length;
1358
1448
  }
1359
- let frames = 1;
1360
- let animated = isAvis;
1361
- if (animated) {
1362
- const iloc = this.findBox(buffer, "iloc", metaSubStart, metaSubEnd);
1363
- if (iloc) {
1364
- const version = buffer?.[iloc.pos];
1365
- const itemCountPos = iloc.pos + (version ? version < 2 ? 4 : 6 : 4);
1366
- frames = buffer.readUInt16BE(itemCountPos);
1449
+ const mime = this.getMimeTypeForPath(path);
1450
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
1451
+ const extension = this.assetType(path);
1452
+ return { b64encodedData, extension };
1453
+ } else {
1454
+ const arrayBuffer = await response.arrayBuffer();
1455
+ const mime = this.getMimeTypeForPath(path);
1456
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
1457
+ const extension = this.assetType(path);
1458
+ return { b64encodedData, extension };
1459
+ }
1460
+ }
1461
+ formatHelper(f) {
1462
+ if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
1463
+ const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
1464
+ return formatting;
1465
+ } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
1466
+ }
1467
+ cleanDataUrl(props) {
1468
+ return props.replace(
1469
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
1470
+ ""
1471
+ );
1472
+ }
1473
+ /**
1474
+ *
1475
+ * @param inputUrl remote url to fetch data from
1476
+ * @param outputPath desired output path relative to the cwd
1477
+ * @param useDetectedExtension optional, defaults to true
1478
+ *
1479
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1480
+ *
1481
+ * 🚫 'public/assets/image-1'
1482
+ *
1483
+ * ✅ 'public/assets/image-1.png'
1484
+ */
1485
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
1486
+ try {
1487
+ const result = await this.assetToBufferView(inputUrl);
1488
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
1489
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
1490
+ if (/\./g.test(formattedPath) === false) {
1491
+ throw new Error(
1492
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
1493
+ );
1494
+ }
1495
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
1496
+ } catch (err) {
1497
+ return console.error(err);
1498
+ }
1499
+ }
1500
+ knownToBlockHead(inputUrl) {
1501
+ if (inputUrl.startsWith("https://github.com")) {
1502
+ return "GET";
1503
+ } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
1504
+ return "GET";
1505
+ } else {
1506
+ return "HEAD";
1507
+ }
1508
+ }
1509
+ /**
1510
+ *
1511
+ * @param inputUrl remote url to fetch data from
1512
+ * @param outputPath desired output path relative to the cwd
1513
+ * @param useDetectedExtension optional, defaults to true
1514
+ *
1515
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
1516
+ *
1517
+ * 🚫 'public/assets/image-1'
1518
+ *
1519
+ * ✅ 'public/assets/image-1.png'
1520
+ *
1521
+ * @description
1522
+ * This method is designed for all files regardless of size, but especially for
1523
+ * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
1524
+ * For files > 100 MB, it streams the data directly to disk instead of loading it all into memory
1525
+ */
1526
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
1527
+ if (!URL.canParse(inputUrl))
1528
+ throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
1529
+ const MAX_SAFE_IN_MEMORY_MB = 100;
1530
+ try {
1531
+ const head = await fetch(inputUrl, {
1532
+ method: this.knownToBlockHead(inputUrl)
1533
+ });
1534
+ const contentLength = head.headers.get("content-length");
1535
+ const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
1536
+ let outputPath = outputPathI;
1537
+ const assetTypeViaUrl = this.assetType(inputUrl);
1538
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
1539
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
1540
+ this.generateDirIfDNE(this.pathHandler(formattedPath), {
1541
+ recursive: true
1542
+ });
1543
+ if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
1544
+ const res = await fetch(inputUrl);
1545
+ if (!res.ok || !res.body) {
1546
+ throw new Error(`Failed to fetch asset: ${res.statusText}`);
1367
1547
  }
1548
+ const writeStream = import_fs.default.createWriteStream(
1549
+ (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
1550
+ );
1551
+ const reader = res.body.getReader();
1552
+ const pump = /* @__PURE__ */ __name(async () => {
1553
+ while (true) {
1554
+ const { done, value } = await reader.read();
1555
+ if (done) break;
1556
+ writeStream.write(value);
1557
+ }
1558
+ writeStream.end();
1559
+ }, "pump");
1560
+ await pump();
1561
+ return;
1368
1562
  }
1369
- return {
1370
- width,
1371
- height,
1372
- format: "avif",
1373
- frames,
1374
- animated,
1375
- hasAlpha: hasAlpha ? true : null,
1376
- // null if unknown
1377
- orientation: null,
1378
- // Can have 'irot' or 'imir' transforms, but rare
1379
- aspectRatio: width / height,
1380
- colorSpace,
1381
- iccProfile,
1382
- exifDateTimeOriginal: null
1383
- // Can have 'XMP' box, but parse XMP for date if needed
1384
- };
1563
+ const result = await this.assetToBufferView(inputUrl);
1564
+ const cleanedData = this.cleanDataUrl(result.b64encodedData);
1565
+ this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
1566
+ } catch (err) {
1567
+ console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
1385
1568
  }
1386
- throw new Error("Unsupported image format or invalid file");
1387
1569
  }
1388
1570
  /**
1389
1571
  *
@@ -1429,6 +1611,13 @@ var Fs = class extends MimeService {
1429
1611
  const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1430
1612
  Promise.resolve(this.withWs(fullPath, data, options));
1431
1613
  }
1614
+ async readTmpAsync(filename) {
1615
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1616
+ if (!this.exists(fullPath)) {
1617
+ throw new Error(`Tmp file not found: ${filename}`);
1618
+ }
1619
+ return await this.fileToBufferAsync(fullPath);
1620
+ }
1432
1621
  /**
1433
1622
  * Read a file from the tmp directory
1434
1623
  * @param filename The filename to read (can include subdirectories)
@@ -1638,6 +1827,7 @@ var Fs = class extends MimeService {
1638
1827
  // Annotate the CommonJS export names for ESM import in node:
1639
1828
  0 && (module.exports = {
1640
1829
  Fs,
1830
+ ImageService,
1641
1831
  MimeService,
1642
1832
  UrlService,
1643
1833
  UtilsService,