This commit is contained in:
2022-09-30 05:39:11 +00:00
parent 41ee9463ae
commit 4687fa49bc
11418 changed files with 1312504 additions and 0 deletions

View File

@ -0,0 +1,14 @@
import { Arch } from "builder-util";
import { AppImageOptions } from "..";
import { Target } from "../core";
import { LinuxPackager } from "../linuxPackager";
import { LinuxTargetHelper } from "./LinuxTargetHelper";
export default class AppImageTarget extends Target {
private readonly packager;
private readonly helper;
readonly outDir: string;
readonly options: AppImageOptions;
private readonly desktopEntry;
constructor(ignored: string, packager: LinuxPackager, helper: LinuxTargetHelper, outDir: string);
build(appOutDir: string, arch: Arch): Promise<any>;
}

View File

@ -0,0 +1,169 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _lazyVal() {
const data = require("lazy-val");
_lazyVal = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _PublishManager() {
const data = require("../publish/PublishManager");
_PublishManager = function () {
return data;
};
return data;
}
function _appBuilder() {
const data = require("../util/appBuilder");
_appBuilder = function () {
return data;
};
return data;
}
function _license() {
const data = require("../util/license");
_license = function () {
return data;
};
return data;
}
function _targetUtil() {
const data = require("./targetUtil");
_targetUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
// https://unix.stackexchange.com/questions/375191/append-to-sub-directory-inside-squashfs-file
class AppImageTarget extends _core().Target {
constructor(ignored, packager, helper, outDir) {
super("appImage");
this.packager = packager;
this.helper = helper;
this.outDir = outDir;
this.options = { ...this.packager.platformSpecificBuildOptions,
...this.packager.config[this.name]
};
this.desktopEntry = new (_lazyVal().Lazy)(() => helper.computeDesktopEntry(this.options, "AppRun %U", {
"X-AppImage-Version": `${packager.appInfo.buildVersion}`
}));
}
async build(appOutDir, arch) {
const packager = this.packager;
const options = this.options; // https://github.com/electron-userland/electron-builder/issues/775
// https://github.com/electron-userland/electron-builder/issues/1726
// tslint:disable-next-line:no-invalid-template-strings
const artifactName = packager.expandArtifactNamePattern(options, "AppImage", arch);
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: "AppImage",
file: artifactPath,
arch
});
const c = await Promise.all([this.desktopEntry.value, this.helper.icons, (0, _PublishManager().getAppUpdatePublishConfiguration)(packager, arch, false
/* in any case validation will be done on publish */
), (0, _license().getNotLocalizedLicenseFile)(options.license, this.packager, ["txt", "html"]), (0, _targetUtil().createStageDir)(this, packager, arch)]);
const license = c[3];
const stageDir = c[4];
const publishConfig = c[2];
if (publishConfig != null) {
await (0, _fsExtra().outputFile)(path.join(packager.getResourcesDir(stageDir.dir), "app-update.yml"), (0, _builderUtil().serializeToYaml)(publishConfig));
}
if (this.packager.packagerOptions.effectiveOptionComputed != null && (await this.packager.packagerOptions.effectiveOptionComputed({
desktop: await this.desktopEntry.value
}))) {
return;
}
const args = ["appimage", "--stage", stageDir.dir, "--arch", _builderUtil().Arch[arch], "--output", artifactPath, "--app", appOutDir, "--configuration", JSON.stringify({
productName: this.packager.appInfo.productName,
productFilename: this.packager.appInfo.productFilename,
desktopEntry: c[0],
executableName: this.packager.executableName,
icons: c[1],
fileAssociations: this.packager.fileAssociations,
...options
})];
(0, _appBuilder().objectToArgs)(args, {
license
});
if (packager.compression === "maximum") {
args.push("--compression", "xz");
}
await packager.info.callArtifactBuildCompleted({
file: artifactPath,
safeArtifactName: packager.computeSafeArtifactName(artifactName, "AppImage", arch, false),
target: this,
arch,
packager,
isWriteUpdateInfo: true,
updateInfo: await (0, _appBuilder().executeAppBuilderAsJson)(args)
});
}
} exports.default = AppImageTarget;
// __ts-babel@6.0.4
//# sourceMappingURL=AppImageTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
import { Arch } from "builder-util";
import { AppXOptions } from "../";
import { Target } from "../core";
import { WinPackager } from "../winPackager";
export default class AppXTarget extends Target {
private readonly packager;
readonly outDir: string;
readonly options: AppXOptions;
constructor(packager: WinPackager, outDir: string);
build(appOutDir: string, arch: Arch): Promise<any>;
private static computeUserAssets;
private computePublisherName;
private writeManifest;
private getExtensions;
}

View File

@ -0,0 +1,468 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _windowsCodeSign() {
const data = require("../codeSign/windowsCodeSign");
_windowsCodeSign = function () {
return data;
};
return data;
}
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _pathManager() {
const data = require("../util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
function _targetUtil() {
const data = require("./targetUtil");
_targetUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const APPX_ASSETS_DIR_NAME = "appx";
const vendorAssetsForDefaultAssets = {
"StoreLogo.png": "SampleAppx.50x50.png",
"Square150x150Logo.png": "SampleAppx.150x150.png",
"Square44x44Logo.png": "SampleAppx.44x44.png",
"Wide310x150Logo.png": "SampleAppx.310x150.png"
};
const DEFAULT_RESOURCE_LANG = "en-US";
class AppXTarget extends _core().Target {
constructor(packager, outDir) {
super("appx");
this.packager = packager;
this.outDir = outDir;
this.options = (0, _builderUtil().deepAssign)({}, this.packager.platformSpecificBuildOptions, this.packager.config.appx);
if (process.platform !== "darwin" && (process.platform !== "win32" || (0, _windowsCodeSign().isOldWin6)())) {
throw new Error("AppX is supported only on Windows 10 or Windows Server 2012 R2 (version number 6.3+)");
}
} // https://docs.microsoft.com/en-us/windows/uwp/packaging/create-app-package-with-makeappx-tool#mapping-files
async build(appOutDir, arch) {
const packager = this.packager;
const artifactName = packager.expandArtifactBeautyNamePattern(this.options, "appx", arch);
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: "AppX",
file: artifactPath,
arch
});
const vendorPath = await (0, _windowsCodeSign().getSignVendorPath)();
const vm = await packager.vm.value;
const stageDir = await (0, _targetUtil().createStageDir)(this, packager, arch);
const mappingFile = stageDir.getTempFile("mapping.txt");
const makeAppXArgs = ["pack", "/o"
/* overwrite the output file if it exists */
, "/f", vm.toVmFile(mappingFile), "/p", vm.toVmFile(artifactPath)];
if (packager.compression === "store") {
makeAppXArgs.push("/nc");
}
const mappingList = [];
mappingList.push(await _bluebirdLst().default.map((0, _fs().walk)(appOutDir), file => {
let appxPath = file.substring(appOutDir.length + 1);
if (path.sep !== "\\") {
appxPath = appxPath.replace(/\//g, "\\");
}
return `"${vm.toVmFile(file)}" "app\\${appxPath}"`;
}));
const userAssetDir = await this.packager.getResource(undefined, APPX_ASSETS_DIR_NAME);
const assetInfo = await AppXTarget.computeUserAssets(vm, vendorPath, userAssetDir);
const userAssets = assetInfo.userAssets;
const manifestFile = stageDir.getTempFile("AppxManifest.xml");
await this.writeManifest(manifestFile, arch, await this.computePublisherName(), userAssets);
await packager.info.callAppxManifestCreated(manifestFile);
mappingList.push(assetInfo.mappings);
mappingList.push([`"${vm.toVmFile(manifestFile)}" "AppxManifest.xml"`]);
const signToolArch = arch === _builderUtil().Arch.arm64 ? "x64" : _builderUtil().Arch[arch];
if (isScaledAssetsProvided(userAssets)) {
const outFile = vm.toVmFile(stageDir.getTempFile("resources.pri"));
const makePriPath = vm.toVmFile(path.join(vendorPath, "windows-10", signToolArch, "makepri.exe"));
const assetRoot = stageDir.getTempFile("appx/assets");
await (0, _fsExtra().emptyDir)(assetRoot);
await _bluebirdLst().default.map(assetInfo.allAssets, it => (0, _fs().copyOrLinkFile)(it, path.join(assetRoot, path.basename(it))));
await vm.exec(makePriPath, ["new", "/Overwrite", "/Manifest", vm.toVmFile(manifestFile), "/ProjectRoot", vm.toVmFile(path.dirname(assetRoot)), "/ConfigXml", vm.toVmFile(path.join((0, _pathManager().getTemplatePath)("appx"), "priconfig.xml")), "/OutputFile", outFile]); // in addition to resources.pri, resources.scale-140.pri and other such files will be generated
for (const resourceFile of (await (0, _fsExtra().readdir)(stageDir.dir)).filter(it => it.startsWith("resources.")).sort()) {
mappingList.push([`"${vm.toVmFile(stageDir.getTempFile(resourceFile))}" "${resourceFile}"`]);
}
makeAppXArgs.push("/l");
}
let mapping = "[Files]";
for (const list of mappingList) {
mapping += "\r\n" + list.join("\r\n");
}
await (0, _fsExtra().writeFile)(mappingFile, mapping);
packager.debugLogger.add("appx.mapping", mapping);
if (this.options.makeappxArgs != null) {
makeAppXArgs.push(...this.options.makeappxArgs);
}
await vm.exec(vm.toVmFile(path.join(vendorPath, "windows-10", signToolArch, "makeappx.exe")), makeAppXArgs);
await packager.sign(artifactPath);
await stageDir.cleanup();
await packager.info.callArtifactBuildCompleted({
file: artifactPath,
packager,
arch,
safeArtifactName: packager.computeSafeArtifactName(artifactName, "appx"),
target: this,
isWriteUpdateInfo: this.options.electronUpdaterAware
});
}
static async computeUserAssets(vm, vendorPath, userAssetDir) {
const mappings = [];
let userAssets;
const allAssets = [];
if (userAssetDir == null) {
userAssets = [];
} else {
userAssets = (await (0, _fsExtra().readdir)(userAssetDir)).filter(it => !it.startsWith(".") && !it.endsWith(".db") && it.includes("."));
for (const name of userAssets) {
mappings.push(`"${vm.toVmFile(userAssetDir)}${vm.pathSep}${name}" "assets\\${name}"`);
allAssets.push(path.join(userAssetDir, name));
}
}
for (const defaultAsset of Object.keys(vendorAssetsForDefaultAssets)) {
if (userAssets.length === 0 || !isDefaultAssetIncluded(userAssets, defaultAsset)) {
const file = path.join(vendorPath, "appxAssets", vendorAssetsForDefaultAssets[defaultAsset]);
mappings.push(`"${vm.toVmFile(file)}" "assets\\${defaultAsset}"`);
allAssets.push(file);
}
} // we do not use process.arch to build path to tools, because even if you are on x64, ia32 appx tool must be used if you build appx for ia32
return {
userAssets,
mappings,
allAssets
};
} // https://github.com/electron-userland/electron-builder/issues/2108#issuecomment-333200711
async computePublisherName() {
if ((await this.packager.cscInfo.value) == null) {
_builderUtil().log.info({
reason: "Windows Store only build"
}, "AppX is not signed");
return this.options.publisher || "CN=ms";
}
const certInfo = await this.packager.lazyCertInfo.value;
const publisher = certInfo == null ? null : certInfo.bloodyMicrosoftSubjectDn;
if (publisher == null) {
throw new Error("Internal error: cannot compute subject using certificate info");
}
return publisher;
}
async writeManifest(outFile, arch, publisher, userAssets) {
const appInfo = this.packager.appInfo;
const options = this.options;
const executable = `app\\${appInfo.productFilename}.exe`;
const displayName = options.displayName || appInfo.productName;
const extensions = await this.getExtensions(executable, displayName);
const manifest = (await (0, _fsExtra().readFile)(path.join((0, _pathManager().getTemplatePath)("appx"), "appxmanifest.xml"), "utf8")).replace(/\${([a-zA-Z0-9]+)}/g, (match, p1) => {
switch (p1) {
case "publisher":
return publisher;
case "publisherDisplayName":
{
const name = options.publisherDisplayName || appInfo.companyName;
if (name == null) {
throw new (_builderUtil().InvalidConfigurationError)(`Please specify "author" in the application package.json — it is required because "appx.publisherDisplayName" is not set.`);
}
return name;
}
case "version":
return appInfo.getVersionInWeirdWindowsForm(options.setBuildNumber === true);
case "applicationId":
{
const result = options.applicationId || options.identityName || appInfo.name;
if (!isNaN(parseInt(result[0], 10))) {
let message = `AppX Application.Id cant start with numbers: "${result}"`;
if (options.applicationId == null) {
message += `\nPlease set appx.applicationId (or correct appx.identityName or name)`;
}
throw new (_builderUtil().InvalidConfigurationError)(message);
}
return result;
}
case "identityName":
return options.identityName || appInfo.name;
case "executable":
return executable;
case "displayName":
return displayName;
case "description":
return appInfo.description || appInfo.productName;
case "backgroundColor":
return options.backgroundColor || "#464646";
case "logo":
return "assets\\StoreLogo.png";
case "square150x150Logo":
return "assets\\Square150x150Logo.png";
case "square44x44Logo":
return "assets\\Square44x44Logo.png";
case "lockScreen":
return lockScreenTag(userAssets);
case "defaultTile":
return defaultTileTag(userAssets, options.showNameOnTiles || false);
case "splashScreen":
return splashScreenTag(userAssets);
case "arch":
return arch === _builderUtil().Arch.ia32 ? "x86" : arch === _builderUtil().Arch.arm64 ? "arm64" : "x64";
case "resourceLanguages":
return resourceLanguageTag((0, _builderUtil().asArray)(options.languages));
case "extensions":
return extensions;
case "minVersion":
return arch === _builderUtil().Arch.arm64 ? "10.0.16299.0" : "10.0.14316.0";
case "maxVersionTested":
return arch === _builderUtil().Arch.arm64 ? "10.0.16299.0" : "10.0.14316.0";
default:
throw new Error(`Macro ${p1} is not defined`);
}
});
await (0, _fsExtra().writeFile)(outFile, manifest);
}
async getExtensions(executable, displayName) {
const uriSchemes = (0, _builderUtil().asArray)(this.packager.config.protocols).concat((0, _builderUtil().asArray)(this.packager.platformSpecificBuildOptions.protocols));
const fileAssociations = (0, _builderUtil().asArray)(this.packager.config.fileAssociations).concat((0, _builderUtil().asArray)(this.packager.platformSpecificBuildOptions.fileAssociations));
let isAddAutoLaunchExtension = this.options.addAutoLaunchExtension;
if (isAddAutoLaunchExtension === undefined) {
const deps = this.packager.info.metadata.dependencies;
isAddAutoLaunchExtension = deps != null && deps["electron-winstore-auto-launch"] != null;
}
if (!isAddAutoLaunchExtension && uriSchemes.length === 0 && fileAssociations.length === 0 && this.options.customExtensionsPath === undefined) {
return "";
}
let extensions = "<Extensions>";
if (isAddAutoLaunchExtension) {
extensions += `
<desktop:Extension Category="windows.startupTask" Executable="${executable}" EntryPoint="Windows.FullTrustApplication">
<desktop:StartupTask TaskId="SlackStartup" Enabled="true" DisplayName="${displayName}" />
</desktop:Extension>`;
}
for (const protocol of uriSchemes) {
for (const scheme of (0, _builderUtil().asArray)(protocol.schemes)) {
extensions += `
<uap:Extension Category="windows.protocol">
<uap:Protocol Name="${scheme}">
<uap:DisplayName>${protocol.name}</uap:DisplayName>
</uap:Protocol>
</uap:Extension>`;
}
}
for (const fileAssociation of fileAssociations) {
for (const ext of (0, _builderUtil().asArray)(fileAssociation.ext)) {
extensions += `
<uap:Extension Category="windows.fileTypeAssociation">
<uap:FileTypeAssociation Name="${ext}">
<uap:SupportedFileTypes>
<uap:FileType>.${ext}</uap:FileType>
</uap:SupportedFileTypes>
</uap:FileTypeAssociation>
</uap:Extension>`;
}
}
if (this.options.customExtensionsPath !== undefined) {
const extensionsPath = path.resolve(this.packager.info.appDir, this.options.customExtensionsPath);
extensions += await (0, _fsExtra().readFile)(extensionsPath, "utf8");
}
extensions += "</Extensions>";
return extensions;
}
} // get the resource - language tag, see https://docs.microsoft.com/en-us/windows/uwp/globalizing/manage-language-and-region#specify-the-supported-languages-in-the-apps-manifest
exports.default = AppXTarget;
function resourceLanguageTag(userLanguages) {
if (userLanguages == null || userLanguages.length === 0) {
userLanguages = [DEFAULT_RESOURCE_LANG];
}
return userLanguages.map(it => `<Resource Language="${it.replace(/_/g, "-")}" />`).join("\n");
}
function lockScreenTag(userAssets) {
if (isDefaultAssetIncluded(userAssets, "BadgeLogo.png")) {
return '<uap:LockScreen Notification="badgeAndTileText" BadgeLogo="assets\\BadgeLogo.png" />';
} else {
return "";
}
}
function defaultTileTag(userAssets, showNameOnTiles) {
const defaultTiles = ["<uap:DefaultTile", 'Wide310x150Logo="assets\\Wide310x150Logo.png"'];
if (isDefaultAssetIncluded(userAssets, "LargeTile.png")) {
defaultTiles.push('Square310x310Logo="assets\\LargeTile.png"');
}
if (isDefaultAssetIncluded(userAssets, "SmallTile.png")) {
defaultTiles.push('Square71x71Logo="assets\\SmallTile.png"');
}
if (showNameOnTiles) {
defaultTiles.push(">");
defaultTiles.push("<uap:ShowNameOnTiles>");
defaultTiles.push("<uap:ShowOn", 'Tile="wide310x150Logo"', "/>");
defaultTiles.push("<uap:ShowOn", 'Tile="square150x150Logo"', "/>");
defaultTiles.push("</uap:ShowNameOnTiles>");
defaultTiles.push("</uap:DefaultTile>");
} else {
defaultTiles.push("/>");
}
return defaultTiles.join(" ");
}
function splashScreenTag(userAssets) {
if (isDefaultAssetIncluded(userAssets, "SplashScreen.png")) {
return '<uap:SplashScreen Image="assets\\SplashScreen.png" />';
} else {
return "";
}
}
function isDefaultAssetIncluded(userAssets, defaultAsset) {
const defaultAssetName = defaultAsset.substring(0, defaultAsset.indexOf("."));
return userAssets.some(it => it.includes(defaultAssetName));
}
function isScaledAssetsProvided(userAssets) {
return userAssets.some(it => it.includes(".scale-") || it.includes(".targetsize-"));
}
// __ts-babel@6.0.4
//# sourceMappingURL=AppxTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
import { Arch } from "builder-util";
import { Target, TargetSpecificOptions } from "../core";
import { PlatformPackager } from "../platformPackager";
export declare class ArchiveTarget extends Target {
readonly outDir: string;
private readonly packager;
private readonly isWriteUpdateInfo;
readonly options: TargetSpecificOptions;
constructor(name: string, outDir: string, packager: PlatformPackager<any>, isWriteUpdateInfo?: boolean);
build(appOutDir: string, arch: Arch): Promise<any>;
}

View File

@ -0,0 +1,141 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ArchiveTarget = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _fileMatcher() {
const data = require("../fileMatcher");
_fileMatcher = function () {
return data;
};
return data;
}
function _archive() {
const data = require("./archive");
_archive = function () {
return data;
};
return data;
}
function _differentialUpdateInfoBuilder() {
const data = require("./differentialUpdateInfoBuilder");
_differentialUpdateInfoBuilder = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
class ArchiveTarget extends _core().Target {
constructor(name, outDir, packager, isWriteUpdateInfo = false) {
super(name);
this.outDir = outDir;
this.packager = packager;
this.isWriteUpdateInfo = isWriteUpdateInfo;
this.options = this.packager.config[this.name];
}
async build(appOutDir, arch) {
const packager = this.packager;
const isMac = packager.platform === _core().Platform.MAC;
const format = this.name;
let defaultPattern;
if (packager.platform === _core().Platform.LINUX) {
// tslint:disable-next-line:no-invalid-template-strings
defaultPattern = "${name}-${version}" + (arch === _builderUtil().Arch.x64 ? "" : "-${arch}") + ".${ext}";
} else {
// tslint:disable-next-line:no-invalid-template-strings
defaultPattern = "${productName}-${version}" + (arch === _builderUtil().Arch.x64 ? "" : "-${arch}") + "-${os}.${ext}";
}
const artifactName = packager.expandArtifactNamePattern(this.options, format, arch, defaultPattern, false);
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: `${isMac ? "macOS " : ""}${format}`,
file: artifactPath,
arch
});
let updateInfo = null;
if (format.startsWith("tar.")) {
await (0, _archive().tar)(packager.compression, format, artifactPath, appOutDir, isMac, packager.info.tempDirManager);
} else {
let withoutDir = !isMac;
let dirToArchive = appOutDir;
if (isMac) {
dirToArchive = path.dirname(appOutDir);
const fileMatchers = (0, _fileMatcher().getFileMatchers)(packager.config, "extraDistFiles", dirToArchive, packager.createGetFileMatchersOptions(this.outDir, arch, packager.platformSpecificBuildOptions));
if (fileMatchers == null) {
dirToArchive = appOutDir;
} else {
await (0, _fileMatcher().copyFiles)(fileMatchers, null, true);
withoutDir = true;
}
}
const archiveOptions = {
compression: packager.compression,
withoutDir
};
await (0, _archive().archive)(format, artifactPath, dirToArchive, archiveOptions);
if (this.isWriteUpdateInfo && format === "zip") {
updateInfo = await (0, _differentialUpdateInfoBuilder().appendBlockmap)(artifactPath);
}
}
await packager.info.callArtifactBuildCompleted({
updateInfo,
file: artifactPath,
// tslint:disable-next-line:no-invalid-template-strings
safeArtifactName: packager.computeSafeArtifactName(artifactName, format, arch, false, defaultPattern.replace("${productName}", "${name}")),
target: this,
arch,
packager,
isWriteUpdateInfo: this.isWriteUpdateInfo
});
}
} exports.ArchiveTarget = ArchiveTarget;
// __ts-babel@6.0.4
//# sourceMappingURL=ArchiveTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,22 @@
import { LinuxTargetSpecificOptions } from "..";
import { LinuxPackager } from "../linuxPackager";
import { IconInfo } from "../platformPackager";
export declare const installPrefix = "/opt";
export declare class LinuxTargetHelper {
private packager;
private readonly iconPromise;
private readonly mimeTypeFilesPromise;
maxIconPath: string | null;
constructor(packager: LinuxPackager);
get icons(): Promise<Array<IconInfo>>;
get mimeTypeFiles(): Promise<string | null>;
private computeMimeTypeFiles;
private computeDesktopIcons;
getDescription(options: LinuxTargetSpecificOptions): string;
writeDesktopEntry(targetSpecificOptions: LinuxTargetSpecificOptions, exec?: string, destination?: string | null, extra?: {
[key: string]: string;
}): Promise<string>;
computeDesktopEntry(targetSpecificOptions: LinuxTargetSpecificOptions, exec?: string, extra?: {
[key: string]: string;
}): Promise<string>;
}

View File

@ -0,0 +1,231 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LinuxTargetHelper = exports.installPrefix = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _lazyVal() {
const data = require("lazy-val");
_lazyVal = function () {
return data;
};
return data;
}
const installPrefix = "/opt";
exports.installPrefix = installPrefix;
class LinuxTargetHelper {
constructor(packager) {
this.packager = packager;
this.iconPromise = new (_lazyVal().Lazy)(() => this.computeDesktopIcons());
this.mimeTypeFilesPromise = new (_lazyVal().Lazy)(() => this.computeMimeTypeFiles());
this.maxIconPath = null;
}
get icons() {
return this.iconPromise.value;
}
get mimeTypeFiles() {
return this.mimeTypeFilesPromise.value;
}
async computeMimeTypeFiles() {
const items = [];
for (const fileAssociation of this.packager.fileAssociations) {
if (!fileAssociation.mimeType) {
continue;
}
const data = `<mime-type type="${fileAssociation.mimeType}">
<glob pattern="*.${fileAssociation.ext}"/>
${fileAssociation.description ? `<comment>${fileAssociation.description}</comment>` : ""}
<icon name="x-office-document" />
</mime-type>`;
items.push(data);
}
if (items.length === 0) {
return null;
}
const file = await this.packager.getTempFile(".xml");
await (0, _fsExtra().outputFile)(file, '<?xml version="1.0" encoding="utf-8"?>\n<mime-info xmlns="http://www.freedesktop.org/standards/shared-mime-info">\n' + items.join("\n") + "\n</mime-info>");
return file;
} // must be name without spaces and other special characters, but not product name used
async computeDesktopIcons() {
const packager = this.packager;
const iconDir = packager.platformSpecificBuildOptions.icon;
const sources = iconDir == null ? [] : [iconDir];
const commonConfiguration = packager.config;
const icnsPath = (commonConfiguration.mac || {}).icon || commonConfiguration.icon;
if (icnsPath != null) {
sources.push(icnsPath);
} // need to put here and not as default because need to resolve image size
const result = await packager.resolveIcon(sources, (0, _builderUtil().asArray)(packager.getDefaultFrameworkIcon()), "set");
this.maxIconPath = result[result.length - 1].file;
return result;
}
getDescription(options) {
return options.description || this.packager.appInfo.description;
}
async writeDesktopEntry(targetSpecificOptions, exec, destination, extra) {
const data = await this.computeDesktopEntry(targetSpecificOptions, exec, extra);
const file = destination || (await this.packager.getTempFile(`${this.packager.appInfo.productFilename}.desktop`));
await (0, _fsExtra().outputFile)(file, data);
return file;
}
async computeDesktopEntry(targetSpecificOptions, exec, extra) {
if (exec != null && exec.length === 0) {
throw new Error("Specified exec is empty");
} // https://github.com/electron-userland/electron-builder/issues/3418
if (targetSpecificOptions.desktop != null && targetSpecificOptions.desktop.Exec != null) {
throw new Error("Please specify executable name as linux.executableName instead of linux.desktop.Exec");
}
const packager = this.packager;
const appInfo = packager.appInfo;
const productFilename = appInfo.productFilename;
const executableArgs = targetSpecificOptions.executableArgs;
if (exec == null) {
exec = `${installPrefix}/${productFilename}/${packager.executableName}`;
if (!/^[/0-9A-Za-z._-]+$/.test(exec)) {
exec = `"${exec}"`;
}
if (executableArgs) {
exec += " ";
exec += executableArgs.join(" ");
}
exec += " %U";
}
const desktopMeta = {
Name: appInfo.productName,
Exec: exec,
Terminal: "false",
Type: "Application",
Icon: packager.executableName,
// https://askubuntu.com/questions/367396/what-represent-the-startupwmclass-field-of-a-desktop-file
// must be set to package.json name (because it is Electron set WM_CLASS)
// to get WM_CLASS of running window: xprop WM_CLASS
// StartupWMClass doesn't work for unicode
// https://github.com/electron/electron/blob/2-0-x/atom/browser/native_window_views.cc#L226
StartupWMClass: appInfo.productName,
...extra,
...targetSpecificOptions.desktop
};
const description = this.getDescription(targetSpecificOptions);
if (!(0, _builderUtil().isEmptyOrSpaces)(description)) {
desktopMeta.Comment = description;
}
const mimeTypes = (0, _builderUtil().asArray)(targetSpecificOptions.mimeTypes);
for (const fileAssociation of packager.fileAssociations) {
if (fileAssociation.mimeType != null) {
mimeTypes.push(fileAssociation.mimeType);
}
}
for (const protocol of (0, _builderUtil().asArray)(packager.config.protocols).concat((0, _builderUtil().asArray)(packager.platformSpecificBuildOptions.protocols))) {
for (const scheme of (0, _builderUtil().asArray)(protocol.schemes)) {
mimeTypes.push(`x-scheme-handler/${scheme}`);
}
}
if (mimeTypes.length !== 0) {
desktopMeta.MimeType = mimeTypes.join(";") + ";";
}
let category = targetSpecificOptions.category;
if ((0, _builderUtil().isEmptyOrSpaces)(category)) {
const macCategory = (packager.config.mac || {}).category;
if (macCategory != null) {
category = macToLinuxCategory[macCategory];
}
if (category == null) {
// https://github.com/develar/onshape-desktop-shell/issues/48
if (macCategory != null) {
_builderUtil().log.warn({
macCategory
}, "cannot map macOS category to Linux. If possible mapping is known for you, please file issue to add it.");
}
_builderUtil().log.warn({
reason: "linux.category is not set and cannot map from macOS",
docs: "https://www.electron.build/configuration/linux"
}, "application Linux category is set to default \"Utility\"");
category = "Utility";
}
}
desktopMeta.Categories = `${category}${category.endsWith(";") ? "" : ";"}`;
let data = `[Desktop Entry]`;
for (const name of Object.keys(desktopMeta)) {
data += `\n${name}=${desktopMeta[name]}`;
}
data += "\n";
return data;
}
}
exports.LinuxTargetHelper = LinuxTargetHelper;
const macToLinuxCategory = {
"public.app-category.graphics-design": "Graphics",
"public.app-category.developer-tools": "Development",
"public.app-category.education": "Education",
"public.app-category.games": "Game",
"public.app-category.video": "Video;AudioVideo",
"public.app-category.utilities": "Utility",
"public.app-category.social-networking": "Network;Chat",
"public.app-category.finance": "Office;Finance"
};
// __ts-babel@6.0.4
//# sourceMappingURL=LinuxTargetHelper.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,16 @@
import { Arch } from "builder-util";
import { MsiOptions } from "../";
import { Target } from "../core";
import { WinPackager } from "../winPackager";
export default class MsiTarget extends Target {
private readonly packager;
readonly outDir: string;
private readonly vm;
readonly options: MsiOptions;
constructor(packager: WinPackager, outDir: string);
build(appOutDir: string, arch: Arch): Promise<void>;
private light;
private getCommonWixArgs;
private writeManifest;
private computeFileDeclaration;
}

View File

@ -0,0 +1,397 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _builderUtilRuntime() {
const data = require("builder-util-runtime");
_builderUtilRuntime = function () {
return data;
};
return data;
}
function _binDownload() {
const data = require("../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _crypto() {
const data = require("crypto");
_crypto = function () {
return data;
};
return data;
}
function ejs() {
const data = _interopRequireWildcard(require("ejs"));
ejs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _lazyVal() {
const data = require("lazy-val");
_lazyVal = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _CommonWindowsInstallerConfiguration() {
const data = require("../options/CommonWindowsInstallerConfiguration");
_CommonWindowsInstallerConfiguration = function () {
return data;
};
return data;
}
function _pathManager() {
const data = require("../util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
function _vm() {
const data = require("../vm/vm");
_vm = function () {
return data;
};
return data;
}
function _WineVm() {
const data = require("../vm/WineVm");
_WineVm = function () {
return data;
};
return data;
}
function _targetUtil() {
const data = require("./targetUtil");
_targetUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const ELECTRON_BUILDER_UPGRADE_CODE_NS_UUID = _builderUtilRuntime().UUID.parse("d752fe43-5d44-44d5-9fc9-6dd1bf19d5cc");
const ROOT_DIR_ID = "APPLICATIONFOLDER";
const ASSISTED_UI_FILE_NAME = "WixUI_Assisted.wxs";
const projectTemplate = new (_lazyVal().Lazy)(async () => {
const template = (await (0, _fsExtra().readFile)(path.join((0, _pathManager().getTemplatePath)("msi"), "template.xml"), "utf8")).replace(/{{/g, "<%").replace(/}}/g, "%>").replace(/\${([^}]+)}/g, "<%=$1%>");
return ejs().compile(template);
}); // WiX doesn't support Mono, so, dontnet462 is required to be installed for wine (preinstalled in our bundled wine)
class MsiTarget extends _core().Target {
constructor(packager, outDir) {
super("msi");
this.packager = packager;
this.outDir = outDir;
this.vm = process.platform === "win32" ? new (_vm().VmManager)() : new (_WineVm().WineVmManager)();
this.options = (0, _builderUtil().deepAssign)(this.packager.platformSpecificBuildOptions, this.packager.config.msi);
}
async build(appOutDir, arch) {
const packager = this.packager;
const artifactName = packager.expandArtifactBeautyNamePattern(this.options, "msi", arch);
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: "MSI",
file: artifactPath,
arch
});
const stageDir = await (0, _targetUtil().createStageDir)(this, packager, arch);
const vm = this.vm;
const commonOptions = (0, _CommonWindowsInstallerConfiguration().getEffectiveOptions)(this.options, this.packager);
if (commonOptions.isAssisted) {
// F*** *** *** *** *** *** *** *** *** *** *** *** *** WiX *** *** *** *** *** *** *** *** ***
// cannot understand how to set MSIINSTALLPERUSER on radio box change. In any case installed per user.
_builderUtil().log.warn(`MSI DOESN'T SUPPORT assisted installer. Please use NSIS instead.`);
}
const projectFile = stageDir.getTempFile("project.wxs");
const objectFiles = ["project.wixobj"];
const uiFile = commonOptions.isAssisted ? stageDir.getTempFile(ASSISTED_UI_FILE_NAME) : null;
await (0, _fsExtra().writeFile)(projectFile, await this.writeManifest(appOutDir, arch, commonOptions));
if (uiFile !== null) {
await (0, _fsExtra().writeFile)(uiFile, await (0, _fsExtra().readFile)(path.join((0, _pathManager().getTemplatePath)("msi"), ASSISTED_UI_FILE_NAME), "utf8"));
objectFiles.push(ASSISTED_UI_FILE_NAME.replace(".wxs", ".wixobj"));
} // noinspection SpellCheckingInspection
const vendorPath = await (0, _binDownload().getBinFromUrl)("wix", "4.0.0.5512.2", "/X5poahdCc3199Vt6AP7gluTlT1nxi9cbbHhZhCMEu+ngyP1LiBMn+oZX7QAZVaKeBMc2SjVp7fJqNLqsUnPNQ=="); // noinspection SpellCheckingInspection
const candleArgs = ["-arch", arch === _builderUtil().Arch.ia32 ? "x86" : arch === _builderUtil().Arch.arm64 ? "arm64" : "x64", `-dappDir=${vm.toVmFile(appOutDir)}`].concat(this.getCommonWixArgs());
candleArgs.push("project.wxs");
if (uiFile !== null) {
candleArgs.push(ASSISTED_UI_FILE_NAME);
}
await vm.exec(vm.toVmFile(path.join(vendorPath, "candle.exe")), candleArgs, {
cwd: stageDir.dir
});
await this.light(objectFiles, vm, artifactPath, appOutDir, vendorPath, stageDir.dir);
await stageDir.cleanup();
await packager.sign(artifactPath);
await packager.info.callArtifactBuildCompleted({
file: artifactPath,
packager,
arch,
safeArtifactName: packager.computeSafeArtifactName(artifactName, "msi"),
target: this,
isWriteUpdateInfo: false
});
}
async light(objectFiles, vm, artifactPath, appOutDir, vendorPath, tempDir) {
// noinspection SpellCheckingInspection
const lightArgs = ["-out", vm.toVmFile(artifactPath), "-v", // https://github.com/wixtoolset/issues/issues/5169
"-spdb", // https://sourceforge.net/p/wix/bugs/2405/
// error LGHT1076 : ICE61: This product should remove only older versions of itself. The Maximum version is not less than the current product. (1.1.0.42 1.1.0.42)
"-sw1076", `-dappDir=${vm.toVmFile(appOutDir)}`].concat(this.getCommonWixArgs()); // http://windows-installer-xml-wix-toolset.687559.n2.nabble.com/Build-3-5-2229-0-give-me-the-following-error-error-LGHT0216-An-unexpected-Win32-exception-with-errorn-td5707443.html
if (process.platform !== "win32") {
// noinspection SpellCheckingInspection
lightArgs.push("-sval");
}
if (this.options.oneClick === false) {
lightArgs.push("-ext", "WixUIExtension");
} // objectFiles - only filenames, we set current directory to our temp stage dir
lightArgs.push(...objectFiles);
await vm.exec(vm.toVmFile(path.join(vendorPath, "light.exe")), lightArgs, {
cwd: tempDir
});
}
getCommonWixArgs() {
const args = ["-pedantic"];
if (this.options.warningsAsErrors !== false) {
args.push("-wx");
}
return args;
}
async writeManifest(appOutDir, arch, commonOptions) {
const appInfo = this.packager.appInfo;
const {
files,
dirs
} = await this.computeFileDeclaration(appOutDir);
const companyName = appInfo.companyName;
if (!companyName) {
_builderUtil().log.warn(`Manufacturer is not set for MSI — please set "author" in the package.json`);
}
const compression = this.packager.compression;
const options = this.options;
const iconPath = await this.packager.getIconPath();
return (await projectTemplate.value)({ ...commonOptions,
isCreateDesktopShortcut: commonOptions.isCreateDesktopShortcut !== _CommonWindowsInstallerConfiguration().DesktopShortcutCreationPolicy.NEVER,
isRunAfterFinish: options.runAfterFinish !== false,
iconPath: iconPath == null ? null : this.vm.toVmFile(iconPath),
compressionLevel: compression === "store" ? "none" : "high",
version: appInfo.getVersionInWeirdWindowsForm(),
productName: appInfo.productName,
upgradeCode: (options.upgradeCode || _builderUtilRuntime().UUID.v5(appInfo.id, ELECTRON_BUILDER_UPGRADE_CODE_NS_UUID)).toUpperCase(),
manufacturer: companyName || appInfo.productName,
appDescription: appInfo.description,
// https://stackoverflow.com/questions/1929038/compilation-error-ice80-the-64bitcomponent-uses-32bitdirectory
programFilesId: arch === _builderUtil().Arch.x64 ? "ProgramFiles64Folder" : "ProgramFilesFolder",
// wix in the name because special wix format can be used in the name
installationDirectoryWixName: (0, _targetUtil().getWindowsInstallationDirName)(appInfo, commonOptions.isPerMachine === true),
dirs,
files
});
}
async computeFileDeclaration(appOutDir) {
const appInfo = this.packager.appInfo;
let isRootDirAddedToRemoveTable = false;
const dirNames = new Set();
const dirs = [];
const fileSpace = " ".repeat(6);
const commonOptions = (0, _CommonWindowsInstallerConfiguration().getEffectiveOptions)(this.options, this.packager);
const files = await _bluebirdLst().default.map((0, _fs().walk)(appOutDir), file => {
const packagePath = file.substring(appOutDir.length + 1);
const lastSlash = packagePath.lastIndexOf(path.sep);
const fileName = lastSlash > 0 ? packagePath.substring(lastSlash + 1) : packagePath;
let directoryId = null;
let dirName = ""; // Wix Directory.FileSource doesn't work - https://stackoverflow.com/questions/21519388/wix-filesource-confusion
if (lastSlash > 0) {
// This Name attribute may also define multiple directories using the inline directory syntax.
// For example, "ProgramFilesFolder:\My Company\My Product\bin" would create a reference to a Directory element with Id="ProgramFilesFolder" then create directories named "My Company" then "My Product" then "bin" nested beneath each other.
// This syntax is a shortcut to defining each directory in an individual Directory element.
dirName = packagePath.substring(0, lastSlash); // https://github.com/electron-userland/electron-builder/issues/3027
directoryId = "d" + (0, _crypto().createHash)("md5").update(dirName).digest("base64").replace(/\//g, "_").replace(/\+/g, ".").replace(/=+$/, "");
if (!dirNames.has(dirName)) {
dirNames.add(dirName);
dirs.push(`<Directory Id="${directoryId}" Name="${ROOT_DIR_ID}:\\${dirName.replace(/\//g, "\\")}\\"/>`);
}
} else if (!isRootDirAddedToRemoveTable) {
isRootDirAddedToRemoveTable = true;
} // since RegistryValue can be part of Component, *** *** *** *** *** *** *** *** *** wix cannot auto generate guid
// https://stackoverflow.com/questions/1405100/change-my-component-guid-in-wix
let result = `<Component${directoryId === null ? "" : ` Directory="${directoryId}"`}>`;
result += `\n${fileSpace} <File Name="${fileName}" Source="$(var.appDir)${path.sep}${packagePath}" ReadOnly="yes" KeyPath="yes"`;
const isMainExecutable = packagePath === `${appInfo.productFilename}.exe`;
if (isMainExecutable) {
result += ' Id="mainExecutable"';
} else if (directoryId === null) {
result += ` Id="${path.basename(packagePath)}_f"`;
}
const isCreateDesktopShortcut = commonOptions.isCreateDesktopShortcut !== _CommonWindowsInstallerConfiguration().DesktopShortcutCreationPolicy.NEVER;
if (isMainExecutable && (isCreateDesktopShortcut || commonOptions.isCreateStartMenuShortcut)) {
result += `>\n`;
const shortcutName = commonOptions.shortcutName;
if (isCreateDesktopShortcut) {
result += `${fileSpace} <Shortcut Id="desktopShortcut" Directory="DesktopFolder" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico"/>\n`;
}
const hasMenuCategory = commonOptions.menuCategory != null;
const startMenuShortcutDirectoryId = hasMenuCategory ? "AppProgramMenuDir" : "ProgramMenuFolder";
if (commonOptions.isCreateStartMenuShortcut) {
if (hasMenuCategory) {
dirs.push(`<Directory Id="${startMenuShortcutDirectoryId}" Name="ProgramMenuFolder:\\${commonOptions.menuCategory}\\"/>`);
}
result += `${fileSpace} <Shortcut Id="startMenuShortcut" Directory="${startMenuShortcutDirectoryId}" Name="${shortcutName}" WorkingDirectory="APPLICATIONFOLDER" Advertise="yes" Icon="icon.ico">\n`;
result += `${fileSpace} <ShortcutProperty Key="System.AppUserModel.ID" Value="${this.packager.appInfo.id}"/>\n`;
result += `${fileSpace} </Shortcut>\n`;
}
result += `${fileSpace}</File>`;
if (hasMenuCategory) {
result += `<RemoveFolder Id="${startMenuShortcutDirectoryId}" Directory="${startMenuShortcutDirectoryId}" On="uninstall"/>\n`;
}
} else {
result += `/>`;
}
return `${result}\n${fileSpace}</Component>`;
});
return {
dirs: listToString(dirs, 2),
files: listToString(files, 3)
};
}
}
exports.default = MsiTarget;
function listToString(list, indentLevel) {
const space = " ".repeat(indentLevel * 2);
return list.join(`\n${space}`);
}
// __ts-babel@6.0.4
//# sourceMappingURL=MsiTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,21 @@
import { CompressionLevel } from "../core";
export interface ArchiveOptions {
compression?: CompressionLevel | null;
/**
* @default false
*/
withoutDir?: boolean;
/**
* @default true
*/
solid?: boolean;
/**
* @default true
*/
isArchiveHeaderCompressed?: boolean;
dictSize?: number;
excluded?: Array<string> | null;
method?: "Copy" | "LZMA" | "Deflate" | "DEFAULT";
isRegularFile?: boolean;
}
export declare function compute7zCompressArgs(format: string, options?: ArchiveOptions): string[];

View File

@ -0,0 +1,219 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.tar = tar;
exports.compute7zCompressArgs = compute7zCompressArgs;
exports.archive = archive;
function _zipBin() {
const data = require("7zip-bin");
_zipBin = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _tools() {
const data = require("./tools");
_tools = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
/** @internal */
async function tar(compression, format, outFile, dirToArchive, isMacApp, tempDirManager) {
const tarFile = await tempDirManager.getTempFile({
suffix: ".tar"
});
const tarArgs = debug7zArgs("a");
tarArgs.push(tarFile);
tarArgs.push(path.basename(dirToArchive));
await Promise.all([(0, _builderUtil().exec)(_zipBin().path7za, tarArgs, {
cwd: path.dirname(dirToArchive)
}), // remove file before - 7z doesn't overwrite file, but update
(0, _fs().unlinkIfExists)(outFile)]);
if (!isMacApp) {
await (0, _builderUtil().exec)(_zipBin().path7za, ["rn", tarFile, path.basename(dirToArchive), path.basename(outFile, `.${format}`)]);
}
if (format === "tar.lz") {
// noinspection SpellCheckingInspection
let lzipPath = "lzip";
if (process.platform === "darwin") {
lzipPath = path.join(await (0, _tools().getLinuxToolsPath)(), "bin", lzipPath);
}
await (0, _builderUtil().exec)(lzipPath, [compression === "store" ? "-1" : "-9", "--keep"
/* keep (don't delete) input files */
, tarFile]); // bloody lzip creates file in the same dir where input file with postfix `.lz`, option --output doesn't work
await (0, _fsExtra().move)(`${tarFile}.lz`, outFile);
return;
}
const args = compute7zCompressArgs(format === "tar.xz" ? "xz" : format === "tar.bz2" ? "bzip2" : "gzip", {
isRegularFile: true,
method: "DEFAULT",
compression
});
args.push(outFile, tarFile);
await (0, _builderUtil().exec)(_zipBin().path7za, args, {
cwd: path.dirname(dirToArchive)
}, _builderUtil().debug7z.enabled);
}
function compute7zCompressArgs(format, options = {}) {
let storeOnly = options.compression === "store";
const args = debug7zArgs("a");
let isLevelSet = false;
if (process.env.ELECTRON_BUILDER_COMPRESSION_LEVEL != null) {
storeOnly = false;
args.push(`-mx=${process.env.ELECTRON_BUILDER_COMPRESSION_LEVEL}`);
isLevelSet = true;
}
const isZip = format === "zip";
if (!storeOnly) {
if (isZip && options.compression === "maximum") {
// http://superuser.com/a/742034
args.push("-mfb=258", "-mpass=15");
}
if (!isLevelSet) {
// https://github.com/electron-userland/electron-builder/pull/3032
args.push("-mx=" + (!isZip || options.compression === "maximum" ? "9" : "7"));
}
}
if (options.dictSize != null) {
args.push(`-md=${options.dictSize}m`);
} // https://sevenzip.osdn.jp/chm/cmdline/switches/method.htm#7Z
// https://stackoverflow.com/questions/27136783/7zip-produces-different-output-from-identical-input
// tc and ta are off by default, but to be sure, we explicitly set it to off
// disable "Stores NTFS timestamps for files: Modification time, Creation time, Last access time." to produce the same archive for the same data
if (!options.isRegularFile) {
args.push("-mtc=off");
}
if (format === "7z" || format.endsWith(".7z")) {
if (options.solid === false) {
args.push("-ms=off");
}
if (options.isArchiveHeaderCompressed === false) {
args.push("-mhc=off");
} // args valid only for 7z
// -mtm=off disable "Stores last Modified timestamps for files."
args.push("-mtm=off", "-mta=off");
}
if (options.method != null) {
if (options.method !== "DEFAULT") {
args.push(`-mm=${options.method}`);
}
} else if (isZip || storeOnly) {
args.push(`-mm=${storeOnly ? "Copy" : "Deflate"}`);
}
if (isZip) {
// -mcu switch: 7-Zip uses UTF-8, if there are non-ASCII symbols.
// because default mode: 7-Zip uses UTF-8, if the local code page doesn't contain required symbols.
// but archive should be the same regardless where produced
args.push("-mcu");
}
return args;
} // 7z is very fast, so, use ultra compression
/** @internal */
async function archive(format, outFile, dirToArchive, options = {}) {
const args = compute7zCompressArgs(format, options); // remove file before - 7z doesn't overwrite file, but update
await (0, _fs().unlinkIfExists)(outFile);
args.push(outFile, options.withoutDir ? "." : path.basename(dirToArchive));
if (options.excluded != null) {
for (const mask of options.excluded) {
args.push(`-xr!${mask}`);
}
}
try {
await (0, _builderUtil().exec)(_zipBin().path7za, args, {
cwd: options.withoutDir ? dirToArchive : path.dirname(dirToArchive)
}, _builderUtil().debug7z.enabled);
} catch (e) {
if (e.code === "ENOENT" && !(await (0, _fs().exists)(dirToArchive))) {
throw new Error(`Cannot create archive: "${dirToArchive}" doesn't exist`);
} else {
throw e;
}
}
return outFile;
}
function debug7zArgs(command) {
const args = [command, "-bd"];
if (_builderUtil().debug7z.enabled) {
args.push("-bb");
}
return args;
}
// __ts-babel@6.0.4
//# sourceMappingURL=archive.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
import { BlockMapDataHolder, PackageFileInfo } from "builder-util-runtime";
import { Target } from "../core";
import { PlatformPackager } from "../platformPackager";
import { ArchiveOptions } from "./archive";
export declare const BLOCK_MAP_FILE_SUFFIX = ".blockmap";
export declare function createNsisWebDifferentialUpdateInfo(artifactPath: string, packageFiles: {
[arch: string]: PackageFileInfo;
}): {
packages: {
[arch: string]: PackageFileInfo;
};
} | null;
export declare function configureDifferentialAwareArchiveOptions(archiveOptions: ArchiveOptions): ArchiveOptions;
export declare function appendBlockmap(file: string): Promise<BlockMapDataHolder>;
export declare function createBlockmap(file: string, target: Target, packager: PlatformPackager<any>, safeArtifactName: string | null): Promise<BlockMapDataHolder>;

View File

@ -0,0 +1,119 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createNsisWebDifferentialUpdateInfo = createNsisWebDifferentialUpdateInfo;
exports.configureDifferentialAwareArchiveOptions = configureDifferentialAwareArchiveOptions;
exports.appendBlockmap = appendBlockmap;
exports.createBlockmap = createBlockmap;
exports.BLOCK_MAP_FILE_SUFFIX = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _appBuilder() {
const data = require("../util/appBuilder");
_appBuilder = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const BLOCK_MAP_FILE_SUFFIX = ".blockmap";
exports.BLOCK_MAP_FILE_SUFFIX = BLOCK_MAP_FILE_SUFFIX;
function createNsisWebDifferentialUpdateInfo(artifactPath, packageFiles) {
if (packageFiles == null) {
return null;
}
const keys = Object.keys(packageFiles);
if (keys.length <= 0) {
return null;
}
const packages = {};
for (const arch of keys) {
const packageFileInfo = packageFiles[arch];
const file = path.basename(packageFileInfo.path);
packages[arch] = { ...packageFileInfo,
path: file,
// https://github.com/electron-userland/electron-builder/issues/2583
file
};
}
return {
packages
};
}
function configureDifferentialAwareArchiveOptions(archiveOptions) {
/*
* dict size 64 MB: Full: 33,744.88 KB, To download: 17,630.3 KB (52%)
* dict size 16 MB: Full: 33,936.84 KB, To download: 16,175.9 KB (48%)
* dict size 8 MB: Full: 34,187.59 KB, To download: 8,229.9 KB (24%)
* dict size 4 MB: Full: 34,628.73 KB, To download: 3,782.97 KB (11%)
as we can see, if file changed in one place, all block is invalidated (and update size approximately equals to dict size)
1 MB is used:
1MB:
2018/01/11 11:54:41:0045 File has 59 changed blocks
2018/01/11 11:54:41:0050 Full: 71,588.59 KB, To download: 1,243.39 KB (2%)
4MB:
2018/01/11 11:31:43:0440 Full: 70,303.55 KB, To download: 4,843.27 KB (7%)
2018/01/11 11:31:43:0435 File has 234 changed blocks
*/
archiveOptions.dictSize = 1; // solid compression leads to a lot of changed blocks
archiveOptions.solid = false; // do not allow to change compression level to avoid different packages
archiveOptions.compression = "normal";
return archiveOptions;
}
async function appendBlockmap(file) {
_builderUtil().log.info({
file: _builderUtil().log.filePath(file)
}, "building embedded block map");
return await (0, _appBuilder().executeAppBuilderAsJson)(["blockmap", "--input", file, "--compression", "deflate"]);
}
async function createBlockmap(file, target, packager, safeArtifactName) {
const blockMapFile = `${file}${BLOCK_MAP_FILE_SUFFIX}`;
_builderUtil().log.info({
blockMapFile: _builderUtil().log.filePath(blockMapFile)
}, "building block map");
const updateInfo = await (0, _appBuilder().executeAppBuilderAsJson)(["blockmap", "--input", file, "--output", blockMapFile]);
await packager.info.callArtifactBuildCompleted({
file: blockMapFile,
safeArtifactName: safeArtifactName == null ? null : `${safeArtifactName}${BLOCK_MAP_FILE_SUFFIX}`,
target,
arch: null,
packager,
updateInfo
});
return updateInfo;
}
// __ts-babel@6.0.4
//# sourceMappingURL=differentialUpdateInfoBuilder.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,17 @@
import { Arch } from "builder-util";
import { LinuxTargetSpecificOptions } from "..";
import { Target } from "../core";
import { LinuxPackager } from "../linuxPackager";
import { LinuxTargetHelper } from "./LinuxTargetHelper";
export default class FpmTarget extends Target {
private readonly packager;
private readonly helper;
readonly outDir: string;
readonly options: LinuxTargetSpecificOptions;
private readonly scriptFiles;
constructor(name: string, packager: LinuxPackager, helper: LinuxTargetHelper, outDir: string);
private createScripts;
checkOptions(): Promise<any>;
private computeFpmMetaInfoOptions;
build(appOutDir: string, arch: Arch): Promise<any>;
}

View File

@ -0,0 +1,356 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _zipBin() {
const data = require("7zip-bin");
_zipBin = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _appInfo() {
const data = require("../appInfo");
_appInfo = function () {
return data;
};
return data;
}
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function errorMessages() {
const data = _interopRequireWildcard(require("../errorMessages"));
errorMessages = function () {
return data;
};
return data;
}
function _appBuilder() {
const data = require("../util/appBuilder");
_appBuilder = function () {
return data;
};
return data;
}
function _bundledTool() {
const data = require("../util/bundledTool");
_bundledTool = function () {
return data;
};
return data;
}
function _macosVersion() {
const data = require("../util/macosVersion");
_macosVersion = function () {
return data;
};
return data;
}
function _pathManager() {
const data = require("../util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
function _LinuxTargetHelper() {
const data = require("./LinuxTargetHelper");
_LinuxTargetHelper = function () {
return data;
};
return data;
}
function _tools() {
const data = require("./tools");
_tools = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
class FpmTarget extends _core().Target {
constructor(name, packager, helper, outDir) {
super(name, false);
this.packager = packager;
this.helper = helper;
this.outDir = outDir;
this.options = { ...this.packager.platformSpecificBuildOptions,
...this.packager.config[this.name]
};
this.scriptFiles = this.createScripts();
}
async createScripts() {
const defaultTemplatesDir = (0, _pathManager().getTemplatePath)("linux");
const packager = this.packager;
const templateOptions = {
// old API compatibility
executable: packager.executableName,
productFilename: packager.appInfo.productFilename,
...packager.platformSpecificBuildOptions
};
function getResource(value, defaultFile) {
if (value == null) {
return path.join(defaultTemplatesDir, defaultFile);
}
return path.resolve(packager.projectDir, value);
}
return await Promise.all([writeConfigFile(packager.info.tempDirManager, getResource(this.options.afterInstall, "after-install.tpl"), templateOptions), writeConfigFile(packager.info.tempDirManager, getResource(this.options.afterRemove, "after-remove.tpl"), templateOptions)]);
}
checkOptions() {
return this.computeFpmMetaInfoOptions();
}
async computeFpmMetaInfoOptions() {
const packager = this.packager;
const projectUrl = await packager.appInfo.computePackageUrl();
const errors = [];
if (projectUrl == null) {
errors.push("Please specify project homepage, see https://electron.build/configuration/configuration#Metadata-homepage");
}
const options = this.options;
let author = options.maintainer;
if (author == null) {
const a = packager.info.metadata.author;
if (a == null || a.email == null) {
errors.push(errorMessages().authorEmailIsMissed);
} else {
author = `${a.name} <${a.email}>`;
}
}
if (errors.length > 0) {
throw new Error(errors.join("\n\n"));
}
return {
maintainer: author,
url: projectUrl,
vendor: options.vendor || author
};
}
async build(appOutDir, arch) {
const target = this.name; // tslint:disable:no-invalid-template-strings
let nameFormat = "${name}-${version}-${arch}.${ext}";
let isUseArchIfX64 = false;
if (target === "deb") {
nameFormat = "${name}_${version}_${arch}.${ext}";
isUseArchIfX64 = true;
} else if (target === "rpm") {
nameFormat = "${name}-${version}.${arch}.${ext}";
isUseArchIfX64 = true;
}
const packager = this.packager;
const artifactPath = path.join(this.outDir, packager.expandArtifactNamePattern(this.options, target, arch, nameFormat, !isUseArchIfX64));
await packager.info.callArtifactBuildStarted({
targetPresentableName: target,
file: artifactPath,
arch
});
await (0, _fs().unlinkIfExists)(artifactPath);
if (packager.packagerOptions.prepackaged != null) {
await (0, _fsExtra().ensureDir)(this.outDir);
}
const scripts = await this.scriptFiles;
const appInfo = packager.appInfo;
const options = this.options;
const synopsis = options.synopsis;
const args = ["--architecture", (0, _builderUtil().toLinuxArchString)(arch, target), "--name", appInfo.linuxPackageName, "--after-install", scripts[0], "--after-remove", scripts[1], "--description", (0, _appInfo().smarten)(target === "rpm" ? this.helper.getDescription(options) : `${synopsis || ""}\n ${this.helper.getDescription(options)}`), "--version", appInfo.version, "--package", artifactPath];
(0, _appBuilder().objectToArgs)(args, await this.computeFpmMetaInfoOptions());
const packageCategory = options.packageCategory;
if (packageCategory != null) {
args.push("--category", packageCategory);
}
if (target === "deb") {
(0, _builderUtil().use)(options.priority, it => args.push("--deb-priority", it));
} else if (target === "rpm") {
if (synopsis != null) {
args.push("--rpm-summary", (0, _appInfo().smarten)(synopsis));
}
}
const fpmConfiguration = {
args,
target
};
if (options.compression != null) {
fpmConfiguration.compression = options.compression;
} // noinspection JSDeprecatedSymbols
const depends = options.depends;
if (depends != null) {
if (Array.isArray(depends)) {
fpmConfiguration.customDepends = depends;
} else {
// noinspection SuspiciousTypeOfGuard
if (typeof depends === "string") {
fpmConfiguration.customDepends = [depends];
} else {
throw new Error(`depends must be Array or String, but specified as: ${depends}`);
}
}
}
(0, _builderUtil().use)(packager.info.metadata.license, it => args.push("--license", it));
(0, _builderUtil().use)(appInfo.buildNumber, it => args.push("--iteration", it));
(0, _builderUtil().use)(options.fpm, it => args.push(...it));
args.push(`${appOutDir}/=${_LinuxTargetHelper().installPrefix}/${appInfo.productFilename}`);
for (const icon of await this.helper.icons) {
const extWithDot = path.extname(icon.file);
const sizeName = extWithDot === ".svg" ? "scalable" : `${icon.size}x${icon.size}`;
args.push(`${icon.file}=/usr/share/icons/hicolor/${sizeName}/apps/${packager.executableName}${extWithDot}`);
}
const mimeTypeFilePath = await this.helper.mimeTypeFiles;
if (mimeTypeFilePath != null) {
args.push(`${mimeTypeFilePath}=/usr/share/mime/packages/${packager.executableName}.xml`);
}
const desktopFilePath = await this.helper.writeDesktopEntry(this.options);
args.push(`${desktopFilePath}=/usr/share/applications/${packager.executableName}.desktop`);
if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed([args, desktopFilePath]))) {
return;
}
const env = { ...process.env,
SZA_PATH: _zipBin().path7za,
SZA_COMPRESSION_LEVEL: packager.compression === "store" ? "0" : "9"
}; // rpmbuild wants directory rpm with some default config files. Even if we can use dylibbundler, path to such config files are not changed (we need to replace in the binary)
// so, for now, brew install rpm is still required.
if (target !== "rpm" && (await (0, _macosVersion().isMacOsSierra)())) {
const linuxToolsPath = await (0, _tools().getLinuxToolsPath)();
Object.assign(env, {
PATH: (0, _bundledTool().computeEnv)(process.env.PATH, [path.join(linuxToolsPath, "bin")]),
DYLD_LIBRARY_PATH: (0, _bundledTool().computeEnv)(process.env.DYLD_LIBRARY_PATH, [path.join(linuxToolsPath, "lib")])
});
}
await (0, _builderUtil().executeAppBuilder)(["fpm", "--configuration", JSON.stringify(fpmConfiguration)], undefined, {
env
});
await packager.dispatchArtifactCreated(artifactPath, this, arch);
}
}
exports.default = FpmTarget;
async function writeConfigFile(tmpDir, templatePath, options) {
//noinspection JSUnusedLocalSymbols
function replacer(match, p1) {
if (p1 in options) {
return options[p1];
} else {
throw new Error(`Macro ${p1} is not defined`);
}
}
const config = (await (0, _fsExtra().readFile)(templatePath, "utf8")).replace(/\${([a-zA-Z]+)}/g, replacer).replace(/<%=([a-zA-Z]+)%>/g, (match, p1) => {
_builderUtil().log.warn("<%= varName %> is deprecated, please use ${varName} instead");
return replacer(match, p1.trim());
});
const outputPath = await tmpDir.getTempFile({
suffix: path.basename(templatePath, ".tpl")
});
await (0, _fsExtra().outputFile)(outputPath, config);
return outputPath;
}
// __ts-babel@6.0.4
//# sourceMappingURL=fpm.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,34 @@
import { Arch } from "builder-util";
import { PackageFileInfo } from "builder-util-runtime";
import { Target } from "../../core";
import { WinPackager } from "../../winPackager";
import { NsisOptions } from "./nsisOptions";
import { AppPackageHelper } from "./nsisUtil";
export declare class NsisTarget extends Target {
readonly packager: WinPackager;
readonly outDir: string;
protected readonly packageHelper: AppPackageHelper;
readonly options: NsisOptions;
/** @private */
readonly archs: Map<Arch, string>;
constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper);
build(appOutDir: string, arch: Arch): Promise<void>;
get isBuildDifferentialAware(): boolean;
private getPreCompressedFileExtensions;
/** @private */
buildAppPackage(appOutDir: string, arch: Arch): Promise<PackageFileInfo>;
finishBuild(): Promise<any>;
protected get installerFilenamePattern(): string;
private get isPortable();
private buildInstaller;
protected generateGitHubInstallerName(): string;
private get isUnicodeEnabled();
get isWebInstaller(): boolean;
private computeScriptAndSignUninstaller;
private computeVersionKey;
protected configureDefines(oneClick: boolean, defines: any): Promise<any>;
private configureDefinesForAllTypeOfInstaller;
private executeMakensis;
private computeCommonInstallerScriptHeader;
private computeFinalScript;
}

View File

@ -0,0 +1,952 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NsisTarget = void 0;
function _zipBin() {
const data = require("7zip-bin");
_zipBin = function () {
return data;
};
return data;
}
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _builderUtilRuntime() {
const data = require("builder-util-runtime");
_builderUtilRuntime = function () {
return data;
};
return data;
}
function _binDownload() {
const data = require("../../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _hash() {
const data = require("../../util/hash");
_hash = function () {
return data;
};
return data;
}
var _debug2 = _interopRequireDefault(require("debug"));
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
var fs = _interopRequireWildcard(require("fs"));
function _core() {
const data = require("../../core");
_core = function () {
return data;
};
return data;
}
function _CommonWindowsInstallerConfiguration() {
const data = require("../../options/CommonWindowsInstallerConfiguration");
_CommonWindowsInstallerConfiguration = function () {
return data;
};
return data;
}
function _platformPackager() {
const data = require("../../platformPackager");
_platformPackager = function () {
return data;
};
return data;
}
function _macosVersion() {
const data = require("../../util/macosVersion");
_macosVersion = function () {
return data;
};
return data;
}
function _timer() {
const data = require("../../util/timer");
_timer = function () {
return data;
};
return data;
}
function _wine() {
const data = require("../../wine");
_wine = function () {
return data;
};
return data;
}
function _archive() {
const data = require("../archive");
_archive = function () {
return data;
};
return data;
}
function _differentialUpdateInfoBuilder() {
const data = require("../differentialUpdateInfoBuilder");
_differentialUpdateInfoBuilder = function () {
return data;
};
return data;
}
function _targetUtil() {
const data = require("../targetUtil");
_targetUtil = function () {
return data;
};
return data;
}
function _nsisLang() {
const data = require("./nsisLang");
_nsisLang = function () {
return data;
};
return data;
}
function _nsisLicense() {
const data = require("./nsisLicense");
_nsisLicense = function () {
return data;
};
return data;
}
function _nsisScriptGenerator() {
const data = require("./nsisScriptGenerator");
_nsisScriptGenerator = function () {
return data;
};
return data;
}
function _nsisUtil() {
const data = require("./nsisUtil");
_nsisUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug2.default)("electron-builder:nsis"); // noinspection SpellCheckingInspection
const ELECTRON_BUILDER_NS_UUID = _builderUtilRuntime().UUID.parse("50e065bc-3134-11e6-9bab-38c9862bdaf3"); // noinspection SpellCheckingInspection
const nsisResourcePathPromise = () => (0, _binDownload().getBinFromUrl)("nsis-resources", "3.4.1", "Dqd6g+2buwwvoG1Vyf6BHR1b+25QMmPcwZx40atOT57gH27rkjOei1L0JTldxZu4NFoEmW4kJgZ3DlSWVON3+Q==");
const USE_NSIS_BUILT_IN_COMPRESSOR = false;
class NsisTarget extends _core().Target {
constructor(packager, outDir, targetName, packageHelper) {
super(targetName);
this.packager = packager;
this.outDir = outDir;
this.packageHelper = packageHelper;
/** @private */
this.archs = new Map();
this.packageHelper.refCount++;
this.options = targetName === "portable" ? Object.create(null) : {
preCompressedFileExtensions: [".avi", ".mov", ".m4v", ".mp4", ".m4p", ".qt", ".mkv", ".webm", ".vmdk"],
...this.packager.config.nsis
};
if (targetName !== "nsis") {
Object.assign(this.options, this.packager.config[targetName === "nsis-web" ? "nsisWeb" : targetName]);
}
const deps = packager.info.metadata.dependencies;
if (deps != null && deps["electron-squirrel-startup"] != null) {
_builderUtil().log.warn('"electron-squirrel-startup" dependency is not required for NSIS');
}
}
async build(appOutDir, arch) {
this.archs.set(arch, appOutDir);
}
get isBuildDifferentialAware() {
return !this.isPortable && this.options.differentialPackage !== false;
}
getPreCompressedFileExtensions() {
const result = this.isWebInstaller ? null : this.options.preCompressedFileExtensions;
return result == null ? null : (0, _builderUtil().asArray)(result).map(it => it.startsWith(".") ? it : `.${it}`);
}
/** @private */
async buildAppPackage(appOutDir, arch) {
const options = this.options;
const packager = this.packager;
const isBuildDifferentialAware = this.isBuildDifferentialAware;
const format = !isBuildDifferentialAware && options.useZip ? "zip" : "7z";
const archiveFile = path.join(this.outDir, `${packager.appInfo.sanitizedName}-${packager.appInfo.version}-${_builderUtil().Arch[arch]}.nsis.${format}`);
const preCompressedFileExtensions = this.getPreCompressedFileExtensions();
const archiveOptions = {
withoutDir: true,
compression: packager.compression,
excluded: preCompressedFileExtensions == null ? null : preCompressedFileExtensions.map(it => `*${it}`)
};
const timer = (0, _timer().time)(`nsis package, ${_builderUtil().Arch[arch]}`);
await (0, _archive().archive)(format, archiveFile, appOutDir, isBuildDifferentialAware ? (0, _differentialUpdateInfoBuilder().configureDifferentialAwareArchiveOptions)(archiveOptions) : archiveOptions);
timer.end();
if (isBuildDifferentialAware && this.isWebInstaller) {
const data = await (0, _differentialUpdateInfoBuilder().appendBlockmap)(archiveFile);
return { ...data,
path: archiveFile
};
} else {
return await createPackageFileInfo(archiveFile);
}
}
async finishBuild() {
try {
await this.buildInstaller();
} finally {
await this.packageHelper.finishBuild();
}
}
get installerFilenamePattern() {
// tslint:disable:no-invalid-template-strings
return "${productName} " + (this.isPortable ? "" : "Setup ") + "${version}.${ext}";
}
get isPortable() {
return this.name === "portable";
}
async buildInstaller() {
const packager = this.packager;
const appInfo = packager.appInfo;
const options = this.options;
const installerFilename = packager.expandArtifactNamePattern(options, "exe", null, this.installerFilenamePattern);
const oneClick = options.oneClick !== false;
const installerPath = path.join(this.outDir, installerFilename);
const logFields = {
target: this.name,
file: _builderUtil().log.filePath(installerPath),
archs: Array.from(this.archs.keys()).map(it => _builderUtil().Arch[it]).join(", ")
};
const isPerMachine = options.perMachine === true;
if (!this.isPortable) {
logFields.oneClick = oneClick;
logFields.perMachine = isPerMachine;
}
await packager.info.callArtifactBuildStarted({
targetPresentableName: this.name,
file: installerPath,
arch: null
}, logFields);
const guid = options.guid || _builderUtilRuntime().UUID.v5(appInfo.id, ELECTRON_BUILDER_NS_UUID);
const uninstallAppKey = guid.replace(/\\/g, " - ");
const defines = {
APP_ID: appInfo.id,
APP_GUID: guid,
// Windows bug - entry in Software\Microsoft\Windows\CurrentVersion\Uninstall cannot have \ symbols (dir)
UNINSTALL_APP_KEY: uninstallAppKey,
PRODUCT_NAME: appInfo.productName,
PRODUCT_FILENAME: appInfo.productFilename,
APP_FILENAME: (0, _targetUtil().getWindowsInstallationDirName)(appInfo, !oneClick || isPerMachine),
APP_DESCRIPTION: appInfo.description,
VERSION: appInfo.version,
PROJECT_DIR: packager.projectDir,
BUILD_RESOURCES_DIR: packager.info.buildResourcesDir,
APP_PACKAGE_NAME: appInfo.name
};
if (uninstallAppKey !== guid) {
defines.UNINSTALL_REGISTRY_KEY_2 = `Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\${guid}`;
}
const commands = {
OutFile: `"${installerPath}"`,
VIProductVersion: appInfo.getVersionInWeirdWindowsForm(),
VIAddVersionKey: this.computeVersionKey(),
Unicode: this.isUnicodeEnabled
};
const isPortable = this.isPortable;
const iconPath = (isPortable ? null : await packager.getResource(options.installerIcon, "installerIcon.ico")) || (await packager.getIconPath());
if (iconPath != null) {
if (isPortable) {
commands.Icon = `"${iconPath}"`;
} else {
defines.MUI_ICON = iconPath;
defines.MUI_UNICON = iconPath;
}
}
const packageFiles = {};
let estimatedSize = 0;
if (this.isPortable && options.useZip) {
for (const [arch, dir] of this.archs.entries()) {
defines[arch === _builderUtil().Arch.x64 ? "APP_DIR_64" : arch === _builderUtil().Arch.arm64 ? "APP_DIR_ARM64" : "APP_DIR_32"] = dir;
}
} else if (USE_NSIS_BUILT_IN_COMPRESSOR && this.archs.size === 1) {
defines.APP_BUILD_DIR = this.archs.get(this.archs.keys().next().value);
} else {
await _bluebirdLst().default.map(this.archs.keys(), async arch => {
const fileInfo = await this.packageHelper.packArch(arch, this);
const file = fileInfo.path;
const defineKey = arch === _builderUtil().Arch.x64 ? "APP_64" : arch === _builderUtil().Arch.arm64 ? "APP_ARM64" : "APP_32";
defines[defineKey] = file;
defines[`${defineKey}_NAME`] = path.basename(file); // nsis expect a hexadecimal string
defines[`${defineKey}_HASH`] = Buffer.from(fileInfo.sha512, "base64").toString("hex").toUpperCase();
if (this.isWebInstaller) {
await packager.dispatchArtifactCreated(file, this, arch);
packageFiles[_builderUtil().Arch[arch]] = fileInfo;
}
const archiveInfo = (await (0, _builderUtil().exec)(_zipBin().path7za, ["l", file])).trim(); // after adding blockmap data will be "Warnings: 1" in the end of output
const match = archiveInfo.match(/(\d+)\s+\d+\s+\d+\s+files/);
if (match == null) {
_builderUtil().log.warn({
output: archiveInfo
}, "cannot compute size of app package");
} else {
estimatedSize += parseInt(match[1], 10);
}
});
}
this.configureDefinesForAllTypeOfInstaller(defines);
if (isPortable) {
const portableOptions = options;
defines.REQUEST_EXECUTION_LEVEL = portableOptions.requestExecutionLevel || "user";
defines.UNPACK_DIR_NAME = portableOptions.unpackDirName || (await (0, _builderUtil().executeAppBuilder)(["ksuid"]));
if (portableOptions.splashImage != null) {
defines.SPLASH_IMAGE = path.resolve(packager.projectDir, portableOptions.splashImage);
}
} else {
await this.configureDefines(oneClick, defines);
}
if (estimatedSize !== 0) {
// in kb
defines.ESTIMATED_SIZE = Math.round(estimatedSize / 1024);
}
if (packager.compression === "store") {
commands.SetCompress = "off";
} else {
// difference - 33.540 vs 33.601, only 61 KB (but zip is faster to decompress)
// do not use /SOLID - "With solid compression, files are uncompressed to temporary file before they are copied to their final destination",
// it is not good for portable installer (where built-in NSIS compression is used). http://forums.winamp.com/showpost.php?p=2982902&postcount=6
commands.SetCompressor = "zlib";
if (!this.isWebInstaller) {
defines.COMPRESS = "auto";
}
}
debug(defines);
debug(commands);
if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed([defines, commands]))) {
return;
} // prepare short-version variants of defines and commands, to make an uninstaller that doesn't differ much from the previous one
const definesUninstaller = { ...defines
};
const commandsUninstaller = { ...commands
};
if (appInfo.shortVersion != null) {
definesUninstaller.VERSION = appInfo.shortVersion;
commandsUninstaller.VIProductVersion = appInfo.shortVersionWindows;
commandsUninstaller.VIAddVersionKey = this.computeVersionKey(true);
}
const sharedHeader = await this.computeCommonInstallerScriptHeader();
const script = isPortable ? await (0, _fsExtra().readFile)(path.join(_nsisUtil().nsisTemplatesDir, "portable.nsi"), "utf8") : await this.computeScriptAndSignUninstaller(definesUninstaller, commandsUninstaller, installerPath, sharedHeader); // copy outfile name into main options, as the computeScriptAndSignUninstaller function was kind enough to add important data to temporary defines.
defines.UNINSTALLER_OUT_FILE = definesUninstaller.UNINSTALLER_OUT_FILE;
await this.executeMakensis(defines, commands, sharedHeader + (await this.computeFinalScript(script, true)));
await Promise.all([packager.sign(installerPath), defines.UNINSTALLER_OUT_FILE == null ? Promise.resolve() : (0, _fsExtra().unlink)(defines.UNINSTALLER_OUT_FILE)]);
const safeArtifactName = (0, _platformPackager().computeSafeArtifactNameIfNeeded)(installerFilename, () => this.generateGitHubInstallerName());
let updateInfo;
if (this.isWebInstaller) {
updateInfo = (0, _differentialUpdateInfoBuilder().createNsisWebDifferentialUpdateInfo)(installerPath, packageFiles);
} else if (this.isBuildDifferentialAware) {
updateInfo = await (0, _differentialUpdateInfoBuilder().createBlockmap)(installerPath, this, packager, safeArtifactName);
}
if (updateInfo != null && isPerMachine && oneClick) {
updateInfo.isAdminRightsRequired = true;
}
await packager.info.callArtifactBuildCompleted({
file: installerPath,
updateInfo,
target: this,
packager,
arch: this.archs.size === 1 ? this.archs.keys().next().value : null,
safeArtifactName,
isWriteUpdateInfo: !this.isPortable
});
}
generateGitHubInstallerName() {
const appInfo = this.packager.appInfo;
const classifier = appInfo.name.toLowerCase() === appInfo.name ? "setup-" : "Setup-";
return `${appInfo.name}-${this.isPortable ? "" : classifier}${appInfo.version}.exe`;
}
get isUnicodeEnabled() {
return this.options.unicode !== false;
}
get isWebInstaller() {
return false;
}
async computeScriptAndSignUninstaller(defines, commands, installerPath, sharedHeader) {
const packager = this.packager;
const customScriptPath = await packager.getResource(this.options.script, "installer.nsi");
const script = await (0, _fsExtra().readFile)(customScriptPath || path.join(_nsisUtil().nsisTemplatesDir, "installer.nsi"), "utf8");
if (customScriptPath != null) {
_builderUtil().log.info({
reason: "custom NSIS script is used"
}, "uninstaller is not signed by electron-builder");
return script;
} // https://github.com/electron-userland/electron-builder/issues/2103
// it is more safe and reliable to write uninstaller to our out dir
const uninstallerPath = path.join(this.outDir, `__uninstaller-${this.name}-${this.packager.appInfo.sanitizedName}.exe`);
const isWin = process.platform === "win32";
defines.BUILD_UNINSTALLER = null;
defines.UNINSTALLER_OUT_FILE = isWin ? uninstallerPath : path.win32.join("Z:", uninstallerPath);
await this.executeMakensis(defines, commands, sharedHeader + (await this.computeFinalScript(script, false))); // http://forums.winamp.com/showthread.php?p=3078545
if ((0, _macosVersion().isMacOsCatalina)()) {
try {
_nsisUtil().UninstallerReader.exec(installerPath, uninstallerPath);
} catch (error) {
_builderUtil().log.warn("packager.vm is used: " + error.message);
const vm = await packager.vm.value;
await vm.exec(installerPath, []); // Parallels VM can exit after command execution, but NSIS continue to be running
let i = 0;
while (!(await (0, _fs().exists)(uninstallerPath)) && i++ < 100) {
// noinspection JSUnusedLocalSymbols
// eslint-disable-next-line @typescript-eslint/no-unused-vars
await new Promise((resolve, _reject) => setTimeout(resolve, 300));
}
}
} else {
await (0, _wine().execWine)(installerPath);
}
await packager.sign(uninstallerPath, " Signing NSIS uninstaller");
delete defines.BUILD_UNINSTALLER; // platform-specific path, not wine
defines.UNINSTALLER_OUT_FILE = uninstallerPath;
return script;
}
computeVersionKey(short = false) {
// Error: invalid VIProductVersion format, should be X.X.X.X
// so, we must strip beta
const localeId = this.options.language || "1033";
const appInfo = this.packager.appInfo;
const versionKey = [`/LANG=${localeId} ProductName "${appInfo.productName}"`, `/LANG=${localeId} ProductVersion "${appInfo.version}"`, `/LANG=${localeId} LegalCopyright "${appInfo.copyright}"`, `/LANG=${localeId} FileDescription "${appInfo.description}"`, `/LANG=${localeId} FileVersion "${appInfo.buildVersion}"`];
if (short) {
versionKey[1] = `/LANG=${localeId} ProductVersion "${appInfo.shortVersion}"`;
versionKey[4] = `/LANG=${localeId} FileVersion "${appInfo.shortVersion}"`;
}
(0, _builderUtil().use)(this.packager.platformSpecificBuildOptions.legalTrademarks, it => versionKey.push(`/LANG=${localeId} LegalTrademarks "${it}"`));
(0, _builderUtil().use)(appInfo.companyName, it => versionKey.push(`/LANG=${localeId} CompanyName "${it}"`));
return versionKey;
}
configureDefines(oneClick, defines) {
const packager = this.packager;
const options = this.options;
const asyncTaskManager = new (_builderUtil().AsyncTaskManager)(packager.info.cancellationToken);
if (oneClick) {
defines.ONE_CLICK = null;
if (options.runAfterFinish !== false) {
defines.RUN_AFTER_FINISH = null;
}
asyncTaskManager.add(async () => {
const installerHeaderIcon = await packager.getResource(options.installerHeaderIcon, "installerHeaderIcon.ico");
if (installerHeaderIcon != null) {
defines.HEADER_ICO = installerHeaderIcon;
}
});
} else {
if (options.runAfterFinish === false) {
defines.HIDE_RUN_AFTER_FINISH = null;
}
asyncTaskManager.add(async () => {
const installerHeader = await packager.getResource(options.installerHeader, "installerHeader.bmp");
if (installerHeader != null) {
defines.MUI_HEADERIMAGE = null;
defines.MUI_HEADERIMAGE_RIGHT = null;
defines.MUI_HEADERIMAGE_BITMAP = installerHeader;
}
});
asyncTaskManager.add(async () => {
const bitmap = (await packager.getResource(options.installerSidebar, "installerSidebar.bmp")) || "${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp";
defines.MUI_WELCOMEFINISHPAGE_BITMAP = bitmap;
defines.MUI_UNWELCOMEFINISHPAGE_BITMAP = (await packager.getResource(options.uninstallerSidebar, "uninstallerSidebar.bmp")) || bitmap;
});
if (options.allowElevation !== false) {
defines.MULTIUSER_INSTALLMODE_ALLOW_ELEVATION = null;
}
}
if (options.perMachine === true) {
defines.INSTALL_MODE_PER_ALL_USERS = null;
}
if (!oneClick || options.perMachine === true) {
defines.INSTALL_MODE_PER_ALL_USERS_REQUIRED = null;
}
if (options.allowToChangeInstallationDirectory) {
if (oneClick) {
throw new (_builderUtil().InvalidConfigurationError)("allowToChangeInstallationDirectory makes sense only for assisted installer (please set oneClick to false)");
}
defines.allowToChangeInstallationDirectory = null;
}
const commonOptions = (0, _CommonWindowsInstallerConfiguration().getEffectiveOptions)(options, packager);
if (commonOptions.menuCategory != null) {
defines.MENU_FILENAME = commonOptions.menuCategory;
}
defines.SHORTCUT_NAME = commonOptions.shortcutName;
if (options.deleteAppDataOnUninstall) {
defines.DELETE_APP_DATA_ON_UNINSTALL = null;
}
asyncTaskManager.add(async () => {
const uninstallerIcon = await packager.getResource(options.uninstallerIcon, "uninstallerIcon.ico");
if (uninstallerIcon != null) {
// we don't need to copy MUI_UNICON (defaults to app icon), so, we have 2 defines
defines.UNINSTALLER_ICON = uninstallerIcon;
defines.MUI_UNICON = uninstallerIcon;
}
});
defines.UNINSTALL_DISPLAY_NAME = packager.expandMacro(options.uninstallDisplayName || "${productName} ${version}", null, {}, false);
if (commonOptions.isCreateDesktopShortcut === _CommonWindowsInstallerConfiguration().DesktopShortcutCreationPolicy.NEVER) {
defines.DO_NOT_CREATE_DESKTOP_SHORTCUT = null;
}
if (commonOptions.isCreateDesktopShortcut === _CommonWindowsInstallerConfiguration().DesktopShortcutCreationPolicy.ALWAYS) {
defines.RECREATE_DESKTOP_SHORTCUT = null;
}
if (!commonOptions.isCreateStartMenuShortcut) {
defines.DO_NOT_CREATE_START_MENU_SHORTCUT = null;
}
if (options.displayLanguageSelector === true) {
defines.DISPLAY_LANG_SELECTOR = null;
}
return asyncTaskManager.awaitTasks();
}
configureDefinesForAllTypeOfInstaller(defines) {
const appInfo = this.packager.appInfo;
const companyName = appInfo.companyName;
if (companyName != null) {
defines.COMPANY_NAME = companyName;
} // electron uses product file name as app data, define it as well to remove on uninstall
if (defines.APP_FILENAME !== appInfo.productFilename) {
defines.APP_PRODUCT_FILENAME = appInfo.productFilename;
}
if (this.isWebInstaller) {
defines.APP_PACKAGE_STORE_FILE = `${appInfo.updaterCacheDirName}\\${_builderUtilRuntime().CURRENT_APP_PACKAGE_FILE_NAME}`;
} else {
defines.APP_INSTALLER_STORE_FILE = `${appInfo.updaterCacheDirName}\\${_builderUtilRuntime().CURRENT_APP_INSTALLER_FILE_NAME}`;
}
if (!this.isWebInstaller && defines.APP_BUILD_DIR == null) {
const options = this.options;
if (options.useZip) {
defines.ZIP_COMPRESSION = null;
}
defines.COMPRESSION_METHOD = options.useZip ? "zip" : "7z";
}
}
async executeMakensis(defines, commands, script) {
const args = this.options.warningsAsErrors === false ? [] : ["-WX"];
for (const name of Object.keys(defines)) {
const value = defines[name];
if (value == null) {
args.push(`-D${name}`);
} else {
args.push(`-D${name}=${value}`);
}
}
for (const name of Object.keys(commands)) {
const value = commands[name];
if (Array.isArray(value)) {
for (const c of value) {
args.push(`-X${name} ${c}`);
}
} else {
args.push(`-X${name} ${value}`);
}
}
args.push("-");
if (this.packager.debugLogger.isEnabled) {
this.packager.debugLogger.add("nsis.script", script);
}
const nsisPath = await (0, _nsisUtil().NSIS_PATH)();
const command = path.join(nsisPath, process.platform === "darwin" ? "mac" : process.platform === "win32" ? "Bin" : "linux", process.platform === "win32" ? "makensis.exe" : "makensis"); // if (process.platform === "win32") {
// fix for an issue caused by virus scanners, locking the file during write
// https://github.com/electron-userland/electron-builder/issues/5005
await ensureNotBusy(commands["OutFile"].replace(/"/g, "")); // }
await (0, _builderUtil().spawnAndWrite)(command, args, script, {
// we use NSIS_CONFIG_CONST_DATA_PATH=no to build makensis on Linux, but in any case it doesn't use stubs as MacOS/Windows version, so, we explicitly set NSISDIR
env: { ...process.env,
NSISDIR: nsisPath
},
cwd: _nsisUtil().nsisTemplatesDir
});
}
async computeCommonInstallerScriptHeader() {
const packager = this.packager;
const options = this.options;
const scriptGenerator = new (_nsisScriptGenerator().NsisScriptGenerator)();
const langConfigurator = new (_nsisLang().LangConfigurator)(options);
scriptGenerator.include(path.join(_nsisUtil().nsisTemplatesDir, "include", "StdUtils.nsh"));
const includeDir = path.join(_nsisUtil().nsisTemplatesDir, "include");
scriptGenerator.addIncludeDir(includeDir);
scriptGenerator.flags(["updated", "force-run", "keep-shortcuts", "no-desktop-shortcut", "delete-app-data", "allusers", "currentuser"]);
(0, _nsisLang().createAddLangsMacro)(scriptGenerator, langConfigurator);
const taskManager = new (_builderUtil().AsyncTaskManager)(packager.info.cancellationToken);
const pluginArch = this.isUnicodeEnabled ? "x86-unicode" : "x86-ansi";
taskManager.add(async () => {
scriptGenerator.addPluginDir(pluginArch, path.join(await nsisResourcePathPromise(), "plugins", pluginArch));
});
taskManager.add(async () => {
const userPluginDir = path.join(packager.info.buildResourcesDir, pluginArch);
const stat = await (0, _fs().statOrNull)(userPluginDir);
if (stat != null && stat.isDirectory()) {
scriptGenerator.addPluginDir(pluginArch, userPluginDir);
}
});
taskManager.addTask((0, _nsisLang().addCustomMessageFileInclude)("messages.yml", packager, scriptGenerator, langConfigurator));
if (!this.isPortable) {
if (options.oneClick === false) {
taskManager.addTask((0, _nsisLang().addCustomMessageFileInclude)("assistedMessages.yml", packager, scriptGenerator, langConfigurator));
}
taskManager.add(async () => {
const customInclude = await packager.getResource(this.options.include, "installer.nsh");
if (customInclude != null) {
scriptGenerator.addIncludeDir(packager.info.buildResourcesDir);
scriptGenerator.include(customInclude);
}
});
}
await taskManager.awaitTasks();
return scriptGenerator.build();
}
async computeFinalScript(originalScript, isInstaller) {
const packager = this.packager;
const options = this.options;
const langConfigurator = new (_nsisLang().LangConfigurator)(options);
const scriptGenerator = new (_nsisScriptGenerator().NsisScriptGenerator)();
const taskManager = new (_builderUtil().AsyncTaskManager)(packager.info.cancellationToken);
if (isInstaller) {
// http://stackoverflow.com/questions/997456/nsis-license-file-based-on-language-selection
taskManager.add(() => (0, _nsisLicense().computeLicensePage)(packager, options, scriptGenerator, langConfigurator.langs));
}
await taskManager.awaitTasks();
if (this.isPortable) {
return scriptGenerator.build() + originalScript;
}
const preCompressedFileExtensions = this.getPreCompressedFileExtensions();
if (preCompressedFileExtensions != null && preCompressedFileExtensions.length !== 0) {
for (const [arch, dir] of this.archs.entries()) {
await generateForPreCompressed(preCompressedFileExtensions, dir, arch, scriptGenerator);
}
}
const fileAssociations = packager.fileAssociations;
if (fileAssociations.length !== 0) {
scriptGenerator.include(path.join(path.join(_nsisUtil().nsisTemplatesDir, "include"), "FileAssociation.nsh"));
if (isInstaller) {
const registerFileAssociationsScript = new (_nsisScriptGenerator().NsisScriptGenerator)();
for (const item of fileAssociations) {
const extensions = (0, _builderUtil().asArray)(item.ext).map(_platformPackager().normalizeExt);
for (const ext of extensions) {
const customIcon = await packager.getResource((0, _builderUtil().getPlatformIconFileName)(item.icon, false), `${extensions[0]}.ico`);
let installedIconPath = "$appExe,0";
if (customIcon != null) {
installedIconPath = `$INSTDIR\\resources\\${path.basename(customIcon)}`;
registerFileAssociationsScript.file(installedIconPath, customIcon);
}
const icon = `"${installedIconPath}"`;
const commandText = `"Open with ${packager.appInfo.productName}"`;
const command = '"$appExe $\\"%1$\\""';
registerFileAssociationsScript.insertMacro("APP_ASSOCIATE", `"${ext}" "${item.name || ext}" "${item.description || ""}" ${icon} ${commandText} ${command}`);
}
}
scriptGenerator.macro("registerFileAssociations", registerFileAssociationsScript);
} else {
const unregisterFileAssociationsScript = new (_nsisScriptGenerator().NsisScriptGenerator)();
for (const item of fileAssociations) {
for (const ext of (0, _builderUtil().asArray)(item.ext)) {
unregisterFileAssociationsScript.insertMacro("APP_UNASSOCIATE", `"${(0, _platformPackager().normalizeExt)(ext)}" "${item.name || ext}"`);
}
}
scriptGenerator.macro("unregisterFileAssociations", unregisterFileAssociationsScript);
}
}
return scriptGenerator.build() + originalScript;
}
}
exports.NsisTarget = NsisTarget;
async function generateForPreCompressed(preCompressedFileExtensions, dir, arch, scriptGenerator) {
const resourcesDir = path.join(dir, "resources");
const dirInfo = await (0, _fs().statOrNull)(resourcesDir);
if (dirInfo == null || !dirInfo.isDirectory()) {
return;
}
const nodeModules = `${path.sep}node_modules`;
const preCompressedAssets = await (0, _fs().walk)(resourcesDir, (file, stat) => {
if (stat.isDirectory()) {
return !file.endsWith(nodeModules);
} else {
return preCompressedFileExtensions.some(it => file.endsWith(it));
}
});
if (preCompressedAssets.length !== 0) {
const macro = new (_nsisScriptGenerator().NsisScriptGenerator)();
for (const file of preCompressedAssets) {
macro.file(`$INSTDIR\\${path.relative(dir, file).replace(/\//g, "\\")}`, file);
}
scriptGenerator.macro(`customFiles_${_builderUtil().Arch[arch]}`, macro);
}
}
async function ensureNotBusy(outFile) {
function isBusy(wasBusyBefore) {
return new Promise((resolve, reject) => {
fs.open(outFile, "r+", (error, fd) => {
try {
if (error != null && error.code === "EBUSY") {
if (!wasBusyBefore) {
_builderUtil().log.info({}, "output file is locked for writing (maybe by virus scanner) => waiting for unlock...");
}
resolve(false);
} else if (fd == null) {
resolve(true);
} else {
fs.close(fd, () => resolve(true));
}
} catch (error) {
reject(error);
}
});
}).then(result => {
if (result) {
return true;
} else {
return new Promise(resolve => setTimeout(resolve, 2000)).then(() => isBusy(true));
}
});
}
await isBusy(false);
}
async function createPackageFileInfo(file) {
return {
path: file,
size: (await (0, _fsExtra().stat)(file)).size,
sha512: await (0, _hash().hashFile)(file)
};
}
// __ts-babel@6.0.4
//# sourceMappingURL=NsisTarget.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,11 @@
import { WinPackager } from "../../winPackager";
import { NsisTarget } from "./NsisTarget";
import { AppPackageHelper } from "./nsisUtil";
/** @private */
export declare class WebInstallerTarget extends NsisTarget {
constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper);
get isWebInstaller(): boolean;
protected configureDefines(oneClick: boolean, defines: any): Promise<any>;
protected get installerFilenamePattern(): string;
protected generateGitHubInstallerName(): string;
}

View File

@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.WebInstallerTarget = void 0;
function _PublishManager() {
const data = require("../../publish/PublishManager");
_PublishManager = function () {
return data;
};
return data;
}
function _NsisTarget() {
const data = require("./NsisTarget");
_NsisTarget = function () {
return data;
};
return data;
}
/** @private */
class WebInstallerTarget extends _NsisTarget().NsisTarget {
constructor(packager, outDir, targetName, packageHelper) {
super(packager, outDir, targetName, packageHelper);
}
get isWebInstaller() {
return true;
}
async configureDefines(oneClick, defines) {
//noinspection ES6MissingAwait
await _NsisTarget().NsisTarget.prototype.configureDefines.call(this, oneClick, defines);
const packager = this.packager;
const options = this.options;
let appPackageUrl = options.appPackageUrl;
if (appPackageUrl == null) {
const publishConfigs = await (0, _PublishManager().getPublishConfigsForUpdateInfo)(packager, await (0, _PublishManager().getPublishConfigs)(packager, packager.info.config, null, false), null);
if (publishConfigs == null || publishConfigs.length === 0) {
throw new Error("Cannot compute app package download URL");
}
appPackageUrl = (0, _PublishManager().computeDownloadUrl)(publishConfigs[0], null, packager);
defines.APP_PACKAGE_URL_IS_INCOMLETE = null;
}
defines.APP_PACKAGE_URL = appPackageUrl;
}
get installerFilenamePattern() {
// tslint:disable:no-invalid-template-strings
return "${productName} Web Setup ${version}.${ext}";
}
generateGitHubInstallerName() {
const appInfo = this.packager.appInfo;
const classifier = appInfo.name.toLowerCase() === appInfo.name ? "web-setup" : "WebSetup";
return `${appInfo.name}-${classifier}-${appInfo.version}.exe`;
}
} exports.WebInstallerTarget = WebInstallerTarget;
// __ts-babel@6.0.4
//# sourceMappingURL=WebInstallerTarget.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/targets/nsis/WebInstallerTarget.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AACM,MAAO,kBAAP,SAAkC,wBAAlC,CAA4C;AAChD,EAAA,WAAA,CAAY,QAAZ,EAAmC,MAAnC,EAAmD,UAAnD,EAAuE,aAAvE,EAAsG;AACpG,UAAM,QAAN,EAAgB,MAAhB,EAAwB,UAAxB,EAAoC,aAApC;AACD;;AAED,MAAI,cAAJ,GAAkB;AAChB,WAAO,IAAP;AACD;;AAES,QAAM,gBAAN,CAAuB,QAAvB,EAA0C,OAA1C,EAAsD;AAC9D;AACA,UAAO,yBAAW,SAAX,CAA4C,gBAA5C,CAA6D,IAA7D,CAAkE,IAAlE,EAAwE,QAAxE,EAAkF,OAAlF,CAAP;AAEA,UAAM,QAAQ,GAAG,KAAK,QAAtB;AACA,UAAM,OAAO,GAAG,KAAK,OAArB;AAEA,QAAI,aAAa,GAAG,OAAO,CAAC,aAA5B;;AACA,QAAI,aAAa,IAAI,IAArB,EAA2B;AACzB,YAAM,cAAc,GAAG,MAAM,sDAA+B,QAA/B,EAAyC,MAAM,yCAAkB,QAAlB,EAA4B,QAAQ,CAAC,IAAT,CAAc,MAA1C,EAAkD,IAAlD,EAAwD,KAAxD,CAA/C,EAA+G,IAA/G,CAA7B;;AACA,UAAI,cAAc,IAAI,IAAlB,IAA0B,cAAc,CAAC,MAAf,KAA0B,CAAxD,EAA2D;AACzD,cAAM,IAAI,KAAJ,CAAU,yCAAV,CAAN;AACD;;AAED,MAAA,aAAa,GAAG,0CAAmB,cAAc,CAAC,CAAD,CAAjC,EAAsC,IAAtC,EAA4C,QAA5C,CAAhB;AAEA,MAAA,OAAO,CAAC,4BAAR,GAAuC,IAAvC;AACD;;AAED,IAAA,OAAO,CAAC,eAAR,GAA0B,aAA1B;AACD;;AAED,MAAc,wBAAd,GAAsC;AACpC;AACA,WAAO,4CAAP;AACD;;AAES,EAAA,2BAA2B,GAAA;AACnC,UAAM,OAAO,GAAG,KAAK,QAAL,CAAc,OAA9B;AACA,UAAM,UAAU,GAAG,OAAO,CAAC,IAAR,CAAa,WAAb,OAA+B,OAAO,CAAC,IAAvC,GAA8C,WAA9C,GAA4D,UAA/E;AACA,WAAO,GAAG,OAAO,CAAC,IAAI,IAAI,UAAU,IAAI,OAAO,CAAC,OAAO,MAAvD;AACD;;AAxC+C,C","sourcesContent":["import { computeDownloadUrl, getPublishConfigs, getPublishConfigsForUpdateInfo } from \"../../publish/PublishManager\"\nimport { WinPackager } from \"../../winPackager\"\nimport { NsisWebOptions } from \"./nsisOptions\"\nimport { NsisTarget } from \"./NsisTarget\"\nimport { AppPackageHelper } from \"./nsisUtil\"\n\n/** @private */\nexport class WebInstallerTarget extends NsisTarget {\n constructor(packager: WinPackager, outDir: string, targetName: string, packageHelper: AppPackageHelper) {\n super(packager, outDir, targetName, packageHelper)\n }\n\n get isWebInstaller(): boolean {\n return true\n }\n\n protected async configureDefines(oneClick: boolean, defines: any): Promise<any> {\n //noinspection ES6MissingAwait\n await (NsisTarget.prototype as WebInstallerTarget).configureDefines.call(this, oneClick, defines)\n\n const packager = this.packager\n const options = this.options as NsisWebOptions\n\n let appPackageUrl = options.appPackageUrl\n if (appPackageUrl == null) {\n const publishConfigs = await getPublishConfigsForUpdateInfo(packager, await getPublishConfigs(packager, packager.info.config, null, false), null)\n if (publishConfigs == null || publishConfigs.length === 0) {\n throw new Error(\"Cannot compute app package download URL\")\n }\n\n appPackageUrl = computeDownloadUrl(publishConfigs[0], null, packager)\n\n defines.APP_PACKAGE_URL_IS_INCOMLETE = null\n }\n\n defines.APP_PACKAGE_URL = appPackageUrl\n }\n\n protected get installerFilenamePattern(): string {\n // tslint:disable:no-invalid-template-strings\n return \"${productName} Web Setup ${version}.${ext}\"\n }\n\n protected generateGitHubInstallerName(): string {\n const appInfo = this.packager.appInfo\n const classifier = appInfo.name.toLowerCase() === appInfo.name ? \"web-setup\" : \"WebSetup\"\n return `${appInfo.name}-${classifier}-${appInfo.version}.exe`\n }\n}"],"sourceRoot":""}

View File

@ -0,0 +1,10 @@
import { PlatformPackager } from "../../platformPackager";
import { NsisOptions } from "./nsisOptions";
import { NsisScriptGenerator } from "./nsisScriptGenerator";
export declare class LangConfigurator {
readonly isMultiLang: boolean;
readonly langs: Array<string>;
constructor(options: NsisOptions);
}
export declare function createAddLangsMacro(scriptGenerator: NsisScriptGenerator, langConfigurator: LangConfigurator): void;
export declare function addCustomMessageFileInclude(input: string, packager: PlatformPackager<any>, scriptGenerator: NsisScriptGenerator, langConfigurator: LangConfigurator): Promise<void>;

View File

@ -0,0 +1,176 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createAddLangsMacro = createAddLangsMacro;
exports.addCustomMessageFileInclude = addCustomMessageFileInclude;
exports.LangConfigurator = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _langs() {
const data = require("../../util/langs");
_langs = function () {
return data;
};
return data;
}
var _debug2 = _interopRequireDefault(require("debug"));
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _jsYaml() {
const data = require("js-yaml");
_jsYaml = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _nsisUtil() {
const data = require("./nsisUtil");
_nsisUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const debug = (0, _debug2.default)("electron-builder:nsis");
class LangConfigurator {
constructor(options) {
const rawList = options.installerLanguages;
if (options.unicode === false || rawList === null || Array.isArray(rawList) && rawList.length === 0) {
this.isMultiLang = false;
} else {
this.isMultiLang = options.multiLanguageInstaller !== false;
}
if (this.isMultiLang) {
this.langs = rawList == null ? _langs().bundledLanguages.slice() : (0, _builderUtil().asArray)(rawList).map(it => (0, _langs().toLangWithRegion)(it.replace("-", "_")));
} else {
this.langs = ["en_US"];
}
}
}
exports.LangConfigurator = LangConfigurator;
function createAddLangsMacro(scriptGenerator, langConfigurator) {
const result = [];
for (const langWithRegion of langConfigurator.langs) {
let name;
if (langWithRegion === "zh_CN") {
name = "SimpChinese";
} else if (langWithRegion === "zh_TW") {
name = "TradChinese";
} else if (langWithRegion === "nb_NO") {
name = "Norwegian";
} else if (langWithRegion === "pt_BR") {
name = "PortugueseBR";
} else {
const lang = langWithRegion.substring(0, langWithRegion.indexOf("_"));
name = _langs().langIdToName[lang];
if (name == null) {
throw new Error(`Language name is unknown for ${lang}`);
}
if (name === "Spanish") {
name = "SpanishInternational";
}
}
result.push(`!insertmacro MUI_LANGUAGE "${name}"`);
}
scriptGenerator.macro("addLangs", result);
}
async function writeCustomLangFile(data, packager) {
const file = await packager.getTempFile("messages.nsh");
await (0, _fsExtra().outputFile)(file, data);
return file;
}
async function addCustomMessageFileInclude(input, packager, scriptGenerator, langConfigurator) {
const data = (0, _jsYaml().safeLoad)(await (0, _fsExtra().readFile)(path.join(_nsisUtil().nsisTemplatesDir, input), "utf-8"));
const instructions = computeCustomMessageTranslations(data, langConfigurator).join("\n");
debug(instructions);
scriptGenerator.include(await writeCustomLangFile(instructions, packager));
}
function computeCustomMessageTranslations(messages, langConfigurator) {
const result = [];
const includedLangs = new Set(langConfigurator.langs);
for (const messageId of Object.keys(messages)) {
const langToTranslations = messages[messageId];
const unspecifiedLangs = new Set(langConfigurator.langs);
for (const lang of Object.keys(langToTranslations)) {
const langWithRegion = (0, _langs().toLangWithRegion)(lang);
if (!includedLangs.has(langWithRegion)) {
continue;
}
const value = langToTranslations[lang];
if (value == null) {
throw new Error(`${messageId} not specified for ${lang}`);
}
result.push(`LangString ${messageId} ${_langs().lcid[langWithRegion]} "${value.replace(/\n/g, "$\\r$\\n")}"`);
unspecifiedLangs.delete(langWithRegion);
}
if (langConfigurator.isMultiLang) {
const defaultTranslation = langToTranslations.en.replace(/\n/g, "$\\r$\\n");
for (const langWithRegion of unspecifiedLangs) {
result.push(`LangString ${messageId} ${_langs().lcid[langWithRegion]} "${defaultTranslation}"`);
}
}
}
return result;
}
// __ts-babel@6.0.4
//# sourceMappingURL=nsisLang.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,4 @@
import { WinPackager } from "../../winPackager";
import { NsisOptions } from "./nsisOptions";
import { NsisScriptGenerator } from "./nsisScriptGenerator";
export declare function computeLicensePage(packager: WinPackager, options: NsisOptions, scriptGenerator: NsisScriptGenerator, languages: Array<string>): Promise<void>;

View File

@ -0,0 +1,93 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.computeLicensePage = computeLicensePage;
function _langs() {
const data = require("../../util/langs");
_langs = function () {
return data;
};
return data;
}
function _license() {
const data = require("../../util/license");
_license = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _nsisUtil() {
const data = require("./nsisUtil");
_nsisUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
async function computeLicensePage(packager, options, scriptGenerator, languages) {
const license = await (0, _license().getNotLocalizedLicenseFile)(options.license, packager);
if (license != null) {
let licensePage;
if (license.endsWith(".html")) {
licensePage = ["!define MUI_PAGE_CUSTOMFUNCTION_SHOW LicenseShow", "Function LicenseShow", " FindWindow $R0 `#32770` `` $HWNDPARENT", " GetDlgItem $R0 $R0 1000", "EmbedHTML::Load /replace $R0 file://$PLUGINSDIR\\license.html", "FunctionEnd", `!insertmacro MUI_PAGE_LICENSE "${path.join(_nsisUtil().nsisTemplatesDir, "empty-license.txt")}"`];
} else {
licensePage = [`!insertmacro MUI_PAGE_LICENSE "${license}"`];
}
scriptGenerator.macro("licensePage", licensePage);
if (license.endsWith(".html")) {
scriptGenerator.macro("addLicenseFiles", [`File /oname=$PLUGINSDIR\\license.html "${license}"`]);
}
return;
}
const licenseFiles = await (0, _license().getLicenseFiles)(packager);
if (licenseFiles.length === 0) {
return;
}
const licensePage = [];
const unspecifiedLangs = new Set(languages);
let defaultFile = null;
for (const item of licenseFiles) {
unspecifiedLangs.delete(item.langWithRegion);
if (defaultFile == null) {
defaultFile = item.file;
}
licensePage.push(`LicenseLangString MUILicense ${_langs().lcid[item.langWithRegion] || item.lang} "${item.file}"`);
}
for (const l of unspecifiedLangs) {
licensePage.push(`LicenseLangString MUILicense ${_langs().lcid[l]} "${defaultFile}"`);
}
licensePage.push('!insertmacro MUI_PAGE_LICENSE "$(MUILicense)"');
scriptGenerator.macro("licensePage", licensePage);
}
// __ts-babel@6.0.4
//# sourceMappingURL=nsisLicense.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/targets/nsis/nsisLicense.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AAIA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAEO,eAAe,kBAAf,CAAkC,QAAlC,EAAyD,OAAzD,EAA+E,eAA/E,EAAqH,SAArH,EAA6I;AAClJ,QAAM,OAAO,GAAG,MAAM,2CAA2B,OAAO,CAAC,OAAnC,EAA4C,QAA5C,CAAtB;;AACA,MAAI,OAAO,IAAI,IAAf,EAAqB;AACnB,QAAI,WAAJ;;AACA,QAAI,OAAO,CAAC,QAAR,CAAiB,OAAjB,CAAJ,EAA+B;AAC7B,MAAA,WAAW,GAAG,CACZ,kDADY,EAEZ,sBAFY,EAGZ,0CAHY,EAIZ,2BAJY,EAKZ,+DALY,EAMZ,aANY,EAQZ,kCAAkC,IAAI,CAAC,IAAL,CAAU,4BAAV,EAA4B,mBAA5B,CAAgD,GARtE,CAAd;AAUD,KAXD,MAYK;AACH,MAAA,WAAW,GAAG,CAAC,kCAAkC,OAAO,GAA1C,CAAd;AACD;;AAED,IAAA,eAAe,CAAC,KAAhB,CAAsB,aAAtB,EAAqC,WAArC;;AACA,QAAI,OAAO,CAAC,QAAR,CAAiB,OAAjB,CAAJ,EAA+B;AAC7B,MAAA,eAAe,CAAC,KAAhB,CAAsB,iBAAtB,EAAyC,CAAC,0CAA0C,OAAO,GAAlD,CAAzC;AACD;;AACD;AACD;;AAED,QAAM,YAAY,GAAG,MAAM,gCAAgB,QAAhB,CAA3B;;AACA,MAAI,YAAY,CAAC,MAAb,KAAwB,CAA5B,EAA+B;AAC7B;AACD;;AAED,QAAM,WAAW,GAAkB,EAAnC;AACA,QAAM,gBAAgB,GAAG,IAAI,GAAJ,CAAQ,SAAR,CAAzB;AAEA,MAAI,WAAW,GAAkB,IAAjC;;AACA,OAAK,MAAM,IAAX,IAAmB,YAAnB,EAAiC;AAC/B,IAAA,gBAAgB,CAAC,MAAjB,CAAwB,IAAI,CAAC,cAA7B;;AACA,QAAI,WAAW,IAAI,IAAnB,EAAyB;AACvB,MAAA,WAAW,GAAG,IAAI,CAAC,IAAnB;AACD;;AACD,IAAA,WAAW,CAAC,IAAZ,CAAiB,gCAAgC,cAAK,IAAI,CAAC,cAAV,KAA6B,IAAI,CAAC,IAAI,KAAK,IAAI,CAAC,IAAI,GAArG;AACD;;AAED,OAAK,MAAM,CAAX,IAAgB,gBAAhB,EAAkC;AAChC,IAAA,WAAW,CAAC,IAAZ,CAAiB,gCAAgC,cAAK,CAAL,CAAO,KAAK,WAAW,GAAxE;AACD;;AAED,EAAA,WAAW,CAAC,IAAZ,CAAiB,+CAAjB;AACA,EAAA,eAAe,CAAC,KAAhB,CAAsB,aAAtB,EAAqC,WAArC;AACD,C","sourcesContent":["import { lcid } from \"../../util/langs\"\nimport { getLicenseFiles, getNotLocalizedLicenseFile } from \"../../util/license\"\nimport * as path from \"path\"\nimport { WinPackager } from \"../../winPackager\"\nimport { NsisOptions } from \"./nsisOptions\"\nimport { NsisScriptGenerator } from \"./nsisScriptGenerator\"\nimport { nsisTemplatesDir } from \"./nsisUtil\"\n\nexport async function computeLicensePage(packager: WinPackager, options: NsisOptions, scriptGenerator: NsisScriptGenerator, languages: Array<string>): Promise<void> {\n const license = await getNotLocalizedLicenseFile(options.license, packager)\n if (license != null) {\n let licensePage: Array<string>\n if (license.endsWith(\".html\")) {\n licensePage = [\n \"!define MUI_PAGE_CUSTOMFUNCTION_SHOW LicenseShow\",\n \"Function LicenseShow\",\n \" FindWindow $R0 `#32770` `` $HWNDPARENT\",\n \" GetDlgItem $R0 $R0 1000\",\n \"EmbedHTML::Load /replace $R0 file://$PLUGINSDIR\\\\license.html\",\n \"FunctionEnd\",\n\n `!insertmacro MUI_PAGE_LICENSE \"${path.join(nsisTemplatesDir, \"empty-license.txt\")}\"`,\n ]\n }\n else {\n licensePage = [`!insertmacro MUI_PAGE_LICENSE \"${license}\"`]\n }\n\n scriptGenerator.macro(\"licensePage\", licensePage)\n if (license.endsWith(\".html\")) {\n scriptGenerator.macro(\"addLicenseFiles\", [`File /oname=$PLUGINSDIR\\\\license.html \"${license}\"`])\n }\n return\n }\n\n const licenseFiles = await getLicenseFiles(packager)\n if (licenseFiles.length === 0) {\n return\n }\n\n const licensePage: Array<string> = []\n const unspecifiedLangs = new Set(languages)\n\n let defaultFile: string | null = null\n for (const item of licenseFiles) {\n unspecifiedLangs.delete(item.langWithRegion)\n if (defaultFile == null) {\n defaultFile = item.file\n }\n licensePage.push(`LicenseLangString MUILicense ${lcid[item.langWithRegion] || item.lang} \"${item.file}\"`)\n }\n\n for (const l of unspecifiedLangs) {\n licensePage.push(`LicenseLangString MUILicense ${lcid[l]} \"${defaultFile}\"`)\n }\n\n licensePage.push('!insertmacro MUI_PAGE_LICENSE \"$(MUILicense)\"')\n scriptGenerator.macro(\"licensePage\", licensePage)\n}\n"],"sourceRoot":""}

View File

@ -0,0 +1,181 @@
import { TargetSpecificOptions } from "../../core";
import { CommonWindowsInstallerConfiguration } from "../..";
export interface CommonNsisOptions {
/**
* Whether to create [Unicode installer](http://nsis.sourceforge.net/Docs/Chapter1.html#intro-unicode).
* @default true
*/
readonly unicode?: boolean;
/**
* See [GUID vs Application Name](../configuration/nsis#guid-vs-application-name).
*/
readonly guid?: string | null;
/**
* If `warningsAsErrors` is `true` (default): NSIS will treat warnings as errors. If `warningsAsErrors` is `false`: NSIS will allow warnings.
* @default true
*/
readonly warningsAsErrors?: boolean;
/**
* @private
* @default false
*/
readonly useZip?: boolean;
}
export interface NsisOptions extends CommonNsisOptions, CommonWindowsInstallerConfiguration, TargetSpecificOptions {
/**
* Whether to create one-click installer or assisted.
* @default true
*/
readonly oneClick?: boolean;
/**
* Whether to show install mode installer page (choice per-machine or per-user) for assisted installer. Or whether installation always per all users (per-machine).
*
* If `oneClick` is `true` (default): Whether to install per all users (per-machine).
*
* If `oneClick` is `false` and `perMachine` is `true`: no install mode installer page, always install per-machine.
*
* If `oneClick` is `false` and `perMachine` is `false` (default): install mode installer page.
* @default false
*/
readonly perMachine?: boolean;
/**
* *assisted installer only.* Allow requesting for elevation. If false, user will have to restart installer with elevated permissions.
* @default true
*/
readonly allowElevation?: boolean;
/**
* *assisted installer only.* Whether to allow user to change installation directory.
* @default false
*/
readonly allowToChangeInstallationDirectory?: boolean;
/**
* The path to installer icon, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerIcon.ico` or application icon.
*/
readonly installerIcon?: string | null;
/**
* The path to uninstaller icon, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/uninstallerIcon.ico` or application icon.
*/
readonly uninstallerIcon?: string | null;
/**
* *assisted installer only.* `MUI_HEADERIMAGE`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* @default build/installerHeader.bmp
*/
readonly installerHeader?: string | null;
/**
* *one-click installer only.* The path to header icon (above the progress bar), relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerHeaderIcon.ico` or application icon.
*/
readonly installerHeaderIcon?: string | null;
/**
* *assisted installer only.* `MUI_WELCOMEFINISHPAGE_BITMAP`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `build/installerSidebar.bmp` or `${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp`. Image size 164 × 314 pixels.
*/
readonly installerSidebar?: string | null;
/**
* *assisted installer only.* `MUI_UNWELCOMEFINISHPAGE_BITMAP`, relative to the [build resources](/configuration/configuration#MetadataDirectories-buildResources) or to the project directory.
* Defaults to `installerSidebar` option or `build/uninstallerSidebar.bmp` or `build/installerSidebar.bmp` or `${NSISDIR}\\Contrib\\Graphics\\Wizard\\nsis3-metro.bmp`
*/
readonly uninstallerSidebar?: string | null;
/**
* The uninstaller display name in the control panel.
* @default ${productName} ${version}
*/
readonly uninstallDisplayName?: string;
/**
* The path to NSIS include script to customize installer. Defaults to `build/installer.nsh`. See [Custom NSIS script](#custom-nsis-script).
*/
readonly include?: string | null;
/**
* The path to NSIS script to customize installer. Defaults to `build/installer.nsi`. See [Custom NSIS script](#custom-nsis-script).
*/
readonly script?: string | null;
/**
* The path to EULA license file. Defaults to `license.txt` or `eula.txt` (or uppercase variants). In addition to `txt, `rtf` and `html` supported (don't forget to use `target="_blank"` for links).
*
* Multiple license files in different languages are supported — use lang postfix (e.g. `_de`, `_ru`)). For example, create files `license_de.txt` and `license_en.txt` in the build resources.
* If OS language is german, `license_de.txt` will be displayed. See map of [language code to name](https://github.com/meikidd/iso-639-1/blob/master/src/data.js).
*
* Appropriate license file will be selected by user OS language.
*/
readonly license?: string | null;
/**
* The [artifact file name template](/configuration/configuration#artifact-file-name-template). Defaults to `${productName} Setup ${version}.${ext}`.
*/
readonly artifactName?: string | null;
/**
* *one-click installer only.* Whether to delete app data on uninstall.
* @default false
*/
readonly deleteAppDataOnUninstall?: boolean;
/**
* @private
*/
differentialPackage?: boolean;
/**
* Whether to display a language selection dialog. Not recommended (by default will be detected using OS language).
* @default false
*/
readonly displayLanguageSelector?: boolean;
/**
* The installer languages (e.g. `en_US`, `de_DE`). Change only if you understand what do you do and for what.
*/
readonly installerLanguages?: Array<string> | string | null;
/**
* [LCID Dec](https://msdn.microsoft.com/en-au/goglobal/bb964664.aspx), defaults to `1033`(`English - United States`).
*/
readonly language?: string | null;
/**
* Whether to create multi-language installer. Defaults to `unicode` option value.
*/
readonly multiLanguageInstaller?: boolean;
/**
* Whether to pack the elevate executable (required for electron-updater if per-machine installer used or can be used in the future). Ignored if `perMachine` is set to `true`.
* @default true
*/
readonly packElevateHelper?: boolean;
/**
* The file extension of files that will be not compressed. Applicable only for `extraResources` and `extraFiles` files.
* @default [".avi", ".mov", ".m4v", ".mp4", ".m4p", ".qt", ".mkv", ".webm", ".vmdk"]
*/
readonly preCompressedFileExtensions?: Array<string> | string | null;
}
/**
* Portable options.
*/
export interface PortableOptions extends TargetSpecificOptions, CommonNsisOptions {
/**
* The [requested execution level](http://nsis.sourceforge.net/Reference/RequestExecutionLevel) for Windows.
* @default user
*/
readonly requestExecutionLevel?: "user" | "highest" | "admin";
/**
* The unpack directory name in [TEMP](https://www.askvg.com/where-does-windows-store-temporary-files-and-how-to-change-temp-folder-location/) directory.
*
* Defaults to [uuid](https://github.com/segmentio/ksuid) of build (changed on each build of portable executable).
*/
readonly unpackDirName?: string;
/**
* The image to show while the portable executable is extracting. This image must be a bitmap (`.bmp`) image.
*/
readonly splashImage?: string | null;
}
/**
* Web Installer options.
*/
export interface NsisWebOptions extends NsisOptions {
/**
* The application package download URL. Optional — by default computed using publish configuration.
*
* URL like `https://example.com/download/latest` allows web installer to be version independent (installer will download latest application package).
* Please note — it is [full URL](https://github.com/electron-userland/electron-builder/issues/1810#issuecomment-317650878).
*
* Custom `X-Arch` http header is set to `32` or `64`.
*/
readonly appPackageUrl?: string | null;
/**
* The [artifact file name template](/configuration/configuration#artifact-file-name-template). Defaults to `${productName} Web Setup ${version}.${ext}`.
*/
readonly artifactName?: string | null;
}

View File

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
// __ts-babel@6.0.4
//# sourceMappingURL=nsisOptions.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":[],"names":[],"mappings":"","sourceRoot":""}

View File

@ -0,0 +1,11 @@
export declare class NsisScriptGenerator {
private readonly lines;
addIncludeDir(file: string): void;
addPluginDir(pluginArch: string, dir: string): void;
include(file: string): void;
macro(name: string, lines: Array<string> | NsisScriptGenerator): void;
file(outputName: string | null, file: string): void;
insertMacro(name: string, parameters: string): void;
flags(flags: Array<string>): void;
build(): string;
}

View File

@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NsisScriptGenerator = void 0;
class NsisScriptGenerator {
constructor() {
this.lines = [];
}
addIncludeDir(file) {
this.lines.push(`!addincludedir "${file}"`);
}
addPluginDir(pluginArch, dir) {
this.lines.push(`!addplugindir /${pluginArch} "${dir}"`);
}
include(file) {
this.lines.push(`!include "${file}"`);
}
macro(name, lines) {
this.lines.push(`!macro ${name}`, ` ${(Array.isArray(lines) ? lines : lines.lines).join("\n ")}`, `!macroend\n`);
}
file(outputName, file) {
this.lines.push(`File${outputName == null ? "" : ` "/oname=${outputName}"`} "${file}"`);
}
insertMacro(name, parameters) {
this.lines.push(`!insertmacro ${name} ${parameters}`);
} // without -- !!!
flags(flags) {
for (const flagName of flags) {
const variableName = getVarNameForFlag(flagName).replace(/[-]+(\w|$)/g, (m, p1) => p1.toUpperCase());
this.lines.push(`!macro _${variableName} _a _b _t _f
$\{StdUtils.TestParameter} $R9 "${flagName}"
StrCmp "$R9" "true" \`$\{_t}\` \`$\{_f}\`
!macroend
!define ${variableName} \`"" ${variableName} ""\`
`);
}
}
build() {
return this.lines.join("\n") + "\n";
}
}
exports.NsisScriptGenerator = NsisScriptGenerator;
function getVarNameForFlag(flagName) {
if (flagName === "allusers") {
return "isForAllUsers";
}
if (flagName === "currentuser") {
return "isForCurrentUser";
}
return "is" + flagName[0].toUpperCase() + flagName.substring(1);
}
// __ts-babel@6.0.4
//# sourceMappingURL=nsisScriptGenerator.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../../src/targets/nsis/nsisScriptGenerator.ts"],"names":[],"mappings":";;;;;;;AAAM,MAAO,mBAAP,CAA0B;AAAhC,EAAA,WAAA,GAAA;AACmB,SAAA,KAAA,GAAuB,EAAvB;AA+ClB;;AA7CC,EAAA,aAAa,CAAC,IAAD,EAAa;AACxB,SAAK,KAAL,CAAW,IAAX,CAAgB,mBAAmB,IAAI,GAAvC;AACD;;AAED,EAAA,YAAY,CAAC,UAAD,EAAqB,GAArB,EAAgC;AAC1C,SAAK,KAAL,CAAW,IAAX,CAAgB,kBAAkB,UAAU,KAAK,GAAG,GAApD;AACD;;AAED,EAAA,OAAO,CAAC,IAAD,EAAa;AAClB,SAAK,KAAL,CAAW,IAAX,CAAgB,aAAa,IAAI,GAAjC;AACD;;AAED,EAAA,KAAK,CAAC,IAAD,EAAe,KAAf,EAAyD;AAC5D,SAAK,KAAL,CAAW,IAAX,CACE,UAAU,IAAI,EADhB,EAEE,KAAK,CAAC,KAAK,CAAC,OAAN,CAAc,KAAd,IAAuB,KAAvB,GAAgC,KAA6B,CAAC,KAA/D,EAAsE,IAAtE,CAA2E,MAA3E,CAAkF,EAFzF,EAGE,aAHF;AAKD;;AAED,EAAA,IAAI,CAAC,UAAD,EAA4B,IAA5B,EAAwC;AAC1C,SAAK,KAAL,CAAW,IAAX,CAAgB,OAAO,UAAU,IAAI,IAAd,GAAqB,EAArB,GAA0B,YAAY,UAAU,GAAG,KAAK,IAAI,GAAnF;AACD;;AAED,EAAA,WAAW,CAAC,IAAD,EAAe,UAAf,EAAiC;AAC1C,SAAK,KAAL,CAAW,IAAX,CAAgB,gBAAgB,IAAI,IAAI,UAAU,EAAlD;AACD,GA7B6B,CA+B9B;;;AACA,EAAA,KAAK,CAAC,KAAD,EAAqB;AACxB,SAAK,MAAM,QAAX,IAAuB,KAAvB,EAA8B;AAC5B,YAAM,YAAY,GAAG,iBAAiB,CAAC,QAAD,CAAjB,CAClB,OADkB,CACV,aADU,EACK,CAAC,CAAD,EAAI,EAAJ,KAAW,EAAE,CAAC,WAAH,EADhB,CAArB;AAEA,WAAK,KAAL,CAAW,IAAX,CAAgB,WAAW,YAAY;oCACT,QAAQ;;;UAGlC,YAAY,SAAS,YAAY;CAJrC;AAMD;AACF;;AAED,EAAA,KAAK,GAAA;AACH,WAAO,KAAK,KAAL,CAAW,IAAX,CAAgB,IAAhB,IAAwB,IAA/B;AACD;;AA/C6B;;;;AAkDhC,SAAS,iBAAT,CAA2B,QAA3B,EAA2C;AACzC,MAAI,QAAQ,KAAK,UAAjB,EAA6B;AAC3B,WAAO,eAAP;AACD;;AACD,MAAI,QAAQ,KAAK,aAAjB,EAAgC;AAC9B,WAAO,kBAAP;AACD;;AACD,SAAO,OAAO,QAAQ,CAAC,CAAD,CAAR,CAAY,WAAZ,EAAP,GAAmC,QAAQ,CAAC,SAAT,CAAmB,CAAnB,CAA1C;AACD,C","sourcesContent":["export class NsisScriptGenerator {\n private readonly lines: Array<string> = []\n\n addIncludeDir(file: string) {\n this.lines.push(`!addincludedir \"${file}\"`)\n }\n\n addPluginDir(pluginArch: string, dir: string) {\n this.lines.push(`!addplugindir /${pluginArch} \"${dir}\"`)\n }\n\n include(file: string) {\n this.lines.push(`!include \"${file}\"`)\n }\n\n macro(name: string, lines: Array<string> | NsisScriptGenerator) {\n this.lines.push(\n `!macro ${name}`,\n ` ${(Array.isArray(lines) ? lines : (lines as NsisScriptGenerator).lines).join(\"\\n \")}`,\n `!macroend\\n`\n )\n }\n\n file(outputName: string | null, file: string) {\n this.lines.push(`File${outputName == null ? \"\" : ` \"/oname=${outputName}\"`} \"${file}\"`)\n }\n\n insertMacro(name: string, parameters: string) {\n this.lines.push(`!insertmacro ${name} ${parameters}`)\n }\n\n // without -- !!!\n flags(flags: Array<string>) {\n for (const flagName of flags) {\n const variableName = getVarNameForFlag(flagName)\n .replace(/[-]+(\\w|$)/g, (m, p1) => p1.toUpperCase())\n this.lines.push(`!macro _${variableName} _a _b _t _f\n $\\{StdUtils.TestParameter} $R9 \"${flagName}\"\n StrCmp \"$R9\" \"true\" \\`$\\{_t}\\` \\`$\\{_f}\\`\n!macroend\n!define ${variableName} \\`\"\" ${variableName} \"\"\\`\n`)\n }\n }\n\n build() {\n return this.lines.join(\"\\n\") + \"\\n\"\n }\n}\n\nfunction getVarNameForFlag(flagName: string): string {\n if (flagName === \"allusers\") {\n return \"isForAllUsers\"\n }\n if (flagName === \"currentuser\") {\n return \"isForCurrentUser\"\n }\n return \"is\" + flagName[0].toUpperCase() + flagName.substring(1)\n}"],"sourceRoot":""}

View File

@ -0,0 +1,22 @@
import { Arch } from "builder-util";
import { PackageFileInfo } from "builder-util-runtime";
import { NsisTarget } from "./NsisTarget";
export declare const nsisTemplatesDir: string;
export declare const NSIS_PATH: () => Promise<string>;
export declare class AppPackageHelper {
private readonly elevateHelper;
private readonly archToFileInfo;
private readonly infoToIsDelete;
/** @private */
refCount: number;
constructor(elevateHelper: CopyElevateHelper);
packArch(arch: Arch, target: NsisTarget): Promise<PackageFileInfo>;
finishBuild(): Promise<any>;
}
export declare class CopyElevateHelper {
private readonly copied;
copy(appOutDir: string, target: NsisTarget): Promise<any>;
}
export declare class UninstallerReader {
static exec(installerPath: string, uninstallerPath: string): void;
}

View File

@ -0,0 +1,375 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UninstallerReader = exports.CopyElevateHelper = exports.AppPackageHelper = exports.NSIS_PATH = exports.nsisTemplatesDir = void 0;
function _bluebirdLst() {
const data = _interopRequireDefault(require("bluebird-lst"));
_bluebirdLst = function () {
return data;
};
return data;
}
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _binDownload() {
const data = require("../../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _pathManager() {
const data = require("../../util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
var _fs2 = _interopRequireDefault(require("fs"));
function _zlib() {
const data = _interopRequireDefault(require("zlib"));
_zlib = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const nsisTemplatesDir = (0, _pathManager().getTemplatePath)("nsis");
exports.nsisTemplatesDir = nsisTemplatesDir;
const NSIS_PATH = () => {
const custom = process.env.ELECTRON_BUILDER_NSIS_DIR;
if (custom != null && custom.length > 0) {
return Promise.resolve(custom.trim());
} // noinspection SpellCheckingInspection
return (0, _binDownload().getBinFromUrl)("nsis", "3.0.4.1", "VKMiizYdmNdJOWpRGz4trl4lD++BvYP2irAXpMilheUP0pc93iKlWAoP843Vlraj8YG19CVn0j+dCo/hURz9+Q==");
};
exports.NSIS_PATH = NSIS_PATH;
class AppPackageHelper {
constructor(elevateHelper) {
this.elevateHelper = elevateHelper;
this.archToFileInfo = new Map();
this.infoToIsDelete = new Map();
/** @private */
this.refCount = 0;
}
async packArch(arch, target) {
let infoPromise = this.archToFileInfo.get(arch);
if (infoPromise == null) {
const appOutDir = target.archs.get(arch);
infoPromise = this.elevateHelper.copy(appOutDir, target).then(() => target.buildAppPackage(appOutDir, arch));
this.archToFileInfo.set(arch, infoPromise);
}
const info = await infoPromise;
if (target.isWebInstaller) {
this.infoToIsDelete.set(info, false);
} else if (!this.infoToIsDelete.has(info)) {
this.infoToIsDelete.set(info, true);
}
return info;
}
async finishBuild() {
if (--this.refCount > 0) {
return;
}
const filesToDelete = [];
for (const [info, isDelete] of this.infoToIsDelete.entries()) {
if (isDelete) {
filesToDelete.push(info.path);
}
}
await _bluebirdLst().default.map(filesToDelete, it => (0, _fsExtra().unlink)(it));
}
}
exports.AppPackageHelper = AppPackageHelper;
class CopyElevateHelper {
constructor() {
this.copied = new Map();
}
copy(appOutDir, target) {
if (!target.packager.info.framework.isCopyElevateHelper) {
return Promise.resolve();
}
let isPackElevateHelper = target.options.packElevateHelper;
if (isPackElevateHelper === false && target.options.perMachine === true) {
isPackElevateHelper = true;
_builderUtil().log.warn("`packElevateHelper = false` is ignored, because `perMachine` is set to `true`");
}
if (isPackElevateHelper === false) {
return Promise.resolve();
}
let promise = this.copied.get(appOutDir);
if (promise != null) {
return promise;
}
promise = NSIS_PATH().then(it => {
const outFile = path.join(appOutDir, "resources", "elevate.exe");
const promise = (0, _fs().copyFile)(path.join(it, "elevate.exe"), outFile, false);
if (target.packager.platformSpecificBuildOptions.signAndEditExecutable !== false) {
return promise.then(() => target.packager.sign(outFile));
}
return promise;
});
this.copied.set(appOutDir, promise);
return promise;
}
}
exports.CopyElevateHelper = CopyElevateHelper;
class BinaryReader {
constructor(buffer) {
this._buffer = buffer;
this._position = 0;
}
get length() {
return this._buffer.length;
}
get position() {
return this._position;
}
match(signature) {
if (signature.every((v, i) => this._buffer[this._position + i] === v)) {
this._position += signature.length;
return true;
}
return false;
}
skip(offset) {
this._position += offset;
}
bytes(size) {
const value = this._buffer.subarray(this._position, this._position + size);
this._position += size;
return value;
}
uint16() {
const value = this._buffer[this._position] | this._buffer[this._position + 1] << 8;
this._position += 2;
return value;
}
uint32() {
return this.uint16() | this.uint16() << 16;
}
string(length) {
let value = "";
for (let i = 0; i < length; i++) {
const c = this._buffer[this._position + i];
if (c === 0x00) {
break;
}
value += String.fromCharCode(c);
}
this._position += length;
return value;
}
}
class UninstallerReader {
// noinspection SpellCheckingInspection
static exec(installerPath, uninstallerPath) {
const buffer = _fs2.default.readFileSync(installerPath);
const reader = new BinaryReader(buffer); // IMAGE_DOS_HEADER
if (!reader.match([0x4D, 0x5A])) {
throw new Error("Invalid 'MZ' signature.");
}
reader.skip(58); // e_lfanew
reader.skip(reader.uint32() - reader.position); // IMAGE_FILE_HEADER
if (!reader.match([0x50, 0x45, 0x00, 0x00])) {
throw new Error("Invalid 'PE' signature.");
}
reader.skip(2);
const numberOfSections = reader.uint16();
reader.skip(12);
const sizeOfOptionalHeader = reader.uint16();
reader.skip(2);
reader.skip(sizeOfOptionalHeader); // IMAGE_SECTION_HEADER
let nsisOffset = 0;
for (let i = 0; i < numberOfSections; i++) {
const name = reader.string(8);
reader.skip(8);
const rawSize = reader.uint32();
const rawPointer = reader.uint32();
reader.skip(16);
switch (name) {
case ".text":
case ".rdata":
case ".data":
case ".rsrc":
{
nsisOffset = Math.max(rawPointer + rawSize, nsisOffset);
break;
}
default:
{
if (rawPointer !== 0 && rawSize !== 0) {
throw new Error("Unsupported section '" + name + "'.");
}
break;
}
}
}
const executable = buffer.subarray(0, nsisOffset);
const nsisSize = buffer.length - nsisOffset;
const nsisReader = new BinaryReader(buffer.subarray(nsisOffset, nsisOffset + nsisSize));
const nsisSignature = [0xEF, 0xBE, 0xAD, 0xDE, 0x4E, 0x75, 0x6C, 0x6C, 0x73, 0x6F, 0x66, 0x74, 0x49, 0x6E, 0x73, 0x74];
nsisReader.uint32(); // ?
if (!nsisReader.match(nsisSignature)) {
throw new Error("Invalid signature.");
}
nsisReader.uint32(); // ?
if (nsisSize !== nsisReader.uint32()) {
throw new Error("Size mismatch.");
}
let innerBuffer = null;
while (true) {
let size = nsisReader.uint32();
const compressed = (size & 0x80000000) !== 0;
size = size & 0x7FFFFFFF;
if (size === 0 || nsisReader.position + size > nsisReader.length || nsisReader.position >= nsisReader.length) {
break;
}
let buffer = nsisReader.bytes(size);
if (compressed) {
buffer = _zlib().default.inflateRawSync(buffer);
}
const innerReader = new BinaryReader(buffer);
innerReader.uint32(); // ?
if (innerReader.match(nsisSignature)) {
if (innerBuffer) {
throw new Error("Multiple inner blocks.");
}
innerBuffer = buffer;
}
}
if (!innerBuffer) {
throw new Error("Inner block not found.");
}
_fs2.default.writeFileSync(uninstallerPath, executable);
_fs2.default.appendFileSync(uninstallerPath, innerBuffer);
}
} exports.UninstallerReader = UninstallerReader;
// __ts-babel@6.0.4
//# sourceMappingURL=nsisUtil.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
import { Arch } from "builder-util";
import { PkgOptions } from "..";
import { Identity } from "../codeSign/macCodeSign";
import { Target } from "../core";
import MacPackager from "../macPackager";
export declare class PkgTarget extends Target {
private readonly packager;
readonly outDir: string;
readonly options: PkgOptions;
constructor(packager: MacPackager, outDir: string);
build(appPath: string, arch: Arch): Promise<any>;
private customizeDistributionConfiguration;
private buildComponentPackage;
}
export declare function prepareProductBuildArgs(identity: Identity | null, keychain: string | null | undefined): Array<string>;

View File

@ -0,0 +1,276 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.prepareProductBuildArgs = prepareProductBuildArgs;
exports.PkgTarget = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _fs() {
const data = require("builder-util/out/fs");
_fs = function () {
return data;
};
return data;
}
function _appBuilder() {
const data = require("../util/appBuilder");
_appBuilder = function () {
return data;
};
return data;
}
function _license() {
const data = require("../util/license");
_license = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _appInfo() {
const data = require("../appInfo");
_appInfo = function () {
return data;
};
return data;
}
function _macCodeSign() {
const data = require("../codeSign/macCodeSign");
_macCodeSign = function () {
return data;
};
return data;
}
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const certType = "Developer ID Installer"; // http://www.shanekirk.com/2013/10/creating-flat-packages-in-osx/
// to use --scripts, we must build .app bundle separately using pkgbuild
// productbuild --scripts doesn't work (because scripts in this case not added to our package)
// https://github.com/electron-userland/electron-osx-sign/issues/96#issuecomment-274986942
class PkgTarget extends _core().Target {
constructor(packager, outDir) {
super("pkg");
this.packager = packager;
this.outDir = outDir;
this.options = {
allowAnywhere: true,
allowCurrentUserHome: true,
allowRootDirectory: true,
...this.packager.config.pkg
};
}
async build(appPath, arch) {
const packager = this.packager;
const options = this.options;
const appInfo = packager.appInfo; // pkg doesn't like not ASCII symbols (Could not open package to list files: /Volumes/test/t-gIjdGK/test-project-0/dist/Test App ßW-1.1.0.pkg)
const artifactName = packager.expandArtifactNamePattern(options, "pkg");
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: "pkg",
file: artifactPath,
arch
});
const keychainFile = (await packager.codeSigningInfo.value).keychainFile;
const appOutDir = this.outDir; // https://developer.apple.com/library/content/documentation/DeveloperTools/Reference/DistributionDefinitionRef/Chapters/Distribution_XML_Ref.html
const distInfoFile = path.join(appOutDir, "distribution.xml");
const innerPackageFile = path.join(appOutDir, `${(0, _appInfo().filterCFBundleIdentifier)(appInfo.id)}.pkg`);
const componentPropertyListFile = path.join(appOutDir, `${(0, _appInfo().filterCFBundleIdentifier)(appInfo.id)}.plist`);
const identity = (await Promise.all([(0, _macCodeSign().findIdentity)(certType, options.identity || packager.platformSpecificBuildOptions.identity, keychainFile), this.customizeDistributionConfiguration(distInfoFile, appPath), this.buildComponentPackage(appPath, componentPropertyListFile, innerPackageFile)]))[0];
if (identity == null && packager.forceCodeSigning) {
throw new Error(`Cannot find valid "${certType}" to sign standalone installer, please see https://electron.build/code-signing`);
}
const args = prepareProductBuildArgs(identity, keychainFile);
args.push("--distribution", distInfoFile);
args.push(artifactPath);
(0, _builderUtil().use)(options.productbuild, it => args.push(...it));
await (0, _builderUtil().exec)("productbuild", args, {
cwd: appOutDir
});
await Promise.all([(0, _fsExtra().unlink)(innerPackageFile), (0, _fsExtra().unlink)(distInfoFile)]);
await packager.dispatchArtifactCreated(artifactPath, this, arch, packager.computeSafeArtifactName(artifactName, "pkg", arch));
}
async customizeDistributionConfiguration(distInfoFile, appPath) {
await (0, _builderUtil().exec)("productbuild", ["--synthesize", "--component", appPath, distInfoFile], {
cwd: this.outDir
});
const options = this.options;
let distInfo = await (0, _fsExtra().readFile)(distInfoFile, "utf-8");
if (options.mustClose != null && options.mustClose.length !== 0) {
const startContent = ` <pkg-ref id="${this.packager.appInfo.id}">\n <must-close>\n`;
const endContent = " </must-close>\n </pkg-ref>\n</installer-gui-script>";
let mustCloseContent = "";
options.mustClose.forEach(appId => {
mustCloseContent += ` <app id="${appId}"/>\n`;
});
distInfo = distInfo.replace("</installer-gui-script>", `${startContent}${mustCloseContent}${endContent}`);
}
const insertIndex = distInfo.lastIndexOf("</installer-gui-script>");
distInfo = distInfo.substring(0, insertIndex) + ` <domains enable_anywhere="${options.allowAnywhere}" enable_currentUserHome="${options.allowCurrentUserHome}" enable_localSystem="${options.allowRootDirectory}" />\n` + distInfo.substring(insertIndex);
if (options.background != null) {
const background = await this.packager.getResource(options.background.file);
if (background != null) {
const alignment = options.background.alignment || "center"; // noinspection SpellCheckingInspection
const scaling = options.background.scaling || "tofit";
distInfo = distInfo.substring(0, insertIndex) + ` <background file="${background}" alignment="${alignment}" scaling="${scaling}"/>\n` + distInfo.substring(insertIndex);
distInfo = distInfo.substring(0, insertIndex) + ` <background-darkAqua file="${background}" alignment="${alignment}" scaling="${scaling}"/>\n` + distInfo.substring(insertIndex);
}
}
const welcome = await this.packager.getResource(options.welcome);
if (welcome != null) {
distInfo = distInfo.substring(0, insertIndex) + ` <welcome file="${welcome}"/>\n` + distInfo.substring(insertIndex);
}
const license = await (0, _license().getNotLocalizedLicenseFile)(options.license, this.packager);
if (license != null) {
distInfo = distInfo.substring(0, insertIndex) + ` <license file="${license}"/>\n` + distInfo.substring(insertIndex);
}
const conclusion = await this.packager.getResource(options.conclusion);
if (conclusion != null) {
distInfo = distInfo.substring(0, insertIndex) + ` <conclusion file="${conclusion}"/>\n` + distInfo.substring(insertIndex);
}
(0, _builderUtil().debug)(distInfo);
await (0, _fsExtra().writeFile)(distInfoFile, distInfo);
}
async buildComponentPackage(appPath, propertyListOutputFile, packageOutputFile) {
const options = this.options;
const rootPath = path.dirname(appPath); // first produce a component plist template
await (0, _builderUtil().exec)("pkgbuild", ["--analyze", "--root", rootPath, propertyListOutputFile]); // process the template plist
const plistInfo = (await (0, _appBuilder().executeAppBuilderAsJson)(["decode-plist", "-f", propertyListOutputFile]))[0].filter(it => it.RootRelativeBundlePath !== "Electron.dSYM");
if (plistInfo.length > 0) {
const packageInfo = plistInfo[0]; // ChildBundles lists all of electron binaries within the .app.
// There is no particular reason for removing that key, except to be as close as possible to
// the PackageInfo generated by previous versions of electron-builder.
delete packageInfo.ChildBundles;
if (options.isRelocatable != null) {
packageInfo.BundleIsRelocatable = options.isRelocatable;
}
if (options.isVersionChecked != null) {
packageInfo.BundleIsVersionChecked = options.isVersionChecked;
}
if (options.hasStrictIdentifier != null) {
packageInfo.BundleHasStrictIdentifier = options.hasStrictIdentifier;
}
if (options.overwriteAction != null) {
packageInfo.BundleOverwriteAction = options.overwriteAction;
}
await (0, _appBuilder().executeAppBuilderAndWriteJson)(["encode-plist"], {
[propertyListOutputFile]: plistInfo
});
} // now build the package
const args = ["--root", rootPath, // "--identifier", this.packager.appInfo.id,
"--component-plist", propertyListOutputFile];
(0, _builderUtil().use)(this.options.installLocation || "/Applications", it => args.push("--install-location", it));
if (options.scripts != null) {
args.push("--scripts", path.resolve(this.packager.info.buildResourcesDir, options.scripts));
} else if (options.scripts !== null) {
const dir = path.join(this.packager.info.buildResourcesDir, "pkg-scripts");
const stat = await (0, _fs().statOrNull)(dir);
if (stat != null && stat.isDirectory()) {
args.push("--scripts", dir);
}
}
args.push(packageOutputFile);
await (0, _builderUtil().exec)("pkgbuild", args);
}
}
exports.PkgTarget = PkgTarget;
function prepareProductBuildArgs(identity, keychain) {
const args = [];
if (identity != null) {
args.push("--sign", identity.hash);
if (keychain != null) {
args.push("--keychain", keychain);
}
}
return args;
}
// __ts-babel@6.0.4
//# sourceMappingURL=pkg.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,17 @@
import { Arch } from "builder-util";
import { SnapOptions } from "..";
import { Target } from "../core";
import { LinuxPackager } from "../linuxPackager";
import { LinuxTargetHelper } from "./LinuxTargetHelper";
export default class SnapTarget extends Target {
private readonly packager;
private readonly helper;
readonly outDir: string;
readonly options: SnapOptions;
isUseTemplateApp: boolean;
constructor(name: string, packager: LinuxPackager, helper: LinuxTargetHelper, outDir: string);
private replaceDefault;
private createDescriptor;
build(appOutDir: string, arch: Arch): Promise<any>;
private isElectronVersionGreaterOrEqualThen;
}

View File

@ -0,0 +1,384 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _builderUtilRuntime() {
const data = require("builder-util-runtime");
_builderUtilRuntime = function () {
return data;
};
return data;
}
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
function _jsYaml() {
const data = require("js-yaml");
_jsYaml = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function semver() {
const data = _interopRequireWildcard(require("semver"));
semver = function () {
return data;
};
return data;
}
function _core() {
const data = require("../core");
_core = function () {
return data;
};
return data;
}
function _pathManager() {
const data = require("../util/pathManager");
_pathManager = function () {
return data;
};
return data;
}
function _targetUtil() {
const data = require("./targetUtil");
_targetUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
const defaultPlugs = ["desktop", "desktop-legacy", "home", "x11", "wayland", "unity7", "browser-support", "network", "gsettings", "audio-playback", "pulseaudio", "opengl"];
class SnapTarget extends _core().Target {
constructor(name, packager, helper, outDir) {
super(name);
this.packager = packager;
this.helper = helper;
this.outDir = outDir;
this.options = { ...this.packager.platformSpecificBuildOptions,
...this.packager.config[this.name]
};
this.isUseTemplateApp = false;
}
replaceDefault(inList, defaultList) {
const result = (0, _builderUtil().replaceDefault)(inList, defaultList);
if (result !== defaultList) {
this.isUseTemplateApp = false;
}
return result;
}
async createDescriptor(arch) {
if (!this.isElectronVersionGreaterOrEqualThen("4.0.0")) {
if (!this.isElectronVersionGreaterOrEqualThen("2.0.0-beta.1")) {
throw new (_builderUtil().InvalidConfigurationError)("Electron 2 and higher is required to build Snap");
}
_builderUtil().log.warn("Electron 4 and higher is highly recommended for Snap");
}
const appInfo = this.packager.appInfo;
const snapName = this.packager.executableName.toLowerCase();
const options = this.options;
const plugs = normalizePlugConfiguration(this.options.plugs);
const plugNames = this.replaceDefault(plugs == null ? null : Object.getOwnPropertyNames(plugs), defaultPlugs);
const buildPackages = (0, _builderUtilRuntime().asArray)(options.buildPackages);
const defaultStagePackages = getDefaultStagePackages();
const stagePackages = this.replaceDefault(options.stagePackages, defaultStagePackages);
this.isUseTemplateApp = this.options.useTemplateApp !== false && (arch === _builderUtil().Arch.x64 || arch === _builderUtil().Arch.armv7l) && buildPackages.length === 0 && isArrayEqualRegardlessOfSort(stagePackages, defaultStagePackages);
const appDescriptor = {
command: "command.sh",
plugs: plugNames,
adapter: "none"
};
if (options.slots != null) {
appDescriptor.slots = options.slots;
}
const snap = (0, _jsYaml().safeLoad)(await (0, _fsExtra().readFile)(path.join((0, _pathManager().getTemplatePath)("snap"), "snapcraft.yaml"), "utf-8"));
if (this.isUseTemplateApp) {
delete appDescriptor.adapter;
}
if (options.grade != null) {
snap.grade = options.grade;
}
if (options.confinement != null) {
snap.confinement = options.confinement;
}
if (options.appPartStage != null) {
snap.parts.app.stage = options.appPartStage;
}
if (options.layout != null) {
snap.layout = options.layout;
}
(0, _builderUtil().deepAssign)(snap, {
name: snapName,
version: appInfo.version,
summary: options.summary || appInfo.productName,
description: this.helper.getDescription(options),
architectures: [(0, _builderUtil().toLinuxArchString)(arch, "snap")],
apps: {
[snapName]: appDescriptor
},
parts: {
app: {
"stage-packages": stagePackages
}
}
});
if (options.autoStart) {
appDescriptor.autostart = `${snap.name}.desktop`;
}
if (options.confinement === "classic") {
delete appDescriptor.plugs;
delete snap.plugs;
} else {
const archTriplet = archNameToTriplet(arch);
appDescriptor.environment = {
// https://github.com/electron-userland/electron-builder/issues/4007
// https://github.com/electron/electron/issues/9056
DISABLE_WAYLAND: "1",
TMPDIR: "$XDG_RUNTIME_DIR",
PATH: "$SNAP/usr/sbin:$SNAP/usr/bin:$SNAP/sbin:$SNAP/bin:$PATH",
SNAP_DESKTOP_RUNTIME: "$SNAP/gnome-platform",
LD_LIBRARY_PATH: ["$SNAP_LIBRARY_PATH", "$SNAP/lib:$SNAP/usr/lib:$SNAP/lib/" + archTriplet + ":$SNAP/usr/lib/" + archTriplet, "$LD_LIBRARY_PATH:$SNAP/lib:$SNAP/usr/lib", "$SNAP/lib/" + archTriplet + ":$SNAP/usr/lib/" + archTriplet].join(":"),
...options.environment
};
if (plugs != null) {
for (const plugName of plugNames) {
const plugOptions = plugs[plugName];
if (plugOptions == null) {
continue;
}
snap.plugs[plugName] = plugOptions;
}
}
}
if (buildPackages.length > 0) {
snap.parts.app["build-packages"] = buildPackages;
}
if (options.after != null) {
snap.parts.app.after = options.after;
}
if (options.assumes != null) {
snap.assumes = (0, _builderUtilRuntime().asArray)(options.assumes);
}
return snap;
}
async build(appOutDir, arch) {
const packager = this.packager;
const options = this.options; // tslint:disable-next-line:no-invalid-template-strings
const artifactName = packager.expandArtifactNamePattern(this.options, "snap", arch, "${name}_${version}_${arch}.${ext}", false);
const artifactPath = path.join(this.outDir, artifactName);
await packager.info.callArtifactBuildStarted({
targetPresentableName: "snap",
file: artifactPath,
arch
});
const snap = await this.createDescriptor(arch);
if (this.isUseTemplateApp) {
delete snap.parts;
}
const stageDir = await (0, _targetUtil().createStageDirPath)(this, packager, arch);
const snapArch = (0, _builderUtil().toLinuxArchString)(arch, "snap");
const args = ["snap", "--app", appOutDir, "--stage", stageDir, "--arch", snapArch, "--output", artifactPath, "--executable", this.packager.executableName];
await this.helper.icons;
if (this.helper.maxIconPath != null) {
if (!this.isUseTemplateApp) {
snap.icon = "snap/gui/icon.png";
}
args.push("--icon", this.helper.maxIconPath);
} // snapcraft.yaml inside a snap directory
const snapMetaDir = path.join(stageDir, this.isUseTemplateApp ? "meta" : "snap");
const desktopFile = path.join(snapMetaDir, "gui", `${snap.name}.desktop`);
await this.helper.writeDesktopEntry(this.options, packager.executableName + " %U", desktopFile, {
// tslint:disable:no-invalid-template-strings
Icon: "${SNAP}/meta/gui/icon.png"
});
if (this.isElectronVersionGreaterOrEqualThen("5.0.0") && !isBrowserSandboxAllowed(snap)) {
args.push("--extraAppArgs=--no-sandbox");
if (this.isUseTemplateApp) {
args.push("--exclude", "chrome-sandbox");
}
}
if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed({
snap,
desktopFile,
args
}))) {
return;
}
await (0, _fsExtra().outputFile)(path.join(snapMetaDir, this.isUseTemplateApp ? "snap.yaml" : "snapcraft.yaml"), (0, _builderUtil().serializeToYaml)(snap));
const hooksDir = await packager.getResource(options.hooks, "snap-hooks");
if (hooksDir != null) {
args.push("--hooks", hooksDir);
}
if (this.isUseTemplateApp) {
args.push("--template-url", `electron4:${snapArch}`);
}
await (0, _builderUtil().executeAppBuilder)(args);
await packager.info.callArtifactBuildCompleted({
file: artifactPath,
safeArtifactName: packager.computeSafeArtifactName(artifactName, "snap", arch, false),
target: this,
arch,
packager,
publishConfig: options.publish == null ? {
provider: "snapStore"
} : null
});
}
isElectronVersionGreaterOrEqualThen(version) {
return semver().gte(this.packager.config.electronVersion || "7.0.0", version);
}
}
exports.default = SnapTarget;
function archNameToTriplet(arch) {
switch (arch) {
case _builderUtil().Arch.x64:
return "x86_64-linux-gnu";
case _builderUtil().Arch.ia32:
return "i386-linux-gnu";
case _builderUtil().Arch.armv7l:
// noinspection SpellCheckingInspection
return "arm-linux-gnueabihf";
case _builderUtil().Arch.arm64:
return "aarch64-linux-gnu";
default:
throw new Error(`Unsupported arch ${arch}`);
}
}
function isArrayEqualRegardlessOfSort(a, b) {
a = a.slice();
b = b.slice();
a.sort();
b.sort();
return a.length === b.length && a.every((value, index) => value === b[index]);
}
function normalizePlugConfiguration(raw) {
if (raw == null) {
return null;
}
const result = {};
for (const item of Array.isArray(raw) ? raw : [raw]) {
if (typeof item === "string") {
result[item] = null;
} else {
Object.assign(result, item);
}
}
return result;
}
function isBrowserSandboxAllowed(snap) {
if (snap.plugs != null) {
for (const plugName of Object.keys(snap.plugs)) {
const plug = snap.plugs[plugName];
if (plug.interface === "browser-support" && plug["allow-sandbox"] === true) {
return true;
}
}
}
return false;
}
function getDefaultStagePackages() {
// libxss1 - was "error while loading shared libraries: libXss.so.1" on Xubuntu 16.04
// noinspection SpellCheckingInspection
return ["libnspr4", "libnss3", "libxss1", "libappindicator3-1", "libsecret-1-0"];
}
// __ts-babel@6.0.4
//# sourceMappingURL=snap.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,12 @@
import { Arch } from "builder-util";
import { Platform, Target } from "..";
import { PlatformPackager } from "../platformPackager";
export declare function computeArchToTargetNamesMap(raw: Map<Arch, Array<string>>, platformPackager: PlatformPackager<any>, platform: Platform): Map<Arch, Array<string>>;
export declare function createTargets(nameToTarget: Map<string, Target>, rawList: Array<string>, outDir: string, packager: PlatformPackager<any>): Array<Target>;
export declare function createCommonTarget(target: string, outDir: string, packager: PlatformPackager<any>): Target;
export declare class NoOpTarget extends Target {
readonly options: null;
constructor(name: string);
get outDir(): string;
build(appOutDir: string, arch: Arch): Promise<any>;
}

View File

@ -0,0 +1,151 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.computeArchToTargetNamesMap = computeArchToTargetNamesMap;
exports.createTargets = createTargets;
exports.createCommonTarget = createCommonTarget;
exports.NoOpTarget = void 0;
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _() {
const data = require("..");
_ = function () {
return data;
};
return data;
}
function _ArchiveTarget() {
const data = require("./ArchiveTarget");
_ArchiveTarget = function () {
return data;
};
return data;
}
const archiveTargets = new Set(["zip", "7z", "tar.xz", "tar.lz", "tar.gz", "tar.bz2"]);
function computeArchToTargetNamesMap(raw, platformPackager, platform) {
for (const targetNames of raw.values()) {
if (targetNames.length > 0) {
// https://github.com/electron-userland/electron-builder/issues/1355
return raw;
}
}
const defaultArchs = raw.size === 0 ? [platform === _().Platform.MAC ? "x64" : process.arch] : Array.from(raw.keys()).map(it => _builderUtil().Arch[it]);
const result = new Map(raw);
for (const target of (0, _builderUtil().asArray)(platformPackager.platformSpecificBuildOptions.target).map(it => typeof it === "string" ? {
target: it
} : it)) {
let name = target.target;
let archs = target.arch;
const suffixPos = name.lastIndexOf(":");
if (suffixPos > 0) {
name = target.target.substring(0, suffixPos);
if (archs == null) {
archs = target.target.substring(suffixPos + 1);
}
}
for (const arch of archs == null ? defaultArchs : (0, _builderUtil().asArray)(archs)) {
(0, _builderUtil().addValue)(result, (0, _builderUtil().archFromString)(arch), name);
}
}
if (result.size === 0) {
const defaultTarget = platformPackager.defaultTarget;
if (raw.size === 0 && platform === _().Platform.LINUX && (process.platform === "darwin" || process.platform === "win32")) {
result.set(_builderUtil().Arch.x64, defaultTarget); // cannot enable arm because of native dependencies - e.g. keytar doesn't provide pre-builds for arm
// result.set(Arch.armv7l, ["snap"])
} else {
for (const arch of defaultArchs) {
result.set((0, _builderUtil().archFromString)(arch), defaultTarget);
}
}
}
return result;
}
function createTargets(nameToTarget, rawList, outDir, packager) {
const result = [];
const mapper = (name, factory) => {
let target = nameToTarget.get(name);
if (target == null) {
target = factory(outDir);
nameToTarget.set(name, target);
}
result.push(target);
};
const targets = normalizeTargets(rawList, packager.defaultTarget);
packager.createTargets(targets, mapper);
return result;
}
function normalizeTargets(targets, defaultTarget) {
const list = [];
for (const t of targets) {
const name = t.toLowerCase().trim();
if (name === _().DEFAULT_TARGET) {
list.push(...defaultTarget);
} else {
list.push(name);
}
}
return list;
}
function createCommonTarget(target, outDir, packager) {
if (archiveTargets.has(target)) {
return new (_ArchiveTarget().ArchiveTarget)(target, outDir, packager);
} else if (target === _().DIR_TARGET) {
return new NoOpTarget(_().DIR_TARGET);
} else {
throw new Error(`Unknown target: ${target}`);
}
}
class NoOpTarget extends _().Target {
constructor(name) {
super(name);
this.options = null;
}
get outDir() {
throw new Error("NoOpTarget");
} // eslint-disable-next-line
async build(appOutDir, arch) {// no build
}
} exports.NoOpTarget = NoOpTarget;
// __ts-babel@6.0.4
//# sourceMappingURL=targetFactory.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,13 @@
import { Target, AppInfo } from "../";
import { Arch } from "builder-util";
import { PlatformPackager } from "../platformPackager";
export declare class StageDir {
readonly dir: string;
constructor(dir: string);
getTempFile(name: string): string;
cleanup(): Promise<void>;
toString(): string;
}
export declare function createStageDir(target: Target, packager: PlatformPackager<any>, arch: Arch): Promise<StageDir>;
export declare function createStageDirPath(target: Target, packager: PlatformPackager<any>, arch: Arch): Promise<string>;
export declare function getWindowsInstallationDirName(appInfo: AppInfo, isTryToUseProductName: boolean): string;

View File

@ -0,0 +1,78 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createStageDir = createStageDir;
exports.createStageDirPath = createStageDirPath;
exports.getWindowsInstallationDirName = getWindowsInstallationDirName;
exports.StageDir = void 0;
function _fsExtra() {
const data = require("fs-extra");
_fsExtra = function () {
return data;
};
return data;
}
var path = _interopRequireWildcard(require("path"));
function _builderUtil() {
const data = require("builder-util");
_builderUtil = function () {
return data;
};
return data;
}
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
class StageDir {
constructor(dir) {
this.dir = dir;
}
getTempFile(name) {
return this.dir + path.sep + name;
}
cleanup() {
if (!_builderUtil().debug.enabled || process.env.ELECTRON_BUILDER_REMOVE_STAGE_EVEN_IF_DEBUG === "true") {
return (0, _fsExtra().remove)(this.dir);
}
return Promise.resolve();
}
toString() {
return this.dir;
}
}
exports.StageDir = StageDir;
async function createStageDir(target, packager, arch) {
return new StageDir(await createStageDirPath(target, packager, arch));
}
async function createStageDirPath(target, packager, arch) {
const tempDir = packager.info.stageDirPathCustomizer(target, packager, arch);
await (0, _fsExtra().emptyDir)(tempDir);
return tempDir;
} // https://github.com/electron-userland/electron-builder/issues/3100
// https://github.com/electron-userland/electron-builder/commit/2539cfba20dc639128e75c5b786651b652bb4b78
function getWindowsInstallationDirName(appInfo, isTryToUseProductName) {
return isTryToUseProductName && /^[-_+0-9a-zA-Z .]+$/.test(appInfo.productFilename) ? appInfo.productFilename : appInfo.sanitizedName;
}
// __ts-babel@6.0.4
//# sourceMappingURL=targetUtil.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/targets/targetUtil.ts"],"names":[],"mappings":";;;;;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAGM,MAAO,QAAP,CAAe;AACnB,EAAA,WAAA,CAAqB,GAArB,EAAgC;AAAX,SAAA,GAAA,GAAA,GAAA;AACpB;;AAED,EAAA,WAAW,CAAC,IAAD,EAAa;AACtB,WAAO,KAAK,GAAL,GAAW,IAAI,CAAC,GAAhB,GAAsB,IAA7B;AACD;;AAED,EAAA,OAAO,GAAA;AACL,QAAI,CAAC,qBAAM,OAAP,IAAkB,OAAO,CAAC,GAAR,CAAY,2CAAZ,KAA4D,MAAlF,EAA0F;AACxF,aAAO,uBAAO,KAAK,GAAZ,CAAP;AACD;;AACD,WAAO,OAAO,CAAC,OAAR,EAAP;AACD;;AAED,EAAA,QAAQ,GAAA;AACN,WAAO,KAAK,GAAZ;AACD;;AAjBkB;;;;AAoBd,eAAe,cAAf,CAA8B,MAA9B,EAA8C,QAA9C,EAA+E,IAA/E,EAAyF;AAC9F,SAAO,IAAI,QAAJ,CAAa,MAAM,kBAAkB,CAAC,MAAD,EAAS,QAAT,EAAmB,IAAnB,CAArC,CAAP;AACD;;AAEM,eAAe,kBAAf,CAAkC,MAAlC,EAAkD,QAAlD,EAAmF,IAAnF,EAA6F;AAClG,QAAM,OAAO,GAAG,QAAQ,CAAC,IAAT,CAAc,sBAAd,CAAqC,MAArC,EAA6C,QAA7C,EAAuD,IAAvD,CAAhB;AACA,QAAM,yBAAS,OAAT,CAAN;AACA,SAAO,OAAP;AACD,C,CAED;AACA;;;AACM,SAAU,6BAAV,CAAwC,OAAxC,EAA0D,qBAA1D,EAAwF;AAC5F,SAAO,qBAAqB,IAAI,sBAAsB,IAAtB,CAA2B,OAAO,CAAC,eAAnC,CAAzB,GAA+E,OAAO,CAAC,eAAvF,GAAyG,OAAO,CAAC,aAAxH;AACD,C","sourcesContent":["import { emptyDir, remove } from \"fs-extra\"\nimport * as path from \"path\"\nimport { Target, AppInfo } from \"../\"\nimport { Arch, debug } from \"builder-util\"\nimport { PlatformPackager } from \"../platformPackager\"\n\nexport class StageDir {\n constructor(readonly dir: string) {\n }\n\n getTempFile(name: string) {\n return this.dir + path.sep + name\n }\n\n cleanup() {\n if (!debug.enabled || process.env.ELECTRON_BUILDER_REMOVE_STAGE_EVEN_IF_DEBUG === \"true\") {\n return remove(this.dir)\n }\n return Promise.resolve()\n }\n\n toString() {\n return this.dir\n }\n}\n\nexport async function createStageDir(target: Target, packager: PlatformPackager<any>, arch: Arch): Promise<StageDir> {\n return new StageDir(await createStageDirPath(target, packager, arch))\n}\n\nexport async function createStageDirPath(target: Target, packager: PlatformPackager<any>, arch: Arch): Promise<string> {\n const tempDir = packager.info.stageDirPathCustomizer(target, packager, arch)\n await emptyDir(tempDir)\n return tempDir\n}\n\n// https://github.com/electron-userland/electron-builder/issues/3100\n// https://github.com/electron-userland/electron-builder/commit/2539cfba20dc639128e75c5b786651b652bb4b78\nexport function getWindowsInstallationDirName(appInfo: AppInfo, isTryToUseProductName: boolean): string {\n return isTryToUseProductName && /^[-_+0-9a-zA-Z .]+$/.test(appInfo.productFilename) ? appInfo.productFilename : appInfo.sanitizedName\n}"],"sourceRoot":""}

View File

@ -0,0 +1 @@
export declare function getLinuxToolsPath(): Promise<string>;

View File

@ -0,0 +1,23 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLinuxToolsPath = getLinuxToolsPath;
function _binDownload() {
const data = require("../binDownload");
_binDownload = function () {
return data;
};
return data;
}
function getLinuxToolsPath() {
//noinspection SpellCheckingInspection
return (0, _binDownload().getBinFromUrl)("linux-tools", "mac-10.12.3", "SQ8fqIRVXuQVWnVgaMTDWyf2TLAJjJYw3tRSqQJECmgF6qdM7Kogfa6KD49RbGzzMYIFca9Uw3MdsxzOPRWcYw==");
}
// __ts-babel@6.0.4
//# sourceMappingURL=tools.js.map

View File

@ -0,0 +1 @@
{"version":3,"sources":["../../src/targets/tools.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEM,SAAU,iBAAV,GAA2B;AAC/B;AACA,SAAO,kCAAc,aAAd,EAA6B,aAA7B,EAA4C,0FAA5C,CAAP;AACD,C","sourcesContent":["import { getBinFromUrl } from \"../binDownload\"\n\nexport function getLinuxToolsPath() {\n //noinspection SpellCheckingInspection\n return getBinFromUrl(\"linux-tools\", \"mac-10.12.3\", \"SQ8fqIRVXuQVWnVgaMTDWyf2TLAJjJYw3tRSqQJECmgF6qdM7Kogfa6KD49RbGzzMYIFca9Uw3MdsxzOPRWcYw==\")\n}"],"sourceRoot":""}