forked from utags/userscripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.mjs
More file actions
74 lines (60 loc) · 2.02 KB
/
Copy pathbuild.mjs
File metadata and controls
74 lines (60 loc) · 2.02 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
import fs from 'node:fs'
import process from 'node:process'
import * as esbuild from 'esbuild'
import { getBuildOptions } from '../common.mjs'
const target = 'userscript'
const tag = process.argv.includes('--staging') ? 'staging' : 'prod'
const packageName = process.argv.filter((v) => v !== '--staging')[2]
if (!packageName) {
console.error('Please specify a package name')
process.exit(1)
}
const config = JSON.parse(fs.readFileSync('package.json', 'utf8'))
let banner = fs.readFileSync(`src/packages/${packageName}/banner.txt`, 'utf8')
if (tag !== 'prod') {
banner = banner.replaceAll(/(@name(:[\w-]+)?\s.+)/gm, `$1 - ${tag}`)
}
const buildOptions = {
...getBuildOptions(target, tag, `packages/${packageName}/index`),
banner: {
js: banner,
},
legalComments: 'none',
outfile:
tag === 'prod'
? `${packageName}/${packageName}.user.js`
: `${packageName}/${packageName}-${tag}.user.js`,
}
buildOptions.alias = {
...buildOptions.alias,
'browser-extension-storage': 'browser-extension-storage/userscript',
'browser-extension-utils': 'browser-extension-utils/userscript',
}
await esbuild.build(buildOptions)
let text = fs.readFileSync(buildOptions.outfile, 'utf8')
if (config.bugs && config.bugs.url) {
text = text.replace('{bugs.url}', config.bugs.url)
}
const keys = banner
.split('\n')
.map((v) => /{([\w\-.:]+)}/.exec(v))
.filter(Boolean)
.map((v) => v[1])
for (const key of keys) {
text = text.replace('{' + key + '}', config[key])
}
// Get all userscript GM_* and GM.* functions
const matched = new Set()
text.replaceAll(/(GM[_.]\w+)/gm, (match) => {
matched.add(match)
})
const grants = [...matched]
.map((v) => `// @grant${' '.repeat(16)}${v}`)
.join('\n')
text = text.replace('// ==/UserScript==', `${grants}\n// ==/UserScript==`)
// Replace first one to 'use strict'
text = text.replace('{', '{\n "use strict";')
// Remove all commenets start with '// '
text = text.replaceAll(/^\s*\/\/ [^=@].*$/gm, '')
text = text.replaceAll(/\n+/gm, '\n')
fs.writeFileSync(buildOptions.outfile, text)