-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathparser.ts
50 lines (46 loc) · 1.67 KB
/
parser.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import { existsSync, writeFileSync } from "node:fs";
import { ensureFileSync, getLastPart, getVersion } from "src/utils";
import { logger } from "src/logger";
import { isDebuggingEnabled } from "./config";
/**
* ******************************************************
* PARSER 🔪
* ------------------------------------------------------
* @description handles parsing directories for cached paths
*
* ******************************************************
*/
const log = logger({ file: "parser", isLogging: isDebuggingEnabled() });
export const getPackageNameVersionFromUrl = (url: string) => {
try {
const file = getLastPart(url, "/");
const urlParts = url?.split("@");
const urlPartsCount = urlParts.length;
if (urlPartsCount === 3) {
const name = `@${urlParts[1]}`;
const version = getVersion(urlParts)(2);
return { file, name, version };
}
const name = getLastPart(getLastPart(urlParts[0], "/"), ":");
const version = getVersion(urlParts)(1);
return { file, name, version };
} catch (err) {
log.error(`getPackageNameVersionFromUrl: ${err}`, {});
return {};
}
};
export const parseNodeModuleCachePath = async (modulePath: string, cachePath: string) => {
log.debug("parseNodeModuleCachePath", cachePath, modulePath);
if (existsSync(cachePath)) return cachePath;
try {
const resp = await fetch(modulePath);
if (!resp.ok) throw Error(`404: Module not found: ${modulePath}`);
const code = await resp.text();
ensureFileSync(cachePath);
writeFileSync(cachePath, code);
return cachePath;
} catch (err) {
log.error(`parseNodeModuleCachePath: Failed in parsing module ${err}`);
return cachePath;
}
};