electron-incremental-update 2.0.0 → 2.1.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/README.md CHANGED
@@ -340,7 +340,8 @@ electronWithUpdater({
340
340
 
341
341
  https://electron-vite.org/guide/source-code-protection
342
342
 
343
- - Improve the string protection (see [original issue](https://github.com/alex8088/electron-vite/issues/552)) and protect all strings by default
343
+ - Improve the string protection (see [original issue](https://github.com/alex8088/electron-vite/issues/552))
344
+ - Protect all strings by default
344
345
  - Minification is allowed
345
346
 
346
347
  #### Limitation
@@ -669,6 +670,24 @@ export interface ElectronUpdaterOptions {
669
670
  overrideGenerator?: GeneratorOverrideFunctions
670
671
  }
671
672
 
673
+ export interface BytecodeOptions {
674
+ enable: boolean
675
+ /**
676
+ * Enable in preload script. Remember to set `sandbox: false` when creating window
677
+ */
678
+ preload?: boolean
679
+ /**
680
+ * Custom electron binary path
681
+ */
682
+ electronPath?: string
683
+ /**
684
+ * Before transformed code compile function. If return `Falsy` value, it will be ignored
685
+ * @param code transformed code
686
+ * @param id file path
687
+ */
688
+ beforeCompile?: (code: string, id: string) => Promisable<string | null | undefined | void>
689
+ }
690
+
672
691
  export interface BuildEntryOption {
673
692
  /**
674
693
  * Override to minify on entry
@@ -0,0 +1,166 @@
1
+ import { readableSize } from './chunk-WYQ5DRO7.js';
2
+ import { convertLiteral, bytecodeModuleLoader, convertArrowFunctionAndTemplate, compileToBytecode, useStrict, toRelativePath } from './chunk-AUY7A2FL.js';
3
+ import './chunk-7M7DIMDN.js';
4
+ import { bytecodeLog, bytecodeId } from './chunk-5NKEXGI3.js';
5
+ import { bytecodeModuleLoaderCode } from './chunk-7IRGAAL2.js';
6
+ import path from 'node:path';
7
+ import fs from 'node:fs';
8
+ import { createFilter, normalizePath } from 'vite';
9
+ import MagicString from 'magic-string';
10
+
11
+ function bytecodePlugin(env, options) {
12
+ const {
13
+ enable,
14
+ preload = false,
15
+ electronPath,
16
+ beforeCompile
17
+ } = options;
18
+ if (!enable) {
19
+ return null;
20
+ }
21
+ if (!preload && env === "preload") {
22
+ 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 });
23
+ return null;
24
+ }
25
+ const filter = createFilter(/\.(m?[jt]s|[jt]sx)$/);
26
+ let config;
27
+ let bytecodeRequired = false;
28
+ let bytecodeFiles = [];
29
+ return {
30
+ name: `${bytecodeId}-${env}`,
31
+ apply: "build",
32
+ enforce: "post",
33
+ configResolved(resolvedConfig) {
34
+ config = resolvedConfig;
35
+ },
36
+ transform(code, id) {
37
+ if (!filter(id)) {
38
+ return convertLiteral(code, !!config.build.sourcemap);
39
+ }
40
+ },
41
+ generateBundle(options2) {
42
+ if (options2.format !== "es" && bytecodeRequired) {
43
+ this.emitFile({
44
+ type: "asset",
45
+ source: `${bytecodeModuleLoaderCode}
46
+ `,
47
+ name: "Bytecode Loader File",
48
+ fileName: bytecodeModuleLoader
49
+ });
50
+ }
51
+ },
52
+ renderChunk(code, chunk, options2) {
53
+ if (options2.format === "es") {
54
+ bytecodeLog.warn(
55
+ '`bytecodePlugin` does not support ES module, please set "build.rollupOptions.output.format" option to "cjs"',
56
+ { timestamp: true }
57
+ );
58
+ return null;
59
+ }
60
+ if (chunk.type === "chunk") {
61
+ bytecodeRequired = true;
62
+ return convertArrowFunctionAndTemplate(code);
63
+ }
64
+ return null;
65
+ },
66
+ async writeBundle(options2, output) {
67
+ if (options2.format === "es" || !bytecodeRequired) {
68
+ return;
69
+ }
70
+ const outDir = options2.dir;
71
+ bytecodeFiles = [];
72
+ const bundles = Object.keys(output);
73
+ const chunks = Object.values(output).filter(
74
+ (chunk) => chunk.type === "chunk" && chunk.fileName !== bytecodeModuleLoader
75
+ );
76
+ const bytecodeChunks = chunks.map((chunk) => chunk.fileName);
77
+ const nonEntryChunks = chunks.filter((chunk) => !chunk.isEntry).map((chunk) => path.basename(chunk.fileName));
78
+ const pattern = nonEntryChunks.map((chunk) => `(${chunk})`).join("|");
79
+ const bytecodeRE = pattern ? new RegExp(`require\\(\\S*(?=(${pattern})\\S*\\))`, "g") : null;
80
+ const getBytecodeLoaderBlock = (chunkFileName) => {
81
+ return `require("${toRelativePath(bytecodeModuleLoader, normalizePath(chunkFileName))}");`;
82
+ };
83
+ await Promise.all(
84
+ bundles.map(async (name) => {
85
+ const chunk = output[name];
86
+ if (chunk.type === "chunk") {
87
+ let _code = chunk.code;
88
+ const chunkFilePath = path.resolve(outDir, name);
89
+ if (beforeCompile) {
90
+ const cbResult = await beforeCompile(_code, chunkFilePath);
91
+ if (cbResult) {
92
+ _code = cbResult;
93
+ }
94
+ }
95
+ if (bytecodeRE && _code.match(bytecodeRE)) {
96
+ let match;
97
+ const s = new MagicString(_code);
98
+ while (match = bytecodeRE.exec(_code)) {
99
+ const [prefix, chunkName] = match;
100
+ const len = prefix.length + chunkName.length;
101
+ s.overwrite(match.index, match.index + len, `${prefix + chunkName}c`, {
102
+ contentOnly: true
103
+ });
104
+ }
105
+ _code = s.toString();
106
+ }
107
+ if (bytecodeChunks.includes(name)) {
108
+ const bytecodeBuffer = await compileToBytecode(_code, electronPath);
109
+ fs.writeFileSync(`${chunkFilePath}c`, bytecodeBuffer);
110
+ if (chunk.isEntry) {
111
+ const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
112
+ const bytecodeModuleBlock = `require("./${`${path.basename(name)}c`}");`;
113
+ const code = `${useStrict}
114
+ ${bytecodeLoaderBlock}
115
+ module.exports=${bytecodeModuleBlock}
116
+ `;
117
+ fs.writeFileSync(chunkFilePath, code);
118
+ } else {
119
+ fs.unlinkSync(chunkFilePath);
120
+ }
121
+ bytecodeFiles.push({ name: `${name}c`, size: bytecodeBuffer.length });
122
+ } else {
123
+ if (chunk.isEntry) {
124
+ let hasBytecodeMoudle = false;
125
+ const idsToHandle = /* @__PURE__ */ new Set([...chunk.imports, ...chunk.dynamicImports]);
126
+ for (const moduleId of idsToHandle) {
127
+ if (bytecodeChunks.includes(moduleId)) {
128
+ hasBytecodeMoudle = true;
129
+ break;
130
+ }
131
+ const moduleInfo = this.getModuleInfo(moduleId);
132
+ if (moduleInfo && !moduleInfo.isExternal) {
133
+ const { importers, dynamicImporters } = moduleInfo;
134
+ for (const importerId of importers) {
135
+ idsToHandle.add(importerId);
136
+ }
137
+ for (const importerId of dynamicImporters) {
138
+ idsToHandle.add(importerId);
139
+ }
140
+ }
141
+ }
142
+ const bytecodeLoaderBlock = getBytecodeLoaderBlock(chunk.fileName);
143
+ _code = hasBytecodeMoudle ? _code.replace(useStrict, `${useStrict}
144
+ ${bytecodeLoaderBlock}`) : _code;
145
+ }
146
+ fs.writeFileSync(chunkFilePath, _code);
147
+ }
148
+ }
149
+ })
150
+ );
151
+ },
152
+ closeBundle() {
153
+ const outDir = `${normalizePath(path.relative(config.root, path.resolve(config.root, config.build.outDir)))}/`;
154
+ bytecodeFiles.forEach((file) => {
155
+ bytecodeLog.info(
156
+ `${outDir}${file.name} [${readableSize(file.size)}]`,
157
+ { timestamp: true }
158
+ );
159
+ });
160
+ bytecodeLog.info(`${bytecodeFiles.length} bundles compiled into bytecode.`, { timestamp: true });
161
+ bytecodeFiles = [];
162
+ }
163
+ };
164
+ }
165
+
166
+ export { bytecodePlugin };
@@ -0,0 +1,44 @@
1
+ import { electronMajorVersion } from './chunk-AUY7A2FL.js';
2
+ import MagicString from 'magic-string';
3
+
4
+ // src/vite/esm/constant.ts
5
+ var CJSShim = `
6
+ // -- CommonJS Shims --
7
+ import __cjs_url__ from 'node:url';
8
+ import __cjs_path__ from 'node:path';
9
+ import __cjs_mod__ from 'node:module';
10
+ const __filename = __cjs_url__.fileURLToPath(import.meta.url);
11
+ const __dirname = __cjs_path__.dirname(__filename);
12
+ const require = __cjs_mod__.createRequire(import.meta.url);
13
+ `;
14
+ var CJSShim_electron_30 = `
15
+ // -- CommonJS Shims --
16
+ import __cjs_mod__ from 'node:module';
17
+ const __filename = import.meta.filename;
18
+ const __dirname = import.meta.dirname;
19
+ const require = __cjs_mod__.createRequire(import.meta.url);
20
+ `;
21
+ var shim = electronMajorVersion >= 30 ? CJSShim_electron_30 : CJSShim;
22
+
23
+ // src/vite/esm/utils.ts
24
+ 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;
25
+ function findStaticImports(code) {
26
+ const matches = [];
27
+ for (const match of code.matchAll(ESMStaticImportRe)) {
28
+ matches.push({ end: (match.index || 0) + match[0].length });
29
+ }
30
+ return matches;
31
+ }
32
+ function insertCJSShim(code, sourcemap, insertPosition = 0) {
33
+ if (code.includes(shim) || !/__filename|__dirname|require\(|require\.resolve\(|require\.apply\(/.test(code)) {
34
+ return null;
35
+ }
36
+ const s = new MagicString(code);
37
+ s.appendRight(insertPosition, shim);
38
+ return {
39
+ code: s.toString(),
40
+ map: sourcemap ? s.generateMap({ hires: "boundary" }) : null
41
+ };
42
+ }
43
+
44
+ export { findStaticImports, insertCJSShim };
@@ -0,0 +1,10 @@
1
+ import { createLogger } from 'vite';
2
+
3
+ // src/vite/constant.ts
4
+ var id = "electron-incremental-updater";
5
+ var bytecodeId = `${id}-bytecode`;
6
+ var esmId = `${id}-esm`;
7
+ var log = createLogger("info", { prefix: `[${id}]` });
8
+ var bytecodeLog = createLogger("info", { prefix: `[${bytecodeId}]` });
9
+
10
+ export { bytecodeId, bytecodeLog, esmId, id, log };
@@ -0,0 +1,5 @@
1
+ // src/vite/bytecode/code.ts
2
+ 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";
3
+ 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';
4
+
5
+ export { bytecodeGeneratorScript, bytecodeModuleLoaderCode };
@@ -0,0 +1,43 @@
1
+ // src/utils/version.ts
2
+ function parseVersion(version) {
3
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([a-z0-9.-]+))?/i.exec(version);
4
+ if (!match) {
5
+ throw new TypeError(`invalid version: ${version}`);
6
+ }
7
+ const [major, minor, patch] = match.slice(1, 4).map(Number);
8
+ const ret = {
9
+ major,
10
+ minor,
11
+ patch,
12
+ stage: "",
13
+ stageVersion: -1
14
+ };
15
+ if (match[4]) {
16
+ let [stage, _v] = match[4].split(".");
17
+ ret.stage = stage;
18
+ ret.stageVersion = Number(_v) || -1;
19
+ }
20
+ if (Number.isNaN(major) || Number.isNaN(minor) || Number.isNaN(patch) || Number.isNaN(ret.stageVersion)) {
21
+ throw new TypeError(`Invalid version: ${version}`);
22
+ }
23
+ return ret;
24
+ }
25
+ function isUpdateJSON(json) {
26
+ const is = (j) => !!(j && j.minimumVersion && j.signature && j.version);
27
+ return is(json) && is(json?.beta);
28
+ }
29
+ function defaultVersionJsonGenerator(existingJson, signature, version, minimumVersion) {
30
+ existingJson.beta = {
31
+ version,
32
+ minimumVersion,
33
+ signature
34
+ };
35
+ if (!parseVersion(version).stage) {
36
+ existingJson.version = version;
37
+ existingJson.minimumVersion = minimumVersion;
38
+ existingJson.signature = signature;
39
+ }
40
+ return existingJson;
41
+ }
42
+
43
+ export { defaultVersionJsonGenerator, isUpdateJSON, parseVersion };
@@ -0,0 +1,147 @@
1
+ import { parseVersion } from './chunk-7M7DIMDN.js';
2
+ import { bytecodeLog } from './chunk-5NKEXGI3.js';
3
+ import { bytecodeGeneratorScript } from './chunk-7IRGAAL2.js';
4
+ import path from 'node:path';
5
+ import fs from 'node:fs';
6
+ import cp from 'node:child_process';
7
+ import * as babel from '@babel/core';
8
+ import MagicString from 'magic-string';
9
+ import { getPackageInfoSync } from 'local-pkg';
10
+
11
+ var electronModule = getPackageInfoSync("electron");
12
+ var electronMajorVersion = parseVersion(electronModule.version).major;
13
+ var useStrict = "'use strict';";
14
+ var bytecodeModuleLoader = "__loader__.js";
15
+ function getElectronPath() {
16
+ const electronModulePath = electronModule.rootPath;
17
+ let electronExecPath = process.env.ELECTRON_EXEC_PATH || "";
18
+ if (!electronExecPath) {
19
+ if (!electronModulePath) {
20
+ throw new Error("Electron is not installed");
21
+ }
22
+ const pathFile = path.join(electronModulePath, "path.txt");
23
+ let executablePath;
24
+ if (fs.existsSync(pathFile)) {
25
+ executablePath = fs.readFileSync(pathFile, "utf-8");
26
+ }
27
+ if (executablePath) {
28
+ electronExecPath = path.join(electronModulePath, "dist", executablePath);
29
+ process.env.ELECTRON_EXEC_PATH = electronExecPath;
30
+ } else {
31
+ throw new Error("Electron executable file is not existed");
32
+ }
33
+ }
34
+ return electronExecPath;
35
+ }
36
+ function getBytecodeCompilerPath() {
37
+ const scriptPath = path.join(electronModule.rootPath, "EIU_bytenode.cjs");
38
+ if (!fs.existsSync(scriptPath)) {
39
+ fs.writeFileSync(scriptPath, bytecodeGeneratorScript);
40
+ }
41
+ return scriptPath;
42
+ }
43
+ function toRelativePath(filename, importer) {
44
+ const relPath = path.posix.relative(path.dirname(importer), filename);
45
+ return relPath.startsWith(".") ? relPath : `./${relPath}`;
46
+ }
47
+ function compileToBytecode(code, electronPath = getElectronPath()) {
48
+ let data = Buffer.from([]);
49
+ const logErr = (...args) => bytecodeLog.error(args.join(" "), { timestamp: true });
50
+ const bytecodePath = getBytecodeCompilerPath();
51
+ return new Promise((resolve, reject) => {
52
+ const proc = cp.spawn(electronPath, [bytecodePath], {
53
+ env: { ELECTRON_RUN_AS_NODE: "1" },
54
+ stdio: ["pipe", "pipe", "pipe", "ipc"]
55
+ });
56
+ if (proc.stdin) {
57
+ proc.stdin.write(code);
58
+ proc.stdin.end();
59
+ }
60
+ if (proc.stdout) {
61
+ proc.stdout.on("data", (chunk) => data = Buffer.concat([data, chunk]));
62
+ proc.stdout.on("error", (err) => logErr(err));
63
+ proc.stdout.on("end", () => resolve(data));
64
+ }
65
+ if (proc.stderr) {
66
+ proc.stderr.on("data", (chunk) => logErr("Error: ", chunk.toString()));
67
+ proc.stderr.on("error", (err) => logErr("Error: ", err));
68
+ }
69
+ proc.addListener("error", (err) => logErr(err));
70
+ proc.on("error", (err) => reject(err));
71
+ proc.on("exit", () => resolve(data));
72
+ });
73
+ }
74
+ function convertArrowFunctionAndTemplate(code) {
75
+ const result = babel.transform(code, {
76
+ plugins: ["@babel/plugin-transform-arrow-functions", "@babel/plugin-transform-template-literals"]
77
+ });
78
+ return {
79
+ code: result?.code || code,
80
+ map: result?.map
81
+ };
82
+ }
83
+ var decodeFn = ";function _0xstr_(a,b){return String.fromCharCode.apply(0,a.map(function(x){return x-b}))};";
84
+ function obfuscateString(input, offset = ~~(Math.random() * 16) + 1) {
85
+ const hexArray = input.split("").map((c) => `0x${(c.charCodeAt(0) + offset).toString(16)}`);
86
+ return `_0xstr_([${hexArray.join(",")}],${offset})`;
87
+ }
88
+ function convertLiteral(code, sourcemap, offset) {
89
+ const s = new MagicString(code);
90
+ let hasTransformed = false;
91
+ const ast = babel.parse(code, { ast: true });
92
+ if (!ast) {
93
+ throw new Error("Cannot parse code");
94
+ }
95
+ babel.traverse(ast, {
96
+ StringLiteral(path2) {
97
+ const parent = path2.parent;
98
+ const node = path2.node;
99
+ if (parent.type === "CallExpression") {
100
+ if (parent.callee.type === "Identifier" && parent.callee.name === "require") {
101
+ return;
102
+ }
103
+ if (parent.callee.type === "Import") {
104
+ return;
105
+ }
106
+ }
107
+ if (parent.type.startsWith("Export")) {
108
+ return;
109
+ }
110
+ if (parent.type.startsWith("Import")) {
111
+ return;
112
+ }
113
+ if (parent.type === "ObjectMethod" && parent.key === node) {
114
+ return;
115
+ }
116
+ if (parent.type === "ObjectProperty" && parent.key === node) {
117
+ const result2 = `[${obfuscateString(node.value, offset)}]`;
118
+ const start2 = node.start;
119
+ const end2 = node.end;
120
+ if (start2 && end2) {
121
+ s.overwrite(start2, end2, result2);
122
+ hasTransformed = true;
123
+ }
124
+ return;
125
+ }
126
+ if (!node.value.trim()) {
127
+ return;
128
+ }
129
+ const result = obfuscateString(node.value, offset);
130
+ const start = node.start;
131
+ const end = node.end;
132
+ if (start && end) {
133
+ s.overwrite(start, end, result);
134
+ hasTransformed = true;
135
+ }
136
+ }
137
+ });
138
+ if (hasTransformed) {
139
+ s.append("\n").append(decodeFn);
140
+ }
141
+ return {
142
+ code: s.toString(),
143
+ map: sourcemap ? s.generateMap({ hires: true }) : void 0
144
+ };
145
+ }
146
+
147
+ export { bytecodeModuleLoader, compileToBytecode, convertArrowFunctionAndTemplate, convertLiteral, decodeFn, electronMajorVersion, electronModule, obfuscateString, toRelativePath, useStrict };
@@ -0,0 +1,12 @@
1
+ // src/vite/utils.ts
2
+ function readableSize(size) {
3
+ const units = ["B", "KB", "MB", "GB"];
4
+ let i = 0;
5
+ while (size >= 1024 && i < units.length - 1) {
6
+ size /= 1024;
7
+ i++;
8
+ }
9
+ return `${size.toFixed(2)} ${units[i]}`;
10
+ }
11
+
12
+ export { readableSize };
@@ -0,0 +1,106 @@
1
+ import { __require } from './chunk-RCRKUKFX.js';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import electron 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(electron.app.getAppPath()), `${electron.app.name}.asar`, ...paths);
12
+ }
13
+ function getAppVersion() {
14
+ return isDev ? getEntryVersion() : fs.readFileSync(getPathFromAppNameAsar("version"), "utf-8");
15
+ }
16
+ function getEntryVersion() {
17
+ return electron.app.getVersion();
18
+ }
19
+ function requireNative(moduleName) {
20
+ const m = getPathFromEntryAsar(moduleName);
21
+ if (__EIU_IS_ESM__) {
22
+ throw new Error(`Cannot require "${m}", \`requireNative\` only support CommonJS, use \`importNative\` instead`);
23
+ }
24
+ return __require(m);
25
+ }
26
+ async function importNative(moduleName) {
27
+ const m = getPathFromEntryAsar(moduleName);
28
+ if (!__EIU_IS_ESM__) {
29
+ throw new Error(`Cannot import "${m}", \`importNative\` only support ESModule, use \`requireNative\` instead`);
30
+ }
31
+ return await import(`file://${m}.js`);
32
+ }
33
+ function restartApp() {
34
+ electron.app.relaunch();
35
+ electron.app.quit();
36
+ }
37
+ function setAppUserModelId(id) {
38
+ if (isWin) {
39
+ electron.app.setAppUserModelId(id ?? `org.${electron.app.name}`);
40
+ }
41
+ }
42
+ function disableHWAccForWin7() {
43
+ if (!__EIU_IS_ESM__ && __require("node:os").release().startsWith("6.1")) {
44
+ electron.app.disableHardwareAcceleration();
45
+ }
46
+ }
47
+ function singleInstance(window) {
48
+ const result = electron.app.requestSingleInstanceLock();
49
+ if (result) {
50
+ electron.app.on("second-instance", () => {
51
+ if (window) {
52
+ window.show();
53
+ if (window.isMinimized()) {
54
+ window.restore();
55
+ }
56
+ window.focus();
57
+ }
58
+ });
59
+ } else {
60
+ electron.app.quit();
61
+ }
62
+ return result;
63
+ }
64
+ function setPortableAppDataPath(dirName = "data") {
65
+ const portablePath = path.join(path.dirname(electron.app.getPath("exe")), dirName);
66
+ if (!fs.existsSync(portablePath)) {
67
+ fs.mkdirSync(portablePath);
68
+ }
69
+ electron.app.setPath("appData", portablePath);
70
+ }
71
+ function loadPage(win, htmlFilePath = "index.html") {
72
+ if (isDev) {
73
+ win.loadURL(process.env.VITE_DEV_SERVER_URL + htmlFilePath);
74
+ } else {
75
+ win.loadFile(getPathFromAppNameAsar("renderer", htmlFilePath));
76
+ }
77
+ }
78
+ function beautifyDevTools(win, options) {
79
+ const { mono, sans, scrollbar = true } = options;
80
+ win.webContents.on("devtools-opened", () => {
81
+ let css = `:root{--sans: ${sans};--mono: ${mono}}:root,body{--source-code-font-family: var(--mono) !important;--source-code-font-size: 12px !important;--monospace-font-family: var(--mono) !important;--monospace-font-size: 12px !important;--default-font-family: var(--sans), sans-serif !important;--default-font-size: 12px !important}button,input,select,.undisplayable-text,.expandable-inline-button{font-family:var(--sans)!important}`;
82
+ if (scrollbar) {
83
+ css += ":root{--scrollbar-width: max(.85vw, 10px)}@media (prefers-color-scheme: light){:root{--scrollbar-color-rgb: 0, 0, 0}}@media (prefers-color-scheme: dark){:root{--scrollbar-color-rgb: 255, 255, 255}}*::-webkit-scrollbar{width:var(--scrollbar-width)!important;height:var(--scrollbar-width)!important}*::-webkit-scrollbar-track{background-color:transparent!important;border-radius:var(--scrollbar-width)!important;box-shadow:none!important}*::-webkit-scrollbar-thumb{box-shadow:inset 0 0 0 var(--scrollbar-width)!important;border-radius:var(--scrollbar-width)!important;border:calc(var(--scrollbar-width) * 2 / 9) solid transparent!important;background-clip:content-box;background-color:transparent!important;color:rgba(var(--scrollbar-color-rgb),30%)!important}*::-webkit-scrollbar-thumb:hover{color:rgba(var(--scrollbar-color-rgb),45%)!important}*::-webkit-scrollbar-thumb:active{color:rgba(var(--scrollbar-color-rgb),60%)!important}@supports not selector(::-webkit-scrollbar){html{scrollbar-color:rgb(var(--scrollbar-color-rgb));scrollbar-width:thin}}";
84
+ }
85
+ const js = `let overriddenStyle=document.createElement('style');overriddenStyle.innerHTML='${css}';document.body.append(overriddenStyle);document.body.classList.remove('platform-windows','platform-mac','platform-linux');`;
86
+ win?.webContents.devToolsWebContents?.executeJavaScript(js);
87
+ });
88
+ }
89
+ function getPathFromMain(...paths) {
90
+ return isDev ? path.join(electron.app.getAppPath(), __EIU_ELECTRON_DIST_PATH__, "main", ...paths) : getPathFromAppNameAsar("main", ...paths);
91
+ }
92
+ function getPathFromPreload(...paths) {
93
+ return isDev ? path.join(electron.app.getAppPath(), __EIU_ELECTRON_DIST_PATH__, "preload", ...paths) : getPathFromAppNameAsar("preload", ...paths);
94
+ }
95
+ function getPathFromPublic(...paths) {
96
+ return isDev ? path.join(electron.app.getAppPath(), "public", ...paths) : getPathFromAppNameAsar("renderer", ...paths);
97
+ }
98
+ function getPathFromEntryAsar(...paths) {
99
+ return path.join(electron.app.getAppPath(), __EIU_ENTRY_DIST_PATH__, ...paths);
100
+ }
101
+ function handleUnexpectedErrors(callback) {
102
+ process.on("uncaughtException", callback);
103
+ process.on("unhandledRejection", callback);
104
+ }
105
+
106
+ export { beautifyDevTools, disableHWAccForWin7, getAppVersion, getEntryVersion, getPathFromAppNameAsar, getPathFromEntryAsar, getPathFromMain, getPathFromPreload, getPathFromPublic, handleUnexpectedErrors, importNative, isDev, isLinux, isMac, isWin, loadPage, requireNative, restartApp, setAppUserModelId, setPortableAppDataPath, singleInstance };
@@ -0,0 +1 @@
1
+ export { bytecodeGeneratorScript, bytecodeModuleLoaderCode } from './chunk-7IRGAAL2.js';
@@ -0,0 +1 @@
1
+ export { bytecodeId, bytecodeLog, esmId, id, log } from './chunk-5NKEXGI3.js';
@@ -0,0 +1,26 @@
1
+ import { findStaticImports, insertCJSShim } from './chunk-5CE27A6G.js';
2
+ import './chunk-AUY7A2FL.js';
3
+ import './chunk-7M7DIMDN.js';
4
+ import { esmId } from './chunk-5NKEXGI3.js';
5
+ import './chunk-7IRGAAL2.js';
6
+
7
+ // src/vite/esm/index.ts
8
+ function esm() {
9
+ let sourcemap;
10
+ return {
11
+ name: esmId,
12
+ enforce: "post",
13
+ configResolved(config) {
14
+ sourcemap = config.build.sourcemap;
15
+ },
16
+ renderChunk(code, _chunk, options) {
17
+ if (options.format === "es") {
18
+ const lastESMImport = findStaticImports(code).pop();
19
+ const pos = lastESMImport ? lastESMImport.end : 0;
20
+ return insertCJSShim(code, sourcemap, pos);
21
+ }
22
+ }
23
+ };
24
+ }
25
+
26
+ export { esm };