@d0paminedriven/fs 4.0.0 → 5.0.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 CHANGED
@@ -6,12 +6,6 @@ var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
8
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __commonJS = (cb, mod) => function __require() {
13
- return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
14
- };
15
9
  var __export = (target, all) => {
16
10
  for (var name in all)
17
11
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -34,193 +28,215 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
28
  ));
35
29
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
36
30
 
37
- // ../../node_modules/tsup/assets/cjs_shims.js
38
- var init_cjs_shims = __esm({
39
- "../../node_modules/tsup/assets/cjs_shims.js"() {
40
- "use strict";
41
- }
42
- });
43
-
44
- // ../../node_modules/dotenv-expand/lib/main.js
45
- var require_main = __commonJS({
46
- "../../node_modules/dotenv-expand/lib/main.js"(exports2, module2) {
47
- "use strict";
48
- init_cjs_shims();
49
- function _resolveEscapeSequences(value) {
50
- return value.replace(/\\\$/g, "$");
51
- }
52
- __name(_resolveEscapeSequences, "_resolveEscapeSequences");
53
- function expandValue(value, processEnv, runningParsed) {
54
- const env = { ...runningParsed, ...processEnv };
55
- const regex = /(?<!\\)\${([^{}]+)}|(?<!\\)\$([A-Za-z_][A-Za-z0-9_]*)/g;
56
- let result = value;
57
- let match;
58
- const seen = /* @__PURE__ */ new Set();
59
- while ((match = regex.exec(result)) !== null) {
60
- seen.add(result);
61
- const [template, bracedExpression, unbracedExpression] = match;
62
- const expression = bracedExpression || unbracedExpression;
63
- const opRegex = /(:\+|\+|:-|-)/;
64
- const opMatch = expression.match(opRegex);
65
- const splitter = opMatch ? opMatch[0] : null;
66
- const r = expression.split(splitter);
67
- let defaultValue;
68
- let value2;
69
- const key = r.shift();
70
- if ([":+", "+"].includes(splitter)) {
71
- defaultValue = env[key] ? r.join(splitter) : "";
72
- value2 = null;
73
- } else {
74
- defaultValue = r.join(splitter);
75
- value2 = env[key];
76
- }
77
- if (value2) {
78
- if (seen.has(value2)) {
79
- result = result.replace(template, defaultValue);
80
- } else {
81
- result = result.replace(template, value2);
82
- }
83
- } else {
84
- result = result.replace(template, defaultValue);
85
- }
86
- if (result === runningParsed[key]) {
87
- break;
88
- }
89
- regex.lastIndex = 0;
90
- }
91
- return result;
92
- }
93
- __name(expandValue, "expandValue");
94
- function expand2(options) {
95
- const runningParsed = {};
96
- let processEnv = process.env;
97
- if (options && options.processEnv != null) {
98
- processEnv = options.processEnv;
99
- }
100
- for (const key in options.parsed) {
101
- let value = options.parsed[key];
102
- if (processEnv[key] && processEnv[key] !== value) {
103
- value = processEnv[key];
104
- } else {
105
- value = expandValue(value, processEnv, runningParsed);
106
- }
107
- options.parsed[key] = _resolveEscapeSequences(value);
108
- runningParsed[key] = _resolveEscapeSequences(value);
109
- }
110
- for (const processKey in options.parsed) {
111
- processEnv[processKey] = options.parsed[processKey];
112
- }
113
- return options;
114
- }
115
- __name(expand2, "expand");
116
- module2.exports.expand = expand2;
117
- }
118
- });
119
-
120
31
  // src/fs/index.ts
121
32
  var fs_exports = {};
122
33
  __export(fs_exports, {
123
34
  default: () => Fs
124
35
  });
125
36
  module.exports = __toCommonJS(fs_exports);
126
- init_cjs_shims();
127
37
  var import_child_process = require("child_process");
128
38
  var import_fs = __toESM(require("fs"), 1);
129
39
  var import_promises = __toESM(require("fs/promises"), 1);
130
40
  var import_path = require("path");
131
41
  var dotenv = __toESM(require("dotenv"), 1);
132
- var import_dotenv_expand = __toESM(require_main(), 1);
42
+ var import_dotenv_expand = __toESM(require("dotenv-expand"), 1);
133
43
  var import_sharp = __toESM(require("sharp"), 1);
44
+
45
+ // src/url/index.ts
46
+ var UrlService = class {
47
+ static {
48
+ __name(this, "UrlService");
49
+ }
50
+ URL_REGEX = /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
51
+ parseUrl(url) {
52
+ const parsed = this.URL_REGEX.exec(url);
53
+ if (parsed) {
54
+ return {
55
+ href: parsed[0],
56
+ protocol: parsed[1] ?? "",
57
+ baseUrl: `${parsed[1]}${parsed[3]}`,
58
+ host: parsed[4] ?? "",
59
+ pathname: parsed[5] ?? "",
60
+ search: parsed[6] ?? "",
61
+ hash: parsed[8] ?? ""
62
+ };
63
+ } else return null;
64
+ }
65
+ };
66
+
67
+ // src/mime/index.ts
68
+ var extMimeMap = {
69
+ aac: ["audio/aac"],
70
+ abw: ["application/x-abiword"],
71
+ aces: ["image/aces"],
72
+ apng: ["image/apng"],
73
+ arc: ["application/x-freearc"],
74
+ avci: ["image/avci"],
75
+ avif: ["image/avif"],
76
+ avi: ["video/x-msvideo"],
77
+ azw: ["application/vnd.amazon.ebook"],
78
+ bin: ["application/octet-stream"],
79
+ bmp: ["image/bmp"],
80
+ bz: ["application/x-bzip"],
81
+ bz2: ["application/x-bzip2"],
82
+ cda: ["application/x-cdf"],
83
+ cjs: ["application/node", "text/javascript"],
84
+ csh: ["application/x-csh"],
85
+ css: ["text/css"],
86
+ csv: ["text/csv"],
87
+ doc: ["application/msword"],
88
+ docx: [
89
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
90
+ ],
91
+ dpx: ["image/dpx"],
92
+ emf: ["image/emf"],
93
+ eot: ["application/vnd.ms-fontobject"],
94
+ epub: ["application/epub+zip"],
95
+ gif: ["image/gif"],
96
+ glb: ["model/gltf-binary"],
97
+ gltf: ["model/gltf+json"],
98
+ gz: ["application/x-gzip", "application/gzip"],
99
+ hjif: ["haptics/hjif"],
100
+ hmpg: ["haptics/hmpg"],
101
+ htm: ["text/html"],
102
+ html: ["text/html"],
103
+ ico: ["image/vnd.microsoft.icon"],
104
+ ics: ["text/calendar"],
105
+ ivs: ["haptics/ivs"],
106
+ jar: ["application/java-archive"],
107
+ jpeg: ["image/jpeg"],
108
+ jpg: ["image/jpeg"],
109
+ js: ["application/node", "text/javascript"],
110
+ json: ["application/json"],
111
+ jsonld: ["application/ld+json"],
112
+ ktx: ["image/ktx"],
113
+ ktx2: ["image/ktx2"],
114
+ m3u8: ["application/vnd.apple.mpegurl"],
115
+ m4a: ["audio/mp4"],
116
+ m4v: ["video/mp4"],
117
+ md: ["text/markdown"],
118
+ mdx: ["application/x-mdx"],
119
+ mid: ["audio/midi"],
120
+ midi: ["audio/x-midi"],
121
+ mjs: ["text/javascript"],
122
+ mp3: ["audio/mpeg"],
123
+ mp4: ["video/mp4"],
124
+ mpeg: ["video/mpeg"],
125
+ mpkg: ["application/vnd.apple.installer+xml"],
126
+ ndjson: ["application/x-ndjson"],
127
+ obj: ["application/octet-stream", "text/plain", "model/obj"],
128
+ odp: ["application/vnd.oasis.opendocument.presentation"],
129
+ ods: ["application/vnd.oasis.opendocument.spreadsheet"],
130
+ odt: ["application/vnd.oasis.opendocument.text"],
131
+ oga: ["audio/ogg"],
132
+ ogg: ["audio/ogg"],
133
+ ogv: ["video/ogg"],
134
+ ogx: ["application/ogg"],
135
+ opus: ["audio/ogg"],
136
+ otf: ["font/otf"],
137
+ png: ["image/png"],
138
+ pdf: ["application/pdf"],
139
+ php: ["application/x-httpd-php"],
140
+ pkpass: ["application/vnd.apple.pkpass"],
141
+ ppt: ["application/vnd.ms-powerpoint"],
142
+ pptx: [
143
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation"
144
+ ],
145
+ py: ["text/x-python"],
146
+ pyc: ["application/x-python-code"],
147
+ rar: ["application/vnd.rar"],
148
+ rtf: ["application/rtf"],
149
+ sh: ["application/x-sh"],
150
+ sql: ["application/sql"],
151
+ svg: ["image/svg+xml"],
152
+ tar: ["application/x-tar"],
153
+ tif: ["image/tiff"],
154
+ tiff: ["image/tiff"],
155
+ toml: ["application/toml"],
156
+ ts: ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"],
157
+ ttf: ["application/font-sfnt", "font/ttf"],
158
+ txt: ["text/plain"],
159
+ usdz: ["model/vnd.usdz+zip"],
160
+ vsd: ["application/vnd.visio"],
161
+ vtt: ["text/vtt"],
162
+ wasm: ["application/wasm"],
163
+ wav: ["audio/wav"],
164
+ weba: ["video/webm"],
165
+ webp: ["image/webp"],
166
+ woff: ["font/woff"],
167
+ woff2: ["font/woff2"],
168
+ xhtml: ["application/xhtml+xml"],
169
+ xls: ["application/vnd.ms-excel"],
170
+ xlsx: ["application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"],
171
+ xml: ["application/xml"],
172
+ xul: ["application/vnd.mozilla.xul+xml"],
173
+ yaml: ["application/yaml"],
174
+ yml: ["application/yaml"],
175
+ zip: ["application/zip", "application/x-zip-compressed"],
176
+ "3gp": ["video/3gpp"],
177
+ "3g2": ["video/3gpp2"],
178
+ "7z": ["application/x-7z-compressed"]
179
+ };
180
+ var MimeService = class extends UrlService {
181
+ static {
182
+ __name(this, "MimeService");
183
+ }
184
+ constructor() {
185
+ super();
186
+ }
187
+ mimeTypeObj = extMimeMap;
188
+ assetType(url) {
189
+ const parsed = this.parseUrl(url);
190
+ if (!parsed) return void 0;
191
+ const ext = parsed.pathname.split(/([.])/g)?.reverse()?.[0]?.toLowerCase();
192
+ return ext && ext in this.mimeTypeObj ? ext : void 0;
193
+ }
194
+ getMimes(ext) {
195
+ return this.mimeTypeObj[ext];
196
+ }
197
+ getMimeFor(ext, opts) {
198
+ const mimes = this.getMimes(ext);
199
+ if (mimes.length === 1) return mimes[0];
200
+ if (opts?.type) {
201
+ const found = mimes.find((mime) => mime.startsWith(opts.type + "/"));
202
+ return found ?? mimes[0];
203
+ }
204
+ return mimes[0];
205
+ }
206
+ isMimeFor(ext, mime) {
207
+ return this.getMimes(ext).find((s) => s === mime);
208
+ }
209
+ getMimeTypeForPath(path, opts) {
210
+ const ext = this.assetType(path);
211
+ if (!ext) return "application/octet-stream";
212
+ return this.getMimeFor(ext, opts);
213
+ }
214
+ };
215
+
216
+ // src/fs/index.ts
134
217
  dotenv.config();
135
- var Fs = class {
218
+ var Fs = class extends MimeService {
136
219
  constructor(cwd) {
220
+ super();
137
221
  this.cwd = cwd;
138
222
  }
139
223
  static {
140
224
  __name(this, "Fs");
141
225
  }
142
- extractTuple(obj, props) {
143
- return [props, obj[props]];
144
- }
145
- sort(obj, order) {
146
- return Object.fromEntries(
147
- Object.entries(obj).sort(
148
- ([a, _aa], [b, _bb]) => order === "DESC" ? b.localeCompare(a) - a.localeCompare(b) : a.localeCompare(b) - b.localeCompare(a)
149
- )
150
- );
151
- }
152
- excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
153
- const resolve2 = Object.fromEntries(
154
- Object.entries(obj).map(([key, val]) => {
155
- if (props.includes(key)) {
156
- return ["omit", "omit"];
157
- } else return [key, val];
158
- }).filter(([t, _v]) => /omit/.test(t) === false)
159
- );
160
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
161
- }, "excludeTargeted");
162
- includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
163
- const resolve2 = Object.fromEntries(
164
- props.map((val) => this.extractTuple(obj, val))
165
- );
166
- return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
167
- }, "includeTargeted");
168
226
  get myEnv() {
169
227
  return dotenv.config({ processEnv: {} });
170
228
  }
171
229
  parseDotEnv() {
172
230
  return import_dotenv_expand.default.expand(this.myEnv);
173
231
  }
174
- omitFields(target, keys) {
175
- let obj = target;
176
- keys.forEach((t) => {
177
- if (t in obj) {
178
- delete obj[t];
179
- return obj;
180
- } else {
181
- return obj;
182
- }
183
- });
184
- return obj;
185
- }
186
- omitTargetedFields(targ, keys) {
187
- return { ...this.omitFields(targ, keys) };
188
- }
189
232
  exists(target) {
190
233
  if (!/\//gm.test(target))
191
234
  return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
192
235
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
193
236
  }
194
- arrToArrOfArrs = /* @__PURE__ */ __name(({
195
- arrToFragment = Array.of(),
196
- arrOfArrsAggregator = Array.of(),
197
- interval
198
- }) => new Promise(
199
- (resolve2, _reject) => resolve2(
200
- ((interval2) => {
201
- for (let i = 0; i <= arrToFragment.length; i++) {
202
- if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
203
- let segment = arrToFragment.slice(i, i + interval2);
204
- arrOfArrsAggregator.push(segment);
205
- }
206
- }
207
- })(interval)
208
- )
209
- ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
210
237
  wait(ms) {
211
238
  return new Promise((resolve2) => setTimeout(resolve2, ms));
212
239
  }
213
- countsSorter = /* @__PURE__ */ __name(({
214
- counter,
215
- keySort,
216
- valSort
217
- }) => Object.fromEntries(
218
- Object.entries(counter).sort(
219
- ([aStr, _aNum], [bStr, _bNum]) => keySort === "DESC" ? bStr.localeCompare(aStr) - aStr.localeCompare(bStr) : aStr.localeCompare(bStr) - bStr.localeCompare(aStr)
220
- ).sort(
221
- ([_aStr, aNum], [_bStr, bNum]) => valSort === "ASC" ? aNum - bNum : bNum - aNum
222
- )
223
- ), "countsSorter");
224
240
  handleBuffStrArrUnion(arr) {
225
241
  return arr.map(
226
242
  (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
@@ -236,13 +252,14 @@ var Fs = class {
236
252
  return this.handleBuffStrArrUnion(
237
253
  import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), options)
238
254
  );
239
- } else
255
+ } else {
240
256
  return this.handleBuffStrArrUnion(
241
257
  import_fs.default.readdirSync(
242
258
  (0, import_path.relative)(this.cwd ??= process.cwd(), path),
243
259
  options
244
260
  )
245
261
  );
262
+ }
246
263
  }
247
264
  executeCommand = /* @__PURE__ */ __name(({
248
265
  command,
@@ -250,16 +267,6 @@ var Fs = class {
250
267
  }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString(
251
268
  "utf-8"
252
269
  ), "executeCommand");
253
- fileGenTimestamp(d) {
254
- const date = d.toISOString();
255
- return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
256
- }
257
- configFileGenTimestamp(d) {
258
- return this.fileGenTimestamp(d).replace("/*", "#").replace("*/", "");
259
- }
260
- mdFileGenTimestamp(d) {
261
- return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
262
- }
263
270
  existsSync(path) {
264
271
  if (!/\//gm.test(path))
265
272
  return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, path)));
@@ -317,9 +324,7 @@ var Fs = class {
317
324
  } finally {
318
325
  return await import_promises.default.writeFile(
319
326
  (0, import_path.relative)(this.cwd ?? process.cwd(), path),
320
- Buffer.from(
321
- Buffer.from(data).toJSON().data
322
- ),
327
+ Buffer.from(Buffer.from(data).toJSON().data),
323
328
  options
324
329
  );
325
330
  }
@@ -339,6 +344,13 @@ var Fs = class {
339
344
  throw new Error(`input path ${path} does not exist`);
340
345
  }
341
346
  }
347
+ rmFile(filePath) {
348
+ if (this.existsSync(filePath)) {
349
+ if (this.isRootPathTargeted(filePath)) {
350
+ import_fs.default.rmSync((0, import_path.resolve)((0, import_path.join)(this.cwd, filePath)));
351
+ } else import_fs.default.rmSync((0, import_path.resolve)(this.cwd, filePath));
352
+ } else return;
353
+ }
342
354
  async rmdir(dir, options) {
343
355
  const resolved = (0, import_path.relative)(this.cwd, dir);
344
356
  if (this.dirExists(dir)) {
@@ -347,7 +359,7 @@ var Fs = class {
347
359
  throw new Error(`directory ${resolved} does not exist`);
348
360
  }
349
361
  }
350
- rm(dir) {
362
+ rmDirSync(dir) {
351
363
  const resolved = (0, import_path.resolve)(this.cwd, dir);
352
364
  if (this.dirExists(dir)) {
353
365
  return import_fs.default.rm(resolved, { force: true, recursive: true }, (err) => {
@@ -365,218 +377,26 @@ var Fs = class {
365
377
  dirContainsDir(readDir, targetDir, options) {
366
378
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
367
379
  }
368
- /* begin url */
369
- isServerSide() {
370
- return typeof window === "undefined";
371
- }
372
- isBase64(str) {
373
- if (!str) {
374
- return false;
375
- }
376
- return /^([A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{3}=|[A-Za-z0-9+/]{2}==)?\n?$/.test(
377
- str.replace(/\n/g, "")
378
- );
379
- }
380
- previewRegex = /\/preview(\/\w|\?)/;
381
- isPreviewPath(uri) {
382
- if (typeof uri === "string") {
383
- return this.previewRegex.test(uri);
384
- }
385
- return false;
386
- }
387
- // eslint-disable-next-line @typescript-eslint/class-literal-property-style
388
- get URL_REGEX() {
389
- return /^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;
390
- }
391
- parseUrl(url) {
392
- const parsed = this.URL_REGEX.exec(url);
393
- return {
394
- href: parsed[0],
395
- protocol: parsed[1] ?? "",
396
- baseUrl: `${parsed[1]}${parsed[3]}`,
397
- host: parsed[4] ?? "",
398
- pathname: parsed[5] ?? "",
399
- search: parsed[6] ?? "",
400
- hash: parsed[8] ?? ""
401
- };
402
- }
403
- /* end url */
404
- get cjsVal() {
405
- return ["application/node", "text/javascript"].reduce(
406
- (union) => union
407
- );
408
- }
409
- get gzVal() {
410
- return ["application/x-gzip", "application/gzip"].reduce(
411
- (union) => union
412
- );
413
- }
414
- get jsVal() {
415
- return ["application/node", "text/javascript"].reduce(
416
- (union) => union
417
- );
418
- }
419
- get objVal() {
420
- return ["application/octet-stream", "text/plain", "model/obj"].reduce((union) => union);
421
- }
422
- get tsVal() {
423
- return ["text/typescript", "video/mp2t", "video/vnd.dlna.mpeg-tts"].reduce((union) => union);
424
- }
425
- get ttfVal() {
426
- return ["application/font-sfnt", "font/ttf"].reduce(
427
- (union) => union
428
- );
429
- }
430
- get zipVal() {
431
- return ["application/zip", "application/x-zip-compressed"].reduce((union) => union);
432
- }
433
- get mimeTypeObj() {
434
- return {
435
- aac: "audio/aac",
436
- abw: "application/x-abiword",
437
- aces: "image/aces",
438
- apng: "image/apng",
439
- arc: "application/x-freearc",
440
- avci: "image/avci",
441
- avif: "image/avif",
442
- avi: "video/x-msvideo",
443
- azw: "application/vnd.amazon.ebook",
444
- bin: "application/octet-stream",
445
- bmp: "image/bmp",
446
- bz: "application/x-bzip",
447
- bz2: "application/x-bzip2",
448
- cda: "application/x-cdf",
449
- cjs: this.cjsVal,
450
- csh: "application/x-csh",
451
- css: "text/css",
452
- csv: "text/csv",
453
- doc: "application/msword",
454
- docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
455
- dpx: "image/dpx",
456
- emf: "image/emf",
457
- eot: "application/vnd.ms-fontobject",
458
- epub: "application/epub+zip",
459
- gif: "image/gif",
460
- glb: "model/gltf-binary",
461
- gltf: "model/gltf+json",
462
- gz: this.gzVal,
463
- hjif: "haptics/hjif",
464
- hmpg: "haptics/hmpg",
465
- htm: "text/html",
466
- html: "text/html",
467
- ico: "image/vnd.microsoft.icon",
468
- ics: "text/calendar",
469
- ivs: "haptics/ivs",
470
- jar: "application/java-archive",
471
- jpeg: "image/jpeg",
472
- jpg: "image/jpeg",
473
- js: this.jsVal,
474
- json: "application/json",
475
- jsonld: "application/ld+json",
476
- ktx: "image/ktx",
477
- ktx2: "image/ktx2",
478
- m3u8: "application/vnd.apple.mpegurl",
479
- m4a: "audio/mp4",
480
- m4v: "video/mp4",
481
- md: "text/markdown",
482
- mdx: "application/x-mdx",
483
- mid: "audio/midi",
484
- midi: "audio/x-midi",
485
- mjs: "text/javascript",
486
- mp3: "audio/mpeg",
487
- mp4: "video/mp4",
488
- mpeg: "video/mpeg",
489
- mpkg: "application/vnd.apple.installer+xml",
490
- ndjson: "application/x-ndjson",
491
- obj: this.objVal,
492
- odp: "application/vnd.oasis.opendocument.presentation",
493
- ods: "application/vnd.oasis.opendocument.spreadsheet",
494
- odt: "application/vnd.oasis.opendocument.text",
495
- oga: "audio/ogg",
496
- ogg: "audio/ogg",
497
- ogv: "video/ogg",
498
- ogx: "application/ogg",
499
- opus: "audio/ogg",
500
- otf: "font/otf",
501
- png: "image/png",
502
- pdf: "application/pdf",
503
- php: "application/x-httpd-php",
504
- pkpass: "application/vnd.apple.pkpass",
505
- ppt: "application/vnd.ms-powerpoint",
506
- pptx: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
507
- py: "text/x-python",
508
- pyc: "application/x-python-code",
509
- rar: "application/vnd.rar",
510
- rtf: "application/rtf",
511
- sh: "application/x-sh",
512
- sql: "application/sql",
513
- svg: "image/svg+xml",
514
- tar: "application/x-tar",
515
- tif: "image/tiff",
516
- tiff: "image/tiff",
517
- toml: "application/toml",
518
- ts: this.tsVal,
519
- ttf: this.ttfVal,
520
- txt: "text/plain",
521
- usdz: "model/vnd.usdz+zip",
522
- vsd: "application/vnd.visio",
523
- vtt: "text/vtt",
524
- wasm: "application/wasm",
525
- wav: "audio/wav",
526
- weba: "video/webm",
527
- webp: "image/webp",
528
- woff: "font/woff",
529
- woff2: "font/woff2",
530
- xhtml: "application/xhtml+xml",
531
- xls: "application/vnd.ms-excel",
532
- xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
533
- xml: "application/xml",
534
- xul: "application/vnd.mozilla.xul+xml",
535
- yaml: "application/yaml",
536
- yml: "application/yaml",
537
- zip: this.zipVal,
538
- "3gp": "video/3gpp",
539
- "3g2": "video/3gpp2",
540
- "7z": "application/x-7z-compressed"
541
- };
542
- }
543
- assetType(url) {
544
- const u = this.parseUrl(url);
545
- return u.pathname?.split(/([.])/gim)?.reverse()?.[0];
546
- }
547
- getMime(input) {
548
- return this.mimeTypeObj[input];
549
- }
550
- hmm = /* @__PURE__ */ __name((input) => {
551
- return this.mimeTypeObj[input];
552
- }, "hmm");
553
380
  async assetToBuffer(path) {
554
381
  const [fetcher] = await Promise.all([
555
382
  fetch(path).then((t) => t.arrayBuffer())
556
383
  ]);
557
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(fetcher).toString("base64")}`;
558
- const extension = this.assetType(path);
384
+ const mime = this.getMimeTypeForPath(path);
385
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(fetcher).toString("base64")}`;
386
+ const extension = this.assetType(path) ?? "txt";
559
387
  return {
560
388
  b64encodedData,
561
389
  extension
562
390
  };
563
391
  }
564
392
  async assetToBufferView(path) {
565
- const p = this.parseUrl(path);
566
- const doesUrlPathContainFileExtension = /\./g.test(
567
- p.pathname.split(/\//g).reverse()[0] ?? ""
568
- );
569
- if (doesUrlPathContainFileExtension === false)
570
- console.warn(
571
- `no file extension detected in input url ${path}, attempting fetch`
572
- );
573
393
  const response = await fetch(path);
574
394
  if (!response.ok) {
575
395
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
576
396
  }
577
397
  const reader = response.body?.getReader();
578
398
  if (reader) {
579
- const chunks = [];
399
+ const chunks = Array.of();
580
400
  while (true) {
581
401
  const { done, value } = await reader.read();
582
402
  if (done) break;
@@ -589,12 +409,14 @@ var Fs = class {
589
409
  completeBuffer.set(chunk, offset);
590
410
  offset += chunk.length;
591
411
  }
592
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
412
+ const mime = this.getMimeTypeForPath(path);
413
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(completeBuffer).toString("base64")}`;
593
414
  const extension = this.assetType(path);
594
415
  return { b64encodedData, extension };
595
416
  } else {
596
417
  const arrayBuffer = await response.arrayBuffer();
597
- const b64encodedData = `data:${this.getMime(this.assetType(path))};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
418
+ const mime = this.getMimeTypeForPath(path);
419
+ const b64encodedData = `data:${mime};base64, ${Buffer.from(arrayBuffer).toString("base64")}`;
598
420
  const extension = this.assetType(path);
599
421
  return { b64encodedData, extension };
600
422
  }
@@ -605,84 +427,12 @@ var Fs = class {
605
427
  return formatting;
606
428
  } else return f.substring(0, 1).toUpperCase().concat(f.substring(1));
607
429
  }
608
- range(from, to) {
609
- const values = Array.of();
610
- for (let i = from; i < to; i++) {
611
- values.push(i);
612
- }
613
- return values;
614
- }
615
- isPrimeNumber = /* @__PURE__ */ __name((n) => {
616
- for (let i = 2; n > i; i++) {
617
- if (n % i === 0) {
618
- return false;
619
- }
620
- }
621
- return n > 1;
622
- }, "isPrimeNumber");
623
- acceptor = /* @__PURE__ */ __name((num) => [...Array(num !== 0 ? num : this.range(num = -101, num = 101)).keys()].reverse().filter(this.isPrimeNumber), "acceptor");
624
- chunkArray(arr, maxChunkLength) {
625
- const chunks = Array.of();
626
- let currentChunkLength = 0;
627
- let currentChunk = Array.of();
628
- for (const [index, val] of arr.entries()) {
629
- if (val.length + currentChunkLength >= maxChunkLength) {
630
- if (currentChunk.length) {
631
- chunks.push(currentChunk);
632
- }
633
- currentChunkLength = val.length;
634
- currentChunk = [val];
635
- } else {
636
- currentChunk.push(val);
637
- currentChunkLength += val.length + 1;
638
- }
639
- if (arr.length === index + 1) {
640
- chunks.push(currentChunk);
641
- }
642
- }
643
- return chunks.length ? chunks : [arr];
644
- }
645
- b64ToBlob(b64Data) {
646
- {
647
- const sliceSize = 512;
648
- const typeMatch = b64Data.match(
649
- /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
650
- );
651
- const type = typeMatch?.[1];
652
- if (!typeMatch) {
653
- throw new Error(`${b64Data} is not a valid data Url`);
654
- }
655
- const byteCharacters = Buffer.from(b64Data, "base64").toString("utf-8");
656
- const byteArrays = Array.of();
657
- for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
658
- const slice = byteCharacters.slice(offset, offset + sliceSize);
659
- const byteNumbers = Array.of();
660
- byteNumbers.push(slice.length);
661
- for (let i = 0; i < slice.length; i++) {
662
- byteNumbers[i] = slice.charCodeAt(i);
663
- }
664
- const byteArray = new Uint8Array(byteNumbers);
665
- byteArrays.push(byteArray);
666
- }
667
- const blob = new Blob(byteArrays, { type });
668
- return blob;
669
- }
670
- }
671
430
  cleanDataUrl(props) {
672
431
  return props.replace(
673
432
  /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
674
433
  ""
675
434
  );
676
435
  }
677
- /**
678
- * public cleanDataUrl<const C extends string>(props: C) {
679
- return props.replace(
680
- /^data:(?:image|application|video|text|font|model|audio|haptics|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
681
- ""
682
- );
683
- }
684
-
685
- */
686
436
  /**
687
437
  *
688
438
  * @param inputUrl remote url to fetch data from
@@ -765,47 +515,5 @@ var Fs = class {
765
515
  return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
766
516
  } else return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
767
517
  }
768
- // public async convertImage<
769
- // const L extends "local" | "remote",
770
- // const F extends "webp" | "avif" | "jpg" | "png",
771
- // const I extends string,
772
- // const O extends string
773
- // >(isLocal: L, inputUrl: I, outputPath: O, useDetectedExtension = true) {
774
- // if (isLocal === "remote") {
775
- // try {
776
- // const result = await this.assetToBufferView(inputUrl);
777
- // const cleanData = this.cleanDataUrl(result.b64encodedData);
778
- // const imageBuffer = Buffer.from(cleanData, "base64");
779
- // const s = this.imageTransform({format: "webp", target: imageBuffer, quality: 100, resize: {options: {width: 1.2, height: 1.2}}} )
780
- // const formattedPath = useDetectedExtension
781
- // ? `${outputPath}.${result.extension}`
782
- // : outputPath;
783
- // if (/\./g.test(formattedPath) === false) {
784
- // throw new Error(
785
- // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
786
- // );
787
- // }
788
- // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
789
- // } catch (err) {
790
- // return console.error(err);
791
- // }
792
- // } else {
793
- // try {
794
- // const result = await this.assetToBufferView(inputUrl);
795
- // const cleanData = this.cleanDataUrl(result.b64encodedData);
796
- // const formattedPath = useDetectedExtension
797
- // ? `${outputPath}.${result.extension}`
798
- // : outputPath;
799
- // if (/\./g.test(formattedPath) === false) {
800
- // throw new Error(
801
- // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
802
- // );
803
- // }
804
- // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
805
- // } catch (err) {
806
- // return console.error(err);
807
- // }
808
- // }
809
- // }
810
518
  };
811
519
  //# sourceMappingURL=index.cjs.map