@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
@@ -0,0 +1,69 @@
1
+ import {
2
+ FsFetch
3
+ } from "./chunk-NOOFSAF4.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs/index.ts
9
+ import { resolve } from "path";
10
+ import sharp from "sharp";
11
+ var Fs = class extends FsFetch {
12
+ constructor(cwd) {
13
+ super(cwd ??= process.cwd());
14
+ this.cwd = cwd;
15
+ cwd ??= process.cwd();
16
+ }
17
+ static {
18
+ __name(this, "Fs");
19
+ }
20
+ async getImageSpecs(filePath) {
21
+ const buffer = await this.fileToBufferAsync(filePath);
22
+ return this.getImageSpecsWorkup(buffer);
23
+ }
24
+ async getImageSpecsTmp(target) {
25
+ const buffer = await this.readTmpAsync(target);
26
+ return this.getImageSpecsWorkup(buffer);
27
+ }
28
+ /**
29
+ * Extract image metadata using streaming (only reads ~4KB)
30
+ * Much more memory efficient for large images
31
+ */
32
+ async getImageSpecsStream(filePath) {
33
+ return this.extractFromPath(filePath);
34
+ }
35
+ async getImageSpecsStreamTmp(filePath) {
36
+ return this.extractFromPath(resolve(this.tmpDir, filePath));
37
+ }
38
+ /**
39
+ *
40
+ * @access package-private
41
+ *
42
+ * work in progress, for internal package maintainer use only
43
+ */
44
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
45
+ // https://www.npmjs.com/package/fluent-ffmpeg
46
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
47
+ async imageTransform({
48
+ format,
49
+ target,
50
+ quality = 80,
51
+ tint,
52
+ resize
53
+ }) {
54
+ if (tint && !resize) {
55
+ return await sharp(target).toFormat(format, { quality }).tint(tint).toBuffer();
56
+ } else if (!tint && resize) {
57
+ return await sharp(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
58
+ } else if (tint && resize) {
59
+ return await sharp(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
60
+ } else {
61
+ return await sharp(target).toFormat(format, { quality }).toBuffer();
62
+ }
63
+ }
64
+ };
65
+
66
+ export {
67
+ Fs
68
+ };
69
+ //# sourceMappingURL=chunk-HPM4IQQR.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  UrlService
3
- } from "./chunk-QBG7TFHM.js";
3
+ } from "./chunk-UW52DMHT.js";
4
4
  import {
5
5
  __name
6
6
  } from "./chunk-7QVYU63E.js";
@@ -334,4 +334,4 @@ export {
334
334
  mimeToExt,
335
335
  MimeService
336
336
  };
337
- //# sourceMappingURL=chunk-3WB2TSBO.js.map
337
+ //# sourceMappingURL=chunk-KNLXF622.js.map
@@ -0,0 +1,69 @@
1
+ import {
2
+ FsSize
3
+ } from "./chunk-2IRCHZCF.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs-core/index.ts
9
+ import fsSync from "fs";
10
+ import fsAsync from "fs/promises";
11
+ import { relative } from "path";
12
+ var FsCore = class extends FsSize {
13
+ constructor(cwd) {
14
+ super(cwd ??= process.cwd());
15
+ this.cwd = cwd;
16
+ }
17
+ static {
18
+ __name(this, "FsCore");
19
+ }
20
+ withWs(path, data, options) {
21
+ try {
22
+ if (/\//g.test(path) === true) {
23
+ return this.generateDirIfDNE(this.pathHandler(path), {
24
+ recursive: true
25
+ });
26
+ } else return path;
27
+ } catch (error) {
28
+ console.error(
29
+ `[withWs error]: `.concat(
30
+ typeof error === "string" ? error : JSON.stringify(error, null, 2)
31
+ )
32
+ );
33
+ } finally {
34
+ return fsSync.createWriteStream(
35
+ relative(this.cwd ?? process.cwd(), path),
36
+ typeof options !== "undefined" ? typeof options === "object" ? options : options : { autoClose: true }
37
+ ).write(Buffer.from(Buffer.from(data).toJSON().data));
38
+ }
39
+ }
40
+ writeFileAsync = /* @__PURE__ */ __name(async (path, data, options = {}) => {
41
+ try {
42
+ if (/\//g.test(path) === true)
43
+ return this.generateDirIfDNE(this.pathHandler(path), {
44
+ recursive: true
45
+ });
46
+ else return path;
47
+ } catch (error) {
48
+ console.error(
49
+ `[writeFileAsync error]: `.concat(
50
+ error instanceof Error ? error.message : typeof error === "string" ? error : JSON.stringify(error, null, 2)
51
+ )
52
+ );
53
+ } finally {
54
+ const dataBuff = new Uint8Array(
55
+ Buffer.from(Buffer.from(data).toJSON().data)
56
+ );
57
+ return await fsAsync.writeFile(
58
+ relative(this.cwd, path),
59
+ dataBuff,
60
+ typeof options === "object" ? { ...options } : options
61
+ );
62
+ }
63
+ }, "writeFileAsync");
64
+ };
65
+
66
+ export {
67
+ FsCore
68
+ };
69
+ //# sourceMappingURL=chunk-KOKPGEU4.js.map
@@ -0,0 +1,237 @@
1
+ import {
2
+ ImageService
3
+ } from "./chunk-2XQ44ZWR.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs-base/index.ts
9
+ import fsSync from "fs";
10
+ import { Readable } from "stream";
11
+ import { devNull, EOL, homedir, hostname, platform, tmpdir } from "os";
12
+ import { join, relative, resolve } from "path";
13
+ import { ReadableStream as WebReadableStream } from "stream/web";
14
+ import * as dotenv from "dotenv";
15
+ import expand from "dotenv-expand";
16
+ var FsBase = class extends ImageService {
17
+ constructor(cwd) {
18
+ super(cwd ?? process.cwd());
19
+ this.cwd = cwd;
20
+ }
21
+ static {
22
+ __name(this, "FsBase");
23
+ }
24
+ get tmpDir() {
25
+ return tmpdir();
26
+ }
27
+ get homeDir() {
28
+ return homedir();
29
+ }
30
+ get platform() {
31
+ return platform();
32
+ }
33
+ get hostname() {
34
+ return hostname();
35
+ }
36
+ get devNull() {
37
+ return devNull;
38
+ }
39
+ get eol() {
40
+ return EOL;
41
+ }
42
+ get env() {
43
+ return dotenv.config({ processEnv: {}, quiet: true });
44
+ }
45
+ parseDotEnv() {
46
+ const env = expand.expand(this.env);
47
+ if (typeof env !== "undefined") {
48
+ if (env.error) {
49
+ throw new Error(env.error.message);
50
+ } else {
51
+ return env.parsed;
52
+ }
53
+ } else {
54
+ throw new Error("env returned undefined");
55
+ }
56
+ }
57
+ relative(from, to) {
58
+ return relative(from, to);
59
+ }
60
+ isHomeTargeted(path) {
61
+ if (/^(~\/\.?)$/g.test(path)) {
62
+ return true;
63
+ } else if (path.includes(this.homeDir)) {
64
+ return true;
65
+ }
66
+ }
67
+ isRootPathTargeted(path) {
68
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|cwd|\.\/\.)$/g.test(path)) {
69
+ return true;
70
+ } else {
71
+ return false;
72
+ }
73
+ }
74
+ pathHandler(path) {
75
+ return /\//g.test(path) === true ? path.split(/([/])/gim).reverse().slice(2).reverse().join("") : path;
76
+ }
77
+ isUint8Array(v) {
78
+ return v instanceof Uint8Array;
79
+ }
80
+ isBuffer(v) {
81
+ return Buffer.isBuffer(v);
82
+ }
83
+ isWebReadableStream(v) {
84
+ return v instanceof WebReadableStream;
85
+ }
86
+ isAsyncIterable(v) {
87
+ return typeof v === "object" && v !== null && Symbol.asyncIterator in v;
88
+ }
89
+ formatHelper(f) {
90
+ if (/([A-Za-z]+-[A-Za-z]+)/g.test(f) === true) {
91
+ const formatting = f.split(/-/g).map((v) => v.substring(0, 1).toUpperCase().concat(v.substring(1))).join(" ");
92
+ return formatting;
93
+ } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
94
+ }
95
+ cleanDataUrl(props) {
96
+ return props.replace(
97
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
98
+ ""
99
+ );
100
+ }
101
+ toReadable(data) {
102
+ if (typeof data === "string") return Readable.from([Buffer.from(data)]);
103
+ if (this.isBuffer(data) || this.isUint8Array(data))
104
+ return Readable.from([data]);
105
+ if (this.isWebReadableStream(data)) return Readable.fromWeb(data);
106
+ if (this.isAsyncIterable(data)) return Readable.from(data);
107
+ throw new TypeError("Unsupported data type for toReadable()");
108
+ }
109
+ /**
110
+ *
111
+ * @param target path to the file or directory to check for existence
112
+ * @returns true if the file or directory exists, false otherwise
113
+ * @example
114
+ * ```ts
115
+ * const fs = new Fs(process.cwd());
116
+ * const exists = fs.exists("my-file.txt");
117
+ * console.log(exists); // true if the file exists, false otherwise
118
+ * ```
119
+ * @description
120
+ * This method checks if a file or directory exists at the specified path input
121
+ *
122
+ * Additional Note:
123
+ *
124
+ * say you have a directory that begins with a dot, such as `.turbo`;
125
+ *
126
+ * in this scenario, both `./.turbo` and `.turbo` will return true if the directory exists
127
+ *
128
+ */
129
+ exists(target) {
130
+ if (!/\//gm.test(target)) {
131
+ if (/\./g.test(target)) {
132
+ return fsSync.existsSync(resolve(join(this.cwd, target)));
133
+ } else {
134
+ const statsSync = fsSync.statSync(resolve(join(this.cwd, target)), {
135
+ throwIfNoEntry: false
136
+ });
137
+ const isDir = statsSync?.isDirectory();
138
+ if (isDir) {
139
+ return isDir;
140
+ } else return false;
141
+ }
142
+ } else {
143
+ if (/\./g.test(target)) {
144
+ return fsSync.existsSync(relative(this.cwd ?? process.cwd(), target));
145
+ } else {
146
+ const statsSync = fsSync.statSync(relative(this.cwd, target), {
147
+ throwIfNoEntry: false
148
+ });
149
+ const isDir = statsSync?.isDirectory();
150
+ if (isDir) {
151
+ return isDir;
152
+ } else return false;
153
+ }
154
+ }
155
+ }
156
+ /**
157
+ *
158
+ * @param ms milliseconds to wait
159
+ * @returns a promise that resolves after the specified number of milliseconds
160
+ * @example
161
+ * ```ts
162
+ * const fs = new Fs(process.cwd());
163
+ * await fs.wait(1000); // waits for 1 second
164
+ * console.log("Done waiting!");
165
+ * ```
166
+ *
167
+ * Alternatively, you can use it like this:
168
+ * ```ts
169
+ * const fs = new Fs(process.cwd());
170
+ * fs.wait(1000).then(() => { // waits for 1 second
171
+ * console.log("Done waiting!");
172
+ * // do something after waiting
173
+ * });
174
+ * ```
175
+ *
176
+ * @description
177
+ * 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.
178
+ */
179
+ wait(ms) {
180
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
181
+ }
182
+ /**
183
+ * Handles an array or readonly array of strings and/or Buffers, converting Buffers to strings
184
+ * @param arr An array or readonly array of strings and/or Buffers
185
+ * @returns An array of strings with Buffers converted to UTF-8 strings.
186
+ */
187
+ handleBuffStrArrUnion(arr) {
188
+ return arr.map(
189
+ (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
190
+ );
191
+ }
192
+ /**
193
+ *
194
+ * @param path path to the directory relative to the cwd
195
+ * @param options options for reading the directory, defaults to recursive
196
+ *
197
+ * The following two examples are equivalent:
198
+ *
199
+ * @example
200
+ * ```ts
201
+ * const fs = new Fs(process.cwd());
202
+ * const files = fs.readDir("./my-directory", { recursive: true });
203
+ * console.log(files);
204
+ * ```
205
+ * @example
206
+ * ```ts
207
+ * const fs = new Fs(process.cwd());
208
+ * const files = fs.readDir("my-directory", { recursive: true });
209
+ * console.log(files);
210
+ * ```
211
+ *
212
+ * @returns an array of strings representing the contents of the directory
213
+ */
214
+ readDir(path, options = {
215
+ recursive: true,
216
+ withFileTypes: false,
217
+ encoding: "utf-8"
218
+ }) {
219
+ if (this.isRootPathTargeted(path)) {
220
+ return this.handleBuffStrArrUnion(
221
+ fsSync.readdirSync(resolve(join(this.cwd, "./")), { ...options })
222
+ );
223
+ } else {
224
+ return this.handleBuffStrArrUnion(
225
+ fsSync.readdirSync(
226
+ relative(this.cwd ??= process.cwd(), path),
227
+ options
228
+ )
229
+ );
230
+ }
231
+ }
232
+ };
233
+
234
+ export {
235
+ FsBase
236
+ };
237
+ //# sourceMappingURL=chunk-LQP2FYMK.js.map
@@ -0,0 +1,107 @@
1
+ import {
2
+ FsBase
3
+ } from "./chunk-LQP2FYMK.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs-atomic/index.ts
9
+ import fsSync from "fs";
10
+ import fsAsync from "fs/promises";
11
+ import { execSync } from "child_process";
12
+ import { join, relative, resolve } from "path";
13
+ var FsAtomic = class extends FsBase {
14
+ constructor(cwd) {
15
+ super(cwd ??= process.cwd());
16
+ this.cwd = cwd;
17
+ }
18
+ static {
19
+ __name(this, "FsAtomic");
20
+ }
21
+ executeCommand = /* @__PURE__ */ __name(({
22
+ command,
23
+ ...options
24
+ }) => Buffer.from(execSync(command, { ...options }).toJSON().data).toString(
25
+ "utf-8"
26
+ ), "executeCommand");
27
+ mkdirSync(path, options = { mode: 511, recursive: true }) {
28
+ return fsSync.mkdirSync(relative(this.cwd, path), options);
29
+ }
30
+ generateDirIfDNE(path, options = { mode: 511, recursive: true }) {
31
+ if (this.exists(path)) return;
32
+ else {
33
+ return this.mkdirSync(path, options);
34
+ }
35
+ }
36
+ fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(fsSync.readFileSync(relative(this.cwd, path)).toJSON().data), "fileToBuffer");
37
+ fileToBufferAsync = /* @__PURE__ */ __name(async (path) => {
38
+ return await fsAsync.readFile(relative(this.cwd, path));
39
+ }, "fileToBufferAsync");
40
+ dirContainsDir(readDir, targetDir, options) {
41
+ return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
42
+ }
43
+ rmFile(filePath, options = {
44
+ force: true,
45
+ maxRetries: 0,
46
+ recursive: true,
47
+ retryDelay: 100
48
+ }) {
49
+ if (this.exists(filePath)) {
50
+ if (this.isRootPathTargeted(filePath)) {
51
+ fsSync.rmSync(resolve(join(this.cwd, filePath)), options);
52
+ } else fsSync.rmSync(resolve(this.cwd, filePath), options);
53
+ } else return;
54
+ }
55
+ /**
56
+ * Removes files and directories (modeled on the standard POSIX `rm` utility).
57
+ * To get a behavior similar to the `rm -rf` Unix command, use options `{ recursive: true, force: true }`.
58
+ * @return Fulfills with `undefined` upon success.
59
+ */
60
+ async rmdir(dir, options = {
61
+ maxRetries: 0,
62
+ retryDelay: 100,
63
+ recursive: true,
64
+ force: true
65
+ }) {
66
+ const resolved = relative(this.cwd, dir);
67
+ if (this.exists(dir)) {
68
+ return await fsAsync.rm(relative(this.cwd, dir), options);
69
+ } else {
70
+ throw new Error(`directory ${resolved} does not exist`);
71
+ }
72
+ }
73
+ rmDirSync(dir, options = {
74
+ force: true,
75
+ recursive: true,
76
+ maxRetries: 0,
77
+ retryDelay: 100
78
+ }, callback = (err) => err?.message ? console.error(err.message) : console.error(`directory ${dir} does not exist`)) {
79
+ const resolved = resolve(this.cwd, dir);
80
+ if (this.exists(dir)) {
81
+ return fsSync.rm(resolved, options, callback);
82
+ } else {
83
+ throw new Error(`directory ${resolved} does not exist`);
84
+ }
85
+ }
86
+ existsTmp(path) {
87
+ return this.exists(resolve(this.tmpDir, path));
88
+ }
89
+ mkdirTmp(path, options = { mode: 511, recursive: true }) {
90
+ return this.mkdirSync(resolve(this.tmpDir, path), options);
91
+ }
92
+ generateDirIfDNETmp(path, options) {
93
+ if (this.existsTmp(path)) return;
94
+ else {
95
+ return this.mkdirTmp(path, options);
96
+ }
97
+ }
98
+ rmTmpFile(filename) {
99
+ const tmpPath = resolve(this.tmpDir, filename);
100
+ this.rmFile(tmpPath);
101
+ }
102
+ };
103
+
104
+ export {
105
+ FsAtomic
106
+ };
107
+ //# sourceMappingURL=chunk-NHYRCNMW.js.map
@@ -0,0 +1,165 @@
1
+ import {
2
+ FsTmp
3
+ } from "./chunk-PTXZQBLV.js";
4
+ import {
5
+ __name
6
+ } from "./chunk-7QVYU63E.js";
7
+
8
+ // src/fs-fetch/index.ts
9
+ import fsSync from "fs";
10
+ import { relative } from "path";
11
+ var FsFetch = class extends FsTmp {
12
+ constructor(cwd) {
13
+ super(cwd ??= process.cwd());
14
+ this.cwd = cwd;
15
+ }
16
+ static {
17
+ __name(this, "FsFetch");
18
+ }
19
+ async assetToBuffer(path) {
20
+ const [fetcher] = await Promise.all([
21
+ fetch(path).then((t) => t.arrayBuffer())
22
+ ]);
23
+ const mime = this.getMimeTypeForPath(path);
24
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
25
+ const extension = this.assetType(path) ?? "txt";
26
+ return {
27
+ b64encodedData,
28
+ extension
29
+ };
30
+ }
31
+ async assetToBufferView(path) {
32
+ const response = await fetch(path, { method: "GET" });
33
+ if (!response.ok) {
34
+ throw new Error(`Failed to fetch asset: ${response.statusText}`);
35
+ }
36
+ const reader = response.body?.getReader();
37
+ if (reader) {
38
+ const chunks = Array.of();
39
+ while (true) {
40
+ const { done, value } = await reader.read();
41
+ if (done) break;
42
+ if (value) chunks.push(value);
43
+ }
44
+ const totalLength = chunks.reduce((acc, chunk) => acc + chunk.length, 0);
45
+ const completeBuffer = new Uint8Array(totalLength);
46
+ let offset = 0;
47
+ for (const chunk of chunks) {
48
+ completeBuffer.set(chunk, offset);
49
+ offset += chunk.length;
50
+ }
51
+ const mime = this.getMimeTypeForPath(path);
52
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
53
+ const extension = this.assetType(path);
54
+ return { b64encodedData, extension };
55
+ } else {
56
+ const arrayBuffer = await response.arrayBuffer();
57
+ const mime = this.getMimeTypeForPath(path);
58
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
59
+ const extension = this.assetType(path);
60
+ return { b64encodedData, extension };
61
+ }
62
+ }
63
+ /**
64
+ *
65
+ * @param inputUrl remote url to fetch data from
66
+ * @param outputPath desired output path relative to the cwd
67
+ * @param useDetectedExtension optional, defaults to true
68
+ *
69
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
70
+ *
71
+ * 🚫 'public/assets/image-1'
72
+ *
73
+ * ✅ 'public/assets/image-1.png'
74
+ */
75
+ async fetchRemoteWriteLocal(inputUrl, outputPath, useDetectedExtension = true) {
76
+ try {
77
+ const result = await this.assetToBufferView(inputUrl);
78
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
79
+ const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
80
+ if (/\./g.test(formattedPath) === false) {
81
+ throw new Error(
82
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
83
+ );
84
+ }
85
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
86
+ } catch (err) {
87
+ return console.error(err);
88
+ }
89
+ }
90
+ knownToBlockHead(inputUrl) {
91
+ if (inputUrl.startsWith("https://github.com")) {
92
+ return "GET";
93
+ } else if (inputUrl.startsWith("https://raw.githubusercontent.com")) {
94
+ return "GET";
95
+ } else {
96
+ return "HEAD";
97
+ }
98
+ }
99
+ /**
100
+ *
101
+ * @param inputUrl remote url to fetch data from
102
+ * @param outputPath desired output path relative to the cwd
103
+ * @param useDetectedExtension optional, defaults to true
104
+ *
105
+ * if `useDetectedExtension` is false you must include the file extension in your output path →
106
+ *
107
+ * 🚫 'public/assets/image-1'
108
+ *
109
+ * ✅ 'public/assets/image-1.png'
110
+ *
111
+ * @description
112
+ * This method is designed for all files regardless of size, but especially for
113
+ * larger files that may not fit into memory (it intelligently determines the best approach on the fly)
114
+ * For files > 100 MB, it streams the data directly to disk instead of loading it all into memory
115
+ */
116
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPathI, useDetectedExtension = true) {
117
+ if (!URL.canParse(inputUrl))
118
+ throw new Error(`invalid URL ${inputUrl} is unable to be parsed`);
119
+ const MAX_SAFE_IN_MEMORY_MB = 100;
120
+ try {
121
+ const head = await fetch(inputUrl, {
122
+ method: this.knownToBlockHead(inputUrl)
123
+ });
124
+ const contentLength = head.headers.get("content-length");
125
+ const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
126
+ let outputPath = outputPathI;
127
+ const assetTypeViaUrl = this.assetType(inputUrl);
128
+ const contentType = head.headers.get("content-type") ?? "application/octet-stream";
129
+ const formattedPath = useDetectedExtension ? `${outputPath}.${typeof assetTypeViaUrl === "undefined" ? this.toExtObj[contentType][0] : assetTypeViaUrl}` : outputPath;
130
+ this.generateDirIfDNE(this.pathHandler(formattedPath), {
131
+ recursive: true
132
+ });
133
+ if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
134
+ const res = await fetch(inputUrl);
135
+ if (!res.ok || !res.body) {
136
+ throw new Error(`Failed to fetch asset: ${res.statusText}`);
137
+ }
138
+ const writeStream = fsSync.createWriteStream(
139
+ relative(this.cwd ?? process.cwd(), formattedPath)
140
+ );
141
+ const reader = res.body.getReader();
142
+ const pump = /* @__PURE__ */ __name(async () => {
143
+ while (true) {
144
+ const { done, value } = await reader.read();
145
+ if (done) break;
146
+ writeStream.write(value);
147
+ }
148
+ writeStream.end();
149
+ }, "pump");
150
+ await pump();
151
+ return;
152
+ }
153
+ const result = await this.assetToBufferView(inputUrl);
154
+ const cleanedData = this.cleanDataUrl(result.b64encodedData);
155
+ this.withWs(formattedPath, Buffer.from(cleanedData, "base64"));
156
+ } catch (err) {
157
+ console.error(`[fetchRemoteWriteLocalLargeFiles error]:`, err);
158
+ }
159
+ }
160
+ };
161
+
162
+ export {
163
+ FsFetch
164
+ };
165
+ //# sourceMappingURL=chunk-NOOFSAF4.js.map