forked from AdguardTeam/PopupBlocker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.ts
356 lines (297 loc) · 11.3 KB
/
gulpfile.ts
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
import * as fs from 'async-file';
import * as fsExtra from 'fs-extra';
import log = require('fancy-log');
import minimist = require('minimist');
import gulp = require('gulp');
import insert = require('gulp-insert');
import preprocess = require('gulp-preprocess');
import rename = require('gulp-rename');
import rollup = require('gulp-rollup');
import uglify = require('gulp-uglify');
import file = require('gulp-file');
import xml2js = require('xml2js');
import typescript = require('@rollup/plugin-typescript');
import typescript2 = require('rollup-plugin-typescript2');
import * as closureTools from 'closure-tools-helper';
import { BuildTarget, Channel, BuildOption } from './compiler/BuildOption';
import Builder from './compiler/Builder';
import PathUtils from './compiler/PathUtils';
import { toPromise } from './compiler/utils/to_promise';
const pkg = require('./package.json');
/******************************************************************************************************/
process.setMaxListeners(0);
process.on('unhandledRejection', r => log.error(r));
/******************************************************************************************************/
const preprocessCtxt = {
NO_PROXY: true
};
const devPreprocessCtxt = {
DEBUG: true,
RECORD: true
};
// Define gulp tasks: <channel>-<target>[-[un]minified]
for (let target in BuildTarget) {
for (let channel in Channel) {
let taskName = `${Channel[channel]}-${BuildTarget[target]}`;
let option = new BuildOption(
<BuildTarget>BuildTarget[target],
<Channel>Channel[channel],
channel === 'DEV' ? devPreprocessCtxt : preprocessCtxt
);
let option_minified = option.clone();
option_minified.overrideShouldMinify = true;
let option_unminified = option.clone();
option_unminified.overrideShouldMinify = false;
gulp.task(taskName, new Builder(option).build);
gulp.task(taskName + '-minified', new Builder(option_minified).build);
gulp.task(taskName + '-unminified', new Builder(option_unminified).build);
}
}
gulp.task('build-version', () => {
const str = `version=${pkg.version}`;
return file('build.txt', str, { src: true })
.pipe(gulp.dest('build'))
});
// Define gulp tasks: build -t=chrome -c=beta --minify --use_adg_domain
gulp.task('build', gulp.series('build-version', () => {
let args = minimist(process.argv.slice(2));
let target: BuildTarget = args["target"] || args["t"];
let channel: Channel = args["channel"] || args["c"];
let overrideShouldMinify: boolean = (() => {
if ("minify" in args) {
return !!args["minify"];
}
if ("m" in args) {
return !!args["m"];
}
})();
let useAdGuardDomainForResources: boolean = args["use_adg_domain"];
let option = new BuildOption(
target,
channel,
channel === Channel.DEV ? devPreprocessCtxt : preprocessCtxt,
overrideShouldMinify,
useAdGuardDomainForResources
);
return new Builder(option).build()
}))
/******************************************************************************************************/
// UglifyJS option for dead code removal and stripping out comments.
const uglifyOptions = {
warnings: 'verbose',
mangle: false,
compress: {
sequences: false,
properties: false,
drop_debugger: true,
dead_code: true,
conditionals: false,
comparisons: false,
evaluate: false,
booleans: false,
typeofs: false,
loops: false,
unused: true,
toplevel: false,
hoist_funs: false,
if_return: false,
inline: false,
join_vars: false,
collapse_vars: false,
reduce_vars: false,
keep_fargs: true,
// UglifyJs by default does not remove functions with empty function body.
// We declare here that certain functions used for logging are side-effect free,
// so that UglifyJs can remove them.
pure_funcs: ['print', 'call', 'callEnd', 'closeAllGroup']
},
output: {
beautify: true,
comments: false,
indent_level: 2
}
};
gulp.task('greasyfork-postprocess', () => {
return gulp.src('build/userscript/popupblocker.user.js')
.pipe(uglify(uglifyOptions))
.pipe(insert.prepend(require('fs').readFileSync('build/userscript/popupblocker.meta.js').toString()))
.pipe(gulp.dest('build/userscript'));
});
/******************************************************************************************************/
function testBuilderFactory(tsconfigOverride?) {
const plugin = tsconfigOverride ? (<any>typescript2)({ tsconfigOverride }) : (<any>typescript)();
return () => {
return gulp.src(['test/**/*.ts', 'src/**/*.ts'])
.pipe(<any>preprocess({
context: {
RECORD: true
}
}))
.pipe(rollup({
entry: 'test/index.ts',
plugins: [plugin],
format: 'iife',
strict: false
}))
.pipe(rename('index.js'))
.pipe(gulp.dest('./test/build'));
}
}
gulp.task('build-test', testBuilderFactory());
gulp.task('build-test-es5', testBuilderFactory({ compilerOptions: { target: "es5" } }))
gulp.task('travis-builds', (done) => {
gulp.series('dev-userscript', 'release-userscript-settings')(done);
});
gulp.task('travis', gulp.series('travis-builds', 'build-test-es5', async () => {
const moveTasks = [
gulp.src('build/userscript/**/*')
.pipe(gulp.dest(PathUtils.outputDir)),
gulp.src('build/userscript-settings/**/*')
.pipe(gulp.dest(PathUtils.outputDir)),
gulp.src(['test/index.html', 'test/**/*.js'])
.pipe(gulp.dest(PathUtils.outputDir + '/test/')),
gulp.src('node_modules/mocha/mocha.*')
.pipe(gulp.dest(PathUtils.outputDir + '/node_modules/mocha/')),
gulp.src('node_modules/chai/chai.js')
.pipe(gulp.dest(PathUtils.outputDir + '/node_modules/chai/'))
];
await Promise.all([
fs.writeFile('build/.nojekyll', ''),
fs.writeFile('build/CNAME', 'popupblocker.adguard.com'),
...moveTasks.map(gulpTask => toPromise(gulpTask))
]);
await Promise.all([
fsExtra.remove('build/userscript'),
fsExtra.remove('build/userscript-settings')
]);
}));
gulp.task('clean', Builder.clean);
gulp.task('watch', () => {
const onerror = (error) => { console.log(error.toString()); };
const onchange = (event) => { console.log('File ' + event.path + ' was ' + event.type + ', building...'); };
gulp.watch('src/**/*', <any>['dev-userscript'])
.on('change', onchange)
.on('error', onerror);
gulp.watch('test/**/*.ts', <any>['build-test'])
.on('change', onchange)
.on('error', onerror);
});
/******************************************************************************************************/
// I18n Tasks
import SoyBuilder from './compiler/resc/SoyBuilder';
/**
* Converts xliff files generated by Closure Templates to json recognized by extension and userscripts.
*
* Note that we use a custom format that includes original phrase in descriptions.
* @todo make this robust
*/
async function xliffToJson(xliffContent: string) {
const xmlParser = new xml2js.Parser();
const json: any = await (new Promise((resolve, reject) => {
xmlParser.parseString(xliffContent, (err, data) => {
if (err) {
reject(err);
}
resolve(data);
})
}));
const error: () => never = () => {
console.log(JSON.stringify(transUnit));
throw new Error('Invalid data, check soy sources');
}
const map = Object.create(null);
const transUnit = json.xliff.file[0].body[0]['trans-unit'];
for (let unit of transUnit) {
let source = unit.source[0];
if (typeof source === 'undefined') { error(); }
if (typeof source === 'object') {
// source is string for usual messages,
// but is an object having keys '_' and 'x' in case when it contains
// placeholders
source = source._;
}
if (typeof source !== 'string') { error(); }
if (!unit.note) { continue; }
let message = unit.note[0]._;
if (typeof message !== 'string') { error(); }
if (message.length === 0) { continue; }
map[source] = { message };
}
return map;
}
gulp.task('i18n-extract', async () => {
const sauces = [
SoyBuilder.alert,
SoyBuilder.options,
SoyBuilder.userscript_options
];
await Promise.all(sauces.map(sauce => {
return toPromise(closureTools.extractTemplateMsg([
`--outputFile`, sauce.xliffPath,
sauce.soyPath
]).src());
}));
log.info("Message extraction has been finished.");
const maps = await Promise.all(sauces.map(async (sauce) => {
return await fs.readFile(sauce.xliffPath)
.then(file => file.toString())
.then(async (content) => xliffToJson(content))
}));
// Merge maps and report error when encountered multiple phrases with the same name.
const merged = Object.create(null);
for (let map of maps) {
for (let key in map) {
if (merged[key]) { // If phrase already exists
if (merged[key].message !== map[key].message) // and have different translations
throw new Error(`Phrase name collision for ${key}`);
} else {
merged[key] = map[key];
}
}
}
const writeTasks = [];
// Write translation
const misc = await fsExtra.readJSON(PathUtils.i18nMiscSourceJSONPath);
const translation = Object.assign({}, merged, misc);
writeTasks.push(PathUtils.writeJson(PathUtils.i18nSourceJSONPath, translation));
// Write userscript_keys.json
// Userscript-keys contain certain keys from misc and
// keys from alert.soy file.
const userscriptKeys = [];
const extensionKeys = [];
const settingsKeys = [];
for (let key in misc) {
let platform = misc[key].platform;
if (!platform) {
userscriptKeys.push(key);
extensionKeys.push(key);
settingsKeys.push(key);
} else {
if (platform.includes('userscript')) {
userscriptKeys.push(key);
}
if (platform.includes('extension')) {
extensionKeys.push(key);
}
if (platform.includes('userscript_settings')) {
settingsKeys.push(key);
}
}
}
for (let key in maps[0]) { // keys from alert.soy
userscriptKeys.push(key);
extensionKeys.push(key);
}
for (let key in maps[1]) {
extensionKeys.push(key);
settingsKeys.push(key);
}
for (let key in maps[2]) {
settingsKeys.push(key);
}
writeTasks.push(PathUtils.writeJson(PathUtils.i18nUserscriptKeysPath, userscriptKeys));
writeTasks.push(PathUtils.writeJson(PathUtils.i18nExtensionKeysPath, extensionKeys));
writeTasks.push(PathUtils.writeJson(PathUtils.i18nSettingsKeysPath, settingsKeys));
await Promise.all(writeTasks);
});
/******************************************************************************************************/