-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuildUtil.js
97 lines (80 loc) · 2.26 KB
/
buildUtil.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import fg from "fast-glob";
import fs from "node:fs";
// ts file names that end with this string will be targeted for transpilation/bundling
const ENTRYPOINT_IDENTIFIER = ".user.ts";
/**
*
* @param {string} rootDirPathGlob
* @returns {string[]}
*/
export function getUserscriptPaths(rootDirPathGlob) {
/**@type {string[]} */
const userscriptsFilePaths = [];
const files = fg.sync([rootDirPathGlob]);
files.forEach((file) => {
if (file.endsWith(ENTRYPOINT_IDENTIFIER)) {
userscriptsFilePaths.push(file);
}
});
return userscriptsFilePaths;
}
/**
* Retain comments included at the top of the file (series of // comments). Useful for *monkey userscripts
* @param {string} tsFilePath
* @returns {string[]}
*/
export function parseInitialComments(tsFilePath) {
/**@type {string[]} */
const commentsList = [];
const content = fs.readFileSync(tsFilePath, "utf8");
const lines = content.split("\n");
for (const line of lines) {
if (line.trim().startsWith("//")) {
commentsList.push(line.trim());
} else {
return commentsList;
}
}
return commentsList;
}
/**
*
* @param {string} jsFilePath
* @param {string[]} comments
* @returns {void}
*/
export function prependCommentsToJsFiles(jsFilePath, comments) {
if (comments.length === 0) {
return;
}
try {
const jsFileContent = fs.readFileSync(jsFilePath, "utf8");
const newContent = comments.join("\n") + "\n\n" + jsFileContent;
fs.writeFileSync(jsFilePath, newContent, "utf8");
console.log(`Comments prepended to ${jsFilePath} successfully.`);
} catch (error) {
console.error(`Error writing to file: ${jsFilePath}`);
console.error(error);
}
}
/**
*
* @param {string} inputString
* @param {string} prefix
* @returns {string}
*/
export function slugifyAndCapitalize(inputString, prefix) {
if (inputString.length === 0) {
throw new Error("The input string is length 0");
}
const prefixRegex = /^\w*$/g;
if (!prefixRegex.test(prefix)) {
throw new Error("Prefix can only contain alphanumeric characters");
}
let dunderPrefix = "";
if (prefix.length > 0) {
dunderPrefix = `__${prefix}_`;
}
const slugifiedString = inputString.replaceAll(/[^A-Za-z]+/g, "_");
return `${dunderPrefix}${slugifiedString}__`.toUpperCase();
}