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