@d0paminedriven/fs 6.1.0 → 6.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/fs/index.cjs CHANGED
@@ -37,13 +37,142 @@ module.exports = __toCommonJS(fs_exports);
37
37
  var import_child_process = require("child_process");
38
38
  var import_fs = __toESM(require("fs"), 1);
39
39
  var import_promises = __toESM(require("fs/promises"), 1);
40
+ var import_node_os = require("os");
40
41
  var import_path = require("path");
41
42
  var dotenv = __toESM(require("dotenv"), 1);
42
43
  var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
43
44
  var import_sharp = __toESM(require("sharp"), 1);
44
45
 
46
+ // src/utils/index.ts
47
+ var UtilsService = class {
48
+ static {
49
+ __name(this, "UtilsService");
50
+ }
51
+ chunkArray(arr, maxChunkLength) {
52
+ const chunks = Array.of();
53
+ let currentChunkLength = 0;
54
+ let currentChunk = Array.of();
55
+ for (const [index, val] of arr.entries()) {
56
+ if (val.length + currentChunkLength >= maxChunkLength) {
57
+ if (currentChunk.length) {
58
+ chunks.push(currentChunk);
59
+ }
60
+ currentChunkLength = val.length;
61
+ currentChunk = [val];
62
+ } else {
63
+ currentChunk.push(val);
64
+ currentChunkLength += val.length + 1;
65
+ }
66
+ if (arr.length === index + 1) {
67
+ chunks.push(currentChunk);
68
+ }
69
+ }
70
+ return chunks.length ? chunks : [arr];
71
+ }
72
+ b64ToBlob(b64Data) {
73
+ {
74
+ const sliceSize = 512;
75
+ const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
76
+ b64Data
77
+ );
78
+ if (!typeMatch) {
79
+ throw new Error(`${b64Data} is not a valid data Url`);
80
+ }
81
+ const type = typeMatch[1];
82
+ const base64Data = typeMatch?.[2] ?? "";
83
+ const byteCharacters = Buffer.from(base64Data, "base64").toString(
84
+ "binary"
85
+ );
86
+ const byteArrays = Array.of();
87
+ for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
88
+ const slice = byteCharacters.slice(offset, offset + sliceSize);
89
+ const byteNumbers = new Array(slice.length);
90
+ for (let i = 0; i < slice.length; i++) {
91
+ byteNumbers[i] = slice.charCodeAt(i);
92
+ }
93
+ const byteArray = new Uint8Array(byteNumbers);
94
+ byteArrays.push(byteArray);
95
+ }
96
+ const blob = new Blob(byteArrays, { type });
97
+ return blob;
98
+ }
99
+ }
100
+ arrToArrOfArrs = /* @__PURE__ */ __name(({
101
+ arrToFragment = Array.of(),
102
+ arrOfArrsAggregator = Array.of(),
103
+ interval
104
+ }) => new Promise(
105
+ (resolve2, _reject) => resolve2(
106
+ ((interval2) => {
107
+ for (let i = 0; i <= arrToFragment.length; i++) {
108
+ if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
109
+ let segment = arrToFragment.slice(i, i + interval2);
110
+ arrOfArrsAggregator.push(segment);
111
+ }
112
+ }
113
+ })(interval)
114
+ )
115
+ ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
116
+ extractTuple(obj, props) {
117
+ return [props, obj[props]];
118
+ }
119
+ sort(obj, order) {
120
+ return Object.fromEntries(
121
+ Object.entries(obj).sort(
122
+ ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
123
+ )
124
+ );
125
+ }
126
+ excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
127
+ const resolve2 = Object.fromEntries(
128
+ Object.entries(obj).map(([key, val]) => {
129
+ if (props.includes(key)) {
130
+ return ["omit", "omit"];
131
+ } else return [key, val];
132
+ }).filter(([t, _v]) => /omit/.test(t) === false)
133
+ );
134
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
135
+ }, "excludeTargeted");
136
+ includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
137
+ const resolve2 = Object.fromEntries(
138
+ props.map((val) => this.extractTuple(obj, val))
139
+ );
140
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
141
+ }, "includeTargeted");
142
+ countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
143
+ Array.from(Object.entries(counter)).sort(
144
+ ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
145
+ ).sort(([aStr, aNum], [bStr, bNum]) => {
146
+ if (typeof (aNum && bNum) === "number") {
147
+ return valSort === "ASC" ? aNum - bNum : bNum - aNum;
148
+ } else if (typeof (aNum && bNum) === "string") {
149
+ return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
150
+ } else
151
+ throw new Error(
152
+ "only Record<string, string> and Record<string,number> types supported"
153
+ );
154
+ })
155
+ ), "countsSorter");
156
+ range(from, to) {
157
+ const values = Array.of();
158
+ for (let i = from; i < to; i++) {
159
+ values.push(i);
160
+ }
161
+ return values;
162
+ }
163
+ isPrimeNumber = /* @__PURE__ */ __name((n) => {
164
+ for (let i = 2; n > i; i++) {
165
+ if (n % i === 0) {
166
+ return false;
167
+ }
168
+ }
169
+ return n > 1;
170
+ }, "isPrimeNumber");
171
+ acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
172
+ };
173
+
45
174
  // src/url/index.ts
46
- var UrlService = class {
175
+ var UrlService = class extends UtilsService {
47
176
  static {
48
177
  __name(this, "UrlService");
49
178
  }
@@ -75,7 +204,7 @@ var extMimeMap = {
75
204
  avif: ["image/avif"],
76
205
  avi: ["video/x-msvideo"],
77
206
  azw: ["application/vnd.amazon.ebook"],
78
- bin: ["application/octet-stream"],
207
+ bin: ["application/octet-stream", "multipart/voice-message"],
79
208
  bmp: ["image/bmp"],
80
209
  bz: ["application/x-bzip"],
81
210
  bz2: ["application/x-bzip2"],
@@ -95,7 +224,7 @@ var extMimeMap = {
95
224
  gif: ["image/gif"],
96
225
  glb: ["model/gltf-binary"],
97
226
  gltf: ["model/gltf+json"],
98
- gz: ["application/x-gzip", "application/gzip"],
227
+ gz: ["application/gzip", "application/x-gzip"],
99
228
  hjif: ["haptics/hjif"],
100
229
  hmpg: ["haptics/hmpg"],
101
230
  htm: ["text/html"],
@@ -103,6 +232,7 @@ var extMimeMap = {
103
232
  ico: ["image/vnd.microsoft.icon"],
104
233
  ics: ["text/calendar"],
105
234
  ivs: ["haptics/ivs"],
235
+ ivt: ["haptics/ivs"],
106
236
  jar: ["application/java-archive"],
107
237
  jpeg: ["image/jpeg"],
108
238
  jpg: ["image/jpeg"],
@@ -124,7 +254,8 @@ var extMimeMap = {
124
254
  mpeg: ["video/mpeg"],
125
255
  mpkg: ["application/vnd.apple.installer+xml"],
126
256
  ndjson: ["application/x-ndjson"],
127
- obj: ["application/octet-stream", "text/plain", "model/obj"],
257
+ node: ["application/node", "text/javascript"],
258
+ obj: ["model/obj", "application/octet-stream", "text/plain"],
128
259
  odp: ["application/vnd.oasis.opendocument.presentation"],
129
260
  ods: ["application/vnd.oasis.opendocument.spreadsheet"],
130
261
  odt: ["application/vnd.oasis.opendocument.text"],
@@ -145,9 +276,11 @@ var extMimeMap = {
145
276
  py: ["text/x-python"],
146
277
  pyc: ["application/x-python-code"],
147
278
  rar: ["application/vnd.rar"],
279
+ rs: ["text/rust"],
148
280
  rtf: ["application/rtf"],
149
281
  sh: ["application/x-sh"],
150
282
  sql: ["application/sql"],
283
+ sse: ["text/event-stream"],
151
284
  svg: ["image/svg+xml"],
152
285
  tar: ["application/x-tar"],
153
286
  tif: ["image/tiff"],
@@ -177,6 +310,118 @@ var extMimeMap = {
177
310
  "3g2": ["video/3gpp2"],
178
311
  "7z": ["application/x-7z-compressed"]
179
312
  };
313
+ var mimeToExt = {
314
+ "application/epub+zip": ["epub"],
315
+ "application/font-sfnt": ["ttf"],
316
+ "application/gzip": ["gz"],
317
+ "application/java-archive": ["jar"],
318
+ "application/json": ["json"],
319
+ "application/ld+json": ["jsonld"],
320
+ "application/msword": ["doc"],
321
+ "application/node": ["node", "js"],
322
+ "application/octet-stream": ["bin", "obj"],
323
+ "application/ogg": ["ogx"],
324
+ "application/pdf": ["pdf"],
325
+ "application/rtf": ["rtf"],
326
+ "application/sql": ["sql"],
327
+ "application/toml": ["toml"],
328
+ "application/vnd.amazon.ebook": ["azw"],
329
+ "application/vnd.apple.installer+xml": ["mpkg"],
330
+ "application/vnd.apple.mpegurl": ["m3u8"],
331
+ "application/vnd.apple.pkpass": ["pkpass"],
332
+ "application/vnd.mozilla.xul+xml": ["xul"],
333
+ "application/vnd.ms-excel": ["xls"],
334
+ "application/vnd.ms-fontobject": ["eot"],
335
+ "application/vnd.ms-powerpoint": ["ppt"],
336
+ "application/vnd.oasis.opendocument.presentation": ["odp"],
337
+ "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
338
+ "application/vnd.oasis.opendocument.text": ["odt"],
339
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
340
+ "pptx"
341
+ ],
342
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
343
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
344
+ "docx"
345
+ ],
346
+ "application/vnd.rar": ["rar"],
347
+ "application/vnd.visio": ["vsd"],
348
+ "application/wasm": ["wasm"],
349
+ "application/x-7z-compressed": ["7z"],
350
+ "application/x-abiword": ["abw"],
351
+ "application/x-bzip": ["bz"],
352
+ "application/x-bzip2": ["bz2"],
353
+ "application/x-cdf": ["cda"],
354
+ "application/x-csh": ["csh"],
355
+ "application/x-freearc": ["arc"],
356
+ "application/x-gzip": ["gz"],
357
+ "application/x-httpd-php": ["php"],
358
+ "application/x-mdx": ["mdx"],
359
+ "application/x-ndjson": ["ndjson"],
360
+ "application/x-python-code": ["pyc"],
361
+ "application/x-sh": ["sh"],
362
+ "application/x-tar": ["tar"],
363
+ "application/x-zip-compressed": ["zip"],
364
+ "application/xhtml+xml": ["xhtml"],
365
+ "application/xml": ["xml"],
366
+ "application/yaml": ["yml", "yaml"],
367
+ "application/zip": ["zip"],
368
+ "audio/aac": ["aac"],
369
+ "audio/midi": ["mid"],
370
+ "audio/mp4": ["m4a"],
371
+ "audio/mpeg": ["mp3"],
372
+ "audio/ogg": ["opus", "ogg", "oga"],
373
+ "audio/wav": ["wav"],
374
+ "audio/x-midi": ["midi"],
375
+ "font/otf": ["otf"],
376
+ "font/ttf": ["ttf"],
377
+ "font/woff": ["woff"],
378
+ "font/woff2": ["woff2"],
379
+ "haptics/hjif": ["hjif"],
380
+ "haptics/hmpg": ["hmpg"],
381
+ "haptics/ivs": ["ivs", "ivt"],
382
+ "image/aces": ["aces"],
383
+ "image/apng": ["apng"],
384
+ "image/avci": ["avci"],
385
+ "image/avif": ["avif"],
386
+ "image/bmp": ["bmp"],
387
+ "image/dpx": ["dpx"],
388
+ "image/emf": ["emf"],
389
+ "image/gif": ["gif"],
390
+ "image/jpeg": ["jpg", "jpeg"],
391
+ "image/ktx": ["ktx"],
392
+ "image/ktx2": ["ktx2"],
393
+ "image/png": ["png"],
394
+ "image/svg+xml": ["svg"],
395
+ "image/tiff": ["tiff", "tif"],
396
+ "image/vnd.microsoft.icon": ["ico"],
397
+ "image/webp": ["webp"],
398
+ "model/gltf-binary": ["glb"],
399
+ "model/gltf+json": ["gltf"],
400
+ "model/obj": ["obj"],
401
+ "model/vnd.usdz+zip": ["usdz"],
402
+ "multipart/voice-message": ["bin"],
403
+ "text/calendar": ["ics"],
404
+ "text/css": ["css"],
405
+ "text/csv": ["csv"],
406
+ "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
407
+ "text/html": ["html", "htm"],
408
+ "text/javascript": ["cjs", "js", "mjs"],
409
+ "text/markdown": ["md"],
410
+ "text/plain": ["txt"],
411
+ "text/rust": ["rs"],
412
+ "text/typescript": ["ts"],
413
+ "text/vtt": ["vtt"],
414
+ "text/x-python": ["py"],
415
+ "video/3gpp": ["3gp"],
416
+ "video/3gpp2": ["3g2"],
417
+ "video/mp2t": ["ts"],
418
+ "video/mp4": ["mp4", "m4v"],
419
+ "video/mpeg": ["mpeg"],
420
+ "video/ogg": ["ogv"],
421
+ "video/vnd.dlna.mpeg-tts": ["ts"],
422
+ "video/webm": ["weba"],
423
+ "video/x-msvideo": ["avi"]
424
+ };
180
425
  var MimeService = class extends UrlService {
181
426
  static {
182
427
  __name(this, "MimeService");
@@ -185,6 +430,35 @@ var MimeService = class extends UrlService {
185
430
  super();
186
431
  }
187
432
  mimeTypeObj = extMimeMap;
433
+ toExtObj = mimeToExt;
434
+ compareMimeToExt(p = "mime") {
435
+ let a = {};
436
+ if (p === "mime") {
437
+ for (const [_key, vals] of Object.entries(extMimeMap)) {
438
+ for (const val of vals) {
439
+ a[val] = (a[val] ?? 0) + 1;
440
+ }
441
+ }
442
+ for (const [key, _val] of Object.entries(mimeToExt)) {
443
+ a[key] = (a[key] ?? 0) + 1;
444
+ }
445
+ return Object.fromEntries(
446
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
447
+ );
448
+ } else {
449
+ for (const [_key, vals] of Object.entries(mimeToExt)) {
450
+ for (const val of vals) {
451
+ a[val] = (a[val] ?? 0) + 1;
452
+ }
453
+ }
454
+ for (const [key, _val] of Object.entries(extMimeMap)) {
455
+ a[key] = (a[key] ?? 0) + 1;
456
+ }
457
+ return Object.fromEntries(
458
+ Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
459
+ );
460
+ }
461
+ }
188
462
  assetType(url) {
189
463
  const parsed = this.parseUrl(url);
190
464
  if (!parsed) return void 0;
@@ -229,6 +503,7 @@ var Fs = class extends MimeService {
229
503
  constructor(cwd) {
230
504
  super();
231
505
  this.cwd = cwd;
506
+ cwd ??= process.cwd();
232
507
  }
233
508
  static {
234
509
  __name(this, "Fs");
@@ -236,6 +511,12 @@ var Fs = class extends MimeService {
236
511
  get myEnv() {
237
512
  return dotenv.config({ processEnv: {} });
238
513
  }
514
+ get tmpDir() {
515
+ return (0, import_node_os.tmpdir)();
516
+ }
517
+ get tmpDirRelative() {
518
+ return (0, import_path.relative)(this.cwd, (0, import_node_os.tmpdir)());
519
+ }
239
520
  parseDotEnv() {
240
521
  return import_dotenv_expand.default.expand(this.myEnv);
241
522
  }
@@ -349,7 +630,11 @@ var Fs = class extends MimeService {
349
630
  *
350
631
  * @returns an array of strings representing the contents of the directory
351
632
  */
352
- readDir(path, options = { recursive: true }) {
633
+ readDir(path, options = {
634
+ recursive: true,
635
+ withFileTypes: false,
636
+ encoding: "utf-8"
637
+ }) {
353
638
  if (this.isRootPathTargeted(path)) {
354
639
  return this.handleBuffStrArrUnion(
355
640
  import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), { ...options })
@@ -510,6 +795,9 @@ var Fs = class extends MimeService {
510
795
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
511
796
  import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
512
797
  ), "fileToBuffer");
798
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
799
+ return await import_promises.default.readFile((0, import_path.relative)(this.cwd, path));
800
+ }, "fileToBufferAsync");
513
801
  dirContainsDir(readDir, targetDir, options) {
514
802
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
515
803
  }
@@ -526,10 +814,11 @@ var Fs = class extends MimeService {
526
814
  };
527
815
  }
528
816
  async assetToBufferView(path) {
529
- const response = await fetch(path);
817
+ const response = await fetch(path, { method: "GET" });
530
818
  if (!response.ok) {
531
819
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
532
820
  }
821
+ console.log(Object.fromEntries(Array.from(response.headers.entries())));
533
822
  const reader = response.body?.getReader();
534
823
  if (reader) {
535
824
  const chunks = Array.of();
@@ -596,13 +885,37 @@ var Fs = class extends MimeService {
596
885
  return console.error(err);
597
886
  }
598
887
  }
599
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
888
+ /**
889
+ *
890
+ * @param inputUrl remote url to fetch data from
891
+ * @param outputPath desired output path relative to the cwd
892
+ * @param useDetectedExtension optional, defaults to true
893
+ *
894
+ * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
895
+ *
896
+ * 🚫 'public/assets/image-1'
897
+ *
898
+ * ✅ 'public/assets/image-1.png'
899
+ *
900
+ * @description
901
+ * This method is designed for large files that may not fit into memory.
902
+ * It streams the data directly to disk instead of loading it all into memory.
903
+ */
904
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
600
905
  const MAX_SAFE_IN_MEMORY_MB = 100;
601
906
  try {
602
- const head = await fetch(inputUrl, { method: "HEAD" });
907
+ const isGithubRaw = inputUrl.startsWith(
908
+ "https://raw.githubusercontent.com"
909
+ );
910
+ const head = await fetch(inputUrl, {
911
+ method: isGithubRaw ? "GET" : "HEAD"
912
+ });
603
913
  const contentLength = head.headers.get("content-length");
604
914
  const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
605
- const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
915
+ let outputPath = outputPathI;
916
+ const assetTypeViaUrl = this.assetType(inputUrl);
917
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
918
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
606
919
  this.generateDirIfDNE(this.pathHandler(formattedPath), {
607
920
  recursive: true
608
921
  });
@@ -633,6 +946,149 @@ var Fs = class extends MimeService {
633
946
  console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
634
947
  }
635
948
  }
949
+ findBox(buffer, type, start = 0, end = buffer.length) {
950
+ let pos = start;
951
+ while (pos < end) {
952
+ let boxSize = buffer.readUInt32BE(pos);
953
+ let boxType = buffer.toString("ascii", pos + 4, pos + 8);
954
+ let hdrSize = 8;
955
+ if (boxSize === 1) {
956
+ boxSize = Number(buffer.readBigUInt64BE(pos + 8));
957
+ hdrSize = 16;
958
+ } else if (boxSize === 0) {
959
+ boxSize = end - pos;
960
+ }
961
+ if (boxType === type) {
962
+ return { pos: pos + hdrSize, size: boxSize - hdrSize };
963
+ }
964
+ pos += boxSize;
965
+ }
966
+ return null;
967
+ }
968
+ async getImageSize(filePath) {
969
+ const buffer = await this.fileToBufferAsync(filePath);
970
+ 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) {
971
+ if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
972
+ throw new Error("IHDR Chunk of png not found or incorrect.");
973
+ }
974
+ return {
975
+ width: buffer.readUInt32BE(16),
976
+ height: buffer.readUInt32BE(20),
977
+ type: "png"
978
+ };
979
+ }
980
+ if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
981
+ let pos = 2;
982
+ while (pos < buffer.length - 10) {
983
+ if (buffer[pos] !== 255) {
984
+ throw new Error("Invalid JPEG file");
985
+ }
986
+ const marker = buffer[pos + 1];
987
+ if (marker === 218) break;
988
+ const segmentSize = buffer.readUInt16BE(pos + 2);
989
+ if (!marker) {
990
+ throw new Error("no marker for jpeg");
991
+ }
992
+ if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
993
+ return {
994
+ width: buffer.readUInt16BE(pos + 7),
995
+ height: buffer.readUInt16BE(pos + 5),
996
+ type: "jpeg"
997
+ };
998
+ }
999
+ pos += segmentSize + 2;
1000
+ }
1001
+ throw new Error("No dimensions found in JPEG file");
1002
+ }
1003
+ const gifHeader = buffer.toString("ascii", 0, 6);
1004
+ if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
1005
+ return {
1006
+ width: buffer.readUInt16LE(6),
1007
+ height: buffer.readUInt16LE(8),
1008
+ type: "gif"
1009
+ };
1010
+ }
1011
+ if (buffer.length >= 26 && buffer[0] === 66 && buffer[1] === 77) {
1012
+ return {
1013
+ width: buffer.readInt32LE(18),
1014
+ height: Math.abs(buffer.readInt32LE(22)),
1015
+ type: "bmp"
1016
+ };
1017
+ }
1018
+ if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
1019
+ const chunkType = buffer.toString("ascii", 12, 16);
1020
+ if (chunkType === "VP8X") {
1021
+ let widthSubtractOne = 0;
1022
+ let heightSubtractOne = 0;
1023
+ if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
1024
+ widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
1025
+ }
1026
+ if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
1027
+ heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
1028
+ }
1029
+ return {
1030
+ width: widthSubtractOne + 1,
1031
+ height: heightSubtractOne + 1,
1032
+ type: "webp"
1033
+ };
1034
+ } else if (chunkType === "VP8 ") {
1035
+ const dataStart = 20;
1036
+ if (buffer[dataStart + 3] !== 157 || buffer[dataStart + 4] !== 1 || buffer[dataStart + 5] !== 42) {
1037
+ throw new Error("Invalid VP8 keyframe");
1038
+ }
1039
+ const width = buffer.readUInt16LE(dataStart + 6) & 16383;
1040
+ const height = buffer.readUInt16LE(dataStart + 8) & 16383;
1041
+ return {
1042
+ width,
1043
+ height,
1044
+ type: "webp"
1045
+ };
1046
+ } else if (chunkType === "VP8L") {
1047
+ const dataStart = 20;
1048
+ if (buffer[dataStart] !== 47) {
1049
+ throw new Error("Invalid VP8L signature");
1050
+ }
1051
+ const bits = buffer.readUInt32LE(dataStart + 1);
1052
+ if (bits >>> 29 !== 0) {
1053
+ throw new Error("Invalid VP8L version");
1054
+ }
1055
+ const width = 1 + (bits & 16383);
1056
+ const height = 1 + (bits >> 14 & 16383);
1057
+ return {
1058
+ width,
1059
+ height,
1060
+ type: "webp"
1061
+ };
1062
+ }
1063
+ throw new Error("Unsupported WebP chunk");
1064
+ }
1065
+ if (buffer.length >= 32 && buffer.toString("ascii", 4, 8) === "ftyp") {
1066
+ const ftyp = this.findBox(buffer, "ftyp");
1067
+ if (!ftyp) throw new Error("Invalid AVIF: No ftyp");
1068
+ const brands = buffer.toString("ascii", ftyp.pos, ftyp.pos + ftyp.size);
1069
+ if (!brands.includes("avif") && !brands.includes("avis"))
1070
+ throw new Error("Not an AVIF file");
1071
+ const meta = this.findBox(buffer, "meta");
1072
+ if (!meta) throw new Error("Invalid AVIF: No meta");
1073
+ const metaSubStart = meta.pos + 4;
1074
+ const metaSubEnd = meta.pos + meta.size;
1075
+ const iprp = this.findBox(buffer, "iprp", metaSubStart, metaSubEnd);
1076
+ if (!iprp) throw new Error("Invalid AVIF: No iprp");
1077
+ const ipco = this.findBox(buffer, "ipco", iprp.pos, iprp.pos + iprp.size);
1078
+ if (!ipco) throw new Error("Invalid AVIF: No ipco");
1079
+ const ispe = this.findBox(buffer, "ispe", ipco.pos, ipco.pos + ipco.size);
1080
+ if (!ispe) throw new Error("Invalid AVIF: No ispe");
1081
+ if (buffer[ispe.pos] !== 0) throw new Error("Invalid ispe version");
1082
+ const width = buffer.readUInt32BE(ispe.pos + 4);
1083
+ const height = buffer.readUInt32BE(ispe.pos + 8);
1084
+ return {
1085
+ width,
1086
+ height,
1087
+ type: "avif"
1088
+ };
1089
+ }
1090
+ throw new Error("Unsupported image format or invalid file");
1091
+ }
636
1092
  /**
637
1093
  *
638
1094
  * @access package-private
@@ -659,5 +1115,228 @@ var Fs = class extends MimeService {
659
1115
  return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
660
1116
  }
661
1117
  }
1118
+ /**
1119
+ * Write data to a file in the system's tmp directory
1120
+ * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1121
+ * @param data The data to write
1122
+ * @param options Optional write stream options
1123
+ * @returns The full path to the written file
1124
+ * @example
1125
+ * ```ts
1126
+ * const fs = new Fs(process.cwd());
1127
+ * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1128
+ * // Or with a subdirectory:
1129
+ * fs.writeTmp("img-probe/output.png", imageBuffer);
1130
+ * ```
1131
+ */
1132
+ writeTmp(filename, data, options) {
1133
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1134
+ Promise.resolve(this.withWs(fullPath, data, options));
1135
+ }
1136
+ /**
1137
+ * Read a file from the tmp directory
1138
+ * @param filename The filename to read (can include subdirectories)
1139
+ * @returns Buffer containing the file data
1140
+ * @example
1141
+ * ```ts
1142
+ * const fs = new Fs(process.cwd());
1143
+ * const data = fs.readTmp("session-data.json");
1144
+ * const parsed = JSON.parse(data.toString("utf-8"));
1145
+ * ```
1146
+ */
1147
+ readTmp(filename) {
1148
+ const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1149
+ if (!this.exists(fullPath)) {
1150
+ throw new Error(`Tmp file not found: ${filename}`);
1151
+ }
1152
+ return this.fileToBuffer(fullPath);
1153
+ }
1154
+ /**
1155
+ * Scan the tmp directory for files matching a pattern
1156
+ * @param pattern Optional pattern to filter files (e.g., "img-probe")
1157
+ * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1158
+ * @returns Array of matching file paths relative to tmp directory
1159
+ * @example
1160
+ * ```ts
1161
+ * const fs = new Fs(process.cwd());
1162
+ * // Get all img-probe files
1163
+ * const imgFiles = fs.scanTmp("img-probe");
1164
+ * // Get all files in tmp (non-recursive)
1165
+ * const allFiles = fs.scanTmp();
1166
+ * ```
1167
+ */
1168
+ scanTmp(pattern, options = {
1169
+ recursive: false,
1170
+ withFileTypes: false,
1171
+ encoding: "utf-8"
1172
+ }) {
1173
+ const dirs = (0, import_path.resolve)(this.tmpDir);
1174
+ const tmpContents = this.readDir(dirs, options);
1175
+ if (!pattern) {
1176
+ return tmpContents;
1177
+ }
1178
+ if (typeof pattern === "string") {
1179
+ return tmpContents.filter((t) => t.includes(pattern));
1180
+ }
1181
+ return tmpContents.filter((path) => {
1182
+ return pattern.test(path);
1183
+ });
1184
+ }
1185
+ /**
1186
+ * Extract specific files from tmp directory to a target location
1187
+ * @param pattern Pattern to match files (e.g., "img-probe")
1188
+ * @param targetDir Target directory to extract files to
1189
+ * @param options Options for extraction behavior
1190
+ * @returns Array of extracted file paths
1191
+ * @example
1192
+ * ```ts
1193
+ * const fs = new Fs(process.cwd());
1194
+ * // Extract all img-probe files to ./output
1195
+ * const extracted = fs.extractFromTmp("img-probe", "./output");
1196
+ * // Extract with custom behavior
1197
+ * fs.extractFromTmp("session-", "./sessions", {
1198
+ * preserveStructure: true,
1199
+ * cleanupAfter: true
1200
+ * });
1201
+ * ```
1202
+ */
1203
+ extractFromTmp(pattern, targetDir, options) {
1204
+ const {
1205
+ preserveStructure = false,
1206
+ cleanupAfter = false,
1207
+ overwrite = true
1208
+ } = options ?? {};
1209
+ const matchingFiles = this.scanTmp(pattern);
1210
+ const extracted = [];
1211
+ for (const file of matchingFiles) {
1212
+ const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1213
+ const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1214
+ if (!lastSegment) continue;
1215
+ const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1216
+ if (this.exists(targetPath) && !overwrite) {
1217
+ console.warn(`Skipping existing file: ${targetPath}`);
1218
+ continue;
1219
+ }
1220
+ const data = this.fileToBuffer(sourcePath);
1221
+ this.withWs(targetPath, data);
1222
+ extracted.push(targetPath);
1223
+ if (cleanupAfter) {
1224
+ this.rmFile(sourcePath);
1225
+ }
1226
+ }
1227
+ return extracted;
1228
+ }
1229
+ /**
1230
+ * Clean up tmp files matching a pattern
1231
+ * @param pattern Pattern to match files for deletion
1232
+ * @param maxAge Optional max age in milliseconds (only delete files older than this)
1233
+ * @returns Number of files removed
1234
+ * @example
1235
+ * ```ts
1236
+ * const fs = new Fs(process.cwd());
1237
+ * // Remove all img-probe files
1238
+ * fs.cleanupTmp("img-probe");
1239
+ * // Remove session files older than 1 hour
1240
+ * fs.cleanupTmp("session-", 60 * 60 * 1000);
1241
+ * ```
1242
+ */
1243
+ cleanupTmp(pattern, maxAge) {
1244
+ const matchingFiles = this.scanTmp(pattern);
1245
+ let removed = 0;
1246
+ for (const file of matchingFiles) {
1247
+ const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1248
+ try {
1249
+ const stats = import_fs.default.statSync(fullPath);
1250
+ if (maxAge) {
1251
+ const age = Date.now() - stats.mtimeMs;
1252
+ if (age < maxAge) {
1253
+ continue;
1254
+ }
1255
+ }
1256
+ if (stats.isDirectory()) {
1257
+ this.rmDirSync(fullPath);
1258
+ } else {
1259
+ this.rmFile(fullPath);
1260
+ }
1261
+ removed++;
1262
+ } catch (err) {
1263
+ console.warn(`Failed to remove tmp file ${file}:`, err);
1264
+ }
1265
+ }
1266
+ return removed;
1267
+ }
1268
+ rmTmpFile(filename) {
1269
+ const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1270
+ this.rmFile(tmpPath);
1271
+ }
1272
+ /**
1273
+ * Generate a unique tmp filename with optional prefix
1274
+ * @param prefix Optional prefix for the filename
1275
+ * @param extension Optional file extension (without dot)
1276
+ * @returns Unique filename
1277
+ * @example
1278
+ * ```ts
1279
+ * const fs = new Fs(process.cwd());
1280
+ * const filename = fs.uniqueTmpName("img-probe", "png");
1281
+ * // Returns: "img-probe-1701234567890-a3b2c1.png"
1282
+ * ```
1283
+ */
1284
+ uniqueTmpName(prefix, extension) {
1285
+ const timestamp = Date.now();
1286
+ const random = Math.random().toString(36).substring(2, 8);
1287
+ const parts = [prefix ?? "tmp", timestamp, random].join("-");
1288
+ return extension ? `${parts}.${extension}` : parts;
1289
+ }
1290
+ /**
1291
+ * Async generator for cleaning tmp files with batched removal
1292
+ * @param pattern Pattern to match files for deletion
1293
+ * @param batchSize Number of files to remove per batch (default 10)
1294
+ * @yields Progress information during cleanup
1295
+ * @returns Final cleanup summary
1296
+ * @example
1297
+ * ```ts
1298
+ * const fs = new Fs(process.cwd());
1299
+ * // Clean up with progress tracking
1300
+ * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1301
+ * console.log(progress);
1302
+ * }
1303
+ * ```
1304
+ */
1305
+ async *cleanTmpGenerator(pattern, batchSize = 10) {
1306
+ const files = this.scanTmp(pattern);
1307
+ const batches = await this.arrToArrOfArrs({
1308
+ arrToFragment: files,
1309
+ arrOfArrsAggregator: [],
1310
+ interval: batchSize
1311
+ });
1312
+ let totalRemoved = 0;
1313
+ for (const [index, batch] of batches.entries()) {
1314
+ yield {
1315
+ action: "removing",
1316
+ batch: [...batch],
1317
+ batchNumber: index + 1,
1318
+ totalBatches: batches.length,
1319
+ totalFound: files.length,
1320
+ removed: totalRemoved
1321
+ };
1322
+ for (const file of batch) {
1323
+ this.rmTmpFile(file);
1324
+ totalRemoved++;
1325
+ }
1326
+ yield {
1327
+ action: "batch-complete",
1328
+ batchNumber: index + 1,
1329
+ batchSize: batch.length,
1330
+ totalRemoved,
1331
+ remaining: files.length - totalRemoved
1332
+ };
1333
+ }
1334
+ return {
1335
+ action: "complete",
1336
+ totalRemoved,
1337
+ totalBatches: batches.length,
1338
+ pattern: pattern.toString()
1339
+ };
1340
+ }
662
1341
  };
663
1342
  //# sourceMappingURL=index.cjs.map