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

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-BFoZUBhU.cjs +320 -0
  5. package/dist/electron-CJIoO4ny.mjs +180 -0
  6. package/dist/index.cjs +259 -331
  7. package/dist/index.d.cts +179 -169
  8. package/dist/index.d.mts +204 -0
  9. package/dist/index.mjs +271 -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 +117 -85
  18. package/dist/utils.d.mts +161 -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 +565 -0
  23. package/dist/vite.mjs +1222 -0
  24. package/dist/zip-BCC7FAQ_.cjs +264 -0
  25. package/dist/zip-Dwm7s1C9.mjs +185 -0
  26. package/package.json +65 -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.mjs ADDED
@@ -0,0 +1,1222 @@
1
+ import { builtinModules, createRequire } from "node:module";
2
+ import * as babel from "@babel/core";
3
+ import { getPackageInfoSync, loadPackageJSON, loadPackageJSONSync } from "local-pkg";
4
+ import MagicString from "magic-string";
5
+ import cp from "node:child_process";
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { build, createFilter, createLogger, mergeConfig, normalizePath, version } from "vite";
9
+ import { isCI } from "ci-info";
10
+ import { createPackage } from "@electron/asar";
11
+ import crypto from "node:crypto";
12
+ import zlib from "node:zlib";
13
+ import { generate } from "selfsigned";
14
+
15
+ //#region src/utils/version.ts
16
+ /**
17
+ * Parse version string to {@link Version}, like `0.2.0-beta.1`
18
+ * @param version version string
19
+ */
20
+ function parseVersion(version) {
21
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
22
+ if (!match) throw new TypeError(`invalid version: ${version}`);
23
+ const [major, minor, patch] = match.slice(1, 4).map(Number);
24
+ const ret = {
25
+ major,
26
+ minor,
27
+ patch,
28
+ stage: "",
29
+ stageVersion: -1
30
+ };
31
+ if (match[4]) {
32
+ let [stage, _v] = match[4].split(".");
33
+ ret.stage = stage;
34
+ ret.stageVersion = Number(_v) || -1;
35
+ }
36
+ if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) throw new TypeError(`Invalid version: ${version}`);
37
+ return ret;
38
+ }
39
+ const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
40
+ /**
41
+ * Check is `UpdateJSON`
42
+ * @param json any variable
43
+ */
44
+ function isUpdateJSON(json) {
45
+ return is(json) && is(json?.beta);
46
+ }
47
+ /**
48
+ * Default function to generate `UpdateJSON`
49
+ * @param existingJson exising update json
50
+ * @param signature sigature
51
+ * @param version target version
52
+ * @param minimumVersion minimum version
53
+ */
54
+ function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
55
+ existingJson.beta = {
56
+ version,
57
+ minimumVersion,
58
+ signature
59
+ };
60
+ if (!parseVersion(version).stage) {
61
+ existingJson.version = version;
62
+ existingJson.minimumVersion = minimumVersion;
63
+ existingJson.signature = signature;
64
+ }
65
+ return existingJson;
66
+ }
67
+
68
+ //#endregion
69
+ //#region src/vite/constant.ts
70
+ const id = "electron-incremental-updater";
71
+ const bytecodeId = `${id}-bytecode`;
72
+ const esmId = `${id}-esm`;
73
+ const log = createLogger("info", { prefix: `[${id}]` });
74
+ const bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
75
+
76
+ //#endregion
77
+ //#region src/vite/bytecode/code.ts
78
+ const 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";
79
+ const 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";
80
+
81
+ //#endregion
82
+ //#region src/vite/bytecode/utils.ts
83
+ const electronModule = getPackageInfoSync("electron");
84
+ const electronMajorVersion = parseVersion(electronModule.version).major;
85
+ const useStrict = "'use strict';";
86
+ const bytecodeModuleLoader = "__loader__.js";
87
+ function getElectronPath() {
88
+ const electronModulePath = electronModule.rootPath;
89
+ let electronExecPath = process.env.ELECTRON_EXEC_PATH || "";
90
+ if (!electronExecPath) {
91
+ if (!electronModulePath) throw new Error("Electron is not installed");
92
+ const pathFile = path.join(electronModulePath, "path.txt");
93
+ let executablePath;
94
+ if (fs.existsSync(pathFile)) executablePath = fs.readFileSync(pathFile, "utf-8");
95
+ if (executablePath) {
96
+ electronExecPath = path.join(electronModulePath, "dist", executablePath);
97
+ process.env.ELECTRON_EXEC_PATH = electronExecPath;
98
+ } else throw new Error("Electron executable file is not existed");
99
+ }
100
+ return electronExecPath;
101
+ }
102
+ function getBytecodeCompilerPath() {
103
+ const scriptPath = path.join(electronModule.rootPath, "EIU_bytenode.cjs");
104
+ if (!fs.existsSync(scriptPath)) fs.writeFileSync(scriptPath, bytecodeGeneratorScript);
105
+ return scriptPath;
106
+ }
107
+ function toRelativePath(filename, importer) {
108
+ const relPath = path.posix.relative(path.dirname(importer), filename);
109
+ return relPath.startsWith(".") ? relPath : `./${relPath}`;
110
+ }
111
+ const logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
112
+ function compileToBytecode(code, electronPath = getElectronPath()) {
113
+ let data = Buffer.from([]);
114
+ const bytecodePath = getBytecodeCompilerPath();
115
+ return new Promise((resolve, reject) => {
116
+ const proc = cp.spawn(electronPath, [bytecodePath], {
117
+ env: { ELECTRON_RUN_AS_NODE: "1" },
118
+ stdio: [
119
+ "pipe",
120
+ "pipe",
121
+ "pipe",
122
+ "ipc"
123
+ ]
124
+ });
125
+ if (proc.stdin) {
126
+ proc.stdin.write(code);
127
+ proc.stdin.end();
128
+ }
129
+ if (proc.stdout) {
130
+ proc.stdout.on("data", (chunk) => data = Buffer.concat([data, chunk]));
131
+ proc.stdout.on("error", (err) => logErr(err));
132
+ proc.stdout.on("end", () => resolve(data));
133
+ }
134
+ if (proc.stderr) {
135
+ proc.stderr.on("data", (chunk) => logErr("Error: ", chunk.toString()));
136
+ proc.stderr.on("error", (err) => logErr("Error: ", err));
137
+ }
138
+ proc.addListener("error", (err) => logErr(err));
139
+ proc.on("error", (err) => reject(err));
140
+ proc.on("exit", () => resolve(data));
141
+ });
142
+ }
143
+ function convertArrowFunctionAndTemplate(code) {
144
+ const result = babel.transform(code, { plugins: ["@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals"] });
145
+ return {
146
+ code: result?.code || code,
147
+ map: result?.map
148
+ };
149
+ }
150
+ const decodeFn = ";function _0xstr_(a,b){return String.fromCharCode.apply(0,a.map(function(x){return x-b}))};";
151
+ function obfuscateString(input, offset = ~~(Math.random() * 16) + 1) {
152
+ return `_0xstr_([${input.split("").map((c) => `0x${(c.charCodeAt(0) + offset).toString(16)}`).join(",")}],${offset})`;
153
+ }
154
+ /**
155
+ * Obfuscate string
156
+ * @param code source code
157
+ * @param sourcemap whether to generate sourcemap
158
+ * @param offset custom offset
159
+ */
160
+ function convertLiteral(code, sourcemap, offset) {
161
+ const s = new MagicString(code);
162
+ let hasTransformed = false;
163
+ const ast = babel.parse(code, { ast: true });
164
+ if (!ast) throw new Error("Cannot parse code");
165
+ babel.traverse(ast, { StringLiteral(path) {
166
+ const parent = path.parent;
167
+ const node = path.node;
168
+ if (parent.type === "CallExpression") {
169
+ if (parent.callee.type === "Identifier" && parent.callee.name === "require") return;
170
+ if (parent.callee.type === "Import") return;
171
+ }
172
+ if (parent.type.startsWith("Export")) return;
173
+ if (parent.type.startsWith("Import")) return;
174
+ if (parent.type === "ObjectMethod" && parent.key === node) return;
175
+ if (parent.type === "ObjectProperty" && parent.key === node) {
176
+ const result = `[${obfuscateString(node.value, offset)}]`;
177
+ const start = node.start;
178
+ const end = node.end;
179
+ if (start && end) {
180
+ s.overwrite(start, end, result);
181
+ hasTransformed = true;
182
+ }
183
+ return;
184
+ }
185
+ if (!node.value.trim()) return;
186
+ const result = obfuscateString(node.value, offset);
187
+ const start = node.start;
188
+ const end = node.end;
189
+ if (start && end) {
190
+ s.overwrite(start, end, result);
191
+ hasTransformed = true;
192
+ }
193
+ } });
194
+ if (hasTransformed) s.append("\n").append(decodeFn);
195
+ return {
196
+ code: s.toString(),
197
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
198
+ };
199
+ }
200
+
201
+ //#endregion
202
+ //#region src/vite/utils.ts
203
+ function readableSize(size) {
204
+ const units = [
205
+ "B",
206
+ "KB",
207
+ "MB",
208
+ "GB"
209
+ ];
210
+ let i = 0;
211
+ while (size >= 1024 && i < units.length - 1) {
212
+ size /= 1024;
213
+ i++;
214
+ }
215
+ return `${size.toFixed(2)} ${units[i]}`;
216
+ }
217
+ function copyAndSkipIfExist(from, to, skipIfExist) {
218
+ if (!skipIfExist || !fs.existsSync(to)) try {
219
+ fs.cpSync(from, to, { recursive: true });
220
+ } catch (error) {
221
+ log.warn(`Copy failed: ${error}`, { timestamp: true });
222
+ }
223
+ }
224
+ function resolveInputToArray(files) {
225
+ if (typeof files === "string") return [files];
226
+ if (Array.isArray(files)) return files;
227
+ return Object.values(files);
228
+ }
229
+
230
+ //#endregion
231
+ //#region src/vite/bytecode/index.ts
232
+ function getBytecodeLoaderBlock(chunkFileName) {
233
+ return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
234
+ }
235
+ /**
236
+ * Compile to v8 bytecode to protect source code.
237
+ */
238
+ function bytecodePlugin(env, options) {
239
+ const { enable, preload = false, electronPath, beforeCompile } = options;
240
+ if (!enable) return null;
241
+ if (!preload && env === "preload") {
242
+ 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 });
243
+ return null;
244
+ }
245
+ const filter = createFilter(/\.(m?[jt]s|[jt]sx)$/);
246
+ let config;
247
+ let bytecodeRequired = false;
248
+ let bytecodeFiles = [];
249
+ return {
250
+ name: `${bytecodeId}-${env}`,
251
+ apply: "build",
252
+ enforce: "post",
253
+ configResolved(resolvedConfig) {
254
+ config = resolvedConfig;
255
+ },
256
+ transform(code, id) {
257
+ if (!filter(id)) return convertLiteral(code, !!config.build.sourcemap);
258
+ },
259
+ generateBundle(options) {
260
+ if (options.format !== "es" && bytecodeRequired) this.emitFile({
261
+ type: "asset",
262
+ source: `${bytecodeModuleLoaderCode}\n`,
263
+ name: "Bytecode Loader File",
264
+ fileName: bytecodeModuleLoader
265
+ });
266
+ },
267
+ renderChunk(code, chunk, options) {
268
+ if (options.format === "es") {
269
+ bytecodeLog.warn("`bytecodePlugin` does not support ES module, please set \"build.rollupOptions.output.format\" option to \"cjs\"", { timestamp: true });
270
+ return null;
271
+ }
272
+ if (chunk.type === "chunk") {
273
+ bytecodeRequired = true;
274
+ return convertArrowFunctionAndTemplate(code);
275
+ }
276
+ return null;
277
+ },
278
+ async writeBundle(options, output) {
279
+ if (options.format === "es" || !bytecodeRequired) return;
280
+ const outDir = options.dir;
281
+ bytecodeFiles = [];
282
+ const bundles = Object.keys(output);
283
+ const chunks = Object.values(output).filter((chunk) => chunk.type === "chunk" && chunk.fileName !== bytecodeModuleLoader);
284
+ const bytecodeChunks = new Set(chunks.map((chunk) => chunk.fileName));
285
+ const pattern = chunks.filter((chunk) => !chunk.isEntry).map((chunk) => path.basename(chunk.fileName)).map((chunk) => `(${chunk})`).join("|");
286
+ const bytecodeRE = pattern ? new RegExp(`require\\(\\S*(?=(${pattern})\\S*\\))`, "g") : null;
287
+ await Promise.all(bundles.map(async (name) => {
288
+ const chunk = output[name];
289
+ if (chunk.type === "chunk") {
290
+ let _code = chunk.code;
291
+ const chunkFilePath = path.resolve(outDir, name);
292
+ if (beforeCompile) {
293
+ const cbResult = await beforeCompile(_code, chunkFilePath);
294
+ if (cbResult) _code = cbResult;
295
+ }
296
+ if (bytecodeRE && _code.match(bytecodeRE)) {
297
+ let match;
298
+ const s = new MagicString(_code);
299
+ while (match = bytecodeRE.exec(_code)) {
300
+ const [prefix, chunkName] = match;
301
+ const len = prefix.length + chunkName.length;
302
+ s.overwrite(match.index, match.index + len, `${prefix + chunkName}c`, { contentOnly: true });
303
+ }
304
+ _code = s.toString();
305
+ }
306
+ if (bytecodeChunks.has(name)) {
307
+ const bytecodeBuffer = await compileToBytecode(_code, electronPath);
308
+ fs.writeFileSync(`${chunkFilePath}c`, bytecodeBuffer);
309
+ if (chunk.isEntry) {
310
+ const code = `${useStrict}\n${getBytecodeLoaderBlock(chunk.fileName)}\nmodule.exports=${`require("./${`${path.basename(name)}c`}");`}\n`;
311
+ fs.writeFileSync(chunkFilePath, code);
312
+ } else fs.unlinkSync(chunkFilePath);
313
+ bytecodeFiles.push({
314
+ name: `${name}c`,
315
+ size: bytecodeBuffer.length
316
+ });
317
+ } else {
318
+ if (chunk.isEntry) {
319
+ let hasBytecodeMoudle = false;
320
+ const idsToHandle = new Set([...chunk.imports, ...chunk.dynamicImports]);
321
+ for (const moduleId of idsToHandle) {
322
+ if (bytecodeChunks.has(moduleId)) {
323
+ hasBytecodeMoudle = true;
324
+ break;
325
+ }
326
+ const moduleInfo = this.getModuleInfo(moduleId);
327
+ if (moduleInfo) {
328
+ const { importers, dynamicImporters } = moduleInfo;
329
+ for (const importerId of importers) idsToHandle.add(importerId);
330
+ for (const importerId of dynamicImporters) idsToHandle.add(importerId);
331
+ }
332
+ }
333
+ const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
334
+ _code = hasBytecodeMoudle ? _code.replace(new RegExp(`(${useStrict})|("use strict";)`), `${useStrict}\n${bytecodeLoaderBlock}`) : _code;
335
+ }
336
+ fs.writeFileSync(chunkFilePath, _code);
337
+ }
338
+ }
339
+ }));
340
+ },
341
+ closeBundle() {
342
+ const outDir = `${normalizePath(path.relative(config.root, path.resolve(config.root, config.build.outDir)))}/`;
343
+ bytecodeFiles.forEach((file) => {
344
+ bytecodeLog.info(`${outDir}${file.name} [${readableSize(file.size)}]`, { timestamp: true });
345
+ });
346
+ bytecodeLog.info(`${bytecodeFiles.length} bundles compiled into bytecode.`, { timestamp: true });
347
+ bytecodeFiles = [];
348
+ }
349
+ };
350
+ }
351
+
352
+ //#endregion
353
+ //#region src/vite/electron/utils.ts
354
+ /** Resolve the default Vite's `InlineConfig` for build Electron-Main */
355
+ function resolveViteConfig(options) {
356
+ const esmodule = (loadPackageJSONSync() ?? {}).type === "module";
357
+ return mergeConfig({
358
+ configFile: false,
359
+ publicDir: false,
360
+ build: {
361
+ lib: options.entry && {
362
+ entry: options.entry,
363
+ formats: esmodule ? ["es"] : ["cjs"],
364
+ fileName: () => "[name].js"
365
+ },
366
+ outDir: "dist-electron",
367
+ emptyOutDir: false
368
+ },
369
+ resolve: {
370
+ conditions: ["node"],
371
+ mainFields: [
372
+ "module",
373
+ "jsnext:main",
374
+ "jsnext"
375
+ ]
376
+ },
377
+ define: { "process.env": "process.env" }
378
+ }, options?.vite || {});
379
+ }
380
+ function withExternalBuiltins(config) {
381
+ const builtins = builtinModules.filter((e) => !e.startsWith("_"));
382
+ builtins.push("electron", ...builtins.map((m) => `node:${m}`));
383
+ config.build ??= {};
384
+ config.build.rolldownOptions ??= {};
385
+ let external = config.build.rolldownOptions.external;
386
+ if (Array.isArray(external) || typeof external === "string" || external instanceof RegExp) external = builtins.concat(external);
387
+ else if (typeof external === "function") {
388
+ const original = external;
389
+ external = function(source, importer, isResolved) {
390
+ if (builtins.includes(source)) return true;
391
+ return original(source, importer, isResolved);
392
+ };
393
+ } else external = builtins;
394
+ config.build.rolldownOptions.external = external;
395
+ return config;
396
+ }
397
+ /**
398
+ * @see https://github.com/vitejs/vite/blob/v4.0.1/packages/vite/src/node/constants.ts#L137-L147
399
+ */
400
+ function resolveHostname(hostname) {
401
+ const loopbackHosts = new Set([
402
+ "localhost",
403
+ "127.0.0.1",
404
+ "::1",
405
+ "0000:0000:0000:0000:0000:0000:0000:0001"
406
+ ]);
407
+ const wildcardHosts = new Set([
408
+ "0.0.0.0",
409
+ "::",
410
+ "0000:0000:0000:0000:0000:0000:0000:0000"
411
+ ]);
412
+ return loopbackHosts.has(hostname) || wildcardHosts.has(hostname) ? "localhost" : hostname;
413
+ }
414
+ function resolveServerUrl(server) {
415
+ const addressInfo = server.httpServer?.address();
416
+ const isAddressInfo = (x) => x?.address;
417
+ if (isAddressInfo(addressInfo)) {
418
+ const { address, port } = addressInfo;
419
+ const hostname = resolveHostname(address);
420
+ const options = server.config.server;
421
+ const protocol = options.https ? "https" : "http";
422
+ const devBase = server.config.base;
423
+ const path = typeof options.open === "string" ? options.open : devBase;
424
+ return path.startsWith("http") ? path : `${protocol}://${hostname}:${port}${path}`;
425
+ }
426
+ }
427
+ /** @see https://github.com/vitejs/vite/blob/v5.4.9/packages/vite/src/node/build.ts#L489-L504 */
428
+ function resolveInput(config) {
429
+ const options = config.build;
430
+ const { root } = config;
431
+ const libOptions = options.lib;
432
+ const resolve = (p) => path.resolve(root, p);
433
+ const input = libOptions ? options.rolldownOptions?.input || (typeof libOptions.entry === "string" ? resolve(libOptions.entry) : Array.isArray(libOptions.entry) ? libOptions.entry.map(resolve) : Object.fromEntries(Object.entries(libOptions.entry).map(([alias, file]) => [alias, resolve(file)]))) : options.rolldownOptions?.input;
434
+ if (input) return input;
435
+ const indexHtml = resolve("index.html");
436
+ return fs.existsSync(indexHtml) ? indexHtml : void 0;
437
+ }
438
+ /**
439
+ * When run the `vite build` command, there must be an entry file.
440
+ * If the user does not need Renderer, we need to create a temporary entry file to avoid Vite throw error.
441
+ * @see https://github.com/vitejs/vite/blob/v5.4.9/packages/vite/src/node/config.ts#L1234-L1236
442
+ */
443
+ async function mockIndexHtml(config) {
444
+ const { root, build } = config;
445
+ const output = path.resolve(root, build.outDir);
446
+ const content = `
447
+ <!doctype html>
448
+ <html lang="en">
449
+ <head>
450
+ <title>vite-plugin-electron</title>
451
+ </head>
452
+ <body>
453
+ <div>An entry file for electron renderer process.</div>
454
+ </body>
455
+ </html>
456
+ `.trim();
457
+ const index = "index.html";
458
+ const filepath = path.join(root, index);
459
+ const distpath = path.join(output, index);
460
+ await fs.promises.writeFile(filepath, content);
461
+ return {
462
+ async remove() {
463
+ await fs.promises.unlink(filepath);
464
+ await fs.promises.unlink(distpath);
465
+ },
466
+ filepath,
467
+ distpath
468
+ };
469
+ }
470
+ /**
471
+ * Inspired `tree-kill`, implemented based on sync-api. #168
472
+ * @see https://github.com/pkrumins/node-tree-kill/blob/v1.2.2/index.js
473
+ */
474
+ function treeKillSync(pid) {
475
+ if (process.platform === "win32") cp.execSync(`taskkill /pid ${pid} /T /F`);
476
+ else killTree(pidTree({
477
+ pid,
478
+ ppid: process.pid
479
+ }));
480
+ }
481
+ function pidTree(tree) {
482
+ const command = process.platform === "darwin" ? `pgrep -P ${tree.pid}` : `ps -o pid --no-headers --ppid ${tree.ppid}`;
483
+ try {
484
+ const childs = cp.execSync(command, { encoding: "utf8" }).match(/\d+/g)?.map((id) => +id);
485
+ if (childs) tree.children = childs.map((cid) => pidTree({
486
+ pid: cid,
487
+ ppid: tree.pid
488
+ }));
489
+ } catch {}
490
+ return tree;
491
+ }
492
+ function killTree(tree) {
493
+ if (tree.children) for (const child of tree.children) killTree(child);
494
+ try {
495
+ process.kill(tree.pid);
496
+ } catch {}
497
+ }
498
+
499
+ //#endregion
500
+ //#region src/vite/electron/core.ts
501
+ function build$1(options) {
502
+ return build(withExternalBuiltins(resolveViteConfig(options)));
503
+ }
504
+ function electron(options) {
505
+ const optionsArray = Array.isArray(options) ? options : [options];
506
+ let userConfig;
507
+ let configEnv;
508
+ let mockdInput;
509
+ if (!version.startsWith("8.")) throw new Error(`[vite-plugin-electron] Vite v${version} does not support \`rolldownOptions\`, please install \`vite@>=8\` or use an earlier version of \`vite-plugin-electron\`.`);
510
+ return [{
511
+ name: "vite-plugin-electron:dev",
512
+ apply: "serve",
513
+ configureServer(server) {
514
+ server.httpServer?.once("listening", () => {
515
+ Object.assign(process.env, { VITE_DEV_SERVER_URL: resolveServerUrl(server) });
516
+ const entryCount = optionsArray.length;
517
+ let closeBundleCount = 0;
518
+ for (const options of optionsArray) {
519
+ options.vite ??= {};
520
+ options.vite.mode ??= server.config.mode;
521
+ options.vite.root ??= server.config.root;
522
+ options.vite.envDir ??= server.config.envDir;
523
+ options.vite.envPrefix ??= server.config.envPrefix;
524
+ options.vite.build ??= {};
525
+ if (!Object.keys(options.vite.build).includes("watch")) options.vite.build.watch = {};
526
+ options.vite.build.minify ??= false;
527
+ options.vite.plugins ??= [];
528
+ options.vite.plugins.push({
529
+ name: ":startup",
530
+ closeBundle() {
531
+ if (++closeBundleCount < entryCount) return;
532
+ if (options.onstart) options.onstart.call(this, {
533
+ startup,
534
+ reload() {
535
+ if (process.electronApp) {
536
+ (server.hot || server.ws).send({ type: "full-reload" });
537
+ startup.send("electron-vite&type=hot-reload");
538
+ } else startup();
539
+ }
540
+ });
541
+ else startup();
542
+ }
543
+ });
544
+ build$1(options);
545
+ }
546
+ });
547
+ }
548
+ }, {
549
+ name: "vite-plugin-electron:prod",
550
+ apply: "build",
551
+ config(config, env) {
552
+ userConfig = config;
553
+ configEnv = env;
554
+ config.base ??= "./";
555
+ },
556
+ async configResolved(config) {
557
+ if (resolveInput(config) == null) mockdInput = await mockIndexHtml(config);
558
+ },
559
+ async closeBundle() {
560
+ mockdInput?.remove();
561
+ for (const options of optionsArray) {
562
+ options.vite ??= {};
563
+ options.vite.mode ??= configEnv.mode;
564
+ options.vite.root ??= userConfig.root;
565
+ options.vite.envDir ??= userConfig.envDir;
566
+ options.vite.envPrefix ??= userConfig.envPrefix;
567
+ await build$1(options);
568
+ }
569
+ }
570
+ }];
571
+ }
572
+ /**
573
+ * Electron App startup function.
574
+ * It will mount the Electron App child-process to `process.electronApp`.
575
+ * @param argv default value `['.', '--no-sandbox']`
576
+ * @param options options for `child_process.spawn`
577
+ * @param customElectronPkg custom electron package name (default: 'electron')
578
+ */
579
+ const startup = async (argv = [".", "--no-sandbox"], options, customElectronPkg) => {
580
+ const { spawn } = await import("node:child_process");
581
+ const electron = await import(customElectronPkg ?? "electron");
582
+ const electronPath = electron.default ?? electron;
583
+ await startup.exit();
584
+ const stdio = process.platform === "linux" ? [
585
+ "inherit",
586
+ "inherit",
587
+ "inherit",
588
+ "ignore",
589
+ "ipc"
590
+ ] : [
591
+ "inherit",
592
+ "inherit",
593
+ "inherit",
594
+ "ipc"
595
+ ];
596
+ process.electronApp = spawn(electronPath, argv, {
597
+ stdio,
598
+ ...options
599
+ });
600
+ process.electronApp.once("exit", process.exit);
601
+ if (!startup.hookedProcessExit) {
602
+ startup.hookedProcessExit = true;
603
+ process.once("exit", startup.exit);
604
+ }
605
+ };
606
+ startup.send = (message) => {
607
+ if (process.electronApp) process.electronApp.send?.(message);
608
+ };
609
+ startup.hookedProcessExit = false;
610
+ startup.exit = async () => {
611
+ if (process.electronApp) await new Promise((resolve) => {
612
+ process.electronApp.removeAllListeners();
613
+ process.electronApp.once("exit", resolve);
614
+ treeKillSync(process.electronApp.pid);
615
+ });
616
+ };
617
+
618
+ //#endregion
619
+ //#region src/vite/build.ts
620
+ async function buildAsar({ version, asarOutputPath, gzipPath, electronDistPath, rendererDistPath, generateGzipFile }) {
621
+ fs.renameSync(rendererDistPath, path.join(electronDistPath, "renderer"));
622
+ fs.writeFileSync(path.join(electronDistPath, "version"), version);
623
+ await createPackage(electronDistPath, asarOutputPath);
624
+ const buf = await generateGzipFile(fs.readFileSync(asarOutputPath));
625
+ fs.writeFileSync(gzipPath, buf);
626
+ log.info(`Build update asar to '${gzipPath}' [${readableSize(buf.length)}]`, { timestamp: true });
627
+ return buf;
628
+ }
629
+ async function buildUpdateJson({ versionPath, privateKey, cert, version, minimumVersion, generateSignature, generateUpdateJson }, asarBuffer) {
630
+ let _json = {
631
+ beta: {
632
+ minimumVersion: version,
633
+ signature: "",
634
+ version
635
+ },
636
+ minimumVersion: version,
637
+ signature: "",
638
+ version
639
+ };
640
+ if (fs.existsSync(versionPath)) try {
641
+ const oldVersionJson = JSON.parse(fs.readFileSync(versionPath, "utf-8"));
642
+ if (isUpdateJSON(oldVersionJson)) _json = oldVersionJson;
643
+ else log.warn("Old version json is invalid, ignore it", { timestamp: true });
644
+ } catch {}
645
+ const sig = await generateSignature(asarBuffer, privateKey, cert, version);
646
+ _json = await generateUpdateJson(_json, sig, version, minimumVersion);
647
+ if (!isUpdateJSON(_json)) throw new Error("Invalid update json");
648
+ fs.writeFileSync(versionPath, JSON.stringify(_json, null, 2));
649
+ log.info(`build update json to '${versionPath}'`, { timestamp: true });
650
+ }
651
+ async function buildEntry({ sourcemap, minify, files, outDir, ignoreDynamicRequires, external, vite }, isESM, define, bytecodeOptions) {
652
+ await build$1({
653
+ entry: files,
654
+ vite: mergeConfig({
655
+ plugins: [bytecodeOptions && bytecodePlugin("main", bytecodeOptions)],
656
+ build: {
657
+ sourcemap,
658
+ minify,
659
+ outDir,
660
+ emptyOutDir: true,
661
+ rolldownOptions: {
662
+ external,
663
+ platform: "node",
664
+ output: {
665
+ polyfillRequire: false,
666
+ format: isESM ? "esm" : "cjs",
667
+ dynamicImportInCjs: !ignoreDynamicRequires
668
+ }
669
+ }
670
+ },
671
+ define
672
+ }, vite ?? {})
673
+ });
674
+ }
675
+
676
+ //#endregion
677
+ //#region src/vite/electron/plugin.ts
678
+ /**
679
+ * @see https://github.com/vitejs/vite/blob/v4.4.7/packages/vite/src/node/utils.ts#L140
680
+ */
681
+ const bareImportRE = /^(?![a-zA-Z]:)[\w@](?!.*:\/\/)/;
682
+ const nodeModulesRE = /\/node_modules\//;
683
+ /**
684
+ * During dev, we exclude the `cjs` npm-pkg from bundle, mush like Vite :)
685
+ */
686
+ function notBundle(options = {}) {
687
+ const externalIds = /* @__PURE__ */ new Set();
688
+ return {
689
+ name: "vite-plugin-electron:not-bundle",
690
+ enforce: "pre",
691
+ apply: "serve",
692
+ resolveId: {
693
+ filter: { id: bareImportRE },
694
+ async handler(source, importer) {
695
+ if (!importer || importer.includes("node_modules/")) return;
696
+ if (externalIds.has(source)) return {
697
+ id: source,
698
+ external: true
699
+ };
700
+ const id = (await this.resolve(source, importer, { skipSelf: true }))?.id;
701
+ if (!id || !nodeModulesRE.test(id) || options.filter?.(id) === false) return;
702
+ try {
703
+ createRequire(importer).resolve(source);
704
+ } catch {
705
+ return;
706
+ }
707
+ externalIds.add(source);
708
+ return {
709
+ id: source,
710
+ external: true,
711
+ moduleSideEffects: false
712
+ };
713
+ }
714
+ }
715
+ };
716
+ }
717
+
718
+ //#endregion
719
+ //#region src/vite/electron/simple.ts
720
+ async function electronSimple(options) {
721
+ const flatApiOptions = [options.main];
722
+ const esmodule = (await loadPackageJSON() ?? {}).type === "module";
723
+ if (options.preload) {
724
+ const { input, vite: viteConfig = {}, ...preloadOptions } = options.preload;
725
+ const preload = {
726
+ onstart(args) {
727
+ args.reload();
728
+ },
729
+ ...preloadOptions,
730
+ vite: mergeConfig({ build: { rolldownOptions: {
731
+ input,
732
+ output: {
733
+ format: "cjs",
734
+ inlineDynamicImports: true,
735
+ entryFileNames: `[name].${esmodule ? "mjs" : "js"}`,
736
+ chunkFileNames: `[name].${esmodule ? "mjs" : "js"}`,
737
+ assetFileNames: "[name].[ext]"
738
+ }
739
+ } } }, viteConfig)
740
+ };
741
+ flatApiOptions.push(preload);
742
+ }
743
+ return electron(flatApiOptions);
744
+ }
745
+
746
+ //#endregion
747
+ //#region src/utils/crypto.ts
748
+ function hashBuffer(data, length) {
749
+ const hash = crypto.createHash("SHA256").update(data).digest("binary");
750
+ return Buffer.from(hash).subarray(0, length);
751
+ }
752
+ function aesEncrypt(plainText, key, iv) {
753
+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
754
+ return cipher.update(plainText, "utf8", "base64url") + cipher.final("base64url");
755
+ }
756
+ /**
757
+ * Default function to generate asar signature, returns generated signature
758
+ * @param buffer file buffer
759
+ * @param privateKey primary key
760
+ * @param cert certificate
761
+ * @param version target version
762
+ */
763
+ function defaultSignature(buffer, privateKey, cert, version) {
764
+ return aesEncrypt(`${crypto.createSign("RSA-SHA256").update(buffer).sign(crypto.createPrivateKey(privateKey), "base64")}%${version}`, hashBuffer(cert, 32), hashBuffer(buffer, 16));
765
+ }
766
+
767
+ //#endregion
768
+ //#region src/utils/zip.ts
769
+ /**
770
+ * Default function to compress file using brotli
771
+ * @param buffer uncompressed file buffer
772
+ */
773
+ async function defaultZipFile(buffer) {
774
+ return new Promise((resolve, reject) => {
775
+ zlib.brotliCompress(buffer, (err, buffer) => err ? reject(err) : resolve(buffer));
776
+ });
777
+ }
778
+
779
+ //#endregion
780
+ //#region src/vite/key.ts
781
+ async function generateKeyPair(keyLength, subject, days, privateKeyPath, certPath) {
782
+ const privateKeyDir = path.dirname(privateKeyPath);
783
+ if (!fs.existsSync(privateKeyDir)) fs.mkdirSync(privateKeyDir, { recursive: true });
784
+ const certDir = path.dirname(certPath);
785
+ if (!fs.existsSync(certDir)) fs.mkdirSync(certDir, { recursive: true });
786
+ const startDate = /* @__PURE__ */ new Date();
787
+ const endDate = new Date(startDate);
788
+ endDate.setDate(startDate.getDate() + days);
789
+ const { cert, private: privateKey } = await generate(subject, {
790
+ keySize: keyLength,
791
+ algorithm: "sha256",
792
+ notBeforeDate: startDate,
793
+ notAfterDate: endDate
794
+ });
795
+ fs.writeFileSync(privateKeyPath, privateKey.replace(/\r\n?/g, "\n"));
796
+ fs.writeFileSync(certPath, cert.replace(/\r\n?/g, "\n"));
797
+ }
798
+ async function parseKeys({ keyLength, privateKeyPath, certPath, subject, days }) {
799
+ const keysDir = path.dirname(privateKeyPath);
800
+ let privateKey = process.env.UPDATER_PK;
801
+ let cert = process.env.UPDATER_CERT;
802
+ if (privateKey && cert) {
803
+ log.info("Use `UPDATER_PK` and `UPDATER_CERT` from environment variables", { timestamp: true });
804
+ return {
805
+ privateKey,
806
+ cert
807
+ };
808
+ }
809
+ if (!fs.existsSync(keysDir)) fs.mkdirSync(keysDir);
810
+ if (!fs.existsSync(privateKeyPath) || !fs.existsSync(certPath)) {
811
+ log.info("No key pair found, generate new key pair", { timestamp: true });
812
+ await generateKeyPair(keyLength, parseSubjects(subject), days, privateKeyPath, certPath);
813
+ }
814
+ privateKey = fs.readFileSync(privateKeyPath, "utf-8");
815
+ cert = fs.readFileSync(certPath, "utf-8");
816
+ return {
817
+ privateKey,
818
+ cert
819
+ };
820
+ }
821
+ function parseSubjects(subject) {
822
+ return Object.entries(subject).filter(([_, value]) => !!value).map(([name, value]) => ({
823
+ name,
824
+ value
825
+ }));
826
+ }
827
+
828
+ //#endregion
829
+ //#region src/vite/option.ts
830
+ async function parseOptions(isBuild, pkg, sourcemap = false, minify = false, entry = {}, options = {}) {
831
+ const { minify: entryMinify, sourcemap: entrySourcemap, outDir = "dist-entry", files = "electron/entry.ts", postBuild, ignoreDynamicRequires = false, external = [
832
+ /^node:.*/,
833
+ /.*\.(node|dll|dylib|so)$/,
834
+ "original-fs",
835
+ "electron",
836
+ ...isBuild || postBuild ? [] : Object.keys("dependencies" in pkg ? pkg.dependencies : {})
837
+ ], vite = {} } = entry;
838
+ const { minimumVersion = "0.0.0", paths: { asarOutputPath = `release/${pkg.name}.asar`, gzipPath = `release/${pkg.name}-${pkg.version}.asar.gz`, electronDistPath = "dist-electron", rendererDistPath = "dist", versionPath = "version.json" } = {}, keys: { privateKeyPath = "keys/private.pem", certPath = "keys/cert.pem", keyLength = 2048, certInfo: { subject = {
839
+ commonName: pkg.name,
840
+ organizationName: `org.${pkg.name}`
841
+ }, days = 3650 } = {} } = {}, overrideGenerator: { generateGzipFile = defaultZipFile, generateSignature = defaultSignature, generateUpdateJson = defaultVersionJsonGenerator } = {} } = options;
842
+ const buildAsarOption = {
843
+ version: pkg.version,
844
+ asarOutputPath,
845
+ gzipPath,
846
+ electronDistPath,
847
+ rendererDistPath,
848
+ generateGzipFile
849
+ };
850
+ const buildEntryOption = {
851
+ minify: entryMinify ?? minify,
852
+ sourcemap: entrySourcemap ?? sourcemap,
853
+ outDir,
854
+ files,
855
+ vite,
856
+ ignoreDynamicRequires,
857
+ external
858
+ };
859
+ const { privateKey, cert } = await parseKeys({
860
+ keyLength,
861
+ privateKeyPath,
862
+ certPath,
863
+ subject,
864
+ days
865
+ });
866
+ return {
867
+ buildAsarOption,
868
+ buildEntryOption,
869
+ buildVersionOption: {
870
+ version: pkg.version,
871
+ minimumVersion,
872
+ privateKey,
873
+ cert,
874
+ versionPath,
875
+ generateSignature,
876
+ generateUpdateJson
877
+ },
878
+ postBuild,
879
+ cert
880
+ };
881
+ }
882
+
883
+ //#endregion
884
+ //#region src/vite/core.ts
885
+ /**
886
+ * Startup function for debug
887
+ * @see {@link https://github.com/electron-vite/electron-vite-vue/blob/main/vite.config.ts electron-vite-vue template}
888
+ * @example
889
+ * import { debugStartup, buildElectronPluginOptions } from 'electron-incremental-update/vite'
890
+ * const options = buildElectronPluginOptions({
891
+ * // ...
892
+ * main: {
893
+ * // ...
894
+ * startup: debugStartup
895
+ * },
896
+ * })
897
+ */
898
+ const debugStartup = async (args) => {
899
+ if (process.env.VSCODE_DEBUG) console.log("[startup] Electron App");
900
+ else await args.startup();
901
+ };
902
+ /**
903
+ * Startup function to filter unwanted error message
904
+ * @see {@link https://github.com/electron/electron/issues/46903#issuecomment-2848483520 reference}
905
+ * @example
906
+ * import { filterErrorMessageStartup, buildElectronPluginOptions } from 'electron-incremental-update/vite'
907
+ * const options = buildElectronPluginOptions({
908
+ * // ...
909
+ * main: {
910
+ * // ...
911
+ * startup: args => filterErrorMessageStartup(
912
+ * args,
913
+ * // ignore error message when function returns false
914
+ * msg => !/"code":-32601/.test(msg)
915
+ * )
916
+ * },
917
+ * })
918
+ */
919
+ async function filterErrorMessageStartup(args, filter) {
920
+ const stdio = process.platform === "linux" ? [
921
+ "inherit",
922
+ "pipe",
923
+ "pipe",
924
+ "ignore",
925
+ "ipc"
926
+ ] : [
927
+ "inherit",
928
+ "pipe",
929
+ "pipe",
930
+ "ipc"
931
+ ];
932
+ await args.startup(void 0, { stdio });
933
+ const elec = process.electronApp;
934
+ elec.stdout.addListener("data", (data) => {
935
+ console.log(data.toString().trimEnd());
936
+ });
937
+ elec.stderr.addListener("data", (data) => {
938
+ const message = data.toString();
939
+ if (filter(message)) console.error(message);
940
+ });
941
+ }
942
+ /**
943
+ * Startup function util to fix Windows terminal charset
944
+ * @example
945
+ * import { debugStartup, fixWinCharEncoding, buildElectronPluginOptions } from 'electron-incremental-update/vite'
946
+ * const options = buildElectronPluginOptions({
947
+ * // ...
948
+ * main: {
949
+ * // ...
950
+ * startup: fixWinCharEncoding(debugStartup)
951
+ * },
952
+ * })
953
+ */
954
+ function fixWinCharEncoding(fn) {
955
+ return (async (...args) => {
956
+ if (process.platform === "win32") (await import("node:child_process")).spawnSync("chcp", ["65001"]);
957
+ await fn(...args);
958
+ });
959
+ }
960
+ function getMainFileBaseName(options) {
961
+ let mainFilePath;
962
+ if (typeof options === "string") mainFilePath = path.basename(options);
963
+ else if (Array.isArray(options)) mainFilePath = path.basename(options[0]);
964
+ else {
965
+ if (!(options?.index ?? options?.main)) throw new Error(`\`options.main.files\` (${options}) must have "index" or "main" key, like \`{ index: "./electron/main/index.ts" }\``);
966
+ mainFilePath = options?.index ? "index.js" : "main.js";
967
+ }
968
+ log.info(`Using "${mainFilePath}" as main file`, { timestamp: true });
969
+ return mainFilePath.replace(/\.[cm]?ts$/, ".js");
970
+ }
971
+ function parseVersionPath(versionPath) {
972
+ versionPath = normalizePath(versionPath);
973
+ if (!versionPath.startsWith("./")) versionPath = `./${versionPath}`;
974
+ return new URL(versionPath, "file://").pathname.slice(1);
975
+ }
976
+ /**
977
+ * Base on `./electron/simple`
978
+ * - integrate with updater
979
+ * - no `renderer` config
980
+ * - remove old output file
981
+ * - externalize dependencies
982
+ * - auto restart when entry file changes
983
+ * - other configs in {@link https://github.com/electron-vite/electron-vite-vue/blob/main/vite.config.ts electron-vite-vue template}
984
+ *
985
+ * You can override all the vite configs, except output directories (use `options.updater.paths.electronDistPath` instead)
986
+ *
987
+ * @example
988
+ * ```ts
989
+ * import { defineConfig } from 'vite'
990
+ * import { debugStartup, electronWithUpdater } from 'electron-incremental-update/vite'
991
+ *
992
+ * export default defineConfig(async ({ command }) => {
993
+ * const isBuild = command === 'build'
994
+ * return {
995
+ * plugins: [
996
+ * electronWithUpdater({
997
+ * isBuild,
998
+ * main: {
999
+ * files: ['./electron/main/index.ts', './electron/main/worker.ts'],
1000
+ * // see https://github.com/electron-vite/electron-vite-vue/blob/85ed267c4851bf59f32888d766c0071661d4b94c/vite.config.ts#L22-L28
1001
+ * onstart: debugStartup,
1002
+ * },
1003
+ * preload: {
1004
+ * files: './electron/preload/index.ts',
1005
+ * },
1006
+ * updater: {
1007
+ * // options
1008
+ * }
1009
+ * }),
1010
+ * ],
1011
+ * server: process.env.VSCODE_DEBUG && (() => {
1012
+ * const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)
1013
+ * return {
1014
+ * host: url.hostname,
1015
+ * port: +url.port,
1016
+ * }
1017
+ * })(),
1018
+ * }
1019
+ * })
1020
+ * ```
1021
+ */
1022
+ async function electronWithUpdater(options) {
1023
+ let { isBuild, entry: _entry, main: _main, preload: _preload, sourcemap = !isBuild, minify = isBuild, buildVersionJson, updater, bytecode, useNotBundle = true } = options;
1024
+ const pkg = await loadPackageJSON();
1025
+ if (!pkg || !pkg.version || !pkg.name || !pkg.main) {
1026
+ log.error("package.json not found or invalid, must contains version, name and main field", { timestamp: true });
1027
+ return;
1028
+ }
1029
+ const isESM = pkg.type === "module";
1030
+ let bytecodeOptions = typeof bytecode === "object" ? bytecode : bytecode === true ? { enable: true } : void 0;
1031
+ if (isESM && bytecodeOptions?.enable) throw new Error("`bytecodePlugin` does not support ES module, please remove \"type\": \"module\" in package.json");
1032
+ const { buildAsarOption, buildEntryOption, buildVersionOption, postBuild, cert } = await parseOptions(isBuild, pkg, sourcemap, minify, _entry, updater);
1033
+ const { outDir: entryOutputDirPath, files, external } = buildEntryOption;
1034
+ try {
1035
+ fs.rmSync(buildAsarOption.electronDistPath, {
1036
+ recursive: true,
1037
+ force: true
1038
+ });
1039
+ fs.rmSync(entryOutputDirPath, {
1040
+ recursive: true,
1041
+ force: true
1042
+ });
1043
+ } catch {}
1044
+ log.info(`Clear cache files`, { timestamp: true });
1045
+ sourcemap ??= isBuild || !!process.env.VSCODE_DEBUG;
1046
+ const _appPath = normalizePath(path.join(entryOutputDirPath, "entry.js"));
1047
+ if (path.resolve(normalizePath(pkg.main)) !== path.resolve(_appPath)) throw new Error(`Wrong "main" field in package.json: "${pkg.main}", it should be "${_appPath}"`);
1048
+ const define = {
1049
+ __EIU_ASAR_BASE_NAME__: JSON.stringify(path.basename(buildAsarOption.asarOutputPath)),
1050
+ __EIU_ELECTRON_DIST_PATH__: JSON.stringify(normalizePath(buildAsarOption.electronDistPath)),
1051
+ __EIU_ENTRY_DIST_PATH__: JSON.stringify(normalizePath(buildEntryOption.outDir)),
1052
+ __EIU_IS_DEV__: JSON.stringify(!isBuild),
1053
+ __EIU_IS_ESM__: JSON.stringify(isESM),
1054
+ __EIU_MAIN_FILE__: JSON.stringify(getMainFileBaseName(_main.files)),
1055
+ __EIU_SIGNATURE_CERT__: JSON.stringify(cert),
1056
+ __EIU_VERSION_PATH__: JSON.stringify(parseVersionPath(normalizePath(buildVersionOption.versionPath)))
1057
+ };
1058
+ async function _buildEntry() {
1059
+ await buildEntry(buildEntryOption, isESM, define, bytecodeOptions);
1060
+ log.info(`Build entry to '${entryOutputDirPath}'`, { timestamp: true });
1061
+ await postBuild?.({
1062
+ isBuild,
1063
+ getPathFromEntryOutputDir(...paths) {
1064
+ return path.join(entryOutputDirPath, ...paths);
1065
+ },
1066
+ copyToEntryOutputDir({ from, to = path.basename(from), skipIfExist = true }) {
1067
+ if (!fs.existsSync(from)) {
1068
+ log.warn(`${from} not found`, { timestamp: true });
1069
+ return;
1070
+ }
1071
+ copyAndSkipIfExist(from, path.join(entryOutputDirPath, to), skipIfExist);
1072
+ },
1073
+ copyModules({ modules, skipIfExist = true }) {
1074
+ const nodeModulesPath = path.join(entryOutputDirPath, "node_modules");
1075
+ for (const m of modules) {
1076
+ const { rootPath } = getPackageInfoSync(m) || {};
1077
+ if (!rootPath) {
1078
+ log.warn(`Package '${m}' not found`, { timestamp: true });
1079
+ continue;
1080
+ }
1081
+ copyAndSkipIfExist(rootPath, path.join(nodeModulesPath, m), skipIfExist);
1082
+ }
1083
+ }
1084
+ });
1085
+ }
1086
+ let isInit = false;
1087
+ const result = [electronSimple({
1088
+ main: {
1089
+ entry: _main.files,
1090
+ onstart: async (args) => {
1091
+ if (!isInit) {
1092
+ isInit = true;
1093
+ await _buildEntry();
1094
+ }
1095
+ if (_main.onstart) await _main.onstart(args);
1096
+ else await args.startup();
1097
+ },
1098
+ vite: mergeConfig({
1099
+ plugins: [!isBuild && useNotBundle && notBundle(), bytecodeOptions && bytecodePlugin("main", bytecodeOptions)],
1100
+ build: {
1101
+ sourcemap,
1102
+ minify,
1103
+ outDir: `${buildAsarOption.electronDistPath}/main`,
1104
+ rolldownOptions: {
1105
+ external,
1106
+ output: {
1107
+ polyfillRequire: false,
1108
+ format: isESM ? "esm" : "cjs"
1109
+ }
1110
+ }
1111
+ },
1112
+ define
1113
+ }, _main.vite ?? {})
1114
+ },
1115
+ preload: {
1116
+ input: _preload.files,
1117
+ vite: mergeConfig({
1118
+ plugins: [bytecodeOptions && bytecodePlugin("preload", bytecodeOptions), {
1119
+ name: `${id}-build`,
1120
+ enforce: "post",
1121
+ apply() {
1122
+ return isBuild;
1123
+ },
1124
+ async closeBundle() {
1125
+ await _buildEntry();
1126
+ const buffer = await buildAsar(buildAsarOption);
1127
+ if (!buildVersionJson && !isCI) log.warn("No `buildVersionJson` option setup, skip build version json. Only build in CI by default", { timestamp: true });
1128
+ else await buildUpdateJson(buildVersionOption, buffer);
1129
+ }
1130
+ }],
1131
+ build: {
1132
+ sourcemap: sourcemap ? "inline" : void 0,
1133
+ minify,
1134
+ outDir: `${buildAsarOption.electronDistPath}/preload`,
1135
+ rolldownOptions: {
1136
+ external,
1137
+ output: { polyfillRequire: false }
1138
+ }
1139
+ },
1140
+ define
1141
+ }, _preload?.vite ?? {})
1142
+ }
1143
+ })];
1144
+ if (files) {
1145
+ const watchFiles = resolveInputToArray(files).map((file) => path.resolve(normalizePath(file)));
1146
+ result.push({
1147
+ name: `${id}-dev`,
1148
+ apply() {
1149
+ return !isBuild;
1150
+ },
1151
+ configureServer(server) {
1152
+ server.watcher.add(watchFiles).on("change", async (p) => {
1153
+ if (!watchFiles.includes(p)) return;
1154
+ await _buildEntry();
1155
+ if (_main.onstart) await _main.onstart({
1156
+ startup,
1157
+ reload: () => {
1158
+ if (process.electronApp) {
1159
+ (server.hot || server.ws).send({ type: "full-reload" });
1160
+ startup.send("electron-vite&type=hot-reload");
1161
+ } else startup();
1162
+ }
1163
+ });
1164
+ else await startup();
1165
+ });
1166
+ }
1167
+ });
1168
+ }
1169
+ return result;
1170
+ }
1171
+
1172
+ //#endregion
1173
+ //#region src/vite/define.ts
1174
+ /**
1175
+ * Vite config helper
1176
+ * @see {@link electronWithUpdater}
1177
+ * @example
1178
+ * ```ts
1179
+ * import { defineElectronConfig } from 'electron-incremental-update/vite'
1180
+ *
1181
+ * export default defineElectronConfig({
1182
+ * main: {
1183
+ * files: ['./electron/main/index.ts', './electron/main/worker.ts'],
1184
+ * // see https://github.com/electron-vite/electron-vite-vue/blob/85ed267c4851bf59f32888d766c0071661d4b94c/vite.config.ts#L22-L28
1185
+ * onstart: debugStartup,
1186
+ * },
1187
+ * preload: {
1188
+ * files: './electron/preload/index.ts',
1189
+ * },
1190
+ * updater: {
1191
+ * // options
1192
+ * },
1193
+ * renderer: {
1194
+ * server: process.env.VSCODE_DEBUG && (() => {
1195
+ * const url = new URL(pkg.debug.env.VITE_DEV_SERVER_URL)
1196
+ * return {
1197
+ * host: url.hostname,
1198
+ * port: +url.port,
1199
+ * }
1200
+ * })(),
1201
+ * }
1202
+ * })
1203
+ * ```
1204
+ */
1205
+ function defineElectronConfig(options) {
1206
+ return ({ command }) => {
1207
+ options.isBuild ??= command === "build";
1208
+ const electronPlugin = electronWithUpdater(options);
1209
+ const result = options.renderer ?? {};
1210
+ result.plugins ??= [];
1211
+ result.plugins.push(electronPlugin);
1212
+ const rendererDistPath = options.updater?.paths?.rendererDistPath;
1213
+ if (rendererDistPath) {
1214
+ result.build ??= {};
1215
+ result.build.outDir = rendererDistPath;
1216
+ }
1217
+ return result;
1218
+ };
1219
+ }
1220
+
1221
+ //#endregion
1222
+ export { convertLiteral, debugStartup, electronWithUpdater as default, electronWithUpdater, defineElectronConfig, filterErrorMessageStartup, fixWinCharEncoding };