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