electron-updater 4.3.4 → 4.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.
Files changed (39) hide show
  1. package/out/AppImageUpdater.js +25 -3
  2. package/out/AppImageUpdater.js.map +1 -1
  3. package/out/AppUpdater.d.ts +0 -2
  4. package/out/AppUpdater.js +5 -7
  5. package/out/AppUpdater.js.map +1 -1
  6. package/out/DownloadedUpdateHelper.js +1 -2
  7. package/out/DownloadedUpdateHelper.js.map +1 -1
  8. package/out/MacUpdater.d.ts +1 -1
  9. package/out/MacUpdater.js +29 -10
  10. package/out/MacUpdater.js.map +1 -1
  11. package/out/NsisUpdater.js +23 -17
  12. package/out/NsisUpdater.js.map +1 -1
  13. package/out/differentialDownloader/DifferentialDownloader.d.ts +3 -0
  14. package/out/differentialDownloader/DifferentialDownloader.js +50 -2
  15. package/out/differentialDownloader/DifferentialDownloader.js.map +1 -1
  16. package/out/differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader.js +1 -1
  17. package/out/differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader.js.map +1 -1
  18. package/out/differentialDownloader/ProgressDifferentialDownloadCallbackTransform.d.ts +32 -0
  19. package/out/differentialDownloader/ProgressDifferentialDownloadCallbackTransform.js +118 -0
  20. package/out/differentialDownloader/ProgressDifferentialDownloadCallbackTransform.js.map +1 -0
  21. package/out/differentialDownloader/downloadPlanBuilder.js +2 -3
  22. package/out/differentialDownloader/downloadPlanBuilder.js.map +1 -1
  23. package/out/differentialDownloader/multipleRangeDownloader.js +6 -0
  24. package/out/differentialDownloader/multipleRangeDownloader.js.map +1 -1
  25. package/out/main.d.ts +0 -1
  26. package/out/main.js +0 -16
  27. package/out/main.js.map +1 -1
  28. package/out/providers/BintrayProvider.js +1 -1
  29. package/out/providers/BintrayProvider.js.map +1 -1
  30. package/out/providers/GenericProvider.js +1 -1
  31. package/out/providers/GenericProvider.js.map +1 -1
  32. package/out/providers/PrivateGitHubProvider.js +2 -2
  33. package/out/providers/PrivateGitHubProvider.js.map +1 -1
  34. package/out/providers/Provider.js +1 -1
  35. package/out/providers/Provider.js.map +1 -1
  36. package/out/windowsExecutableCodeSignatureVerifier.d.ts +1 -1
  37. package/out/windowsExecutableCodeSignatureVerifier.js +22 -2
  38. package/out/windowsExecutableCodeSignatureVerifier.js.map +1 -1
  39. package/package.json +8 -8
@@ -59,6 +59,16 @@ function _FileWithEmbeddedBlockMapDifferentialDownloader() {
59
59
  return data;
60
60
  }
61
61
 
62
+ function _main() {
63
+ const data = require("./main");
64
+
65
+ _main = function () {
66
+ return data;
67
+ };
68
+
69
+ return data;
70
+ }
71
+
62
72
  function _Provider() {
63
73
  const data = require("./providers/Provider");
64
74
 
@@ -111,14 +121,21 @@ class AppImageUpdater extends _BaseUpdater().BaseUpdater {
111
121
  let isDownloadFull = false;
112
122
 
113
123
  try {
114
- await new (_FileWithEmbeddedBlockMapDifferentialDownloader().FileWithEmbeddedBlockMapDifferentialDownloader)(fileInfo.info, this.httpExecutor, {
124
+ const downloadOptions = {
115
125
  newUrl: fileInfo.url,
116
126
  oldFile,
117
127
  logger: this._logger,
118
128
  newFile: updateFile,
119
129
  isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,
120
- requestHeaders: downloadUpdateOptions.requestHeaders
121
- }).download();
130
+ requestHeaders: downloadUpdateOptions.requestHeaders,
131
+ cancellationToken: downloadUpdateOptions.cancellationToken
132
+ };
133
+
134
+ if (this.listenerCount(_main().DOWNLOAD_PROGRESS) > 0) {
135
+ downloadOptions.onProgress = it => this.emit(_main().DOWNLOAD_PROGRESS, it);
136
+ }
137
+
138
+ await new (_FileWithEmbeddedBlockMapDifferentialDownloader().FileWithEmbeddedBlockMapDifferentialDownloader)(fileInfo.info, this.httpExecutor, downloadOptions).download();
122
139
  } catch (e) {
123
140
  this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`); // during test (developer machine mac) we must throw error
124
141
 
@@ -156,6 +173,11 @@ class AppImageUpdater extends _BaseUpdater().BaseUpdater {
156
173
  }
157
174
 
158
175
  (0, _child_process().execFileSync)("mv", ["-f", options.installerPath, destination]);
176
+
177
+ if (destination !== appImageFile) {
178
+ this.emit('appimage-filename-updated', destination);
179
+ }
180
+
159
181
  const env = { ...process.env,
160
182
  APPIMAGE_SILENT_INSTALL: "true"
161
183
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/AppImageUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAEM,MAAO,eAAP,SAA+B,0BAA/B,CAA0C;AAC9C,EAAA,WAAA,CAAY,OAAZ,EAAgD,GAAhD,EAAyD;AACvD,UAAM,OAAN,EAAe,GAAf;AACD;;AAEM,EAAA,eAAe,GAAA;AACpB,QAAI,OAAO,CAAC,GAAR,CAAY,QAAZ,IAAwB,IAA5B,EAAkC;AAChC,UAAI,OAAO,CAAC,GAAR,CAAY,IAAZ,IAAoB,IAAxB,EAA8B;AAC5B,aAAK,OAAL,CAAa,IAAb,CAAkB,qEAAlB;AACD,OAFD,MAGK;AACH,aAAK,OAAL,CAAa,IAAb,CAAkB,0CAAlB;AACD;;AACD,aAAO,KAAP;AACD;;AACD,WAAO,MAAM,eAAN,EAAP;AACD;AAED;;;AACU,EAAA,gBAAgB,CAAC,qBAAD,EAA6C;AACrE,UAAM,QAAQ,GAAG,qBAAqB,CAAC,qBAAtB,CAA4C,QAA7D;AACA,UAAM,QAAQ,GAAG,0BAAS,QAAQ,CAAC,YAAT,CAAsB,qBAAqB,CAAC,qBAAtB,C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AY,IAAI,IAApB,EAA0B;AACxB,YAAM,oCAAS,6BAAT,EAAwC,gCAAxC,CAAN;AACD,KAJwC,CAMzC;;;AACA,wBAAW,YAAX;AAEA,QAAI,WAAJ;AACA,UAAM,gBAAgB,GAAG,IAAI,CAAC,QAAL,CAAc,YAAd,CAAzB,CAVyC,CAWzC;AACA;;AACA,QAAI,IAAI,CAAC,QAAL,CAAc,OAAO,CAAC,aAAtB,MAAyC,gBAAzC,IAA6D,CAAC,gBAAgB,IAAhB,CAAqB,gBAArB,CAAlE,EAA0G;AACxG;AACA,MAAA,WAAW,GAAG,YAAd;AACD,KAHD,MAIK;AACH,MAAA,WAAW,GAAG,IAAI,CAAC,IAAL,CAAU,IAAI,CAAC,OAAL,CAAa,YAAb,CAAV,EAAsC,IAAI,CAAC,QAAL,CAAc,OAAO,CAAC,aAAtB,CAAtC,CAAd;AACD;;AAED,uCAAa,IAAb,EAAmB,CAAC,IAAD,EAAO,OAAO,CAAC,aAAf,EAA8B,WAA9B,CAAnB;AAEA,UAAM,GAAG,GAAQ,EACf,GAAG,OAAO,CAAC,GADI;AAEf,MAAA,uBAAuB,EAAE;AAFV,KAAjB;;AAKA,QAAI,OAAO,CAAC,eAAZ,EAA6B;AAC3B,kCAAM,WAAN,EAAmB,EAAnB,EAAuB;AACrB,QAAA,QAAQ,EAAE,IADW;AAErB,QAAA,KAAK,EAAE,QAFc;AAGrB,QAAA;AAHqB,OAAvB,EAKG,KALH;AAMD,KAPD,MAQK;AACH,MAAA,GAAG,CAAC,2BAAJ,GAAkC,MAAlC;AACA,yCAAa,WAAb,EAA0B,EAA1B,EAA8B;AAAC,QAAA;AAAD,OAA9B;AACD;;AACD,WAAO,IAAP;AACD;;AApG6C,C","sourcesContent":["import { AllPublishOptions, newError } from \"builder-util-runtime\"\nimport { execFileSync, spawn } from \"child_process\"\nimport { chmod } from \"fs-extra\"\nimport { unlinkSync } from \"fs\"\nimport * as path from \"path\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { findFile } from \"./providers/Provider\"\n\nexport class AppImageUpdater extends BaseUpdater {\n constructor(options?: AllPublishOptions | null, app?: any) {\n super(options, app)\n }\n\n public isUpdaterActive(): boolean {\n if (process.env.APPIMAGE == null) {\n if (process.env.SNAP == null) {\n this._logger.warn(\"APPIMAGE env is not defined, current application is not an AppImage\")\n }\n else {\n this._logger.info(\"SNAP env is defined, updater is disabled\")\n }\n return false\n }\n return super.isUpdaterActive()\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), \"AppImage\")!!\n return this.executeDownload({\n fileExtension: \"AppImage\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n const oldFile = process.env.APPIMAGE!!\n if (oldFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n let isDownloadFull = false\n try {\n await new FileWithEmbeddedBlockMapDifferentialDownloader(fileInfo.info, this.httpExecutor, {\n newUrl: fileInfo.url,\n oldFile,\n logger: this._logger,\n newFile: updateFile,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\n })\n .download()\n }\n catch (e) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac) we must throw error\n isDownloadFull = process.platform === \"linux\"\n }\n\n if (isDownloadFull) {\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n }\n\n await chmod(updateFile, 0o755)\n },\n })\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const appImageFile = process.env.APPIMAGE!!\n if (appImageFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n // https://stackoverflow.com/a/1712051/1910191\n unlinkSync(appImageFile)\n\n let destination: string\n const existingBaseName = path.basename(appImageFile)\n // https://github.com/electron-userland/electron-builder/issues/2964\n // if no version in existing file name, it means that user wants to preserve current custom name\n if (path.basename(options.installerPath) === existingBaseName || !/\\d+\\.\\d+\\.\\d+/.test(existingBaseName)) {\n // no version in the file name, overwrite existing\n destination = appImageFile\n }\n else {\n destination = path.join(path.dirname(appImageFile), path.basename(options.installerPath))\n }\n\n execFileSync(\"mv\", [\"-f\", options.installerPath, destination])\n\n const env: any = {\n ...process.env,\n APPIMAGE_SILENT_INSTALL: \"true\",\n }\n\n if (options.isForceRunAfter) {\n spawn(destination, [], {\n detached: true,\n stdio: \"ignore\",\n env,\n })\n .unref()\n }\n else {\n env.APPIMAGE_EXIT_AFTER_INSTALL = \"true\"\n execFileSync(destination, [], {env})\n }\n return true\n }\n}"],"sourceRoot":""}
1
+ {"version":3,"sources":["../src/AppImageUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAEM,MAAO,eAAP,SAA+B,0BAA/B,CAA0C;AAC9C,EAAA,WAAA,CAAY,OAAZ,EAAgD,GAAhD,EAAyD;AACvD,UAAM,OAAN,EAAe,GAAf;AACD;;AAEM,EAAA,eAAe,GAAA;AACpB,QAAI,OAAO,CAAC,G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,aAAtB,CAAtC,CAAd;AACD;;AAED,uCAAa,IAAb,EAAmB,CAAC,IAAD,EAAO,OAAO,CAAC,aAAf,EAA8B,WAA9B,CAAnB;;AACA,QAAI,WAAW,KAAK,YAApB,EAAkC;AAChC,WAAK,IAAL,CAAU,2BAAV,EAAuC,WAAvC;AACD;;AAED,UAAM,GAAG,GAAQ,EACf,GAAG,OAAO,CAAC,GADI;AAEf,MAAA,uBAAuB,EAAE;AAFV,KAAjB;;AAKA,QAAI,OAAO,CAAC,eAAZ,EAA6B;AAC3B,kCAAM,WAAN,EAAmB,EAAnB,EAAuB;AACrB,QAAA,QAAQ,EAAE,IADW;AAErB,QAAA,KAAK,EAAE,QAFc;AAGrB,QAAA;AAHqB,OAAvB,EAKG,KALH;AAMD,KAPD,MAQK;AACH,MAAA,GAAG,CAAC,2BAAJ,GAAkC,MAAlC;AACA,yCAAa,WAAb,EAA0B,EAA1B,EAA8B;AAAC,QAAA;AAAD,OAA9B;AACD;;AACD,WAAO,IAAP;AACD;;AA9G6C,C","sourcesContent":["import { AllPublishOptions, newError } from \"builder-util-runtime\"\nimport { execFileSync, spawn } from \"child_process\"\nimport { chmod } from \"fs-extra\"\nimport { unlinkSync } from \"fs\"\nimport * as path from \"path\"\nimport { DownloadUpdateOptions } from \"./AppUpdater\"\nimport { BaseUpdater, InstallOptions } from \"./BaseUpdater\"\nimport { DifferentialDownloaderOptions } from \"./differentialDownloader/DifferentialDownloader\"\nimport { FileWithEmbeddedBlockMapDifferentialDownloader } from \"./differentialDownloader/FileWithEmbeddedBlockMapDifferentialDownloader\"\nimport { DOWNLOAD_PROGRESS } from \"./main\"\nimport { findFile } from \"./providers/Provider\"\n\nexport class AppImageUpdater extends BaseUpdater {\n constructor(options?: AllPublishOptions | null, app?: any) {\n super(options, app)\n }\n\n public isUpdaterActive(): boolean {\n if (process.env.APPIMAGE == null) {\n if (process.env.SNAP == null) {\n this._logger.warn(\"APPIMAGE env is not defined, current application is not an AppImage\")\n }\n else {\n this._logger.info(\"SNAP env is defined, updater is disabled\")\n }\n return false\n }\n return super.isUpdaterActive()\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), \"AppImage\")!!\n return this.executeDownload({\n fileExtension: \"AppImage\",\n fileInfo,\n downloadUpdateOptions,\n task: async (updateFile, downloadOptions) => {\n const oldFile = process.env.APPIMAGE!!\n if (oldFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n let isDownloadFull = false\n try {\n const downloadOptions: DifferentialDownloaderOptions = {\n newUrl: fileInfo.url,\n oldFile,\n logger: this._logger,\n newFile: updateFile,\n isUseMultipleRangeRequest: provider.isUseMultipleRangeRequest,\n requestHeaders: downloadUpdateOptions.requestHeaders,\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(fileInfo.info, this.httpExecutor, downloadOptions)\n .download()\n }\n catch (e) {\n this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`)\n // during test (developer machine mac) we must throw error\n isDownloadFull = process.platform === \"linux\"\n }\n\n if (isDownloadFull) {\n await this.httpExecutor.download(fileInfo.url, updateFile, downloadOptions)\n }\n\n await chmod(updateFile, 0o755)\n },\n })\n }\n\n protected doInstall(options: InstallOptions): boolean {\n const appImageFile = process.env.APPIMAGE!!\n if (appImageFile == null) {\n throw newError(\"APPIMAGE env is not defined\", \"ERR_UPDATER_OLD_FILE_NOT_FOUND\")\n }\n\n // https://stackoverflow.com/a/1712051/1910191\n unlinkSync(appImageFile)\n\n let destination: string\n const existingBaseName = path.basename(appImageFile)\n // https://github.com/electron-userland/electron-builder/issues/2964\n // if no version in existing file name, it means that user wants to preserve current custom name\n if (path.basename(options.installerPath) === existingBaseName || !/\\d+\\.\\d+\\.\\d+/.test(existingBaseName)) {\n // no version in the file name, overwrite existing\n destination = appImageFile\n }\n else {\n destination = path.join(path.dirname(appImageFile), path.basename(options.installerPath))\n }\n\n execFileSync(\"mv\", [\"-f\", options.installerPath, destination])\n if (destination !== appImageFile) {\n this.emit('appimage-filename-updated', destination)\n }\n\n const env: any = {\n ...process.env,\n APPIMAGE_SILENT_INSTALL: \"true\",\n }\n\n if (options.isForceRunAfter) {\n spawn(destination, [], {\n detached: true,\n stdio: \"ignore\",\n env,\n })\n .unref()\n }\n else {\n env.APPIMAGE_EXIT_AFTER_INSTALL = \"true\"\n execFileSync(destination, [], {env})\n }\n return true\n }\n}\n"],"sourceRoot":""}
@@ -16,8 +16,6 @@ export declare abstract class AppUpdater extends EventEmitter {
16
16
  autoDownload: boolean;
17
17
  /**
18
18
  * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).
19
- *
20
- * Applicable only on Windows and Linux.
21
19
  */
22
20
  autoInstallOnAppQuit: boolean;
23
21
  /**
package/out/AppUpdater.js CHANGED
@@ -161,8 +161,6 @@ class AppUpdater extends _events().EventEmitter {
161
161
  this.autoDownload = true;
162
162
  /**
163
163
  * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).
164
- *
165
- * Applicable only on Windows and Linux.
166
164
  */
167
165
 
168
166
  this.autoInstallOnAppQuit = true;
@@ -599,7 +597,7 @@ class AppUpdater extends _events().EventEmitter {
599
597
  this._appUpdateConfigPath = this.app.appUpdateConfigPath;
600
598
  }
601
599
 
602
- return (0, _jsYaml().safeLoad)((await (0, _fsExtra().readFile)(this._appUpdateConfigPath, "utf-8")));
600
+ return (0, _jsYaml().load)(await (0, _fsExtra().readFile)(this._appUpdateConfigPath, "utf-8"));
603
601
  }
604
602
 
605
603
  computeRequestHeaders(provider) {
@@ -783,12 +781,12 @@ function hasPrereleaseComponents(version) {
783
781
 
784
782
  class NoOpLogger {
785
783
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
786
- info(message) {} // ignore
787
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
784
+ info(message) {// ignore
785
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
788
786
 
789
787
 
790
- warn(message) {} // ignore
791
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
788
+ warn(message) {// ignore
789
+ } // eslint-disable-next-line @typescript-eslint/no-unused-vars
792
790
 
793
791
 
794
792
  error(message) {// ignore
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/AppUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;;;;;AAIM,MAAgB,UAAhB,SAAmC,sBAAnC,CAA+C;AAmInD,EAAA,WAAA,CAAsB,OAAtB,EAAqE,GAArE,EAAqF;AACnF;AAnIF;;;;AAGA,SAAA,YAAA,GAAwB,IAAxB;AAEA;;;;;;AA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Error, PublishConfiguration, UpdateInfo, UUID, DownloadOptions, CancellationError } from \"builder-util-runtime\"\nimport { randomBytes } from \"crypto\"\nimport { Notification } from \"electron\"\nimport { EventEmitter } from \"events\"\nimport { ensureDir, outputFile, readFile, rename, unlink } from \"fs-extra\"\nimport { OutgoingHttpHeaders } from \"http\"\nimport { safeLoad } from \"js-yaml\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { eq as isVersionsEqual, gt as isVersionGreaterThan, lt as isVersionLessThan, parse as parseVersion, prerelease as getVersionPreleaseComponents, SemVer } from \"semver\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { createTempUpdateFile, DownloadedUpdateHelper } from \"./DownloadedUpdateHelper\"\nimport { ElectronAppAdapter } from \"./ElectronAppAdapter\"\nimport { ElectronHttpExecutor, getNetSession } from \"./electronHttpExecutor\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { DOWNLOAD_PROGRESS, Logger, Provider, ResolvedUpdateFileInfo, UPDATE_DOWNLOADED, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from \"./main\"\nimport { createClient, isUrlProbablySupportMultiRangeRequests } from \"./providerFactory\"\nimport { ProviderPlatform } from \"./providers/Provider\"\nimport Session = Electron.Session\n\nexport abstract class AppUpdater extends EventEmitter {\n /**\n * Whether to automatically download an update when it is found.\n */\n autoDownload: boolean = true\n\n /**\n * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).\n *\n * Applicable only on Windows and Linux.\n */\n autoInstallOnAppQuit: boolean = true\n\n /**\n * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.\n *\n * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).\n */\n allowPrerelease: boolean = false\n\n /**\n * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.\n * @default false\n */\n fullChangelog: boolean = false\n\n /**\n * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).\n *\n * Taken in account only if channel differs (pre-release version component in terms of semantic versioning).\n *\n * @default false\n */\n allowDowngrade: boolean = false\n\n /**\n * The current application version.\n */\n readonly currentVersion: SemVer\n\n private _channel: string | null = null\n\n protected downloadedUpdateHelper: DownloadedUpdateHelper | null = null\n\n /**\n * Get the update channel. Not applicable for GitHub. Doesn't return `channel` from the update configuration, only if was previously set.\n */\n get channel(): string | null {\n return this._channel\n }\n\n /**\n * Set the update channel. Not applicable for GitHub. Overrides `channel` in the update configuration.\n *\n * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.\n */\n set channel(value: string | null) {\n if (this._channel != null) {\n // noinspection SuspiciousTypeOfGuard\n if (typeof value !== \"string\") {\n throw newError(`Channel must be a string, but got: ${value}`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n else if (value.length === 0) {\n throw newError(`Channel must be not an empty string`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n }\n\n this._channel = value\n this.allowDowngrade = true\n }\n\n /**\n * The request headers.\n */\n requestHeaders: OutgoingHttpHeaders | null = null\n\n protected _logger: Logger = console\n\n // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n get netSession(): Session {\n return getNetSession()\n }\n\n /**\n * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.\n * Set it to `null` if you would like to disable a logging feature.\n */\n get logger(): Logger | null {\n return this._logger\n }\n\n set logger(value: Logger | null) {\n this._logger = value == null ? new NoOpLogger() : value\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`\n */\n readonly signals = new UpdaterSignal(this)\n\n private _appUpdateConfigPath: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * test only\n * @private\n */\n set updateConfigPath(value: string | null) {\n this.clientPromise = null\n this._appUpdateConfigPath = value\n this.configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n }\n\n private clientPromise: Promise<Provider<any>> | null = null\n\n protected readonly stagingUserIdPromise = new Lazy<string>(() => this.getOrCreateStagingUserId())\n\n // public, allow to read old config for anyone\n /** @internal */\n configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n\n private checkForUpdatesPromise: Promise<UpdateCheckResult> | null = null\n\n protected readonly app: AppAdapter\n\n protected updateInfoAndProvider: UpdateInfoAndProvider | null = null\n\n /** @internal */\n readonly httpExecutor: ElectronHttpExecutor\n\n protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter) {\n super()\n\n this.on(\"error\", (error: Error) => {\n this._logger.error(`Error: ${error.stack || error.message}`)\n })\n\n if (app == null) {\n this.app = new ElectronAppAdapter()\n this.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => this.emit(\"login\", authInfo, callback))\n }\n else {\n this.app = app\n this.httpExecutor = null as any\n }\n\n const currentVersionString = this.app.version\n const currentVersion = parseVersion(currentVersionString)\n if (currentVersion == null) {\n throw newError(`App version is not a valid semver version: \"${currentVersionString}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n this.currentVersion = currentVersion\n this.allowPrerelease = hasPrereleaseComponents(currentVersion)\n\n if (options != null) {\n this.setFeedURL(options)\n\n if (typeof options !== \"string\" && options.requestHeaders) {\n this.requestHeaders = options.requestHeaders\n }\n }\n }\n\n //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n getFeedURL(): string | null | undefined {\n return \"Deprecated. Do not use it.\"\n }\n\n /**\n * Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.\n * @param options If you want to override configuration in the `app-update.yml`.\n */\n setFeedURL(options: PublishConfiguration | AllPublishOptions | string) {\n const runtimeOptions = this.createProviderRuntimeOptions()\n // https://github.com/electron-userland/electron-builder/issues/1105\n let provider: Provider<any>\n if (typeof options === \"string\") {\n provider = new GenericProvider({provider: \"generic\", url: options}, this, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: isUrlProbablySupportMultiRangeRequests(options),\n })\n }\n else {\n provider = createClient(options, this, runtimeOptions)\n }\n this.clientPromise = Promise.resolve(provider)\n }\n\n /**\n * Asks the server whether there is an update.\n */\n checkForUpdates(): Promise<UpdateCheckResult> {\n let checkForUpdatesPromise = this.checkForUpdatesPromise\n if (checkForUpdatesPromise != null) {\n this._logger.info(\"Checking for update (already in progress)\")\n return checkForUpdatesPromise\n }\n\n const nullizePromise = () => this.checkForUpdatesPromise = null\n\n this._logger.info(\"Checking for update\")\n checkForUpdatesPromise = this.doCheckForUpdates()\n .then(it => {\n nullizePromise()\n return it\n })\n .catch(e => {\n nullizePromise()\n this.emit(\"error\", e, `Cannot check for updates: ${(e.stack || e).toString()}`)\n throw e\n })\n\n this.checkForUpdatesPromise = checkForUpdatesPromise\n return checkForUpdatesPromise\n }\n\n public isUpdaterActive(): boolean {\n if (!this.app.isPackaged) {\n this._logger.info(\"Skip checkForUpdatesAndNotify because application is not packed\")\n return false\n }\n return true\n }\n\n // noinspection JSUnusedGlobalSymbols\n checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise<UpdateCheckResult | null> {\n if (!this.isUpdaterActive()) {\n return Promise.resolve(null)\n }\n\n return this.checkForUpdates()\n .then(it => {\n const downloadPromise = it.downloadPromise\n if (downloadPromise == null) {\n const debug = this._logger.debug\n if (debug != null) {\n debug(\"checkForUpdatesAndNotify called, downloadPromise is null\")\n }\n return it\n }\n\n downloadPromise\n .then(() => {\n const notificationContent = this.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification);\n new Notification(notificationContent).show()\n })\n\n return it\n })\n }\n\n private formatDownloadNotification(version: string, appName: string, downloadNotification?: DownloadNotification): DownloadNotification {\n if (downloadNotification == null) {\n downloadNotification = {\n title: \"A new update is ready to install\",\n body: `{appName} version {version} has been downloaded and will be automatically installed on exit`\n }\n }\n downloadNotification = {\n title: downloadNotification.title.replace(\"{appName}\", appName).replace(\"{version}\", version),\n body: downloadNotification.body.replace(\"{appName}\", appName).replace(\"{version}\", version)\n }\n return downloadNotification;\n }\n\n private async isStagingMatch(updateInfo: UpdateInfo): Promise<boolean> {\n const rawStagingPercentage = updateInfo.stagingPercentage\n let stagingPercentage = rawStagingPercentage\n if (stagingPercentage == null) {\n return true\n }\n\n stagingPercentage = parseInt(stagingPercentage as any, 10)\n if (isNaN(stagingPercentage)) {\n this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`)\n return true\n }\n\n // convert from user 0-100 to internal 0-1\n stagingPercentage = stagingPercentage / 100\n\n const stagingUserId = await this.stagingUserIdPromise.value\n const val = UUID.parse(stagingUserId).readUInt32BE(12)\n const percentage = (val / 0xFFFFFFFF)\n this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`)\n return percentage < stagingPercentage\n }\n\n private computeFinalHeaders(headers: OutgoingHttpHeaders) {\n if (this.requestHeaders != null) {\n Object.assign(headers, this.requestHeaders)\n }\n return headers\n }\n\n private async isUpdateAvailable(updateInfo: UpdateInfo): Promise<boolean> {\n const latestVersion = parseVersion(updateInfo.version)\n if (latestVersion == null) {\n throw newError(`This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: \"${updateInfo.version}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n\n const currentVersion = this.currentVersion\n if (isVersionsEqual(latestVersion, currentVersion)) {\n return false\n }\n\n const isStagingMatch = await this.isStagingMatch(updateInfo)\n if (!isStagingMatch) {\n return false\n }\n\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797\n const isLatestVersionNewer = isVersionGreaterThan(latestVersion, currentVersion)\n const isLatestVersionOlder = isVersionLessThan(latestVersion, currentVersion)\n\n if (isLatestVersionNewer) {\n return true\n }\n return this.allowDowngrade && isLatestVersionOlder;\n }\n\n protected async getUpdateInfoAndProvider(): Promise<UpdateInfoAndProvider> {\n await this.app.whenReady()\n\n if (this.clientPromise == null) {\n this.clientPromise = this.configOnDisk.value.then(it => createClient(it, this, this.createProviderRuntimeOptions()))\n }\n\n const client = await this.clientPromise\n const stagingUserId = await this.stagingUserIdPromise.value\n client.setRequestHeaders(this.computeFinalHeaders({\"x-user-staging-id\": stagingUserId}))\n return {\n info: await client.getLatestVersion(),\n provider: client,\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n private createProviderRuntimeOptions() {\n return {\n isUseMultipleRangeRequest: true,\n platform: this._testOnlyOptions == null ? process.platform as ProviderPlatform : this._testOnlyOptions.platform,\n executor: this.httpExecutor,\n }\n }\n\n private async doCheckForUpdates(): Promise<UpdateCheckResult> {\n this.emit(\"checking-for-update\")\n\n const result = await this.getUpdateInfoAndProvider()\n const updateInfo = result.info\n if (!await this.isUpdateAvailable(updateInfo)) {\n this._logger.info(`Update for version ${this.currentVersion} is not available (latest version: ${updateInfo.version}, downgrade is ${this.allowDowngrade ? \"allowed\" : \"disallowed\"}).`)\n this.emit(\"update-not-available\", updateInfo)\n return {\n versionInfo: updateInfo,\n updateInfo,\n }\n }\n\n this.updateInfoAndProvider = result\n this.onUpdateAvailable(updateInfo)\n\n const cancellationToken = new CancellationToken()\n //noinspection ES6MissingAwait\n return {\n versionInfo: updateInfo,\n updateInfo,\n cancellationToken,\n downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null\n }\n }\n\n protected onUpdateAvailable(updateInfo: UpdateInfo): void {\n this._logger.info(`Found version ${updateInfo.version} (url: ${asArray(updateInfo.files).map(it => it.url).join(\", \")})`)\n this.emit(\"update-available\", updateInfo)\n }\n\n /**\n * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.\n * @returns {Promise<string>} Path to downloaded file.\n */\n downloadUpdate(cancellationToken: CancellationToken = new CancellationToken()): Promise<any> {\n const updateInfoAndProvider = this.updateInfoAndProvider\n if (updateInfoAndProvider == null) {\n const error = new Error(\"Please check update first\")\n this.dispatchError(error)\n return Promise.reject(error)\n }\n\n this._logger.info(`Downloading update from ${asArray(updateInfoAndProvider.info.files).map(it => it.url).join(\", \")}`)\n const errorHandler = (e: Error): Error => {\n // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159\n if (!(e instanceof CancellationError)) {\n try {\n this.dispatchError(e)\n }\n catch (nestedError) {\n this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`)\n }\n }\n\n return e\n }\n\n try {\n return this.doDownloadUpdate({\n updateInfoAndProvider,\n requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),\n cancellationToken,\n })\n .catch(e => {\n throw errorHandler(e)\n })\n }\n catch (e) {\n return Promise.reject(errorHandler(e))\n }\n }\n\n protected dispatchError(e: Error): void {\n this.emit(\"error\", e, (e.stack || e).toString())\n }\n\n protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void {\n this.emit(UPDATE_DOWNLOADED, event)\n }\n\n protected async abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>\n\n /**\n * Restarts the app and installs the update after it has been downloaded.\n * It should only be called after `update-downloaded` has been emitted.\n *\n * **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.\n * This is different from the normal quit event sequence.\n *\n * @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.\n * @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS. Ignored if `isSilent` is set to `false`.\n */\n abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void\n\n private async loadUpdateConfig(): Promise<any> {\n if (this._appUpdateConfigPath == null) {\n this._appUpdateConfigPath = this.app.appUpdateConfigPath\n }\n return safeLoad(await readFile(this._appUpdateConfigPath, \"utf-8\"))\n }\n\n private computeRequestHeaders(provider: Provider<any>): OutgoingHttpHeaders {\n const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders\n if (fileExtraDownloadHeaders != null) {\n const requestHeaders = this.requestHeaders\n return requestHeaders == null ? fileExtraDownloadHeaders : {\n ...fileExtraDownloadHeaders,\n ...requestHeaders,\n }\n }\n return this.computeFinalHeaders({accept: \"*/*\"})\n }\n\n private async getOrCreateStagingUserId(): Promise<string> {\n const file = path.join(this.app.userDataPath, \".updaterId\")\n try {\n const id = await readFile(file, \"utf-8\")\n if (UUID.check(id)) {\n return id\n }\n else {\n this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`)\n }\n }\n catch (e) {\n if (e.code !== \"ENOENT\") {\n this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)\n }\n }\n\n const id = UUID.v5(randomBytes(4096), UUID.OID)\n this._logger.info(`Generated new staging user ID: ${id}`)\n try {\n await outputFile(file, id)\n }\n catch (e) {\n this._logger.warn(`Couldn't write out staging user ID: ${e}`)\n }\n return id\n }\n\n /** @internal */\n get isAddNoCacheQuery(): boolean {\n const headers = this.requestHeaders\n // https://github.com/electron-userland/electron-builder/issues/3021\n if (headers == null) {\n return true\n }\n\n for (const headerName of Object.keys(headers)) {\n const s = headerName.toLowerCase()\n if (s === \"authorization\" || s === \"private-token\") {\n return false\n }\n }\n return true\n }\n\n /**\n * @private\n * @internal\n */\n _testOnlyOptions: TestOnlyUpdaterOptions | null = null\n\n private async getOrCreateDownloadHelper(): Promise<DownloadedUpdateHelper> {\n let result = this.downloadedUpdateHelper\n if (result == null) {\n const dirName = (await this.configOnDisk.value).updaterCacheDirName\n const logger = this._logger\n if (dirName == null) {\n logger.error(\"updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?\")\n }\n const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name)\n if (logger.debug != null) {\n logger.debug(`updater cache dir: ${cacheDir}`)\n }\n\n result = new DownloadedUpdateHelper(cacheDir)\n this.downloadedUpdateHelper = result\n }\n return result\n }\n\n protected async executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>> {\n const fileInfo = taskOptions.fileInfo\n const downloadOptions: DownloadOptions = {\n headers: taskOptions.downloadUpdateOptions.requestHeaders,\n cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,\n sha2: (fileInfo.info as any).sha2,\n sha512: fileInfo.info.sha512,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info\n const version = updateInfo.version\n const packageInfo = fileInfo.packageInfo\n\n function getCacheUpdateFileName(): string {\n // NodeJS URL doesn't decode automatically\n const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname)\n if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {\n return path.posix.basename(urlPath)\n }\n else {\n // url like /latest, generate name\n return `update.${taskOptions.fileExtension}`\n }\n }\n\n const downloadedUpdateHelper = await this.getOrCreateDownloadHelper()\n const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate\n await ensureDir(cacheDir)\n const updateFileName = getCacheUpdateFileName()\n let updateFile = path.join(cacheDir, updateFileName)\n const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || \".7z\"}`)\n\n const done = async (isSaveCache: boolean) => {\n await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache)\n await taskOptions.done!!({\n ...updateInfo,\n downloadedFile: updateFile,\n })\n return packageFile == null ? [updateFile] : [updateFile, packageFile]\n }\n\n const log = this._logger\n const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log)\n if (cachedUpdateFile != null) {\n updateFile = cachedUpdateFile\n return await done(false)\n }\n\n const removeFileIfAny = async () => {\n await downloadedUpdateHelper.clear()\n .catch(() => {\n // ignore\n })\n return await unlink(updateFile)\n .catch(() => {\n // ignore\n })\n }\n\n const tempUpdateFile = await createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log)\n try {\n await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny)\n await rename(tempUpdateFile, updateFile)\n }\n catch (e) {\n await removeFileIfAny()\n\n if (e instanceof CancellationError) {\n log.info(\"cancelled\")\n this.emit(\"update-cancelled\", updateInfo)\n }\n throw e\n }\n\n log.info(`New version ${version} has been downloaded to ${updateFile}`)\n return await done(true)\n }\n}\n\nexport interface DownloadUpdateOptions {\n readonly updateInfoAndProvider: UpdateInfoAndProvider\n readonly requestHeaders: OutgoingHttpHeaders\n readonly cancellationToken: CancellationToken\n}\n\nfunction hasPrereleaseComponents(version: SemVer) {\n const versionPrereleaseComponent = getVersionPreleaseComponents(version)\n return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0\n}\n\n/** @private */\nexport class NoOpLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n warn(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(message?: any) {\n // ignore\n }\n}\n\nexport interface UpdateInfoAndProvider {\n info: UpdateInfo\n provider: Provider<any>\n}\n\nexport interface DownloadExecutorTask {\n readonly fileExtension: string\n readonly fileInfo: ResolvedUpdateFileInfo\n readonly downloadUpdateOptions: DownloadUpdateOptions\n readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise<any>) => Promise<any>\n\n readonly done?: (event: UpdateDownloadedEvent) => Promise<any>\n}\n\nexport interface DownloadNotification {\n body: string\n title: string\n}\n\n/** @private */\nexport interface TestOnlyUpdaterOptions {\n platform: ProviderPlatform\n\n isUseDifferentialDownload?: boolean\n}\n"],"sourceRoot":""}
1
+ {"version":3,"sources":["../src/AppUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AA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B;;AAEA,UAAI,CAAC,YAAY,uCAAjB,EAAoC;AAClC,QAAA,GAAG,CAAC,IAAJ,CAAS,WAAT;AACA,aAAK,IAAL,CAAU,kBAAV,EAA8B,UAA9B;AACD;;AACD,YAAM,CAAN;AACD;;AAED,IAAA,GAAG,CAAC,IAAJ,CAAS,eAAe,OAAO,2BAA2B,UAAU,EAApE;AACA,WAAO,MAAM,IAAI,CAAC,IAAD,CAAjB;AACD;;AAnmBkD;;;;AA4mBrD,SAAS,uBAAT,CAAiC,OAAjC,EAAgD;AAC9C,QAAM,0BAA0B,GAAG,0BAA6B,OAA7B,CAAnC;AACA,SAAO,0BAA0B,IAAI,IAA9B,IAAsC,0BAA0B,CAAC,MAA3B,GAAoC,CAAjF;AACD;AAED;;;AACM,MAAO,UAAP,CAAiB;AACrB;AACA,EAAA,IAAI,CAAC,OAAD,EAAc,CAChB;AACD,GAJoB,CAMrB;;;AACA,EAAA,IAAI,CAAC,OAAD,EAAc,CAChB;AACD,GAToB,CAWrB;;;AACA,EAAA,KAAK,CAAC,OAAD,EAAc,CACjB;AACD;;AAdoB,C","sourcesContent":["import { AllPublishOptions, asArray, CancellationToken, newError, PublishConfiguration, UpdateInfo, UUID, DownloadOptions, CancellationError } from \"builder-util-runtime\"\nimport { randomBytes } from \"crypto\"\nimport { Notification } from \"electron\"\nimport { EventEmitter } from \"events\"\nimport { ensureDir, outputFile, readFile, rename, unlink } from \"fs-extra\"\nimport { OutgoingHttpHeaders } from \"http\"\nimport { load } from \"js-yaml\"\nimport { Lazy } from \"lazy-val\"\nimport * as path from \"path\"\nimport { eq as isVersionsEqual, gt as isVersionGreaterThan, lt as isVersionLessThan, parse as parseVersion, prerelease as getVersionPreleaseComponents, SemVer } from \"semver\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { createTempUpdateFile, DownloadedUpdateHelper } from \"./DownloadedUpdateHelper\"\nimport { ElectronAppAdapter } from \"./ElectronAppAdapter\"\nimport { ElectronHttpExecutor, getNetSession } from \"./electronHttpExecutor\"\nimport { GenericProvider } from \"./providers/GenericProvider\"\nimport { DOWNLOAD_PROGRESS, Logger, Provider, ResolvedUpdateFileInfo, UPDATE_DOWNLOADED, UpdateCheckResult, UpdateDownloadedEvent, UpdaterSignal } from \"./main\"\nimport { createClient, isUrlProbablySupportMultiRangeRequests } from \"./providerFactory\"\nimport { ProviderPlatform } from \"./providers/Provider\"\nimport Session = Electron.Session\n\nexport abstract class AppUpdater extends EventEmitter {\n /**\n * Whether to automatically download an update when it is found.\n */\n autoDownload: boolean = true\n\n /**\n * Whether to automatically install a downloaded update on app quit (if `quitAndInstall` was not called before).\n */\n autoInstallOnAppQuit: boolean = true\n\n /**\n * *GitHub provider only.* Whether to allow update to pre-release versions. Defaults to `true` if application version contains prerelease components (e.g. `0.12.1-alpha.1`, here `alpha` is a prerelease component), otherwise `false`.\n *\n * If `true`, downgrade will be allowed (`allowDowngrade` will be set to `true`).\n */\n allowPrerelease: boolean = false\n\n /**\n * *GitHub provider only.* Get all release notes (from current version to latest), not just the latest.\n * @default false\n */\n fullChangelog: boolean = false\n\n /**\n * Whether to allow version downgrade (when a user from the beta channel wants to go back to the stable channel).\n *\n * Taken in account only if channel differs (pre-release version component in terms of semantic versioning).\n *\n * @default false\n */\n allowDowngrade: boolean = false\n\n /**\n * The current application version.\n */\n readonly currentVersion: SemVer\n\n private _channel: string | null = null\n\n protected downloadedUpdateHelper: DownloadedUpdateHelper | null = null\n\n /**\n * Get the update channel. Not applicable for GitHub. Doesn't return `channel` from the update configuration, only if was previously set.\n */\n get channel(): string | null {\n return this._channel\n }\n\n /**\n * Set the update channel. Not applicable for GitHub. Overrides `channel` in the update configuration.\n *\n * `allowDowngrade` will be automatically set to `true`. If this behavior is not suitable for you, simple set `allowDowngrade` explicitly after.\n */\n set channel(value: string | null) {\n if (this._channel != null) {\n // noinspection SuspiciousTypeOfGuard\n if (typeof value !== \"string\") {\n throw newError(`Channel must be a string, but got: ${value}`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n else if (value.length === 0) {\n throw newError(`Channel must be not an empty string`, \"ERR_UPDATER_INVALID_CHANNEL\")\n }\n }\n\n this._channel = value\n this.allowDowngrade = true\n }\n\n /**\n * The request headers.\n */\n requestHeaders: OutgoingHttpHeaders | null = null\n\n protected _logger: Logger = console\n\n // noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n get netSession(): Session {\n return getNetSession()\n }\n\n /**\n * The logger. You can pass [electron-log](https://github.com/megahertz/electron-log), [winston](https://github.com/winstonjs/winston) or another logger with the following interface: `{ info(), warn(), error() }`.\n * Set it to `null` if you would like to disable a logging feature.\n */\n get logger(): Logger | null {\n return this._logger\n }\n\n set logger(value: Logger | null) {\n this._logger = value == null ? new NoOpLogger() : value\n }\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * For type safety you can use signals, e.g. `autoUpdater.signals.updateDownloaded(() => {})` instead of `autoUpdater.on('update-available', () => {})`\n */\n readonly signals = new UpdaterSignal(this)\n\n private _appUpdateConfigPath: string | null = null\n\n // noinspection JSUnusedGlobalSymbols\n /**\n * test only\n * @private\n */\n set updateConfigPath(value: string | null) {\n this.clientPromise = null\n this._appUpdateConfigPath = value\n this.configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n }\n\n private clientPromise: Promise<Provider<any>> | null = null\n\n protected readonly stagingUserIdPromise = new Lazy<string>(() => this.getOrCreateStagingUserId())\n\n // public, allow to read old config for anyone\n /** @internal */\n configOnDisk = new Lazy<any>(() => this.loadUpdateConfig())\n\n private checkForUpdatesPromise: Promise<UpdateCheckResult> | null = null\n\n protected readonly app: AppAdapter\n\n protected updateInfoAndProvider: UpdateInfoAndProvider | null = null\n\n /** @internal */\n readonly httpExecutor: ElectronHttpExecutor\n\n protected constructor(options: AllPublishOptions | null | undefined, app?: AppAdapter) {\n super()\n\n this.on(\"error\", (error: Error) => {\n this._logger.error(`Error: ${error.stack || error.message}`)\n })\n\n if (app == null) {\n this.app = new ElectronAppAdapter()\n this.httpExecutor = new ElectronHttpExecutor((authInfo, callback) => this.emit(\"login\", authInfo, callback))\n }\n else {\n this.app = app\n this.httpExecutor = null as any\n }\n\n const currentVersionString = this.app.version\n const currentVersion = parseVersion(currentVersionString)\n if (currentVersion == null) {\n throw newError(`App version is not a valid semver version: \"${currentVersionString}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n this.currentVersion = currentVersion\n this.allowPrerelease = hasPrereleaseComponents(currentVersion)\n\n if (options != null) {\n this.setFeedURL(options)\n\n if (typeof options !== \"string\" && options.requestHeaders) {\n this.requestHeaders = options.requestHeaders\n }\n }\n }\n\n //noinspection JSMethodCanBeStatic,JSUnusedGlobalSymbols\n getFeedURL(): string | null | undefined {\n return \"Deprecated. Do not use it.\"\n }\n\n /**\n * Configure update provider. If value is `string`, [GenericServerOptions](/configuration/publish#genericserveroptions) will be set with value as `url`.\n * @param options If you want to override configuration in the `app-update.yml`.\n */\n setFeedURL(options: PublishConfiguration | AllPublishOptions | string) {\n const runtimeOptions = this.createProviderRuntimeOptions()\n // https://github.com/electron-userland/electron-builder/issues/1105\n let provider: Provider<any>\n if (typeof options === \"string\") {\n provider = new GenericProvider({provider: \"generic\", url: options}, this, {\n ...runtimeOptions,\n isUseMultipleRangeRequest: isUrlProbablySupportMultiRangeRequests(options),\n })\n }\n else {\n provider = createClient(options, this, runtimeOptions)\n }\n this.clientPromise = Promise.resolve(provider)\n }\n\n /**\n * Asks the server whether there is an update.\n */\n checkForUpdates(): Promise<UpdateCheckResult> {\n let checkForUpdatesPromise = this.checkForUpdatesPromise\n if (checkForUpdatesPromise != null) {\n this._logger.info(\"Checking for update (already in progress)\")\n return checkForUpdatesPromise\n }\n\n const nullizePromise = () => this.checkForUpdatesPromise = null\n\n this._logger.info(\"Checking for update\")\n checkForUpdatesPromise = this.doCheckForUpdates()\n .then(it => {\n nullizePromise()\n return it\n })\n .catch(e => {\n nullizePromise()\n this.emit(\"error\", e, `Cannot check for updates: ${(e.stack || e).toString()}`)\n throw e\n })\n\n this.checkForUpdatesPromise = checkForUpdatesPromise\n return checkForUpdatesPromise\n }\n\n public isUpdaterActive(): boolean {\n if (!this.app.isPackaged) {\n this._logger.info(\"Skip checkForUpdatesAndNotify because application is not packed\")\n return false\n }\n return true\n }\n\n // noinspection JSUnusedGlobalSymbols\n checkForUpdatesAndNotify(downloadNotification?: DownloadNotification): Promise<UpdateCheckResult | null> {\n if (!this.isUpdaterActive()) {\n return Promise.resolve(null)\n }\n\n return this.checkForUpdates()\n .then(it => {\n const downloadPromise = it.downloadPromise\n if (downloadPromise == null) {\n const debug = this._logger.debug\n if (debug != null) {\n debug(\"checkForUpdatesAndNotify called, downloadPromise is null\")\n }\n return it\n }\n\n downloadPromise\n .then(() => {\n const notificationContent = this.formatDownloadNotification(it.updateInfo.version, this.app.name, downloadNotification);\n new Notification(notificationContent).show()\n })\n\n return it\n })\n }\n\n private formatDownloadNotification(version: string, appName: string, downloadNotification?: DownloadNotification): DownloadNotification {\n if (downloadNotification == null) {\n downloadNotification = {\n title: \"A new update is ready to install\",\n body: `{appName} version {version} has been downloaded and will be automatically installed on exit`\n }\n }\n downloadNotification = {\n title: downloadNotification.title.replace(\"{appName}\", appName).replace(\"{version}\", version),\n body: downloadNotification.body.replace(\"{appName}\", appName).replace(\"{version}\", version)\n }\n return downloadNotification;\n }\n\n private async isStagingMatch(updateInfo: UpdateInfo): Promise<boolean> {\n const rawStagingPercentage = updateInfo.stagingPercentage\n let stagingPercentage = rawStagingPercentage\n if (stagingPercentage == null) {\n return true\n }\n\n stagingPercentage = parseInt(stagingPercentage as any, 10)\n if (isNaN(stagingPercentage)) {\n this._logger.warn(`Staging percentage is NaN: ${rawStagingPercentage}`)\n return true\n }\n\n // convert from user 0-100 to internal 0-1\n stagingPercentage = stagingPercentage / 100\n\n const stagingUserId = await this.stagingUserIdPromise.value\n const val = UUID.parse(stagingUserId).readUInt32BE(12)\n const percentage = (val / 0xFFFFFFFF)\n this._logger.info(`Staging percentage: ${stagingPercentage}, percentage: ${percentage}, user id: ${stagingUserId}`)\n return percentage < stagingPercentage\n }\n\n private computeFinalHeaders(headers: OutgoingHttpHeaders) {\n if (this.requestHeaders != null) {\n Object.assign(headers, this.requestHeaders)\n }\n return headers\n }\n\n private async isUpdateAvailable(updateInfo: UpdateInfo): Promise<boolean> {\n const latestVersion = parseVersion(updateInfo.version)\n if (latestVersion == null) {\n throw newError(`This file could not be downloaded, or the latest version (from update server) does not have a valid semver version: \"${updateInfo.version}\"`, \"ERR_UPDATER_INVALID_VERSION\")\n }\n\n const currentVersion = this.currentVersion\n if (isVersionsEqual(latestVersion, currentVersion)) {\n return false\n }\n\n const isStagingMatch = await this.isStagingMatch(updateInfo)\n if (!isStagingMatch) {\n return false\n }\n\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405033227\n // https://github.com/electron-userland/electron-builder/pull/3111#issuecomment-405030797\n const isLatestVersionNewer = isVersionGreaterThan(latestVersion, currentVersion)\n const isLatestVersionOlder = isVersionLessThan(latestVersion, currentVersion)\n\n if (isLatestVersionNewer) {\n return true\n }\n return this.allowDowngrade && isLatestVersionOlder;\n }\n\n protected async getUpdateInfoAndProvider(): Promise<UpdateInfoAndProvider> {\n await this.app.whenReady()\n\n if (this.clientPromise == null) {\n this.clientPromise = this.configOnDisk.value.then(it => createClient(it, this, this.createProviderRuntimeOptions()))\n }\n\n const client = await this.clientPromise\n const stagingUserId = await this.stagingUserIdPromise.value\n client.setRequestHeaders(this.computeFinalHeaders({\"x-user-staging-id\": stagingUserId}))\n return {\n info: await client.getLatestVersion(),\n provider: client,\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/explicit-function-return-type\n private createProviderRuntimeOptions() {\n return {\n isUseMultipleRangeRequest: true,\n platform: this._testOnlyOptions == null ? process.platform as ProviderPlatform : this._testOnlyOptions.platform,\n executor: this.httpExecutor,\n }\n }\n\n private async doCheckForUpdates(): Promise<UpdateCheckResult> {\n this.emit(\"checking-for-update\")\n\n const result = await this.getUpdateInfoAndProvider()\n const updateInfo = result.info\n if (!await this.isUpdateAvailable(updateInfo)) {\n this._logger.info(`Update for version ${this.currentVersion} is not available (latest version: ${updateInfo.version}, downgrade is ${this.allowDowngrade ? \"allowed\" : \"disallowed\"}).`)\n this.emit(\"update-not-available\", updateInfo)\n return {\n versionInfo: updateInfo,\n updateInfo,\n }\n }\n\n this.updateInfoAndProvider = result\n this.onUpdateAvailable(updateInfo)\n\n const cancellationToken = new CancellationToken()\n //noinspection ES6MissingAwait\n return {\n versionInfo: updateInfo,\n updateInfo,\n cancellationToken,\n downloadPromise: this.autoDownload ? this.downloadUpdate(cancellationToken) : null\n }\n }\n\n protected onUpdateAvailable(updateInfo: UpdateInfo): void {\n this._logger.info(`Found version ${updateInfo.version} (url: ${asArray(updateInfo.files).map(it => it.url).join(\", \")})`)\n this.emit(\"update-available\", updateInfo)\n }\n\n /**\n * Start downloading update manually. You can use this method if `autoDownload` option is set to `false`.\n * @returns {Promise<string>} Path to downloaded file.\n */\n downloadUpdate(cancellationToken: CancellationToken = new CancellationToken()): Promise<any> {\n const updateInfoAndProvider = this.updateInfoAndProvider\n if (updateInfoAndProvider == null) {\n const error = new Error(\"Please check update first\")\n this.dispatchError(error)\n return Promise.reject(error)\n }\n\n this._logger.info(`Downloading update from ${asArray(updateInfoAndProvider.info.files).map(it => it.url).join(\", \")}`)\n const errorHandler = (e: Error): Error => {\n // https://github.com/electron-userland/electron-builder/issues/1150#issuecomment-436891159\n if (!(e instanceof CancellationError)) {\n try {\n this.dispatchError(e)\n }\n catch (nestedError) {\n this._logger.warn(`Cannot dispatch error event: ${nestedError.stack || nestedError}`)\n }\n }\n\n return e\n }\n\n try {\n return this.doDownloadUpdate({\n updateInfoAndProvider,\n requestHeaders: this.computeRequestHeaders(updateInfoAndProvider.provider),\n cancellationToken,\n })\n .catch(e => {\n throw errorHandler(e)\n })\n }\n catch (e) {\n return Promise.reject(errorHandler(e))\n }\n }\n\n protected dispatchError(e: Error): void {\n this.emit(\"error\", e, (e.stack || e).toString())\n }\n\n protected dispatchUpdateDownloaded(event: UpdateDownloadedEvent): void {\n this.emit(UPDATE_DOWNLOADED, event)\n }\n\n protected abstract doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>\n\n /**\n * Restarts the app and installs the update after it has been downloaded.\n * It should only be called after `update-downloaded` has been emitted.\n *\n * **Note:** `autoUpdater.quitAndInstall()` will close all application windows first and only emit `before-quit` event on `app` after that.\n * This is different from the normal quit event sequence.\n *\n * @param isSilent *windows-only* Runs the installer in silent mode. Defaults to `false`.\n * @param isForceRunAfter Run the app after finish even on silent install. Not applicable for macOS. Ignored if `isSilent` is set to `false`.\n */\n abstract quitAndInstall(isSilent?: boolean, isForceRunAfter?: boolean): void\n\n private async loadUpdateConfig(): Promise<any> {\n if (this._appUpdateConfigPath == null) {\n this._appUpdateConfigPath = this.app.appUpdateConfigPath\n }\n return load(await readFile(this._appUpdateConfigPath, \"utf-8\"))\n }\n\n private computeRequestHeaders(provider: Provider<any>): OutgoingHttpHeaders {\n const fileExtraDownloadHeaders = provider.fileExtraDownloadHeaders\n if (fileExtraDownloadHeaders != null) {\n const requestHeaders = this.requestHeaders\n return requestHeaders == null ? fileExtraDownloadHeaders : {\n ...fileExtraDownloadHeaders,\n ...requestHeaders,\n }\n }\n return this.computeFinalHeaders({accept: \"*/*\"})\n }\n\n private async getOrCreateStagingUserId(): Promise<string> {\n const file = path.join(this.app.userDataPath, \".updaterId\")\n try {\n const id = await readFile(file, \"utf-8\")\n if (UUID.check(id)) {\n return id\n }\n else {\n this._logger.warn(`Staging user id file exists, but content was invalid: ${id}`)\n }\n }\n catch (e) {\n if (e.code !== \"ENOENT\") {\n this._logger.warn(`Couldn't read staging user ID, creating a blank one: ${e}`)\n }\n }\n\n const id = UUID.v5(randomBytes(4096), UUID.OID)\n this._logger.info(`Generated new staging user ID: ${id}`)\n try {\n await outputFile(file, id)\n }\n catch (e) {\n this._logger.warn(`Couldn't write out staging user ID: ${e}`)\n }\n return id\n }\n\n /** @internal */\n get isAddNoCacheQuery(): boolean {\n const headers = this.requestHeaders\n // https://github.com/electron-userland/electron-builder/issues/3021\n if (headers == null) {\n return true\n }\n\n for (const headerName of Object.keys(headers)) {\n const s = headerName.toLowerCase()\n if (s === \"authorization\" || s === \"private-token\") {\n return false\n }\n }\n return true\n }\n\n /**\n * @private\n * @internal\n */\n _testOnlyOptions: TestOnlyUpdaterOptions | null = null\n\n private async getOrCreateDownloadHelper(): Promise<DownloadedUpdateHelper> {\n let result = this.downloadedUpdateHelper\n if (result == null) {\n const dirName = (await this.configOnDisk.value).updaterCacheDirName\n const logger = this._logger\n if (dirName == null) {\n logger.error(\"updaterCacheDirName is not specified in app-update.yml Was app build using at least electron-builder 20.34.0?\")\n }\n const cacheDir = path.join(this.app.baseCachePath, dirName || this.app.name)\n if (logger.debug != null) {\n logger.debug(`updater cache dir: ${cacheDir}`)\n }\n\n result = new DownloadedUpdateHelper(cacheDir)\n this.downloadedUpdateHelper = result\n }\n return result\n }\n\n protected async executeDownload(taskOptions: DownloadExecutorTask): Promise<Array<string>> {\n const fileInfo = taskOptions.fileInfo\n const downloadOptions: DownloadOptions = {\n headers: taskOptions.downloadUpdateOptions.requestHeaders,\n cancellationToken: taskOptions.downloadUpdateOptions.cancellationToken,\n sha2: (fileInfo.info as any).sha2,\n sha512: fileInfo.info.sha512,\n }\n\n if (this.listenerCount(DOWNLOAD_PROGRESS) > 0) {\n downloadOptions.onProgress = it => this.emit(DOWNLOAD_PROGRESS, it)\n }\n\n const updateInfo = taskOptions.downloadUpdateOptions.updateInfoAndProvider.info\n const version = updateInfo.version\n const packageInfo = fileInfo.packageInfo\n\n function getCacheUpdateFileName(): string {\n // NodeJS URL doesn't decode automatically\n const urlPath = decodeURIComponent(taskOptions.fileInfo.url.pathname)\n if (urlPath.endsWith(`.${taskOptions.fileExtension}`)) {\n return path.posix.basename(urlPath)\n }\n else {\n // url like /latest, generate name\n return `update.${taskOptions.fileExtension}`\n }\n }\n\n const downloadedUpdateHelper = await this.getOrCreateDownloadHelper()\n const cacheDir = downloadedUpdateHelper.cacheDirForPendingUpdate\n await ensureDir(cacheDir)\n const updateFileName = getCacheUpdateFileName()\n let updateFile = path.join(cacheDir, updateFileName)\n const packageFile = packageInfo == null ? null : path.join(cacheDir, `package-${version}${path.extname(packageInfo.path) || \".7z\"}`)\n\n const done = async (isSaveCache: boolean) => {\n await downloadedUpdateHelper.setDownloadedFile(updateFile, packageFile, updateInfo, fileInfo, updateFileName, isSaveCache)\n await taskOptions.done!!({\n ...updateInfo,\n downloadedFile: updateFile,\n })\n return packageFile == null ? [updateFile] : [updateFile, packageFile]\n }\n\n const log = this._logger\n const cachedUpdateFile = await downloadedUpdateHelper.validateDownloadedPath(updateFile, updateInfo, fileInfo, log)\n if (cachedUpdateFile != null) {\n updateFile = cachedUpdateFile\n return await done(false)\n }\n\n const removeFileIfAny = async () => {\n await downloadedUpdateHelper.clear()\n .catch(() => {\n // ignore\n })\n return await unlink(updateFile)\n .catch(() => {\n // ignore\n })\n }\n\n const tempUpdateFile = await createTempUpdateFile(`temp-${updateFileName}`, cacheDir, log)\n try {\n await taskOptions.task(tempUpdateFile, downloadOptions, packageFile, removeFileIfAny)\n await rename(tempUpdateFile, updateFile)\n }\n catch (e) {\n await removeFileIfAny()\n\n if (e instanceof CancellationError) {\n log.info(\"cancelled\")\n this.emit(\"update-cancelled\", updateInfo)\n }\n throw e\n }\n\n log.info(`New version ${version} has been downloaded to ${updateFile}`)\n return await done(true)\n }\n}\n\nexport interface DownloadUpdateOptions {\n readonly updateInfoAndProvider: UpdateInfoAndProvider\n readonly requestHeaders: OutgoingHttpHeaders\n readonly cancellationToken: CancellationToken\n}\n\nfunction hasPrereleaseComponents(version: SemVer) {\n const versionPrereleaseComponent = getVersionPreleaseComponents(version)\n return versionPrereleaseComponent != null && versionPrereleaseComponent.length > 0\n}\n\n/** @private */\nexport class NoOpLogger implements Logger {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n info(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n warn(message?: any) {\n // ignore\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n error(message?: any) {\n // ignore\n }\n}\n\nexport interface UpdateInfoAndProvider {\n info: UpdateInfo\n provider: Provider<any>\n}\n\nexport interface DownloadExecutorTask {\n readonly fileExtension: string\n readonly fileInfo: ResolvedUpdateFileInfo\n readonly downloadUpdateOptions: DownloadUpdateOptions\n readonly task: (destinationFile: string, downloadOptions: DownloadOptions, packageFile: string | null, removeTempDirIfAny: () => Promise<any>) => Promise<any>\n\n readonly done?: (event: UpdateDownloadedEvent) => Promise<any>\n}\n\nexport interface DownloadNotification {\n body: string\n title: string\n}\n\n/** @private */\nexport interface TestOnlyUpdaterOptions {\n platform: ProviderPlatform\n\n isUseDifferentialDownload?: boolean\n}\n"],"sourceRoot":""}
@@ -177,8 +177,7 @@ class DownloadedUpdateHelper {
177
177
  const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName);
178
178
 
179
179
  if (!(await (0, _fsExtra().pathExists)(updateFile))) {
180
- logger.info("Cached update file doesn't exist, directory for cached update will be cleaned");
181
- await this.cleanCacheDirForPendingUpdate();
180
+ logger.info("Cached update file doesn't exist");
182
181
  return null;
183
182
  }
184
183
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/DownloadedUpdateHelper.ts"],"names":[],"mappings":";;;;;;;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;;;;;;;AAEA;AACM,MAAO,sBAAP,CAA6B;AAOjC,EAAA,WAAA,CAAqB,QAArB,EAAqC;AAAhB,SAAA,QAAA,GAAA,QAAA;AANb,SAAA,KAAA,GAAuB,IAAvB;AACA,SAAA,YAAA,GAA8B,IAA9B;AAEA,SAAA,WAAA,GAAiC,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I,CAAC,IAAL,CAAU,QAAV,EAAoB,GAAG,WAAW,EAAE,IAAI,IAAI,EAA5C,CAAT;AACD;AACF;;AACD,SAAO,MAAP;AACD,C","sourcesContent":["import { UpdateInfo } from \"builder-util-runtime\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\nimport isEqual from \"lodash.isequal\"\nimport { Logger, ResolvedUpdateFileInfo } from \"./main\"\nimport { pathExists, readJson, emptyDir, outputJson, unlink, pathExistsSync } 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\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 }\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(downloadedFile: string, packageFile: string | null, versionInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, updateFileName: string, isSaveCache: boolean): 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 }\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 pathExistsSync(updateInfoFilePath);\n if(!doesUpdateInfoFileExist) {\n return null;\n }\n\n\n let cachedInfo: CachedUpdateInfo\n try {\n cachedInfo = await readJson(updateInfoFilePath)\n }\n catch (error) {\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(`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 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, directory for cached update will be cleaned\")\n await this.cleanCacheDirForPendingUpdate()\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\n .on(\"error\", reject)\n .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 }\n catch (e) {\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"],"sourceRoot":""}
1
+ {"version":3,"sources":["../src/DownloadedUpdateHelper.ts"],"names":[],"mappings":";;;;;;;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;A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C,EAAxB,EAA4B;AAC1B,QAAI;AACF,YAAM,uBAAO,MAAP,CAAN;AACA,aAAO,MAAP;AACD,KAHD,CAIA,OAAO,CAAP,EAAU;AACR,UAAI,CAAC,CAAC,IAAF,KAAW,QAAf,EAAyB;AACvB,eAAO,MAAP;AACD;;AAED,MAAA,GAAG,CAAC,IAAJ,CAAS,qCAAqC,CAAC,EAA/C;AACA,MAAA,MAAM,GAAG,IAAI,CAAC,IAAL,CAAU,QAAV,EAAoB,GAAG,WAAW,EAAE,IAAI,IAAI,EAA5C,CAAT;AACD;AACF;;AACD,SAAO,MAAP;AACD,C","sourcesContent":["import { UpdateInfo } from \"builder-util-runtime\"\nimport { createHash } from \"crypto\"\nimport { createReadStream } from \"fs\"\nimport isEqual from \"lodash.isequal\"\nimport { Logger, ResolvedUpdateFileInfo } from \"./main\"\nimport { pathExists, readJson, emptyDir, outputJson, unlink, pathExistsSync } 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\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 }\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(downloadedFile: string, packageFile: string | null, versionInfo: UpdateInfo, fileInfo: ResolvedUpdateFileInfo, updateFileName: string, isSaveCache: boolean): 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 }\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 pathExistsSync(updateInfoFilePath);\n if(!doesUpdateInfoFileExist) {\n return null;\n }\n\n\n let cachedInfo: CachedUpdateInfo\n try {\n cachedInfo = await readJson(updateInfoFilePath)\n }\n catch (error) {\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(`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 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\n .on(\"error\", reject)\n .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 }\n catch (e) {\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"],"sourceRoot":""}
@@ -3,7 +3,7 @@ import { AppAdapter } from "./AppAdapter";
3
3
  import { AppUpdater, DownloadUpdateOptions } from "./AppUpdater";
4
4
  export declare class MacUpdater extends AppUpdater {
5
5
  private readonly nativeUpdater;
6
- private updateInfoForPendingUpdateDownloadedEvent;
6
+ private squirrelDownloadedUpdate;
7
7
  constructor(options?: AllPublishOptions, app?: AppAdapter);
8
8
  protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>>;
9
9
  quitAndInstall(): void;
package/out/MacUpdater.js CHANGED
@@ -61,22 +61,26 @@ class MacUpdater extends _AppUpdater().AppUpdater {
61
61
  constructor(options, app) {
62
62
  super(options, app);
63
63
  this.nativeUpdater = require("electron").autoUpdater;
64
- this.updateInfoForPendingUpdateDownloadedEvent = null;
64
+ this.squirrelDownloadedUpdate = false;
65
65
  this.nativeUpdater.on("error", it => {
66
66
  this._logger.warn(it);
67
67
 
68
68
  this.emit("error", it);
69
69
  });
70
70
  this.nativeUpdater.on("update-downloaded", () => {
71
- const updateInfo = this.updateInfoForPendingUpdateDownloadedEvent;
72
- this.updateInfoForPendingUpdateDownloadedEvent = null;
73
- this.dispatchUpdateDownloaded(updateInfo);
71
+ this.squirrelDownloadedUpdate = true;
74
72
  });
75
73
  }
76
74
 
77
75
  doDownloadUpdate(downloadUpdateOptions) {
78
- this.updateInfoForPendingUpdateDownloadedEvent = null;
79
- const files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info);
76
+ let files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info); // Allow arm64 macs to install universal or rosetta2(x64) - https://github.com/electron-userland/electron-builder/pull/5524
77
+
78
+ const isArm64 = file => file.url.pathname.includes("arm64");
79
+
80
+ if (files.some(isArm64)) {
81
+ files = files.filter(file => process.arch === "arm64" === isArm64(file));
82
+ }
83
+
80
84
  const zipFileInfo = (0, _Provider().findFile)(files, "zip", ["pkg", "dmg"]);
81
85
 
82
86
  if (zipFileInfo == null) {
@@ -102,7 +106,6 @@ class MacUpdater extends _AppUpdater().AppUpdater {
102
106
  },
103
107
  done: async event => {
104
108
  const downloadedFile = event.downloadedFile;
105
- this.updateInfoForPendingUpdateDownloadedEvent = event;
106
109
  let updateFileSize = zipFileInfo.info.size;
107
110
 
108
111
  if (updateFileSize == null) {
@@ -173,8 +176,14 @@ class MacUpdater extends _AppUpdater().AppUpdater {
173
176
  "Cache-Control": "no-cache"
174
177
  }
175
178
  });
176
- this.nativeUpdater.once("error", reject);
177
- this.nativeUpdater.checkForUpdates();
179
+ this.nativeUpdater.once("error", reject); // The update has been dowloaded and is ready to be served to Squirrel
180
+
181
+ this.dispatchUpdateDownloaded(event);
182
+
183
+ if (this.autoInstallOnAppQuit) {
184
+ // This will trigger fetching and installing the file on Squirrel side
185
+ this.nativeUpdater.checkForUpdates();
186
+ }
178
187
  });
179
188
  });
180
189
  }
@@ -182,7 +191,17 @@ class MacUpdater extends _AppUpdater().AppUpdater {
182
191
  }
183
192
 
184
193
  quitAndInstall() {
185
- this.nativeUpdater.quitAndInstall();
194
+ if (this.squirrelDownloadedUpdate) {
195
+ // Update already fetched by Squirrel, it's ready to install
196
+ this.nativeUpdater.quitAndInstall();
197
+ } else {
198
+ // Quit and install as soon as Squirrel get the update
199
+ this.nativeUpdater.on("update-downloaded", () => {
200
+ this.nativeUpdater.quitAndInstall();
201
+ }); // And trigger the update
202
+
203
+ this.nativeUpdater.checkForUpdates();
204
+ }
186
205
  }
187
206
 
188
207
  } exports.MacUpdater = MacUpdater;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/MacUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;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kC,OAAlC,EAA2C,MAA3C;AACA,cAAA,MAAM,CAAC,IAAI,KAAJ,CAAU,gBAAgB,cAAc,MAAM,KAAK,EAAnD,CAAD,CAAN;AACD,aAVD;AAYA,YAAA,QAAQ,CAAC,SAAT,CAAmB,GAAnB,EAAwB;AACtB,8BAAgB,iBADM;AAEtB,gCAAkB;AAFI,aAAxB;AAIA,YAAA,UAAU,CAAC,IAAX,CAAgB,QAAhB;AACD,WAlDD;AAmDA,UAAA,MAAM,CAAC,MAAP,CAAc,CAAd,EAAiB,WAAjB,EAA8B,MAAK;AACjC,iBAAK,aAAL,CAAmB,UAAnB,CAA8B;AAC5B,cAAA,GAAG,EAAE,YAAY,EADW;AAE5B,cAAA,OAAO,EAAE;AAAC,iCAAiB;AAAlB;AAFmB,aAA9B;AAKA,iBAAK,aAAL,CAAmB,IAAnB,CAAwB,OAAxB,EAAiC,MAAjC;AACA,iBAAK,aAAL,CAAmB,eAAnB;AACD,WARD;AASD,SA/DY,CAAb;AAgED;AA/EyB,KAArB,CAAP;AAiFD;;AAED,EAAA,cAAc,GAAA;AACZ,SAAK,aAAL,CAAmB,cAAnB;AACD;;AA3HuC,C","sourcesContent":["import { AllPublishOptions, newError, safeStringifyJson } from \"builder-util-runtime\"\nimport { stat } from \"fs-extra\"\nimport { createReadStream } from \"fs\"\nimport { createServer, IncomingMessage, ServerResponse } from \"http\"\nimport { AddressInfo } from \"net\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { AppUpdater, DownloadUpdateOptions } from \"./AppUpdater\"\nimport { UpdateDownloadedEvent } from \"./main\"\nimport { findFile } from \"./providers/Provider\"\nimport AutoUpdater = Electron.AutoUpdater\n\nexport class MacUpdater extends AppUpdater {\n private readonly nativeUpdater: AutoUpdater = require(\"electron\").autoUpdater\n\n private updateInfoForPendingUpdateDownloadedEvent: UpdateDownloadedEvent | null = null\n\n constructor(options?: AllPublishOptions, app?: AppAdapter) {\n super(options, app)\n\n this.nativeUpdater.on(\"error\", it => {\n this._logger.warn(it)\n this.emit(\"error\", it)\n })\n this.nativeUpdater.on(\"update-downloaded\", () => {\n const updateInfo = this.updateInfoForPendingUpdateDownloadedEvent\n this.updateInfoForPendingUpdateDownloadedEvent = null\n this.dispatchUpdateDownloaded(updateInfo!!)\n })\n }\n\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>> {\n this.updateInfoForPendingUpdateDownloadedEvent = null\n\n const files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info)\n const zipFileInfo = findFile(files, \"zip\", [\"pkg\", \"dmg\"])\n if (zipFileInfo == null) {\n throw newError(`ZIP file not provided: ${safeStringifyJson(files)}`, \"ERR_UPDATER_ZIP_FILE_NOT_FOUND\")\n }\n\n const server = createServer()\n server.on(\"close\", () => {\n this._logger.info(`Proxy server for native Squirrel.Mac is closed (was started to download ${zipFileInfo.url.href})`)\n })\n\n function getServerUrl(): string {\n const address = server.address() as AddressInfo\n return `http://127.0.0.1:${address.port}`\n }\n\n return this.executeDownload({\n fileExtension: \"zip\",\n fileInfo: zipFileInfo,\n downloadUpdateOptions,\n task: (destinationFile, downloadOptions) => {\n return this.httpExecutor.download(zipFileInfo.url, destinationFile, downloadOptions)\n },\n done: async event => {\n const downloadedFile = event.downloadedFile\n this.updateInfoForPendingUpdateDownloadedEvent = event\n let updateFileSize = zipFileInfo.info.size\n if (updateFileSize == null) {\n updateFileSize = (await stat(downloadedFile)).size\n }\n\n return await new Promise<Array<string>>((resolve, reject) => {\n // insecure random is ok\n const fileUrl = \"/\" + Date.now() + \"-\" + Math.floor(Math.random() * 9999) + \".zip\"\n server.on(\"request\", (request: IncomingMessage, response: ServerResponse) => {\n const requestUrl = request.url!!\n this._logger.info(`${requestUrl} requested`)\n if (requestUrl === \"/\") {\n const data = Buffer.from(`{ \"url\": \"${getServerUrl()}${fileUrl}\" }`)\n response.writeHead(200, {\"Content-Type\": \"application/json\", \"Content-Length\": data.length})\n response.end(data)\n return\n }\n\n if (!requestUrl.startsWith(fileUrl)) {\n this._logger.warn(`${requestUrl} requested, but not supported`)\n response.writeHead(404)\n response.end()\n return\n }\n\n this._logger.info(`${fileUrl} requested by Squirrel.Mac, pipe ${downloadedFile}`)\n\n let errorOccurred = false\n response.on(\"finish\", () => {\n try {\n setImmediate(() => server.close())\n }\n finally {\n if (!errorOccurred) {\n this.nativeUpdater.removeListener(\"error\", reject)\n resolve([])\n }\n }\n })\n\n const readStream = createReadStream(downloadedFile)\n readStream.on(\"error\", error => {\n try {\n response.end()\n }\n catch (e) {\n this._logger.warn(`cannot end response: ${e}`)\n }\n errorOccurred = true\n this.nativeUpdater.removeListener(\"error\", reject)\n reject(new Error(`Cannot pipe \"${downloadedFile}\": ${error}`))\n })\n\n response.writeHead(200, {\n \"Content-Type\": \"application/zip\",\n \"Content-Length\": updateFileSize,\n })\n readStream.pipe(response)\n })\n server.listen(0, \"127.0.0.1\", () => {\n this.nativeUpdater.setFeedURL({\n url: getServerUrl(),\n headers: {\"Cache-Control\": \"no-cache\"},\n })\n\n this.nativeUpdater.once(\"error\", reject)\n this.nativeUpdater.checkForUpdates()\n })\n })\n }\n })\n }\n\n quitAndInstall(): void {\n this.nativeUpdater.quitAndInstall()\n }\n}"],"sourceRoot":""}
1
+ {"version":3,"sources":["../src/MacUpdater.ts"],"names":[],"mappings":";;;;;;;AAAA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AACA;;AACA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAEA;AAAA;;AAAA;AAAA;AAAA;;AAAA;AAAA;;AAGM,MAAO,UAAP,SAA0B,wBAA1B,CAAoC;AAKxC,EAAA,WAAA,CAAY,OAAZ,EAAyC,GAAzC,EAAyD;AACvD,UAAM,OAAN,EAAe,GAAf;AALe,SAAA,aAAA,GAA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AC,SAAT,CAAmB,GAAnB,EAAwB;AACtB,8BAAgB,iBADM;AAEtB,gCAAkB;AAFI,aAAxB;AAIA,YAAA,UAAU,CAAC,IAAX,CAAgB,QAAhB;AACD,WAlDD;AAmDA,UAAA,MAAM,CAAC,MAAP,CAAc,CAAd,EAAiB,WAAjB,EAA8B,MAAK;AACjC,iBAAK,aAAL,CAAmB,UAAnB,CAA8B;AAC5B,cAAA,GAAG,EAAE,YAAY,EADW;AAE5B,cAAA,OAAO,EAAE;AAAC,iCAAiB;AAAlB;AAFmB,aAA9B;AAKA,iBAAK,aAAL,CAAmB,IAAnB,CAAwB,OAAxB,EAAiC,MAAjC,EANiC,CAQjC;;AACA,iBAAK,wBAAL,CAA8B,KAA9B;;AAEA,gBAAI,KAAK,oBAAT,EAA+B;AAC7B;AACA,mBAAK,aAAL,CAAmB,eAAnB;AACD;AACF,WAfD;AAgBD,SAtEY,CAAb;AAuED;AArFyB,KAArB,CAAP;AAuFD;;AAED,EAAA,cAAc,GAAA;AACZ,QAAI,KAAK,wBAAT,EAAmC;AACjC;AACA,WAAK,aAAL,CAAmB,cAAnB;AACD,KAHD,MAGO;AACL;AACA,WAAK,aAAL,CAAmB,EAAnB,CAAsB,mBAAtB,EAA2C,MAAK;AAC9C,aAAK,aAAL,CAAmB,cAAnB;AACD,OAFD,EAFK,CAML;;AACA,WAAK,aAAL,CAAmB,eAAnB;AACD;AACF;;AA/IuC,C","sourcesContent":["import { AllPublishOptions, newError, safeStringifyJson } from \"builder-util-runtime\"\nimport { stat } from \"fs-extra\"\nimport { createReadStream } from \"fs\"\nimport { createServer, IncomingMessage, ServerResponse } from \"http\"\nimport { AddressInfo } from \"net\"\nimport { AppAdapter } from \"./AppAdapter\"\nimport { AppUpdater, DownloadUpdateOptions } from \"./AppUpdater\"\nimport { ResolvedUpdateFileInfo } from \"./main\"\nimport { findFile } from \"./providers/Provider\"\nimport AutoUpdater = Electron.AutoUpdater\n\nexport class MacUpdater extends AppUpdater {\n private readonly nativeUpdater: AutoUpdater = require(\"electron\").autoUpdater\n\n private squirrelDownloadedUpdate: boolean = false\n\n constructor(options?: AllPublishOptions, app?: AppAdapter) {\n super(options, app)\n\n this.nativeUpdater.on(\"error\", it => {\n this._logger.warn(it)\n this.emit(\"error\", it)\n })\n this.nativeUpdater.on(\"update-downloaded\", () => {\n this.squirrelDownloadedUpdate = true\n })\n }\n\n protected doDownloadUpdate(downloadUpdateOptions: DownloadUpdateOptions): Promise<Array<string>> {\n let files = downloadUpdateOptions.updateInfoAndProvider.provider.resolveFiles(downloadUpdateOptions.updateInfoAndProvider.info);\n\n // Allow arm64 macs to install universal or rosetta2(x64) - https://github.com/electron-userland/electron-builder/pull/5524\n const isArm64 = (file: ResolvedUpdateFileInfo) => file.url.pathname.includes(\"arm64\")\n if (files.some(isArm64)) {\n files = files.filter(file => (process.arch === \"arm64\") === isArm64(file));\n }\n\n const zipFileInfo = findFile(files, \"zip\", [\"pkg\", \"dmg\"])\n if (zipFileInfo == null) {\n throw newError(`ZIP file not provided: ${safeStringifyJson(files)}`, \"ERR_UPDATER_ZIP_FILE_NOT_FOUND\")\n }\n\n const server = createServer()\n server.on(\"close\", () => {\n this._logger.info(`Proxy server for native Squirrel.Mac is closed (was started to download ${zipFileInfo.url.href})`)\n })\n\n function getServerUrl(): string {\n const address = server.address() as AddressInfo\n return `http://127.0.0.1:${address.port}`\n }\n\n return this.executeDownload({\n fileExtension: \"zip\",\n fileInfo: zipFileInfo,\n downloadUpdateOptions,\n task: (destinationFile, downloadOptions) => {\n return this.httpExecutor.download(zipFileInfo.url, destinationFile, downloadOptions)\n },\n done: async event => {\n const downloadedFile = event.downloadedFile\n let updateFileSize = zipFileInfo.info.size\n if (updateFileSize == null) {\n updateFileSize = (await stat(downloadedFile)).size\n }\n\n return await new Promise<Array<string>>((resolve, reject) => {\n // insecure random is ok\n const fileUrl = \"/\" + Date.now() + \"-\" + Math.floor(Math.random() * 9999) + \".zip\"\n server.on(\"request\", (request: IncomingMessage, response: ServerResponse) => {\n const requestUrl = request.url!!\n this._logger.info(`${requestUrl} requested`)\n if (requestUrl === \"/\") {\n const data = Buffer.from(`{ \"url\": \"${getServerUrl()}${fileUrl}\" }`)\n response.writeHead(200, {\"Content-Type\": \"application/json\", \"Content-Length\": data.length})\n response.end(data)\n return\n }\n\n if (!requestUrl.startsWith(fileUrl)) {\n this._logger.warn(`${requestUrl} requested, but not supported`)\n response.writeHead(404)\n response.end()\n return\n }\n\n this._logger.info(`${fileUrl} requested by Squirrel.Mac, pipe ${downloadedFile}`)\n\n let errorOccurred = false\n response.on(\"finish\", () => {\n try {\n setImmediate(() => server.close())\n }\n finally {\n if (!errorOccurred) {\n this.nativeUpdater.removeListener(\"error\", reject)\n resolve([])\n }\n }\n })\n\n const readStream = createReadStream(downloadedFile)\n readStream.on(\"error\", error => {\n try {\n response.end()\n }\n catch (e) {\n this._logger.warn(`cannot end response: ${e}`)\n }\n errorOccurred = true\n this.nativeUpdater.removeListener(\"error\", reject)\n reject(new Error(`Cannot pipe \"${downloadedFile}\": ${error}`))\n })\n\n response.writeHead(200, {\n \"Content-Type\": \"application/zip\",\n \"Content-Length\": updateFileSize,\n })\n readStream.pipe(response)\n })\n server.listen(0, \"127.0.0.1\", () => {\n this.nativeUpdater.setFeedURL({\n url: getServerUrl(),\n headers: {\"Cache-Control\": \"no-cache\"},\n })\n\n this.nativeUpdater.once(\"error\", reject)\n\n // The update has been dowloaded and is ready to be served to Squirrel\n this.dispatchUpdateDownloaded(event)\n\n if (this.autoInstallOnAppQuit) {\n // This will trigger fetching and installing the file on Squirrel side\n this.nativeUpdater.checkForUpdates()\n }\n })\n })\n }\n })\n }\n\n quitAndInstall(): void {\n if (this.squirrelDownloadedUpdate) {\n // Update already fetched by Squirrel, it's ready to install\n this.nativeUpdater.quitAndInstall()\n } else {\n // Quit and install as soon as Squirrel get the update\n this.nativeUpdater.on(\"update-downloaded\", () => {\n this.nativeUpdater.quitAndInstall()\n })\n\n // And trigger the update\n this.nativeUpdater.checkForUpdates()\n }\n }\n}"],"sourceRoot":""}