@d0paminedriven/fs 7.0.1 → 7.2.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 DELETED
@@ -1,1648 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __export = (target, all) => {
10
- for (var name in all)
11
- __defProp(target, name, { get: all[name], enumerable: true });
12
- };
13
- var __copyProps = (to, from, except, desc) => {
14
- if (from && typeof from === "object" || typeof from === "function") {
15
- for (let key of __getOwnPropNames(from))
16
- if (!__hasOwnProp.call(to, key) && key !== except)
17
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
- }
19
- return to;
20
- };
21
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
- // If the importer is in node compatibility mode or this is not an ESM
23
- // file that has been converted to a CommonJS file using a Babel-
24
- // compatible transform (i.e. "__esModule" has not been set), then set
25
- // "default" to the CommonJS "module.exports" for node compatibility.
26
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
- mod
28
- ));
29
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
-
31
- // src/index.ts
32
- var index_exports = {};
33
- __export(index_exports, {
34
- Fs: () => Fs,
35
- MimeService: () => MimeService,
36
- UrlService: () => UrlService,
37
- UtilsService: () => UtilsService,
38
- extMimeMap: () => extMimeMap,
39
- mimeToExt: () => mimeToExt,
40
- unitsObj: () => unitsObj
41
- });
42
- module.exports = __toCommonJS(index_exports);
43
-
44
- // src/fs/index.ts
45
- var import_child_process = require("child_process");
46
- var import_fs = __toESM(require("fs"), 1);
47
- var import_promises = __toESM(require("fs/promises"), 1);
48
- var import_node_os = require("os");
49
- var import_path = require("path");
50
- var dotenv = __toESM(require("dotenv"), 1);
51
- var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
52
- var import_sharp = __toESM(require("sharp"), 1);
53
-
54
- // src/utils/index.ts
55
- var UtilsService = class {
56
- static {
57
- __name(this, "UtilsService");
58
- }
59
- chunkArray(arr, maxChunkLength) {
60
- const chunks = Array.of();
61
- let currentChunkLength = 0;
62
- let currentChunk = Array.of();
63
- for (const [index, val] of arr.entries()) {
64
- if (val.length + currentChunkLength >= maxChunkLength) {
65
- if (currentChunk.length) {
66
- chunks.push(currentChunk);
67
- }
68
- currentChunkLength = val.length;
69
- currentChunk = [val];
70
- } else {
71
- currentChunk.push(val);
72
- currentChunkLength += val.length + 1;
73
- }
74
- if (arr.length === index + 1) {
75
- chunks.push(currentChunk);
76
- }
77
- }
78
- return chunks.length ? chunks : [arr];
79
- }
80
- b64ToBlob(b64Data) {
81
- {
82
- const sliceSize = 512;
83
- const typeMatch = /^data:((?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*);base64,(.+)$/i.exec(
84
- b64Data
85
- );
86
- if (!typeMatch) {
87
- throw new Error(`${b64Data} is not a valid data Url`);
88
- }
89
- const type = typeMatch[1];
90
- const base64Data = typeMatch?.[2] ?? "";
91
- const byteCharacters = Buffer.from(base64Data, "base64").toString(
92
- "binary"
93
- );
94
- const byteArrays = Array.of();
95
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
96
- const slice = byteCharacters.slice(offset, offset + sliceSize);
97
- const byteNumbers = new Array(slice.length);
98
- for (let i = 0; i < slice.length; i++) {
99
- byteNumbers[i] = slice.charCodeAt(i);
100
- }
101
- const byteArray = new Uint8Array(byteNumbers);
102
- byteArrays.push(byteArray);
103
- }
104
- const blob = new Blob(byteArrays, { type });
105
- return blob;
106
- }
107
- }
108
- arrToArrOfArrs = /* @__PURE__ */ __name(({
109
- arrToFragment = Array.of(),
110
- arrOfArrsAggregator = Array.of(),
111
- interval
112
- }) => new Promise(
113
- (resolve2, _reject) => resolve2(
114
- ((interval2) => {
115
- for (let i = 0; i <= arrToFragment.length; i++) {
116
- if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
117
- let segment = arrToFragment.slice(i, i + interval2);
118
- arrOfArrsAggregator.push(segment);
119
- }
120
- }
121
- })(interval)
122
- )
123
- ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
124
- extractTuple(obj, props) {
125
- return [props, obj[props]];
126
- }
127
- sort(obj, order) {
128
- return Object.fromEntries(
129
- Object.entries(obj).sort(
130
- ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
131
- )
132
- );
133
- }
134
- excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
135
- const resolve2 = Object.fromEntries(
136
- Object.entries(obj).map(([key, val]) => {
137
- if (props.includes(key)) {
138
- return ["omit", "omit"];
139
- } else return [key, val];
140
- }).filter(([t, _v]) => /omit/.test(t) === false)
141
- );
142
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
143
- }, "excludeTargeted");
144
- includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
145
- const resolve2 = Object.fromEntries(
146
- props.map((val) => this.extractTuple(obj, val))
147
- );
148
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
149
- }, "includeTargeted");
150
- countsSorter = /* @__PURE__ */ __name((counter, keySort = "ASC", valSort = "DESC") => Object.fromEntries(
151
- Array.from(Object.entries(counter)).sort(
152
- ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
153
- ).sort(([aStr, aNum], [bStr, bNum]) => {
154
- if (typeof (aNum && bNum) === "number") {
155
- return valSort === "ASC" ? aNum - bNum : bNum - aNum;
156
- } else if (typeof (aNum && bNum) === "string") {
157
- return valSort === "ASC" ? aStr.localeCompare(bStr) - bStr.localeCompare(aStr) : bStr.localeCompare(aStr) - aStr.localeCompare(bStr);
158
- } else
159
- throw new Error(
160
- "only Record<string, string> and Record<string,number> types supported"
161
- );
162
- })
163
- ), "countsSorter");
164
- range(from, to) {
165
- const values = Array.of();
166
- for (let i = from; i < to; i++) {
167
- values.push(i);
168
- }
169
- return values;
170
- }
171
- isPrimeNumber = /* @__PURE__ */ __name((n) => {
172
- for (let i = 2; n > i; i++) {
173
- if (n % i === 0) {
174
- return false;
175
- }
176
- }
177
- return n > 1;
178
- }, "isPrimeNumber");
179
- acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
180
- };
181
-
182
- // src/url/index.ts
183
- var UrlService = class extends UtilsService {
184
- static {
185
- __name(this, "UrlService");
186
- }
187
- URL_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
188
- parseUrl(url) {
189
- const parsed = this.URL_REGEX.exec(url);
190
- if (parsed) {
191
- return {
192
- href: parsed[0],
193
- protocol: parsed[1] ?? "",
194
- baseUrl: `${parsed[1]}${parsed[3]}`,
195
- host: parsed[4] ?? "",
196
- pathname: parsed[5] ?? "",
197
- search: parsed[6] ?? "",
198
- hash: parsed[8] ?? ""
199
- };
200
- } else return null;
201
- }
202
- };
203
-
204
- // src/mime/index.ts
205
- var extMimeMap = {
206
- aac: ["audio/aac"],
207
- abw: ["application/x-abiword"],
208
- aces: ["image/aces"],
209
- apng: ["image/apng"],
210
- arc: ["application/x-freearc"],
211
- avci: ["image/avci"],
212
- avif: ["image/avif"],
213
- avi: ["video/x-msvideo"],
214
- azw: ["application/vnd.amazon.ebook"],
215
- bin: ["application/octet-stream", "multipart/voice-message"],
216
- bmp: ["image/bmp"],
217
- bz: ["application/x-bzip"],
218
- bz2: ["application/x-bzip2"],
219
- cda: ["application/x-cdf"],
220
- cjs: ["application/node", "text/javascript"],
221
- csh: ["application/x-csh"],
222
- css: ["text/css"],
223
- csv: ["text/csv"],
224
- doc: ["application/msword"],
225
- docx: [
226
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
227
- ],
228
- dpx: ["image/dpx"],
229
- emf: ["image/emf"],
230
- eot: ["application/vnd.ms-fontobject"],
231
- epub: ["application/epub+zip"],
232
- gif: ["image/gif"],
233
- glb: ["model/gltf-binary"],
234
- gltf: ["model/gltf+json"],
235
- gz: ["application/gzip", "application/x-gzip"],
236
- hjif: ["haptics/hjif"],
237
- hmpg: ["haptics/hmpg"],
238
- htm: ["text/html"],
239
- html: ["text/html"],
240
- ico: ["image/vnd.microsoft.icon"],
241
- ics: ["text/calendar"],
242
- ivs: ["haptics/ivs"],
243
- ivt: ["haptics/ivs"],
244
- jar: ["application/java-archive"],
245
- jpeg: ["image/jpeg"],
246
- jpg: ["image/jpeg"],
247
- js: ["application/node", "text/javascript"],
248
- json: ["application/json"],
249
- jsonld: ["application/ld+json"],
250
- ktx: ["image/ktx"],
251
- ktx2: ["image/ktx2"],
252
- m3u8: ["application/vnd.apple.mpegurl"],
253
- m4a: ["audio/mp4"],
254
- m4v: ["video/mp4"],
255
- md: ["text/markdown"],
256
- mdx: ["application/x-mdx"],
257
- mid: ["audio/midi"],
258
- midi: ["audio/x-midi"],
259
- mjs: ["text/javascript"],
260
- mp3: ["audio/mpeg"],
261
- mp4: ["video/mp4"],
262
- mpeg: ["video/mpeg"],
263
- mpkg: ["application/vnd.apple.installer+xml"],
264
- ndjson: ["application/x-ndjson"],
265
- node: ["application/node", "text/javascript"],
266
- obj: ["model/obj", "application/octet-stream", "text/plain"],
267
- odp: ["application/vnd.oasis.opendocument.presentation"],
268
- ods: ["application/vnd.oasis.opendocument.spreadsheet"],
269
- odt: ["application/vnd.oasis.opendocument.text"],
270
- oga: ["audio/ogg"],
271
- ogg: ["audio/ogg"],
272
- ogv: ["video/ogg"],
273
- ogx: ["application/ogg"],
274
- opus: ["audio/ogg"],
275
- otf: ["font/otf"],
276
- png: ["image/png"],
277
- pdf: ["application/pdf"],
278
- php: ["application/x-httpd-php"],
279
- pkpass: ["application/vnd.apple.pkpass"],
280
- ppt: ["application/vnd.ms-powerpoint"],
281
- pptx: [
282
- "application/vnd.openxmlformats-officedocument.presentationml.presentation"
283
- ],
284
- py: ["text/x-python"],
285
- pyc: ["application/x-python-code"],
286
- rar: ["application/vnd.rar"],
287
- rs: ["text/rust"],
288
- rtf: ["application/rtf"],
289
- sh: ["application/x-sh"],
290
- sql: ["application/sql"],
291
- sse: ["text/event-stream"],
292
- svg: ["image/svg+xml"],
293
- tar: ["application/x-tar"],
294
- tif: ["image/tiff"],
295
- tiff: ["image/tiff"],
296
- toml: ["application/toml"],
297
- ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
298
- ttf: ["application/font-sfnt", "font/ttf"],
299
- txt: ["text/plain"],
300
- usdz: ["model/vnd.usdz+zip"],
301
- vsd: ["application/vnd.visio"],
302
- vtt: ["text/vtt"],
303
- wasm: ["application/wasm"],
304
- wav: ["audio/wav"],
305
- weba: ["video/webm"],
306
- webp: ["image/webp"],
307
- woff: ["font/woff"],
308
- woff2: ["font/woff2"],
309
- xhtml: ["application/xhtml+xml"],
310
- xls: ["application/vnd.ms-excel"],
311
- xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
312
- xml: ["application/xml"],
313
- xul: ["application/vnd.mozilla.xul+xml"],
314
- yaml: ["application/yaml"],
315
- yml: ["application/yaml"],
316
- zip: ["application/zip", "application/x-zip-compressed"],
317
- "3gp": ["video/3gpp"],
318
- "3g2": ["video/3gpp2"],
319
- "7z": ["application/x-7z-compressed"]
320
- };
321
- var mimeToExt = {
322
- "application/epub+zip": ["epub"],
323
- "application/font-sfnt": ["ttf"],
324
- "application/gzip": ["gz"],
325
- "application/java-archive": ["jar"],
326
- "application/json": ["json"],
327
- "application/ld+json": ["jsonld"],
328
- "application/msword": ["doc"],
329
- "application/node": ["node", "js"],
330
- "application/octet-stream": ["bin", "obj"],
331
- "application/ogg": ["ogx"],
332
- "application/pdf": ["pdf"],
333
- "application/rtf": ["rtf"],
334
- "application/sql": ["sql"],
335
- "application/toml": ["toml"],
336
- "application/vnd.amazon.ebook": ["azw"],
337
- "application/vnd.apple.installer+xml": ["mpkg"],
338
- "application/vnd.apple.mpegurl": ["m3u8"],
339
- "application/vnd.apple.pkpass": ["pkpass"],
340
- "application/vnd.mozilla.xul+xml": ["xul"],
341
- "application/vnd.ms-excel": ["xls"],
342
- "application/vnd.ms-fontobject": ["eot"],
343
- "application/vnd.ms-powerpoint": ["ppt"],
344
- "application/vnd.oasis.opendocument.presentation": ["odp"],
345
- "application/vnd.oasis.opendocument.spreadsheet": ["ods"],
346
- "application/vnd.oasis.opendocument.text": ["odt"],
347
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
348
- "pptx"
349
- ],
350
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"],
351
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
352
- "docx"
353
- ],
354
- "application/vnd.rar": ["rar"],
355
- "application/vnd.visio": ["vsd"],
356
- "application/wasm": ["wasm"],
357
- "application/x-7z-compressed": ["7z"],
358
- "application/x-abiword": ["abw"],
359
- "application/x-bzip": ["bz"],
360
- "application/x-bzip2": ["bz2"],
361
- "application/x-cdf": ["cda"],
362
- "application/x-csh": ["csh"],
363
- "application/x-freearc": ["arc"],
364
- "application/x-gzip": ["gz"],
365
- "application/x-httpd-php": ["php"],
366
- "application/x-mdx": ["mdx"],
367
- "application/x-ndjson": ["ndjson"],
368
- "application/x-python-code": ["pyc"],
369
- "application/x-sh": ["sh"],
370
- "application/x-tar": ["tar"],
371
- "application/x-zip-compressed": ["zip"],
372
- "application/xhtml+xml": ["xhtml"],
373
- "application/xml": ["xml"],
374
- "application/yaml": ["yml", "yaml"],
375
- "application/zip": ["zip"],
376
- "audio/aac": ["aac"],
377
- "audio/midi": ["mid"],
378
- "audio/mp4": ["m4a"],
379
- "audio/mpeg": ["mp3"],
380
- "audio/ogg": ["opus", "ogg", "oga"],
381
- "audio/wav": ["wav"],
382
- "audio/x-midi": ["midi"],
383
- "font/otf": ["otf"],
384
- "font/ttf": ["ttf"],
385
- "font/woff": ["woff"],
386
- "font/woff2": ["woff2"],
387
- "haptics/hjif": ["hjif"],
388
- "haptics/hmpg": ["hmpg"],
389
- "haptics/ivs": ["ivs", "ivt"],
390
- "image/aces": ["aces"],
391
- "image/apng": ["apng"],
392
- "image/avci": ["avci"],
393
- "image/avif": ["avif"],
394
- "image/bmp": ["bmp"],
395
- "image/dpx": ["dpx"],
396
- "image/emf": ["emf"],
397
- "image/gif": ["gif"],
398
- "image/jpeg": ["jpg", "jpeg"],
399
- "image/ktx": ["ktx"],
400
- "image/ktx2": ["ktx2"],
401
- "image/png": ["png"],
402
- "image/svg+xml": ["svg"],
403
- "image/tiff": ["tiff", "tif"],
404
- "image/vnd.microsoft.icon": ["ico"],
405
- "image/webp": ["webp"],
406
- "model/gltf-binary": ["glb"],
407
- "model/gltf+json": ["gltf"],
408
- "model/obj": ["obj"],
409
- "model/vnd.usdz+zip": ["usdz"],
410
- "multipart/voice-message": ["bin"],
411
- "text/calendar": ["ics"],
412
- "text/css": ["css"],
413
- "text/csv": ["csv"],
414
- "text/event-stream": ["sse", "ts", "rs", "py", "txt"],
415
- "text/html": ["html", "htm"],
416
- "text/javascript": ["cjs", "js", "mjs"],
417
- "text/markdown": ["md"],
418
- "text/plain": ["txt"],
419
- "text/rust": ["rs"],
420
- "text/typescript": ["ts"],
421
- "text/vtt": ["vtt"],
422
- "text/x-python": ["py"],
423
- "video/3gpp": ["3gp"],
424
- "video/3gpp2": ["3g2"],
425
- "video/mp2t": ["ts"],
426
- "video/mp4": ["mp4", "m4v"],
427
- "video/mpeg": ["mpeg"],
428
- "video/ogg": ["ogv"],
429
- "video/vnd.dlna.mpeg-tts": ["ts"],
430
- "video/webm": ["weba"],
431
- "video/x-msvideo": ["avi"]
432
- };
433
- var MimeService = class extends UrlService {
434
- static {
435
- __name(this, "MimeService");
436
- }
437
- constructor() {
438
- super();
439
- }
440
- mimeTypeObj = extMimeMap;
441
- toExtObj = mimeToExt;
442
- compareMimeToExt(p = "mime") {
443
- let a = {};
444
- if (p === "mime") {
445
- for (const [_key, vals] of Object.entries(extMimeMap)) {
446
- for (const val of vals) {
447
- a[val] = (a[val] ?? 0) + 1;
448
- }
449
- }
450
- for (const [key, _val] of Object.entries(mimeToExt)) {
451
- a[key] = (a[key] ?? 0) + 1;
452
- }
453
- return Object.fromEntries(
454
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
455
- );
456
- } else {
457
- for (const [_key, vals] of Object.entries(mimeToExt)) {
458
- for (const val of vals) {
459
- a[val] = (a[val] ?? 0) + 1;
460
- }
461
- }
462
- for (const [key, _val] of Object.entries(extMimeMap)) {
463
- a[key] = (a[key] ?? 0) + 1;
464
- }
465
- return Object.fromEntries(
466
- Object.entries(a).sort(([_a, aa], [_b, bb]) => bb - aa)
467
- );
468
- }
469
- }
470
- mimeToExt(mime) {
471
- const extensions = this.toExtObj[mime];
472
- if (extensions.length === 1) return extensions[0];
473
- if (extensions.length === 2) {
474
- return extensions[0];
475
- }
476
- if (extensions.length === 3) {
477
- if (mime === "audio/ogg") return "ogg";
478
- return extensions[0];
479
- }
480
- if (extensions.length === 5) {
481
- return "sse";
482
- }
483
- return extensions[0];
484
- }
485
- assetType(url) {
486
- const parsed = this.parseUrl(url);
487
- if (!parsed) return void 0;
488
- const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
489
- return ext && ext in this.mimeTypeObj ? ext : void 0;
490
- }
491
- getMimes(ext) {
492
- return this.mimeTypeObj[ext];
493
- }
494
- getMimeFor(ext, opts) {
495
- const mimes = this.getMimes(ext);
496
- if (mimes.length === 1) return mimes[0];
497
- if (opts?.type) {
498
- const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
499
- return found ?? mimes[0];
500
- }
501
- return mimes[0];
502
- }
503
- isMimeFor(ext, mime) {
504
- return this.getMimes(ext).find((s) => s === mime);
505
- }
506
- getMimeTypeForPath(path, opts) {
507
- const ext = this.assetType(path);
508
- if (!ext) return "application/octet-stream";
509
- return this.getMimeFor(ext, opts);
510
- }
511
- };
512
-
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
- }
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)());
542
- }
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;
590
- }
591
- }
592
- }
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
627
- );
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);
706
- }
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;
720
- }
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
- );
735
- }
736
- }
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);
1001
- }
1002
- }
1003
- findBox(buffer, type, start = 0, end = buffer.length) {
1004
- let pos = start;
1005
- while (pos < end) {
1006
- let boxSize = buffer.readUInt32BE(pos);
1007
- let boxType = buffer.toString("ascii", pos + 4, pos + 8);
1008
- let hdrSize = 8;
1009
- if (boxSize === 1) {
1010
- boxSize = Number(buffer.readBigUInt64BE(pos + 8));
1011
- hdrSize = 16;
1012
- } else if (boxSize === 0) {
1013
- boxSize = end - pos;
1014
- }
1015
- if (boxType === type) {
1016
- return { pos: pos + hdrSize, size: boxSize - hdrSize };
1017
- }
1018
- pos += boxSize;
1019
- }
1020
- return null;
1021
- }
1022
- async getImageSpecs(filePath) {
1023
- const buffer = await this.fileToBufferAsync(filePath);
1024
- 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
- if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
1026
- throw new Error("IHDR Chunk of png not found or incorrect.");
1027
- }
1028
- const colorType = buffer[25];
1029
- let colorSpace;
1030
- let hasAlpha = false;
1031
- switch (colorType) {
1032
- case 0:
1033
- colorSpace = "grayscale";
1034
- break;
1035
- case 2:
1036
- colorSpace = "rgb";
1037
- break;
1038
- case 3:
1039
- colorSpace = "indexed";
1040
- break;
1041
- case 4:
1042
- colorSpace = "grayscale-alpha";
1043
- hasAlpha = true;
1044
- break;
1045
- case 6:
1046
- colorSpace = "rgba";
1047
- hasAlpha = true;
1048
- break;
1049
- default:
1050
- colorSpace = "unknown";
1051
- }
1052
- const width = buffer.readUInt32BE(16);
1053
- const height = buffer.readUInt32BE(20);
1054
- let frames = 1;
1055
- let animated = false;
1056
- let iccProfile = null;
1057
- let exifDateTimeOriginal = null;
1058
- let orientation = null;
1059
- let pos = 33;
1060
- while (pos < buffer.length - 12) {
1061
- const chunkLen = buffer.readUInt32BE(pos);
1062
- const chunkType = buffer.toString("ascii", pos + 4, pos + 8);
1063
- const chunkData = pos + 8;
1064
- if (chunkType === "acTL") {
1065
- animated = true;
1066
- frames = buffer.readUInt32BE(chunkData);
1067
- } else if (chunkType === "iCCP") {
1068
- const nameEnd = buffer.indexOf(0, chunkData);
1069
- const profileName = buffer.toString("ascii", chunkData, nameEnd);
1070
- iccProfile = profileName || "embedded";
1071
- } else if (chunkType === "tIME") {
1072
- const month = buffer?.[chunkData + 2], day = buffer?.[chunkData + 3], hour = buffer?.[chunkData + 4], minute = buffer?.[chunkData + 5], second = buffer?.[chunkData + 6];
1073
- if (typeof month !== "undefined" && typeof day !== "undefined" && typeof hour !== "undefined" && typeof minute !== "undefined" && typeof second !== "undefined") {
1074
- const year = buffer.readUInt16BE(chunkData);
1075
- exifDateTimeOriginal = `${year}:${month.toString().padStart(2, "0")}:${day.toString().padStart(2, "0")} ${hour.toString().padStart(2, "0")}:${minute.toString().padStart(2, "0")}:${second.toString().padStart(2, "0")}`;
1076
- }
1077
- } else if (chunkType === "IDAT") {
1078
- break;
1079
- }
1080
- pos += 12 + chunkLen;
1081
- }
1082
- return {
1083
- width,
1084
- height,
1085
- format: "png",
1086
- frames,
1087
- animated,
1088
- hasAlpha,
1089
- orientation,
1090
- aspectRatio: width / height,
1091
- colorSpace,
1092
- iccProfile,
1093
- exifDateTimeOriginal
1094
- };
1095
- }
1096
- if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
1097
- let pos = 2, colorSpace = "unknown", hasAlpha = false, width = 0, height = 0, iccProfile = null, orientation = null, exifDateTimeOriginal = null;
1098
- while (pos < buffer.length - 10) {
1099
- if (buffer[pos] !== 255) {
1100
- throw new Error("Invalid JPEG file");
1101
- }
1102
- const marker = buffer[pos + 1];
1103
- if (marker === 218) break;
1104
- const segmentSize = buffer.readUInt16BE(pos + 2);
1105
- if (!marker) {
1106
- throw new Error("no marker for jpeg");
1107
- }
1108
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
1109
- const numComponents = buffer[pos + 4];
1110
- switch (numComponents) {
1111
- case 1:
1112
- colorSpace = "grayscale";
1113
- break;
1114
- case 3:
1115
- colorSpace = "ycbcr";
1116
- break;
1117
- // Most common for RGB JPEGs (stored as YCbCr)
1118
- case 4:
1119
- colorSpace = "ycck";
1120
- break;
1121
- // YCCK for CMYK with alpha-like, but no true alpha
1122
- default:
1123
- colorSpace = "unknown";
1124
- }
1125
- width = buffer.readUInt16BE(pos + 7);
1126
- height = buffer.readUInt16BE(pos + 5);
1127
- } else if (marker === 225) {
1128
- const { orientation: ori, dateTimeOriginal } = this.parseExif(
1129
- buffer,
1130
- pos,
1131
- segmentSize
1132
- );
1133
- orientation = ori;
1134
- exifDateTimeOriginal = dateTimeOriginal;
1135
- } else if (marker === 226) {
1136
- const iccHeader = buffer.toString("ascii", pos + 4, pos + 18);
1137
- if (iccHeader.startsWith("ICC_PROFILE")) {
1138
- iccProfile = "embedded";
1139
- }
1140
- }
1141
- pos += segmentSize + 2;
1142
- }
1143
- if (width === 0) throw new Error("No dimensions found in JPEG file");
1144
- return {
1145
- width,
1146
- height,
1147
- format: "jpeg",
1148
- frames: 1,
1149
- animated: false,
1150
- // JPEG not animated
1151
- hasAlpha,
1152
- orientation,
1153
- aspectRatio: width / height,
1154
- colorSpace,
1155
- iccProfile,
1156
- exifDateTimeOriginal
1157
- };
1158
- }
1159
- const gifHeader = buffer.toString("ascii", 0, 6);
1160
- if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
1161
- const width = buffer.readUInt16LE(6), height = buffer.readUInt16LE(8);
1162
- let frames = 0;
1163
- let pos = 13;
1164
- let bufTen = buffer?.[10];
1165
- if (typeof bufTen === "undefined") {
1166
- pos = 13;
1167
- frames = 0;
1168
- } else if (bufTen & 128) pos += 3 << (bufTen & 7) + 1;
1169
- while (pos < buffer.length) {
1170
- if (buffer[pos] === 33) {
1171
- pos += 2;
1172
- let subSize = buffer?.[pos];
1173
- while (subSize && subSize > 0) {
1174
- pos += subSize + 1;
1175
- subSize = buffer?.[pos];
1176
- }
1177
- pos++;
1178
- } else if (buffer?.[pos] && buffer?.[pos] === 44) {
1179
- frames++;
1180
- pos += 10;
1181
- let b = buffer?.[pos - 1];
1182
- if (typeof b !== "undefined" && b & 128)
1183
- pos += 3 << (b & 7) + 1;
1184
- pos++;
1185
- let dataSize = buffer?.[pos];
1186
- while (dataSize && dataSize > 0) {
1187
- pos += dataSize + 1;
1188
- dataSize = buffer[pos];
1189
- }
1190
- pos++;
1191
- } else if (buffer[pos] === 59) {
1192
- break;
1193
- } else {
1194
- pos++;
1195
- }
1196
- }
1197
- return {
1198
- width,
1199
- height,
1200
- format: "gif",
1201
- frames,
1202
- animated: frames > 1,
1203
- hasAlpha: null,
1204
- // GIF transparency is per-pixel binary, not full alpha; set null or true if transparent color exists, but complex
1205
- orientation: null,
1206
- // No orientation in GIF
1207
- aspectRatio: width / height,
1208
- colorSpace: "indexed",
1209
- iccProfile: null,
1210
- // No ICC in GIF
1211
- exifDateTimeOriginal: null
1212
- // No EXIF in GIF
1213
- };
1214
- }
1215
- if (buffer.length >= 26 && buffer?.[0] === 66 && buffer?.[1] === 77) {
1216
- const width = buffer.readInt32LE(18);
1217
- const height = Math.abs(buffer.readInt32LE(22));
1218
- const bitDepth = buffer.readUInt16LE(28);
1219
- let colorSpace = bitDepth <= 8 ? "indexed" : "rgb";
1220
- return {
1221
- width,
1222
- height,
1223
- format: "bmp",
1224
- frames: 1,
1225
- animated: false,
1226
- hasAlpha: null,
1227
- // Some BMP have alpha in 32bpp, check if bitDepth===32 && compression===3 (bitfields with alpha)
1228
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
1229
- // Negative height means top-down (orientation 1), positive bottom-up (like 6, but simplified)
1230
- aspectRatio: width / height,
1231
- colorSpace,
1232
- iccProfile: null,
1233
- // Rare in BMP
1234
- exifDateTimeOriginal: null
1235
- };
1236
- }
1237
- if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
1238
- const chunkType = buffer.toString("ascii", 12, 16);
1239
- let colorSpace = "unknown";
1240
- let hasAlpha = false;
1241
- let width = 0;
1242
- let height = 0;
1243
- let frames = 1;
1244
- let animated = false;
1245
- let iccProfile = null;
1246
- if (chunkType === "VP8X") {
1247
- const flags = buffer?.[20];
1248
- colorSpace = flags ? flags & 2 ? "rgba" : "rgb" : "unknown";
1249
- hasAlpha = flags ? !!(flags & 2) : false;
1250
- animated = flags ? !!(flags & 1) : false;
1251
- let widthSubtractOne = 0;
1252
- let heightSubtractOne = 0;
1253
- if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
1254
- widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
1255
- }
1256
- if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
1257
- heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
1258
- }
1259
- width = widthSubtractOne + 1;
1260
- height = heightSubtractOne + 1;
1261
- if (animated) {
1262
- let pos = 30;
1263
- frames = 0;
1264
- while (pos < buffer.length - 8) {
1265
- const subChunkType = buffer.toString("ascii", pos, pos + 4);
1266
- const subChunkSize = buffer.readUInt32LE(pos + 4);
1267
- if (subChunkType === "ICCP") {
1268
- iccProfile = "embedded";
1269
- } else if (subChunkType === "ANMF") {
1270
- frames++;
1271
- }
1272
- pos += 8 + subChunkSize + subChunkSize % 2;
1273
- }
1274
- }
1275
- } else if (chunkType === "VP8 ") {
1276
- colorSpace = "rgb";
1277
- hasAlpha = false;
1278
- const dataStart = 20;
1279
- if (buffer?.[dataStart + 3] !== 157 || buffer?.[dataStart + 4] !== 1 || buffer?.[dataStart + 5] !== 42) {
1280
- throw new Error("Invalid VP8 keyframe");
1281
- }
1282
- width = buffer.readUInt16LE(dataStart + 6) & 16383;
1283
- height = buffer.readUInt16LE(dataStart + 8) & 16383;
1284
- } else if (chunkType === "VP8L") {
1285
- const dataStart = 20;
1286
- if (buffer?.[dataStart] !== 47) {
1287
- throw new Error("Invalid VP8L signature");
1288
- }
1289
- const bits = buffer.readUInt32LE(dataStart + 1);
1290
- if (bits >>> 29 !== 0) {
1291
- throw new Error("Invalid VP8L version");
1292
- }
1293
- colorSpace = bits & 1 << 8 ? "rgba" : "rgb";
1294
- hasAlpha = !!(bits & 1 << 8);
1295
- width = 1 + (bits & 16383);
1296
- height = 1 + (bits >> 14 & 16383);
1297
- } else {
1298
- throw new Error("Unsupported WebP chunk");
1299
- }
1300
- return {
1301
- width,
1302
- height,
1303
- format: "webp",
1304
- frames,
1305
- animated,
1306
- hasAlpha,
1307
- orientation: null,
1308
- // No standard orientation in WebP
1309
- aspectRatio: width / height,
1310
- colorSpace,
1311
- iccProfile,
1312
- exifDateTimeOriginal: null
1313
- // Can have EXIF chunk, but rare; add if needed
1314
- };
1315
- }
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";
1348
- }
1349
- }
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
- }
1358
- }
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);
1367
- }
1368
- }
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
- };
1385
- }
1386
- throw new Error("Unsupported image format or invalid file");
1387
- }
1388
- /**
1389
- *
1390
- * @access package-private
1391
- *
1392
- * work in progress, for internal package maintainer use only
1393
- */
1394
- // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
1395
- // https://www.npmjs.com/package/fluent-ffmpeg
1396
- // https://www.npmjs.com/package/@types/fluent-ffmpeg
1397
- async imageTransform({
1398
- format,
1399
- target,
1400
- quality = 80,
1401
- tint,
1402
- resize
1403
- }) {
1404
- if (tint && !resize) {
1405
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
1406
- } else if (!tint && resize) {
1407
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1408
- } else if (tint && resize) {
1409
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1410
- } else {
1411
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
1412
- }
1413
- }
1414
- /**
1415
- * Write data to a file in the system's tmp directory
1416
- * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1417
- * @param data The data to write
1418
- * @param options Optional write stream options
1419
- * @returns The full path to the written file
1420
- * @example
1421
- * ```ts
1422
- * const fs = new Fs(process.cwd());
1423
- * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1424
- * // Or with a subdirectory:
1425
- * fs.writeTmp("img-probe/output.png", imageBuffer);
1426
- * ```
1427
- */
1428
- writeTmp(filename, data, options) {
1429
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1430
- Promise.resolve(this.withWs(fullPath, data, options));
1431
- }
1432
- /**
1433
- * Read a file from the tmp directory
1434
- * @param filename The filename to read (can include subdirectories)
1435
- * @returns Buffer containing the file data
1436
- * @example
1437
- * ```ts
1438
- * const fs = new Fs(process.cwd());
1439
- * const data = fs.readTmp("session-data.json");
1440
- * const parsed = JSON.parse(data.toString("utf-8"));
1441
- * ```
1442
- */
1443
- readTmp(filename) {
1444
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1445
- if (!this.exists(fullPath)) {
1446
- throw new Error(`Tmp file not found: ${filename}`);
1447
- }
1448
- return this.fileToBuffer(fullPath);
1449
- }
1450
- /**
1451
- * Scan the tmp directory for files matching a pattern
1452
- * @param pattern Optional pattern to filter files (e.g., "img-probe")
1453
- * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1454
- * @returns Array of matching file paths relative to tmp directory
1455
- * @example
1456
- * ```ts
1457
- * const fs = new Fs(process.cwd());
1458
- * // Get all img-probe files
1459
- * const imgFiles = fs.scanTmp("img-probe");
1460
- * // Get all files in tmp (non-recursive)
1461
- * const allFiles = fs.scanTmp();
1462
- * ```
1463
- */
1464
- scanTmp(pattern, options = {
1465
- recursive: false,
1466
- withFileTypes: false,
1467
- encoding: "utf-8"
1468
- }) {
1469
- const dirs = (0, import_path.resolve)(this.tmpDir);
1470
- const tmpContents = this.readDir(dirs, options);
1471
- if (!pattern) {
1472
- return tmpContents;
1473
- }
1474
- if (typeof pattern === "string") {
1475
- return tmpContents.filter((t) => t.includes(pattern));
1476
- }
1477
- return tmpContents.filter((path) => {
1478
- return pattern.test(path);
1479
- });
1480
- }
1481
- /**
1482
- * Extract specific files from tmp directory to a target location
1483
- * @param pattern Pattern to match files (e.g., "img-probe")
1484
- * @param targetDir Target directory to extract files to
1485
- * @param options Options for extraction behavior
1486
- * @returns Array of extracted file paths
1487
- * @example
1488
- * ```ts
1489
- * const fs = new Fs(process.cwd());
1490
- * // Extract all img-probe files to ./output
1491
- * const extracted = fs.extractFromTmp("img-probe", "./output");
1492
- * // Extract with custom behavior
1493
- * fs.extractFromTmp("session-", "./sessions", {
1494
- * preserveStructure: true,
1495
- * cleanupAfter: true
1496
- * });
1497
- * ```
1498
- */
1499
- extractFromTmp(pattern, targetDir, options) {
1500
- const {
1501
- preserveStructure = false,
1502
- cleanupAfter = false,
1503
- overwrite = true
1504
- } = options ?? {};
1505
- const matchingFiles = this.scanTmp(pattern);
1506
- const extracted = [];
1507
- for (const file of matchingFiles) {
1508
- const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1509
- const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1510
- if (!lastSegment) continue;
1511
- const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1512
- if (this.exists(targetPath) && !overwrite) {
1513
- console.warn(`Skipping existing file: ${targetPath}`);
1514
- continue;
1515
- }
1516
- const data = this.fileToBuffer(sourcePath);
1517
- this.withWs(targetPath, data);
1518
- extracted.push(targetPath);
1519
- if (cleanupAfter) {
1520
- this.rmFile(sourcePath);
1521
- }
1522
- }
1523
- return extracted;
1524
- }
1525
- /**
1526
- * Clean up tmp files matching a pattern
1527
- * @param pattern Pattern to match files for deletion
1528
- * @param maxAge Optional max age in milliseconds (only delete files older than this)
1529
- * @returns Number of files removed
1530
- * @example
1531
- * ```ts
1532
- * const fs = new Fs(process.cwd());
1533
- * // Remove all img-probe files
1534
- * fs.cleanupTmp("img-probe");
1535
- * // Remove session files older than 1 hour
1536
- * fs.cleanupTmp("session-", 60 * 60 * 1000);
1537
- * ```
1538
- */
1539
- cleanupTmp(pattern, maxAge) {
1540
- const matchingFiles = this.scanTmp(pattern);
1541
- let removed = 0;
1542
- for (const file of matchingFiles) {
1543
- const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1544
- try {
1545
- const stats = import_fs.default.statSync(fullPath);
1546
- if (maxAge) {
1547
- const age = Date.now() - stats.mtimeMs;
1548
- if (age < maxAge) {
1549
- continue;
1550
- }
1551
- }
1552
- if (stats.isDirectory()) {
1553
- this.rmDirSync(fullPath);
1554
- } else {
1555
- this.rmFile(fullPath);
1556
- }
1557
- removed++;
1558
- } catch (err) {
1559
- console.warn(`Failed to remove tmp file ${file}:`, err);
1560
- }
1561
- }
1562
- return removed;
1563
- }
1564
- rmTmpFile(filename) {
1565
- const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1566
- this.rmFile(tmpPath);
1567
- }
1568
- /**
1569
- * Generate a unique tmp filename with optional prefix
1570
- * @param prefix Optional prefix for the filename
1571
- * @param extension Optional file extension (without dot)
1572
- * @returns Unique filename
1573
- * @example
1574
- * ```ts
1575
- * const fs = new Fs(process.cwd());
1576
- * const filename = fs.uniqueTmpName("img-probe", "png");
1577
- * // Returns: "img-probe-1701234567890-a3b2c1.png"
1578
- * ```
1579
- */
1580
- uniqueTmpName(prefix, extension) {
1581
- const timestamp = Date.now();
1582
- const random = Math.random().toString(36).substring(2, 8);
1583
- const parts = [prefix ?? "tmp", timestamp, random].join("-");
1584
- return extension ? `${parts}.${extension}` : parts;
1585
- }
1586
- /**
1587
- * Async generator for cleaning tmp files with batched removal
1588
- * @param pattern Pattern to match files for deletion
1589
- * @param batchSize Number of files to remove per batch (default 10)
1590
- * @yields Progress information during cleanup
1591
- * @returns Final cleanup summary
1592
- * @example
1593
- * ```ts
1594
- * const fs = new Fs(process.cwd());
1595
- * // Clean up with progress tracking
1596
- * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1597
- * console.log(progress);
1598
- * }
1599
- * ```
1600
- */
1601
- async *cleanTmpGenerator(pattern, batchSize = 10) {
1602
- const files = this.scanTmp(pattern);
1603
- const batches = await this.arrToArrOfArrs({
1604
- arrToFragment: files,
1605
- arrOfArrsAggregator: [],
1606
- interval: batchSize
1607
- });
1608
- let totalRemoved = 0;
1609
- for (const [index, batch] of batches.entries()) {
1610
- yield {
1611
- action: "removing",
1612
- batch: [...batch],
1613
- batchNumber: index + 1,
1614
- totalBatches: batches.length,
1615
- totalFound: files.length,
1616
- removed: totalRemoved
1617
- };
1618
- for (const file of batch) {
1619
- this.rmTmpFile(file);
1620
- totalRemoved++;
1621
- }
1622
- yield {
1623
- action: "batch-complete",
1624
- batchNumber: index + 1,
1625
- batchSize: batch.length,
1626
- totalRemoved,
1627
- remaining: files.length - totalRemoved
1628
- };
1629
- }
1630
- return {
1631
- action: "complete",
1632
- totalRemoved,
1633
- totalBatches: batches.length,
1634
- pattern: pattern.toString()
1635
- };
1636
- }
1637
- };
1638
- // Annotate the CommonJS export names for ESM import in node:
1639
- 0 && (module.exports = {
1640
- Fs,
1641
- MimeService,
1642
- UrlService,
1643
- UtilsService,
1644
- extMimeMap,
1645
- mimeToExt,
1646
- unitsObj
1647
- });
1648
- //# sourceMappingURL=index.cjs.map