@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/fs/index.cjs DELETED
@@ -1,1630 +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/fs/index.ts
32
- var fs_exports = {};
33
- __export(fs_exports, {
34
- default: () => Fs
35
- });
36
- module.exports = __toCommonJS(fs_exports);
37
- var import_child_process = require("child_process");
38
- var import_fs = __toESM(require("fs"), 1);
39
- var import_promises = __toESM(require("fs/promises"), 1);
40
- var import_node_os = require("os");
41
- var import_path = require("path");
42
- var dotenv = __toESM(require("dotenv"), 1);
43
- var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
44
- var import_sharp = __toESM(require("sharp"), 1);
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
-
174
- // src/url/index.ts
175
- var UrlService = class extends UtilsService {
176
- static {
177
- __name(this, "UrlService");
178
- }
179
- URL_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
180
- parseUrl(url) {
181
- const parsed = this.URL_REGEX.exec(url);
182
- if (parsed) {
183
- return {
184
- href: parsed[0],
185
- protocol: parsed[1] ?? "",
186
- baseUrl: `${parsed[1]}${parsed[3]}`,
187
- host: parsed[4] ?? "",
188
- pathname: parsed[5] ?? "",
189
- search: parsed[6] ?? "",
190
- hash: parsed[8] ?? ""
191
- };
192
- } else return null;
193
- }
194
- };
195
-
196
- // src/mime/index.ts
197
- var extMimeMap = {
198
- aac: ["audio/aac"],
199
- abw: ["application/x-abiword"],
200
- aces: ["image/aces"],
201
- apng: ["image/apng"],
202
- arc: ["application/x-freearc"],
203
- avci: ["image/avci"],
204
- avif: ["image/avif"],
205
- avi: ["video/x-msvideo"],
206
- azw: ["application/vnd.amazon.ebook"],
207
- bin: ["application/octet-stream", "multipart/voice-message"],
208
- bmp: ["image/bmp"],
209
- bz: ["application/x-bzip"],
210
- bz2: ["application/x-bzip2"],
211
- cda: ["application/x-cdf"],
212
- cjs: ["application/node", "text/javascript"],
213
- csh: ["application/x-csh"],
214
- css: ["text/css"],
215
- csv: ["text/csv"],
216
- doc: ["application/msword"],
217
- docx: [
218
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
219
- ],
220
- dpx: ["image/dpx"],
221
- emf: ["image/emf"],
222
- eot: ["application/vnd.ms-fontobject"],
223
- epub: ["application/epub+zip"],
224
- gif: ["image/gif"],
225
- glb: ["model/gltf-binary"],
226
- gltf: ["model/gltf+json"],
227
- gz: ["application/gzip", "application/x-gzip"],
228
- hjif: ["haptics/hjif"],
229
- hmpg: ["haptics/hmpg"],
230
- htm: ["text/html"],
231
- html: ["text/html"],
232
- ico: ["image/vnd.microsoft.icon"],
233
- ics: ["text/calendar"],
234
- ivs: ["haptics/ivs"],
235
- ivt: ["haptics/ivs"],
236
- jar: ["application/java-archive"],
237
- jpeg: ["image/jpeg"],
238
- jpg: ["image/jpeg"],
239
- js: ["application/node", "text/javascript"],
240
- json: ["application/json"],
241
- jsonld: ["application/ld+json"],
242
- ktx: ["image/ktx"],
243
- ktx2: ["image/ktx2"],
244
- m3u8: ["application/vnd.apple.mpegurl"],
245
- m4a: ["audio/mp4"],
246
- m4v: ["video/mp4"],
247
- md: ["text/markdown"],
248
- mdx: ["application/x-mdx"],
249
- mid: ["audio/midi"],
250
- midi: ["audio/x-midi"],
251
- mjs: ["text/javascript"],
252
- mp3: ["audio/mpeg"],
253
- mp4: ["video/mp4"],
254
- mpeg: ["video/mpeg"],
255
- mpkg: ["application/vnd.apple.installer+xml"],
256
- ndjson: ["application/x-ndjson"],
257
- node: ["application/node", "text/javascript"],
258
- obj: ["model/obj", "application/octet-stream", "text/plain"],
259
- odp: ["application/vnd.oasis.opendocument.presentation"],
260
- ods: ["application/vnd.oasis.opendocument.spreadsheet"],
261
- odt: ["application/vnd.oasis.opendocument.text"],
262
- oga: ["audio/ogg"],
263
- ogg: ["audio/ogg"],
264
- ogv: ["video/ogg"],
265
- ogx: ["application/ogg"],
266
- opus: ["audio/ogg"],
267
- otf: ["font/otf"],
268
- png: ["image/png"],
269
- pdf: ["application/pdf"],
270
- php: ["application/x-httpd-php"],
271
- pkpass: ["application/vnd.apple.pkpass"],
272
- ppt: ["application/vnd.ms-powerpoint"],
273
- pptx: [
274
- "application/vnd.openxmlformats-officedocument.presentationml.presentation"
275
- ],
276
- py: ["text/x-python"],
277
- pyc: ["application/x-python-code"],
278
- rar: ["application/vnd.rar"],
279
- rs: ["text/rust"],
280
- rtf: ["application/rtf"],
281
- sh: ["application/x-sh"],
282
- sql: ["application/sql"],
283
- sse: ["text/event-stream"],
284
- svg: ["image/svg+xml"],
285
- tar: ["application/x-tar"],
286
- tif: ["image/tiff"],
287
- tiff: ["image/tiff"],
288
- toml: ["application/toml"],
289
- ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
290
- ttf: ["application/font-sfnt", "font/ttf"],
291
- txt: ["text/plain"],
292
- usdz: ["model/vnd.usdz+zip"],
293
- vsd: ["application/vnd.visio"],
294
- vtt: ["text/vtt"],
295
- wasm: ["application/wasm"],
296
- wav: ["audio/wav"],
297
- weba: ["video/webm"],
298
- webp: ["image/webp"],
299
- woff: ["font/woff"],
300
- woff2: ["font/woff2"],
301
- xhtml: ["application/xhtml+xml"],
302
- xls: ["application/vnd.ms-excel"],
303
- xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
304
- xml: ["application/xml"],
305
- xul: ["application/vnd.mozilla.xul+xml"],
306
- yaml: ["application/yaml"],
307
- yml: ["application/yaml"],
308
- zip: ["application/zip", "application/x-zip-compressed"],
309
- "3gp": ["video/3gpp"],
310
- "3g2": ["video/3gpp2"],
311
- "7z": ["application/x-7z-compressed"]
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
- };
425
- var MimeService = class extends UrlService {
426
- static {
427
- __name(this, "MimeService");
428
- }
429
- constructor() {
430
- super();
431
- }
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
- }
462
- mimeToExt(mime) {
463
- const extensions = this.toExtObj[mime];
464
- if (extensions.length === 1) return extensions[0];
465
- if (extensions.length === 2) {
466
- return extensions[0];
467
- }
468
- if (extensions.length === 3) {
469
- if (mime === "audio/ogg") return "ogg";
470
- return extensions[0];
471
- }
472
- if (extensions.length === 5) {
473
- return "sse";
474
- }
475
- return extensions[0];
476
- }
477
- assetType(url) {
478
- const parsed = this.parseUrl(url);
479
- if (!parsed) return void 0;
480
- const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
481
- return ext && ext in this.mimeTypeObj ? ext : void 0;
482
- }
483
- getMimes(ext) {
484
- return this.mimeTypeObj[ext];
485
- }
486
- getMimeFor(ext, opts) {
487
- const mimes = this.getMimes(ext);
488
- if (mimes.length === 1) return mimes[0];
489
- if (opts?.type) {
490
- const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
491
- return found ?? mimes[0];
492
- }
493
- return mimes[0];
494
- }
495
- isMimeFor(ext, mime) {
496
- return this.getMimes(ext).find((s) => s === mime);
497
- }
498
- getMimeTypeForPath(path, opts) {
499
- const ext = this.assetType(path);
500
- if (!ext) return "application/octet-stream";
501
- return this.getMimeFor(ext, opts);
502
- }
503
- };
504
-
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
- }
523
- 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)());
534
- }
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;
582
- }
583
- }
584
- }
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
619
- );
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);
698
- }
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;
712
- }
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
- );
727
- }
728
- }
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);
993
- }
994
- }
995
- findBox(buffer, type, start = 0, end = buffer.length) {
996
- let pos = start;
997
- while (pos < end) {
998
- let boxSize = buffer.readUInt32BE(pos);
999
- let boxType = buffer.toString("ascii", pos + 4, pos + 8);
1000
- let hdrSize = 8;
1001
- if (boxSize === 1) {
1002
- boxSize = Number(buffer.readBigUInt64BE(pos + 8));
1003
- hdrSize = 16;
1004
- } else if (boxSize === 0) {
1005
- boxSize = end - pos;
1006
- }
1007
- if (boxType === type) {
1008
- return { pos: pos + hdrSize, size: boxSize - hdrSize };
1009
- }
1010
- pos += boxSize;
1011
- }
1012
- return null;
1013
- }
1014
- async getImageSpecs(filePath) {
1015
- const buffer = await this.fileToBufferAsync(filePath);
1016
- 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
- if (buffer.readUint32BE(8) !== 13 || buffer?.[12] !== 73 || buffer?.[13] !== 72 || buffer?.[14] !== 68 || buffer?.[15] !== 82) {
1018
- throw new Error("IHDR Chunk of png not found or incorrect.");
1019
- }
1020
- const colorType = buffer[25];
1021
- let colorSpace;
1022
- let hasAlpha = false;
1023
- switch (colorType) {
1024
- case 0:
1025
- colorSpace = "grayscale";
1026
- break;
1027
- case 2:
1028
- colorSpace = "rgb";
1029
- break;
1030
- case 3:
1031
- colorSpace = "indexed";
1032
- break;
1033
- case 4:
1034
- colorSpace = "grayscale-alpha";
1035
- hasAlpha = true;
1036
- break;
1037
- case 6:
1038
- colorSpace = "rgba";
1039
- hasAlpha = true;
1040
- break;
1041
- default:
1042
- colorSpace = "unknown";
1043
- }
1044
- const width = buffer.readUInt32BE(16);
1045
- const height = buffer.readUInt32BE(20);
1046
- let frames = 1;
1047
- let animated = false;
1048
- let iccProfile = null;
1049
- let exifDateTimeOriginal = null;
1050
- let orientation = null;
1051
- let pos = 33;
1052
- while (pos < buffer.length - 12) {
1053
- const chunkLen = buffer.readUInt32BE(pos);
1054
- const chunkType = buffer.toString("ascii", pos + 4, pos + 8);
1055
- const chunkData = pos + 8;
1056
- if (chunkType === "acTL") {
1057
- animated = true;
1058
- frames = buffer.readUInt32BE(chunkData);
1059
- } else if (chunkType === "iCCP") {
1060
- const nameEnd = buffer.indexOf(0, chunkData);
1061
- const profileName = buffer.toString("ascii", chunkData, nameEnd);
1062
- iccProfile = profileName || "embedded";
1063
- } else if (chunkType === "tIME") {
1064
- const month = buffer?.[chunkData + 2], day = buffer?.[chunkData + 3], hour = buffer?.[chunkData + 4], minute = buffer?.[chunkData + 5], second = buffer?.[chunkData + 6];
1065
- if (typeof month !== "undefined" && typeof day !== "undefined" && typeof hour !== "undefined" && typeof minute !== "undefined" && typeof second !== "undefined") {
1066
- const year = buffer.readUInt16BE(chunkData);
1067
- 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")}`;
1068
- }
1069
- } else if (chunkType === "IDAT") {
1070
- break;
1071
- }
1072
- pos += 12 + chunkLen;
1073
- }
1074
- return {
1075
- width,
1076
- height,
1077
- format: "png",
1078
- frames,
1079
- animated,
1080
- hasAlpha,
1081
- orientation,
1082
- aspectRatio: width / height,
1083
- colorSpace,
1084
- iccProfile,
1085
- exifDateTimeOriginal
1086
- };
1087
- }
1088
- if (buffer.length >= 10 && buffer[0] === 255 && buffer[1] === 216) {
1089
- let pos = 2, colorSpace = "unknown", hasAlpha = false, width = 0, height = 0, iccProfile = null, orientation = null, exifDateTimeOriginal = null;
1090
- while (pos < buffer.length - 10) {
1091
- if (buffer[pos] !== 255) {
1092
- throw new Error("Invalid JPEG file");
1093
- }
1094
- const marker = buffer[pos + 1];
1095
- if (marker === 218) break;
1096
- const segmentSize = buffer.readUInt16BE(pos + 2);
1097
- if (!marker) {
1098
- throw new Error("no marker for jpeg");
1099
- }
1100
- if (marker >= 192 && marker <= 207 && marker !== 196 && marker !== 200 && marker !== 204) {
1101
- const numComponents = buffer[pos + 4];
1102
- switch (numComponents) {
1103
- case 1:
1104
- colorSpace = "grayscale";
1105
- break;
1106
- case 3:
1107
- colorSpace = "ycbcr";
1108
- break;
1109
- // Most common for RGB JPEGs (stored as YCbCr)
1110
- case 4:
1111
- colorSpace = "ycck";
1112
- break;
1113
- // YCCK for CMYK with alpha-like, but no true alpha
1114
- default:
1115
- colorSpace = "unknown";
1116
- }
1117
- width = buffer.readUInt16BE(pos + 7);
1118
- height = buffer.readUInt16BE(pos + 5);
1119
- } else if (marker === 225) {
1120
- const { orientation: ori, dateTimeOriginal } = this.parseExif(
1121
- buffer,
1122
- pos,
1123
- segmentSize
1124
- );
1125
- orientation = ori;
1126
- exifDateTimeOriginal = dateTimeOriginal;
1127
- } else if (marker === 226) {
1128
- const iccHeader = buffer.toString("ascii", pos + 4, pos + 18);
1129
- if (iccHeader.startsWith("ICC_PROFILE")) {
1130
- iccProfile = "embedded";
1131
- }
1132
- }
1133
- pos += segmentSize + 2;
1134
- }
1135
- if (width === 0) throw new Error("No dimensions found in JPEG file");
1136
- return {
1137
- width,
1138
- height,
1139
- format: "jpeg",
1140
- frames: 1,
1141
- animated: false,
1142
- // JPEG not animated
1143
- hasAlpha,
1144
- orientation,
1145
- aspectRatio: width / height,
1146
- colorSpace,
1147
- iccProfile,
1148
- exifDateTimeOriginal
1149
- };
1150
- }
1151
- const gifHeader = buffer.toString("ascii", 0, 6);
1152
- if (buffer.length >= 10 && (gifHeader === "GIF87a" || gifHeader === "GIF89a")) {
1153
- const width = buffer.readUInt16LE(6), height = buffer.readUInt16LE(8);
1154
- let frames = 0;
1155
- let pos = 13;
1156
- let bufTen = buffer?.[10];
1157
- if (typeof bufTen === "undefined") {
1158
- pos = 13;
1159
- frames = 0;
1160
- } else if (bufTen & 128) pos += 3 << (bufTen & 7) + 1;
1161
- while (pos < buffer.length) {
1162
- if (buffer[pos] === 33) {
1163
- pos += 2;
1164
- let subSize = buffer?.[pos];
1165
- while (subSize && subSize > 0) {
1166
- pos += subSize + 1;
1167
- subSize = buffer?.[pos];
1168
- }
1169
- pos++;
1170
- } else if (buffer?.[pos] && buffer?.[pos] === 44) {
1171
- frames++;
1172
- pos += 10;
1173
- let b = buffer?.[pos - 1];
1174
- if (typeof b !== "undefined" && b & 128)
1175
- pos += 3 << (b & 7) + 1;
1176
- pos++;
1177
- let dataSize = buffer?.[pos];
1178
- while (dataSize && dataSize > 0) {
1179
- pos += dataSize + 1;
1180
- dataSize = buffer[pos];
1181
- }
1182
- pos++;
1183
- } else if (buffer[pos] === 59) {
1184
- break;
1185
- } else {
1186
- pos++;
1187
- }
1188
- }
1189
- return {
1190
- width,
1191
- height,
1192
- format: "gif",
1193
- frames,
1194
- animated: frames > 1,
1195
- hasAlpha: null,
1196
- // GIF transparency is per-pixel binary, not full alpha; set null or true if transparent color exists, but complex
1197
- orientation: null,
1198
- // No orientation in GIF
1199
- aspectRatio: width / height,
1200
- colorSpace: "indexed",
1201
- iccProfile: null,
1202
- // No ICC in GIF
1203
- exifDateTimeOriginal: null
1204
- // No EXIF in GIF
1205
- };
1206
- }
1207
- if (buffer.length >= 26 && buffer?.[0] === 66 && buffer?.[1] === 77) {
1208
- const width = buffer.readInt32LE(18);
1209
- const height = Math.abs(buffer.readInt32LE(22));
1210
- const bitDepth = buffer.readUInt16LE(28);
1211
- let colorSpace = bitDepth <= 8 ? "indexed" : "rgb";
1212
- return {
1213
- width,
1214
- height,
1215
- format: "bmp",
1216
- frames: 1,
1217
- animated: false,
1218
- hasAlpha: null,
1219
- // Some BMP have alpha in 32bpp, check if bitDepth===32 && compression===3 (bitfields with alpha)
1220
- orientation: buffer.readInt32LE(22) < 0 ? 1 : 6,
1221
- // Negative height means top-down (orientation 1), positive bottom-up (like 6, but simplified)
1222
- aspectRatio: width / height,
1223
- colorSpace,
1224
- iccProfile: null,
1225
- // Rare in BMP
1226
- exifDateTimeOriginal: null
1227
- };
1228
- }
1229
- if (buffer.length >= 30 && buffer.toString("ascii", 0, 4) === "RIFF" && buffer.toString("ascii", 8, 12) === "WEBP") {
1230
- const chunkType = buffer.toString("ascii", 12, 16);
1231
- let colorSpace = "unknown";
1232
- let hasAlpha = false;
1233
- let width = 0;
1234
- let height = 0;
1235
- let frames = 1;
1236
- let animated = false;
1237
- let iccProfile = null;
1238
- if (chunkType === "VP8X") {
1239
- const flags = buffer?.[20];
1240
- colorSpace = flags ? flags & 2 ? "rgba" : "rgb" : "unknown";
1241
- hasAlpha = flags ? !!(flags & 2) : false;
1242
- animated = flags ? !!(flags & 1) : false;
1243
- let widthSubtractOne = 0;
1244
- let heightSubtractOne = 0;
1245
- if (buffer?.[24] && buffer?.[25] && buffer?.[26]) {
1246
- widthSubtractOne = buffer[24] | buffer[25] << 8 | buffer[26] << 16;
1247
- }
1248
- if (buffer?.[27] && buffer?.[28] && buffer?.[29]) {
1249
- heightSubtractOne = buffer[27] | buffer[28] << 8 | buffer[29] << 16;
1250
- }
1251
- width = widthSubtractOne + 1;
1252
- height = heightSubtractOne + 1;
1253
- if (animated) {
1254
- let pos = 30;
1255
- frames = 0;
1256
- while (pos < buffer.length - 8) {
1257
- const subChunkType = buffer.toString("ascii", pos, pos + 4);
1258
- const subChunkSize = buffer.readUInt32LE(pos + 4);
1259
- if (subChunkType === "ICCP") {
1260
- iccProfile = "embedded";
1261
- } else if (subChunkType === "ANMF") {
1262
- frames++;
1263
- }
1264
- pos += 8 + subChunkSize + subChunkSize % 2;
1265
- }
1266
- }
1267
- } else if (chunkType === "VP8 ") {
1268
- colorSpace = "rgb";
1269
- hasAlpha = false;
1270
- const dataStart = 20;
1271
- if (buffer?.[dataStart + 3] !== 157 || buffer?.[dataStart + 4] !== 1 || buffer?.[dataStart + 5] !== 42) {
1272
- throw new Error("Invalid VP8 keyframe");
1273
- }
1274
- width = buffer.readUInt16LE(dataStart + 6) & 16383;
1275
- height = buffer.readUInt16LE(dataStart + 8) & 16383;
1276
- } else if (chunkType === "VP8L") {
1277
- const dataStart = 20;
1278
- if (buffer?.[dataStart] !== 47) {
1279
- throw new Error("Invalid VP8L signature");
1280
- }
1281
- const bits = buffer.readUInt32LE(dataStart + 1);
1282
- if (bits >>> 29 !== 0) {
1283
- throw new Error("Invalid VP8L version");
1284
- }
1285
- colorSpace = bits & 1 << 8 ? "rgba" : "rgb";
1286
- hasAlpha = !!(bits & 1 << 8);
1287
- width = 1 + (bits & 16383);
1288
- height = 1 + (bits >> 14 & 16383);
1289
- } else {
1290
- throw new Error("Unsupported WebP chunk");
1291
- }
1292
- return {
1293
- width,
1294
- height,
1295
- format: "webp",
1296
- frames,
1297
- animated,
1298
- hasAlpha,
1299
- orientation: null,
1300
- // No standard orientation in WebP
1301
- aspectRatio: width / height,
1302
- colorSpace,
1303
- iccProfile,
1304
- exifDateTimeOriginal: null
1305
- // Can have EXIF chunk, but rare; add if needed
1306
- };
1307
- }
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";
1340
- }
1341
- }
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
- }
1350
- }
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);
1359
- }
1360
- }
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
- };
1377
- }
1378
- throw new Error("Unsupported image format or invalid file");
1379
- }
1380
- /**
1381
- *
1382
- * @access package-private
1383
- *
1384
- * work in progress, for internal package maintainer use only
1385
- */
1386
- // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
1387
- // https://www.npmjs.com/package/fluent-ffmpeg
1388
- // https://www.npmjs.com/package/@types/fluent-ffmpeg
1389
- async imageTransform({
1390
- format,
1391
- target,
1392
- quality = 80,
1393
- tint,
1394
- resize
1395
- }) {
1396
- if (tint && !resize) {
1397
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
1398
- } else if (!tint && resize) {
1399
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1400
- } else if (tint && resize) {
1401
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
1402
- } else {
1403
- return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
1404
- }
1405
- }
1406
- /**
1407
- * Write data to a file in the system's tmp directory
1408
- * @param filename The filename (can include subdirectories like "img-probe/file.txt")
1409
- * @param data The data to write
1410
- * @param options Optional write stream options
1411
- * @returns The full path to the written file
1412
- * @example
1413
- * ```ts
1414
- * const fs = new Fs(process.cwd());
1415
- * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
1416
- * // Or with a subdirectory:
1417
- * fs.writeTmp("img-probe/output.png", imageBuffer);
1418
- * ```
1419
- */
1420
- writeTmp(filename, data, options) {
1421
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1422
- Promise.resolve(this.withWs(fullPath, data, options));
1423
- }
1424
- /**
1425
- * Read a file from the tmp directory
1426
- * @param filename The filename to read (can include subdirectories)
1427
- * @returns Buffer containing the file data
1428
- * @example
1429
- * ```ts
1430
- * const fs = new Fs(process.cwd());
1431
- * const data = fs.readTmp("session-data.json");
1432
- * const parsed = JSON.parse(data.toString("utf-8"));
1433
- * ```
1434
- */
1435
- readTmp(filename) {
1436
- const fullPath = (0, import_path.resolve)(this.tmpDir, filename);
1437
- if (!this.exists(fullPath)) {
1438
- throw new Error(`Tmp file not found: ${filename}`);
1439
- }
1440
- return this.fileToBuffer(fullPath);
1441
- }
1442
- /**
1443
- * Scan the tmp directory for files matching a pattern
1444
- * @param pattern Optional pattern to filter files (e.g., "img-probe")
1445
- * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
1446
- * @returns Array of matching file paths relative to tmp directory
1447
- * @example
1448
- * ```ts
1449
- * const fs = new Fs(process.cwd());
1450
- * // Get all img-probe files
1451
- * const imgFiles = fs.scanTmp("img-probe");
1452
- * // Get all files in tmp (non-recursive)
1453
- * const allFiles = fs.scanTmp();
1454
- * ```
1455
- */
1456
- scanTmp(pattern, options = {
1457
- recursive: false,
1458
- withFileTypes: false,
1459
- encoding: "utf-8"
1460
- }) {
1461
- const dirs = (0, import_path.resolve)(this.tmpDir);
1462
- const tmpContents = this.readDir(dirs, options);
1463
- if (!pattern) {
1464
- return tmpContents;
1465
- }
1466
- if (typeof pattern === "string") {
1467
- return tmpContents.filter((t) => t.includes(pattern));
1468
- }
1469
- return tmpContents.filter((path) => {
1470
- return pattern.test(path);
1471
- });
1472
- }
1473
- /**
1474
- * Extract specific files from tmp directory to a target location
1475
- * @param pattern Pattern to match files (e.g., "img-probe")
1476
- * @param targetDir Target directory to extract files to
1477
- * @param options Options for extraction behavior
1478
- * @returns Array of extracted file paths
1479
- * @example
1480
- * ```ts
1481
- * const fs = new Fs(process.cwd());
1482
- * // Extract all img-probe files to ./output
1483
- * const extracted = fs.extractFromTmp("img-probe", "./output");
1484
- * // Extract with custom behavior
1485
- * fs.extractFromTmp("session-", "./sessions", {
1486
- * preserveStructure: true,
1487
- * cleanupAfter: true
1488
- * });
1489
- * ```
1490
- */
1491
- extractFromTmp(pattern, targetDir, options) {
1492
- const {
1493
- preserveStructure = false,
1494
- cleanupAfter = false,
1495
- overwrite = true
1496
- } = options ?? {};
1497
- const matchingFiles = this.scanTmp(pattern);
1498
- const extracted = [];
1499
- for (const file of matchingFiles) {
1500
- const sourcePath = (0, import_path.resolve)(this.tmpDir, file);
1501
- const lastSegment = file.includes("/") ? file.split("/").pop() : file;
1502
- if (!lastSegment) continue;
1503
- const targetPath = preserveStructure ? (0, import_path.resolve)(targetDir, file) : (0, import_path.resolve)(targetDir, lastSegment);
1504
- if (this.exists(targetPath) && !overwrite) {
1505
- console.warn(`Skipping existing file: ${targetPath}`);
1506
- continue;
1507
- }
1508
- const data = this.fileToBuffer(sourcePath);
1509
- this.withWs(targetPath, data);
1510
- extracted.push(targetPath);
1511
- if (cleanupAfter) {
1512
- this.rmFile(sourcePath);
1513
- }
1514
- }
1515
- return extracted;
1516
- }
1517
- /**
1518
- * Clean up tmp files matching a pattern
1519
- * @param pattern Pattern to match files for deletion
1520
- * @param maxAge Optional max age in milliseconds (only delete files older than this)
1521
- * @returns Number of files removed
1522
- * @example
1523
- * ```ts
1524
- * const fs = new Fs(process.cwd());
1525
- * // Remove all img-probe files
1526
- * fs.cleanupTmp("img-probe");
1527
- * // Remove session files older than 1 hour
1528
- * fs.cleanupTmp("session-", 60 * 60 * 1000);
1529
- * ```
1530
- */
1531
- cleanupTmp(pattern, maxAge) {
1532
- const matchingFiles = this.scanTmp(pattern);
1533
- let removed = 0;
1534
- for (const file of matchingFiles) {
1535
- const fullPath = (0, import_path.resolve)(this.tmpDir, file);
1536
- try {
1537
- const stats = import_fs.default.statSync(fullPath);
1538
- if (maxAge) {
1539
- const age = Date.now() - stats.mtimeMs;
1540
- if (age < maxAge) {
1541
- continue;
1542
- }
1543
- }
1544
- if (stats.isDirectory()) {
1545
- this.rmDirSync(fullPath);
1546
- } else {
1547
- this.rmFile(fullPath);
1548
- }
1549
- removed++;
1550
- } catch (err) {
1551
- console.warn(`Failed to remove tmp file ${file}:`, err);
1552
- }
1553
- }
1554
- return removed;
1555
- }
1556
- rmTmpFile(filename) {
1557
- const tmpPath = (0, import_path.resolve)(this.tmpDir, filename);
1558
- this.rmFile(tmpPath);
1559
- }
1560
- /**
1561
- * Generate a unique tmp filename with optional prefix
1562
- * @param prefix Optional prefix for the filename
1563
- * @param extension Optional file extension (without dot)
1564
- * @returns Unique filename
1565
- * @example
1566
- * ```ts
1567
- * const fs = new Fs(process.cwd());
1568
- * const filename = fs.uniqueTmpName("img-probe", "png");
1569
- * // Returns: "img-probe-1701234567890-a3b2c1.png"
1570
- * ```
1571
- */
1572
- uniqueTmpName(prefix, extension) {
1573
- const timestamp = Date.now();
1574
- const random = Math.random().toString(36).substring(2, 8);
1575
- const parts = [prefix ?? "tmp", timestamp, random].join("-");
1576
- return extension ? `${parts}.${extension}` : parts;
1577
- }
1578
- /**
1579
- * Async generator for cleaning tmp files with batched removal
1580
- * @param pattern Pattern to match files for deletion
1581
- * @param batchSize Number of files to remove per batch (default 10)
1582
- * @yields Progress information during cleanup
1583
- * @returns Final cleanup summary
1584
- * @example
1585
- * ```ts
1586
- * const fs = new Fs(process.cwd());
1587
- * // Clean up with progress tracking
1588
- * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
1589
- * console.log(progress);
1590
- * }
1591
- * ```
1592
- */
1593
- async *cleanTmpGenerator(pattern, batchSize = 10) {
1594
- const files = this.scanTmp(pattern);
1595
- const batches = await this.arrToArrOfArrs({
1596
- arrToFragment: files,
1597
- arrOfArrsAggregator: [],
1598
- interval: batchSize
1599
- });
1600
- let totalRemoved = 0;
1601
- for (const [index, batch] of batches.entries()) {
1602
- yield {
1603
- action: "removing",
1604
- batch: [...batch],
1605
- batchNumber: index + 1,
1606
- totalBatches: batches.length,
1607
- totalFound: files.length,
1608
- removed: totalRemoved
1609
- };
1610
- for (const file of batch) {
1611
- this.rmTmpFile(file);
1612
- totalRemoved++;
1613
- }
1614
- yield {
1615
- action: "batch-complete",
1616
- batchNumber: index + 1,
1617
- batchSize: batch.length,
1618
- totalRemoved,
1619
- remaining: files.length - totalRemoved
1620
- };
1621
- }
1622
- return {
1623
- action: "complete",
1624
- totalRemoved,
1625
- totalBatches: batches.length,
1626
- pattern: pattern.toString()
1627
- };
1628
- }
1629
- };
1630
- //# sourceMappingURL=index.cjs.map