electron-incremental-update 2.0.0-beta.8 → 2.0.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/vite.js CHANGED
@@ -16,7 +16,7 @@ import zlib from 'node:zlib';
16
16
  import crypto from 'node:crypto';
17
17
  import { generate } from 'selfsigned';
18
18
 
19
- // src/vite.ts
19
+ // src/vite/index.ts
20
20
 
21
21
  // src/utils/version.ts
22
22
  function parseVersion(version) {
@@ -38,7 +38,7 @@ function parseVersion(version) {
38
38
  ret.stageVersion = Number(_v) || -1;
39
39
  }
40
40
  if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
41
- throw new TypeError(`invalid version: ${version}`);
41
+ throw new TypeError(`Invalid version: ${version}`);
42
42
  }
43
43
  return ret;
44
44
  }
@@ -64,7 +64,7 @@ var bytecodeId = `${id}-bytecode`;
64
64
  var log = createLogger("info", { prefix: `[${id}]` });
65
65
  var bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
66
66
 
67
- // src/build-plugins/bytecode/code.ts
67
+ // src/vite/bytecode/code.ts
68
68
  var bytecodeGeneratorScript = "const vm = require('vm')\nconst v8 = require('v8')\nconst wrap = require('module').wrap\nv8.setFlagsFromString('--no-lazy')\nv8.setFlagsFromString('--no-flush-bytecode')\nlet code = ''\nprocess.stdin.setEncoding('utf-8')\nprocess.stdin.on('readable', () => {\n const data = process.stdin.read()\n if (data !== null) {\n code += data\n }\n})\nprocess.stdin.on('end', () => {\n try {\n if (typeof code !== 'string') {\n throw new Error('javascript code must be string.')\n }\n const script = new vm.Script(wrap(code), { produceCachedData: true })\n const bytecodeBuffer = script.createCachedData()\n process.stdout.write(bytecodeBuffer)\n } catch (error) {\n console.error(error)\n }\n})\n";
69
69
  var bytecodeModuleLoaderCode = '"use strict";\nconst fs = require("fs");\nconst path = require("path");\nconst vm = require("vm");\nconst v8 = require("v8");\nconst Module = require("module");\nv8.setFlagsFromString("--no-lazy");\nv8.setFlagsFromString("--no-flush-bytecode");\nconst FLAG_HASH_OFFSET = 12;\nconst SOURCE_HASH_OFFSET = 8;\nlet dummyBytecode;\nfunction setFlagHashHeader(bytecodeBuffer) {\n if (!dummyBytecode) {\n const script = new vm.Script("", {\n produceCachedData: true\n });\n dummyBytecode = script.createCachedData();\n }\n dummyBytecode.slice(FLAG_HASH_OFFSET, FLAG_HASH_OFFSET + 4).copy(bytecodeBuffer, FLAG_HASH_OFFSET);\n};\nfunction getSourceHashHeader(bytecodeBuffer) {\n return bytecodeBuffer.slice(SOURCE_HASH_OFFSET, SOURCE_HASH_OFFSET + 4);\n};\nfunction buffer2Number(buffer) {\n let ret = 0;\n ret |= buffer[3] << 24;\n ret |= buffer[2] << 16;\n ret |= buffer[1] << 8;\n ret |= buffer[0];\n return ret;\n};\nModule._extensions[".jsc"] = Module._extensions[".cjsc"] = function (module, filename) {\n const bytecodeBuffer = fs.readFileSync(filename);\n if (!Buffer.isBuffer(bytecodeBuffer)) {\n throw new Error("BytecodeBuffer must be a buffer object.");\n }\n setFlagHashHeader(bytecodeBuffer);\n const length = buffer2Number(getSourceHashHeader(bytecodeBuffer));\n let dummyCode = "";\n if (length > 1) {\n dummyCode = "\\"" + "\\u200b".repeat(length - 2) + "\\"";\n }\n const script = new vm.Script(dummyCode, {\n filename: filename,\n lineOffset: 0,\n displayErrors: true,\n cachedData: bytecodeBuffer\n });\n if (script.cachedDataRejected) {\n throw new Error("Invalid or incompatible cached data (cachedDataRejected)");\n }\n const require = function (id) {\n return module.require(id);\n };\n require.resolve = function (request, options) {\n return Module._resolveFilename(request, module, false, options);\n };\n if (process.mainModule) {\n require.main = process.mainModule;\n }\n require.extensions = Module._extensions;\n require.cache = Module._cache;\n const compiledWrapper = script.runInThisContext({\n filename: filename,\n lineOffset: 0,\n columnOffset: 0,\n displayErrors: true\n });\n const dirname = path.dirname(filename);\n const args = [module.exports, require, module, filename, dirname, process, global];\n return compiledWrapper.apply(module.exports, args);\n};\n';
70
70
  var electronModulePath = getPackageInfoSync("electron")?.rootPath;
@@ -91,7 +91,7 @@ function getElectronPath() {
91
91
  return electronExecPath;
92
92
  }
93
93
  function getBytecodeCompilerPath() {
94
- const scriptPath = path5.join(electronModulePath, "bytenode.cjs");
94
+ const scriptPath = path5.join(electronModulePath, "EIU_bytenode.cjs");
95
95
  if (!fs3.existsSync(scriptPath)) {
96
96
  fs3.writeFileSync(scriptPath, bytecodeGeneratorScript);
97
97
  }
@@ -129,7 +129,7 @@ function compileToBytecode(code) {
129
129
  proc.on("exit", () => resolve(data));
130
130
  });
131
131
  }
132
- function convertArrowToFunction(code) {
132
+ function convertArrowFunctionAndTemplate(code) {
133
133
  const result = babel.transform(code, {
134
134
  plugins: ["@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals"]
135
135
  });
@@ -140,7 +140,7 @@ function convertArrowToFunction(code) {
140
140
  }
141
141
  var decodeFn = ";function _0xstr_(a,b){return String.fromCharCode.apply(0,a.map(function(x){return x-b}))};";
142
142
  function obfuscateString(input, offset = ~~(Math.random() * 16) + 1) {
143
- const hexArray = input.split("").map((c) => "0x" + (c.charCodeAt(0) + offset).toString(16));
143
+ const hexArray = input.split("").map((c) => `0x${(c.charCodeAt(0) + offset).toString(16)}`);
144
144
  return `_0xstr_([${hexArray.join(",")}],${offset})`;
145
145
  }
146
146
  function convertLiteral(code, sourcemap, offset) {
@@ -148,7 +148,7 @@ function convertLiteral(code, sourcemap, offset) {
148
148
  let hasTransformed = false;
149
149
  const ast = babel.parse(code, { ast: true });
150
150
  if (!ast) {
151
- throw new Error("cannot parse code");
151
+ throw new Error("Cannot parse code");
152
152
  }
153
153
  babel.traverse(ast, {
154
154
  StringLiteral(path6) {
@@ -168,6 +168,9 @@ function convertLiteral(code, sourcemap, offset) {
168
168
  if (parent.type.startsWith("Import")) {
169
169
  return;
170
170
  }
171
+ if (parent.type === "ObjectMethod" && parent.key === node) {
172
+ return;
173
+ }
171
174
  if (parent.type === "ObjectProperty" && parent.key === node) {
172
175
  const result2 = `[${obfuscateString(node.value, offset)}]`;
173
176
  const start2 = node.start;
@@ -199,7 +202,7 @@ function convertLiteral(code, sourcemap, offset) {
199
202
  };
200
203
  }
201
204
 
202
- // src/build-plugins/utils.ts
205
+ // src/vite/utils.ts
203
206
  function readableSize(size) {
204
207
  const units = ["B", "KB", "MB", "GB"];
205
208
  let i = 0;
@@ -210,7 +213,7 @@ function readableSize(size) {
210
213
  return `${size.toFixed(2)} ${units[i]}`;
211
214
  }
212
215
 
213
- // src/build-plugins/build.ts
216
+ // src/vite/build.ts
214
217
  async function buildAsar({
215
218
  version,
216
219
  asarOutputPath,
@@ -224,7 +227,7 @@ async function buildAsar({
224
227
  await Asar.createPackage(electronDistPath, asarOutputPath);
225
228
  const buf = await generateGzipFile(fs3.readFileSync(asarOutputPath));
226
229
  fs3.writeFileSync(gzipPath, buf);
227
- log.info(`build update asar to '${gzipPath}' [${readableSize(buf.length)}]`, { timestamp: true });
230
+ log.info(`Build update asar to '${gzipPath}' [${readableSize(buf.length)}]`, { timestamp: true });
228
231
  return buf;
229
232
  }
230
233
  async function buildVersion({
@@ -252,7 +255,7 @@ async function buildVersion({
252
255
  if (isUpdateJSON(oldVersionJson)) {
253
256
  _json = oldVersionJson;
254
257
  } else {
255
- log.warn("old version json is invalid, ignore it", { timestamp: true });
258
+ log.warn("Old version json is invalid, ignore it", { timestamp: true });
256
259
  }
257
260
  } catch {
258
261
  }
@@ -260,7 +263,7 @@ async function buildVersion({
260
263
  const sig = await generateSignature(asarBuffer, privateKey, cert, version);
261
264
  _json = await generateVersionJson(_json, sig, version, minimumVersion);
262
265
  if (!isUpdateJSON(_json)) {
263
- throw new Error("invalid version info");
266
+ throw new Error("Invalid version info");
264
267
  }
265
268
  fs3.writeFileSync(versionPath, JSON.stringify(_json, null, 2));
266
269
  log.info(`build version info to '${versionPath}'`, { timestamp: true });
@@ -272,7 +275,7 @@ async function buildEntry({
272
275
  entryOutputDirPath,
273
276
  nativeModuleEntryMap,
274
277
  overrideEsbuildOptions
275
- }, define, bytecodeOptions) {
278
+ }, isESM, define, bytecodeOptions) {
276
279
  const option = mergeConfig(
277
280
  {
278
281
  entryPoints: {
@@ -292,26 +295,21 @@ async function buildEntry({
292
295
  loader: {
293
296
  ".node": "empty"
294
297
  },
295
- define
298
+ define,
299
+ format: isESM ? "esm" : "cjs"
296
300
  },
297
301
  overrideEsbuildOptions ?? {}
298
302
  );
299
303
  const { metafile } = await build(option);
300
- if (!bytecodeOptions || !bytecodeOptions.enable) {
304
+ if (!bytecodeOptions?.enable) {
301
305
  return;
302
306
  }
303
- const filePaths = Object.keys(metafile?.outputs ?? []);
307
+ const filePaths = Object.keys(metafile?.outputs ?? []).filter((filePath) => filePath.endsWith("js"));
304
308
  for (const filePath of filePaths) {
305
309
  let code = fs3.readFileSync(filePath, "utf-8");
306
310
  const fileName = path5.basename(filePath);
307
311
  const isEntry = fileName.endsWith("entry.js");
308
- if (isEntry) {
309
- code = code.replace(
310
- /(`-----BEGIN CERTIFICATE-----[\s\S]*-----END CERTIFICATE-----\n`)/,
311
- (_, cert) => `"${cert.slice(1, -1).replace(/\n/g, "\\n")}"`
312
- );
313
- }
314
- let transformedCode = convertLiteral(convertArrowToFunction(code).code).code;
312
+ let transformedCode = convertLiteral(convertArrowFunctionAndTemplate(code).code).code;
315
313
  if (bytecodeOptions.beforeCompile) {
316
314
  const result = await bytecodeOptions.beforeCompile(transformedCode, filePath);
317
315
  if (result) {
@@ -382,14 +380,14 @@ function parseKeys({
382
380
  let privateKey = process.env.UPDATER_PK;
383
381
  let cert = process.env.UPDATER_CERT;
384
382
  if (privateKey && cert) {
385
- log.info("use UPDATER_PK and UPDATER_CERT from environment variables", { timestamp: true });
383
+ log.info("Use `UPDATER_PK` and `UPDATER_CERT` from environment variables", { timestamp: true });
386
384
  return { privateKey, cert };
387
385
  }
388
386
  if (!fs3.existsSync(keysDir)) {
389
387
  fs3.mkdirSync(keysDir);
390
388
  }
391
389
  if (!fs3.existsSync(privateKeyPath) || !fs3.existsSync(certPath)) {
392
- log.info("no key pair found, generate new key pair", { timestamp: true });
390
+ log.info("No key pair found, generate new key pair", { timestamp: true });
393
391
  generateKeyPair(keyLength, parseSubjects(subject), days, privateKeyPath, certPath);
394
392
  }
395
393
  privateKey = fs3.readFileSync(privateKeyPath, "utf-8");
@@ -400,7 +398,7 @@ function parseSubjects(subject) {
400
398
  return Object.entries(subject).filter(([_, value]) => !!value).map(([name, value]) => ({ name, value }));
401
399
  }
402
400
 
403
- // src/build-plugins/option.ts
401
+ // src/vite/option.ts
404
402
  function parseOptions(pkg, sourcemap = false, minify = false, options = {}) {
405
403
  const {
406
404
  minimumVersion = "0.0.0",
@@ -482,7 +480,7 @@ function bytecodePlugin(env, options) {
482
480
  return null;
483
481
  }
484
482
  if (!preload && env === "preload") {
485
- bytecodeLog.warn('bytecodePlugin is skiped in preload. To enable in preload, please manually set the "enablePreload" option to true and set `sandbox: false` when creating the window', { timestamp: true });
483
+ bytecodeLog.warn('`bytecodePlugin` is skiped in preload. To enable in preload, please manually set the "enablePreload" option to true and set `sandbox: false` when creating the window', { timestamp: true });
486
484
  return null;
487
485
  }
488
486
  const filter = createFilter(/\.(m?[jt]s|[jt]sx)$/);
@@ -505,7 +503,8 @@ function bytecodePlugin(env, options) {
505
503
  if (options2.format !== "es" && bytecodeRequired) {
506
504
  this.emitFile({
507
505
  type: "asset",
508
- source: bytecodeModuleLoaderCode + "\n",
506
+ source: `${bytecodeModuleLoaderCode}
507
+ `,
509
508
  name: "Bytecode Loader File",
510
509
  fileName: bytecodeModuleLoader
511
510
  });
@@ -514,14 +513,14 @@ function bytecodePlugin(env, options) {
514
513
  renderChunk(code, chunk, options2) {
515
514
  if (options2.format === "es") {
516
515
  bytecodeLog.warn(
517
- 'bytecodePlugin does not support ES module, please remove "type": "module" in package.json or set the "build.rollupOptions.output.format" option to "cjs".',
516
+ '`bytecodePlugin` does not support ES module, please set "build.rollupOptions.output.format" option to "cjs"',
518
517
  { timestamp: true }
519
518
  );
520
519
  return null;
521
520
  }
522
521
  if (chunk.type === "chunk") {
523
522
  bytecodeRequired = true;
524
- return convertArrowToFunction(code);
523
+ return convertArrowFunctionAndTemplate(code);
525
524
  }
526
525
  return null;
527
526
  },
@@ -547,8 +546,9 @@ function bytecodePlugin(env, options) {
547
546
  const chunk = output[name];
548
547
  if (chunk.type === "chunk") {
549
548
  let _code = chunk.code;
549
+ const chunkFilePath = path5.resolve(outDir, name);
550
550
  if (beforeCompile) {
551
- const cbResult = await beforeCompile(_code, chunk.fileName);
551
+ const cbResult = await beforeCompile(_code, chunkFilePath);
552
552
  if (cbResult) {
553
553
  _code = cbResult;
554
554
  }
@@ -559,19 +559,18 @@ function bytecodePlugin(env, options) {
559
559
  while (match = bytecodeRE.exec(_code)) {
560
560
  const [prefix, chunkName] = match;
561
561
  const len = prefix.length + chunkName.length;
562
- s.overwrite(match.index, match.index + len, prefix + chunkName + "c", {
562
+ s.overwrite(match.index, match.index + len, `${prefix + chunkName}c`, {
563
563
  contentOnly: true
564
564
  });
565
565
  }
566
566
  _code = s.toString();
567
567
  }
568
- const chunkFilePath = path5.resolve(outDir, name);
569
568
  if (bytecodeChunks.includes(name)) {
570
569
  const bytecodeBuffer = await compileToBytecode(_code);
571
- fs3.writeFileSync(chunkFilePath + "c", bytecodeBuffer);
570
+ fs3.writeFileSync(`${chunkFilePath}c`, bytecodeBuffer);
572
571
  if (chunk.isEntry) {
573
572
  const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
574
- const bytecodeModuleBlock = `require("./${path5.basename(name) + "c"}");`;
573
+ const bytecodeModuleBlock = `require("./${`${path5.basename(name)}c`}");`;
575
574
  const code = `${useStrict}
576
575
  ${bytecodeLoaderBlock}
577
576
  module.exports=${bytecodeModuleBlock}
@@ -580,7 +579,7 @@ module.exports=${bytecodeModuleBlock}
580
579
  } else {
581
580
  fs3.unlinkSync(chunkFilePath);
582
581
  }
583
- bytecodeFiles.push({ name: name + "c", size: bytecodeBuffer.length });
582
+ bytecodeFiles.push({ name: `${name}c`, size: bytecodeBuffer.length });
584
583
  } else {
585
584
  if (chunk.isEntry) {
586
585
  let hasBytecodeMoudle = false;
@@ -644,12 +643,13 @@ function getMainFilePath(options) {
644
643
  }
645
644
  mainFilePath = options?.index ? "index.js" : "main.js";
646
645
  }
646
+ log.info(`Using "${mainFilePath}" as main file`, { timestamp: true });
647
647
  return mainFilePath.replace(/\.[cm]?ts$/, ".js");
648
648
  }
649
649
  function parseVersionPath(versionPath) {
650
650
  versionPath = normalizePath(versionPath);
651
651
  if (!versionPath.startsWith("./")) {
652
- versionPath = "./" + versionPath;
652
+ versionPath = `./${versionPath}`;
653
653
  }
654
654
  return new URL(versionPath, "file://").pathname.slice(1);
655
655
  }
@@ -667,33 +667,43 @@ async function electronWithUpdater(options) {
667
667
  useNotBundle = true,
668
668
  logParsedOptions
669
669
  } = options;
670
- if (!pkg) {
671
- log.error(`package.json not found`, { timestamp: true });
670
+ if (!pkg || !pkg.version || !pkg.name || !pkg.main) {
671
+ log.error("package.json not found or invalid", { timestamp: true });
672
672
  return void 0;
673
673
  }
674
- if (!pkg.version || !pkg.name || !pkg.main) {
675
- log.error(`package.json not valid`, { timestamp: true });
676
- return void 0;
674
+ const isESM = pkg.type === "module";
675
+ let bytecodeOptions = typeof bytecode === "object" ? bytecode : bytecode === true ? { enable: true } : void 0;
676
+ if (isESM && bytecodeOptions?.enable) {
677
+ bytecodeLog.warn(
678
+ '`bytecodePlugin` does not support ES module, please remove "type": "module" in package.json',
679
+ { timestamp: true }
680
+ );
681
+ bytecodeOptions = void 0;
677
682
  }
678
- const _options = parseOptions(pkg, sourcemap, minify, updater);
679
- const bytecodeOptions = typeof bytecode === "object" ? bytecode : bytecode === true ? { enable: true } : void 0;
683
+ const {
684
+ buildAsarOption,
685
+ buildEntryOption,
686
+ buildVersionOption,
687
+ postBuild,
688
+ cert
689
+ } = parseOptions(pkg, sourcemap, minify, updater);
690
+ const { entryOutputDirPath, nativeModuleEntryMap, appEntryPath } = buildEntryOption;
680
691
  try {
681
- fs3.rmSync(_options.buildAsarOption.electronDistPath, { recursive: true, force: true });
682
- fs3.rmSync(_options.buildEntryOption.entryOutputDirPath, { recursive: true, force: true });
692
+ fs3.rmSync(buildAsarOption.electronDistPath, { recursive: true, force: true });
693
+ fs3.rmSync(entryOutputDirPath, { recursive: true, force: true });
683
694
  } catch {
684
695
  }
685
- log.info(`remove old files`, { timestamp: true });
686
- const { buildAsarOption, buildEntryOption, buildVersionOption, postBuild, cert } = _options;
687
- const { entryOutputDirPath, nativeModuleEntryMap, appEntryPath } = buildEntryOption;
696
+ log.info(`Clear cache files`, { timestamp: true });
688
697
  sourcemap ??= isBuild || !!process.env.VSCODE_DEBUG;
689
698
  const _appPath = normalizePath(path5.join(entryOutputDirPath, "entry.js"));
690
699
  if (path5.resolve(normalizePath(pkg.main)) !== path5.resolve(_appPath)) {
691
- throw new Error(`wrong "main" field in package.json: "${pkg.main}", it should be "${_appPath}"`);
700
+ throw new Error(`Wrong "main" field in package.json: "${pkg.main}", it should be "${_appPath}"`);
692
701
  }
693
702
  const define = {
694
703
  __EIU_ELECTRON_DIST_PATH__: JSON.stringify(buildAsarOption.electronDistPath),
695
704
  __EIU_ENTRY_DIST_PATH__: JSON.stringify(buildEntryOption.entryOutputDirPath),
696
705
  __EIU_IS_DEV__: JSON.stringify(!isBuild),
706
+ __EIU_IS_ESM__: JSON.stringify(isESM),
697
707
  __EIU_MAIN_DEV_DIR__: JSON.stringify(buildAsarOption.electronDistPath),
698
708
  __EIU_MAIN_FILE__: JSON.stringify(getMainFilePath(_main.files)),
699
709
  __EIU_SIGNATURE_CERT__: JSON.stringify(cert),
@@ -702,10 +712,11 @@ async function electronWithUpdater(options) {
702
712
  const _buildEntry = async () => {
703
713
  await buildEntry(
704
714
  buildEntryOption,
715
+ isESM,
705
716
  define,
706
717
  bytecodeOptions
707
718
  );
708
- log.info(`vite build entry to '${entryOutputDirPath}'`, { timestamp: true });
719
+ log.info(`Build entry to '${entryOutputDirPath}'`, { timestamp: true });
709
720
  };
710
721
  const _postBuild = postBuild ? async () => await postBuild({
711
722
  getPathFromEntryOutputDir(...paths) {
@@ -718,7 +729,7 @@ async function electronWithUpdater(options) {
718
729
  try {
719
730
  fs3.cpSync(from, target);
720
731
  } catch (error) {
721
- log.warn(`copy failed: ${error}`);
732
+ log.warn(`Copy failed: ${error}`, { timestamp: true });
722
733
  }
723
734
  }
724
735
  }
@@ -780,7 +791,7 @@ async function electronWithUpdater(options) {
780
791
  await _postBuild();
781
792
  const buffer = await buildAsar(buildAsarOption);
782
793
  if (!buildVersionJson && !isCI) {
783
- log.warn("no `buildVersionJson` setup, skip build version json. Will build in CI by default", { timestamp: true });
794
+ log.warn("No `buildVersionJson` setup, skip build version json. Will build in CI by default", { timestamp: true });
784
795
  } else {
785
796
  await buildVersion(buildVersionOption, buffer);
786
797
  }
@@ -806,7 +817,7 @@ async function electronWithUpdater(options) {
806
817
  ...electronPluginOptions,
807
818
  updater: { buildAsarOption, buildEntryOption, buildVersionOption }
808
819
  },
809
- (key, value) => (key === "privateKey" || key === "cert") && !(typeof logParsedOptions === "object" && logParsedOptions.showKeys === true) ? "***" : value,
820
+ (key, value) => ["privateKey", "cert", "define"].includes(key) && !(typeof logParsedOptions === "object" && logParsedOptions.showKeys === true) ? "***" : value,
810
821
  2
811
822
  ),
812
823
  { timestamp: true }
@@ -837,5 +848,6 @@ async function electronWithUpdater(options) {
837
848
  }
838
849
  return [ElectronSimple(electronPluginOptions), extraHmrPlugin];
839
850
  }
851
+ var vite_default = electronWithUpdater;
840
852
 
841
- export { debugStartup, electronWithUpdater };
853
+ export { debugStartup, vite_default as default, electronWithUpdater };
@@ -1,10 +1,33 @@
1
1
  declare function hashBuffer(data: string | Buffer, length: number): Buffer;
2
2
  declare function aesEncrypt(plainText: string, key: Buffer, iv: Buffer): string;
3
+ /**
4
+ * Default function to generate asar signature, returns generated signature
5
+ * @param buffer file buffer
6
+ * @param privateKey primary key
7
+ * @param cert certificate
8
+ * @param version target version
9
+ */
3
10
  declare function defaultSignature(buffer: Buffer, privateKey: string, cert: string, version: string): string;
4
11
  declare function aesDecrypt(encryptedText: string, key: Buffer, iv: Buffer): string;
12
+ /**
13
+ * Default function to verify asar signature,
14
+ * if signature is valid, returns the version, otherwise returns `undefined`
15
+ * @param buffer file buffer
16
+ * @param version target version
17
+ * @param signature signature
18
+ * @param cert certificate
19
+ */
5
20
  declare function defaultVerifySignature(buffer: Buffer, version: string, signature: string, cert: string): boolean;
6
21
 
22
+ /**
23
+ * Default function to compress file using brotli
24
+ * @param buffer uncompressed file buffer
25
+ */
7
26
  declare function defaultZipFile(buffer: Buffer): Promise<Buffer>;
27
+ /**
28
+ * Default function to decompress file using brotli
29
+ * @param buffer compressed file buffer
30
+ */
8
31
  declare function defaultUnzipFile(buffer: Buffer): Promise<Buffer>;
9
32
 
10
33
  export { defaultUnzipFile as a, aesEncrypt as b, defaultSignature as c, defaultZipFile as d, aesDecrypt as e, defaultVerifySignature as f, hashBuffer as h };
@@ -1,10 +1,33 @@
1
1
  declare function hashBuffer(data: string | Buffer, length: number): Buffer;
2
2
  declare function aesEncrypt(plainText: string, key: Buffer, iv: Buffer): string;
3
+ /**
4
+ * Default function to generate asar signature, returns generated signature
5
+ * @param buffer file buffer
6
+ * @param privateKey primary key
7
+ * @param cert certificate
8
+ * @param version target version
9
+ */
3
10
  declare function defaultSignature(buffer: Buffer, privateKey: string, cert: string, version: string): string;
4
11
  declare function aesDecrypt(encryptedText: string, key: Buffer, iv: Buffer): string;
12
+ /**
13
+ * Default function to verify asar signature,
14
+ * if signature is valid, returns the version, otherwise returns `undefined`
15
+ * @param buffer file buffer
16
+ * @param version target version
17
+ * @param signature signature
18
+ * @param cert certificate
19
+ */
5
20
  declare function defaultVerifySignature(buffer: Buffer, version: string, signature: string, cert: string): boolean;
6
21
 
22
+ /**
23
+ * Default function to compress file using brotli
24
+ * @param buffer uncompressed file buffer
25
+ */
7
26
  declare function defaultZipFile(buffer: Buffer): Promise<Buffer>;
27
+ /**
28
+ * Default function to decompress file using brotli
29
+ * @param buffer compressed file buffer
30
+ */
8
31
  declare function defaultUnzipFile(buffer: Buffer): Promise<Buffer>;
9
32
 
10
33
  export { defaultUnzipFile as a, aesEncrypt as b, defaultSignature as c, defaultZipFile as d, aesDecrypt as e, defaultVerifySignature as f, hashBuffer as h };
package/package.json CHANGED
@@ -1,11 +1,14 @@
1
1
  {
2
2
  "name": "electron-incremental-update",
3
3
  "type": "module",
4
- "version": "2.0.0-beta.8",
5
- "description": "electron incremental update tools, powered by vite",
4
+ "version": "2.0.0",
5
+ "description": "Electron incremental update tools with Vite plugin, support bytecode protection",
6
6
  "author": "subframe7536",
7
7
  "license": "MIT",
8
- "repository": "https://github.com/subframe7536/electron-incremental-update",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/subframe7536/electron-incremental-update.git"
11
+ },
9
12
  "keywords": [
10
13
  "electron",
11
14
  "incremental update",
@@ -70,15 +73,15 @@
70
73
  "devDependencies": {
71
74
  "@subframe7536/eslint-config": "^0.7.3",
72
75
  "@types/babel__core": "^7.20.5",
73
- "@types/node": "^20.14.11",
76
+ "@types/node": "^20.14.12",
74
77
  "bumpp": "^9.4.1",
75
78
  "electron": "28.2.10",
76
79
  "eslint": "^9.7.0",
77
80
  "esno": "^4.7.0",
78
- "tsup": "^8.2.1",
79
- "typescript": "^5.5.3",
81
+ "tsup": "^8.2.2",
82
+ "typescript": "^5.5.4",
80
83
  "vite": "^5.3.4",
81
84
  "vite-plugin-electron": "^0.28.7",
82
- "vitest": "^2.0.3"
85
+ "vitest": "^2.0.4"
83
86
  }
84
87
  }
@@ -1,81 +0,0 @@
1
- import { __require } from './chunk-72ZAJ7AF.js';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import { app } from 'electron';
5
-
6
- var isDev = __EIU_IS_DEV__;
7
- var isWin = process.platform === "win32";
8
- var isMac = process.platform === "darwin";
9
- var isLinux = process.platform === "linux";
10
- function getPathFromAppNameAsar(...paths) {
11
- return isDev ? "DEV.asar" : path.join(path.dirname(app.getAppPath()), `${app.name}.asar`, ...paths);
12
- }
13
- function getAppVersion() {
14
- return isDev ? getEntryVersion() : fs.readFileSync(getPathFromAppNameAsar("version"), "utf-8");
15
- }
16
- function getEntryVersion() {
17
- return app.getVersion();
18
- }
19
- function requireNative(moduleName) {
20
- return __require(path.join(app.getAppPath(), __EIU_ENTRY_DIST_PATH__, moduleName));
21
- }
22
- function restartApp() {
23
- app.relaunch();
24
- app.quit();
25
- }
26
- function setAppUserModelId(id) {
27
- if (isWin) {
28
- app.setAppUserModelId(id ?? `org.${app.name}`);
29
- }
30
- }
31
- function disableHWAccForWin7() {
32
- if (__require("node:os").release().startsWith("6.1")) {
33
- app.disableHardwareAcceleration();
34
- }
35
- }
36
- function singleInstance(window) {
37
- const result = app.requestSingleInstanceLock();
38
- if (result) {
39
- app.on("second-instance", () => {
40
- if (window) {
41
- window.show();
42
- if (window.isMinimized()) {
43
- window.restore();
44
- }
45
- window.focus();
46
- }
47
- });
48
- } else {
49
- app.quit();
50
- }
51
- return result;
52
- }
53
- function setPortableAppDataPath(dirName = "data") {
54
- const portablePath = path.join(path.dirname(app.getPath("exe")), dirName);
55
- if (!fs.existsSync(portablePath)) {
56
- fs.mkdirSync(portablePath);
57
- }
58
- app.setPath("appData", portablePath);
59
- }
60
- function loadPage(win, htmlFilePath = "index.html") {
61
- if (isDev) {
62
- win.loadURL(process.env.VITE_DEV_SERVER_URL + htmlFilePath);
63
- } else {
64
- win.loadFile(getPathFromAppNameAsar("renderer", htmlFilePath));
65
- }
66
- }
67
- function getPathFromPreload(...paths) {
68
- return isDev ? path.join(app.getAppPath(), __EIU_ELECTRON_DIST_PATH__, "preload", ...paths) : getPathFromAppNameAsar("preload", ...paths);
69
- }
70
- function getPathFromPublic(...paths) {
71
- return isDev ? path.join(app.getAppPath(), "public", ...paths) : getPathFromAppNameAsar("renderer", ...paths);
72
- }
73
- function getPathFromEntryAsar(...paths) {
74
- return path.join(app.getAppPath(), __EIU_ENTRY_DIST_PATH__, ...paths);
75
- }
76
- function handleUnexpectedErrors(callback) {
77
- process.on("uncaughtException", callback);
78
- process.on("unhandledRejection", callback);
79
- }
80
-
81
- export { disableHWAccForWin7, getAppVersion, getEntryVersion, getPathFromAppNameAsar, getPathFromEntryAsar, getPathFromPreload, getPathFromPublic, handleUnexpectedErrors, isDev, isLinux, isMac, isWin, loadPage, requireNative, restartApp, setAppUserModelId, setPortableAppDataPath, singleInstance };