@reliverse/pathkit 1.2.5 → 1.2.6

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 (2) hide show
  1. package/bin/mod.js +93 -32
  2. package/package.json +1 -1
package/bin/mod.js CHANGED
@@ -2,19 +2,14 @@ import fs from "node:fs/promises";
2
2
  import {
3
3
  getFileImportsExports
4
4
  } from "./impl/getFileImportsExports.js";
5
- const logger = (msg, debugOnly = false) => {
6
- if (!debugOnly || DEBUG_MODE) {
7
- const message = typeof msg === "function" ? msg() : msg;
8
- console.log(`\x1B[2m${message}\x1B[0m`);
9
- }
5
+ const logger = (msg) => {
6
+ const message = typeof msg === "function" ? msg() : msg;
7
+ console.log(`\x1B[2m${message}\x1B[0m`);
10
8
  };
11
- const logInternal = (msg) => {
12
- if (DEBUG_MODE) {
13
- const message = typeof msg === "function" ? msg() : msg;
14
- console.log(`\x1B[36;2m${message}\x1B[0m`);
15
- }
9
+ const logger2 = (msg) => {
10
+ const message = typeof msg === "function" ? msg() : msg;
11
+ console.log(`\x1B[36;2m${message}\x1B[0m`);
16
12
  };
17
- const DEBUG_MODE = true;
18
13
  const EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".d.ts"];
19
14
  const SLASH = "/";
20
15
  const BACK_SLASH = "\\";
@@ -355,15 +350,20 @@ function reverseResolveAlias(path2, aliases) {
355
350
  return matches.sort((a, b) => b.length - a.length);
356
351
  }
357
352
  const findAliasMatch = (importPath, paths) => {
353
+ logger2(`[findAliasMatch] Processing import: ${importPath}`);
354
+ logger2(` - paths: ${JSON.stringify(paths)}`);
358
355
  const firstPathKey = Object.keys(paths)[0];
359
356
  if (!firstPathKey) {
357
+ logger2(` - no paths defined`);
360
358
  return null;
361
359
  }
362
360
  const baseAlias = firstPathKey.replace("/*", "");
363
361
  if (importPath.startsWith("@") && !importPath.startsWith(baseAlias)) {
362
+ logger2(` - skipping: npm package import`);
364
363
  return null;
365
364
  }
366
365
  if (paths[importPath]?.[0]) {
366
+ logger2(` - found exact match`);
367
367
  return {
368
368
  key: importPath,
369
369
  root: importPath,
@@ -374,11 +374,15 @@ const findAliasMatch = (importPath, paths) => {
374
374
  for (const aliasKey in paths) {
375
375
  if (aliasKey.endsWith("/*")) {
376
376
  const aliasRoot = aliasKey.slice(0, -2);
377
+ logger2(` - checking wildcard match for: ${aliasRoot}`);
377
378
  if (importPath === aliasRoot || importPath.startsWith(`${aliasRoot}/`)) {
378
379
  const suffix = importPath === aliasRoot ? "" : importPath.slice(aliasRoot.length + 1);
379
380
  const targetPaths = paths[aliasKey];
380
381
  if (targetPaths?.[0]) {
381
382
  const resolvedPathPattern = targetPaths[0].slice(0, -2);
383
+ logger2(` - found wildcard match`);
384
+ logger2(` - suffix: ${suffix}`);
385
+ logger2(` - resolvedPathPattern: ${resolvedPathPattern}`);
382
386
  return {
383
387
  key: aliasKey,
384
388
  root: aliasRoot,
@@ -389,6 +393,7 @@ const findAliasMatch = (importPath, paths) => {
389
393
  }
390
394
  }
391
395
  }
396
+ logger2(` - no match found`);
392
397
  return null;
393
398
  };
394
399
  const toRelativeImport = (absPath, fromDir) => {
@@ -430,21 +435,32 @@ async function convertStringAliasRelative({
430
435
  pathPattern,
431
436
  targetDir
432
437
  }) {
438
+ logger2(`[convertStringAliasRelative] Processing import: ${importPath}`);
439
+ logger2(` - importerFile: ${importerFile}`);
440
+ logger2(` - pathPattern: ${pathPattern}`);
441
+ logger2(` - targetDir: ${targetDir}`);
433
442
  const baseAlias = pathPattern.replace("/*", "");
434
443
  if (importPath.startsWith("@") && !importPath.startsWith(baseAlias)) {
444
+ logger2(` - skipping: npm package import`);
435
445
  return importPath;
436
446
  }
437
447
  const paths = { [pathPattern]: ["./*"] };
438
448
  const importerDir = dirname(importerFile);
439
449
  const match = findAliasMatch(importPath, paths);
440
450
  if (!match) {
451
+ logger2(` - no alias match found`);
441
452
  return importPath;
442
453
  }
454
+ logger2(` - found alias match: ${JSON.stringify(match)}`);
443
455
  const absPath = resolve(targetDir, match.resolvedPath, match.suffix);
456
+ logger2(` - resolved absolute path: ${absPath}`);
444
457
  const resolvedFile = await resolveFileWithExtensions(absPath);
458
+ logger2(` - resolved file with extensions: ${resolvedFile || "not found"}`);
445
459
  const relPath = toRelativeImport(resolvedFile || absPath, importerDir);
460
+ logger2(` - relative path: ${relPath}`);
446
461
  const originalExt = extname(importPath);
447
462
  const result = getTargetExtension(relPath, originalExt);
463
+ logger2(` - final result: ${result}`);
448
464
  return result;
449
465
  }
450
466
  function replaceAllInString(original, searchValue, replaceValue) {
@@ -469,36 +485,50 @@ async function processFile(filePath, aliasToReplace, targetDir, pathExtFilter) {
469
485
  const matches = Array.from(content.matchAll(IMPORT_REGEX));
470
486
  const normalizedAlias = aliasToReplace.endsWith("/*") ? aliasToReplace : `${aliasToReplace}/*`;
471
487
  const baseAlias = aliasToReplace.replace("/*", "");
488
+ logger2(`[processFile] Processing file: ${filePath}`);
489
+ logger2(` - normalizedAlias: ${normalizedAlias}`);
490
+ logger2(` - baseAlias: ${baseAlias}`);
491
+ logger2(` - found ${matches.length} import statements`);
472
492
  for (const match of matches) {
473
493
  const originalQuote = match[1];
474
494
  const importPath = match[2];
475
495
  if (!importPath) continue;
496
+ logger2(` Processing import: ${importPath}`);
476
497
  if (!importPath.startsWith(baseAlias)) {
498
+ logger2(` - skipping: import doesn't start with ${baseAlias}`);
477
499
  continue;
478
500
  }
479
501
  const importExt = extname(importPath);
480
502
  const shouldProcess = pathExtFilter === "js" && importExt === ".js" || pathExtFilter === "ts" && importExt === ".ts" || pathExtFilter === "none" && importExt === "" || pathExtFilter === "js-ts-none";
481
503
  if (!shouldProcess) {
504
+ logger2(` - skipping: doesn't match pathExtFilter ${pathExtFilter}`);
482
505
  continue;
483
506
  }
507
+ logger2(` - converting alias to relative path...`);
484
508
  const relPath = await convertStringAliasRelative({
485
509
  importPath,
486
510
  importerFile: filePath,
487
511
  pathPattern: normalizedAlias,
488
512
  targetDir
489
513
  });
514
+ logger2(` - original path: ${importPath}`);
515
+ logger2(` - converted to: ${relPath}`);
490
516
  const finalPath = pathExtFilter === "none" ? relPath.replace(/\.(ts|js|tsx|jsx|mjs|cjs)$/, "") : relPath;
491
517
  if (importPath !== finalPath) {
492
518
  changes.push({ from: importPath, to: finalPath });
493
519
  const searchString = `${originalQuote}${importPath}${originalQuote}`;
494
520
  const replacementString = `${originalQuote}${finalPath}${originalQuote}`;
495
521
  updated = replaceAllInString(updated, searchString, replacementString);
522
+ logger2(` - applied change: ${importPath} \u2192 ${finalPath}`);
496
523
  } else {
524
+ logger2(` - no change needed`);
497
525
  }
498
526
  }
499
527
  if (content !== updated) {
500
528
  await fs.writeFile(filePath, updated);
529
+ logger2(`\u2713 processed: ${filePath}`);
501
530
  } else {
531
+ logger2(` - no changes made to file`);
502
532
  }
503
533
  return changes;
504
534
  }
@@ -536,6 +566,7 @@ async function processAllFiles({
536
566
  results.push({ file: fullPath, changes });
537
567
  }
538
568
  } else {
569
+ logger2(` - skipping non-matching file: ${entry.name}`);
539
570
  }
540
571
  })
541
572
  );
@@ -559,6 +590,7 @@ async function convertImportsAliasToRelative({
559
590
  logger(
560
591
  ` (Assuming "${normalizedAlias}" resolves relative to "${targetDir}")`
561
592
  );
593
+ logger2(` (Using extension mode: ${pathExtFilter})`);
562
594
  const results = await processAllFiles({
563
595
  srcDir: targetDir,
564
596
  aliasToReplace: normalizedAlias,
@@ -567,12 +599,12 @@ async function convertImportsAliasToRelative({
567
599
  pathExtFilter
568
600
  });
569
601
  if (results.length > 0) {
570
- logger("\n[convertImportsAliasToRelative] Summary of changes:", true);
602
+ logger("\n[convertImportsAliasToRelative] Summary of changes:");
571
603
  for (const { file, changes } of results) {
572
604
  const displayPath = relative(targetDir, file) || basename(file);
573
- logger(() => ` in ${displayPath}:`, true);
605
+ logger(() => ` in ${displayPath}:`);
574
606
  for (const { from, to } of changes) {
575
- logger(() => ` - ${from} \u2192 ${to}`, true);
607
+ logger(() => ` - ${from} \u2192 ${to}`);
576
608
  }
577
609
  }
578
610
  } else {
@@ -586,6 +618,9 @@ async function convertImportsExt({
586
618
  extTo,
587
619
  alias
588
620
  }) {
621
+ logger2(
622
+ `Converting import extensions from '${extFrom}' to '${extTo}' in "${targetDir}"...`
623
+ );
589
624
  const fromExtStr = extFrom === "none" ? "" : `.${extFrom}`;
590
625
  const toExtStr = extTo === "none" ? "" : `.${extTo}`;
591
626
  const normalizedAlias = alias ? alias.endsWith("/*") ? alias : `${alias}/*` : void 0;
@@ -658,24 +693,27 @@ async function convertImportsExt({
658
693
  }
659
694
  if (content !== updated) {
660
695
  await fs.writeFile(fullPath, updated);
696
+ logger2(`\u2713 processed: ${fullPath}`);
661
697
  if (changes.length > 0) {
662
698
  results.push({ file: fullPath, changes });
663
699
  }
664
700
  }
665
701
  } else {
702
+ logger2(` - skipping non-matching file: ${entry.name}`);
666
703
  }
667
704
  })
668
705
  );
669
706
  if (results.length > 0) {
670
- logger("\n[convertImportsExt] Summary of changes:", true);
707
+ logger("\n[convertImportsExt] Summary of changes:");
671
708
  for (const { file, changes } of results) {
672
709
  const displayPath = relative(targetDir, file) || basename(file);
673
- logger(() => ` in ${displayPath}:`, true);
710
+ logger(() => ` in ${displayPath}:`);
674
711
  for (const { from, to } of changes) {
675
- logger(() => ` - ${from} \u2192 ${to}`, true);
712
+ logger(() => ` - ${from} \u2192 ${to}`);
676
713
  }
677
714
  }
678
715
  }
716
+ logger2("Extension conversion complete.");
679
717
  return results;
680
718
  } catch (error) {
681
719
  logger(
@@ -687,8 +725,12 @@ async function convertImportsExt({
687
725
  function stripPathSegments(path2, count = 1, alias = "") {
688
726
  if (typeof path2 !== "string" || path2.length === 0) return path2;
689
727
  if (count <= 0) return path2;
728
+ logger2(`[stripPathSegments] Processing path: ${path2}`);
729
+ logger2(` - count: ${count}, alias: ${alias}`);
690
730
  const normalizedPath = normalizeWindowsPath(path2);
731
+ logger2(` - normalized: ${normalizedPath}`);
691
732
  const parsed = parse(normalizedPath);
733
+ logger2(` - parsed: ${JSON.stringify(parsed)}`);
692
734
  let pathSegments = [];
693
735
  if (parsed.dir && parsed.dir !== parsed.root) {
694
736
  let dirRelativeToRoot = parsed.dir;
@@ -701,26 +743,36 @@ function stripPathSegments(path2, count = 1, alias = "") {
701
743
  pathSegments.push(parsed.base);
702
744
  }
703
745
  pathSegments = pathSegments.filter(Boolean);
746
+ logger2(` - initial segments: ${JSON.stringify(pathSegments)}`);
704
747
  const leadingPreservedSegments = [];
705
748
  if (alias && pathSegments.length > 0 && pathSegments[0]?.startsWith(alias)) {
706
749
  const preserved = pathSegments.shift();
707
750
  if (preserved) {
708
751
  leadingPreservedSegments.push(preserved);
752
+ logger2(` - preserved alias segment: ${preserved}`);
709
753
  }
710
754
  }
711
755
  while (pathSegments.length > 0 && (pathSegments[0] === DOT || pathSegments[0] === DOUBLE_DOT)) {
712
756
  const preserved = pathSegments.shift();
713
757
  if (preserved) {
714
758
  leadingPreservedSegments.push(preserved);
759
+ logger2(` - preserved relative segment: ${preserved}`);
715
760
  }
716
761
  }
717
762
  const numToStrip = Math.min(count, pathSegments.length);
718
763
  const remainingBodySegments = pathSegments.slice(numToStrip);
764
+ logger2(
765
+ ` - stripping ${numToStrip} segments from: ${JSON.stringify(pathSegments)}`
766
+ );
767
+ logger2(
768
+ ` - remaining body segments: ${JSON.stringify(remainingBodySegments)}`
769
+ );
719
770
  const pathRoot = parsed.root;
720
771
  const effectiveSegments = [
721
772
  ...leadingPreservedSegments,
722
773
  ...remainingBodySegments
723
774
  ];
775
+ logger2(` - effective segments: ${JSON.stringify(effectiveSegments)}`);
724
776
  let result;
725
777
  if (effectiveSegments.length === 0) {
726
778
  result = normalize(pathRoot || DOT);
@@ -729,6 +781,7 @@ function stripPathSegments(path2, count = 1, alias = "") {
729
781
  } else {
730
782
  result = join(...effectiveSegments);
731
783
  }
784
+ logger2(` - final result: ${result}`);
732
785
  return result;
733
786
  }
734
787
  async function stripPathSegmentsInDirectory({
@@ -738,13 +791,10 @@ async function stripPathSegmentsInDirectory({
738
791
  extensionsToProcess = EXTENSIONS
739
792
  }) {
740
793
  logger(
741
- () => `[stripPathSegmentsInDirectory] Processing directory: ${targetDir}`,
742
- true
743
- );
744
- logger(
745
- () => ` - segmentsToStrip: ${segmentsToStrip}, alias: ${alias}`,
746
- true
794
+ () => `[stripPathSegmentsInDirectory] Processing directory: ${targetDir}`
747
795
  );
796
+ logger(() => ` - segmentsToStrip: ${segmentsToStrip}, alias: ${alias}`);
797
+ logger2(` - extensions: ${JSON.stringify(extensionsToProcess)}`);
748
798
  try {
749
799
  const entries = await fs.readdir(targetDir, { withFileTypes: true });
750
800
  const results = [];
@@ -753,6 +803,7 @@ async function stripPathSegmentsInDirectory({
753
803
  const fullPath = join(targetDir, entry.name);
754
804
  if (entry.isDirectory()) {
755
805
  if (entry.name === "node_modules") return;
806
+ logger2(` - recursing into directory: ${entry.name}`);
756
807
  const subdirResults = await stripPathSegmentsInDirectory({
757
808
  targetDir: fullPath,
758
809
  segmentsToStrip,
@@ -761,54 +812,65 @@ async function stripPathSegmentsInDirectory({
761
812
  });
762
813
  results.push(...subdirResults);
763
814
  } else if (extensionsToProcess.includes(extname(entry.name))) {
815
+ logger2(` Processing file: ${entry.name}`);
764
816
  const content = await fs.readFile(fullPath, "utf-8");
765
817
  let updated = content;
766
818
  const changes = [];
767
819
  const matches = Array.from(content.matchAll(IMPORT_REGEX));
820
+ logger2(` - found ${matches.length} import statements`);
768
821
  for (const match of matches) {
769
822
  const originalQuote = match[1];
770
823
  const importPath = match[2];
771
824
  if (!importPath) continue;
772
825
  if (!importPath.includes(SLASH)) {
826
+ logger2(` - skipping non-path import: ${importPath}`);
773
827
  continue;
774
828
  }
775
829
  if (alias && !importPath.startsWith(alias.replace("/*", ""))) {
830
+ logger2(` - skipping non-alias import: ${importPath}`);
776
831
  continue;
777
832
  }
833
+ logger2(` Processing import: ${importPath}`);
778
834
  const strippedPath = stripPathSegments(
779
835
  importPath,
780
836
  segmentsToStrip,
781
837
  alias
782
838
  );
783
839
  if (importPath === strippedPath) {
840
+ logger2(" - no changes needed");
784
841
  continue;
785
842
  }
786
843
  changes.push({ from: importPath, to: strippedPath });
844
+ logger2(` - transformed: ${importPath} \u2192 ${strippedPath}`);
787
845
  const searchStr = `${originalQuote}${importPath}${originalQuote}`;
788
846
  const replaceStr = `${originalQuote}${strippedPath}${originalQuote}`;
789
847
  updated = replaceAllInString(updated, searchStr, replaceStr);
790
848
  }
791
849
  if (content !== updated) {
792
850
  await fs.writeFile(fullPath, updated);
851
+ logger2(" \u2713 wrote changes to file");
793
852
  if (changes.length > 0) {
794
853
  results.push({ file: fullPath, changes });
795
854
  }
796
855
  } else {
856
+ logger2(" - no changes made to file");
797
857
  }
798
858
  } else {
859
+ logger2(` - skipping non-matching file: ${entry.name}`);
799
860
  }
800
861
  })
801
862
  );
802
863
  if (results.length > 0) {
803
- logger(() => "[stripPathSegmentsInDirectory] Summary of changes:", true);
864
+ logger(() => "[stripPathSegmentsInDirectory] Summary of changes:");
804
865
  for (const { file, changes } of results) {
805
866
  const displayPath = relative(targetDir, file) || basename(file);
806
- logger(() => ` in ${displayPath}:`, true);
867
+ logger(() => ` in ${displayPath}:`);
807
868
  for (const { from, to } of changes) {
808
- logger(() => ` - ${from} \u2192 ${to}`, true);
869
+ logger(() => ` - ${from} \u2192 ${to}`);
809
870
  }
810
871
  }
811
872
  } else {
873
+ logger2(" No changes were made in any files");
812
874
  }
813
875
  return results;
814
876
  } catch (error) {
@@ -898,24 +960,23 @@ async function attachPathSegmentsInDirectory({
898
960
  }
899
961
  if (content !== updated) {
900
962
  await fs.writeFile(fullPath, updated);
963
+ logger2(`\u2713 processed: ${fullPath}`);
901
964
  if (changes.length > 0) {
902
965
  results.push({ file: fullPath, changes });
903
966
  }
904
967
  }
905
968
  } else {
969
+ logger2(` - skipping non-matching file: ${entry.name}`);
906
970
  }
907
971
  })
908
972
  );
909
973
  if (results.length > 0) {
910
- logger(
911
- () => "\n[attachPathSegmentsInDirectory] Summary of changes:",
912
- true
913
- );
974
+ logger(() => "\n[attachPathSegmentsInDirectory] Summary of changes:");
914
975
  for (const { file, changes } of results) {
915
976
  const displayPath = relative(targetDir, file) || basename(file);
916
- logger(() => ` in ${displayPath}:`, true);
977
+ logger(() => ` in ${displayPath}:`);
917
978
  for (const { from, to } of changes) {
918
- logger(() => ` - ${from} \u2192 ${to}`, true);
979
+ logger(() => ` - ${from} \u2192 ${to}`);
919
980
  }
920
981
  }
921
982
  }
package/package.json CHANGED
@@ -5,7 +5,7 @@
5
5
  "license": "MIT",
6
6
  "name": "@reliverse/pathkit",
7
7
  "type": "module",
8
- "version": "1.2.5",
8
+ "version": "1.2.6",
9
9
  "devDependencies": {},
10
10
  "exports": {
11
11
  ".": "./bin/mod.js"