electron-updater 6.3.7 → 6.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/DownloadedUpdateHelper.js +2 -3
- package/out/DownloadedUpdateHelper.js.map +1 -1
- package/out/NsisUpdater.js +1 -1
- package/out/NsisUpdater.js.map +1 -1
- package/out/differentialDownloader/DifferentialDownloader.js +1 -1
- package/out/differentialDownloader/DifferentialDownloader.js.map +1 -1
- package/package.json +2 -2
|
@@ -76,7 +76,7 @@ class DownloadedUpdateHelper {
|
|
|
76
76
|
// remove stale data
|
|
77
77
|
await (0, fs_extra_1.emptyDir)(this.cacheDirForPendingUpdate);
|
|
78
78
|
}
|
|
79
|
-
catch (
|
|
79
|
+
catch (_ignore) {
|
|
80
80
|
// ignore
|
|
81
81
|
}
|
|
82
82
|
}
|
|
@@ -86,7 +86,6 @@ class DownloadedUpdateHelper {
|
|
|
86
86
|
* @param logger
|
|
87
87
|
*/
|
|
88
88
|
async getValidCachedUpdateFile(fileInfo, logger) {
|
|
89
|
-
var _a;
|
|
90
89
|
const updateInfoFilePath = this.getUpdateInfoFile();
|
|
91
90
|
const doesUpdateInfoFileExist = await (0, fs_extra_1.pathExists)(updateInfoFilePath);
|
|
92
91
|
if (!doesUpdateInfoFileExist) {
|
|
@@ -105,7 +104,7 @@ class DownloadedUpdateHelper {
|
|
|
105
104
|
logger.info(message);
|
|
106
105
|
return null;
|
|
107
106
|
}
|
|
108
|
-
const isCachedInfoFileNameValid = (
|
|
107
|
+
const isCachedInfoFileNameValid = (cachedInfo === null || cachedInfo === void 0 ? void 0 : cachedInfo.fileName) !== null;
|
|
109
108
|
if (!isCachedInfoFileNameValid) {
|
|
110
109
|
logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`);
|
|
111
110
|
await this.cleanCacheDirForPendingUpdate();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DownloadedUpdateHelper.js","sourceRoot":"","sources":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,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { UpdateInfo } from \"builder-util-runtime\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\n// @ts-ignore\nimport * as isEqual from \"lodash.isequal\"\nimport { Logger, ResolvedUpdateFileInfo } from \"./main\"\nimport { pathExists, readJson, emptyDir, outputJson, unlink } from \"fs-extra\"\nimport * as path from \"path\"\n\n/** @private **/\nexport class DownloadedUpdateHelper {\n private _file: string | null = null\n private _packageFile: string | null = null\n\n private versionInfo: UpdateInfo | null = null\n private fileInfo: ResolvedUpdateFileInfo | null = null\n\n constructor(readonly cacheDir: string) {}\n\n private _downloadedFileInfo: CachedUpdateInfo | null = null\n get downloadedFileInfo(): CachedUpdateInfo | null {\n return this._downloadedFileInfo\n }\n\n get file(): string | null {\n return this._file\n }\n\n get packageFile(): string | null {\n return this._packageFile\n }\n\n get cacheDirForPendingUpdate(): string {\n return path.join(this.cacheDir, \"pending\")\n }\n\n async validateDownloadedPath(updateFile: string, updateInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {\n if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) {\n // update has already been downloaded from this running instance\n // check here only existence, not checksum\n if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await pathExists(updateFile))) {\n return updateFile\n } else {\n return null\n }\n }\n\n // update has already been downloaded from some previous app launch\n const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger)\n if (cachedUpdateFile === null) {\n return null\n }\n logger.info(`Update has already been downloaded to ${updateFile}).`)\n this._file = cachedUpdateFile\n return cachedUpdateFile\n }\n\n async setDownloadedFile(\n downloadedFile: string,\n packageFile: string | null,\n versionInfo: UpdateInfo,\n fileInfo: ResolvedUpdateFileInfo,\n updateFileName: string,\n isSaveCache: boolean\n ): Promise<void> {\n this._file = downloadedFile\n this._packageFile = packageFile\n this.versionInfo = versionInfo\n this.fileInfo = fileInfo\n this._downloadedFileInfo = {\n fileName: updateFileName,\n sha512: fileInfo.info.sha512,\n isAdminRightsRequired: fileInfo.info.isAdminRightsRequired === true,\n }\n\n if (isSaveCache) {\n await outputJson(this.getUpdateInfoFile(), this._downloadedFileInfo)\n }\n }\n\n async clear(): Promise<void> {\n this._file = null\n this._packageFile = null\n this.versionInfo = null\n this.fileInfo = null\n await this.cleanCacheDirForPendingUpdate()\n }\n\n private async cleanCacheDirForPendingUpdate(): Promise<void> {\n try {\n // remove stale data\n await emptyDir(this.cacheDirForPendingUpdate)\n } catch (ignore) {\n // ignore\n }\n }\n\n /**\n * Returns \"update-info.json\" which is created in the update cache directory's \"pending\" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated.\n * @param fileInfo\n * @param logger\n */\n private async getValidCachedUpdateFile(fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {\n const updateInfoFilePath: string = this.getUpdateInfoFile()\n\n const doesUpdateInfoFileExist = await pathExists(updateInfoFilePath)\n if (!doesUpdateInfoFileExist) {\n return null\n }\n\n let cachedInfo: CachedUpdateInfo\n try {\n cachedInfo = await readJson(updateInfoFilePath)\n } catch (error: any) {\n let message = `No cached update info available`\n if (error.code !== \"ENOENT\") {\n await this.cleanCacheDirForPendingUpdate()\n message += ` (error on read: ${error.message})`\n }\n logger.info(message)\n return null\n }\n\n const isCachedInfoFileNameValid = cachedInfo?.fileName !== null ?? false\n if (!isCachedInfoFileNameValid) {\n logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n if (fileInfo.info.sha512 !== cachedInfo.sha512) {\n logger.info(\n `Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`\n )\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName)\n if (!(await pathExists(updateFile))) {\n logger.info(\"Cached update file doesn't exist\")\n return null\n }\n\n const sha512 = await hashFile(updateFile)\n if (fileInfo.info.sha512 !== sha512) {\n logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n this._downloadedFileInfo = cachedInfo\n return updateFile\n }\n\n private getUpdateInfoFile(): string {\n return path.join(this.cacheDirForPendingUpdate, \"update-info.json\")\n }\n}\n\ninterface CachedUpdateInfo {\n fileName: string\n sha512: string\n readonly isAdminRightsRequired: boolean\n}\n\nfunction hashFile(file: string, algorithm = \"sha512\", encoding: \"base64\" | \"hex\" = \"base64\", options?: any): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const hash = createHash(algorithm)\n hash.on(\"error\", reject).setEncoding(encoding)\n\n createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ })\n .on(\"error\", reject)\n .on(\"end\", () => {\n hash.end()\n resolve(hash.read() as string)\n })\n .pipe(hash, { end: false })\n })\n}\n\nexport async function createTempUpdateFile(name: string, cacheDir: string, log: Logger): Promise<string> {\n // https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912\n let nameCounter = 0\n let result = path.join(cacheDir, name)\n for (let i = 0; i < 3; i++) {\n try {\n await unlink(result)\n return result\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n return result\n }\n\n log.warn(`Error on remove temp update file: ${e}`)\n result = path.join(cacheDir, `${nameCounter++}-${name}`)\n }\n }\n return result\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DownloadedUpdateHelper.js","sourceRoot":"","sources":["../src/DownloadedUpdateHelper.ts"],"names":[],"mappings":";;;AAoLA,oDAkBC;AArMD,mCAAmC;AACnC,2BAAqC;AACrC,aAAa;AACb,0CAAyC;AAEzC,uCAA6E;AAC7E,6BAA4B;AAE5B,gBAAgB;AAChB,MAAa,sBAAsB;IAOjC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C,+CAA+C,EAAE,CAAC;aAC/G,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC;aACnB,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YACd,IAAI,CAAC,GAAG,EAAE,CAAA;YACV,OAAO,CAAC,IAAI,CAAC,IAAI,EAAY,CAAC,CAAA;QAChC,CAAC,CAAC;aACD,IAAI,CAAC,IAAI,EAAE,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC,CAAA;IAC/B,CAAC,CAAC,CAAA;AACJ,CAAC;AAEM,KAAK,UAAU,oBAAoB,CAAC,IAAY,EAAE,QAAgB,EAAE,GAAW;IACpF,yFAAyF;IACzF,IAAI,WAAW,GAAG,CAAC,CAAA;IACnB,IAAI,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAA;IACtC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;QAC3B,IAAI,CAAC;YACH,MAAM,IAAA,iBAAM,EAAC,MAAM,CAAC,CAAA;YACpB,OAAO,MAAM,CAAA;QACf,CAAC;QAAC,OAAO,CAAM,EAAE,CAAC;YAChB,IAAI,CAAC,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBACxB,OAAO,MAAM,CAAA;YACf,CAAC;YAED,GAAG,CAAC,IAAI,CAAC,qCAAqC,CAAC,EAAE,CAAC,CAAA;YAClD,MAAM,GAAG,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,GAAG,WAAW,EAAE,IAAI,IAAI,EAAE,CAAC,CAAA;QAC1D,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC","sourcesContent":["import { UpdateInfo } from \"builder-util-runtime\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\n// @ts-ignore\nimport * as isEqual from \"lodash.isequal\"\nimport { Logger, ResolvedUpdateFileInfo } from \"./main\"\nimport { pathExists, readJson, emptyDir, outputJson, unlink } from \"fs-extra\"\nimport * as path from \"path\"\n\n/** @private **/\nexport class DownloadedUpdateHelper {\n private _file: string | null = null\n private _packageFile: string | null = null\n\n private versionInfo: UpdateInfo | null = null\n private fileInfo: ResolvedUpdateFileInfo | null = null\n\n constructor(readonly cacheDir: string) {}\n\n private _downloadedFileInfo: CachedUpdateInfo | null = null\n get downloadedFileInfo(): CachedUpdateInfo | null {\n return this._downloadedFileInfo\n }\n\n get file(): string | null {\n return this._file\n }\n\n get packageFile(): string | null {\n return this._packageFile\n }\n\n get cacheDirForPendingUpdate(): string {\n return path.join(this.cacheDir, \"pending\")\n }\n\n async validateDownloadedPath(updateFile: string, updateInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {\n if (this.versionInfo != null && this.file === updateFile && this.fileInfo != null) {\n // update has already been downloaded from this running instance\n // check here only existence, not checksum\n if (isEqual(this.versionInfo, updateInfo) && isEqual(this.fileInfo.info, fileInfo.info) && (await pathExists(updateFile))) {\n return updateFile\n } else {\n return null\n }\n }\n\n // update has already been downloaded from some previous app launch\n const cachedUpdateFile = await this.getValidCachedUpdateFile(fileInfo, logger)\n if (cachedUpdateFile === null) {\n return null\n }\n logger.info(`Update has already been downloaded to ${updateFile}).`)\n this._file = cachedUpdateFile\n return cachedUpdateFile\n }\n\n async setDownloadedFile(\n downloadedFile: string,\n packageFile: string | null,\n versionInfo: UpdateInfo,\n fileInfo: ResolvedUpdateFileInfo,\n updateFileName: string,\n isSaveCache: boolean\n ): Promise<void> {\n this._file = downloadedFile\n this._packageFile = packageFile\n this.versionInfo = versionInfo\n this.fileInfo = fileInfo\n this._downloadedFileInfo = {\n fileName: updateFileName,\n sha512: fileInfo.info.sha512,\n isAdminRightsRequired: fileInfo.info.isAdminRightsRequired === true,\n }\n\n if (isSaveCache) {\n await outputJson(this.getUpdateInfoFile(), this._downloadedFileInfo)\n }\n }\n\n async clear(): Promise<void> {\n this._file = null\n this._packageFile = null\n this.versionInfo = null\n this.fileInfo = null\n await this.cleanCacheDirForPendingUpdate()\n }\n\n private async cleanCacheDirForPendingUpdate(): Promise<void> {\n try {\n // remove stale data\n await emptyDir(this.cacheDirForPendingUpdate)\n } catch (_ignore) {\n // ignore\n }\n }\n\n /**\n * Returns \"update-info.json\" which is created in the update cache directory's \"pending\" subfolder after the first update is downloaded. If the update file does not exist then the cache is cleared and recreated. If the update file exists then its properties are validated.\n * @param fileInfo\n * @param logger\n */\n private async getValidCachedUpdateFile(fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {\n const updateInfoFilePath: string = this.getUpdateInfoFile()\n\n const doesUpdateInfoFileExist = await pathExists(updateInfoFilePath)\n if (!doesUpdateInfoFileExist) {\n return null\n }\n\n let cachedInfo: CachedUpdateInfo\n try {\n cachedInfo = await readJson(updateInfoFilePath)\n } catch (error: any) {\n let message = `No cached update info available`\n if (error.code !== \"ENOENT\") {\n await this.cleanCacheDirForPendingUpdate()\n message += ` (error on read: ${error.message})`\n }\n logger.info(message)\n return null\n }\n\n const isCachedInfoFileNameValid = cachedInfo?.fileName !== null\n if (!isCachedInfoFileNameValid) {\n logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n if (fileInfo.info.sha512 !== cachedInfo.sha512) {\n logger.info(\n `Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`\n )\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n\n const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName)\n if (!(await pathExists(updateFile))) {\n logger.info(\"Cached update file doesn't exist\")\n return null\n }\n\n const sha512 = await hashFile(updateFile)\n if (fileInfo.info.sha512 !== sha512) {\n logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`)\n await this.cleanCacheDirForPendingUpdate()\n return null\n }\n this._downloadedFileInfo = cachedInfo\n return updateFile\n }\n\n private getUpdateInfoFile(): string {\n return path.join(this.cacheDirForPendingUpdate, \"update-info.json\")\n }\n}\n\ninterface CachedUpdateInfo {\n fileName: string\n sha512: string\n readonly isAdminRightsRequired: boolean\n}\n\nfunction hashFile(file: string, algorithm = \"sha512\", encoding: \"base64\" | \"hex\" = \"base64\", options?: any): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const hash = createHash(algorithm)\n hash.on(\"error\", reject).setEncoding(encoding)\n\n createReadStream(file, { ...options, highWaterMark: 1024 * 1024 /* better to use more memory but hash faster */ })\n .on(\"error\", reject)\n .on(\"end\", () => {\n hash.end()\n resolve(hash.read() as string)\n })\n .pipe(hash, { end: false })\n })\n}\n\nexport async function createTempUpdateFile(name: string, cacheDir: string, log: Logger): Promise<string> {\n // https://github.com/electron-userland/electron-builder/pull/2474#issuecomment-366481912\n let nameCounter = 0\n let result = path.join(cacheDir, name)\n for (let i = 0; i < 3; i++) {\n try {\n await unlink(result)\n return result\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n return result\n }\n\n log.warn(`Error on remove temp update file: ${e}`)\n result = path.join(cacheDir, `${nameCounter++}-${name}`)\n }\n }\n return result\n}\n"]}
|
package/out/NsisUpdater.js
CHANGED
package/out/NsisUpdater.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"NsisUpdater.js","sourceRoot":"","sources":["../src/NsisUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAAmJ;AACnJ,6BAA4B;AAG5B,+CAA2D;AAE3D,4IAAwI;AACxI,iCAAqE;AACrE,mDAAyD;AACzD,uCAAiC;AACjC,qGAA0E;AAC1E,6BAAyB;AAEzB,MAAa,WAAY,SAAQ,yBAAW;IAO1C,YAAY,OAAkC,EAAE,GAAgB;QAC9D,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QAGX,+BAA0B,GAA8B,CAAC,cAA6B,EA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mE;YACnE,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;QACrC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAnMD,kCAmMC","sourcesContent":["import { AllPublishOptions, newError, PackageFileInfo, CURRENT_APP_INSTALLER_FILE_NAME, CURRENT_APP_PACKAGE_FILE_NAME } from \"builder-util-runtime\"\nimport * as path from \"path\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { DOWNLOAD_PROGRESS, verifyUpdateCodeSignature } from \"./main\"\nimport { findFile, Provider } from \"./providers/Provider\"\nimport { unlink } from \"fs-extra\"\nimport { verifySignature } from \"./windowsExecutableCodeSignatureVerifier\"\nimport { URL } from \"url\"\n\nexport class NsisUpdater extends BaseUpdater {\n /**\n * Specify custom install directory path\n *\n */\n installDirectory?: string\n\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n protected _verifyUpdateCodeSignature: verifyUpdateCodeSignature = (publisherNames: Array<string>, unescapedTempUpdateFile: string) =>\n verifySignature(publisherNames, unescapedTempUpdateFile, this._logger)\n\n /**\n * The verifyUpdateCodeSignature. You can pass [win-verify-signature](https://github.com/beyondkmp/win-verify-trust) or another custom verify function: ` (publisherName: string[], path: string) => Promise<string | null>`.\n * The default verify function uses [windowsExecutableCodeSignatureVerifier](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/windowsExecutableCodeSignatureVerifier.ts)\n */\n get verifyUpdateCodeSignature(): verifyUpdateCodeSignature {\n return this._verifyUpdateCodeSignature\n }\n\n set verifyUpdateCodeSignature(value: verifyUpdateCodeSignature) {\n if (value) {\n this._verifyUpdateCodeSignature = value\n }\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"exe\")!\n return this.executeDownload({\n fileExtension: \"exe\",\n downloadUpdateOptions,\n fileInfo,\n task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => {\n const packageInfo = fileInfo.packageInfo\n const isWebInstaller = packageInfo != null && packageFile != null\n if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) {\n throw newError(\n `Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`,\n \"ERR_UPDATER_WEB_INSTALLER_DISABLED\"\n )\n }\n if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) {\n this._logger.warn(\n \"disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version.\"\n )\n }\n if (\n isWebInstaller ||\n downloadUpdateOptions.disableDifferentialDownload ||\n (await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_APP_INSTALLER_FILE_NAME))\n ) {\n await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions)\n }\n\n const signatureVerificationStatus = await this.verifySignature(destinationFile)\n if (signatureVerificationStatus != null) {\n await removeTempDirIfAny()\n // noinspection ThrowInsideFinallyBlockJS\n throw newError(\n `New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`,\n \"ERR_UPDATER_INVALID_SIGNATURE\"\n )\n }\n\n if (isWebInstaller) {\n if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) {\n try {\n await this.httpExecutor.download(new URL(packageInfo.path), packageFile, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n sha512: packageInfo.sha512,\n })\n } catch (e: any) {\n try {\n await unlink(packageFile)\n } catch (ignored) {\n // ignore\n }\n\n throw e\n }\n }\n }\n },\n })\n }\n\n // $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n // | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n // | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\n private async verifySignature(tempUpdateFile: string): Promise<string | null> {\n let publisherName: Array<string> | string | null\n try {\n publisherName = (await this.configOnDisk.value).publisherName\n if (publisherName == null) {\n return null\n }\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // no app-update.yml\n return null\n }\n throw e\n }\n return await this._verifyUpdateCodeSignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile)\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const args = [\"--updated\"]\n if (options.isSilent) {\n args.push(\"/S\")\n }\n\n if (options.isForceRunAfter) {\n args.push(\"--force-run\")\n }\n\n if (this.installDirectory) {\n // maybe check if folder exists\n args.push(`/D=${this.installDirectory}`)\n }\n\n const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile\n if (packagePath != null) {\n // only = form is supported\n args.push(`--package-file=${packagePath}`)\n }\n\n const callUsingElevation = (): void => {\n this.spawnLog(path.join(process.resourcesPath, \"elevate.exe\"), [options.installerPath].concat(args)).catch(e => this.dispatchError(e))\n }\n\n if (options.isAdminRightsRequired) {\n this._logger.info(\"isAdminRightsRequired is set to true, run installer using elevate.exe\")\n callUsingElevation()\n return true\n }\n\n this.spawnLog(options.installerPath, args).catch((e: Error) => {\n // https://github.com/electron-userland/electron-builder/issues/1129\n // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors\n const errorCode = (e as NodeJS.ErrnoException).code\n this._logger.info(\n `Cannot run installer: error code: ${errorCode}, error message: \"${e.message}\", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`\n )\n if (errorCode === \"UNKNOWN\" || errorCode === \"EACCES\") {\n callUsingElevation()\n } else if (errorCode === \"ENOENT\") {\n require(\"electron\")\n .shell.openPath(options.installerPath)\n .catch((err: Error) => this.dispatchError(err))\n } else {\n this.dispatchError(e)\n }\n })\n return true\n }\n\n private async differentialDownloadWebPackage(\n downloadUpdateOptions: DownloadUpdateOptions,\n packageInfo: PackageFileInfo,\n packagePath: string,\n provider: Provider<any>\n ): Promise<boolean> {\n if (packageInfo.blockMapSize == null) {\n return true\n }\n\n try {\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: new URL(packageInfo.path),\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_APP_PACKAGE_FILE_NAME),\n logger: this._logger,\n newFile: packagePath,\n requestHeaders: this.requestHeaders,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n await new FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download()\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac or linux) we must throw error\n return process.platform === \"win32\"\n }\n return false\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"NsisUpdater.js","sourceRoot":"","sources":["../src/NsisUpdater.ts"],"names":[],"mappings":";;;AAAA,+DAAmJ;AACnJ,6BAA4B;AAG5B,+CAA2D;AAE3D,4IAAwI;AACxI,iCAAqE;AACrE,mDAAyD;AACzD,uCAAiC;AACjC,qGAA0E;AAC1E,6BAAyB;AAEzB,MAAa,WAAY,SAAQ,yBAAW;IAO1C,YAAY,OAAkC,EAAE,GAAgB;QAC9D,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC,CAAA;QAGX,+BAA0B,GAA8B,CAAC,cAA6B,EA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AmE;YACnE,OAAO,OAAO,CAAC,QAAQ,KAAK,OAAO,CAAA;QACrC,CAAC;QACD,OAAO,KAAK,CAAA;IACd,CAAC;CACF;AAnMD,kCAmMC","sourcesContent":["import { AllPublishOptions, newError, PackageFileInfo, CURRENT_APP_INSTALLER_FILE_NAME, CURRENT_APP_PACKAGE_FILE_NAME } from \"builder-util-runtime\"\nimport * as path from \"path\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { DOWNLOAD_PROGRESS, verifyUpdateCodeSignature } from \"./main\"\nimport { findFile, Provider } from \"./providers/Provider\"\nimport { unlink } from \"fs-extra\"\nimport { verifySignature } from \"./windowsExecutableCodeSignatureVerifier\"\nimport { URL } from \"url\"\n\nexport class NsisUpdater extends BaseUpdater {\n /**\n * Specify custom install directory path\n *\n */\n installDirectory?: string\n\n constructor(options?: AllPublishOptions | null, app?: AppAdapter) {\n super(options, app)\n }\n\n protected _verifyUpdateCodeSignature: verifyUpdateCodeSignature = (publisherNames: Array<string>, unescapedTempUpdateFile: string) =>\n verifySignature(publisherNames, unescapedTempUpdateFile, this._logger)\n\n /**\n * The verifyUpdateCodeSignature. You can pass [win-verify-signature](https://github.com/beyondkmp/win-verify-trust) or another custom verify function: ` (publisherName: string[], path: string) => Promise<string | null>`.\n * The default verify function uses [windowsExecutableCodeSignatureVerifier](https://github.com/electron-userland/electron-builder/blob/master/packages/electron-updater/src/windowsExecutableCodeSignatureVerifier.ts)\n */\n get verifyUpdateCodeSignature(): verifyUpdateCodeSignature {\n return this._verifyUpdateCodeSignature\n }\n\n set verifyUpdateCodeSignature(value: verifyUpdateCodeSignature) {\n if (value) {\n this._verifyUpdateCodeSignature = value\n }\n }\n\n /*** @private */\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>> {\n const provider = downloadUpdateOptions.updateInfoAndProvider.provider\n const fileInfo = findFile(provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info), \"exe\")!\n return this.executeDownload({\n fileExtension: \"exe\",\n downloadUpdateOptions,\n fileInfo,\n task: async (destinationFile, downloadOptions, packageFile, removeTempDirIfAny) => {\n const packageInfo = fileInfo.packageInfo\n const isWebInstaller = packageInfo != null && packageFile != null\n if (isWebInstaller && downloadUpdateOptions.disableWebInstaller) {\n throw newError(\n `Unable to download new version ${downloadUpdateOptions.updateInfoAndProvider.info.version}. Web Installers are disabled`,\n \"ERR_UPDATER_WEB_INSTALLER_DISABLED\"\n )\n }\n if (!isWebInstaller && !downloadUpdateOptions.disableWebInstaller) {\n this._logger.warn(\n \"disableWebInstaller is set to false, you should set it to true if you do not plan on using a web installer. This will default to true in a future version.\"\n )\n }\n if (\n isWebInstaller ||\n downloadUpdateOptions.disableDifferentialDownload ||\n (await this.differentialDownloadInstaller(fileInfo, downloadUpdateOptions, destinationFile, provider, CURRENT_APP_INSTALLER_FILE_NAME))\n ) {\n await this.httpExecutor.download(fileInfo.url, destinationFile, downloadOptions)\n }\n\n const signatureVerificationStatus = await this.verifySignature(destinationFile)\n if (signatureVerificationStatus != null) {\n await removeTempDirIfAny()\n // noinspection ThrowInsideFinallyBlockJS\n throw newError(\n `New version ${downloadUpdateOptions.updateInfoAndProvider.info.version} is not signed by the application owner: ${signatureVerificationStatus}`,\n \"ERR_UPDATER_INVALID_SIGNATURE\"\n )\n }\n\n if (isWebInstaller) {\n if (await this.differentialDownloadWebPackage(downloadUpdateOptions, packageInfo, packageFile, provider)) {\n try {\n await this.httpExecutor.download(new URL(packageInfo.path), packageFile, {\n headers: downloadUpdateOptions.requestHeaders,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n sha512: packageInfo.sha512,\n })\n } catch (e: any) {\n try {\n await unlink(packageFile)\n } catch (_ignored) {\n // ignore\n }\n\n throw e\n }\n }\n }\n },\n })\n }\n\n // $certificateInfo = (Get-AuthenticodeSignature 'xxx\\yyy.exe'\n // | where {$_.Status.Equals([System.Management.Automation.SignatureStatus]::Valid) -and $_.SignerCertificate.Subject.Contains(\"CN=siemens.com\")})\n // | Out-String ; if ($certificateInfo) { exit 0 } else { exit 1 }\n private async verifySignature(tempUpdateFile: string): Promise<string | null> {\n let publisherName: Array<string> | string | null\n try {\n publisherName = (await this.configOnDisk.value).publisherName\n if (publisherName == null) {\n return null\n }\n } catch (e: any) {\n if (e.code === \"ENOENT\") {\n // no app-update.yml\n return null\n }\n throw e\n }\n return await this._verifyUpdateCodeSignature(Array.isArray(publisherName) ? publisherName : [publisherName], tempUpdateFile)\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const args = [\"--updated\"]\n if (options.isSilent) {\n args.push(\"/S\")\n }\n\n if (options.isForceRunAfter) {\n args.push(\"--force-run\")\n }\n\n if (this.installDirectory) {\n // maybe check if folder exists\n args.push(`/D=${this.installDirectory}`)\n }\n\n const packagePath = this.downloadedUpdateHelper == null ? null : this.downloadedUpdateHelper.packageFile\n if (packagePath != null) {\n // only = form is supported\n args.push(`--package-file=${packagePath}`)\n }\n\n const callUsingElevation = (): void => {\n this.spawnLog(path.join(process.resourcesPath, \"elevate.exe\"), [options.installerPath].concat(args)).catch(e => this.dispatchError(e))\n }\n\n if (options.isAdminRightsRequired) {\n this._logger.info(\"isAdminRightsRequired is set to true, run installer using elevate.exe\")\n callUsingElevation()\n return true\n }\n\n this.spawnLog(options.installerPath, args).catch((e: Error) => {\n // https://github.com/electron-userland/electron-builder/issues/1129\n // Node 8 sends errors: https://nodejs.org/dist/latest-v8.x/docs/api/errors.html#errors_common_system_errors\n const errorCode = (e as NodeJS.ErrnoException).code\n this._logger.info(\n `Cannot run installer: error code: ${errorCode}, error message: \"${e.message}\", will be executed again using elevate if EACCES, and will try to use electron.shell.openItem if ENOENT`\n )\n if (errorCode === \"UNKNOWN\" || errorCode === \"EACCES\") {\n callUsingElevation()\n } else if (errorCode === \"ENOENT\") {\n require(\"electron\")\n .shell.openPath(options.installerPath)\n .catch((err: Error) => this.dispatchError(err))\n } else {\n this.dispatchError(e)\n }\n })\n return true\n }\n\n private async differentialDownloadWebPackage(\n downloadUpdateOptions: DownloadUpdateOptions,\n packageInfo: PackageFileInfo,\n packagePath: string,\n provider: Provider<any>\n ): Promise<boolean> {\n if (packageInfo.blockMapSize == null) {\n return true\n }\n\n try {\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: new URL(packageInfo.path),\n oldFile: path.join(this.downloadedUpdateHelper!.cacheDir, CURRENT_APP_PACKAGE_FILE_NAME),\n logger: this._logger,\n newFile: packagePath,\n requestHeaders: this.requestHeaders,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n cancellationToken: downloadUpdateOptions.cancellationToken,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n await new FileWithEmbeddedBlockMapDifferentialDownloader(packageInfo, this.httpExecutor, downloadOptions).download()\n } catch (e: any) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac or linux) we must throw error\n return process.platform === \"win32\"\n }\n return false\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/DifferentialDownloader.ts"],"names":[],"mappings":";;;AAAA,+DAAuJ;AAEvJ,uCAAsC;AACtC,2BAAsC;AAItC,iDAAyC;AACzC,6BAAyB;AACzB,+DAAmF;AACnF,uEAA0G;AAC1G,mHAAiJ;AAgBjJ,MAAsB,sBAAsB;IAK1C,oEAAoE;IACpE,YACqB,kBAAsC,EAChD,YAA+B,EAC/B,OAAsC;QAF5B,uBAAkB,GAAlB,kBAAkB,CAAoB;Q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EAAE,CAAC;oBAC9C,OAAM;gBACR,CAAC;gBAED,QAAQ,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;gBAC5B,QAAQ,CAAC,EAAE,CAAC,SAAS,EAAE,GAAG,EAAE;oBAC1B,MAAM,CAAC,IAAI,KAAK,CAAC,yCAAyC,CAAC,CAAC,CAAA;gBAC9D,CAAC,CAAC,CAAA;gBAEF,QAAQ,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,CAAC,CAAA;gBAChC,QAAQ,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE,CAAC,OAAO,EAAE,CAAC,CAAA;YACrC,CAAC,CAAC,CAAA;YACF,IAAI,CAAC,YAAY,CAAC,0BAA0B,CAAC,OAAO,EAAE,MAAM,CAAC,CAAA;YAC7D,OAAO,CAAC,GAAG,EAAE,CAAA;QACf,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA1RD,wDA0RC;AAED,SAAS,WAAW,CAAC,KAAa,EAAE,MAAM,GAAG,KAAK;IAChD,OAAO,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAQ,CAAC,GAAG,MAAM,CAAA;AACtF,CAAC;AAED,SAAS;AACT,SAAS,WAAW,CAAC,GAAW;IAC9B,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import { BlockMapDataHolder, createHttpError, DigestTransform, HttpExecutor, configureRequestUrl, configureRequestOptions } from \"builder-util-runtime\"\nimport { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, open } from \"fs-extra\"\nimport { createWriteStream } from \"fs\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { ProgressInfo, CancellationToken } from \"builder-util-runtime\"\nimport { Logger } from \"../main\"\nimport { copyData } from \"./DataSplitter\"\nimport { URL } from \"url\"\nimport { computeOperations, Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { checkIsRangesSupported, executeTasksUsingMultipleRangeRequests } from \"./multipleRangeDownloader\"\nimport { ProgressDifferentialDownloadCallbackTransform, ProgressDifferentialDownloadInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nexport interface DifferentialDownloaderOptions {\n readonly oldFile: string\n readonly newUrl: URL\n readonly logger: Logger\n readonly newFile: string\n\n readonly requestHeaders: OutgoingHttpHeaders | null\n\n readonly isUseMultipleRangeRequest?: boolean\n\n readonly cancellationToken: CancellationToken\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport abstract class DifferentialDownloader {\n fileMetadataBuffer: Buffer | null = null\n\n private readonly logger: Logger\n\n // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected\n constructor(\n protected readonly blockAwareFileInfo: BlockMapDataHolder,\n readonly httpExecutor: HttpExecutor<any>,\n readonly options: DifferentialDownloaderOptions\n ) {\n this.logger = options.logger\n }\n\n createRequestOptions(): RequestOptions {\n const result = {\n headers: {\n ...this.options.requestHeaders,\n accept: \"*/*\",\n },\n }\n configureRequestUrl(this.options.newUrl, result)\n // user-agent, cache-control and other common options\n configureRequestOptions(result)\n return result\n }\n\n protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any> {\n // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it\n if (oldBlockMap.version !== newBlockMap.version) {\n throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`)\n }\n\n const logger = this.logger\n const operations = computeOperations(oldBlockMap, newBlockMap, logger)\n if (logger.debug != null) {\n logger.debug(JSON.stringify(operations, null, 2))\n }\n\n let downloadSize = 0\n let copySize = 0\n for (const operation of operations) {\n const length = operation.end - operation.start\n if (operation.kind === OperationKind.DOWNLOAD) {\n downloadSize += length\n } else {\n copySize += length\n }\n }\n\n const newSize = this.blockAwareFileInfo.size\n if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {\n throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`)\n }\n\n logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`)\n\n return this.downloadFile(operations)\n }\n\n private downloadFile(tasks: Array<Operation>): Promise<any> {\n const fdList: Array<OpenedFile> = []\n const closeFiles = (): Promise<Array<void>> => {\n return Promise.all(\n fdList.map(openedFile => {\n return close(openedFile.descriptor).catch((e: any) => {\n this.logger.error(`cannot close file \"${openedFile.path}\": ${e}`)\n })\n })\n )\n }\n return this.doDownloadFile(tasks, fdList)\n .then(closeFiles)\n .catch((e: any) => {\n // then must be after catch here (since then always throws error)\n return closeFiles()\n .catch(closeFilesError => {\n // closeFiles never throw error, but just to be sure\n try {\n this.logger.error(`cannot close files: ${closeFilesError}`)\n } catch (errorOnLog) {\n try {\n console.error(errorOnLog)\n } catch (ignored) {\n // ok, give up and ignore error\n }\n }\n throw e\n })\n .then(() => {\n throw e\n })\n })\n }\n\n private async doDownloadFile(tasks: Array<Operation>, fdList: Array<OpenedFile>): Promise<any> {\n const oldFileFd = await open(this.options.oldFile, \"r\")\n fdList.push({ descriptor: oldFileFd, path: this.options.oldFile })\n const newFileFd = await open(this.options.newFile, \"w\")\n fdList.push({ descriptor: newFileFd, path: this.options.newFile })\n const fileOut = createWriteStream(this.options.newFile, { fd: newFileFd })\n await new Promise((resolve, reject) => {\n const streams: Array<any> = []\n\n // Create our download info transformer if we have one\n let downloadInfoTransform: ProgressDifferentialDownloadCallbackTransform | undefined = undefined\n if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {\n // TODO: Does not support multiple ranges (someone feel free to PR this!)\n const expectedByteCounts: Array<number> = []\n let grandTotalBytes = 0\n\n for (const task of tasks) {\n if (task.kind === OperationKind.DOWNLOAD) {\n expectedByteCounts.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n const progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo = {\n expectedByteCounts: expectedByteCounts,\n grandTotal: grandTotalBytes,\n }\n\n downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress)\n streams.push(downloadInfoTransform)\n }\n\n const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)\n // to simply debug, do manual validation to allow file to be fully written\n digestTransform.isValidateOnEnd = false\n streams.push(digestTransform)\n\n // noinspection JSArrowFunctionCanBeReplacedWithShorthand\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(() => {\n // remove from fd list because closed successfully\n fdList.splice(1, 1)\n try {\n digestTransform.validate()\n } catch (e: any) {\n reject(e)\n return\n }\n\n resolve(undefined)\n })\n })\n\n streams.push(fileOut)\n\n let lastStream = null\n for (const stream of streams) {\n stream.on(\"error\", reject)\n if (lastStream == null) {\n lastStream = stream\n } else {\n lastStream = lastStream.pipe(stream)\n }\n }\n\n const firstStream = streams[0]\n\n let w: any\n if (this.options.isUseMultipleRangeRequest) {\n w = executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject)\n w(0)\n return\n }\n\n let downloadOperationCount = 0\n let actualUrl: string | null = null\n this.logger.info(`Differential download: ${this.options.newUrl}`)\n\n const requestOptions = this.createRequestOptions()\n ;(requestOptions as any).redirect = \"manual\"\n\n w = (index: number): void => {\n if (index >= tasks.length) {\n if (this.fileMetadataBuffer != null) {\n firstStream.write(this.fileMetadataBuffer)\n }\n firstStream.end()\n return\n }\n\n const operation = tasks[index++]\n if (operation.kind === OperationKind.COPY) {\n // We are copying, let's not send status updates to the UI\n if (downloadInfoTransform) {\n downloadInfoTransform.beginFileCopy()\n }\n\n copyData(operation, firstStream, oldFileFd, reject, () => w(index))\n return\n }\n\n const range = `bytes=${operation.start}-${operation.end - 1}`\n requestOptions.headers!.range = range\n\n this.logger?.debug?.(`download range: ${range}`)\n\n // We are starting to download\n if (downloadInfoTransform) {\n downloadInfoTransform.beginRangeDownload()\n }\n\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode >= 400) {\n reject(createHttpError(response))\n }\n\n response.pipe(firstStream, {\n end: false,\n })\n response.once(\"end\", () => {\n // Pass on that we are downloading a segment\n if (downloadInfoTransform) {\n downloadInfoTransform.endRangeDownload()\n }\n\n if (++downloadOperationCount === 100) {\n downloadOperationCount = 0\n setTimeout(() => w(index), 1000)\n } else {\n w(index)\n }\n })\n })\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)\n actualUrl = redirectUrl\n configureRequestUrl(new URL(actualUrl), requestOptions)\n request.followRedirect()\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n\n w(0)\n })\n }\n\n protected async readRemoteBytes(start: number, endInclusive: number): Promise<Buffer> {\n const buffer = Buffer.allocUnsafe(endInclusive + 1 - start)\n const requestOptions = this.createRequestOptions()\n requestOptions.headers!.range = `bytes=${start}-${endInclusive}`\n let position = 0\n await this.request(requestOptions, chunk => {\n chunk.copy(buffer, position)\n position += chunk.length\n })\n\n if (position !== buffer.length) {\n throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`)\n }\n return buffer\n }\n\n private request(requestOptions: RequestOptions, dataHandler: (chunk: Buffer) => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n\n response.on(\"data\", dataHandler)\n response.on(\"end\", () => resolve())\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n })\n }\n}\n\nfunction formatBytes(value: number, symbol = \" KB\"): string {\n return new Intl.NumberFormat(\"en\").format((value / 1024).toFixed(2) as any) + symbol\n}\n\n// safety\nfunction removeQuery(url: string): string {\n const index = url.indexOf(\"?\")\n return index < 0 ? url : url.substring(0, index)\n}\n\ninterface OpenedFile {\n readonly descriptor: number\n readonly path: string\n}\n"]}
|
|
1
|
+
{"version":3,"file":"DifferentialDownloader.js","sourceRoot":"","sources":["../../src/differentialDownloader/DifferentialDownloader.ts"],"names":[],"mappings":";;;AAAA,+DAAuJ;AAEvJ,uCAAsC;AACtC,2BAAsC;AAItC,iDAAyC;AACzC,6BAAyB;AACzB,+DAAmF;AACnF,uEAA0G;AAC1G,mHAAiJ;AAgBjJ,MAAsB,sBAAsB;IAK1C,oEAAoE;IACpE,YACqB,kBAAsC,EAChD,YAA+B,EAC/B,OAAsC;QAF5B,uBAAkB,GAAlB,kBAAkB,CAAoB;QAChD,iBAAY,GAAZ,YAAY,CAAmB;QAC/B,YAAO,GAAP,OAAO,CAA+B;QARjD,uBAAkB,GAAkB,IAAI,CAAA;QAUtC,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAA;IAC9B,CAAC;IAED,oBAAoB;QAClB,MAAM,MAAM,GAAG;YACb,OAAO,EAAE;gBACP,GAAG,IAAI,CAAC,OAAO,CAAC,cAAc;gBAC9B,MAAM,EAAE,KAAK;aACd;SACF,CAAA;QACD,IAAA,0CAAmB,EAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;QAChD,qDAAqD;QACrD,IAAA,8CAAuB,EAAC,MAAM,CAAC,CAAA;QAC/B,OAAO,MAAM,CAAA;IACf,CAAC;IAES,UAAU,CAAC,WAAq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D,OAAO,CAAC,GAAG,EAAE,CAAA;QACf,CAAC,CAAC,CAAA;IACJ,CAAC;CACF;AA1RD,wDA0RC;AAED,SAAS,WAAW,CAAC,KAAa,EAAE,MAAM,GAAG,KAAK;IAChD,OAAO,IAAI,IAAI,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAQ,CAAC,GAAG,MAAM,CAAA;AACtF,CAAC;AAED,SAAS;AACT,SAAS,WAAW,CAAC,GAAW;IAC9B,MAAM,KAAK,GAAG,GAAG,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC9B,OAAO,KAAK,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,EAAE,KAAK,CAAC,CAAA;AAClD,CAAC","sourcesContent":["import { BlockMapDataHolder, createHttpError, DigestTransform, HttpExecutor, configureRequestUrl, configureRequestOptions } from \"builder-util-runtime\"\nimport { BlockMap } from \"builder-util-runtime/out/blockMapApi\"\nimport { close, open } from \"fs-extra\"\nimport { createWriteStream } from \"fs\"\nimport { OutgoingHttpHeaders, RequestOptions } from \"http\"\nimport { ProgressInfo, CancellationToken } from \"builder-util-runtime\"\nimport { Logger } from \"../main\"\nimport { copyData } from \"./DataSplitter\"\nimport { URL } from \"url\"\nimport { computeOperations, Operation, OperationKind } from \"./downloadPlanBuilder\"\nimport { checkIsRangesSupported, executeTasksUsingMultipleRangeRequests } from \"./multipleRangeDownloader\"\nimport { ProgressDifferentialDownloadCallbackTransform, ProgressDifferentialDownloadInfo } from \"./ProgressDifferentialDownloadCallbackTransform\"\n\nexport interface DifferentialDownloaderOptions {\n readonly oldFile: string\n readonly newUrl: URL\n readonly logger: Logger\n readonly newFile: string\n\n readonly requestHeaders: OutgoingHttpHeaders | null\n\n readonly isUseMultipleRangeRequest?: boolean\n\n readonly cancellationToken: CancellationToken\n onProgress?: (progress: ProgressInfo) => void\n}\n\nexport abstract class DifferentialDownloader {\n fileMetadataBuffer: Buffer | null = null\n\n private readonly logger: Logger\n\n // noinspection TypeScriptAbstractClassConstructorCanBeMadeProtected\n constructor(\n protected readonly blockAwareFileInfo: BlockMapDataHolder,\n readonly httpExecutor: HttpExecutor<any>,\n readonly options: DifferentialDownloaderOptions\n ) {\n this.logger = options.logger\n }\n\n createRequestOptions(): RequestOptions {\n const result = {\n headers: {\n ...this.options.requestHeaders,\n accept: \"*/*\",\n },\n }\n configureRequestUrl(this.options.newUrl, result)\n // user-agent, cache-control and other common options\n configureRequestOptions(result)\n return result\n }\n\n protected doDownload(oldBlockMap: BlockMap, newBlockMap: BlockMap): Promise<any> {\n // we don't check other metadata like compressionMethod - generic check that it is make sense to differentially update is suitable for it\n if (oldBlockMap.version !== newBlockMap.version) {\n throw new Error(`version is different (${oldBlockMap.version} - ${newBlockMap.version}), full download is required`)\n }\n\n const logger = this.logger\n const operations = computeOperations(oldBlockMap, newBlockMap, logger)\n if (logger.debug != null) {\n logger.debug(JSON.stringify(operations, null, 2))\n }\n\n let downloadSize = 0\n let copySize = 0\n for (const operation of operations) {\n const length = operation.end - operation.start\n if (operation.kind === OperationKind.DOWNLOAD) {\n downloadSize += length\n } else {\n copySize += length\n }\n }\n\n const newSize = this.blockAwareFileInfo.size\n if (downloadSize + copySize + (this.fileMetadataBuffer == null ? 0 : this.fileMetadataBuffer.length) !== newSize) {\n throw new Error(`Internal error, size mismatch: downloadSize: ${downloadSize}, copySize: ${copySize}, newSize: ${newSize}`)\n }\n\n logger.info(`Full: ${formatBytes(newSize)}, To download: ${formatBytes(downloadSize)} (${Math.round(downloadSize / (newSize / 100))}%)`)\n\n return this.downloadFile(operations)\n }\n\n private downloadFile(tasks: Array<Operation>): Promise<any> {\n const fdList: Array<OpenedFile> = []\n const closeFiles = (): Promise<Array<void>> => {\n return Promise.all(\n fdList.map(openedFile => {\n return close(openedFile.descriptor).catch((e: any) => {\n this.logger.error(`cannot close file \"${openedFile.path}\": ${e}`)\n })\n })\n )\n }\n return this.doDownloadFile(tasks, fdList)\n .then(closeFiles)\n .catch((e: any) => {\n // then must be after catch here (since then always throws error)\n return closeFiles()\n .catch(closeFilesError => {\n // closeFiles never throw error, but just to be sure\n try {\n this.logger.error(`cannot close files: ${closeFilesError}`)\n } catch (errorOnLog) {\n try {\n console.error(errorOnLog)\n } catch (_ignored) {\n // ok, give up and ignore error\n }\n }\n throw e\n })\n .then(() => {\n throw e\n })\n })\n }\n\n private async doDownloadFile(tasks: Array<Operation>, fdList: Array<OpenedFile>): Promise<any> {\n const oldFileFd = await open(this.options.oldFile, \"r\")\n fdList.push({ descriptor: oldFileFd, path: this.options.oldFile })\n const newFileFd = await open(this.options.newFile, \"w\")\n fdList.push({ descriptor: newFileFd, path: this.options.newFile })\n const fileOut = createWriteStream(this.options.newFile, { fd: newFileFd })\n await new Promise((resolve, reject) => {\n const streams: Array<any> = []\n\n // Create our download info transformer if we have one\n let downloadInfoTransform: ProgressDifferentialDownloadCallbackTransform | undefined = undefined\n if (!this.options.isUseMultipleRangeRequest && this.options.onProgress) {\n // TODO: Does not support multiple ranges (someone feel free to PR this!)\n const expectedByteCounts: Array<number> = []\n let grandTotalBytes = 0\n\n for (const task of tasks) {\n if (task.kind === OperationKind.DOWNLOAD) {\n expectedByteCounts.push(task.end - task.start)\n grandTotalBytes += task.end - task.start\n }\n }\n\n const progressDifferentialDownloadInfo: ProgressDifferentialDownloadInfo = {\n expectedByteCounts: expectedByteCounts,\n grandTotal: grandTotalBytes,\n }\n\n downloadInfoTransform = new ProgressDifferentialDownloadCallbackTransform(progressDifferentialDownloadInfo, this.options.cancellationToken, this.options.onProgress)\n streams.push(downloadInfoTransform)\n }\n\n const digestTransform = new DigestTransform(this.blockAwareFileInfo.sha512)\n // to simply debug, do manual validation to allow file to be fully written\n digestTransform.isValidateOnEnd = false\n streams.push(digestTransform)\n\n // noinspection JSArrowFunctionCanBeReplacedWithShorthand\n fileOut.on(\"finish\", () => {\n ;(fileOut.close as any)(() => {\n // remove from fd list because closed successfully\n fdList.splice(1, 1)\n try {\n digestTransform.validate()\n } catch (e: any) {\n reject(e)\n return\n }\n\n resolve(undefined)\n })\n })\n\n streams.push(fileOut)\n\n let lastStream = null\n for (const stream of streams) {\n stream.on(\"error\", reject)\n if (lastStream == null) {\n lastStream = stream\n } else {\n lastStream = lastStream.pipe(stream)\n }\n }\n\n const firstStream = streams[0]\n\n let w: any\n if (this.options.isUseMultipleRangeRequest) {\n w = executeTasksUsingMultipleRangeRequests(this, tasks, firstStream, oldFileFd, reject)\n w(0)\n return\n }\n\n let downloadOperationCount = 0\n let actualUrl: string | null = null\n this.logger.info(`Differential download: ${this.options.newUrl}`)\n\n const requestOptions = this.createRequestOptions()\n ;(requestOptions as any).redirect = \"manual\"\n\n w = (index: number): void => {\n if (index >= tasks.length) {\n if (this.fileMetadataBuffer != null) {\n firstStream.write(this.fileMetadataBuffer)\n }\n firstStream.end()\n return\n }\n\n const operation = tasks[index++]\n if (operation.kind === OperationKind.COPY) {\n // We are copying, let's not send status updates to the UI\n if (downloadInfoTransform) {\n downloadInfoTransform.beginFileCopy()\n }\n\n copyData(operation, firstStream, oldFileFd, reject, () => w(index))\n return\n }\n\n const range = `bytes=${operation.start}-${operation.end - 1}`\n requestOptions.headers!.range = range\n\n this.logger?.debug?.(`download range: ${range}`)\n\n // We are starting to download\n if (downloadInfoTransform) {\n downloadInfoTransform.beginRangeDownload()\n }\n\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n // Electron net handles redirects automatically, our NodeJS test server doesn't use redirects - so, we don't check 3xx codes.\n if (response.statusCode >= 400) {\n reject(createHttpError(response))\n }\n\n response.pipe(firstStream, {\n end: false,\n })\n response.once(\"end\", () => {\n // Pass on that we are downloading a segment\n if (downloadInfoTransform) {\n downloadInfoTransform.endRangeDownload()\n }\n\n if (++downloadOperationCount === 100) {\n downloadOperationCount = 0\n setTimeout(() => w(index), 1000)\n } else {\n w(index)\n }\n })\n })\n request.on(\"redirect\", (statusCode: number, method: string, redirectUrl: string) => {\n this.logger.info(`Redirect to ${removeQuery(redirectUrl)}`)\n actualUrl = redirectUrl\n configureRequestUrl(new URL(actualUrl), requestOptions)\n request.followRedirect()\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n }\n\n w(0)\n })\n }\n\n protected async readRemoteBytes(start: number, endInclusive: number): Promise<Buffer> {\n const buffer = Buffer.allocUnsafe(endInclusive + 1 - start)\n const requestOptions = this.createRequestOptions()\n requestOptions.headers!.range = `bytes=${start}-${endInclusive}`\n let position = 0\n await this.request(requestOptions, chunk => {\n chunk.copy(buffer, position)\n position += chunk.length\n })\n\n if (position !== buffer.length) {\n throw new Error(`Received data length ${position} is not equal to expected ${buffer.length}`)\n }\n return buffer\n }\n\n private request(requestOptions: RequestOptions, dataHandler: (chunk: Buffer) => void): Promise<void> {\n return new Promise((resolve, reject) => {\n const request = this.httpExecutor.createRequest(requestOptions, response => {\n if (!checkIsRangesSupported(response, reject)) {\n return\n }\n\n response.on(\"error\", reject)\n response.on(\"aborted\", () => {\n reject(new Error(\"response has been aborted by the server\"))\n })\n\n response.on(\"data\", dataHandler)\n response.on(\"end\", () => resolve())\n })\n this.httpExecutor.addErrorAndTimeoutHandlers(request, reject)\n request.end()\n })\n }\n}\n\nfunction formatBytes(value: number, symbol = \" KB\"): string {\n return new Intl.NumberFormat(\"en\").format((value / 1024).toFixed(2) as any) + symbol\n}\n\n// safety\nfunction removeQuery(url: string): string {\n const index = url.indexOf(\"?\")\n return index < 0 ? url : url.substring(0, index)\n}\n\ninterface OpenedFile {\n readonly descriptor: number\n readonly path: string\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "electron-updater",
|
|
3
|
-
"version": "6.3.
|
|
3
|
+
"version": "6.3.8",
|
|
4
4
|
"description": "Cross platform updater for electron applications",
|
|
5
5
|
"main": "out/main.js",
|
|
6
6
|
"author": "Vladimir Krivosheev",
|
|
@@ -23,7 +23,7 @@
|
|
|
23
23
|
"lodash.isequal": "^4.5.0",
|
|
24
24
|
"semver": "^7.6.3",
|
|
25
25
|
"tiny-typed-emitter": "^2.1.0",
|
|
26
|
-
"builder-util-runtime": "9.2.
|
|
26
|
+
"builder-util-runtime": "9.2.9"
|
|
27
27
|
},
|
|
28
28
|
"devDependencies": {
|
|
29
29
|
"@types/fs-extra": "9.0.13",
|