forked from jae-jae/Userscript-Plus
-
-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathuserscript.js
More file actions
307 lines (297 loc) · 9.6 KB
/
Copy pathuserscript.js
File metadata and controls
307 lines (297 loc) · 9.6 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
import { URL } from 'node:url';
import { access, constants, readFile, writeFile } from 'node:fs/promises';
import dotenv from 'dotenv';
import watch from 'node-watch';
import { loadLanguages } from './languageLoader.js';
/** @type { dotenv.DotenvConfigOutput } */
let result = {};
const log = (...msg) => {
console.log('[LOG]', ...msg);
};
const err = (...msg) => {
console.error('[ERROR]', ...msg);
};
/**
* Object is typeof `object` / JSON Object
* @template O
* @param { O } obj
* @returns { boolean }
*/
const isObj = (obj) => {
/** @type { string } */
const s = Object.prototype.toString.call(obj);
return s.includes('Object');
};
/**
* Object is `null` or `undefined`
* @template O
* @param { O } obj
* @returns { boolean }
*/
const isNull = (obj) => {
return Object.is(obj, null) || Object.is(obj, undefined);
};
/**
* Object is Blank
* @template O
* @param { O } obj
* @returns { boolean }
*/
const isBlank = (obj) => {
return (
(typeof obj === 'string' && Object.is(obj.trim(), '')) ||
((obj instanceof Set || obj instanceof Map) && Object.is(obj.size, 0)) ||
(Array.isArray(obj) && Object.is(obj.length, 0)) ||
(isObj(obj) && Object.is(Object.keys(obj).length, 0))
);
};
/**
* Object is Empty
* @template O
* @param { O } obj
* @returns { boolean }
*/
const isEmpty = (obj) => {
return isNull(obj) || isBlank(obj);
};
const canAccess = async (filePath, encoding = 'utf-8') => {
const testAccess = await access(filePath, constants.R_OK | constants.W_OK);
if (isNull(testAccess)) {
const data = await readFile(filePath, encoding);
return data.toString(encoding);
}
return {
msg: `Cannot access provided filePath: ${filePath}`,
};
};
const fileToJSON = async (filePath, encoding = 'utf-8') => {
const testAccess = await canAccess(filePath, encoding);
if (isObj(testAccess)) {
throw new Error(testAccess.msg);
}
return JSON.parse(testAccess);
};
const dateOptions = {
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
fractionalSecondDigits: 3
};
const initUserJS = async () => {
try {
const jsonData = await fileToJSON('./package.json', 'utf-8');
if (!jsonData.userJS) {
throw new Error('Missing "userJS" key in package.json')
}
const userJS = jsonData.userJS;
const { build } = userJS;
result = isEmpty(process.env.JS_ENV)
? dotenv.config({ path: build.paths.dev.env })
: dotenv.config({ path: build.paths.public.env });
if (result.error) {
throw result.error;
}
if (isNull(result.parsed.JS_ENV)) {
dotenv.populate(
result.parsed,
{
JS_ENV: 'development'
},
{ override: true, debug: true }
);
}
const env = result.parsed;
const js_env = env.JS_ENV === 'development';
const dp = js_env ? 'dev' : 'public';
const lngList = await loadLanguages(new URL('../src/_locales', import.meta.url));
const nano = (template, data) => {
return template.replace(/\{\{(.*?)\}\}/g, (_match, key) => {
const keys = key.split('.');
let v = data[keys.shift()];
for (const i in keys.length) v = v[keys[i]];
return isEmpty(v) ? '' : v;
});
};
const buildUserJS = async () => {
try {
const transformLanguages = () => {
try {
const resp = {};
for (const obj of lngList) {
for (const [k, v] of Object.entries(obj)) {
if (k.includes('_')) {
continue;
}
const o = {};
for (const [key, value] of Object.entries(v)) {
if (key.startsWith('ext')) {
continue;
}
if (key.startsWith('userjs')) {
continue;
}
if (isEmpty(value.message)) {
continue;
}
o[key] = value.message;
}
resp[k] = o;
}
}
return JSON.stringify(resp);
} catch (ex) {
err(ex)
}
}
const compileLanguage = (type = 'userjsName') => {
try {
const resp = [];
for (const obj of lngList) {
for (const [k, v] of Object.entries(obj)) {
if (v[type]) {
if (isEmpty(v[type].message)) {
continue;
}
if (k.startsWith('en')) {
continue;
}
const t = type.toLowerCase().replace('userjs', '');
if (type === 'userjsName') {
resp.push(`// @${t}:${k.replace('_', '-')} ${js_env ? '[Dev] ' : ''}${v[type].message}`);
} else {
resp.push(`// @${t}:${k.replace('_', '-')} ${v[type].message}`);
}
}
}
}
return resp;
} catch (ex) {
err(ex)
}
};
const compileMetadata = () => {
const metaData = [];
try {
for (const [key, value] of Object.entries(userJS.metadata)) {
if (Array.isArray(value)) {
for (const v of value) {
metaData.push(`// @${key} ${v}`);
}
} else if (isObj(value)) {
for (const [k, v] of Object.entries(value)) {
metaData.push(`// @${key} ${k} ${v}`);
}
} else if (typeof value === 'boolean') {
if (value === true) {
metaData.push(`// @${key}`);
}
} else {
metaData.push(`// @${key} ${value}`);
}
}
} catch (ex) {
err(ex)
}
return metaData.join('\n');
};
/**
* @template { import('../package.json') } J
* @template { string } S
* @param { S[] } arr
* @returns { J["userJS"][S] }
*/
const getData = (arr = []) => {
try {
if (!isObj(jsonData)) {
return 'ERROR "jsonData" IS NOT A JSON OBJECT';
}
const resp = [];
for (const str of arr) {
const param = 'userJS' in jsonData && jsonData.userJS[str] ? jsonData.userJS[str] : jsonData[str] ?? null;
if (!param) {
continue;
}
if (str === 'name') {
resp.push(`// @${str} ${js_env ? '[Dev] ' : ''}${param}`, ...compileLanguage('userjsName'));
} else if (str === 'description') {
resp.push(`// @${str} ${param}`, ...compileLanguage('userjsDescription'));
} else if (str === 'author') {
resp.push(`// @${str} ${param}`);
} else if (str === 'icon') {
resp.push(`// @${str} ${param}`);
} else if (str === 'url') {
resp.push(`// @downloadURL ${param}`, `// @updateURL ${param}`);
} else if (str === 'version') {
resp.push(`// @${str} ${js_env ? +new Date() : param}`);
} else if (str === 'homepage') {
resp.push(`// @namespace ${param}`, `// @homepageURL ${param}`);
} else if (str === 'bugs') {
resp.push(`// @supportURL ${param}`);
} else if (str === 'license') {
resp.push(`// @${str} ${param}`);
} else {
resp.push(param);
}
}
return resp.join('\n')
} catch (ex) {
err(ex)
}
};
const userJSHeader = `// ==UserScript==\n${getData(['name', 'description', 'author', 'icon', 'version', 'url', 'homepage', 'bugs', 'license'])}\n${compileMetadata()}\n// ==/UserScript==`;
const headerFile = await canAccess(build.source.head);
const mainFile = await canAccess(build.source.body);
const nanoCFG = {
metadata: userJSHeader,
languageList: transformLanguages(),
code: mainFile,
};
for (const [k, v] of Object.entries(build.source.extras)) {
const extraFile = await canAccess(v);
if (typeof extraFile === 'string') {
nanoCFG[k] = extraFile;
}
};
const outFile = `${build.paths[dp].dir}/${build.paths[dp].fileName}.user.js`;
await writeFile(outFile, nano(headerFile, nanoCFG));
log('UserJS Build:', {
path: outFile,
time: new Intl.DateTimeFormat('default', dateOptions).format(new Date())
});
if (!js_env) {
const metaFile = await canAccess(build.source.metadata);
const outMeta = `${build.paths[dp].dir}/${build.paths[dp].fileName}.meta.user.js`;
await writeFile(outMeta, nano(metaFile, { metadata: userJSHeader }));
log('UserJS Metadata:', {
path: outMeta,
time: new Intl.DateTimeFormat('default', dateOptions).format(new Date())
});
}
} catch (ex) {
err(ex);
}
};
const watcher = watch(build.watchDirs, {
recursive: true,
delay: 2000,
filter: /\.(js|[s]css)$/
});
//#region Start Process
log(`Node ENV: ${env.JS_ENV}`);
if (js_env) {
watcher.on('change', buildUserJS);
watcher.on('error', (ex) => {
err(ex);
watcher.close();
});
watcher.on('ready', buildUserJS);
return;
}
await buildUserJS();
process.exit(0);
//#endregion
} catch (ex) {
err(ex);
}
};
initUserJS();