forked from tutao/tutanota
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdist.js
399 lines (360 loc) · 16.2 KB
/
dist.js
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
"use strict"
const options = require('commander')
const Promise = require('bluebird')
const fs = Promise.promisifyAll(require("fs-extra"))
const Builder = require('systemjs-builder')
let version = require('./package.json').version
const env = require('./buildSrc/env.js')
const LaunchHtml = require('./buildSrc/LaunchHtml.js')
const spawnSync = require('child_process').spawnSync
const glob = require('glob')
const path = require("path")
const os = require("os")
const SystemConfig = require('./buildSrc/SystemConfig.js')
const builder = new Builder(SystemConfig.distBuildConfig()) // baseURL and configuration
const babelCompile = require('./buildSrc/Builder.js').babelCompile
let start = Date.now()
const DistDir = 'build/dist'
let bundles = {}
const bundlesCache = "build/bundles.json"
function getAsyncImports(file) {
let appSrc = fs.readFileSync(path.resolve(__dirname, file), 'utf-8')
const regExp = /_asyncImport\(["|'](.*?)["|']\)/g
let match = regExp.exec(appSrc)
let asyncImports = []
while (match != null) {
asyncImports.push(match[1])
match = regExp.exec(appSrc)
}
//console.log(`async imports for ${file}: ${asyncImports.join(" + ")}`)
return asyncImports
}
const distLoc = (filename) => `${DistDir}/${filename}`
options
.usage('[options] [test|prod|local|release|host <url>], "release" is default')
.arguments('[stage] [host]')
.option('-e, --existing', 'Use existing prebuilt Webapp files in /build/dist/')
.option('-w --win', 'Build desktop client for windows')
.option('-l --linux', 'Build desktop client for linux')
.option('-m --mac', 'Build desktop client for mac')
.option('-d, --deb', 'Build .deb package')
.option('-p, --publish', 'Git tag and upload package, only allowed in release stage. Implies -d.')
.action((stage, host) => {
if (!["test", "prod", "local", "host", "release", undefined].includes(stage)
|| (stage !== "host" && host)
|| (stage === "host" && !host)
|| stage !== "release" && options.publish) {
options.outputHelp()
process.exit(1)
}
options.stage = stage || "release"
options.host = host
options.deb = options.deb || options.publish
options.desktop = {
win: options.win ? [] : undefined,
linux: options.linux ? [] : undefined,
mac: options.mac ? [] : undefined
}
options.desktop = Object.values(options.desktop).some(Boolean)
? options.desktop
: undefined
})
.parse(process.argv)
Promise.resolve()
.then(buildWebapp)
.then(buildDesktopClient)
.then(packageDeb)
.then(publish)
.then(() => {
const now = new Date(Date.now()).toTimeString().substr(0, 5)
console.log(`\nBuild time: ${measure()}s (${now})`)
})
.catch(e => {
console.log("\nBuild error:", e)
process.exit(1)
})
function measure() {
return (Date.now() - start) / 1000
}
function clean() {
return fs.removeAsync("build")
.then(() => fs.ensureDirAsync(DistDir + "/translations"))
}
function buildWebapp() {
if (options.existing) {
console.log("Found existing option (-e). Skipping Webapp build.")
return fs.readFileAsync(path.join(__dirname, bundlesCache)).then(bundlesCache => {
bundles = JSON.parse(bundlesCache)
})
}
return Promise.resolve()
.then(() => console.log("started cleaning", measure()))
.then(() => clean())
.then(() => console.log("started copying images", measure()))
.then(() => fs.copyAsync(path.join(__dirname, '/resources/favicon'), path.join(__dirname, '/build/dist/images')))
.then(() => fs.copyAsync(path.join(__dirname, '/resources/images'), path.join(__dirname, '/build/dist/images')))
.then(() => fs.readFileAsync('src/api/worker/WorkerBootstrap.js', 'utf-8').then(bootstrap => {
let lines = bootstrap.split("\n")
lines[0] = `importScripts('libs.js')`
let code = babelCompile(lines.join("\n")).code
return fs.writeFileAsync('build/dist/WorkerBootstrap.js', code, 'utf-8')
}))
.then(() => {
console.log("started tracing", measure())
return Promise.all([
builder.trace('src/api/worker/WorkerImpl.js + src/api/entities/*/* + src/system-resolve.js + libs/polyfill.js'),
builder.trace('src/app.js + src/system-resolve.js'),
builder.trace('src/gui/theme.js - libs/stream.js'),
builder.trace(getAsyncImports('src/app.js')
.concat(getAsyncImports('src/native/NativeWrapper.js'))
.concat(getAsyncImports('src/native/NativeWrapperCommands.js'))
.concat([
"src/login/LoginViewController.js",
"src/gui/base/icons/Icons.js",
"src/search/SearchBar.js",
"src/subscription/terms.js"
]).join(" + "))
])
})
.then(([workerTree, bootTree, themeTree, mainTree]) => {
console.log("started bundling", measure())
let commonTree = builder.intersectTrees(workerTree, mainTree)
return Promise.all([
bundle(commonTree, distLoc("common.js"), bundles),
bundle(builder.subtractTrees(workerTree, commonTree), distLoc("worker.js"), bundles),
bundle(builder.subtractTrees(builder.subtractTrees(builder.subtractTrees(mainTree, commonTree), bootTree), themeTree), distLoc("main.js"), bundles),
bundle(builder.subtractTrees(themeTree, commonTree), distLoc("theme.js"), bundles),
bundle(builder.subtractTrees(bootTree, themeTree), distLoc("main-boot.js"), bundles)
])
})
.then(() => console.log("creating language bundles"))
.then(() => createLanguageBundles(bundles))
.then(() => {
let restUrl
if (options.stage === 'test') {
restUrl = 'https://test.tutanota.com'
} else if (options.stage === 'prod') {
restUrl = 'https://mail.tutanota.com'
} else if (options.stage === 'local') {
restUrl = "http://" + os.hostname().split(".")[0] + ":9000"
} else if (options.stage === 'release') {
restUrl = undefined
} else { // host
restUrl = options.host
}
return Promise.all([
createHtml(env.create(SystemConfig.distRuntimeConfig(bundles),
(options.stage === 'release' || options.stage === 'local')
? null
: restUrl, version, "Browser", true), bundles),
(options.stage !== 'release')
? createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), restUrl, version, "App", true), bundles)
: null,
])
})
.then(() => bundleServiceWorker(bundles))
.then(copyDependencies)
.then(() => _writeFile(path.join(__dirname, bundlesCache), JSON.stringify(bundles)))
}
function buildDesktopClient() {
if (options.desktop) {
const desktopBuilder = require('./buildSrc/DesktopBuilder.js')
if (options.stage === "release") {
return createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), "https://mail.tutanota.com", version, "Desktop", true), bundles)
.then(() => desktopBuilder.build(__dirname, version, options.desktop, "https://mail.tutanota.com/desktop", ""))
.then(() => createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), "https://test.tutanota.com", version, "Desktop", true), bundles))
.then(() => desktopBuilder.build(__dirname, version, options.desktop, "https://test.tutanota.com/desktop", "-test"))
} else if (options.stage === "local") {
return createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), "http://localhost:9000", version, "Desktop", true), bundles)
.then(() => desktopBuilder.build(__dirname, `${new Date().getTime()}.0.0`,
options.desktop, "http://localhost:9000", "-snapshot"))
} else if (options.stage === "test") {
return createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), "https://test.tutanota.com", version, "Desktop", true), bundles)
.then(() => desktopBuilder.build(__dirname, `${new Date().getTime()}.0.0`,
options.desktop, "http://localhost:9000/desktop", "-test"))
} else if (options.stage === "prod") {
return createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), "https://mail.tutanota.com", version, "Desktop", true), bundles)
.then(() => desktopBuilder.build(__dirname, `${new Date().getTime()}.0.0`,
options.desktop, "http://localhost:9000/desktop", ""))
} else { // stage = host
return createHtml(env.create(SystemConfig.distRuntimeConfig(bundles), options.host, version, "Desktop", true), bundles)
.then(() => desktopBuilder.build(__dirname, `${new Date().getTime()}.0.0`,
options.desktop, "http://localhost:9000/desktop-snapshot", "-snapshot"))
}
}
}
const buildConfig = {
minify: true,
mangle: false, // destroys type information (e.g. used for bluebird catch blocks)
runtime: false,
sourceMaps: true,
sourceMapContents: true
}
function bundle(src, targetFile, bundles) {
return builder.bundle(src, targetFile, buildConfig).then(function (output) {
bundles[path.basename(targetFile)] = output.modules.sort()
console.log(` > bundled ${targetFile}`);
return bundles
}).catch(function (err) {
console.log('Build error in bundle ' + targetFile);
throw err
})
}
function bundleServiceWorker(bundles) {
return fs.readFileAsync("src/serviceworker/sw.js", "utf8").then((content) => {
const filesToCache = ["index.js", "WorkerBootstrap.js", "index.html", "libs.js"]
.concat(Object.keys(bundles).filter(b => !b.startsWith("translations")))
.concat(["images/logo-favicon.png", "images/logo-favicon-152.png", "images/logo-favicon-196.png", "images/ionicons.ttf"])
// Using "function" to hoist declaration, var wouldn't work in this case and we cannot prepend because
// of "delcare var"
const customDomainFileExclusions = ["index.html", "index.js"]
content = content + "\n" + "function filesToCache() { return " + JSON.stringify(filesToCache) + "}"
+ "\n function version() { return \"" + version + "\"}"
+ "\n" + "function customDomainCacheExclusions() { return " + JSON.stringify(customDomainFileExclusions)
+ "}"
return babelCompile(content).code
}).then((content) => _writeFile(distLoc("sw.js"), content))
}
function copyDependencies() {
let libs = SystemConfig.baseProdDependencies.map(file => fs.readFileSync(file, 'utf-8')).join("\n")
return fs.writeFileSync('build/dist/libs.js', libs, 'utf-8')
}
function createHtml(env) {
let filenamePrefix
switch (env.mode) {
case "App":
filenamePrefix = "app"
break
case "Browser":
filenamePrefix = "index"
break
case "Desktop":
filenamePrefix = "desktop"
}
let imports = ["libs.js", "main-boot.js", `${filenamePrefix}.js`]
return Promise.all([
_writeFile(`./build/dist/${filenamePrefix}.js`, [
`window.whitelabelCustomizations = null`,
`window.env = ${JSON.stringify(env, null, 2)}`,
`System.config(env.systemConfig)`,
`System.import("src/system-resolve.js").then(function() { System.import('src/app.js') })`,
].join("\n")),
_writeFile(`./build/dist/${filenamePrefix}.html`, LaunchHtml.renderHtml(imports, env))
])
}
function createLanguageBundles(bundles) {
const languageFiles = options.stage === 'release' || options.stage === 'prod'
? glob.sync('src/translations/*.js')
: ['src/translations/en.js', 'src/translations/de.js', 'src/translations/de_sie.js', 'src/translations/ru.js']
return Promise.all(languageFiles.map(translation => {
let filename = path.basename(translation)
return builder.bundle(translation, {
minify: false,
mangle: false,
runtime: false,
sourceMaps: false
}).then(function (output) {
const bundle = `${DistDir}/translations/${filename}`
bundles["translations/" + filename] = output.modules.sort()
fs.writeFileSync(bundle, output.source, 'utf-8')
console.log(` > bundled ${bundle}`);
})
})).then(() => bundles)
}
function _writeFile(targetFile, content) {
return fs.mkdirsAsync(path.dirname(targetFile)).then(() => fs.writeFileAsync(targetFile, content, 'utf-8'))
}
let webAppDebName = `tutanota_${version}_amd64.deb`
let desktopDebName = `tutanota-desktop_${version}_amd64.deb`
let desktopTestDebName = `tutanota-desktop-test_${version}_amd64.deb`
function packageDeb() {
if (options.deb) {
const target = `/opt/tutanota`
exitOnFail(spawnSync("/usr/bin/find", `. ( -name *.js -o -name *.html ) -exec gzip -fkv --best {} \;`.split(" "), {
cwd: __dirname + '/build/dist',
stdio: [process.stdin, process.stdout, process.stderr]
}))
console.log("create " + webAppDebName)
exitOnFail(spawnSync("/usr/local/bin/fpm", `-f -s dir -t deb --deb-user tutadb --deb-group tutadb -n tutanota -v ${version} dist/=${target}`.split(" "), {
cwd: __dirname + '/build',
stdio: [process.stdin, process.stdout, process.stderr]
}))
console.log("create " + desktopDebName)
exitOnFail(spawnSync("/usr/local/bin/fpm", `-f -s dir -t deb --deb-user tutadb --deb-group tutadb -n tutanota-desktop -v ${version} desktop/=${target}-desktop`.split(" "), {
cwd: __dirname + '/build',
stdio: [process.stdin, process.stdout, process.stderr]
}))
console.log("create " + desktopTestDebName)
exitOnFail(spawnSync("/usr/local/bin/fpm", `-f -s dir -t deb --deb-user tutadb --deb-group tutadb -n tutanota-desktop-test -v ${version} desktop-test/=${target}-desktop`.split(" "), {
cwd: __dirname + '/build',
stdio: [process.stdin, process.stdout, process.stderr]
}))
}
}
function publish() {
if (options.publish) {
console.log("Create git tag and copy .deb")
exitOnFail(spawnSync("/usr/bin/git", `tag -a tutanota-release-${version} -m ''`.split(" "), {
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/usr/bin/git", `push origin tutanota-release-${version}`.split(" "), {
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/cp", `-f build/${webAppDebName} /opt/repository/tutanota/`.split(" "), {
cwd: __dirname,
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/cp", `-f build/${desktopDebName} /opt/repository/tutanota-desktop/`.split(" "), {
cwd: __dirname,
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/cp", `-f build/${desktopTestDebName} /opt/repository/tutanota-desktop-test/`.split(" "), {
cwd: __dirname,
stdio: [process.stdin, process.stdout, process.stderr]
}))
// copy appimage for dev_clients
exitOnFail(spawnSync("/bin/cp", `-f build/desktop/tutanota-desktop-linux.AppImage /opt/repository/dev_client/`.split(" "), {
cwd: __dirname,
stdio: [process.stdin, process.stdout, process.stderr]
}))
// user puppet needs to read the deb file from jetty
exitOnFail(spawnSync("/bin/chmod", `o+r /opt/repository/tutanota/${webAppDebName}`.split(" "), {
cwd: __dirname + '/build/',
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/chmod", `o+r /opt/repository/tutanota-desktop/${desktopDebName}`.split(" "), {
cwd: __dirname + '/build/',
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/chmod", `o+r /opt/repository/tutanota-desktop-test/${desktopTestDebName}`.split(" "), {
cwd: __dirname + '/build/',
stdio: [process.stdin, process.stdout, process.stderr]
}))
exitOnFail(spawnSync("/bin/chmod", `o+r /opt/repository/dev_client/tutanota-desktop-linux.AppImage`.split(" "), {
cwd: __dirname + '/build/',
stdio: [process.stdin, process.stdout, process.stderr]
}))
}
}
function exitOnFail(result) {
if (result.status !== 0) {
throw new Error("error invoking process" + JSON.stringify(result))
}
}
function printTraceReport(trace) {
function formatNumber(number) {
number = number + ""
while (number.length < 6) {
number = '0' + number
}
return number
}
let size = 0
let filesAndSizes = Object.keys(trace).map(file => {
return {
file,
length: trace[file].source.length
}
}).sort((a, b) => a.length - b.length)
console.log(filesAndSizes.map(o => formatNumber(o.length) + ": " + o.file).join("\n" + " > "))
}