electron-incremental-update 1.1.0 → 1.3.0

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.d.ts CHANGED
@@ -1,22 +1,16 @@
1
1
  import { U as UpdateInfo, a as UpdateJSON } from './pure-GoN_3MEj.js';
2
2
 
3
- declare class MinimumVersionError extends Error {
4
- currentVersion: string;
5
- minVersion: string;
6
- constructor(version: string, minimumVersion: string);
7
- }
8
- declare class VerifyFailedError extends Error {
9
- signature: string;
10
- cert: string;
11
- constructor(signature: string, cert: string);
12
- }
13
- declare class DownloadError extends Error {
14
- constructor(msg: string);
3
+ declare const ErrorInfo: {
4
+ readonly downlaod: "Download failed";
5
+ readonly validate: "Validate failed";
6
+ readonly param: "Missing params";
7
+ readonly version: "Unsatisfied version";
8
+ };
9
+ declare class UpdaterError extends Error {
10
+ constructor(msg: typeof ErrorInfo[keyof typeof ErrorInfo], info: string);
15
11
  }
16
- type CheckResult = UpdateInfo | undefined | CheckResultError;
17
- type CheckResultError = MinimumVersionError | DownloadError | TypeError | Error;
18
- type DownloadResult = true | DownloadResultError;
19
- type DownloadResultError = DownloadError | VerifyFailedError | TypeError | Error;
12
+ type CheckResult = UpdateInfo | undefined | UpdaterError;
13
+ type DownloadResult = true | UpdaterError;
20
14
  type DownloadingInfo = {
21
15
  /**
22
16
  * downloaded percent, 0% - 100%
@@ -42,9 +36,9 @@ type UpdaterOverrideFunctions = {
42
36
  * custom version compare function
43
37
  * @param version1 old version string
44
38
  * @param version2 new version string
45
- * @returns whether version1 < version2
39
+ * @returns if version1 < version2
46
40
  */
47
- compareVersion?: (version1: string, version2: string) => boolean | Promise<boolean>;
41
+ isLowerVersion?: (version1: string, version2: string) => boolean | Promise<boolean>;
48
42
  /**
49
43
  * custom verify signature function
50
44
  * @param buffer file buffer
@@ -83,19 +77,10 @@ type UpdaterDownloadConfig = {
83
77
  };
84
78
  interface UpdaterOption {
85
79
  /**
86
- * public key of signature, which will be auto generated by plugin
87
- * @example
88
- * ```ts
89
- * // just empty here, auto filled by plugin
90
- * const SIGNATURE_CERT = ''
91
- *
92
- * const updater = createUpdater({
93
- * SIGNATURE_CERT,
94
- * ...
95
- * })
96
- * ```
80
+ * public key of signature, which will be auto generated by plugin,
81
+ * generate by `selfsigned` if not set
97
82
  */
98
- SIGNATURE_CERT: string;
83
+ SIGNATURE_CERT?: string;
99
84
  /**
100
85
  * repository url, e.g. `https://github.com/electron/electron`
101
86
  *
@@ -126,6 +111,7 @@ interface UpdaterOption {
126
111
  }
127
112
 
128
113
  declare class Updater {
114
+ private CERT;
129
115
  private info?;
130
116
  private option;
131
117
  private asarPath;
@@ -153,7 +139,7 @@ declare class Updater {
153
139
  * initialize incremental updater
154
140
  * @param option UpdaterOption
155
141
  */
156
- constructor(option: UpdaterOption);
142
+ constructor(option?: UpdaterOption);
157
143
  private needUpdate;
158
144
  /**
159
145
  * this function is used to parse download data.
@@ -168,43 +154,81 @@ declare class Updater {
168
154
  */
169
155
  private parseData;
170
156
  /**
171
- * check update info
172
- *
173
- * if you want to update **offline**, you can set `data` and `sig` add update info
174
- * @param data custom download URL of `updatejson` or existing update json
157
+ * check update info using default options
158
+ * @returns
159
+ * - Available: `{size: number, version: string}`
160
+ * - Unavailable: `undefined`
161
+ * - Fail: `UpdaterError`
162
+ */
163
+ checkUpdate(): Promise<CheckResult>;
164
+ /**
165
+ * check update info using custom url
166
+ * @param url custom download URL of `updatejson`
175
167
  * @returns
176
168
  * - Available:`{size: number, version: string}`
177
169
  * - Unavailable: `undefined`
178
- * - Fail: `CheckResultError`
170
+ * - Fail: `UpdaterError`
179
171
  */
180
- checkUpdate(data?: string | UpdateJSON): Promise<CheckResult>;
172
+ checkUpdate(url: string): Promise<CheckResult>;
181
173
  /**
182
- * download update
183
- *
184
- * if you want to update **offline**, you can set both `data` and `sig` to verify and install
185
- * @param data custom download URL of `asar.gz` or existing `asar.gz` buffer
174
+ * check update info using existing update json
175
+ * @param data existing update json
176
+ * @returns
177
+ * - Available:`{size: number, version: string}`
178
+ * - Unavailable: `undefined`
179
+ * - Fail: `UpdaterError`
180
+ */
181
+ checkUpdate(data: UpdateJSON): Promise<CheckResult>;
182
+ /**
183
+ * download update using default options
184
+ * @returns
185
+ * - Success: `true`
186
+ * - Fail: `UpdaterError`
187
+ */
188
+ download(): Promise<DownloadResult>;
189
+ /**
190
+ * download update using custom url
191
+ * @param url custom download URL
192
+ * @returns
193
+ * - Success: `true`
194
+ * - Fail: `UpdaterError`
195
+ */
196
+ download(url: string): Promise<DownloadResult>;
197
+ /**
198
+ * download update using existing `asar.gz` buffer and signature
199
+ * @param data existing `asar.gz` buffer
186
200
  * @param sig signature
187
201
  * @returns
188
- * - `true`: success
189
- * - `DownloadResultError`: fail
202
+ * - Success: `true`
203
+ * - Fail: `UpdaterError`
190
204
  */
191
- download(data?: Buffer, sig?: string): Promise<DownloadResult>;
205
+ download(data: Buffer, sig: string): Promise<DownloadResult>;
192
206
  /**
193
207
  * quit App and install
194
208
  */
195
209
  quitAndInstall(): void;
196
210
  }
197
211
 
212
+ type Func = Required<UpdaterOverrideFunctions>;
213
+ declare const downloadJSONDefault: Func['downloadJSON'];
214
+ declare const downloadBufferDefault: Func['downloadBuffer'];
215
+
216
+ declare const isLowerVersionDefault: Func['isLowerVersion'];
217
+
198
218
  /**
199
219
  * create updater instance
200
220
  * @param option updater option
201
221
  * @returns updater
202
222
  */
203
- declare function createUpdater(option: UpdaterOption): Updater;
223
+ declare function createUpdater(option?: UpdaterOption): Updater;
204
224
 
205
225
  type Promisable<T> = T | Promise<T>;
206
226
  type OnInstallFunction = (install: VoidFunction, tempAsarPath: string, appNameAsarPath: string, logger?: Logger) => Promisable<void>;
207
227
  type AppOption = {
228
+ /**
229
+ * updater options
230
+ */
231
+ updater?: (() => Promisable<Updater>) | UpdaterOption;
208
232
  /**
209
233
  * path of electron output dist when in development
210
234
  * @default '../dist-electron'
@@ -252,13 +276,6 @@ type AppOption = {
252
276
  * })
253
277
  */
254
278
  declare function startupWithUpdater(fn: (updater: Updater) => Promisable<void>): (updater: Updater) => Promisable<void>;
255
- type StartupWithUpdater = {
256
- /**
257
- * starup app
258
- * @param updater updater option or create function
259
- */
260
- startupWithUpdater: (updater: (() => Promisable<Updater>) | UpdaterOption) => void;
261
- };
262
279
  /**
263
280
  * initialize app
264
281
  * @example
@@ -266,20 +283,22 @@ type StartupWithUpdater = {
266
283
  * import { getGithubReleaseCdnGroup, initApp, parseGithubCdnURL } from 'electron-incremental-update'
267
284
  * import { repository } from '../package.json'
268
285
  *
269
- * const SIGNATURE_CERT = '' // auto generate certificate when start app
270
286
  * const { cdnPrefix: asarPrefix } = getGithubReleaseCdnGroup()[0]
271
287
  * const { cdnPrefix: jsonPrefix } = getGithubFileCdnGroup()[0]
272
- * initApp({ onStart: console.log })
288
+ *
289
+ * initApp({
273
290
  * // can be updater option or function that return updater
274
- * .startupWithUpdater({
275
- * SIGNATURE_CERT,
291
+ * updater: {
292
+ * SIGNATURE_CERT: 'custom certificate',
276
293
  * repository,
277
294
  * updateJsonURL: parseGithubCdnURL(repository, jsonPrefix, 'version.json'),
278
295
  * releaseAsarURL: parseGithubCdnURL(repository, asarPrefix, `download/latest/${app.name}.asar.gz`),
279
296
  * receiveBeta: true,
280
- * })
297
+ * },
298
+ * onStart: console.log
299
+ * })
281
300
  * ```
282
301
  */
283
- declare function initApp(appOptions?: AppOption): StartupWithUpdater;
302
+ declare function initApp(appOptions?: AppOption): Promise<void>;
284
303
 
285
- export { type AppOption, type CheckResult, type CheckResultError, DownloadError, type DownloadResult, type DownloadResultError, type DownloadingInfo, type Logger, MinimumVersionError, Updater, type UpdaterDownloadConfig, type UpdaterOption, type UpdaterOverrideFunctions, VerifyFailedError, createUpdater, initApp, startupWithUpdater };
304
+ export { type AppOption, type CheckResult, type DownloadResult, type DownloadingInfo, ErrorInfo, type Func, type Logger, Updater, type UpdaterDownloadConfig, UpdaterError, type UpdaterOption, type UpdaterOverrideFunctions, createUpdater, downloadBufferDefault, downloadJSONDefault, initApp, isLowerVersionDefault, startupWithUpdater };
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import {
8
8
  restartApp,
9
9
  unzipFile,
10
10
  waitAppReady
11
- } from "./chunk-CXHA5TF7.js";
11
+ } from "./chunk-SBPTSLG7.js";
12
12
 
13
13
  // src/index.ts
14
14
  import { resolve } from "node:path";
@@ -16,8 +16,7 @@ import { existsSync as existsSync2, renameSync } from "node:fs";
16
16
  import { app as app2 } from "electron";
17
17
 
18
18
  // src/updater/core.ts
19
- import { existsSync } from "node:fs";
20
- import { rm, writeFile } from "node:fs/promises";
19
+ import { existsSync, rmSync, writeFileSync } from "node:fs";
21
20
  import { app } from "electron";
22
21
 
23
22
  // src/crypto/dec.ts
@@ -48,100 +47,67 @@ var verify = (buffer, signature, cert) => {
48
47
  };
49
48
 
50
49
  // src/updater/types.ts
51
- var MinimumVersionError = class extends Error {
52
- currentVersion;
53
- minVersion;
54
- constructor(version, minimumVersion) {
55
- super(`current entry version is ${version}, less than the minimumVersion ${minimumVersion}`);
56
- this.currentVersion = version;
57
- this.minVersion = minimumVersion;
58
- }
59
- };
60
- var VerifyFailedError = class extends Error {
61
- signature;
62
- cert;
63
- constructor(signature, cert) {
64
- super("verify failed, invalid signature or certificate");
65
- this.signature = signature;
66
- this.cert = cert;
67
- }
50
+ var ErrorInfo = {
51
+ downlaod: "Download failed",
52
+ validate: "Validate failed",
53
+ param: "Missing params",
54
+ version: "Unsatisfied version"
68
55
  };
69
- var DownloadError = class extends Error {
70
- constructor(msg) {
71
- super(`download update error, ${msg}`);
56
+ var UpdaterError = class extends Error {
57
+ constructor(msg, info) {
58
+ super(msg + ": " + info);
72
59
  }
73
60
  };
74
61
 
75
62
  // src/updater/defaultFunctions/download.ts
76
63
  import { net } from "electron";
77
- var downloadJSONDefault = async (url, headers) => {
64
+ async function downlaodFn(url, headers, onResponse) {
78
65
  await waitAppReady();
79
66
  return new Promise((resolve2, reject) => {
80
- const request = net.request({
81
- url,
82
- method: "GET",
83
- redirect: "follow"
84
- });
85
- Object.keys(headers).forEach((key) => {
86
- request.setHeader(key, headers[key]);
87
- });
88
- request.on("response", (res) => {
89
- let data = "";
90
- res.on("data", (chunk) => data += chunk);
91
- res.on("end", () => {
92
- try {
93
- const json = JSON.parse(data);
94
- if (isUpdateJSON(json)) {
95
- resolve2(json);
96
- } else {
97
- throw Error;
98
- }
99
- } catch (e) {
100
- reject(new Error("invalid json"));
67
+ const request = net.request({ url, method: "GET", redirect: "follow" });
68
+ Object.keys(headers).forEach((key) => request.setHeader(key, headers[key]));
69
+ request.on("response", (res) => onResponse(res, resolve2, reject));
70
+ request.on("error", reject);
71
+ request.end();
72
+ });
73
+ }
74
+ var downloadJSONDefault = async (url, headers) => {
75
+ return await downlaodFn(url, headers, (resp, resolve2, reject) => {
76
+ let data = "";
77
+ resp.on("data", (chunk) => data += chunk);
78
+ resp.on("end", () => {
79
+ try {
80
+ const json = JSON.parse(data);
81
+ if (isUpdateJSON(json)) {
82
+ resolve2(json);
83
+ } else {
84
+ throw Error;
101
85
  }
102
- });
103
- });
104
- request.on("error", (e) => {
105
- reject(e);
86
+ } catch (ignore) {
87
+ reject(new Error("invalid update json"));
88
+ }
106
89
  });
107
- request.end();
90
+ resp.on("aborted", () => reject(new Error("aborted")));
91
+ resp.on("error", () => reject(new Error("download error")));
108
92
  });
109
93
  };
110
94
  var downloadBufferDefault = async (url, headers, total, onDownloading) => {
111
- await waitAppReady();
112
95
  let current = 0;
113
- return new Promise((resolve2, reject) => {
114
- const request = net.request({
115
- url,
116
- method: "GET",
117
- redirect: "follow"
118
- });
119
- Object.keys(headers).forEach((key) => {
120
- request.setHeader(key, headers[key]);
96
+ return await downlaodFn(url, headers, (resp, resolve2, reject) => {
97
+ let data = [];
98
+ resp.on("data", (chunk) => {
99
+ current += chunk.length;
100
+ onDownloading?.({ percent: `${+(current / total).toFixed(2) * 100}%`, total, current });
101
+ data.push(chunk);
121
102
  });
122
- request.on("response", (res) => {
123
- let data = [];
124
- res.on("data", (chunk) => {
125
- current += chunk.length;
126
- onDownloading?.({
127
- percent: `${+(current / total).toFixed(2) * 100}%`,
128
- total,
129
- current
130
- });
131
- data.push(chunk);
132
- });
133
- res.on("end", () => {
134
- resolve2(Buffer.concat(data));
135
- });
136
- }).on("error", (e) => {
137
- reject(e);
138
- });
139
- request.end();
103
+ resp.on("end", () => resolve2(Buffer.concat(data)));
104
+ resp.on("aborted", () => reject(new Error("aborted")));
105
+ resp.on("error", () => reject(new Error("download error")));
140
106
  });
141
107
  };
142
108
 
143
109
  // src/updater/defaultFunctions/compareVersion.ts
144
- var compareVersionDefault = (version1, version2) => {
110
+ var isLowerVersionDefault = (version1, version2) => {
145
111
  const oldV = parseVersion(version1);
146
112
  const newV = parseVersion(version2);
147
113
  function compareStrings(str1, str2) {
@@ -164,6 +130,7 @@ var compareVersionDefault = (version1, version2) => {
164
130
 
165
131
  // src/updater/core.ts
166
132
  var Updater = class {
133
+ CERT = __SIGNATURE_CERT__;
167
134
  info;
168
135
  option;
169
136
  asarPath;
@@ -195,38 +162,39 @@ var Updater = class {
195
162
  * initialize incremental updater
196
163
  * @param option UpdaterOption
197
164
  */
198
- constructor(option) {
165
+ constructor(option = {}) {
199
166
  this.option = option;
167
+ if (option.SIGNATURE_CERT) {
168
+ this.CERT = option.SIGNATURE_CERT;
169
+ }
200
170
  this.asarPath = getPathFromAppNameAsar();
201
171
  this.gzipPath = `${this.asarPath}.gz`;
202
172
  this.tmpFilePath = `${this.asarPath}.tmp`;
203
173
  }
204
174
  async needUpdate(version, minVersion) {
205
- const compare = this.option.overrideFunctions?.compareVersion ?? compareVersionDefault;
175
+ const isLowerVersion = this.option.overrideFunctions?.isLowerVersion ?? isLowerVersionDefault;
206
176
  const { appVersion, entryVersion } = getVersions();
207
- if (await compare(entryVersion, minVersion)) {
208
- throw new MinimumVersionError(entryVersion, minVersion);
177
+ if (await isLowerVersion(entryVersion, minVersion)) {
178
+ throw new UpdaterError(ErrorInfo.version, `entry version (${entryVersion}) < minimumVersion (${minVersion})`);
209
179
  }
210
180
  this.logger?.info(`check update: current version is ${appVersion}, new version is ${version}`);
211
- return await compare(appVersion, version);
181
+ return await isLowerVersion(appVersion, version);
212
182
  }
213
183
  async parseData(format, data) {
214
184
  if (existsSync(this.tmpFilePath)) {
215
185
  this.logger?.warn(`remove tmp file: ${this.tmpFilePath}`);
216
- await rm(this.tmpFilePath);
186
+ rmSync(this.tmpFilePath);
217
187
  }
218
188
  if (existsSync(this.gzipPath)) {
219
189
  this.logger?.warn(`remove .gz file: ${this.gzipPath}`);
220
- await rm(this.gzipPath);
221
- }
222
- if (!["string", "object", "undefined"].includes(typeof data)) {
223
- throw new TypeError(`invalid type at format '${format}': ${data}`);
224
- }
225
- if (typeof data === "object" && (format === "json" && isUpdateJSON(data) || format === "buffer" && Buffer.isBuffer(data))) {
226
- return data;
190
+ rmSync(this.gzipPath);
227
191
  }
228
192
  if (typeof data === "object") {
229
- throw new TypeError(`invalid type at format '${format}': ${data}`);
193
+ if (format === "json" && isUpdateJSON(data) || format === "buffer" && Buffer.isBuffer(data)) {
194
+ return data;
195
+ } else {
196
+ throw new UpdaterError(ErrorInfo.param, `invalid type at format '${format}': ${JSON.stringify(data)}`);
197
+ }
230
198
  }
231
199
  const ua = this.option.downloadConfig?.userAgent || "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36";
232
200
  const headers = {
@@ -234,11 +202,11 @@ var Updater = class {
234
202
  UserAgent: ua,
235
203
  ...this.option.downloadConfig?.extraHeader
236
204
  };
237
- this.logger?.info(`download headers: ${JSON.stringify(headers, null, 2)}`);
205
+ this.logger?.debug(`download headers: ${JSON.stringify(headers)}`);
238
206
  const config = format === "json" ? {
239
207
  name: "updateJsonURL",
240
208
  url: this.option.updateJsonURL,
241
- repoFallback: `${this.option.repository.replace("github.com", "raw.githubusercontent.com")}/master/version.json`,
209
+ repoFallback: `${this.option.repository?.replace("github.com", "raw.githubusercontent.com")}/master/version.json`,
242
210
  fn: this.option.overrideFunctions?.downloadJSON ?? downloadJSONDefault
243
211
  } : {
244
212
  name: "releaseAsarURL",
@@ -250,32 +218,22 @@ var Updater = class {
250
218
  if (!data) {
251
219
  this.logger?.debug(`no ${config.name}, fallback to use repository`);
252
220
  if (!this.option.repository) {
253
- throw new Error(`${config.name} or repository are not set`);
221
+ throw new UpdaterError(ErrorInfo.param, `${config.name} or repository is not set`);
254
222
  }
255
223
  if (format === "buffer" && !this.info?.version) {
256
- throw new Error("version are not set");
224
+ throw new UpdaterError(ErrorInfo.param, "version is not set");
257
225
  }
258
226
  data = config.repoFallback;
259
227
  }
260
- this.logger?.info(`download ${format} from ${data}`);
228
+ this.logger?.debug(`download ${format} from ${data}`);
261
229
  try {
262
230
  const ret = format === "json" ? await config.fn(data, headers) : await config.fn(data, headers, this.info.size, this.onDownloading);
263
- this.logger?.info(`download ${format} success${format === "buffer" ? `, file size: ${ret.length}` : ""}`);
231
+ this.logger?.debug(`download ${format} success${format === "buffer" ? `, file size: ${ret.length}` : ""}`);
264
232
  return ret;
265
233
  } catch (e) {
266
- throw new DownloadError(e.toString());
234
+ throw new UpdaterError(ErrorInfo.downlaod, e.toString());
267
235
  }
268
236
  }
269
- /**
270
- * check update info
271
- *
272
- * if you want to update **offline**, you can set `data` and `sig` add update info
273
- * @param data custom download URL of `updatejson` or existing update json
274
- * @returns
275
- * - Available:`{size: number, version: string}`
276
- * - Unavailable: `undefined`
277
- * - Fail: `CheckResultError`
278
- */
279
237
  async checkUpdate(data) {
280
238
  try {
281
239
  let { signature, size, version, minimumVersion, beta } = await this.parseData("json", data);
@@ -285,7 +243,7 @@ var Updater = class {
285
243
  minimumVersion = beta.minimumVersion;
286
244
  size = beta.size;
287
245
  }
288
- this.logger?.info(`checked version: ${version}, size: ${size}, signature: ${signature}`);
246
+ this.logger?.debug(`checked version: ${version}, size: ${size}, signature: ${signature}`);
289
247
  if (!await this.needUpdate(version, minimumVersion)) {
290
248
  this.logger?.info(`update unavailable: ${version} is the latest version`);
291
249
  return void 0;
@@ -304,33 +262,23 @@ var Updater = class {
304
262
  return error;
305
263
  }
306
264
  }
307
- /**
308
- * download update
309
- *
310
- * if you want to update **offline**, you can set both `data` and `sig` to verify and install
311
- * @param data custom download URL of `asar.gz` or existing `asar.gz` buffer
312
- * @param sig signature
313
- * @returns
314
- * - `true`: success
315
- * - `DownloadResultError`: fail
316
- */
317
265
  async download(data, sig) {
318
266
  try {
319
267
  const _sig = sig ?? this.info?.signature;
320
268
  if (!_sig) {
321
- throw new Error("signature are not set, please checkUpdate first or set the second parameter");
269
+ throw new UpdaterError(ErrorInfo.param, "signature is empty");
322
270
  }
323
271
  const buffer = await this.parseData("buffer", data);
324
- this.logger?.info("verify start");
272
+ this.logger?.debug("verify start");
325
273
  const _verify = this.option.overrideFunctions?.verifySignaure ?? verify;
326
- const _ver = await _verify(buffer, _sig, this.option.SIGNATURE_CERT);
274
+ const _ver = await _verify(buffer, _sig, this.CERT);
327
275
  if (!_ver) {
328
- throw new VerifyFailedError(_sig, this.option.SIGNATURE_CERT);
276
+ throw new UpdaterError(ErrorInfo.validate, "invalid signature or certificate");
329
277
  }
330
- this.logger?.info("verify success");
331
- this.logger?.info(`write to ${this.gzipPath}`);
332
- await writeFile(this.gzipPath, buffer);
333
- this.logger?.info(`extract to ${this.tmpFilePath}`);
278
+ this.logger?.debug("verify success");
279
+ this.logger?.debug(`write to ${this.gzipPath}`);
280
+ writeFileSync(this.gzipPath, buffer);
281
+ this.logger?.debug(`extract to ${this.tmpFilePath}`);
334
282
  await unzipFile(this.gzipPath, this.tmpFilePath);
335
283
  this.logger?.info(`download success, version: ${_ver}`);
336
284
  this.info = void 0;
@@ -362,8 +310,9 @@ var defaultOnInstall = (install, _, __, logger) => {
362
310
  install();
363
311
  logger?.info(`update success!`);
364
312
  };
365
- function initApp(appOptions) {
313
+ async function initApp(appOptions = {}) {
366
314
  const {
315
+ updater,
367
316
  electronDevDistPath = "../dist-electron",
368
317
  mainPath = "main/index.js",
369
318
  hooks
@@ -373,50 +322,41 @@ function initApp(appOptions) {
373
322
  beforeStart,
374
323
  onStartError
375
324
  } = hooks || {};
376
- function handleError(err, logger) {
325
+ function handleError(err, logger2) {
377
326
  console.error(err);
378
- onStartError?.(err, logger);
327
+ onStartError?.(err, logger2);
379
328
  app2.quit();
380
329
  }
381
- async function startup(updater) {
382
- const logger = updater.logger;
383
- try {
384
- const appNameAsarPath = getPathFromAppNameAsar();
385
- const tempAsarPath = `${appNameAsarPath}.tmp`;
386
- if (existsSync2(tempAsarPath)) {
387
- logger?.info(`installing new asar: ${tempAsarPath}`);
388
- await onInstall(() => renameSync(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
389
- }
390
- const mainDir = is.dev ? electronDevDistPath : appNameAsarPath;
391
- const entry = resolve(__dirname, mainDir, mainPath);
392
- await beforeStart?.(entry, logger);
393
- __require(entry)(updater);
394
- } catch (error) {
395
- handleError(error, logger);
396
- }
330
+ let updaterInstance;
331
+ if (typeof updater === "object" || !updater) {
332
+ updaterInstance = createUpdater(updater);
333
+ } else {
334
+ updaterInstance = await updater();
397
335
  }
398
- let timer = setTimeout(() => {
399
- handleError("start app timeout, please start app with `initApp(options).startupWithUpdater(options)`");
400
- }, 3e3);
401
- return {
402
- async startupWithUpdater(updater) {
403
- clearTimeout(timer);
404
- if (typeof updater === "object") {
405
- await startup(createUpdater(updater));
406
- } else if (typeof updater === "function") {
407
- await startup(await updater());
408
- } else {
409
- handleError("invalid updater option or updater is not a function");
410
- }
336
+ const logger = updaterInstance.logger;
337
+ try {
338
+ const appNameAsarPath = getPathFromAppNameAsar();
339
+ const tempAsarPath = `${appNameAsarPath}.tmp`;
340
+ if (existsSync2(tempAsarPath)) {
341
+ logger?.info(`installing new asar: ${tempAsarPath}`);
342
+ await onInstall(() => renameSync(tempAsarPath, appNameAsarPath), tempAsarPath, appNameAsarPath, logger);
411
343
  }
412
- };
344
+ const mainDir = is.dev ? electronDevDistPath : appNameAsarPath;
345
+ const entry = resolve(__dirname, mainDir, mainPath);
346
+ await beforeStart?.(entry, logger);
347
+ __require(entry)(updaterInstance);
348
+ } catch (error) {
349
+ handleError(error, logger);
350
+ }
413
351
  }
414
352
  export {
415
- DownloadError,
416
- MinimumVersionError,
353
+ ErrorInfo,
417
354
  Updater,
418
- VerifyFailedError,
355
+ UpdaterError,
419
356
  createUpdater,
357
+ downloadBufferDefault,
358
+ downloadJSONDefault,
420
359
  initApp,
360
+ isLowerVersionDefault,
421
361
  startupWithUpdater
422
362
  };