@d0paminedriven/fs 1.0.0 → 3.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
@@ -133,6 +133,7 @@ var import_promises = __toESM(require("fs/promises"), 1);
133
133
  var import_path = require("path");
134
134
  var dotenv = __toESM(require("dotenv"), 1);
135
135
  var import_dotenv_expand = __toESM(require_main(), 1);
136
+ var import_sharp = __toESM(require("sharp"), 1);
136
137
  dotenv.config();
137
138
  var Fs = class {
138
139
  constructor(cwd) {
@@ -152,20 +153,20 @@ var Fs = class {
152
153
  );
153
154
  }
154
155
  excludeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
155
- const resolve = Object.fromEntries(
156
+ const resolve2 = Object.fromEntries(
156
157
  Object.entries(obj).map(([key, val]) => {
157
158
  if (props.includes(key)) {
158
159
  return ["omit", "omit"];
159
160
  } else return [key, val];
160
161
  }).filter(([t, _v]) => /omit/.test(t) === false)
161
162
  );
162
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
163
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
163
164
  }, "excludeTargeted");
164
165
  includeTargeted = /* @__PURE__ */ __name((obj, props, sort) => {
165
- const resolve = Object.fromEntries(
166
+ const resolve2 = Object.fromEntries(
166
167
  props.map((val) => this.extractTuple(obj, val))
167
168
  );
168
- return typeof sort !== "undefined" ? this.sort(resolve, sort) : resolve;
169
+ return typeof sort !== "undefined" ? this.sort(resolve2, sort) : resolve2;
169
170
  }, "includeTargeted");
170
171
  get myEnv() {
171
172
  return dotenv.config({ processEnv: {} });
@@ -189,6 +190,7 @@ var Fs = class {
189
190
  return { ...this.omitFields(targ, keys) };
190
191
  }
191
192
  exists(target) {
193
+ if (!/\//gm.test(target)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, target)));
192
194
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), target));
193
195
  }
194
196
  arrToArrOfArrs = /* @__PURE__ */ __name(({
@@ -196,7 +198,7 @@ var Fs = class {
196
198
  arrOfArrsAggregator = Array.of(),
197
199
  interval
198
200
  }) => new Promise(
199
- (resolve, _reject) => resolve(
201
+ (resolve2, _reject) => resolve2(
200
202
  ((interval2) => {
201
203
  for (let i = 0; i <= arrToFragment.length; i++) {
202
204
  if ((i % interval2 === 0 || i === 0) && i <= arrToFragment.length) {
@@ -208,7 +210,7 @@ var Fs = class {
208
210
  )
209
211
  ).then((_) => arrOfArrsAggregator), "arrToArrOfArrs");
210
212
  wait(ms) {
211
- return new Promise((resolve) => setTimeout(resolve, ms));
213
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
212
214
  }
213
215
  countsSorter = /* @__PURE__ */ __name(({
214
216
  counter,
@@ -226,8 +228,15 @@ var Fs = class {
226
228
  (v) => Buffer.isBuffer(v) ? Buffer.from(v).toString("utf-8") : v
227
229
  );
228
230
  }
231
+ isRootPathTargeted(path) {
232
+ if (/^(?:\.\/|\.|\/|root|\.\.\/|~\/\.?|cwd|\.\/\.)$/g.test(path)) {
233
+ return true;
234
+ } else return false;
235
+ }
229
236
  readDir(path, options) {
230
- return this.handleBuffStrArrUnion(
237
+ if (this.isRootPathTargeted(path)) {
238
+ return this.handleBuffStrArrUnion(import_fs.default.readdirSync((0, import_path.resolve)((0, import_path.join)(this.cwd, "./")), options));
239
+ } else return this.handleBuffStrArrUnion(
231
240
  import_fs.default.readdirSync(
232
241
  (0, import_path.relative)(this.cwd ??= process.cwd(), path),
233
242
  options
@@ -237,9 +246,7 @@ var Fs = class {
237
246
  executeCommand = /* @__PURE__ */ __name(({
238
247
  command,
239
248
  ...options
240
- }) => Buffer.from(
241
- Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data)
242
- ).toString("utf-8"), "executeCommand");
249
+ }) => Buffer.from((0, import_child_process.execSync)(command, { ...options }).toJSON().data).toString("utf-8"), "executeCommand");
243
250
  fileGenTimestamp(d) {
244
251
  const date = d.toISOString();
245
252
  return `/* file-autogenerated by @d0paminedriven/fs on ${date.split(/([T])/gm)?.[0]} at ${date.split(/([T])/gm)[2]?.split(/([Z])/gm)?.[0]} UTC */`;
@@ -251,6 +258,7 @@ var Fs = class {
251
258
  return this.fileGenTimestamp(d).replace("/*", "<!--").replace("*/", "-->");
252
259
  }
253
260
  existsSync(path) {
261
+ if (!/\//gm.test(path)) return import_fs.default.existsSync((0, import_path.resolve)((0, import_path.join)(this.cwd, path)));
254
262
  return import_fs.default.existsSync((0, import_path.relative)(this.cwd ?? process.cwd(), path));
255
263
  }
256
264
  pathHandler(path) {
@@ -313,18 +321,11 @@ var Fs = class {
313
321
  }
314
322
  }, "writeFileAsync");
315
323
  fileToBuffer = /* @__PURE__ */ __name((path) => Buffer.from(
316
- Buffer.from(
317
- import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
318
- )
324
+ import_fs.default.readFileSync((0, import_path.relative)(this.cwd ?? process.cwd(), path)).toJSON().data
319
325
  ), "fileToBuffer");
320
326
  dirContainsDir(readDir, targetDir, options) {
321
327
  return this.readDir(readDir, options).filter((t) => t.split(".").length === 1).includes(targetDir);
322
328
  }
323
- parseJsonBuffer(p) {
324
- return JSON.parse(
325
- Buffer.from(Buffer.from(p).toJSON().data).toString("utf-8")
326
- );
327
- }
328
329
  /* begin url */
329
330
  isServerSide() {
330
331
  return typeof window === "undefined";
@@ -361,11 +362,21 @@ var Fs = class {
361
362
  };
362
363
  }
363
364
  /* end url */
365
+ get cjsVal() {
366
+ return ["application/node", "text/javascript"].reduce(
367
+ (union) => union
368
+ );
369
+ }
364
370
  get gzVal() {
365
371
  return ["application/x-gzip", "application/gzip"].reduce(
366
372
  (union) => union
367
373
  );
368
374
  }
375
+ get jsVal() {
376
+ return ["application/node", "text/javascript"].reduce(
377
+ (union) => union
378
+ );
379
+ }
369
380
  get objVal() {
370
381
  return ["application/octet-stream", "text/plain", "model/obj"].reduce((union) => union);
371
382
  }
@@ -384,8 +395,10 @@ var Fs = class {
384
395
  return {
385
396
  aac: "audio/aac",
386
397
  abw: "application/x-abiword",
398
+ aces: "image/aces",
387
399
  apng: "image/apng",
388
400
  arc: "application/x-freearc",
401
+ avci: "image/avci",
389
402
  avif: "image/avif",
390
403
  avi: "video/x-msvideo",
391
404
  azw: "application/vnd.amazon.ebook",
@@ -394,26 +407,31 @@ var Fs = class {
394
407
  bz: "application/x-bzip",
395
408
  bz2: "application/x-bzip2",
396
409
  cda: "application/x-cdf",
397
- cjs: "application/javascript",
410
+ cjs: this.cjsVal,
398
411
  csh: "application/x-csh",
399
412
  css: "text/css",
400
413
  csv: "text/csv",
401
414
  doc: "application/msword",
402
415
  docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
416
+ dpx: "image/dpx",
417
+ emf: "image/emf",
403
418
  eot: "application/vnd.ms-fontobject",
404
419
  epub: "application/epub+zip",
405
420
  gif: "image/gif",
406
421
  glb: "model/gltf-binary",
407
422
  gltf: "model/gltf+json",
408
423
  gz: this.gzVal,
424
+ hjif: "haptics/hjif",
425
+ hmpg: "haptics/hmpg",
409
426
  htm: "text/html",
410
427
  html: "text/html",
411
428
  ico: "image/vnd.microsoft.icon",
412
429
  ics: "text/calendar",
430
+ ivs: "haptics/ivs",
413
431
  jar: "application/java-archive",
414
432
  jpeg: "image/jpeg",
415
433
  jpg: "image/jpeg",
416
- js: "text/javascript",
434
+ js: this.jsVal,
417
435
  json: "application/json",
418
436
  jsonld: "application/ld+json",
419
437
  m3u8: "application/vnd.apple.mpegurl",
@@ -450,13 +468,16 @@ var Fs = class {
450
468
  rar: "application/vnd.rar",
451
469
  rtf: "application/rtf",
452
470
  sh: "application/x-sh",
471
+ sql: "application/sql",
453
472
  svg: "image/svg+xml",
454
473
  tar: "application/x-tar",
455
474
  tif: "image/tiff",
456
475
  tiff: "image/tiff",
476
+ toml: "application/toml",
457
477
  ts: this.tsVal,
458
478
  ttf: this.ttfVal,
459
479
  txt: "text/plain",
480
+ usdz: "model/vnd.usdz+zip",
460
481
  vsd: "application/vnd.visio",
461
482
  vtt: "text/vtt",
462
483
  wasm: "application/wasm",
@@ -470,6 +491,8 @@ var Fs = class {
470
491
  xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
471
492
  xml: "application/xml",
472
493
  xul: "application/vnd.mozilla.xul+xml",
494
+ yaml: "application/yaml",
495
+ yml: "application/yaml",
473
496
  zip: this.zipVal,
474
497
  "3gp": "video/3gpp",
475
498
  "3g2": "video/3gpp2",
@@ -498,6 +521,12 @@ var Fs = class {
498
521
  };
499
522
  }
500
523
  async assetToBufferView(path) {
524
+ const p = this.parseUrl(path);
525
+ const doesUrlPathContainFileExtension = /\./g.test(
526
+ p.pathname.split(/\//g).reverse()[0] ?? ""
527
+ );
528
+ if (doesUrlPathContainFileExtension === false)
529
+ console.warn(`no file extension detected in input url ${path}, attempting fetch`);
501
530
  const response = await fetch(path);
502
531
  if (!response.ok) {
503
532
  throw new Error(`Failed to fetch asset: ${response.statusText}`);
@@ -574,7 +603,7 @@ var Fs = class {
574
603
  {
575
604
  const sliceSize = 512;
576
605
  const typeMatch = b64Data.match(
577
- /^data:(image|application|video|text|model|font)\/[A-Za-z0-9+-.]+;base64,/
606
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i
578
607
  );
579
608
  const type = typeMatch?.[1];
580
609
  if (!typeMatch) {
@@ -598,10 +627,19 @@ var Fs = class {
598
627
  }
599
628
  cleanDataUrl(props) {
600
629
  return props.replace(
601
- /^data:(image|application|video|text|font|model|audio)\/[A-Za-z0-9+-.]+;base64,/,
630
+ /^data:(?:image|application|haptics|video|text|font|model|audio|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
631
+ ""
632
+ );
633
+ }
634
+ /**
635
+ * public cleanDataUrl<const C extends string>(props: C) {
636
+ return props.replace(
637
+ /^data:(?:image|application|video|text|font|model|audio|haptics|multipart)\/[A-Za-z0-9+-.]+(?:;[^,]+)*;base64,/i,
602
638
  ""
603
639
  );
604
640
  }
641
+
642
+ */
605
643
  /**
606
644
  *
607
645
  * @param inputUrl remote url to fetch data from
@@ -621,7 +659,7 @@ var Fs = class {
621
659
  const formattedPath = useDetectedExtension ? `${outputPath}.${result.extension}` : outputPath;
622
660
  if (/\./g.test(formattedPath) === false) {
623
661
  throw new Error(
624
- "either add false as the third argument in `fetchRemoteWriteLocal` [input, output, use-detected-file-extension (defaults to true)]"
662
+ "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension) or provide an output path without a file extension"
625
663
  );
626
664
  }
627
665
  this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
@@ -629,6 +667,103 @@ var Fs = class {
629
667
  return console.error(err);
630
668
  }
631
669
  }
670
+ async fetchRemoteWriteLocalLargeFiles(inputUrl, outputPath, useDetectedExtension = true) {
671
+ const MAX_SAFE_IN_MEMORY_MB = 100;
672
+ try {
673
+ const head = await fetch(inputUrl, { method: "HEAD" });
674
+ const contentLength = head.headers.get("content-length");
675
+ const fileSizeMb = contentLength ? parseInt(contentLength, 10) / (1024 * 1024) : null;
676
+ const formattedPath = useDetectedExtension ? `${outputPath}.${this.assetType(inputUrl)}` : outputPath;
677
+ this.generateDirIfDNE(this.pathHandler(formattedPath), {
678
+ recursive: true
679
+ });
680
+ if (fileSizeMb !== null && fileSizeMb > MAX_SAFE_IN_MEMORY_MB) {
681
+ const res = await fetch(inputUrl);
682
+ if (!res.ok || !res.body) {
683
+ throw new Error(`Failed to fetch asset: ${res.statusText}`);
684
+ }
685
+ const writeStream = import_fs.default.createWriteStream(
686
+ (0, import_path.relative)(this.cwd ?? process.cwd(), formattedPath)
687
+ );
688
+ const reader = res.body.getReader();
689
+ const pump = /* @__PURE__ */ __name(async () => {
690
+ while (true) {
691
+ const { done, value } = await reader.read();
692
+ if (done) break;
693
+ writeStream.write(value);
694
+ }
695
+ writeStream.end();
696
+ }, "pump");
697
+ await pump();
698
+ return;
699
+ }
700
+ const result = await this.assetToBufferView(inputUrl);
701
+ const cleanData = this.cleanDataUrl(result.b64encodedData);
702
+ this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
703
+ } catch (err) {
704
+ console.error(`[fetchRemoteWriteLocal error]:`, err);
705
+ }
706
+ }
707
+ // USE fluent-ffmpeg for video/animated image transforms (apng, etc)
708
+ // https://www.npmjs.com/package/fluent-ffmpeg
709
+ // https://www.npmjs.com/package/@types/fluent-ffmpeg
710
+ async imageTransform({
711
+ format,
712
+ target,
713
+ quality = 80,
714
+ tint,
715
+ resize
716
+ }) {
717
+ if (tint && !resize) {
718
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).toBuffer();
719
+ } else if (!tint && resize) {
720
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
721
+ } else if (tint && resize) {
722
+ return await (0, import_sharp.default)(target).toFormat(format, { quality }).tint(tint).resize(resize.widthOrOptions, resize.height, resize.options).toBuffer();
723
+ } else return await (0, import_sharp.default)(target).toFormat(format, { quality }).toBuffer();
724
+ }
725
+ // public async convertImage<
726
+ // const L extends "local" | "remote",
727
+ // const F extends "webp" | "avif" | "jpg" | "png",
728
+ // const I extends string,
729
+ // const O extends string
730
+ // >(isLocal: L, inputUrl: I, outputPath: O, useDetectedExtension = true) {
731
+ // if (isLocal === "remote") {
732
+ // try {
733
+ // const result = await this.assetToBufferView(inputUrl);
734
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
735
+ // const imageBuffer = Buffer.from(cleanData, "base64");
736
+ // const s = this.imageTransform({format: "webp", target: imageBuffer, quality: 100, resize: {options: {width: 1.2, height: 1.2}}} )
737
+ // const formattedPath = useDetectedExtension
738
+ // ? `${outputPath}.${result.extension}`
739
+ // : outputPath;
740
+ // if (/\./g.test(formattedPath) === false) {
741
+ // throw new Error(
742
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
743
+ // );
744
+ // }
745
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
746
+ // } catch (err) {
747
+ // return console.error(err);
748
+ // }
749
+ // } else {
750
+ // try {
751
+ // const result = await this.assetToBufferView(inputUrl);
752
+ // const cleanData = this.cleanDataUrl(result.b64encodedData);
753
+ // const formattedPath = useDetectedExtension
754
+ // ? `${outputPath}.${result.extension}`
755
+ // : outputPath;
756
+ // if (/\./g.test(formattedPath) === false) {
757
+ // throw new Error(
758
+ // "either add false as the third argument in `fetchRemoteWriteLocal` (input, output, use-detected-file-extension)"
759
+ // );
760
+ // }
761
+ // this.withWs(formattedPath, Buffer.from(cleanData, "base64"));
762
+ // } catch (err) {
763
+ // return console.error(err);
764
+ // }
765
+ // }
766
+ // }
632
767
  };
633
768
  // Annotate the CommonJS export names for ESM import in node:
634
769
  0 && (module.exports = {
package/dist/index.d.cts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { default as Fs } from './fs/index.cjs';
2
2
  export { Abortable, ArrayBufferView, ArrayOrReadOnlyArray, BashEnv, BufferEncodingUnion, CoercionUnion, CommonExecOptions, CommonOptions, ConditionalPromise, ConditionalToRequired, Depth, Dict, Equal, ExcludeFieldEnumerable, ExecSyncOptions, ExecSyncOptionsWithBufferEncoding, ExecSyncOptionsWithStringEncoding, ExecuteCommandProps, Expect, Extends, FieldToConditionallyNever, IOType, InferDepth, InjectScriptsProps, MkDirOptions, MkDirSyncOptions, MkDirSyncProps, Mode, ObjEncodingOptions, OmitSrc, OpenMode, ParsedUrlInfo, ProcessEnv, ProcessEnvOptions, ReadDirOptions, ReadDirProps, RemoveFields, RequiredToConditional, Signals, StdioOptions, TypedArray, Unenumerate, UnwrapPromise, Without, WriteFileAsyncDataUnion, WriteFileAsyncOptions, WriteFileAsyncProps, WriteStreamDataShape, WriteStreamOptions, WriteStreamProps, XOR } from './types/index.cjs';
3
3
  import 'dotenv-expand';
4
+ import 'sharp';
4
5
  import 'stream';
5
6
  import 'buffer';
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export { default as Fs } from './fs/index.js';
2
2
  export { Abortable, ArrayBufferView, ArrayOrReadOnlyArray, BashEnv, BufferEncodingUnion, CoercionUnion, CommonExecOptions, CommonOptions, ConditionalPromise, ConditionalToRequired, Depth, Dict, Equal, ExcludeFieldEnumerable, ExecSyncOptions, ExecSyncOptionsWithBufferEncoding, ExecSyncOptionsWithStringEncoding, ExecuteCommandProps, Expect, Extends, FieldToConditionallyNever, IOType, InferDepth, InjectScriptsProps, MkDirOptions, MkDirSyncOptions, MkDirSyncProps, Mode, ObjEncodingOptions, OmitSrc, OpenMode, ParsedUrlInfo, ProcessEnv, ProcessEnvOptions, ReadDirOptions, ReadDirProps, RemoveFields, RequiredToConditional, Signals, StdioOptions, TypedArray, Unenumerate, UnwrapPromise, Without, WriteFileAsyncDataUnion, WriteFileAsyncOptions, WriteFileAsyncProps, WriteStreamDataShape, WriteStreamOptions, WriteStreamProps, XOR } from './types/index.js';
3
3
  import 'dotenv-expand';
4
+ import 'sharp';
4
5
  import 'stream';
5
6
  import 'buffer';
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  Fs
3
- } from "./chunk-MFKSUNKN.js";
3
+ } from "./chunk-SPP3NFBL.js";
4
4
  import {
5
5
  init_esm_shims
6
6
  } from "./chunk-I6PDZOED.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@d0paminedriven/fs",
3
- "version": "1.0.0",
3
+ "version": "3.0.0",
4
4
  "description": "convenient fs helpers",
5
5
  "publishConfig": {
6
6
  "access": "public"
@@ -35,15 +35,15 @@
35
35
  "./types": "./dist/types/index.js"
36
36
  },
37
37
  "dependencies": {
38
- "dotenv": "^16.4.7"
38
+ "dotenv": "^16.5.0",
39
+ "sharp": "^0.34.1"
39
40
  },
40
41
  "devDependencies": {
41
- "@microsoft/api-extractor": "^7.52.2",
42
- "@swc/core": "^1.11.13",
43
- "@swc/wasm": "^1.11.13",
44
- "@types/node": "^22.13.13",
42
+ "@microsoft/api-extractor": "^7.52.3",
43
+ "@swc/core": "^1.11.21",
44
+ "@swc/wasm": "^1.11.21",
45
+ "@types/node": "^22.14.1",
45
46
  "chokidar": "^4.0.3",
46
- "dotenv": "^16.4.7",
47
47
  "dotenv-cli": "^8.0.0",
48
48
  "dotenv-expand": "^12.0.1",
49
49
  "eslint": "latest",
@@ -56,8 +56,8 @@
56
56
  "typescript": "latest",
57
57
  "typescript-eslint": "latest",
58
58
  "@portfolio/eslint-config": "1.0.0",
59
- "@portfolio/tsconfig": "0.1.0",
60
- "@portfolio/prettier-config": "0.1.0"
59
+ "@portfolio/prettier-config": "0.1.0",
60
+ "@portfolio/tsconfig": "0.1.0"
61
61
  },
62
62
  "prettier": "@portfolio/prettier-config",
63
63
  "scripts": {