-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathpackager.ts
655 lines (540 loc) · 22.3 KB
/
packager.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
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
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
import {
addValue,
Arch,
archFromString,
AsyncTaskManager,
DebugLogger,
deepAssign,
executeFinally,
getArtifactArchName,
InvalidConfigurationError,
log,
MAX_FILE_REQUESTS,
orNullIfFileNotExist,
safeStringifyJson,
serializeToYaml,
TmpDir,
} from "builder-util"
import { CancellationToken } from "builder-util-runtime"
import { chmod, mkdirs, outputFile } from "fs-extra"
import * as isCI from "is-ci"
import { Lazy } from "lazy-val"
import { release as getOsRelease } from "os"
import * as path from "path"
import { AppInfo } from "./appInfo"
import { readAsarJson } from "./asar/asar"
import { AfterExtractContext, AfterPackContext, BeforePackContext, Configuration, Hook } from "./configuration"
import { Platform, SourceRepositoryInfo, Target } from "./core"
import { createElectronFrameworkSupport } from "./electron/ElectronFramework"
import { Framework } from "./Framework"
import { LibUiFramework } from "./frameworks/LibUiFramework"
import { Metadata } from "./options/metadata"
import { ArtifactBuildStarted, ArtifactCreated, PackagerOptions } from "./packagerApi"
import { PlatformPackager } from "./platformPackager"
import { ProtonFramework } from "./ProtonFramework"
import { computeArchToTargetNamesMap, createTargets, NoOpTarget } from "./targets/targetFactory"
import { computeDefaultAppDirectory, getConfig, validateConfiguration } from "./util/config/config"
import { expandMacro } from "./util/macroExpander"
import { createLazyProductionDeps, NodeModuleDirInfo, NodeModuleInfo } from "./util/packageDependencies"
import { checkMetadata, readPackageJson } from "./util/packageMetadata"
import { getRepositoryInfo } from "./util/repositoryInfo"
import { resolveFunction } from "./util/resolve"
import { installOrRebuild, nodeGypRebuild } from "./util/yarn"
import { PACKAGE_VERSION } from "./version"
import { AsyncEventEmitter, HandlerType } from "./util/asyncEventEmitter"
import asyncPool from "tiny-async-pool"
async function createFrameworkInfo(configuration: Configuration, packager: Packager): Promise<Framework> {
let framework = configuration.framework
if (framework != null) {
framework = framework.toLowerCase()
}
let nodeVersion = configuration.nodeVersion
if (framework === "electron" || framework == null) {
return await createElectronFrameworkSupport(configuration, packager)
}
if (nodeVersion == null || nodeVersion === "current") {
nodeVersion = process.versions.node
}
const distMacOsName = `${packager.appInfo.productFilename}.app`
const isUseLaunchUi = configuration.launchUiVersion !== false
if (framework === "proton" || framework === "proton-native") {
return new ProtonFramework(nodeVersion, distMacOsName, isUseLaunchUi)
} else if (framework === "libui") {
return new LibUiFramework(nodeVersion, distMacOsName, isUseLaunchUi)
} else {
throw new InvalidConfigurationError(`Unknown framework: ${framework}`)
}
}
type PackagerEvents = {
artifactBuildStarted: Hook<ArtifactBuildStarted, void>
beforePack: Hook<BeforePackContext, void>
afterExtract: Hook<AfterExtractContext, void>
afterPack: Hook<AfterPackContext, void>
afterSign: Hook<AfterPackContext, void>
artifactBuildCompleted: Hook<ArtifactCreated, void>
msiProjectCreated: Hook<string, void>
appxManifestCreated: Hook<string, void>
// internal-use only, prefer usage of `artifactBuildCompleted`
artifactCreated: Hook<ArtifactCreated, void>
}
export class Packager {
readonly projectDir: string
private _appDir: string
get appDir(): string {
return this._appDir
}
private _metadata: Metadata | null = null
get metadata(): Metadata {
return this._metadata!
}
private _nodeModulesHandledExternally = false
get areNodeModulesHandledExternally(): boolean {
return this._nodeModulesHandledExternally
}
private _isPrepackedAppAsar = false
get isPrepackedAppAsar(): boolean {
return this._isPrepackedAppAsar
}
private _devMetadata: Metadata | null = null
get devMetadata(): Metadata | null {
return this._devMetadata
}
private _configuration: Configuration | null = null
get config(): Configuration {
return this._configuration!
}
isTwoPackageJsonProjectLayoutUsed = false
private readonly eventEmitter = new AsyncEventEmitter<PackagerEvents>()
_appInfo: AppInfo | null = null
get appInfo(): AppInfo {
return this._appInfo!
}
readonly tempDirManager = new TmpDir("packager")
private _repositoryInfo = new Lazy<SourceRepositoryInfo | null>(() => getRepositoryInfo(this.projectDir, this.metadata, this.devMetadata))
readonly options: PackagerOptions
readonly debugLogger = new DebugLogger(log.isDebugEnabled)
get repositoryInfo(): Promise<SourceRepositoryInfo | null> {
return this._repositoryInfo.value
}
private nodeDependencyInfo = new Map<string, Lazy<Array<any>>>()
getNodeDependencyInfo(platform: Platform | null, flatten: boolean = true): Lazy<Array<NodeModuleInfo | NodeModuleDirInfo>> {
let key = "" + flatten.toString()
let excludedDependencies: Array<string> | null = null
if (platform != null && this.framework.getExcludedDependencies != null) {
excludedDependencies = this.framework.getExcludedDependencies(platform)
if (excludedDependencies != null) {
key += `-${platform.name}`
}
}
let result = this.nodeDependencyInfo.get(key)
if (result == null) {
result = createLazyProductionDeps(this.appDir, excludedDependencies, flatten)
this.nodeDependencyInfo.set(key, result)
}
return result
}
stageDirPathCustomizer: (target: Target, packager: PlatformPackager<any>, arch: Arch) => string = (target, packager, arch) => {
return path.join(target.outDir, `__${target.name}-${getArtifactArchName(arch, target.name)}`)
}
private _buildResourcesDir: string | null = null
get buildResourcesDir(): string {
let result = this._buildResourcesDir
if (result == null) {
result = path.resolve(this.projectDir, this.relativeBuildResourcesDirname)
this._buildResourcesDir = result
}
return result
}
get relativeBuildResourcesDirname(): string {
return this.config.directories!.buildResources!
}
private _framework: Framework | null = null
get framework(): Framework {
return this._framework!
}
private readonly toDispose: Array<() => Promise<void>> = []
disposeOnBuildFinish(disposer: () => Promise<void>) {
this.toDispose.push(disposer)
}
//noinspection JSUnusedGlobalSymbols
constructor(
options: PackagerOptions,
readonly cancellationToken = new CancellationToken()
) {
if ("devMetadata" in options) {
throw new InvalidConfigurationError("devMetadata in the options is deprecated, please use config instead")
}
if ("extraMetadata" in options) {
throw new InvalidConfigurationError("extraMetadata in the options is deprecated, please use config.extraMetadata instead")
}
const targets = options.targets || new Map<Platform, Map<Arch, Array<string>>>()
if (options.targets == null) {
options.targets = targets
}
function processTargets(platform: Platform, types: Array<string>) {
function commonArch(currentIfNotSpecified: boolean): Array<Arch> {
const result = Array<Arch>()
return result.length === 0 && currentIfNotSpecified ? [archFromString(process.arch)] : result
}
let archToType = targets.get(platform)
if (archToType == null) {
archToType = new Map<Arch, Array<string>>()
targets.set(platform, archToType)
}
if (types.length === 0) {
for (const arch of commonArch(false)) {
archToType.set(arch, [])
}
return
}
for (const type of types) {
const suffixPos = type.lastIndexOf(":")
if (suffixPos > 0) {
addValue(archToType, archFromString(type.substring(suffixPos + 1)), type.substring(0, suffixPos))
} else {
for (const arch of commonArch(true)) {
addValue(archToType, arch, type)
}
}
}
}
if (options.mac != null) {
processTargets(Platform.MAC, options.mac)
}
if (options.linux != null) {
processTargets(Platform.LINUX, options.linux)
}
if (options.win != null) {
processTargets(Platform.WINDOWS, options.win)
}
this.projectDir = options.projectDir == null ? process.cwd() : path.resolve(options.projectDir)
this._appDir = this.projectDir
this.options = {
...options,
prepackaged: options.prepackaged == null ? null : path.resolve(this.projectDir, options.prepackaged),
}
log.info({ version: PACKAGE_VERSION, os: getOsRelease() }, "electron-builder")
}
async addPackagerEventHandlers() {
const { type } = this.appInfo
this.eventEmitter.on("artifactBuildStarted", await resolveFunction(type, this.config.artifactBuildStarted, "artifactBuildStarted"), "user")
this.eventEmitter.on("artifactBuildCompleted", await resolveFunction(type, this.config.artifactBuildCompleted, "artifactBuildCompleted"), "user")
this.eventEmitter.on("appxManifestCreated", await resolveFunction(type, this.config.appxManifestCreated, "appxManifestCreated"), "user")
this.eventEmitter.on("msiProjectCreated", await resolveFunction(type, this.config.msiProjectCreated, "msiProjectCreated"), "user")
this.eventEmitter.on("beforePack", await resolveFunction(type, this.config.beforePack, "beforePack"), "user")
this.eventEmitter.on("afterExtract", await resolveFunction(type, this.config.afterExtract, "afterExtract"), "user")
this.eventEmitter.on("afterPack", await resolveFunction(type, this.config.afterPack, "afterPack"), "user")
this.eventEmitter.on("afterSign", await resolveFunction(type, this.config.afterSign, "afterSign"), "user")
}
onAfterPack(handler: PackagerEvents["afterPack"]): Packager {
this.eventEmitter.on("afterPack", handler)
return this
}
onArtifactCreated(handler: PackagerEvents["artifactCreated"]): Packager {
this.eventEmitter.on("artifactCreated", handler)
return this
}
filterPackagerEventListeners(event: keyof PackagerEvents, type: HandlerType | undefined) {
return this.eventEmitter.filterListeners(event, type)
}
clearPackagerEventListeners() {
this.eventEmitter.clear()
}
async emitArtifactBuildStarted(event: ArtifactBuildStarted, logFields?: any) {
log.info(
logFields || {
target: event.targetPresentableName,
arch: event.arch == null ? null : Arch[event.arch],
file: log.filePath(event.file),
},
"building"
)
await this.eventEmitter.emit("artifactBuildStarted", event)
}
/**
* Only for sub artifacts (update info), for main artifacts use `callArtifactBuildCompleted`.
*/
async emitArtifactCreated(event: ArtifactCreated) {
await this.eventEmitter.emit("artifactCreated", event)
}
async emitArtifactBuildCompleted(event: ArtifactCreated) {
await this.eventEmitter.emit("artifactBuildCompleted", event)
await this.emitArtifactCreated(event)
}
async emitAppxManifestCreated(path: string) {
await this.eventEmitter.emit("appxManifestCreated", path)
}
async emitMsiProjectCreated(path: string) {
await this.eventEmitter.emit("msiProjectCreated", path)
}
async emitBeforePack(context: BeforePackContext) {
await this.eventEmitter.emit("beforePack", context)
}
async emitAfterPack(context: AfterPackContext) {
await this.eventEmitter.emit("afterPack", context)
}
async emitAfterSign(context: AfterPackContext) {
await this.eventEmitter.emit("afterSign", context)
}
async emitAfterExtract(context: AfterPackContext) {
await this.eventEmitter.emit("afterExtract", context)
}
async validateConfig(): Promise<void> {
let configPath: string | null = null
let configFromOptions = this.options.config
if (typeof configFromOptions === "string") {
// it is a path to config file
configPath = configFromOptions
configFromOptions = null
} else if (configFromOptions != null && typeof configFromOptions.extends === "string" && configFromOptions.extends.includes(".")) {
configPath = configFromOptions.extends
delete configFromOptions.extends
}
const projectDir = this.projectDir
const devPackageFile = path.join(projectDir, "package.json")
this._devMetadata = await orNullIfFileNotExist(readPackageJson(devPackageFile))
const devMetadata = this.devMetadata
const configuration = await getConfig(projectDir, configPath, configFromOptions, new Lazy(() => Promise.resolve(devMetadata)))
if (log.isDebugEnabled) {
log.debug({ config: getSafeEffectiveConfig(configuration) }, "effective config")
}
this._appDir = await computeDefaultAppDirectory(projectDir, configuration.directories!.app)
this.isTwoPackageJsonProjectLayoutUsed = this._appDir !== projectDir
const appPackageFile = this.isTwoPackageJsonProjectLayoutUsed ? path.join(this.appDir, "package.json") : devPackageFile
// tslint:disable:prefer-conditional-expression
if (this.devMetadata != null && !this.isTwoPackageJsonProjectLayoutUsed) {
this._metadata = this.devMetadata
} else {
this._metadata = await this.readProjectMetadataIfTwoPackageStructureOrPrepacked(appPackageFile)
}
deepAssign(this.metadata, configuration.extraMetadata)
if (this.isTwoPackageJsonProjectLayoutUsed) {
log.debug({ devPackageFile, appPackageFile }, "two package.json structure is used")
}
checkMetadata(this.metadata, this.devMetadata, appPackageFile, devPackageFile)
await validateConfiguration(configuration, this.debugLogger)
this._configuration = configuration
this._devMetadata = devMetadata
}
// external caller of this method always uses isTwoPackageJsonProjectLayoutUsed=false and appDir=projectDir, no way (and need) to use another values
async build(repositoryInfo?: SourceRepositoryInfo): Promise<BuildResult> {
await this.validateConfig()
if (repositoryInfo != null) {
this._repositoryInfo.value = Promise.resolve(repositoryInfo)
}
this._appInfo = new AppInfo(this, null)
await this.addPackagerEventHandlers()
this._framework = await createFrameworkInfo(this.config, this)
const commonOutDirWithoutPossibleOsMacro = path.resolve(
this.projectDir,
expandMacro(this.config.directories!.output!, null, this._appInfo, {
os: "",
})
)
if (!isCI && (process.stdout as any).isTTY) {
const effectiveConfigFile = path.join(commonOutDirWithoutPossibleOsMacro, "builder-effective-config.yaml")
log.info({ file: log.filePath(effectiveConfigFile) }, "writing effective config")
await outputFile(effectiveConfigFile, getSafeEffectiveConfig(this.config))
}
// because artifact event maybe dispatched several times for different publish providers
const artifactPaths = new Set<string>()
this.onArtifactCreated(event => {
if (event.file != null) {
artifactPaths.add(event.file)
}
})
this.disposeOnBuildFinish(() => this.tempDirManager.cleanup())
const platformToTargets = await executeFinally(this.doBuild(), async () => {
if (this.debugLogger.isEnabled) {
await this.debugLogger.save(path.join(commonOutDirWithoutPossibleOsMacro, "builder-debug.yml"))
}
const toDispose = this.toDispose.slice()
this.toDispose.length = 0
for (const disposer of toDispose) {
await disposer().catch((e: any) => {
log.warn({ error: e }, "cannot dispose")
})
}
})
return {
outDir: commonOutDirWithoutPossibleOsMacro,
artifactPaths: Array.from(artifactPaths),
platformToTargets,
configuration: this.config,
}
}
private async readProjectMetadataIfTwoPackageStructureOrPrepacked(appPackageFile: string): Promise<Metadata> {
let data = await orNullIfFileNotExist(readPackageJson(appPackageFile))
if (data != null) {
return data
}
data = await orNullIfFileNotExist(readAsarJson(path.join(this.projectDir, "app.asar"), "package.json"))
if (data != null) {
this._isPrepackedAppAsar = true
return data
}
throw new Error(`Cannot find package.json in the ${path.dirname(appPackageFile)}`)
}
private async doBuild(): Promise<Map<Platform, Map<string, Target>>> {
const taskManager = new AsyncTaskManager(this.cancellationToken)
const syncTargetsIfAny = [] as Target[]
const platformToTarget = new Map<Platform, Map<string, Target>>()
const createdOutDirs = new Set<string>()
for (const [platform, archToType] of this.options.targets!) {
if (this.cancellationToken.cancelled) {
break
}
if (platform === Platform.MAC && process.platform === Platform.WINDOWS.nodeName) {
throw new InvalidConfigurationError("Build for macOS is supported only on macOS, please see https://electron.build/multi-platform-build")
}
const packager = await this.createHelper(platform)
const nameToTarget: Map<string, Target> = new Map()
platformToTarget.set(platform, nameToTarget)
let poolCount = Math.floor(packager.config.concurrency?.jobs || 1)
if (poolCount < 1) {
log.warn({ concurrency: poolCount }, "concurrency is invalid, overriding with job count: 1")
poolCount = 1
} else if (poolCount > MAX_FILE_REQUESTS) {
log.warn(
{ concurrency: poolCount, MAX_FILE_REQUESTS },
`job concurrency is greater than recommended MAX_FILE_REQUESTS, this may lead to File Descriptor errors (too many files open). Proceed with caution (e.g. this is an experimental feature)`
)
}
const packPromises: Promise<any>[] = []
for (const [arch, targetNames] of computeArchToTargetNamesMap(archToType, packager, platform)) {
if (this.cancellationToken.cancelled) {
break
}
// support os and arch macro in output value
const outDir = path.resolve(this.projectDir, packager.expandMacro(this.config.directories!.output!, Arch[arch]))
const targetList = createTargets(nameToTarget, targetNames.length === 0 ? packager.defaultTarget : targetNames, outDir, packager)
await createOutDirIfNeed(targetList, createdOutDirs)
const promise = packager.pack(outDir, arch, targetList, taskManager)
if (poolCount < 2) {
await promise
} else {
packPromises.push(promise)
}
}
await asyncPool(poolCount, packPromises, async it => {
if (this.cancellationToken.cancelled) {
return
}
await it
})
if (this.cancellationToken.cancelled) {
break
}
for (const target of nameToTarget.values()) {
if (target.isAsyncSupported) {
taskManager.addTask(target.finishBuild())
} else {
syncTargetsIfAny.push(target)
}
}
}
await taskManager.awaitTasks()
for (const target of syncTargetsIfAny) {
if (this.cancellationToken.cancelled) {
break
}
await target.finishBuild()
}
return platformToTarget
}
private async createHelper(platform: Platform): Promise<PlatformPackager<any>> {
if (this.options.platformPackagerFactory != null) {
return this.options.platformPackagerFactory(this, platform)
}
switch (platform) {
case Platform.MAC: {
const helperClass = (await import("./macPackager")).MacPackager
return new helperClass(this)
}
case Platform.WINDOWS: {
const helperClass = (await import("./winPackager")).WinPackager
return new helperClass(this)
}
case Platform.LINUX:
return new (await import("./linuxPackager")).LinuxPackager(this)
default:
throw new Error(`Unknown platform: ${platform}`)
}
}
public async installAppDependencies(platform: Platform, arch: Arch): Promise<any> {
if (this.options.prepackaged != null || !this.framework.isNpmRebuildRequired) {
return
}
const frameworkInfo = { version: this.framework.version, useCustomDist: true }
const config = this.config
if (config.nodeGypRebuild === true) {
await nodeGypRebuild(platform.nodeName, Arch[arch], frameworkInfo)
}
if (config.npmRebuild === false) {
log.info({ reason: "npmRebuild is set to false" }, "skipped dependencies rebuild")
return
}
const beforeBuild = await resolveFunction(this.appInfo.type, config.beforeBuild, "beforeBuild")
if (beforeBuild != null) {
const performDependenciesInstallOrRebuild = await beforeBuild({
appDir: this.appDir,
electronVersion: this.config.electronVersion!,
platform,
arch: Arch[arch],
})
// If beforeBuild resolves to false, it means that handling node_modules is done outside of electron-builder.
this._nodeModulesHandledExternally = !performDependenciesInstallOrRebuild
if (!performDependenciesInstallOrRebuild) {
return
}
}
if (config.buildDependenciesFromSource === true && platform.nodeName !== process.platform) {
log.info({ reason: "platform is different and buildDependenciesFromSource is set to true" }, "skipped dependencies rebuild")
} else {
await installOrRebuild(config, this.appDir, {
frameworkInfo,
platform: platform.nodeName,
arch: Arch[arch],
productionDeps: this.getNodeDependencyInfo(null, false) as Lazy<Array<NodeModuleDirInfo>>,
})
}
}
}
function createOutDirIfNeed(targetList: Array<Target>, createdOutDirs: Set<string>): Promise<any> {
const ourDirs = new Set<string>()
for (const target of targetList) {
// noinspection SuspiciousInstanceOfGuard
if (target instanceof NoOpTarget) {
continue
}
const outDir = target.outDir
if (!createdOutDirs.has(outDir)) {
ourDirs.add(outDir)
}
}
if (ourDirs.size === 0) {
return Promise.resolve()
}
return Promise.all(
Array.from(ourDirs)
.sort()
.map(dir => {
return mkdirs(dir)
.then(() => chmod(dir, 0o755) /* set explicitly */)
.then(() => createdOutDirs.add(dir))
})
)
}
export interface BuildResult {
readonly outDir: string
readonly artifactPaths: Array<string>
readonly platformToTargets: Map<Platform, Map<string, Target>>
readonly configuration: Configuration
}
function getSafeEffectiveConfig(configuration: Configuration): string {
const o = JSON.parse(safeStringifyJson(configuration))
if (o.cscLink != null) {
o.cscLink = "<hidden by builder>"
}
return serializeToYaml(o, true)
}