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