electron-incremental-update 2.4.3 → 3.0.0-beta.3

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 (47) hide show
  1. package/README.md +48 -40
  2. package/dist/download-BN4uMS4_.d.mts +39 -0
  3. package/dist/download-DO7iuxEJ.d.cts +39 -0
  4. package/dist/electron-DH-Uyikp.cjs +321 -0
  5. package/dist/electron-OKQIYbcw.mjs +181 -0
  6. package/dist/index.cjs +261 -331
  7. package/dist/index.d.cts +179 -169
  8. package/dist/index.d.mts +204 -0
  9. package/dist/index.mjs +273 -0
  10. package/dist/provider.cjs +142 -330
  11. package/dist/provider.d.cts +113 -114
  12. package/dist/provider.d.mts +133 -0
  13. package/dist/provider.mjs +152 -0
  14. package/dist/types-BM9Jfu7q.d.cts +154 -0
  15. package/dist/types-DASqEPXE.d.mts +154 -0
  16. package/dist/utils.cjs +43 -381
  17. package/dist/utils.d.cts +120 -85
  18. package/dist/utils.d.mts +164 -0
  19. package/dist/utils.mjs +5 -0
  20. package/dist/version--eVB2A7n.mjs +72 -0
  21. package/dist/version-aPrLuz_-.cjs +129 -0
  22. package/dist/vite.d.mts +521 -0
  23. package/dist/vite.mjs +1094 -0
  24. package/dist/zip-BCC7FAQ_.cjs +264 -0
  25. package/dist/zip-Dwm7s1C9.mjs +185 -0
  26. package/package.json +66 -64
  27. package/dist/chunk-AAAM44NW.js +0 -70
  28. package/dist/chunk-IVHNGRZY.js +0 -122
  29. package/dist/chunk-PD4EV4MM.js +0 -147
  30. package/dist/index.d.ts +0 -194
  31. package/dist/index.js +0 -309
  32. package/dist/provider.d.ts +0 -134
  33. package/dist/provider.js +0 -152
  34. package/dist/types-CU7GyVez.d.cts +0 -151
  35. package/dist/types-CU7GyVez.d.ts +0 -151
  36. package/dist/utils.d.ts +0 -129
  37. package/dist/utils.js +0 -3
  38. package/dist/vite.d.ts +0 -533
  39. package/dist/vite.js +0 -945
  40. package/dist/zip-Blmn2vzE.d.cts +0 -71
  41. package/dist/zip-CnSv_Njj.d.ts +0 -71
  42. package/provider.d.ts +0 -1
  43. package/provider.js +0 -1
  44. package/utils.d.ts +0 -1
  45. package/utils.js +0 -1
  46. package/vite.d.ts +0 -1
  47. package/vite.js +0 -1
package/dist/vite.js DELETED
@@ -1,945 +0,0 @@
1
- import cp from 'child_process';
2
- import fs5 from 'fs';
3
- import path5 from 'path';
4
- import * as babel from '@babel/core';
5
- import { getPackageInfoSync, loadPackageJSON } from 'local-pkg';
6
- export { getPackageInfo, getPackageInfoSync, loadPackageJSON, resolveModule } from 'local-pkg';
7
- import MagicString from 'magic-string';
8
- import { createLogger, normalizePath, mergeConfig, createFilter } from 'vite';
9
- import { isCI } from 'ci-info';
10
- export { isCI } from 'ci-info';
11
- import { startup, build } from 'vite-plugin-electron';
12
- import { notBundle } from 'vite-plugin-electron/plugin';
13
- import ElectronSimple from 'vite-plugin-electron/simple';
14
- import Asar from '@electron/asar';
15
- import { builtinModules } from 'module';
16
- import crypto from 'crypto';
17
- import zlib from 'zlib';
18
- import { generate } from 'selfsigned';
19
-
20
- // src/vite/bytecode/utils.ts
21
-
22
- // src/utils/version.ts
23
- function parseVersion(version) {
24
- const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
25
- if (!match) {
26
- throw new TypeError(`invalid version: ${version}`);
27
- }
28
- const [major, minor, patch] = match.slice(1, 4).map(Number);
29
- const ret = {
30
- major,
31
- minor,
32
- patch,
33
- stage: "",
34
- stageVersion: -1
35
- };
36
- if (match[4]) {
37
- let [stage, _v] = match[4].split(".");
38
- ret.stage = stage;
39
- ret.stageVersion = Number(_v) || -1;
40
- }
41
- if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
42
- throw new TypeError(`Invalid version: ${version}`);
43
- }
44
- return ret;
45
- }
46
- var is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
47
- function isUpdateJSON(json) {
48
- return is(json) && is(json?.beta);
49
- }
50
- function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
51
- existingJson.beta = {
52
- version,
53
- minimumVersion,
54
- signature
55
- };
56
- if (!parseVersion(version).stage) {
57
- existingJson.version = version;
58
- existingJson.minimumVersion = minimumVersion;
59
- existingJson.signature = signature;
60
- }
61
- return existingJson;
62
- }
63
- var id = "electron-incremental-updater";
64
- var bytecodeId = `${id}-bytecode`;
65
- var esmId = `${id}-esm`;
66
- var log = createLogger("info", { prefix: `[${id}]` });
67
- var bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
68
-
69
- // src/vite/bytecode/code.ts
70
- 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";
71
- 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';
72
-
73
- // src/vite/bytecode/utils.ts
74
- var electronModule = getPackageInfoSync("electron");
75
- var electronMajorVersion = parseVersion(electronModule.version).major;
76
- var useStrict = "'use strict';";
77
- var bytecodeModuleLoader = "__loader__.js";
78
- function getElectronPath() {
79
- const electronModulePath = electronModule.rootPath;
80
- let electronExecPath = process.env.ELECTRON_EXEC_PATH || "";
81
- if (!electronExecPath) {
82
- if (!electronModulePath) {
83
- throw new Error("Electron is not installed");
84
- }
85
- const pathFile = path5.join(electronModulePath, "path.txt");
86
- let executablePath;
87
- if (fs5.existsSync(pathFile)) {
88
- executablePath = fs5.readFileSync(pathFile, "utf-8");
89
- }
90
- if (executablePath) {
91
- electronExecPath = path5.join(electronModulePath, "dist", executablePath);
92
- process.env.ELECTRON_EXEC_PATH = electronExecPath;
93
- } else {
94
- throw new Error("Electron executable file is not existed");
95
- }
96
- }
97
- return electronExecPath;
98
- }
99
- function getBytecodeCompilerPath() {
100
- const scriptPath = path5.join(electronModule.rootPath, "EIU_bytenode.cjs");
101
- if (!fs5.existsSync(scriptPath)) {
102
- fs5.writeFileSync(scriptPath, bytecodeGeneratorScript);
103
- }
104
- return scriptPath;
105
- }
106
- function toRelativePath(filename, importer) {
107
- const relPath = path5.posix.relative(path5.dirname(importer), filename);
108
- return relPath.startsWith(".") ? relPath : `./${relPath}`;
109
- }
110
- var logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
111
- function compileToBytecode(code, electronPath = getElectronPath()) {
112
- let data = Buffer.from([]);
113
- const bytecodePath = getBytecodeCompilerPath();
114
- return new Promise((resolve, reject) => {
115
- const proc = cp.spawn(electronPath, [bytecodePath], {
116
- env: { ELECTRON_RUN_AS_NODE: "1" },
117
- stdio: ["pipe", "pipe", "pipe", "ipc"]
118
- });
119
- if (proc.stdin) {
120
- proc.stdin.write(code);
121
- proc.stdin.end();
122
- }
123
- if (proc.stdout) {
124
- proc.stdout.on("data", (chunk) => data = Buffer.concat([data, chunk]));
125
- proc.stdout.on("error", (err) => logErr(err));
126
- proc.stdout.on("end", () => resolve(data));
127
- }
128
- if (proc.stderr) {
129
- proc.stderr.on("data", (chunk) => logErr("Error: ", chunk.toString()));
130
- proc.stderr.on("error", (err) => logErr("Error: ", err));
131
- }
132
- proc.addListener("error", (err) => logErr(err));
133
- proc.on("error", (err) => reject(err));
134
- proc.on("exit", () => resolve(data));
135
- });
136
- }
137
- function convertArrowFunctionAndTemplate(code) {
138
- const result = babel.transform(code, {
139
- plugins: ["@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals"]
140
- });
141
- return {
142
- code: result?.code || code,
143
- map: result?.map
144
- };
145
- }
146
- var decodeFn = ";function _0xstr_(a,b){return String.fromCharCode.apply(0,a.map(function(x){return x-b}))};";
147
- function obfuscateString(input, offset = ~~(Math.random() * 16) + 1) {
148
- const hexArray = input.split("").map((c) => `0x${(c.charCodeAt(0) + offset).toString(16)}`);
149
- return `_0xstr_([${hexArray.join(",")}],${offset})`;
150
- }
151
- function convertLiteral(code, sourcemap, offset) {
152
- const s = new MagicString(code);
153
- let hasTransformed = false;
154
- const ast = babel.parse(code, { ast: true });
155
- if (!ast) {
156
- throw new Error("Cannot parse code");
157
- }
158
- babel.traverse(ast, {
159
- StringLiteral(path6) {
160
- const parent = path6.parent;
161
- const node = path6.node;
162
- if (parent.type === "CallExpression") {
163
- if (parent.callee.type === "Identifier" && parent.callee.name === "require") {
164
- return;
165
- }
166
- if (parent.callee.type === "Import") {
167
- return;
168
- }
169
- }
170
- if (parent.type.startsWith("Export")) {
171
- return;
172
- }
173
- if (parent.type.startsWith("Import")) {
174
- return;
175
- }
176
- if (parent.type === "ObjectMethod" && parent.key === node) {
177
- return;
178
- }
179
- if (parent.type === "ObjectProperty" && parent.key === node) {
180
- const result2 = `[${obfuscateString(node.value, offset)}]`;
181
- const start2 = node.start;
182
- const end2 = node.end;
183
- if (start2 && end2) {
184
- s.overwrite(start2, end2, result2);
185
- hasTransformed = true;
186
- }
187
- return;
188
- }
189
- if (!node.value.trim()) {
190
- return;
191
- }
192
- const result = obfuscateString(node.value, offset);
193
- const start = node.start;
194
- const end = node.end;
195
- if (start && end) {
196
- s.overwrite(start, end, result);
197
- hasTransformed = true;
198
- }
199
- }
200
- });
201
- if (hasTransformed) {
202
- s.append("\n").append(decodeFn);
203
- }
204
- return {
205
- code: s.toString(),
206
- map: sourcemap ? s.generateMap({ hires: true }) : void 0
207
- };
208
- }
209
- function readableSize(size) {
210
- const units = ["B", "KB", "MB", "GB"];
211
- let i = 0;
212
- while (size >= 1024 && i < units.length - 1) {
213
- size /= 1024;
214
- i++;
215
- }
216
- return `${size.toFixed(2)} ${units[i]}`;
217
- }
218
- function copyAndSkipIfExist(from, to, skipIfExist) {
219
- if (!skipIfExist || !fs5.existsSync(to)) {
220
- try {
221
- fs5.cpSync(from, to, { recursive: true });
222
- } catch (error) {
223
- log.warn(`Copy failed: ${error}`, { timestamp: true });
224
- }
225
- }
226
- }
227
-
228
- // src/vite/bytecode/index.ts
229
- function getBytecodeLoaderBlock(chunkFileName) {
230
- return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
231
- }
232
- function bytecodePlugin(env, options) {
233
- const {
234
- enable,
235
- preload = false,
236
- electronPath,
237
- beforeCompile
238
- } = options;
239
- if (!enable) {
240
- return null;
241
- }
242
- if (!preload && env === "preload") {
243
- 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 });
244
- return null;
245
- }
246
- const filter = createFilter(/\.(m?[jt]s|[jt]sx)$/);
247
- let config;
248
- let bytecodeRequired = false;
249
- let bytecodeFiles = [];
250
- return {
251
- name: `${bytecodeId}-${env}`,
252
- apply: "build",
253
- enforce: "post",
254
- configResolved(resolvedConfig) {
255
- config = resolvedConfig;
256
- },
257
- transform(code, id2) {
258
- if (!filter(id2)) {
259
- return convertLiteral(code, !!config.build.sourcemap);
260
- }
261
- },
262
- generateBundle(options2) {
263
- if (options2.format !== "es" && bytecodeRequired) {
264
- this.emitFile({
265
- type: "asset",
266
- source: `${bytecodeModuleLoaderCode}
267
- `,
268
- name: "Bytecode Loader File",
269
- fileName: bytecodeModuleLoader
270
- });
271
- }
272
- },
273
- renderChunk(code, chunk, options2) {
274
- if (options2.format === "es") {
275
- bytecodeLog.warn(
276
- '`bytecodePlugin` does not support ES module, please set "build.rollupOptions.output.format" option to "cjs"',
277
- { timestamp: true }
278
- );
279
- return null;
280
- }
281
- if (chunk.type === "chunk") {
282
- bytecodeRequired = true;
283
- return convertArrowFunctionAndTemplate(code);
284
- }
285
- return null;
286
- },
287
- async writeBundle(options2, output) {
288
- if (options2.format === "es" || !bytecodeRequired) {
289
- return;
290
- }
291
- const outDir = options2.dir;
292
- bytecodeFiles = [];
293
- const bundles = Object.keys(output);
294
- const chunks = Object.values(output).filter(
295
- (chunk) => chunk.type === "chunk" && chunk.fileName !== bytecodeModuleLoader
296
- );
297
- const bytecodeChunks = chunks.map((chunk) => chunk.fileName);
298
- const nonEntryChunks = chunks.filter((chunk) => !chunk.isEntry).map((chunk) => path5.basename(chunk.fileName));
299
- const pattern = nonEntryChunks.map((chunk) => `(${chunk})`).join("|");
300
- const bytecodeRE = pattern ? new RegExp(`require\\(\\S*(?=(${pattern})\\S*\\))`, "g") : null;
301
- await Promise.all(
302
- bundles.map(async (name) => {
303
- const chunk = output[name];
304
- if (chunk.type === "chunk") {
305
- let _code = chunk.code;
306
- const chunkFilePath = path5.resolve(outDir, name);
307
- if (beforeCompile) {
308
- const cbResult = await beforeCompile(_code, chunkFilePath);
309
- if (cbResult) {
310
- _code = cbResult;
311
- }
312
- }
313
- if (bytecodeRE && _code.match(bytecodeRE)) {
314
- let match;
315
- const s = new MagicString(_code);
316
- while (match = bytecodeRE.exec(_code)) {
317
- const [prefix, chunkName] = match;
318
- const len = prefix.length + chunkName.length;
319
- s.overwrite(match.index, match.index + len, `${prefix + chunkName}c`, {
320
- contentOnly: true
321
- });
322
- }
323
- _code = s.toString();
324
- }
325
- if (bytecodeChunks.includes(name)) {
326
- const bytecodeBuffer = await compileToBytecode(_code, electronPath);
327
- fs5.writeFileSync(`${chunkFilePath}c`, bytecodeBuffer);
328
- if (chunk.isEntry) {
329
- const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
330
- const bytecodeModuleBlock = `require("./${`${path5.basename(name)}c`}");`;
331
- const code = `${useStrict}
332
- ${bytecodeLoaderBlock}
333
- module.exports=${bytecodeModuleBlock}
334
- `;
335
- fs5.writeFileSync(chunkFilePath, code);
336
- } else {
337
- fs5.unlinkSync(chunkFilePath);
338
- }
339
- bytecodeFiles.push({ name: `${name}c`, size: bytecodeBuffer.length });
340
- } else {
341
- if (chunk.isEntry) {
342
- let hasBytecodeMoudle = false;
343
- const idsToHandle = /* @__PURE__ */ new Set([...chunk.imports, ...chunk.dynamicImports]);
344
- for (const moduleId of idsToHandle) {
345
- if (bytecodeChunks.includes(moduleId)) {
346
- hasBytecodeMoudle = true;
347
- break;
348
- }
349
- const moduleInfo = this.getModuleInfo(moduleId);
350
- if (moduleInfo && !moduleInfo.isExternal) {
351
- const { importers, dynamicImporters } = moduleInfo;
352
- for (const importerId of importers) {
353
- idsToHandle.add(importerId);
354
- }
355
- for (const importerId of dynamicImporters) {
356
- idsToHandle.add(importerId);
357
- }
358
- }
359
- }
360
- const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
361
- _code = hasBytecodeMoudle ? _code.replace(
362
- new RegExp(`(${useStrict})|("use strict";)`),
363
- `${useStrict}
364
- ${bytecodeLoaderBlock}`
365
- ) : _code;
366
- }
367
- fs5.writeFileSync(chunkFilePath, _code);
368
- }
369
- }
370
- })
371
- );
372
- },
373
- closeBundle() {
374
- const outDir = `${normalizePath(path5.relative(config.root, path5.resolve(config.root, config.build.outDir)))}/`;
375
- bytecodeFiles.forEach((file) => {
376
- bytecodeLog.info(
377
- `${outDir}${file.name} [${readableSize(file.size)}]`,
378
- { timestamp: true }
379
- );
380
- });
381
- bytecodeLog.info(`${bytecodeFiles.length} bundles compiled into bytecode.`, { timestamp: true });
382
- bytecodeFiles = [];
383
- }
384
- };
385
- }
386
-
387
- // src/vite/esm/constant.ts
388
- var CJSShim = `
389
- // -- CommonJS Shims --
390
- import __cjs_url__ from 'node:url';
391
- import __cjs_path__ from 'node:path';
392
- import __cjs_mod__ from 'node:module';
393
- var __filename = __cjs_url__.fileURLToPath(import.meta.url);
394
- var __dirname = __cjs_path__.dirname(__filename);
395
- var require = __cjs_mod__.createRequire(import.meta.url);
396
- `;
397
- var CJSShim_electron_30 = `
398
- // -- CommonJS Shims --
399
- import __cjs_mod__ from 'node:module';
400
- var __filename = import.meta.filename;
401
- var __dirname = import.meta.dirname;
402
- var require = __cjs_mod__.createRequire(import.meta.url);
403
- `;
404
- var shim = electronMajorVersion >= 30 ? CJSShim_electron_30 : CJSShim;
405
-
406
- // src/vite/esm/utils.ts
407
- var ESMStaticImportRe = /(?<=\s|^|;)import\s*([\s"']*(?<imports>[\p{L}\p{M}\w\t\n\r $*,/{}@.]+)from\s*)?["']\s*(?<specifier>(?<=")[^"]*[^\s"](?=\s*")|(?<=')[^']*[^\s'](?=\s*'))\s*["'][\s;]*/gmu;
408
- function findStaticImports(code) {
409
- const matches = [];
410
- for (const match of code.matchAll(ESMStaticImportRe)) {
411
- matches.push({ end: (match.index || 0) + match[0].length });
412
- }
413
- return matches;
414
- }
415
- function insertCJSShim(code, sourcemap, insertPosition = 0) {
416
- if (code.includes(shim) || !/__filename|__dirname|require\(|require\.resolve\(|require\.apply\(/.test(code)) {
417
- return null;
418
- }
419
- const s = new MagicString(code);
420
- s.appendRight(insertPosition, shim);
421
- return {
422
- code: s.toString(),
423
- map: sourcemap ? s.generateMap({ hires: "boundary" }) : null
424
- };
425
- }
426
-
427
- // src/vite/esm/index.ts
428
- function esm() {
429
- let sourcemap;
430
- return {
431
- name: esmId,
432
- enforce: "post",
433
- configResolved(config) {
434
- sourcemap = config.build.sourcemap;
435
- },
436
- renderChunk(code, _chunk, options) {
437
- if (options.format === "es") {
438
- const lastESMImport = findStaticImports(code).pop();
439
- const pos = lastESMImport ? lastESMImport.end : 0;
440
- return insertCJSShim(code, sourcemap, pos);
441
- }
442
- }
443
- };
444
- }
445
-
446
- // src/vite/build.ts
447
- async function buildAsar({
448
- version,
449
- asarOutputPath,
450
- gzipPath,
451
- electronDistPath,
452
- rendererDistPath,
453
- generateGzipFile
454
- }) {
455
- fs5.renameSync(rendererDistPath, path5.join(electronDistPath, "renderer"));
456
- fs5.writeFileSync(path5.join(electronDistPath, "version"), version);
457
- await Asar.createPackage(electronDistPath, asarOutputPath);
458
- const buf = await generateGzipFile(fs5.readFileSync(asarOutputPath));
459
- fs5.writeFileSync(gzipPath, buf);
460
- log.info(`Build update asar to '${gzipPath}' [${readableSize(buf.length)}]`, { timestamp: true });
461
- return buf;
462
- }
463
- async function buildUpdateJson({
464
- versionPath,
465
- privateKey,
466
- cert,
467
- version,
468
- minimumVersion,
469
- generateSignature,
470
- generateUpdateJson
471
- }, asarBuffer) {
472
- let _json = {
473
- beta: {
474
- minimumVersion: version,
475
- signature: "",
476
- version
477
- },
478
- minimumVersion: version,
479
- signature: "",
480
- version
481
- };
482
- if (fs5.existsSync(versionPath)) {
483
- try {
484
- const oldVersionJson = JSON.parse(fs5.readFileSync(versionPath, "utf-8"));
485
- if (isUpdateJSON(oldVersionJson)) {
486
- _json = oldVersionJson;
487
- } else {
488
- log.warn("Old version json is invalid, ignore it", { timestamp: true });
489
- }
490
- } catch {
491
- }
492
- }
493
- const sig = await generateSignature(asarBuffer, privateKey, cert, version);
494
- _json = await generateUpdateJson(_json, sig, version, minimumVersion);
495
- if (!isUpdateJSON(_json)) {
496
- throw new Error("Invalid update json");
497
- }
498
- fs5.writeFileSync(versionPath, JSON.stringify(_json, null, 2));
499
- log.info(`build update json to '${versionPath}'`, { timestamp: true });
500
- }
501
- async function buildEntry({
502
- sourcemap,
503
- minify,
504
- appEntryPath,
505
- entryOutputDirPath,
506
- nativeModuleEntryMap,
507
- ignoreDynamicRequires,
508
- external,
509
- overrideViteOptions
510
- }, isESM, define, bytecodeOptions) {
511
- await build({
512
- entry: {
513
- entry: appEntryPath,
514
- ...nativeModuleEntryMap
515
- },
516
- vite: mergeConfig({
517
- plugins: [
518
- isESM && esm(),
519
- bytecodeOptions && bytecodePlugin("main", bytecodeOptions)
520
- ],
521
- build: {
522
- sourcemap,
523
- minify,
524
- outDir: entryOutputDirPath,
525
- commonjsOptions: { ignoreDynamicRequires },
526
- rollupOptions: { external }
527
- },
528
- define
529
- }, overrideViteOptions ?? {})
530
- });
531
- }
532
- function hashBuffer(data, length) {
533
- const hash = crypto.createHash("SHA256").update(data).digest("binary");
534
- return Buffer.from(hash).subarray(0, length);
535
- }
536
- function aesEncrypt(plainText, key, iv) {
537
- const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
538
- return cipher.update(plainText, "utf8", "base64url") + cipher.final("base64url");
539
- }
540
- function defaultSignature(buffer, privateKey, cert, version) {
541
- const sig = crypto.createSign("RSA-SHA256").update(buffer).sign(crypto.createPrivateKey(privateKey), "base64");
542
- return aesEncrypt(`${sig}%${version}`, hashBuffer(cert, 32), hashBuffer(buffer, 16));
543
- }
544
- async function defaultZipFile(buffer) {
545
- return new Promise((resolve, reject) => {
546
- zlib.brotliCompress(buffer, (err, buffer2) => err ? reject(err) : resolve(buffer2));
547
- });
548
- }
549
- function generateKeyPair(keyLength, subject, days, privateKeyPath, certPath) {
550
- const privateKeyDir = path5.dirname(privateKeyPath);
551
- if (!fs5.existsSync(privateKeyDir)) {
552
- fs5.mkdirSync(privateKeyDir, { recursive: true });
553
- }
554
- const certDir = path5.dirname(certPath);
555
- if (!fs5.existsSync(certDir)) {
556
- fs5.mkdirSync(certDir, { recursive: true });
557
- }
558
- const { cert, private: privateKey } = generate(subject, {
559
- keySize: keyLength,
560
- algorithm: "sha256",
561
- days
562
- });
563
- fs5.writeFileSync(privateKeyPath, privateKey.replace(/\r\n?/g, "\n"));
564
- fs5.writeFileSync(certPath, cert.replace(/\r\n?/g, "\n"));
565
- }
566
- function parseKeys({
567
- keyLength,
568
- privateKeyPath,
569
- certPath,
570
- subject,
571
- days
572
- }) {
573
- const keysDir = path5.dirname(privateKeyPath);
574
- let privateKey = process.env.UPDATER_PK;
575
- let cert = process.env.UPDATER_CERT;
576
- if (privateKey && cert) {
577
- log.info("Use `UPDATER_PK` and `UPDATER_CERT` from environment variables", { timestamp: true });
578
- return { privateKey, cert };
579
- }
580
- if (!fs5.existsSync(keysDir)) {
581
- fs5.mkdirSync(keysDir);
582
- }
583
- if (!fs5.existsSync(privateKeyPath) || !fs5.existsSync(certPath)) {
584
- log.info("No key pair found, generate new key pair", { timestamp: true });
585
- generateKeyPair(keyLength, parseSubjects(subject), days, privateKeyPath, certPath);
586
- }
587
- privateKey = fs5.readFileSync(privateKeyPath, "utf-8");
588
- cert = fs5.readFileSync(certPath, "utf-8");
589
- return { privateKey, cert };
590
- }
591
- function parseSubjects(subject) {
592
- return Object.entries(subject).filter(([_, value]) => !!value).map(([name, value]) => ({ name, value }));
593
- }
594
-
595
- // src/vite/option.ts
596
- function parseOptions(isBuild, pkg, sourcemap = false, minify = false, options = {}) {
597
- const {
598
- minimumVersion = "0.0.0",
599
- entry: {
600
- minify: entryMinify,
601
- sourcemap: entrySourcemap,
602
- entryOutputDirPath = "dist-entry",
603
- appEntryPath = "electron/entry.ts",
604
- nativeModuleEntryMap = {},
605
- postBuild,
606
- ignoreDynamicRequires = false,
607
- external = [
608
- /^node:.*/,
609
- /.*\.(node|dll|dylib|so)$/,
610
- "original-fs",
611
- ...builtinModules,
612
- ...isBuild || postBuild ? [] : Object.keys("dependencies" in pkg ? pkg.dependencies : {})
613
- ],
614
- overrideViteOptions = {}
615
- } = {},
616
- paths: {
617
- asarOutputPath = `release/${pkg.name}.asar`,
618
- gzipPath = `release/${pkg.name}-${pkg.version}.asar.gz`,
619
- electronDistPath = "dist-electron",
620
- rendererDistPath = "dist",
621
- versionPath = "version.json"
622
- } = {},
623
- keys: {
624
- privateKeyPath = "keys/private.pem",
625
- certPath = "keys/cert.pem",
626
- keyLength = 2048,
627
- certInfo: {
628
- subject = {
629
- commonName: pkg.name,
630
- organizationName: `org.${pkg.name}`
631
- },
632
- days = 3650
633
- } = {}
634
- } = {},
635
- overrideGenerator: {
636
- generateGzipFile = defaultZipFile,
637
- generateSignature = defaultSignature,
638
- generateUpdateJson = defaultVersionJsonGenerator
639
- } = {}
640
- } = options;
641
- const buildAsarOption = {
642
- version: pkg.version,
643
- asarOutputPath,
644
- gzipPath,
645
- electronDistPath,
646
- rendererDistPath,
647
- generateGzipFile
648
- };
649
- const buildEntryOption = {
650
- minify: entryMinify ?? minify,
651
- sourcemap: entrySourcemap ?? sourcemap,
652
- entryOutputDirPath,
653
- appEntryPath,
654
- nativeModuleEntryMap,
655
- overrideViteOptions,
656
- ignoreDynamicRequires,
657
- external
658
- };
659
- const { privateKey, cert } = parseKeys({
660
- keyLength,
661
- privateKeyPath,
662
- certPath,
663
- subject,
664
- days
665
- });
666
- const buildVersionOption = {
667
- version: pkg.version,
668
- minimumVersion,
669
- privateKey,
670
- cert,
671
- versionPath,
672
- generateSignature,
673
- generateUpdateJson
674
- };
675
- return { buildAsarOption, buildEntryOption, buildVersionOption, postBuild, cert };
676
- }
677
-
678
- // src/vite/core.ts
679
- var debugStartup = async (args) => {
680
- if (process.env.VSCODE_DEBUG) {
681
- console.log("[startup] Electron App");
682
- } else {
683
- await args.startup();
684
- }
685
- };
686
- async function filterErrorMessageStartup(args, filter) {
687
- await args.startup(void 0, { stdio: ["inherit", "pipe", "pipe", "ipc"] });
688
- const elec = process.electronApp;
689
- elec.stdout.addListener("data", (data) => {
690
- console.log(data.toString().trimEnd());
691
- });
692
- elec.stderr.addListener("data", (data) => {
693
- const message = data.toString();
694
- if (filter(message)) {
695
- console.error(message);
696
- }
697
- });
698
- }
699
- function fixWinCharEncoding(fn) {
700
- return async (...args) => {
701
- if (process.platform === "win32") {
702
- (await import('child_process')).spawnSync("chcp", ["65001"]);
703
- }
704
- await fn(...args);
705
- };
706
- }
707
- function getMainFileBaseName(options) {
708
- let mainFilePath;
709
- if (typeof options === "string") {
710
- mainFilePath = path5.basename(options);
711
- } else if (Array.isArray(options)) {
712
- mainFilePath = path5.basename(options[0]);
713
- } else {
714
- const name = options?.index ?? options?.main;
715
- if (!name) {
716
- throw new Error(`\`options.main.files\` (${options}) must have "index" or "main" key, like \`{ index: "./electron/main/index.ts" }\``);
717
- }
718
- mainFilePath = options?.index ? "index.js" : "main.js";
719
- }
720
- log.info(`Using "${mainFilePath}" as main file`, { timestamp: true });
721
- return mainFilePath.replace(/\.[cm]?ts$/, ".js");
722
- }
723
- function parseVersionPath(versionPath) {
724
- versionPath = normalizePath(versionPath);
725
- if (!versionPath.startsWith("./")) {
726
- versionPath = `./${versionPath}`;
727
- }
728
- return new URL(versionPath, "file://").pathname.slice(1);
729
- }
730
- async function electronWithUpdater(options) {
731
- let {
732
- isBuild,
733
- pkg = await loadPackageJSON(),
734
- main: _main,
735
- preload: _preload,
736
- sourcemap = !isBuild,
737
- minify = isBuild,
738
- buildVersionJson,
739
- updater,
740
- bytecode,
741
- useNotBundle = true
742
- } = options;
743
- if (!pkg || !pkg.version || !pkg.name || !pkg.main) {
744
- log.error("package.json not found or invalid", { timestamp: true });
745
- return void 0;
746
- }
747
- const isESM = pkg.type === "module";
748
- let bytecodeOptions = typeof bytecode === "object" ? bytecode : bytecode === true ? { enable: true } : void 0;
749
- if (isESM && bytecodeOptions?.enable) {
750
- bytecodeLog.warn(
751
- '`bytecodePlugin` does not support ES module, please remove "type": "module" in package.json',
752
- { timestamp: true }
753
- );
754
- bytecodeOptions = void 0;
755
- }
756
- const {
757
- buildAsarOption,
758
- buildEntryOption,
759
- buildVersionOption,
760
- postBuild,
761
- cert
762
- } = parseOptions(isBuild, pkg, sourcemap, minify, updater);
763
- const { entryOutputDirPath, nativeModuleEntryMap, appEntryPath, external } = buildEntryOption;
764
- try {
765
- fs5.rmSync(buildAsarOption.electronDistPath, { recursive: true, force: true });
766
- fs5.rmSync(entryOutputDirPath, { recursive: true, force: true });
767
- } catch {
768
- }
769
- log.info(`Clear cache files`, { timestamp: true });
770
- sourcemap ??= isBuild || !!process.env.VSCODE_DEBUG;
771
- const _appPath = normalizePath(path5.join(entryOutputDirPath, "entry.js"));
772
- if (path5.resolve(normalizePath(pkg.main)) !== path5.resolve(_appPath)) {
773
- throw new Error(`Wrong "main" field in package.json: "${pkg.main}", it should be "${_appPath}"`);
774
- }
775
- const define = {
776
- __EIU_ASAR_BASE_NAME__: JSON.stringify(path5.basename(buildAsarOption.asarOutputPath)),
777
- __EIU_ELECTRON_DIST_PATH__: JSON.stringify(normalizePath(buildAsarOption.electronDistPath)),
778
- __EIU_ENTRY_DIST_PATH__: JSON.stringify(normalizePath(buildEntryOption.entryOutputDirPath)),
779
- __EIU_IS_DEV__: JSON.stringify(!isBuild),
780
- __EIU_IS_ESM__: JSON.stringify(isESM),
781
- __EIU_MAIN_FILE__: JSON.stringify(getMainFileBaseName(_main.files)),
782
- __EIU_SIGNATURE_CERT__: JSON.stringify(cert),
783
- __EIU_VERSION_PATH__: JSON.stringify(parseVersionPath(normalizePath(buildVersionOption.versionPath)))
784
- };
785
- async function _buildEntry() {
786
- await buildEntry(
787
- buildEntryOption,
788
- isESM,
789
- define,
790
- bytecodeOptions
791
- );
792
- log.info(`Build entry to '${entryOutputDirPath}'`, { timestamp: true });
793
- await postBuild?.({
794
- getPathFromEntryOutputDir(...paths) {
795
- return path5.join(entryOutputDirPath, ...paths);
796
- },
797
- copyToEntryOutputDir({ from, to = path5.basename(from), skipIfExist = true }) {
798
- if (!fs5.existsSync(from)) {
799
- log.warn(`${from} not found`, { timestamp: true });
800
- return;
801
- }
802
- const target = path5.join(entryOutputDirPath, to);
803
- copyAndSkipIfExist(from, target, skipIfExist);
804
- },
805
- copyModules({ modules, skipIfExist = true }) {
806
- const nodeModulesPath = path5.join(entryOutputDirPath, "node_modules");
807
- for (const m of modules) {
808
- const { rootPath } = getPackageInfoSync(m) || {};
809
- if (!rootPath) {
810
- log.warn(`Package '${m}' not found`, { timestamp: true });
811
- continue;
812
- }
813
- copyAndSkipIfExist(rootPath, path5.join(nodeModulesPath, m), skipIfExist);
814
- }
815
- }
816
- });
817
- }
818
- let isInit = false;
819
- const rollupOptions = {
820
- external,
821
- treeshake: true
822
- };
823
- const electronPluginOptions = {
824
- main: {
825
- entry: _main.files,
826
- onstart: async (args) => {
827
- if (!isInit) {
828
- isInit = true;
829
- await _buildEntry();
830
- }
831
- if (_main.onstart) {
832
- await _main.onstart(args);
833
- } else {
834
- await args.startup();
835
- }
836
- },
837
- vite: mergeConfig(
838
- {
839
- plugins: [
840
- !isBuild && useNotBundle && notBundle(),
841
- bytecodeOptions && bytecodePlugin("main", bytecodeOptions),
842
- isESM && esm()
843
- ],
844
- build: {
845
- sourcemap,
846
- minify,
847
- outDir: `${buildAsarOption.electronDistPath}/main`,
848
- rollupOptions
849
- },
850
- define
851
- },
852
- _main.vite ?? {}
853
- )
854
- },
855
- preload: {
856
- input: _preload.files,
857
- vite: mergeConfig(
858
- {
859
- plugins: [
860
- bytecodeOptions && bytecodePlugin("preload", bytecodeOptions),
861
- isESM && esm(),
862
- {
863
- name: `${id}-build`,
864
- enforce: "post",
865
- apply() {
866
- return isBuild;
867
- },
868
- async closeBundle() {
869
- await _buildEntry();
870
- const buffer = await buildAsar(buildAsarOption);
871
- if (!buildVersionJson && !isCI) {
872
- log.warn("No `buildVersionJson` option setup, skip build version json. Only build in CI by default", { timestamp: true });
873
- } else {
874
- await buildUpdateJson(buildVersionOption, buffer);
875
- }
876
- }
877
- }
878
- ],
879
- build: {
880
- sourcemap: sourcemap ? "inline" : void 0,
881
- minify,
882
- outDir: `${buildAsarOption.electronDistPath}/preload`,
883
- rollupOptions
884
- },
885
- define
886
- },
887
- _preload.vite ?? {}
888
- )
889
- }
890
- };
891
- const result = [ElectronSimple(electronPluginOptions)];
892
- if (nativeModuleEntryMap) {
893
- const files = [
894
- ...Object.values(nativeModuleEntryMap),
895
- appEntryPath
896
- ].map((file) => path5.resolve(normalizePath(file)));
897
- result.push({
898
- name: `${id}-dev`,
899
- apply() {
900
- return !isBuild;
901
- },
902
- configureServer(server) {
903
- server.watcher.add(files).on(
904
- "change",
905
- async (p) => {
906
- if (!files.includes(p)) {
907
- return;
908
- }
909
- await _buildEntry();
910
- if (_main.onstart) {
911
- await _main.onstart({
912
- startup,
913
- reload: () => {
914
- if (process.electronApp) {
915
- (server.hot || server.ws).send({ type: "full-reload" });
916
- startup.send("electron-vite&type=hot-reload");
917
- } else {
918
- startup();
919
- }
920
- }
921
- });
922
- } else {
923
- await startup();
924
- }
925
- }
926
- );
927
- }
928
- });
929
- }
930
- return result;
931
- }
932
-
933
- // src/vite/define.ts
934
- function defineElectronConfig(options) {
935
- return ({ command }) => {
936
- options.isBuild ??= command === "build";
937
- const electronPlugin = electronWithUpdater(options);
938
- const result = options.renderer ?? {};
939
- result.plugins ??= [];
940
- result.plugins.push(electronPlugin);
941
- return result;
942
- };
943
- }
944
-
945
- export { convertLiteral, debugStartup, electronWithUpdater as default, defineElectronConfig, electronWithUpdater, filterErrorMessageStartup, fixWinCharEncoding };