Repository navigation
Expand file tree
/
Copy pathbuild.js
More file actions
226 lines (195 loc) · 7.43 KB
/
Copy pathbuild.js
File metadata and controls
226 lines (195 loc) · 7.43 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
#!/usr/bin/env node
// build.js — discovers every script under scripts/*/src/index.ts and builds it
import * as esbuild from 'esbuild';
import { glob } from 'glob';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const isWatch = process.argv.includes('--watch');
const isDebug = process.argv.includes('--debug');
const scriptFilterIndex = process.argv.indexOf('--script');
const scriptFilter = scriptFilterIndex >= 0 ? process.argv[scriptFilterIndex + 1] : '';
const repoRoot = path.dirname(fileURLToPath(import.meta.url));
const pkg = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8'));
// Default feature flags (can be overridden per-script via .build-flags.json)
const DEFAULT_FLAGS = {
__ENABLE_AD_BYPASS__: 'true',
__ENABLE_AUTO_FULLSCREEN__: 'true',
__ENABLE_AUTO_PLAY__: 'true',
__ENABLE_WATCHLIST__: 'true',
__ENABLE_UI_OVERLAY__: 'true',
__ENABLE_PAGE_HELPERS__: 'true',
__ENABLE_VIDEO_OBSERVER__: 'true',
};
function readScriptFlags(scriptDir) {
const flagsFile = isDebug ? '.build-flags-debug.json' : '.build-flags.json';
const flagsPath = path.join(scriptDir, flagsFile);
if (!fs.existsSync(flagsPath)) return { ...DEFAULT_FLAGS };
try {
const customFlags = JSON.parse(fs.readFileSync(flagsPath, 'utf8'));
const flags = {
__ENABLE_AD_BYPASS__: customFlags.adBypass ? 'true' : 'false',
__ENABLE_AUTO_FULLSCREEN__: customFlags.autoFullscreen ? 'true' : 'false',
__ENABLE_AUTO_PLAY__: customFlags.autoPlay ? 'true' : 'false',
__ENABLE_WATCHLIST__: customFlags.watchlist ? 'true' : 'false',
__ENABLE_UI_OVERLAY__: customFlags.uiOverlay ? 'true' : 'false',
__ENABLE_PAGE_HELPERS__: customFlags.pageHelpers ? 'true' : 'false',
__ENABLE_VIDEO_OBSERVER__: customFlags.videoObserver ? 'true' : 'false',
};
console.log(`[build] Loaded flags from ${flagsPath}:`, flags);
return flags;
} catch (e) {
console.warn(`[build] Failed to read flags from ${flagsPath}, using defaults`);
return { ...DEFAULT_FLAGS };
}
}
const repoUrl =
pkg.repository?.url?.replace('git+', '').replace('.git', '') ||
'https://github.com/unknown/tampermonkey-scripts';
const rawUrl = repoUrl.replace('github.com', 'raw.githubusercontent.com');
const branch = 'main';
function readMetaBanner(scriptDir) {
const metaPath = path.join(scriptDir, 'src', 'meta.ts');
if (!fs.existsSync(metaPath)) return '';
const content = fs.readFileSync(metaPath, 'utf8');
const match = content.match(/\/\*[\s\S]*?\*\//);
return match ? match[0] + '\n\n' : '';
}
function readVersion(scriptDir) {
const metaPath = path.join(scriptDir, 'src', 'meta.ts');
if (!fs.existsSync(metaPath)) return '0.0.0';
const content = fs.readFileSync(metaPath, 'utf8');
const match = content.match(/@version\s+(\S+)/);
return match ? match[1] : '0.0.0';
}
function readMetaMatches(scriptDir) {
const metaPath = path.join(scriptDir, 'src', 'meta.ts');
if (!fs.existsSync(metaPath)) return ['*://*.example.com/*'];
const content = fs.readFileSync(metaPath, 'utf8');
const matches = [...content.matchAll(/@match\s+(.+)/g)].map((match) => match[1].trim());
return matches.length ? matches : ['*://*.example.com/*'];
}
function readMetaRunAt(scriptDir) {
const metaPath = path.join(scriptDir, 'src', 'meta.ts');
if (!fs.existsSync(metaPath)) return 'document-start';
const content = fs.readFileSync(metaPath, 'utf8');
const match = content.match(/@run-at\s+(\S+)/);
return match ? match[1].trim() : 'document-start';
}
function readMetaValues(scriptDir, key) {
const metaPath = path.join(scriptDir, 'src', 'meta.ts');
if (!fs.existsSync(metaPath)) return [];
const content = fs.readFileSync(metaPath, 'utf8');
return [...content.matchAll(new RegExp(`@${key}\\s+(.+)`, 'g'))]
.map((match) => match[1].trim())
.filter((value) => value && value !== 'none');
}
function generateLoader(scriptDir, scriptName) {
const loaderPath = path.join(scriptDir, 'tampermonkey-loader.user.js');
const scriptUrl = `${rawUrl}/${branch}/scripts/${scriptName}/dist/${scriptName}.user.js`;
const matchLines = readMetaMatches(scriptDir)
.map((match) => `// @match ${match}`)
.join('\n');
const runAt = readMetaRunAt(scriptDir);
const grantLines = [
...new Set(['GM_xmlhttpRequest', ...readMetaValues(scriptDir, 'grant')]),
]
.map((grant) => `// @grant ${grant}`)
.join('\n');
const connectLines = [
...new Set(['github.com', 'raw.githubusercontent.com', ...readMetaValues(scriptDir, 'connect')]),
]
.map((connect) => `// @connect ${connect}`)
.join('\n');
const template = `// ==UserScript==
// @name ${scriptName} (loader)
// @namespace ${pkg.repository?.url?.replace('git+', '').replace('.git', '') || 'http://tampermonkey.net/'}
// @version 1.0.0
// @description Loader — fetches the latest build from GitHub
${matchLines}
// @run-at ${runAt}
${grantLines}
${connectLines}
// ==/UserScript==
(function () {
'use strict';
const SCRIPT_URL = '${scriptUrl}';
GM_xmlhttpRequest({
method: 'GET',
url: SCRIPT_URL + '?_=' + Date.now(),
onload(res) {
if (res.status === 200) {
eval(res.responseText);
console.log('[loader] Successfully loaded script from:', SCRIPT_URL);
} else {
console.error('[loader] Failed to fetch script:', res.status, SCRIPT_URL);
}
},
onerror(err) {
console.error('[loader] Network error fetching script:', err);
},
});
})();
`;
fs.writeFileSync(loaderPath, template);
console.log(`[loader] ${scriptName} → ${loaderPath}`);
}
async function buildScript(entryPoint) {
const scriptDir = path.dirname(path.dirname(entryPoint));
const scriptName = path.basename(scriptDir);
const outDir = path.join(scriptDir, isDebug ? 'dist-debug' : 'dist');
const outFile = path.join(outDir, `${scriptName}${isDebug ? '.debug' : ''}.user.js`);
fs.mkdirSync(outDir, { recursive: true });
const banner = readMetaBanner(scriptDir);
const version = readVersion(scriptDir);
const buildDate = new Date().toISOString();
const scriptFlags = readScriptFlags(scriptDir);
const buildOptions = {
entryPoints: [entryPoint],
bundle: true,
outfile: outFile,
format: 'iife',
platform: 'browser',
target: 'es2020',
sourcemap: false,
minify: true,
banner: {
js: banner,
},
define: {
'process.env.NODE_ENV': '"production"',
__VERSION__: JSON.stringify(version),
__BUILD_DATE__: JSON.stringify(buildDate),
__SCRIPT_NAME__: JSON.stringify(scriptName),
...scriptFlags,
},
logLevel: 'info',
};
if (isWatch) {
const ctx = await esbuild.context(buildOptions);
await ctx.watch();
console.log(`[watch${isDebug ? ' DEBUG' : ''}] ${scriptName}`);
} else {
await esbuild.build(buildOptions);
console.log(`[built${isDebug ? ' DEBUG' : ''}] ${scriptName} → ${outFile}`);
}
generateLoader(scriptDir, scriptName);
}
async function main() {
const pattern = scriptFilter
? `scripts/${scriptFilter}/src/index.ts`
: 'scripts/*/src/index.ts';
const entries = await glob(pattern, { cwd: repoRoot });
if (entries.length === 0) {
console.warn('No scripts found. Expected scripts/*/src/index.ts');
process.exit(0);
}
await Promise.all(entries.map((entry) => buildScript(path.join(repoRoot, entry))));
if (!isWatch) {
console.log(`\nBuilt ${entries.length} script(s).`);
}
}
main().catch((err) => {
console.error(err);
process.exit(1);
});