-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcompile-userscripts.js
More file actions
596 lines (520 loc) · 20.6 KB
/
Copy pathcompile-userscripts.js
File metadata and controls
596 lines (520 loc) · 20.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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
const fs = require('fs/promises')
const path = require('path')
const propsTable = ['grant', 'antifeature', 'require', 'resource', 'include', 'match', 'connect']
const keyOrders = ['name', 'namespace', 'version', 'description', 'author', 'homepage', 'supportURL', 'match', 'icon', 'grant']
const atPropsSections = ['grant', 'require', 'match']
const atTechPropsSections = ['postheader']
const techPropsTable = ['postheader']
const atSections = ['import', ...atPropsSections, ...atTechPropsSections]
const allPropsTable = [...propsTable, ...techPropsTable]
const shell = async (command) => {
const { exec } = require('child_process')
return new Promise((resolve, reject) => {
exec(command, (error, stdout, stderr) => {
if (error) {
reject(error)
} else {
resolve({ stdout, stderr })
}
})
})
}
const gitRootByDirnameCache = {}
const getGitVersion = async (files) => {
const results = []
const rootPath = path.resolve('.')
const relativeFilesByRepo = {}
for (let file of files) {
const fullAbsolutePath = path.resolve(file)
const dirname = path.dirname(file)
if (!gitRootByDirnameCache[dirname]) {
const { stdout: gitRootOutput } = await shell(`git -C "${dirname}" rev-parse --show-toplevel`)
const gitRoot = gitRootOutput.trim()
gitRootByDirnameCache[dirname] = gitRoot
}
const gitRoot = gitRootByDirnameCache[dirname]
const gitRelativeRoot = path.relative(rootPath, gitRoot)
const gitRelativeFile = path.relative(gitRelativeRoot, fullAbsolutePath)
if (!relativeFilesByRepo[gitRelativeRoot]) {
relativeFilesByRepo[gitRelativeRoot] = []
}
relativeFilesByRepo[gitRelativeRoot].push(gitRelativeFile)
}
for (const [gitRelativeRoot, relativeFiles] of Object.entries(relativeFilesByRepo)) {
const command = `git -C "${gitRelativeRoot}" log -1 --date='format-local:%Y%m%d-%H%M%S' --format="%cd-%h" -- ${relativeFiles.map(f => `"${f}"`).join(' ')}`
const { stdout: result } = await shell(command)
if (result.trim()) {
results.push(result.trim())
}
}
results.sort()
return results[results.length - 1]
}
const display = (obj, ...objs) => {
let result = JSON.stringify(obj, null, 4)
if (objs !== undefined) {
for (const obj of objs) {
result += ' ' + (JSON.stringify(obj, null, 0))
}
}
console.log(result)
}
const isDir = async (path) => {
try {
const stat = await fs.stat(path)
return stat.isDirectory()
} catch (e) {
return false
}
}
const makedirs = async (path) => await fs.mkdir(path, { recursive: true })
const open = async (path, flags) => await fs.open(path, flags)
const write = async (handle, data) => await handle.write(data)
const writeLine = async (handle, data) => await write(handle, data + '\n')
const close = async (handle) => await handle.close()
const readJson = async (path) => JSON.parse(await fs.readFile(path, 'utf8'))
const readFile = async (path) => await fs.readFile(path, 'utf8')
const writeJson = async (path, data) => await fs.writeFile(path, JSON.stringify(data, null, 0), { encoding: 'utf8', flag: 'w' })
const removeEnd = (data, pattern) => data.endsWith(pattern) ? data.slice(0, -pattern.length) : data
const ensureKey = (obj, key, defaultValue) => {
if (obj[key] === undefined) {
obj[key] = defaultValue
}
return obj[key]
}
const mergeProps = (props) => props.reduce((acc, prop) => ({ ...acc, ...prop }), {})
const parseAtLine = (line, sections) => {
const match = line.match(/^\s*\/\/\s*@(\w+)\{(.*)\}\s*$/)
if (match !== null) {
const [, keyword, value] = match
if (atSections.includes(keyword)) {
if (sections[keyword] === undefined) {
sections[keyword] = []
}
sections[keyword].push(value)
return true
}
}
return false
}
const updateProps = (props, key, value) => {
if (allPropsTable.includes(key)) {
if (props[key] === undefined) {
props[key] = []
}
if (!props[key].includes(value)) {
props[key] = [...props[key], value]
}
} else {
props[key] = value
}
}
const parseScriptContent = (content) => {
let isHeader = false
const localProps = {}
let bodyLines = []
const sections = {}
atSections.forEach(section => sections[section] = [])
for (let line of content.split('\n')) {
line = line.replace('\r', '')
if (line.startsWith('// ==UserScript==')) {
isHeader = true
} else if (line.startsWith('// ==/UserScript==')) {
isHeader = false
} else {
if (isHeader) {
const match = line.match(/^\/\/\s*@(\w+)\s+(.*)\s*$/)
if (match !== null) {
const [, key, value] = match
updateProps(localProps, key, value)
}
} else {
if (!parseAtLine(line, sections)) {
bodyLines.push(line)
}
}
}
}
const { begin, end } = bodyLines.reduce((acc, line, index) => (line === '' ? acc : { begin: acc.begin == undefined ? index : acc.begin, end: index }), { begin: undefined, end: 0 })
bodyLines = bodyLines.slice(begin, end + 1)
return {
sections,
bodyLines,
localProps
}
}
const parseStyleContent = (content) => {
let isHeader = false
const localProps = {}
let bodyLines = []
for (let line of content.split('\n')) {
line = line.replace('\r', '')
if (line.startsWith('/* ==UserStyle==')) {
isHeader = true
} else if (line.startsWith('==/UserStyle== */')) {
isHeader = false
} else {
if (isHeader) {
const match = line.match(/^\s*@(\w+)\s+(.*)\s*$/)
if (match !== null) {
const [, key, value] = match
updateProps(localProps, key, value)
}
} else {
bodyLines.push(line)
}
}
}
const { begin, end } = bodyLines.reduce((acc, line, index) => (line === '' ? acc : { begin: acc.begin == undefined ? index : acc.begin, end: index }), { begin: undefined, end: 0 })
bodyLines = bodyLines.slice(begin, end + 1)
return { bodyLines, localProps }
}
const chooseImport = async (importFolders, importName) => {
for (const importFolder of importFolders) {
const filename = `${importFolder}/${importName}.js`
try {
await fs.access(filename)
return filename
} catch (e) {
// continue searching
}
}
throw new Error(`Import "${importName}" not found in folders: ${importFolders.join(', ')}`)
}
const moveSectionsToProps = (sections, props, techProps) => {
for (const section of atPropsSections) {
sections[section].forEach((value) => updateProps(props, section, value))
}
for (const section of atTechPropsSections) {
sections[section].forEach((value) => updateProps(techProps, section, value))
}
}
const resolveImports = async (imports, props, techProps, importFolders, importContent, parsed) => {
if (importContent === undefined) {
importContent = {
filenames: new Set(),
files: {}
}
}
if (parsed === undefined) {
parsed = {}
}
for (const importName of imports) {
const filename = await chooseImport(importFolders, importName)
const content = await readFile(filename)
if (parsed[importName] === undefined) {
const { sections, bodyLines } = parseScriptContent(content)
parsed[importName] = true
await resolveImports(sections.import, props, techProps, importFolders, importContent, parsed)
moveSectionsToProps(sections, props, techProps)
importContent.files[importName] = bodyLines
importContent.filenames.add(filename)
}
}
return importContent
}
const writeScriptHeaderKey = async (handle, key, value, keyLength) => {
if (Array.isArray(value)) {
for (const valueItem of value) {
await writeScriptHeaderKey(handle, key, valueItem, keyLength)
}
return
} else {
await writeLine(handle, `// @${key}${' '.repeat(keyLength - key.length)} ${value}`)
}
}
const writeScriptHeader = async (handle, props) => {
const keyLength = Object.keys(props).reduce((acc, key) => Math.max(acc, key.length), 0)
await writeLine(handle, '// ==UserScript==')
for (const keyOrder of keyOrders) {
if (props[keyOrder] !== undefined) {
await writeScriptHeaderKey(handle, keyOrder, props[keyOrder], keyLength)
}
}
for (const [key, value] of Object.entries(props)) {
if (!keyOrders.includes(key)) {
await writeScriptHeaderKey(handle, key, value, keyLength)
}
}
await writeLine(handle, '// ==/UserScript==')
}
const writeScriptPostHeader = async (handle, techProps) => {
if (techProps && techProps['postheader'] !== undefined && techProps['postheader'].length > 0) {
await writeLine(handle, '');
await writeLine(handle, '// @begin_postheader');
for (const line of techProps['postheader']) {
await writeLine(handle, line);
}
await writeLine(handle, '// @end_postheader');
}
}
const writeStyleHeaderKey = async (handle, key, value, keyLength) => {
if (Array.isArray(value)) {
for (const valueItem of value) {
await writeStyleHeaderKey(handle, key, valueItem, keyLength)
}
return
} else {
await writeLine(handle, `@${key}${' '.repeat(keyLength - key.length)} ${value}`)
}
}
const writeStyleHeader = async (handle, props) => {
const keyLength = Object.keys(props).reduce((acc, key) => Math.max(acc, key.length), 0)
await writeLine(handle, '/* ==UserStyle==')
for (const keyOrder of keyOrders) {
if (props[keyOrder] !== undefined) {
await writeStyleHeaderKey(handle, keyOrder, props[keyOrder], keyLength)
}
}
for (const [key, value] of Object.entries(props)) {
if (!keyOrders.includes(key)) {
await writeStyleHeaderKey(handle, key, value, keyLength)
}
}
await writeLine(handle, '==/UserStyle== */')
}
const populateUserscripts = (userscripts, path, props) => {
userscripts[path] = []
for (const prop in props) {
if (Array.isArray(props[prop])) {
for (const value of props[prop]) {
userscripts[path].push([prop, value])
}
} else {
userscripts[path].push([prop, props[prop]])
}
}
}
const defineDefaultProps = async (props, filenames) => {
if (props['version'] === undefined) {
props['version'] = await getGitVersion([...filenames])
}
if (props['description'] === undefined) {
props['description'] = props['name']
}
if (props['iconFromDomain'] !== undefined && props['icon'] === undefined) {
props['icon'] = `https://www.google.com/s2/favicons?sz=64&domain=${props['iconFromDomain']}`
delete props['iconFromDomain']
}
}
const compileScript = async (basename, content, filenames, globalProps, userscripts, outFolder, importFolders, subPath) => {
const { sections, bodyLines, localProps } = parseScriptContent(content)
props = { ...globalProps, ...localProps, name: basename }
techProps = {}
moveSectionsToProps(sections, props, techProps)
if (props['@import'] !== undefined) {
props['@import'].forEach((importName) => sections.import.push(importName))
delete props['@import']
}
const importContent = await resolveImports(sections.import, props, techProps, importFolders)
if (props['grant'] !== undefined && props['grant'].includes('none') && props['grant'].length > 1) {
props['grant'].splice(props['grant'].indexOf('none'), 1)
}
await defineDefaultProps(props, [...filenames, ...Array.from(importContent.filenames)])
populateUserscripts(userscripts, `${subPath}${basename}.user.js`, { ...props, type: 'script' })
const outDir = `${outFolder}/${subPath}`
const isDirectory = await isDir(outDir)
if (!isDirectory) {
await makedirs(outDir)
}
const outFile = `${outDir}/${basename}.user.js`
const handle = await open(outFile, 'w')
await writeScriptHeader(handle, props)
await writeScriptPostHeader(handle, techProps)
await writeLine(handle, '')
await writeLine(handle, `const script_name = GM_info?.script?.name || 'no-name'`)
await writeLine(handle, `const script_version = GM_info?.script?.version || 'no-version'`)
await writeLine(handle, "const script_id = `${script_name} ${script_version}`")
await writeLine(handle, "console.log(`Begin - ${script_id}`)")
await writeLine(handle, '')
for (const [importName, importLines] of Object.entries(importContent.files)) {
await writeLine(handle, '')
await writeLine(handle, `// @imported_begin{${importName}}`)
for (const line of importLines) {
await writeLine(handle, line)
}
await writeLine(handle, `// @imported_end{${importName}}`)
}
await writeLine(handle, '')
await writeLine(handle, `// @main_begin{${basename}}`)
for (const line of bodyLines) {
await writeLine(handle, line)
}
await writeLine(handle, `// @main_end{${basename}}`)
await writeLine(handle, '')
await writeLine(handle, "console.log(`End - ${script_id}`)")
await close(handle)
}
const compileStyle = async (basename, content, filenames, props, userscripts, outFolder, subPath) => {
const { bodyLines, localProps } = parseStyleContent(content)
props = { ...props, ...localProps, name: basename }
await defineDefaultProps(props, filenames)
populateUserscripts(userscripts, `${subPath}${basename}.user.css`, { ...props, type: 'style' })
const outDir = `${outFolder}/${subPath}`
const isDirectory = await isDir(outDir)
if (!isDirectory) {
await makedirs(outDir)
}
const outFile = `${outDir}/${basename}.user.css`
const handle = await open(outFile, 'w')
await writeStyleHeader(handle, props)
await writeLine(handle, '')
for (const line of bodyLines) {
await writeLine(handle, line)
}
await close(handle)
}
const compileTest = async (basename, content, inFolders, outFile) => {
const { sections, bodyLines, localProps } = parseScriptContent(content)
sections.import.push(basename)
props = { ...localProps, name: basename }
techProps = {}
moveSectionsToProps(sections, props, techProps)
if (props['@import'] !== undefined) {
props['@import'].forEach((importName) => sections.import.push(importName))
delete props['@import']
}
const importContent = await resolveImports(sections.import, props, techProps, inFolders)
const handle = await open(outFile, 'w')
for (const [importName, importLines] of Object.entries(importContent.files)) {
await writeLine(handle, '')
await writeLine(handle, `// @imported_begin{${importName}}`)
for (const line of importLines) {
await writeLine(handle, line)
}
await writeLine(handle, `// @imported_end{${importName}}`)
}
await writeLine(handle, '')
await writeLine(handle, `// @test_begin{${basename}}`)
for (const line of bodyLines) {
await writeLine(handle, line)
}
await writeLine(handle, `// @test_end{${basename}}`)
await close(handle)
}
const compile = async (inFolder, outFolder, importFolders, pathName, commonProps, userscripts, restrictNames) => {
const directories = []
const scripts = {}
const styles = {}
let subPath = ''
if (commonProps === undefined) {
commonProps = []
} else {
commonProps = [...commonProps]
}
if (pathName === undefined || pathName === '') {
subPath = ''
pathName = ''
} else {
pathName = removeEnd(pathName, '/')
subPath = pathName + '/'
}
if (userscripts === undefined) {
userscripts = {}
}
const files = await fs.readdir(`${inFolder}/${pathName}`)
for (const file of files) {
const inFile = `${inFolder}/${subPath}${file}`
const isDirectory = await isDir(inFile)
const isAllowRestriction = (filename) => !restrictNames || restrictNames.map(x => x.startsWith(filename)).some(x => x);
if (isDirectory) {
directories.push(file)
} else if (file === 'common.props.json') {
commonProps.push(await readJson(inFile))
} else if (file.endsWith('.user.js')) {
if (isAllowRestriction(inFile)) {
const basename = removeEnd(file, '.user.js')
ensureKey(scripts, basename, { filenames: new Set() }).content = await readFile(inFile)
scripts[basename].filenames.add(inFile)
}
} else if (file.endsWith('.props.json')) {
if (isAllowRestriction(removeEnd(inFile, '.props.json'))) {
const basename = removeEnd(file, '.props.json')
ensureKey(scripts, basename, { filenames: new Set() }).props = await readJson(inFile)
scripts[basename].filenames.add(inFile)
}
} else if (file.endsWith('.user.css')) {
if (isAllowRestriction(inFile)) {
const basename = removeEnd(file, '.user.css')
ensureKey(styles, basename, { filenames: new Set() }).content = await readFile(inFile)
styles[basename].filenames.add(inFile)
}
} else if (file.endsWith('.props.json')) {
if (isAllowRestriction(removeEnd(inFile, '.props.json'))) {
const basename = removeEnd(file, '.props.json')
ensureKey(styles, basename, { filenames: new Set() }).props = await readJson(inFile)
styles[basename].filenames.add(inFile)
}
}
}
for (const directory of directories) {
await compile(inFolder, outFolder, importFolders, `${subPath}${directory}`, commonProps, userscripts, restrictNames)
}
for (const [basename, { content, props, filenames }] of Object.entries(scripts)) {
if (content !== undefined) {
await compileScript(basename, content, filenames, mergeProps([...commonProps, props]), userscripts, outFolder, importFolders, subPath)
}
}
for (const [basename, { content, props, filenames }] of Object.entries(styles)) {
if (content !== undefined) {
await compileStyle(basename, content, filenames, mergeProps([...commonProps, props]), userscripts, outFolder, subPath)
}
}
if (subPath === '') {
await writeJson(`${outFolder}/userscripts.json`, userscripts)
}
}
const processTest = async (inFolders, outFolder) => {
for (const inFolder of inFolders) {
const files = (await fs.readdir(`${inFolder}`)).filter(f => f.endsWith('.test.js'))
const isDirectory = await isDir(outFolder)
if (!isDirectory) {
await makedirs(outFolder)
}
for (const file of files) {
const inFile = `${inFolder}/${file}`
const outFile = `${outFolder}/${file}`
const content = await readFile(inFile)
await compileTest(removeEnd(file, '.test.js'), content, inFolders, outFile)
}
}
}
const readConfig = async (path) => {
try {
const config = await readJson(path)
return config
} catch (e) {
console.log(`Warning: Could not read config file at ${path}, using default configuration.`, e)
return {}
}
}
const getConfig = async (path) => {
let { src, dist, snippets, test } = await readConfig(path)
if (!src) {
src = 'src'
}
if (!dist) {
dist = 'dist'
}
if (!snippets) {
snippets = ['snippet']
}
if (!test) {
test = 'test'
}
return { src, dist, snippets, test }
}
const main = async (argv) => {
const { src, dist, snippets, test } = await getConfig('./userscripts.rc')
if (argv.length == 2) {
compile(src, dist, snippets)
} else if (argv.length == 3 && argv[2] === '--help') {
console.log('Usage: node compile-userscripts.js [--help] [--test]')
} else if (argv.length == 3 && argv[2] === '--test') {
processTest(snippets, test)
} else if (argv.length == 4 && argv[2] === '--script') {
const scriptname = argv[3]
compile(src, dist, snippets, undefined, undefined, undefined, [scriptname])
}
}
main(process.argv)