@d0paminedriven/fs 7.1.0 → 7.3.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.
Files changed (60) hide show
  1. package/README.md +104 -51
  2. package/dist/chunk-2IRCHZCF.js +75 -0
  3. package/dist/{chunk-LFHV4PPA.js → chunk-2XQ44ZWR.js} +339 -3
  4. package/dist/{chunk-IUGBPDQJ.js → chunk-6HHKXBIM.js} +5 -2
  5. package/dist/chunk-HPM4IQQR.js +69 -0
  6. package/dist/{chunk-3WB2TSBO.js → chunk-KNLXF622.js} +2 -2
  7. package/dist/chunk-KOKPGEU4.js +69 -0
  8. package/dist/chunk-LQP2FYMK.js +237 -0
  9. package/dist/chunk-NHYRCNMW.js +107 -0
  10. package/dist/chunk-NOOFSAF4.js +165 -0
  11. package/dist/chunk-PTXZQBLV.js +367 -0
  12. package/dist/{chunk-RJ2YQE3C.js → chunk-R63XI7FS.js} +1 -1
  13. package/dist/{chunk-QBG7TFHM.js → chunk-UW52DMHT.js} +2 -2
  14. package/dist/chunk-Z2WZLZC4.js +75 -0
  15. package/dist/fs/index.d.ts +18 -282
  16. package/dist/fs/index.js +13 -6
  17. package/dist/fs-atomic/index.d.ts +38 -0
  18. package/dist/fs-atomic/index.js +14 -0
  19. package/dist/fs-base/index.d.ts +112 -0
  20. package/dist/fs-base/index.js +13 -0
  21. package/dist/fs-core/index.d.ts +24 -0
  22. package/dist/fs-core/index.js +17 -0
  23. package/dist/fs-fetch/index.d.ts +64 -0
  24. package/dist/fs-fetch/index.js +19 -0
  25. package/dist/fs-size/index.d.ts +30 -0
  26. package/dist/fs-size/index.js +16 -0
  27. package/dist/fs-tmp/index.d.ts +194 -0
  28. package/dist/fs-tmp/index.js +18 -0
  29. package/dist/image/index.d.ts +35 -1
  30. package/dist/image/index.js +5 -4
  31. package/dist/index.d.ts +12 -2
  32. package/dist/index.js +36 -8
  33. package/dist/ld/index.d.ts +14 -0
  34. package/dist/ld/index.js +8 -0
  35. package/dist/mime/index.d.ts +1 -0
  36. package/dist/mime/index.js +4 -3
  37. package/dist/types/index.d.ts +12 -12
  38. package/dist/types/index.js +1 -1
  39. package/dist/types/stream.d.ts +9 -0
  40. package/dist/types/stream.js +1 -0
  41. package/dist/url/index.d.ts +1 -0
  42. package/dist/url/index.js +3 -2
  43. package/dist/utils/index.d.ts +2 -1
  44. package/dist/utils/index.js +2 -1
  45. package/package.json +37 -5
  46. package/dist/chunk-3REIEDSC.js +0 -745
  47. package/dist/fs/index.cjs +0 -1818
  48. package/dist/fs/index.d.cts +0 -464
  49. package/dist/image/index.cjs +0 -1071
  50. package/dist/image/index.d.cts +0 -88
  51. package/dist/index.cjs +0 -1838
  52. package/dist/index.d.cts +0 -10
  53. package/dist/mime/index.cjs +0 -509
  54. package/dist/mime/index.d.cts +0 -502
  55. package/dist/types/index.cjs +0 -38
  56. package/dist/types/index.d.cts +0 -333
  57. package/dist/url/index.cjs +0 -181
  58. package/dist/url/index.d.cts +0 -33
  59. package/dist/utils/index.cjs +0 -157
  60. package/dist/utils/index.d.cts +0 -25
@@ -1,745 +0,0 @@
1
- import {
2
- ImageService
3
- } from "./chunk-LFHV4PPA.js";
4
- import {
5
- unitsObj
6
- } from "./chunk-RJ2YQE3C.js";
7
- import {
8
- __name
9
- } from "./chunk-7QVYU63E.js";
10
-
11
- // src/fs/index.ts
12
- import { execSync } from "child_process";
13
- import fsSync from "fs";
14
- import fsAsync from "fs/promises";
15
- import { tmpdir } from "os";
16
- import { join, relative, resolve } from "path";
17
- import * as dotenv from "dotenv";
18
- import expand from "dotenv-expand";
19
- import sharp from "sharp";
20
- dotenv.config({ quiet: true });
21
- var Fs = class extends ImageService {
22
- constructor(cwd) {
23
- super();
24
- this.cwd = cwd;
25
- cwd ??= process.cwd();
26
- }
27
- static {
28
- __name(this, "Fs");
29
- }
30
- async getImageSpecs(filePath) {
31
- const buffer = await this.fileToBufferAsync(filePath);
32
- return this.getImageSpecsWorkup(buffer);
33
- }
34
- async getImageSpecsTmp(target) {
35
- const buffer = await this.readTmpAsync(target);
36
- return this.getImageSpecsWorkup(buffer);
37
- }
38
- get myEnv() {
39
- return dotenv.config({ processEnv: {} });
40
- }
41
- get tmpDir() {
42
- return tmpdir();
43
- }
44
- get tmpDirRelative() {
45
- return relative(this.cwd, tmpdir());
46
- }
47
- parseDotEnv() {
48
- return expand.expand(this.myEnv);
49
- }
50
- /**
51
- *
52
- * @param target path to the file or directory to check for existence
53
- * @returns true if the file or directory exists, false otherwise
54
- * @example
55
- * ```ts
56
- * const fs = new Fs(process.cwd());
57
- * const exists = fs.exists("my-file.txt");
58
- * console.log(exists); // true if the file exists, false otherwise
59
- * ```
60
- * @description
61
- * This method checks if a file or directory exists at the specified path input
62
- *
63
- * Additional Note:
64
- *
65
- * say you have a directory that begins with a dot, such as `.turbo`;
66
- *
67
- * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
68
- *
69
- */
70
- exists(target) {
71
- if (!/\//gm.test(target)) {
72
- if (/\./g.test(target)) {
73
- return fsSync.existsSync(resolve(join(this.cwd, target)));
74
- } else {
75
- const statsSync = fsSync.statSync(resolve(join(this.cwd, target)), {
76
- throwIfNoEntry: false
77
- });
78
- const isDir = statsSync?.isDirectory();
79
- if (isDir) {
80
- return isDir;
81
- } else return false;
82
- }
83
- } else {
84
- if (/\./g.test(target)) {
85
- return fsSync.existsSync(relative(this.cwd ?? process.cwd(), target));
86
- } else {
87
- const statsSync = fsSync.statSync(relative(this.cwd, target), {
88
- throwIfNoEntry: false
89
- });
90
- const isDir = statsSync?.isDirectory();
91
- if (isDir) {
92
- return isDir;
93
- } else return false;
94
- }
95
- }
96
- }
97
- /**
98
- *
99
- * @param ms milliseconds to wait
100
- * @returns a promise that resolves after the specified number of milliseconds
101
- * @example
102
- * ```ts
103
- * const fs = new Fs(process.cwd());
104
- * await fs.wait(1000); // waits for 1 second
105
- * console.log("Done waiting!");
106
- * ```
107
- *
108
- * Alternatively, you can use it like this:
109
- * ```ts
110
- * const fs = new Fs(process.cwd());
111
- * fs.wait(1000).then(() => { // waits for 1 second
112
- * console.log("Done waiting!");
113
- * // do something after waiting
114
- * });
115
- * ```
116
- *
117
- * @description
118
- * 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.
119
- */
120
- wait(ms) {
121
- return new Promise((resolve2) => setTimeout(resolve2, ms));
122
- }
123
- /**
124
- * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
125
- * @param arr An array or readonly array of strings and/or Buffers
126
- * @returns An array of strings with Buffers converted to UTF-8 strings.
127
- */
128
- handleBuffStrArrUnion(arr) {
129
- return arr.map(
130
- (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
131
- );
132
- }
133
- isRootPathTargeted(path) {
134
- if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
135
- return true;
136
- } else return false;
137
- }
138
- /**
139
- *
140
- * @param path path to the directory relative to the cwd
141
- * @param options options for reading the directory, defaults to recursive
142
- *
143
- * The following two examples are equivalent:
144
- *
145
- * @example
146
- * ```ts
147
- * const fs = new Fs(process.cwd());
148
- * const files = fs.readDir("./my-directory", { recursive: true });
149
- * console.log(files);
150
- * ```
151
- * @example
152
- * ```ts
153
- * const fs = new Fs(process.cwd());
154
- * const files = fs.readDir("my-directory", { recursive: true });
155
- * console.log(files);
156
- * ```
157
- *
158
- * @returns an array of strings representing the contents of the directory
159
- */
160
- readDir(path, options = {
161
- recursive: true,
162
- withFileTypes: false,
163
- encoding: "utf-8"
164
- }) {
165
- if (this.isRootPathTargeted(path)) {
166
- return this.handleBuffStrArrUnion(
167
- fsSync.readdirSync(resolve(join(this.cwd, "./")), { ...options })
168
- );
169
- } else {
170
- return this.handleBuffStrArrUnion(
171
- fsSync.readdirSync(
172
- relative(this.cwd ??= process.cwd(), path),
173
- options
174
- )
175
- );
176
- }
177
- }
178
- executeCommand = /* @__PURE__ */ __name(({
179
- command,
180
- ...options
181
- }) => Buffer.from(execSync(command, { ...options }).toJSON().data).toString(
182
- "utf-8"
183
- ), "executeCommand");
184
- existsSync(path) {
185
- return this.exists(path);
186
- }
187
- pathHandler(path) {
188
- return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
189
- }
190
- mkdirSync(path, options) {
191
- return fsSync.mkdirSync(relative(this.cwd, path), options);
192
- }
193
- units = unitsObj;
194
- u = ["B", "KB", "MB", "GB", "TB", "PB"];
195
- autoFileSizeRaw(size) {
196
- let s = typeof size === "bigint" ? Number(size) : size;
197
- let i = 0;
198
- while (s >= 1024 && i < this.u.length - 1) {
199
- s /= 1024;
200
- i++;
201
- }
202
- return { value: s, unit: this.u[i] };
203
- }
204
- getSize(size, target, opts = { decimals: 4, includeUnits: true }) {
205
- const { decimals, includeUnits } = opts;
206
- if (target === "auto") {
207
- const { value, unit } = this.autoFileSizeRaw(size);
208
- const rounded2 = value.toFixed(decimals);
209
- return includeUnits ? `${rounded2} ${unit}` : Number.parseFloat(rounded2);
210
- }
211
- const key = target.toUpperCase();
212
- const exp = this.units[key];
213
- const divisor = typeof size === "bigint" ? 1024n ** BigInt(exp) : 1024 ** exp;
214
- let v = 0;
215
- if (typeof size === "bigint" || typeof divisor === "bigint") {
216
- if (typeof size === "bigint" && typeof divisor === "bigint")
217
- v = Number(size / divisor);
218
- else if (typeof size !== "bigint" && typeof divisor === "bigint")
219
- v = size / Number(divisor);
220
- else if (typeof size === "bigint" && typeof divisor !== "bigint")
221
- v = Number(size) / divisor;
222
- } else if (typeof size === "number" && typeof divisor === "number") {
223
- v = size / divisor;
224
- }
225
- const rounded = v.toFixed(decimals);
226
- return includeUnits ? `${rounded} ${key}` : Number.parseFloat(rounded);
227
- }
228
- fileSizeMb(path) {
229
- return fsSync.statSync(relative(this.cwd, path)).size / (1024 * 1024);
230
- }
231
- fileSize(path, target, opts) {
232
- if (!this.exists(path)) throw new Error(`path ${path} does not exist`);
233
- else {
234
- return this.getSize(
235
- fsSync.statSync(relative(this.cwd, path)).size,
236
- target,
237
- opts
238
- );
239
- }
240
- }
241
- generateDirIfDNE(path, options) {
242
- if (this.existsSync(path)) return;
243
- else {
244
- return this.mkdirSync(path, options);
245
- }
246
- }
247
- withWs(path, data, options) {
248
- try {
249
- if (/\//g.test(path) === true) {
250
- return this.generateDirIfDNE(this.pathHandler(path), {
251
- recursive: true
252
- });
253
- } else return path;
254
- } catch (error) {
255
- console.error(
256
- `[withWs error]: `.concat(
257
- typeof error === "string" ? error : JSON.stringify(error, null, 2)
258
- )
259
- );
260
- } finally {
261
- return fsSync.createWriteStream(
262
- relative(this.cwd ?? process.cwd(), path),
263
- typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
264
- ).write(Buffer.from(Buffer.from(data).toJSON().data));
265
- }
266
- }
267
- writeFileAsync = /* @__PURE__ */ __name(async (path, data, options) => {
268
- try {
269
- if (/\//g.test(path) === true)
270
- return this.generateDirIfDNE(this.pathHandler(path), {
271
- recursive: true
272
- });
273
- else return path;
274
- } catch (error) {
275
- console.error(
276
- `[writeFileAsync error]: `.concat(
277
- error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
278
- )
279
- );
280
- } finally {
281
- return await fsAsync.writeFile(
282
- relative(this.cwd ?? process.cwd(), path),
283
- Buffer.from(Buffer.from(data).toJSON().data),
284
- options
285
- );
286
- }
287
- }, "writeFileAsync");
288
- async unlink(path) {
289
- if (this.existsSync(path)) {
290
- return await fsAsync.unlink(relative(this.cwd, path));
291
- } else {
292
- throw new Error(`input path ${path} does not exist`);
293
- }
294
- }
295
- rmFile(filePath) {
296
- if (this.exists(filePath)) {
297
- if (this.isRootPathTargeted(filePath)) {
298
- fsSync.rmSync(resolve(join(this.cwd, filePath)));
299
- } else fsSync.rmSync(resolve(this.cwd, filePath));
300
- } else return;
301
- }
302
- async rmdir(dir, options) {
303
- const resolved = relative(this.cwd, dir);
304
- if (this.exists(dir)) {
305
- return fsAsync.rmdir(relative(this.cwd, dir), options);
306
- } else {
307
- throw new Error(`directory ${resolved} does not exist`);
308
- }
309
- }
310
- rmDirSync(dir) {
311
- const resolved = resolve(this.cwd, dir);
312
- if (this.exists(dir)) {
313
- return fsSync.rm(resolved, { force: true, recursive: true }, (err) => {
314
- if (err?.message) {
315
- console.error(err?.message);
316
- }
317
- });
318
- } else {
319
- throw new Error(`directory ${resolved} does not exist`);
320
- }
321
- }
322
- fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
323
- fsSync.readFileSync(relative(this.cwd ?? process.cwd(), path)).toJSON().data
324
- ), "fileToBuffer");
325
- fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
326
- return await fsAsync.readFile(relative(this.cwd, path));
327
- }, "fileToBufferAsync");
328
- dirContainsDir(readDir, targetDir, options) {
329
- return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
330
- }
331
- async assetToBuffer(path) {
332
- const [fetcher] = await Promise.all([
333
- fetch(path).then((t) => t.arrayBuffer())
334
- ]);
335
- const mime = this.getMimeTypeForPath(path);
336
- const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
337
- const extension = this.assetType(path) ?? "txt";
338
- return {
339
- b64encodedData,
340
- extension
341
- };
342
- }
343
- async assetToBufferView(path) {
344
- const response = await fetch(path, { method: "GET" });
345
- if (!response.ok) {
346
- throw new Error(`Failed to fetch asset: ${response.statusText}`);
347
- }
348
- const reader = response.body?.getReader();
349
- if (reader) {
350
- const chunks = Array.of();
351
- while (true) {
352
- const { done, value } = await reader.read();
353
- if (done) break;
354
- if (value) chunks.push(value);
355
- }
356
- const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
357
- const completeBuffer = new Uint8Array(totalLength);
358
- let offset = 0;
359
- for (const chunk of chunks) {
360
- completeBuffer.set(chunk, offset);
361
- offset += chunk.length;
362
- }
363
- const mime = this.getMimeTypeForPath(path);
364
- const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
365
- const extension = this.assetType(path);
366
- return { b64encodedData, extension };
367
- } else {
368
- const arrayBuffer = await response.arrayBuffer();
369
- const mime = this.getMimeTypeForPath(path);
370
- const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
371
- const extension = this.assetType(path);
372
- return { b64encodedData, extension };
373
- }
374
- }
375
- formatHelper(f) {
376
- if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
377
- const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
378
- return formatting;
379
- } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
380
- }
381
- cleanDataUrl(props) {
382
- return props.replace(
383
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
384
- ""
385
- );
386
- }
387
- /**
388
- *
389
- * @param inputUrl remote url to fetch data from
390
- * @param outputPath desired output path relative to the cwd
391
- * @param useDetectedExtension optional, defaults to true
392
- *
393
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
394
- *
395
- * 🚫 'public/assets/image-1'
396
- *
397
- * ✅ 'public/assets/image-1.png'
398
- */
399
- async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
400
- try {
401
- const result = await this.assetToBufferView(inputUrl);
402
- const cleanData = this.cleanDataUrl(result.b64encodedData);
403
- const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
404
- if (/\./g.test(formattedPath) === false) {
405
- throw new Error(
406
- "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
407
- );
408
- }
409
- this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
410
- } catch (err) {
411
- return console.error(err);
412
- }
413
- }
414
- knownToBlockHead(inputUrl) {
415
- if (inputUrl.startsWith("https://github.com")) {
416
- return "GET";
417
- } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
418
- return "GET";
419
- } else {
420
- return "HEAD";
421
- }
422
- }
423
- /**
424
- *
425
- * @param inputUrl remote url to fetch data from
426
- * @param outputPath desired output path relative to the cwd
427
- * @param useDetectedExtension optional, defaults to true
428
- *
429
- * if `useDetectedExtension` is false you must include the file extension in your output path &rarr;
430
- *
431
- * 🚫 'public/assets/image-1'
432
- *
433
- * ✅ 'public/assets/image-1.png'
434
- *
435
- * @description
436
- * This method is designed for all files regardless of size, but especially for
437
- * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
438
- * For files > 100 MB, it streams the data directly to disk instead of loading it all into memory
439
- */
440
- async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
441
- if (!URL.canParse(inputUrl))
442
- throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
443
- const MAX_SAFE_IN_MEMORY_MB = 100;
444
- try {
445
- const head = await fetch(inputUrl, {
446
- method: this.knownToBlockHead(inputUrl)
447
- });
448
- const contentLength = head.headers.get("content-length");
449
- const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
450
- let outputPath = outputPathI;
451
- const assetTypeViaUrl = this.assetType(inputUrl);
452
- const contentType = head.headers.get("content-type") ?? "application/octet-stream";
453
- const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
454
- this.generateDirIfDNE(this.pathHandler(formattedPath), {
455
- recursive: true
456
- });
457
- if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
458
- const res = await fetch(inputUrl);
459
- if (!res.ok || !res.body) {
460
- throw new Error(`Failed to fetch asset: ${res.statusText}`);
461
- }
462
- const writeStream = fsSync.createWriteStream(
463
- relative(this.cwd ?? process.cwd(), formattedPath)
464
- );
465
- const reader = res.body.getReader();
466
- const pump = /* @__PURE__ */ __name(async () => {
467
- while (true) {
468
- const { done, value } = await reader.read();
469
- if (done) break;
470
- writeStream.write(value);
471
- }
472
- writeStream.end();
473
- }, "pump");
474
- await pump();
475
- return;
476
- }
477
- const result = await this.assetToBufferView(inputUrl);
478
- const cleanedData = this.cleanDataUrl(result.b64encodedData);
479
- this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
480
- } catch (err) {
481
- console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
482
- }
483
- }
484
- /**
485
- *
486
- * @access package-private
487
- *
488
- * work in progress, for internal package maintainer use only
489
- */
490
- // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
491
- // https://www.npmjs.com/package/fluent-ffmpeg
492
- // https://www.npmjs.com/package/@types/fluent-ffmpeg
493
- async imageTransform({
494
- format,
495
- target,
496
- quality = 80,
497
- tint,
498
- resize
499
- }) {
500
- if (tint && !resize) {
501
- return await sharp(target).toFormat(format, { quality }).tint(tint).toBuffer();
502
- } else if (!tint && resize) {
503
- return await sharp(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
504
- } else if (tint && resize) {
505
- return await sharp(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
506
- } else {
507
- return await sharp(target).toFormat(format, { quality }).toBuffer();
508
- }
509
- }
510
- /**
511
- * Write data to a file in the system's tmp directory
512
- * @param filename The filename (can include subdirectories like "img-probe/file.txt")
513
- * @param data The data to write
514
- * @param options Optional write stream options
515
- * @returns The full path to the written file
516
- * @example
517
- * ```ts
518
- * const fs = new Fs(process.cwd());
519
- * const tmpPath = fs.writeTmp("session-data.json", JSON.stringify(data));
520
- * // Or with a subdirectory:
521
- * fs.writeTmp("img-probe/output.png", imageBuffer);
522
- * ```
523
- */
524
- writeTmp(filename, data, options) {
525
- const fullPath = resolve(this.tmpDir, filename);
526
- Promise.resolve(this.withWs(fullPath, data, options));
527
- }
528
- async readTmpAsync(filename) {
529
- const fullPath = resolve(this.tmpDir, filename);
530
- if (!this.exists(fullPath)) {
531
- throw new Error(`Tmp file not found: ${filename}`);
532
- }
533
- return await this.fileToBufferAsync(fullPath);
534
- }
535
- /**
536
- * Read a file from the tmp directory
537
- * @param filename The filename to read (can include subdirectories)
538
- * @returns Buffer containing the file data
539
- * @example
540
- * ```ts
541
- * const fs = new Fs(process.cwd());
542
- * const data = fs.readTmp("session-data.json");
543
- * const parsed = JSON.parse(data.toString("utf-8"));
544
- * ```
545
- */
546
- readTmp(filename) {
547
- const fullPath = resolve(this.tmpDir, filename);
548
- if (!this.exists(fullPath)) {
549
- throw new Error(`Tmp file not found: ${filename}`);
550
- }
551
- return this.fileToBuffer(fullPath);
552
- }
553
- /**
554
- * Scan the tmp directory for files matching a pattern
555
- * @param pattern Optional pattern to filter files (e.g., "img-probe")
556
- * @param options Options for directory reading (defaults to non-recursive to avoid permission issues)
557
- * @returns Array of matching file paths relative to tmp directory
558
- * @example
559
- * ```ts
560
- * const fs = new Fs(process.cwd());
561
- * // Get all img-probe files
562
- * const imgFiles = fs.scanTmp("img-probe");
563
- * // Get all files in tmp (non-recursive)
564
- * const allFiles = fs.scanTmp();
565
- * ```
566
- */
567
- scanTmp(pattern, options = {
568
- recursive: false,
569
- withFileTypes: false,
570
- encoding: "utf-8"
571
- }) {
572
- const dirs = resolve(this.tmpDir);
573
- const tmpContents = this.readDir(dirs, options);
574
- if (!pattern) {
575
- return tmpContents;
576
- }
577
- if (typeof pattern === "string") {
578
- return tmpContents.filter((t) => t.includes(pattern));
579
- }
580
- return tmpContents.filter((path) => {
581
- return pattern.test(path);
582
- });
583
- }
584
- /**
585
- * Extract specific files from tmp directory to a target location
586
- * @param pattern Pattern to match files (e.g., "img-probe")
587
- * @param targetDir Target directory to extract files to
588
- * @param options Options for extraction behavior
589
- * @returns Array of extracted file paths
590
- * @example
591
- * ```ts
592
- * const fs = new Fs(process.cwd());
593
- * // Extract all img-probe files to ./output
594
- * const extracted = fs.extractFromTmp("img-probe", "./output");
595
- * // Extract with custom behavior
596
- * fs.extractFromTmp("session-", "./sessions", {
597
- * preserveStructure: true,
598
- * cleanupAfter: true
599
- * });
600
- * ```
601
- */
602
- extractFromTmp(pattern, targetDir, options) {
603
- const {
604
- preserveStructure = false,
605
- cleanupAfter = false,
606
- overwrite = true
607
- } = options ?? {};
608
- const matchingFiles = this.scanTmp(pattern);
609
- const extracted = [];
610
- for (const file of matchingFiles) {
611
- const sourcePath = resolve(this.tmpDir, file);
612
- const lastSegment = file.includes("/") ? file.split("/").pop() : file;
613
- if (!lastSegment) continue;
614
- const targetPath = preserveStructure ? resolve(targetDir, file) : resolve(targetDir, lastSegment);
615
- if (this.exists(targetPath) && !overwrite) {
616
- console.warn(`Skipping existing file: ${targetPath}`);
617
- continue;
618
- }
619
- const data = this.fileToBuffer(sourcePath);
620
- this.withWs(targetPath, data);
621
- extracted.push(targetPath);
622
- if (cleanupAfter) {
623
- this.rmFile(sourcePath);
624
- }
625
- }
626
- return extracted;
627
- }
628
- /**
629
- * Clean up tmp files matching a pattern
630
- * @param pattern Pattern to match files for deletion
631
- * @param maxAge Optional max age in milliseconds (only delete files older than this)
632
- * @returns Number of files removed
633
- * @example
634
- * ```ts
635
- * const fs = new Fs(process.cwd());
636
- * // Remove all img-probe files
637
- * fs.cleanupTmp("img-probe");
638
- * // Remove session files older than 1 hour
639
- * fs.cleanupTmp("session-", 60 * 60 * 1000);
640
- * ```
641
- */
642
- cleanupTmp(pattern, maxAge) {
643
- const matchingFiles = this.scanTmp(pattern);
644
- let removed = 0;
645
- for (const file of matchingFiles) {
646
- const fullPath = resolve(this.tmpDir, file);
647
- try {
648
- const stats = fsSync.statSync(fullPath);
649
- if (maxAge) {
650
- const age = Date.now() - stats.mtimeMs;
651
- if (age < maxAge) {
652
- continue;
653
- }
654
- }
655
- if (stats.isDirectory()) {
656
- this.rmDirSync(fullPath);
657
- } else {
658
- this.rmFile(fullPath);
659
- }
660
- removed++;
661
- } catch (err) {
662
- console.warn(`Failed to remove tmp file ${file}:`, err);
663
- }
664
- }
665
- return removed;
666
- }
667
- rmTmpFile(filename) {
668
- const tmpPath = resolve(this.tmpDir, filename);
669
- this.rmFile(tmpPath);
670
- }
671
- /**
672
- * Generate a unique tmp filename with optional prefix
673
- * @param prefix Optional prefix for the filename
674
- * @param extension Optional file extension (without dot)
675
- * @returns Unique filename
676
- * @example
677
- * ```ts
678
- * const fs = new Fs(process.cwd());
679
- * const filename = fs.uniqueTmpName("img-probe", "png");
680
- * // Returns: "img-probe-1701234567890-a3b2c1.png"
681
- * ```
682
- */
683
- uniqueTmpName(prefix, extension) {
684
- const timestamp = Date.now();
685
- const random = Math.random().toString(36).substring(2, 8);
686
- const parts = [prefix ?? "tmp", timestamp, random].join("-");
687
- return extension ? `${parts}.${extension}` : parts;
688
- }
689
- /**
690
- * Async generator for cleaning tmp files with batched removal
691
- * @param pattern Pattern to match files for deletion
692
- * @param batchSize Number of files to remove per batch (default 10)
693
- * @yields Progress information during cleanup
694
- * @returns Final cleanup summary
695
- * @example
696
- * ```ts
697
- * const fs = new Fs(process.cwd());
698
- * // Clean up with progress tracking
699
- * for await (const progress of fs.cleanTmpGenerator("session-", 25)) {
700
- * console.log(progress);
701
- * }
702
- * ```
703
- */
704
- async *cleanTmpGenerator(pattern, batchSize = 10) {
705
- const files = this.scanTmp(pattern);
706
- const batches = await this.arrToArrOfArrs({
707
- arrToFragment: files,
708
- arrOfArrsAggregator: [],
709
- interval: batchSize
710
- });
711
- let totalRemoved = 0;
712
- for (const [index, batch] of batches.entries()) {
713
- yield {
714
- action: "removing",
715
- batch: [...batch],
716
- batchNumber: index + 1,
717
- totalBatches: batches.length,
718
- totalFound: files.length,
719
- removed: totalRemoved
720
- };
721
- for (const file of batch) {
722
- this.rmTmpFile(file);
723
- totalRemoved++;
724
- }
725
- yield {
726
- action: "batch-complete",
727
- batchNumber: index + 1,
728
- batchSize: batch.length,
729
- totalRemoved,
730
- remaining: files.length - totalRemoved
731
- };
732
- }
733
- return {
734
- action: "complete",
735
- totalRemoved,
736
- totalBatches: batches.length,
737
- pattern: pattern.toString()
738
- };
739
- }
740
- };
741
-
742
- export {
743
- Fs
744
- };
745
- //# sourceMappingURL=chunk-3REIEDSC.js.map