electron-incremental-update 2.0.0-beta.1 → 2.0.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,285 +1,246 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
1
+ 'use strict';
19
2
 
20
- // src/entry.ts
21
- var entry_exports = {};
22
- __export(entry_exports, {
23
- ErrorInfo: () => ErrorInfo,
24
- Updater: () => Updater,
25
- UpdaterError: () => UpdaterError,
26
- initApp: () => initApp,
27
- startupWithUpdater: () => startupWithUpdater
28
- });
29
- module.exports = __toCommonJS(entry_exports);
30
- var import_node_path2 = require("path");
31
- var import_node_fs5 = require("fs");
32
- var import_electron4 = require("electron");
3
+ var fs3 = require('fs');
4
+ var events = require('events');
5
+ var electron = require('electron');
6
+ var path = require('path');
7
+
8
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
33
9
 
34
- // src/updater/core.ts
35
- var import_node_fs3 = require("fs");
36
- var import_electron2 = require("electron");
10
+ var fs3__default = /*#__PURE__*/_interopDefault(fs3);
11
+ var electron__default = /*#__PURE__*/_interopDefault(electron);
12
+ var path__default = /*#__PURE__*/_interopDefault(path);
13
+
14
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
15
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
16
+ }) : x)(function(x) {
17
+ if (typeof require !== "undefined") return require.apply(this, arguments);
18
+ throw Error('Dynamic require of "' + x + '" is not supported');
19
+ });
37
20
 
38
21
  // src/utils/version.ts
39
22
  function isUpdateJSON(json) {
40
- const is = (j) => !!(j && j.minimumVersion && j.signature && j.size && j.version);
23
+ const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
41
24
  return is(json) && is(json?.beta);
42
25
  }
43
-
44
- // src/utils/electron.ts
45
- var import_node_fs = require("fs");
46
- var import_node_path = require("path");
47
- var import_electron = require("electron");
48
26
  var isDev = __EIU_IS_DEV__;
49
- var isWin = process.platform === "win32";
50
- var isMac = process.platform === "darwin";
51
- var isLinux = process.platform === "linux";
52
- function getPathFromAppNameAsar(...path) {
53
- return isDev ? "DEV.asar" : (0, import_node_path.join)((0, import_node_path.dirname)(import_electron.app.getAppPath()), `${import_electron.app.name}.asar`, ...path);
27
+ process.platform === "win32";
28
+ process.platform === "darwin";
29
+ process.platform === "linux";
30
+ function getPathFromAppNameAsar(...paths) {
31
+ return isDev ? "DEV.asar" : path__default.default.join(path__default.default.dirname(electron__default.default.app.getAppPath()), `${electron__default.default.app.name}.asar`, ...paths);
54
32
  }
55
33
  function getAppVersion() {
56
- return isDev ? getEntryVersion() : (0, import_node_fs.readFileSync)(getPathFromAppNameAsar("version"), "utf-8");
34
+ return isDev ? getEntryVersion() : fs3__default.default.readFileSync(getPathFromAppNameAsar("version"), "utf-8");
57
35
  }
58
36
  function getEntryVersion() {
59
- return import_electron.app.getVersion();
37
+ return electron__default.default.app.getVersion();
60
38
  }
61
39
  function restartApp() {
62
- import_electron.app.relaunch();
63
- import_electron.app.quit();
64
- }
65
-
66
- // src/utils/unzip.ts
67
- var import_node_fs2 = require("fs");
68
- var import_node_zlib = require("zlib");
69
- async function unzipFile(gzipPath, targetFilePath = gzipPath.slice(0, -3)) {
70
- if (!(0, import_node_fs2.existsSync)(gzipPath)) {
71
- throw new Error(`path to zipped file not exist: ${gzipPath}`);
72
- }
73
- const compressedBuffer = (0, import_node_fs2.readFileSync)(gzipPath);
74
- return new Promise((resolve, reject) => {
75
- (0, import_node_zlib.brotliDecompress)(compressedBuffer, (err, buffer) => {
76
- (0, import_node_fs2.rmSync)(gzipPath);
77
- if (err) {
78
- reject(err);
79
- }
80
- (0, import_node_fs2.writeFileSync)(targetFilePath, buffer);
81
- resolve(null);
82
- });
83
- });
40
+ electron__default.default.app.relaunch();
41
+ electron__default.default.app.quit();
84
42
  }
85
43
 
86
- // src/updater/types.ts
44
+ // src/entry/types.ts
87
45
  var ErrorInfo = {
88
- download: "Download failed",
89
- validate: "Validate failed",
90
- param: "Missing params",
91
- version: "Unsatisfied version"
46
+ download: "Download Failed",
47
+ validate: "Validate Failed",
48
+ param: "Missing Params",
49
+ network: "Network Error"
92
50
  };
93
51
  var UpdaterError = class extends Error {
52
+ code;
94
53
  constructor(msg, info) {
95
- super(msg + ": " + info);
54
+ super("[" + ErrorInfo[msg] + "] " + info);
55
+ this.code = msg;
96
56
  }
97
57
  };
98
58
 
99
- // src/updater/core.ts
100
- var Updater = class {
101
- CERT = __EIU_SIGNATURE_CERT__;
59
+ // src/entry/updater.ts
60
+ var Updater = class extends events.EventEmitter {
61
+ CERT;
62
+ controller;
102
63
  info;
103
- options;
104
- asarPath;
105
- gzipPath;
106
- tmpFilePath;
107
64
  provider;
108
65
  /**
109
- * updater logger
66
+ * Updater logger
110
67
  */
111
68
  logger;
112
69
  /**
113
- * downloading progress hook
114
- * @param progress download progress
115
- * @example
116
- * updater.onDownloading = ({ percent, total, current }) => {
117
- * console.log(`download progress: ${percent}, total: ${total}, current: ${current}`)
118
- * }
70
+ * Whether to receive beta update
119
71
  */
120
- onDownloading;
72
+ receiveBeta;
121
73
  /**
122
- * URL handler hook
123
- *
124
- * for Github, there are some {@link https://github.com/XIU2/UserScript/blob/master/GithubEnhanced-High-Speed-Download.user.js#L34 public CDN links}
125
- * @param url source url
126
- * @param isDownloadAsar whether is download asar
74
+ * Whether force update in DEV
127
75
  */
128
- handleURL;
76
+ forceUpdate;
129
77
  /**
130
- * whether receive beta version
78
+ * Initialize incremental updater
79
+ * @param options UpdaterOption
131
80
  */
132
- get receiveBeta() {
133
- return !!this.options.receiveBeta;
134
- }
135
- set receiveBeta(receiveBeta) {
136
- this.options.receiveBeta = receiveBeta;
137
- }
138
- /**
139
- * initialize incremental updater
140
- * @param provider update provider
141
- * @param option UpdaterOption
142
- */
143
- constructor(provider, option = {}) {
144
- this.provider = provider;
145
- this.options = option;
146
- if (option.SIGNATURE_CERT) {
147
- this.CERT = option.SIGNATURE_CERT;
148
- }
149
- if (option.logger) {
150
- this.logger = option.logger;
151
- }
152
- this.asarPath = getPathFromAppNameAsar();
153
- this.gzipPath = `${this.asarPath}.gz`;
154
- this.tmpFilePath = `${this.asarPath}.tmp`;
155
- }
156
- async needUpdate(version, minVersion) {
157
- if (isDev) {
158
- this.logger?.warn(`in dev mode, skip check update`);
159
- return false;
81
+ constructor(options = {}) {
82
+ super();
83
+ this.provider = options.provider;
84
+ this.receiveBeta = options.receiveBeta;
85
+ this.CERT = options.SIGNATURE_CERT || __EIU_SIGNATURE_CERT__;
86
+ this.logger = options.logger;
87
+ this.controller = new AbortController();
88
+ if (isDev && !this.logger) {
89
+ this.logger = {
90
+ info: (...args) => console.log("[EIU-INFO ]", ...args),
91
+ debug: (...args) => console.log("[EIU-DEBUG]", ...args),
92
+ warn: (...args) => console.log("[EIU-WARN ]", ...args),
93
+ error: (...args) => console.error("[EIU-ERROR]", ...args)
94
+ };
95
+ this.logger.info("No logger set, enable dev-only logger");
160
96
  }
161
- const isLowerVersion = this.provider.isLowerVersion;
162
- const entryVersion = getEntryVersion();
163
- const appVersion = getAppVersion();
164
- if (await isLowerVersion(entryVersion, minVersion)) {
165
- throw new UpdaterError(ErrorInfo.version, `entry version (${entryVersion}) < minimumVersion (${minVersion})`);
97
+ if (!this.provider) {
98
+ this.logger?.debug("WARN: No update provider");
166
99
  }
167
- this.logger?.info(`check update: current version is ${appVersion}, new version is ${version}`);
168
- return await isLowerVersion(appVersion, version);
169
100
  }
170
- async parseData(format, data) {
171
- if ((0, import_node_fs3.existsSync)(this.tmpFilePath)) {
172
- this.logger?.warn(`remove tmp file: ${this.tmpFilePath}`);
173
- (0, import_node_fs3.rmSync)(this.tmpFilePath);
174
- }
175
- if ((0, import_node_fs3.existsSync)(this.gzipPath)) {
176
- this.logger?.warn(`remove .gz file: ${this.gzipPath}`);
177
- (0, import_node_fs3.rmSync)(this.gzipPath);
178
- }
101
+ async fetch(format, data) {
179
102
  if (typeof data === "object") {
180
103
  if (format === "json" && isUpdateJSON(data) || format === "buffer" && Buffer.isBuffer(data)) {
181
104
  return data;
182
105
  } else {
183
- throw new UpdaterError(ErrorInfo.param, `invalid type at format '${format}': ${JSON.stringify(data)}`);
106
+ this.err("Invalid type", "param", `Invalid type at format '${format}': ${JSON.stringify(data)}`);
107
+ return;
184
108
  }
185
109
  }
186
- this.logger?.debug(`download from ${this.provider.name}`);
110
+ this.logger?.debug(`Download from \`${this.provider.name}\``);
187
111
  try {
188
- const result = format === "json" ? await this.provider.downloadJSON(data ?? __EIU_VERSION_PATH__) : await this.provider.downloadBuffer(import_electron2.app.name, this.info, this.onDownloading);
189
- this.logger?.debug(`download ${format} success${format === "buffer" ? `, file size: ${result.length}` : ""}`);
112
+ const result = format === "json" ? await this.provider.downloadJSON(__EIU_VERSION_PATH__, this.controller.signal) : await this.provider.downloadAsar(electron.app.name, this.info, this.controller.signal, (info) => this.emit("download-progress", info));
113
+ this.logger?.debug(`Download ${format} success${format === "buffer" ? `, file size: ${result.length}` : ""}`);
190
114
  return result;
191
115
  } catch (e) {
192
- this.logger?.warn(`download ${format} failed: ${e}`);
193
- throw new UpdaterError(ErrorInfo.download, `download ${format} failed: ${e}`);
116
+ this.err(`Fetch ${format} failed`, "network", `Download ${format} failed: ${e}`);
194
117
  }
195
118
  }
196
- async checkUpdate(data) {
119
+ /**
120
+ * Handle error message and emit error event
121
+ */
122
+ err(msg, code, errorInfo) {
123
+ const err = new UpdaterError(code, errorInfo);
124
+ this.logger?.error(msg, err);
125
+ this.emit("error", err);
126
+ }
127
+ async checkForUpdates(data) {
128
+ const emitUnavailable = (msg) => {
129
+ this.logger?.info(msg);
130
+ this.emit("update-not-available", msg);
131
+ return false;
132
+ };
133
+ if (!data && !this.provider) {
134
+ const errorInfo = "No update json or provider";
135
+ this.err("Check update failed", "param", errorInfo);
136
+ return emitUnavailable(errorInfo);
137
+ }
138
+ const _data = await this.fetch("json", data);
139
+ if (!_data) {
140
+ return emitUnavailable("Failed to get update info");
141
+ }
142
+ let { signature, version, minimumVersion, beta } = _data;
143
+ if (this.receiveBeta) {
144
+ version = beta.version;
145
+ signature = beta.signature;
146
+ minimumVersion = beta.minimumVersion;
147
+ }
148
+ this.logger?.debug(`Checked update, version: ${version}, signature: ${signature}`);
149
+ if (isDev && !this.forceUpdate && !data) {
150
+ return emitUnavailable("Skip check update in dev mode. To force update, set `updater.forceUpdate` to true or call checkUpdate with UpdateJSON");
151
+ }
152
+ const isLowerVersion = this.provider.isLowerVersion;
153
+ const entryVersion = getEntryVersion();
154
+ const appVersion = getAppVersion();
197
155
  try {
198
- let { signature, size, version, minimumVersion, beta } = await this.parseData("json", data);
199
- if (this.receiveBeta) {
200
- version = beta.version;
201
- signature = beta.signature;
202
- minimumVersion = beta.minimumVersion;
203
- size = beta.size;
156
+ if (isLowerVersion(entryVersion, minimumVersion)) {
157
+ return emitUnavailable(`Entry Version (${entryVersion}) < MinimumVersion (${minimumVersion})`);
204
158
  }
205
- this.logger?.debug(`checked update, version: ${version}, size: ${size}, signature: ${signature}`);
206
- if (!await this.needUpdate(version, minimumVersion)) {
207
- this.logger?.info(`update unavailable: ${version} is the latest version`);
208
- return { success: false, data: version };
209
- } else {
210
- this.logger?.info(`update available: ${version}`);
211
- this.info = { signature, minimumVersion, version, size };
212
- return { success: true, data: this.info };
159
+ this.logger?.info(`Check update: current version is ${appVersion}, new version is ${version}`);
160
+ if (!isLowerVersion(appVersion, version)) {
161
+ return emitUnavailable(`Current version (${appVersion}) < New version (${version})`);
213
162
  }
214
- } catch (error) {
215
- this.logger?.error("check update failed", error);
216
- return {
217
- success: false,
218
- data: error instanceof UpdaterError ? error : new UpdaterError(ErrorInfo.download, error.toString())
219
- };
163
+ this.logger?.info(`Update available: ${version}`);
164
+ this.info = { signature, minimumVersion, version };
165
+ this.emit("update-available", this.info);
166
+ return true;
167
+ } catch {
168
+ this.err("Fail to parse version", "validate", "Fail to parse version string");
169
+ return false;
220
170
  }
221
171
  }
222
- async download(data, sig) {
172
+ async downloadUpdate(data, info) {
173
+ const _sig = info?.signature ?? this.info?.signature;
174
+ const _version = info?.version ?? this.info?.version;
175
+ if (!_sig || !_version) {
176
+ this.err("Download failed", "param", "No update signature, please call `checkUpdate` first or manually setup params");
177
+ return false;
178
+ }
179
+ if (!data && !this.provider) {
180
+ this.err("Download failed", "param", "No update asar buffer and provider");
181
+ return false;
182
+ }
183
+ const buffer = await this.fetch("buffer", data ? Buffer.from(data) : void 0);
184
+ if (!buffer) {
185
+ this.err("Download failed", "param", "No update asar file buffer");
186
+ return false;
187
+ }
188
+ this.logger?.debug("verify start");
189
+ if (!await this.provider.verifySignaure(buffer, _version, _sig, this.CERT)) {
190
+ this.err("Download failed", "validate", "Invalid update asar file");
191
+ return false;
192
+ }
193
+ this.logger?.debug("Verify success");
223
194
  try {
224
- if (!this.info) {
225
- throw new UpdaterError(ErrorInfo.param, "no update info");
226
- }
227
- const _sig = sig ?? this.info.signature;
228
- const buffer = await this.parseData("buffer", data);
229
- this.logger?.debug("verify start");
230
- const _ver = await this.provider.verifySignaure(buffer, _sig, this.CERT);
231
- if (!_ver) {
232
- throw new UpdaterError(ErrorInfo.validate, "invalid signature or certificate");
233
- }
234
- this.logger?.debug("verify success");
235
- this.logger?.debug(`write to ${this.gzipPath}`);
236
- (0, import_node_fs3.writeFileSync)(this.gzipPath, buffer);
237
- this.logger?.debug(`extract to ${this.tmpFilePath}`);
238
- await unzipFile(this.gzipPath, this.tmpFilePath);
239
- this.logger?.info(`download success, version: ${_ver}`);
195
+ const tmpFilePath = getPathFromAppNameAsar() + ".tmp";
196
+ this.logger?.debug(`Install to ${tmpFilePath}`);
197
+ fs3__default.default.writeFileSync(tmpFilePath, await this.provider.unzipFile(buffer));
198
+ this.logger?.info(`Download success, version: ${_version}`);
240
199
  this.info = void 0;
241
- return { success: true };
200
+ this.emit("update-downloaded");
201
+ return true;
242
202
  } catch (error) {
243
- this.logger?.error("download asar failed", error);
244
- return {
245
- success: false,
246
- data: error instanceof UpdaterError ? error : new UpdaterError(ErrorInfo.download, error.toString())
247
- };
203
+ this.err("Download failed", "download", `Fail to unwrap asar file, ${error}`);
204
+ return false;
248
205
  }
249
206
  }
250
207
  /**
251
208
  * quit App and install
252
209
  */
253
210
  quitAndInstall() {
254
- this.logger?.info("quit and install");
211
+ this.logger?.info("Quit and install");
255
212
  restartApp();
256
213
  }
214
+ cancel() {
215
+ if (this.controller.signal.aborted) {
216
+ return;
217
+ }
218
+ this.controller.abort();
219
+ this.logger?.info("Cancel update");
220
+ this.emit("update-cancelled");
221
+ this.controller = new AbortController();
222
+ }
257
223
  };
258
-
259
- // src/utils/zip.ts
260
- var import_node_fs4 = require("fs");
261
- var import_node_zlib2 = require("zlib");
262
-
263
- // src/utils/crypto/decrypt.ts
264
- var import_node_crypto2 = require("crypto");
265
-
266
- // src/utils/crypto/utils.ts
267
- var import_node_crypto = require("crypto");
268
-
269
- // src/utils/crypto/encrypt.ts
270
- var import_node_crypto3 = require("crypto");
271
-
272
- // src/entry.ts
224
+ async function autoUpdate(updater) {
225
+ if (await updater.checkForUpdates() && await updater.downloadUpdate()) {
226
+ updater.quitAndInstall();
227
+ }
228
+ }
273
229
  function startupWithUpdater(fn) {
274
230
  return fn;
275
231
  }
276
232
  var defaultOnInstall = (install, _, __, logger) => {
277
233
  install();
278
- logger.info(`update success!`);
234
+ logger?.info(`update success!`);
279
235
  };
280
- async function initApp(appOptions) {
236
+ async function createElectronApp(appOptions = {}) {
237
+ const appNameAsarPath = getPathFromAppNameAsar();
281
238
  const {
282
- provider,
239
+ mainPath = path__default.default.join(
240
+ isDev ? path__default.default.join(electron.app.getAppPath(), __EIU_MAIN_DEV_DIR__) : appNameAsarPath,
241
+ "main",
242
+ __EIU_MAIN_FILE__
243
+ ),
283
244
  updater,
284
245
  onInstall = defaultOnInstall,
285
246
  beforeStart,
@@ -287,36 +248,35 @@ async function initApp(appOptions) {
287
248
  } = appOptions;
288
249
  let updaterInstance;
289
250
  if (typeof updater === "object" || !updater) {
290
- updaterInstance = new Updater(provider, updater);
251
+ updaterInstance = new Updater(updater);
291
252
  } else {
292
253
  updaterInstance = await updater();
293
254
  }
294
- const logger = updaterInstance.logger || console;
255
+ const logger = updaterInstance.logger;
295
256
  try {
296
- const appNameAsarPath = getPathFromAppNameAsar();
297
257
  const tempAsarPath = `${appNameAsarPath}.tmp`;
298
- if ((0, import_node_fs5.existsSync)(tempAsarPath)) {
299
- logger.info(`installing new asar: ${tempAsarPath}`);
300
- await onInstall(() => (0, import_node_fs5.renameSync)(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
258
+ if (fs3__default.default.existsSync(tempAsarPath)) {
259
+ logger?.info(`Installing new asar from ${tempAsarPath}`);
260
+ await onInstall(() => fs3__default.default.renameSync(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
261
+ }
262
+ await beforeStart?.(mainPath, logger);
263
+ if (__EIU_IS_ESM__) {
264
+ (await import("file://" + mainPath)).default(updaterInstance);
265
+ } else {
266
+ __require(mainPath)(updaterInstance);
301
267
  }
302
- const mainFilePath = (0, import_node_path2.join)(
303
- isDev ? (0, import_node_path2.join)(import_electron4.app.getAppPath(), __EIU_MAIN_DEV_DIR__) : appNameAsarPath,
304
- "main",
305
- __EIU_MAIN_FILE__
306
- );
307
- await beforeStart?.(mainFilePath, logger);
308
- require(mainFilePath)(updaterInstance);
309
268
  } catch (error) {
310
- logger.error("startup error", error);
269
+ logger?.error("startup error", error);
311
270
  onStartError?.(error, logger);
312
- import_electron4.app.quit();
271
+ electron.app.quit();
313
272
  }
314
273
  }
315
- // Annotate the CommonJS export names for ESM import in node:
316
- 0 && (module.exports = {
317
- ErrorInfo,
318
- Updater,
319
- UpdaterError,
320
- initApp,
321
- startupWithUpdater
322
- });
274
+ var initApp = createElectronApp;
275
+
276
+ exports.ErrorInfo = ErrorInfo;
277
+ exports.Updater = Updater;
278
+ exports.UpdaterError = UpdaterError;
279
+ exports.autoUpdate = autoUpdate;
280
+ exports.createElectronApp = createElectronApp;
281
+ exports.initApp = initApp;
282
+ exports.startupWithUpdater = startupWithUpdater;