12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231 |
- "use strict";
- var __defProp = Object.defineProperty;
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
- var _a;
- const require$$0$4 = require("electron");
- const path$6 = require("node:path");
- const fs$5 = require("fs");
- const require$$2 = require("path");
- const require$$0 = require("child_process");
- const require$$1 = require("os");
- const require$$0$1 = require("util");
- const require$$0$2 = require("events");
- const require$$0$3 = require("http");
- const require$$1$1 = require("https");
- const express = require("express");
- const cors = require("cors");
- function getDefaultExportFromCjs(x) {
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
- }
- const fs$4 = fs$5;
- const path$5 = require$$2;
- var packageJson$1 = {
- findAndReadPackageJson,
- tryReadJsonAt
- };
- function findAndReadPackageJson() {
- return tryReadJsonAt(getMainModulePath()) || tryReadJsonAt(extractPathFromArgs()) || tryReadJsonAt(process.resourcesPath, "app.asar") || tryReadJsonAt(process.resourcesPath, "app") || tryReadJsonAt(process.cwd()) || { name: void 0, version: void 0 };
- }
- function tryReadJsonAt(...searchPaths) {
- if (!searchPaths[0]) {
- return void 0;
- }
- try {
- const searchPath = path$5.join(...searchPaths);
- const fileName = findUp("package.json", searchPath);
- if (!fileName) {
- return void 0;
- }
- const json = JSON.parse(fs$4.readFileSync(fileName, "utf8"));
- const name = (json == null ? void 0 : json.productName) || (json == null ? void 0 : json.name);
- if (!name || name.toLowerCase() === "electron") {
- return void 0;
- }
- if (name) {
- return { name, version: json == null ? void 0 : json.version };
- }
- return void 0;
- } catch (e) {
- return void 0;
- }
- }
- function findUp(fileName, cwd) {
- let currentPath = cwd;
- while (true) {
- const parsedPath = path$5.parse(currentPath);
- const root = parsedPath.root;
- const dir = parsedPath.dir;
- if (fs$4.existsSync(path$5.join(currentPath, fileName))) {
- return path$5.resolve(path$5.join(currentPath, fileName));
- }
- if (currentPath === root) {
- return null;
- }
- currentPath = dir;
- }
- }
- function extractPathFromArgs() {
- const matchedArgs = process.argv.filter((arg) => {
- return arg.indexOf("--user-data-dir=") === 0;
- });
- if (matchedArgs.length === 0 || typeof matchedArgs[0] !== "string") {
- return null;
- }
- const userDataDir = matchedArgs[0];
- return userDataDir.replace("--user-data-dir=", "");
- }
- function getMainModulePath() {
- var _a2;
- try {
- return (_a2 = require.main) == null ? void 0 : _a2.filename;
- } catch {
- return void 0;
- }
- }
- const childProcess = require$$0;
- const os$3 = require$$1;
- const path$4 = require$$2;
- const packageJson = packageJson$1;
- let NodeExternalApi$1 = class NodeExternalApi {
- constructor() {
- __publicField(this, "appName");
- __publicField(this, "appPackageJson");
- __publicField(this, "platform", process.platform);
- }
- getAppLogPath(appName = this.getAppName()) {
- if (this.platform === "darwin") {
- return path$4.join(this.getSystemPathHome(), "Library/Logs", appName);
- }
- return path$4.join(this.getAppUserDataPath(appName), "logs");
- }
- getAppName() {
- var _a2;
- const appName = this.appName || ((_a2 = this.getAppPackageJson()) == null ? void 0 : _a2.name);
- if (!appName) {
- throw new Error(
- "electron-log can't determine the app name. It tried these methods:\n1. Use `electron.app.name`\n2. Use productName or name from the nearest package.json`\nYou can also set it through log.transports.file.setAppName()"
- );
- }
- return appName;
- }
- /**
- * @private
- * @returns {undefined}
- */
- getAppPackageJson() {
- if (typeof this.appPackageJson !== "object") {
- this.appPackageJson = packageJson.findAndReadPackageJson();
- }
- return this.appPackageJson;
- }
- getAppUserDataPath(appName = this.getAppName()) {
- return appName ? path$4.join(this.getSystemPathAppData(), appName) : void 0;
- }
- getAppVersion() {
- var _a2;
- return (_a2 = this.getAppPackageJson()) == null ? void 0 : _a2.version;
- }
- getElectronLogPath() {
- return this.getAppLogPath();
- }
- getMacOsVersion() {
- const release = Number(os$3.release().split(".")[0]);
- if (release <= 19) {
- return `10.${release - 4}`;
- }
- return release - 9;
- }
- /**
- * @protected
- * @returns {string}
- */
- getOsVersion() {
- let osName = os$3.type().replace("_", " ");
- let osVersion = os$3.release();
- if (osName === "Darwin") {
- osName = "macOS";
- osVersion = this.getMacOsVersion();
- }
- return `${osName} ${osVersion}`;
- }
- /**
- * @return {PathVariables}
- */
- getPathVariables() {
- const appName = this.getAppName();
- const appVersion = this.getAppVersion();
- const self = this;
- return {
- appData: this.getSystemPathAppData(),
- appName,
- appVersion,
- get electronDefaultDir() {
- return self.getElectronLogPath();
- },
- home: this.getSystemPathHome(),
- libraryDefaultDir: this.getAppLogPath(appName),
- libraryTemplate: this.getAppLogPath("{appName}"),
- temp: this.getSystemPathTemp(),
- userData: this.getAppUserDataPath(appName)
- };
- }
- getSystemPathAppData() {
- const home = this.getSystemPathHome();
- switch (this.platform) {
- case "darwin": {
- return path$4.join(home, "Library/Application Support");
- }
- case "win32": {
- return process.env.APPDATA || path$4.join(home, "AppData/Roaming");
- }
- default: {
- return process.env.XDG_CONFIG_HOME || path$4.join(home, ".config");
- }
- }
- }
- getSystemPathHome() {
- var _a2;
- return ((_a2 = os$3.homedir) == null ? void 0 : _a2.call(os$3)) || process.env.HOME;
- }
- getSystemPathTemp() {
- return os$3.tmpdir();
- }
- getVersions() {
- return {
- app: `${this.getAppName()} ${this.getAppVersion()}`,
- electron: void 0,
- os: this.getOsVersion()
- };
- }
- isDev() {
- return process.env.NODE_ENV === "development" || process.env.ELECTRON_IS_DEV === "1";
- }
- isElectron() {
- return Boolean(process.versions.electron);
- }
- onAppEvent(_eventName, _handler) {
- }
- onAppReady(handler) {
- handler();
- }
- onEveryWebContentsEvent(eventName, handler) {
- }
- /**
- * Listen to async messages sent from opposite process
- * @param {string} channel
- * @param {function} listener
- */
- onIpc(channel, listener) {
- }
- onIpcInvoke(channel, listener) {
- }
- /**
- * @param {string} url
- * @param {Function} [logFunction]
- */
- openUrl(url2, logFunction = console.error) {
- const startMap = { darwin: "open", win32: "start", linux: "xdg-open" };
- const start = startMap[process.platform] || "xdg-open";
- childProcess.exec(`${start} ${url2}`, {}, (err) => {
- if (err) {
- logFunction(err);
- }
- });
- }
- setAppName(appName) {
- this.appName = appName;
- }
- setPlatform(platform) {
- this.platform = platform;
- }
- setPreloadFileForSessions({
- filePath,
- // eslint-disable-line no-unused-vars
- includeFutureSession = true,
- // eslint-disable-line no-unused-vars
- getSessions = () => []
- // eslint-disable-line no-unused-vars
- }) {
- }
- /**
- * Sent a message to opposite process
- * @param {string} channel
- * @param {any} message
- */
- sendIpc(channel, message) {
- }
- showErrorBox(title, message) {
- }
- };
- var NodeExternalApi_1 = NodeExternalApi$1;
- const path$3 = require$$2;
- const NodeExternalApi2 = NodeExternalApi_1;
- let ElectronExternalApi$1 = class ElectronExternalApi extends NodeExternalApi2 {
- /**
- * @param {object} options
- * @param {typeof Electron} [options.electron]
- */
- constructor({ electron: electron2 } = {}) {
- super();
- /**
- * @type {typeof Electron}
- */
- __publicField(this, "electron");
- this.electron = electron2;
- }
- getAppName() {
- var _a2, _b;
- let appName;
- try {
- appName = this.appName || ((_a2 = this.electron.app) == null ? void 0 : _a2.name) || ((_b = this.electron.app) == null ? void 0 : _b.getName());
- } catch {
- }
- return appName || super.getAppName();
- }
- getAppUserDataPath(appName) {
- return this.getPath("userData") || super.getAppUserDataPath(appName);
- }
- getAppVersion() {
- var _a2;
- let appVersion;
- try {
- appVersion = (_a2 = this.electron.app) == null ? void 0 : _a2.getVersion();
- } catch {
- }
- return appVersion || super.getAppVersion();
- }
- getElectronLogPath() {
- return this.getPath("logs") || super.getElectronLogPath();
- }
- /**
- * @private
- * @param {any} name
- * @returns {string|undefined}
- */
- getPath(name) {
- var _a2;
- try {
- return (_a2 = this.electron.app) == null ? void 0 : _a2.getPath(name);
- } catch {
- return void 0;
- }
- }
- getVersions() {
- return {
- app: `${this.getAppName()} ${this.getAppVersion()}`,
- electron: `Electron ${process.versions.electron}`,
- os: this.getOsVersion()
- };
- }
- getSystemPathAppData() {
- return this.getPath("appData") || super.getSystemPathAppData();
- }
- isDev() {
- var _a2;
- if (((_a2 = this.electron.app) == null ? void 0 : _a2.isPackaged) !== void 0) {
- return !this.electron.app.isPackaged;
- }
- if (typeof process.execPath === "string") {
- const execFileName = path$3.basename(process.execPath).toLowerCase();
- return execFileName.startsWith("electron");
- }
- return super.isDev();
- }
- onAppEvent(eventName, handler) {
- var _a2;
- (_a2 = this.electron.app) == null ? void 0 : _a2.on(eventName, handler);
- return () => {
- var _a3;
- (_a3 = this.electron.app) == null ? void 0 : _a3.off(eventName, handler);
- };
- }
- onAppReady(handler) {
- var _a2, _b, _c;
- if ((_a2 = this.electron.app) == null ? void 0 : _a2.isReady()) {
- handler();
- } else if ((_b = this.electron.app) == null ? void 0 : _b.once) {
- (_c = this.electron.app) == null ? void 0 : _c.once("ready", handler);
- } else {
- handler();
- }
- }
- onEveryWebContentsEvent(eventName, handler) {
- var _a2, _b, _c;
- (_b = (_a2 = this.electron.webContents) == null ? void 0 : _a2.getAllWebContents()) == null ? void 0 : _b.forEach((webContents) => {
- webContents.on(eventName, handler);
- });
- (_c = this.electron.app) == null ? void 0 : _c.on("web-contents-created", onWebContentsCreated);
- return () => {
- var _a3, _b2;
- (_a3 = this.electron.webContents) == null ? void 0 : _a3.getAllWebContents().forEach((webContents) => {
- webContents.off(eventName, handler);
- });
- (_b2 = this.electron.app) == null ? void 0 : _b2.off("web-contents-created", onWebContentsCreated);
- };
- function onWebContentsCreated(_, webContents) {
- webContents.on(eventName, handler);
- }
- }
- /**
- * Listen to async messages sent from opposite process
- * @param {string} channel
- * @param {function} listener
- */
- onIpc(channel, listener) {
- var _a2;
- (_a2 = this.electron.ipcMain) == null ? void 0 : _a2.on(channel, listener);
- }
- onIpcInvoke(channel, listener) {
- var _a2, _b;
- (_b = (_a2 = this.electron.ipcMain) == null ? void 0 : _a2.handle) == null ? void 0 : _b.call(_a2, channel, listener);
- }
- /**
- * @param {string} url
- * @param {Function} [logFunction]
- */
- openUrl(url2, logFunction = console.error) {
- var _a2;
- (_a2 = this.electron.shell) == null ? void 0 : _a2.openExternal(url2).catch(logFunction);
- }
- setPreloadFileForSessions({
- filePath,
- includeFutureSession = true,
- getSessions = () => {
- var _a2;
- return [(_a2 = this.electron.session) == null ? void 0 : _a2.defaultSession];
- }
- }) {
- for (const session of getSessions().filter(Boolean)) {
- setPreload(session);
- }
- if (includeFutureSession) {
- this.onAppEvent("session-created", (session) => {
- setPreload(session);
- });
- }
- function setPreload(session) {
- session.setPreloads([...session.getPreloads(), filePath]);
- }
- }
- /**
- * Sent a message to opposite process
- * @param {string} channel
- * @param {any} message
- */
- sendIpc(channel, message) {
- var _a2, _b;
- (_b = (_a2 = this.electron.BrowserWindow) == null ? void 0 : _a2.getAllWindows()) == null ? void 0 : _b.forEach((wnd) => {
- var _a3;
- if (((_a3 = wnd.webContents) == null ? void 0 : _a3.isDestroyed()) === false) {
- wnd.webContents.send(channel, message);
- }
- });
- }
- showErrorBox(title, message) {
- var _a2;
- (_a2 = this.electron.dialog) == null ? void 0 : _a2.showErrorBox(title, message);
- }
- };
- var ElectronExternalApi_1 = ElectronExternalApi$1;
- var electronLogPreload = { exports: {} };
- (function(module2) {
- let electron2 = {};
- try {
- electron2 = require("electron");
- } catch (e) {
- }
- if (electron2.ipcRenderer) {
- initialize2(electron2);
- }
- {
- module2.exports = initialize2;
- }
- function initialize2({ contextBridge, ipcRenderer }) {
- if (!ipcRenderer) {
- return;
- }
- ipcRenderer.on("__ELECTRON_LOG_IPC__", (_, message) => {
- window.postMessage({ cmd: "message", ...message });
- });
- ipcRenderer.invoke("__ELECTRON_LOG__", { cmd: "getOptions" }).catch((e) => console.error(new Error(
- `electron-log isn't initialized in the main process. Please call log.initialize() before. ${e.message}`
- )));
- const electronLog = {
- sendToMain(message) {
- try {
- ipcRenderer.send("__ELECTRON_LOG__", message);
- } catch (e) {
- console.error("electronLog.sendToMain ", e, "data:", message);
- ipcRenderer.send("__ELECTRON_LOG__", {
- cmd: "errorHandler",
- error: { message: e == null ? void 0 : e.message, stack: e == null ? void 0 : e.stack },
- errorName: "sendToMain"
- });
- }
- },
- log(...data) {
- electronLog.sendToMain({ data, level: "info" });
- }
- };
- for (const level of ["error", "warn", "info", "verbose", "debug", "silly"]) {
- electronLog[level] = (...data) => electronLog.sendToMain({
- data,
- level
- });
- }
- if (contextBridge && process.contextIsolated) {
- try {
- contextBridge.exposeInMainWorld("__electronLog", electronLog);
- } catch {
- }
- }
- if (typeof window === "object") {
- window.__electronLog = electronLog;
- } else {
- __electronLog = electronLog;
- }
- }
- })(electronLogPreload);
- var electronLogPreloadExports = electronLogPreload.exports;
- const fs$3 = fs$5;
- const os$2 = require$$1;
- const path$2 = require$$2;
- const preloadInitializeFn = electronLogPreloadExports;
- var initialize$1 = {
- initialize({
- externalApi: externalApi2,
- getSessions,
- includeFutureSession,
- logger,
- preload: preload2 = true,
- spyRendererConsole = false
- }) {
- externalApi2.onAppReady(() => {
- try {
- if (preload2) {
- initializePreload({
- externalApi: externalApi2,
- getSessions,
- includeFutureSession,
- preloadOption: preload2
- });
- }
- if (spyRendererConsole) {
- initializeSpyRendererConsole({ externalApi: externalApi2, logger });
- }
- } catch (err) {
- logger.warn(err);
- }
- });
- }
- };
- function initializePreload({
- externalApi: externalApi2,
- getSessions,
- includeFutureSession,
- preloadOption
- }) {
- let preloadPath = typeof preloadOption === "string" ? preloadOption : void 0;
- try {
- preloadPath = path$2.resolve(
- __dirname,
- "../renderer/electron-log-preload.js"
- );
- } catch {
- }
- if (!preloadPath || !fs$3.existsSync(preloadPath)) {
- preloadPath = path$2.join(
- externalApi2.getAppUserDataPath() || os$2.tmpdir(),
- "electron-log-preload.js"
- );
- const preloadCode = `
- try {
- (${preloadInitializeFn.toString()})(require('electron'));
- } catch(e) {
- console.error(e);
- }
- `;
- fs$3.writeFileSync(preloadPath, preloadCode, "utf8");
- }
- externalApi2.setPreloadFileForSessions({
- filePath: preloadPath,
- includeFutureSession,
- getSessions
- });
- }
- function initializeSpyRendererConsole({ externalApi: externalApi2, logger }) {
- const levels = ["verbose", "info", "warning", "error"];
- externalApi2.onEveryWebContentsEvent(
- "console-message",
- (event, level, message) => {
- logger.processMessage({
- data: [message],
- level: levels[level],
- variables: { processType: "renderer" }
- });
- }
- );
- }
- var scope = scopeFactory$1;
- function scopeFactory$1(logger) {
- return Object.defineProperties(scope2, {
- defaultLabel: { value: "", writable: true },
- labelPadding: { value: true, writable: true },
- maxLabelLength: { value: 0, writable: true },
- labelLength: {
- get() {
- switch (typeof scope2.labelPadding) {
- case "boolean":
- return scope2.labelPadding ? scope2.maxLabelLength : 0;
- case "number":
- return scope2.labelPadding;
- default:
- return 0;
- }
- }
- }
- });
- function scope2(label) {
- scope2.maxLabelLength = Math.max(scope2.maxLabelLength, label.length);
- const newScope = {};
- for (const level of [...logger.levels, "log"]) {
- newScope[level] = (...d) => logger.logData(d, { level, scope: label });
- }
- return newScope;
- }
- }
- const scopeFactory = scope;
- let Logger$1 = (_a = class {
- constructor({
- allowUnknownLevel = false,
- dependencies = {},
- errorHandler,
- eventLogger,
- initializeFn,
- isDev = false,
- levels = ["error", "warn", "info", "verbose", "debug", "silly"],
- logId,
- transportFactories = {},
- variables
- } = {}) {
- __publicField(this, "dependencies", {});
- __publicField(this, "errorHandler", null);
- __publicField(this, "eventLogger", null);
- __publicField(this, "functions", {});
- __publicField(this, "hooks", []);
- __publicField(this, "isDev", false);
- __publicField(this, "levels", null);
- __publicField(this, "logId", null);
- __publicField(this, "scope", null);
- __publicField(this, "transports", {});
- __publicField(this, "variables", {});
- this.addLevel = this.addLevel.bind(this);
- this.create = this.create.bind(this);
- this.initialize = this.initialize.bind(this);
- this.logData = this.logData.bind(this);
- this.processMessage = this.processMessage.bind(this);
- this.allowUnknownLevel = allowUnknownLevel;
- this.dependencies = dependencies;
- this.initializeFn = initializeFn;
- this.isDev = isDev;
- this.levels = levels;
- this.logId = logId;
- this.transportFactories = transportFactories;
- this.variables = variables || {};
- this.scope = scopeFactory(this);
- for (const name of this.levels) {
- this.addLevel(name, false);
- }
- this.log = this.info;
- this.functions.log = this.log;
- this.errorHandler = errorHandler;
- errorHandler == null ? void 0 : errorHandler.setOptions({ ...dependencies, logFn: this.error });
- this.eventLogger = eventLogger;
- eventLogger == null ? void 0 : eventLogger.setOptions({ ...dependencies, logger: this });
- for (const [name, factory] of Object.entries(transportFactories)) {
- this.transports[name] = factory(this, dependencies);
- }
- _a.instances[logId] = this;
- }
- static getInstance({ logId }) {
- return this.instances[logId] || this.instances.default;
- }
- addLevel(level, index = this.levels.length) {
- if (index !== false) {
- this.levels.splice(index, 0, level);
- }
- this[level] = (...args) => this.logData(args, { level });
- this.functions[level] = this[level];
- }
- catchErrors(options) {
- this.processMessage(
- {
- data: ["log.catchErrors is deprecated. Use log.errorHandler instead"],
- level: "warn"
- },
- { transports: ["console"] }
- );
- return this.errorHandler.startCatching(options);
- }
- create(options) {
- if (typeof options === "string") {
- options = { logId: options };
- }
- return new _a({
- dependencies: this.dependencies,
- errorHandler: this.errorHandler,
- initializeFn: this.initializeFn,
- isDev: this.isDev,
- transportFactories: this.transportFactories,
- variables: { ...this.variables },
- ...options
- });
- }
- compareLevels(passLevel, checkLevel, levels = this.levels) {
- const pass = levels.indexOf(passLevel);
- const check = levels.indexOf(checkLevel);
- if (check === -1 || pass === -1) {
- return true;
- }
- return check <= pass;
- }
- initialize(options = {}) {
- this.initializeFn({ logger: this, ...this.dependencies, ...options });
- }
- logData(data, options = {}) {
- this.processMessage({ data, ...options });
- }
- processMessage(message, { transports = this.transports } = {}) {
- if (message.cmd === "errorHandler") {
- this.errorHandler.handle(message.error, {
- errorName: message.errorName,
- processType: "renderer",
- showDialog: Boolean(message.showDialog)
- });
- return;
- }
- let level = message.level;
- if (!this.allowUnknownLevel) {
- level = this.levels.includes(message.level) ? message.level : "info";
- }
- const normalizedMessage = {
- date: /* @__PURE__ */ new Date(),
- logId: this.logId,
- ...message,
- level,
- variables: {
- ...this.variables,
- ...message.variables
- }
- };
- for (const [transName, transFn] of this.transportEntries(transports)) {
- if (typeof transFn !== "function" || transFn.level === false) {
- continue;
- }
- if (!this.compareLevels(transFn.level, message.level)) {
- continue;
- }
- try {
- const transformedMsg = this.hooks.reduce((msg, hook) => {
- return msg ? hook(msg, transFn, transName) : msg;
- }, normalizedMessage);
- if (transformedMsg) {
- transFn({ ...transformedMsg, data: [...transformedMsg.data] });
- }
- } catch (e) {
- this.processInternalErrorFn(e);
- }
- }
- }
- processInternalErrorFn(_e) {
- }
- transportEntries(transports = this.transports) {
- const transportArray = Array.isArray(transports) ? transports : Object.entries(transports);
- return transportArray.map((item) => {
- switch (typeof item) {
- case "string":
- return this.transports[item] ? [item, this.transports[item]] : null;
- case "function":
- return [item.name, item];
- default:
- return Array.isArray(item) ? item : null;
- }
- }).filter(Boolean);
- }
- }, __publicField(_a, "instances", {}), _a);
- var Logger_1 = Logger$1;
- let ErrorHandler$1 = class ErrorHandler {
- constructor({
- externalApi: externalApi2,
- logFn = void 0,
- onError = void 0,
- showDialog = void 0
- } = {}) {
- __publicField(this, "externalApi");
- __publicField(this, "isActive", false);
- __publicField(this, "logFn");
- __publicField(this, "onError");
- __publicField(this, "showDialog", true);
- this.createIssue = this.createIssue.bind(this);
- this.handleError = this.handleError.bind(this);
- this.handleRejection = this.handleRejection.bind(this);
- this.setOptions({ externalApi: externalApi2, logFn, onError, showDialog });
- this.startCatching = this.startCatching.bind(this);
- this.stopCatching = this.stopCatching.bind(this);
- }
- handle(error, {
- logFn = this.logFn,
- onError = this.onError,
- processType = "browser",
- showDialog = this.showDialog,
- errorName = ""
- } = {}) {
- var _a2;
- error = normalizeError(error);
- try {
- if (typeof onError === "function") {
- const versions = ((_a2 = this.externalApi) == null ? void 0 : _a2.getVersions()) || {};
- const createIssue = this.createIssue;
- const result = onError({
- createIssue,
- error,
- errorName,
- processType,
- versions
- });
- if (result === false) {
- return;
- }
- }
- errorName ? logFn(errorName, error) : logFn(error);
- if (showDialog && !errorName.includes("rejection") && this.externalApi) {
- this.externalApi.showErrorBox(
- `A JavaScript error occurred in the ${processType} process`,
- error.stack
- );
- }
- } catch {
- console.error(error);
- }
- }
- setOptions({ externalApi: externalApi2, logFn, onError, showDialog }) {
- if (typeof externalApi2 === "object") {
- this.externalApi = externalApi2;
- }
- if (typeof logFn === "function") {
- this.logFn = logFn;
- }
- if (typeof onError === "function") {
- this.onError = onError;
- }
- if (typeof showDialog === "boolean") {
- this.showDialog = showDialog;
- }
- }
- startCatching({ onError, showDialog } = {}) {
- if (this.isActive) {
- return;
- }
- this.isActive = true;
- this.setOptions({ onError, showDialog });
- process.on("uncaughtException", this.handleError);
- process.on("unhandledRejection", this.handleRejection);
- }
- stopCatching() {
- this.isActive = false;
- process.removeListener("uncaughtException", this.handleError);
- process.removeListener("unhandledRejection", this.handleRejection);
- }
- createIssue(pageUrl, queryParams) {
- var _a2;
- (_a2 = this.externalApi) == null ? void 0 : _a2.openUrl(
- `${pageUrl}?${new URLSearchParams(queryParams).toString()}`
- );
- }
- handleError(error) {
- this.handle(error, { errorName: "Unhandled" });
- }
- handleRejection(reason) {
- const error = reason instanceof Error ? reason : new Error(JSON.stringify(reason));
- this.handle(error, { errorName: "Unhandled rejection" });
- }
- };
- function normalizeError(e) {
- if (e instanceof Error) {
- return e;
- }
- if (e && typeof e === "object") {
- if (e.message) {
- return Object.assign(new Error(e.message), e);
- }
- try {
- return new Error(JSON.stringify(e));
- } catch (serErr) {
- return new Error(`Couldn't normalize error ${String(e)}: ${serErr}`);
- }
- }
- return new Error(`Can't normalize error ${String(e)}`);
- }
- var ErrorHandler_1 = ErrorHandler$1;
- let EventLogger$1 = class EventLogger {
- constructor(options = {}) {
- __publicField(this, "disposers", []);
- __publicField(this, "format", "{eventSource}#{eventName}:");
- __publicField(this, "formatters", {
- app: {
- "certificate-error": ({ args }) => {
- return this.arrayToObject(args.slice(1, 4), [
- "url",
- "error",
- "certificate"
- ]);
- },
- "child-process-gone": ({ args }) => {
- return args.length === 1 ? args[0] : args;
- },
- "render-process-gone": ({ args: [webContents, details] }) => {
- return details && typeof details === "object" ? { ...details, ...this.getWebContentsDetails(webContents) } : [];
- }
- },
- webContents: {
- "console-message": ({ args: [level, message, line, sourceId] }) => {
- if (level < 3) {
- return void 0;
- }
- return { message, source: `${sourceId}:${line}` };
- },
- "did-fail-load": ({ args }) => {
- return this.arrayToObject(args, [
- "errorCode",
- "errorDescription",
- "validatedURL",
- "isMainFrame",
- "frameProcessId",
- "frameRoutingId"
- ]);
- },
- "did-fail-provisional-load": ({ args }) => {
- return this.arrayToObject(args, [
- "errorCode",
- "errorDescription",
- "validatedURL",
- "isMainFrame",
- "frameProcessId",
- "frameRoutingId"
- ]);
- },
- "plugin-crashed": ({ args }) => {
- return this.arrayToObject(args, ["name", "version"]);
- },
- "preload-error": ({ args }) => {
- return this.arrayToObject(args, ["preloadPath", "error"]);
- }
- }
- });
- __publicField(this, "events", {
- app: {
- "certificate-error": true,
- "child-process-gone": true,
- "render-process-gone": true
- },
- webContents: {
- // 'console-message': true,
- "did-fail-load": true,
- "did-fail-provisional-load": true,
- "plugin-crashed": true,
- "preload-error": true,
- "unresponsive": true
- }
- });
- __publicField(this, "externalApi");
- __publicField(this, "level", "error");
- __publicField(this, "scope", "");
- this.setOptions(options);
- }
- setOptions({
- events,
- externalApi: externalApi2,
- level,
- logger,
- format: format2,
- formatters,
- scope: scope2
- }) {
- if (typeof events === "object") {
- this.events = events;
- }
- if (typeof externalApi2 === "object") {
- this.externalApi = externalApi2;
- }
- if (typeof level === "string") {
- this.level = level;
- }
- if (typeof logger === "object") {
- this.logger = logger;
- }
- if (typeof format2 === "string" || typeof format2 === "function") {
- this.format = format2;
- }
- if (typeof formatters === "object") {
- this.formatters = formatters;
- }
- if (typeof scope2 === "string") {
- this.scope = scope2;
- }
- }
- startLogging(options = {}) {
- this.setOptions(options);
- this.disposeListeners();
- for (const eventName of this.getEventNames(this.events.app)) {
- this.disposers.push(
- this.externalApi.onAppEvent(eventName, (...handlerArgs) => {
- this.handleEvent({ eventSource: "app", eventName, handlerArgs });
- })
- );
- }
- for (const eventName of this.getEventNames(this.events.webContents)) {
- this.disposers.push(
- this.externalApi.onEveryWebContentsEvent(
- eventName,
- (...handlerArgs) => {
- this.handleEvent(
- { eventSource: "webContents", eventName, handlerArgs }
- );
- }
- )
- );
- }
- }
- stopLogging() {
- this.disposeListeners();
- }
- arrayToObject(array, fieldNames) {
- const obj = {};
- fieldNames.forEach((fieldName, index) => {
- obj[fieldName] = array[index];
- });
- if (array.length > fieldNames.length) {
- obj.unknownArgs = array.slice(fieldNames.length);
- }
- return obj;
- }
- disposeListeners() {
- this.disposers.forEach((disposer) => disposer());
- this.disposers = [];
- }
- formatEventLog({ eventName, eventSource, handlerArgs }) {
- var _a2;
- const [event, ...args] = handlerArgs;
- if (typeof this.format === "function") {
- return this.format({ args, event, eventName, eventSource });
- }
- const formatter = (_a2 = this.formatters[eventSource]) == null ? void 0 : _a2[eventName];
- let formattedArgs = args;
- if (typeof formatter === "function") {
- formattedArgs = formatter({ args, event, eventName, eventSource });
- }
- if (!formattedArgs) {
- return void 0;
- }
- const eventData = {};
- if (Array.isArray(formattedArgs)) {
- eventData.args = formattedArgs;
- } else if (typeof formattedArgs === "object") {
- Object.assign(eventData, formattedArgs);
- }
- if (eventSource === "webContents") {
- Object.assign(eventData, this.getWebContentsDetails(event == null ? void 0 : event.sender));
- }
- const title = this.format.replace("{eventSource}", eventSource === "app" ? "App" : "WebContents").replace("{eventName}", eventName);
- return [title, eventData];
- }
- getEventNames(eventMap) {
- if (!eventMap || typeof eventMap !== "object") {
- return [];
- }
- return Object.entries(eventMap).filter(([_, listen]) => listen).map(([eventName]) => eventName);
- }
- getWebContentsDetails(webContents) {
- if (!(webContents == null ? void 0 : webContents.loadURL)) {
- return {};
- }
- try {
- return {
- webContents: {
- id: webContents.id,
- url: webContents.getURL()
- }
- };
- } catch {
- return {};
- }
- }
- handleEvent({ eventName, eventSource, handlerArgs }) {
- var _a2;
- const log2 = this.formatEventLog({ eventName, eventSource, handlerArgs });
- if (log2) {
- const logFns = this.scope ? this.logger.scope(this.scope) : this.logger;
- (_a2 = logFns == null ? void 0 : logFns[this.level]) == null ? void 0 : _a2.call(logFns, ...log2);
- }
- }
- };
- var EventLogger_1 = EventLogger$1;
- var transform_1 = { transform: transform$5 };
- function transform$5({
- logger,
- message,
- transport,
- initialData = (message == null ? void 0 : message.data) || [],
- transforms = transport == null ? void 0 : transport.transforms
- }) {
- return transforms.reduce((data, trans) => {
- if (typeof trans === "function") {
- return trans({ data, logger, message, transport });
- }
- return data;
- }, initialData);
- }
- const { transform: transform$4 } = transform_1;
- var format$2 = {
- concatFirstStringElements: concatFirstStringElements$2,
- formatScope,
- formatText,
- formatVariables,
- timeZoneFromOffset,
- format({ message, logger, transport, data = message == null ? void 0 : message.data }) {
- switch (typeof transport.format) {
- case "string": {
- return transform$4({
- message,
- logger,
- transforms: [formatVariables, formatScope, formatText],
- transport,
- initialData: [transport.format, ...data]
- });
- }
- case "function": {
- return transport.format({
- data,
- level: (message == null ? void 0 : message.level) || "info",
- logger,
- message,
- transport
- });
- }
- default: {
- return data;
- }
- }
- }
- };
- function concatFirstStringElements$2({ data }) {
- if (typeof data[0] !== "string" || typeof data[1] !== "string") {
- return data;
- }
- if (data[0].match(/%[1cdfiOos]/)) {
- return data;
- }
- return [`${data[0]} ${data[1]}`, ...data.slice(2)];
- }
- function timeZoneFromOffset(minutesOffset) {
- const minutesPositive = Math.abs(minutesOffset);
- const sign = minutesOffset > 0 ? "-" : "+";
- const hours = Math.floor(minutesPositive / 60).toString().padStart(2, "0");
- const minutes = (minutesPositive % 60).toString().padStart(2, "0");
- return `${sign}${hours}:${minutes}`;
- }
- function formatScope({ data, logger, message }) {
- const { defaultLabel, labelLength } = (logger == null ? void 0 : logger.scope) || {};
- const template = data[0];
- let label = message.scope;
- if (!label) {
- label = defaultLabel;
- }
- let scopeText;
- if (label === "") {
- scopeText = labelLength > 0 ? "".padEnd(labelLength + 3) : "";
- } else if (typeof label === "string") {
- scopeText = ` (${label})`.padEnd(labelLength + 3);
- } else {
- scopeText = "";
- }
- data[0] = template.replace("{scope}", scopeText);
- return data;
- }
- function formatVariables({ data, message }) {
- let template = data[0];
- if (typeof template !== "string") {
- return data;
- }
- template = template.replace("{level}]", `${message.level}]`.padEnd(6, " "));
- const date = message.date || /* @__PURE__ */ new Date();
- data[0] = template.replace(/\{(\w+)}/g, (substring, name) => {
- var _a2;
- switch (name) {
- case "level":
- return message.level || "info";
- case "logId":
- return message.logId;
- case "y":
- return date.getFullYear().toString(10);
- case "m":
- return (date.getMonth() + 1).toString(10).padStart(2, "0");
- case "d":
- return date.getDate().toString(10).padStart(2, "0");
- case "h":
- return date.getHours().toString(10).padStart(2, "0");
- case "i":
- return date.getMinutes().toString(10).padStart(2, "0");
- case "s":
- return date.getSeconds().toString(10).padStart(2, "0");
- case "ms":
- return date.getMilliseconds().toString(10).padStart(3, "0");
- case "z":
- return timeZoneFromOffset(date.getTimezoneOffset());
- case "iso":
- return date.toISOString();
- default: {
- return ((_a2 = message.variables) == null ? void 0 : _a2[name]) || substring;
- }
- }
- }).trim();
- return data;
- }
- function formatText({ data }) {
- const template = data[0];
- if (typeof template !== "string") {
- return data;
- }
- const textTplPosition = template.lastIndexOf("{text}");
- if (textTplPosition === template.length - 6) {
- data[0] = template.replace(/\s?{text}/, "");
- if (data[0] === "") {
- data.shift();
- }
- return data;
- }
- const templatePieces = template.split("{text}");
- let result = [];
- if (templatePieces[0] !== "") {
- result.push(templatePieces[0]);
- }
- result = result.concat(data.slice(1));
- if (templatePieces[1] !== "") {
- result.push(templatePieces[1]);
- }
- return result;
- }
- var object = { exports: {} };
- (function(module2) {
- const util = require$$0$1;
- module2.exports = {
- serialize,
- maxDepth({ data, transport, depth = (transport == null ? void 0 : transport.depth) ?? 6 }) {
- if (!data) {
- return data;
- }
- if (depth < 1) {
- if (Array.isArray(data)) return "[array]";
- if (typeof data === "object" && data) return "[object]";
- return data;
- }
- if (Array.isArray(data)) {
- return data.map((child) => module2.exports.maxDepth({
- data: child,
- depth: depth - 1
- }));
- }
- if (typeof data !== "object") {
- return data;
- }
- if (data && typeof data.toISOString === "function") {
- return data;
- }
- if (data === null) {
- return null;
- }
- if (data instanceof Error) {
- return data;
- }
- const newJson = {};
- for (const i in data) {
- if (!Object.prototype.hasOwnProperty.call(data, i)) continue;
- newJson[i] = module2.exports.maxDepth({
- data: data[i],
- depth: depth - 1
- });
- }
- return newJson;
- },
- toJSON({ data }) {
- return JSON.parse(JSON.stringify(data, createSerializer()));
- },
- toString({ data, transport }) {
- const inspectOptions = (transport == null ? void 0 : transport.inspectOptions) || {};
- const simplifiedData = data.map((item) => {
- if (item === void 0) {
- return void 0;
- }
- try {
- const str = JSON.stringify(item, createSerializer(), " ");
- return str === void 0 ? void 0 : JSON.parse(str);
- } catch (e) {
- return item;
- }
- });
- return util.formatWithOptions(inspectOptions, ...simplifiedData);
- }
- };
- function createSerializer(options = {}) {
- const seen = /* @__PURE__ */ new WeakSet();
- return function(key, value) {
- if (typeof value === "object" && value !== null) {
- if (seen.has(value)) {
- return void 0;
- }
- seen.add(value);
- }
- return serialize(key, value, options);
- };
- }
- function serialize(key, value, options = {}) {
- const serializeMapAndSet = (options == null ? void 0 : options.serializeMapAndSet) !== false;
- if (value instanceof Error) {
- return value.stack;
- }
- if (!value) {
- return value;
- }
- if (typeof value === "function") {
- return `[function] ${value.toString()}`;
- }
- if (value instanceof Date) {
- return value.toISOString();
- }
- if (serializeMapAndSet && value instanceof Map && Object.fromEntries) {
- return Object.fromEntries(value);
- }
- if (serializeMapAndSet && value instanceof Set && Array.from) {
- return Array.from(value);
- }
- return value;
- }
- })(object);
- var objectExports = object.exports;
- var style = {
- transformStyles,
- applyAnsiStyles({ data }) {
- return transformStyles(data, styleToAnsi, resetAnsiStyle);
- },
- removeStyles({ data }) {
- return transformStyles(data, () => "");
- }
- };
- const ANSI_COLORS = {
- unset: "\x1B[0m",
- black: "\x1B[30m",
- red: "\x1B[31m",
- green: "\x1B[32m",
- yellow: "\x1B[33m",
- blue: "\x1B[34m",
- magenta: "\x1B[35m",
- cyan: "\x1B[36m",
- white: "\x1B[37m"
- };
- function styleToAnsi(style2) {
- const color = style2.replace(/color:\s*(\w+).*/, "$1").toLowerCase();
- return ANSI_COLORS[color] || "";
- }
- function resetAnsiStyle(string) {
- return string + ANSI_COLORS.unset;
- }
- function transformStyles(data, onStyleFound, onStyleApplied) {
- const foundStyles = {};
- return data.reduce((result, item, index, array) => {
- if (foundStyles[index]) {
- return result;
- }
- if (typeof item === "string") {
- let valueIndex = index;
- let styleApplied = false;
- item = item.replace(/%[1cdfiOos]/g, (match) => {
- valueIndex += 1;
- if (match !== "%c") {
- return match;
- }
- const style2 = array[valueIndex];
- if (typeof style2 === "string") {
- foundStyles[valueIndex] = true;
- styleApplied = true;
- return onStyleFound(style2, item);
- }
- return match;
- });
- if (styleApplied && onStyleApplied) {
- item = onStyleApplied(item);
- }
- }
- result.push(item);
- return result;
- }, []);
- }
- const { concatFirstStringElements: concatFirstStringElements$1, format: format$1 } = format$2;
- const { maxDepth: maxDepth$2, toJSON: toJSON$2 } = objectExports;
- const { applyAnsiStyles, removeStyles: removeStyles$2 } = style;
- const { transform: transform$3 } = transform_1;
- const consoleMethods = {
- error: console.error,
- warn: console.warn,
- info: console.info,
- verbose: console.info,
- debug: console.debug,
- silly: console.debug,
- log: console.log
- };
- var console_1 = consoleTransportFactory;
- const separator = process.platform === "win32" ? ">" : "›";
- const DEFAULT_FORMAT = `%c{h}:{i}:{s}.{ms}{scope}%c ${separator} {text}`;
- Object.assign(consoleTransportFactory, {
- DEFAULT_FORMAT
- });
- function consoleTransportFactory(logger) {
- return Object.assign(transport, {
- format: DEFAULT_FORMAT,
- level: "silly",
- transforms: [
- addTemplateColors,
- format$1,
- formatStyles,
- concatFirstStringElements$1,
- maxDepth$2,
- toJSON$2
- ],
- useStyles: process.env.FORCE_STYLES,
- writeFn({ message }) {
- const consoleLogFn = consoleMethods[message.level] || consoleMethods.info;
- consoleLogFn(...message.data);
- }
- });
- function transport(message) {
- const data = transform$3({ logger, message, transport });
- transport.writeFn({
- message: { ...message, data }
- });
- }
- }
- function addTemplateColors({ data, message, transport }) {
- if (transport.format !== DEFAULT_FORMAT) {
- return data;
- }
- return [`color:${levelToStyle(message.level)}`, "color:unset", ...data];
- }
- function canUseStyles(useStyleValue, level) {
- if (typeof useStyleValue === "boolean") {
- return useStyleValue;
- }
- const useStderr = level === "error" || level === "warn";
- const stream = useStderr ? process.stderr : process.stdout;
- return stream && stream.isTTY;
- }
- function formatStyles(args) {
- const { message, transport } = args;
- const useStyles = canUseStyles(transport.useStyles, message.level);
- const nextTransform = useStyles ? applyAnsiStyles : removeStyles$2;
- return nextTransform(args);
- }
- function levelToStyle(level) {
- const map = { error: "red", warn: "yellow", info: "cyan", default: "unset" };
- return map[level] || map.default;
- }
- const EventEmitter$1 = require$$0$2;
- const fs$2 = fs$5;
- const os$1 = require$$1;
- let File$2 = class File extends EventEmitter$1 {
- constructor({
- path: path2,
- writeOptions = { encoding: "utf8", flag: "a", mode: 438 },
- writeAsync = false
- }) {
- super();
- __publicField(this, "asyncWriteQueue", []);
- __publicField(this, "bytesWritten", 0);
- __publicField(this, "hasActiveAsyncWriting", false);
- __publicField(this, "path", null);
- __publicField(this, "initialSize");
- __publicField(this, "writeOptions", null);
- __publicField(this, "writeAsync", false);
- this.path = path2;
- this.writeOptions = writeOptions;
- this.writeAsync = writeAsync;
- }
- get size() {
- return this.getSize();
- }
- clear() {
- try {
- fs$2.writeFileSync(this.path, "", {
- mode: this.writeOptions.mode,
- flag: "w"
- });
- this.reset();
- return true;
- } catch (e) {
- if (e.code === "ENOENT") {
- return true;
- }
- this.emit("error", e, this);
- return false;
- }
- }
- crop(bytesAfter) {
- try {
- const content = readFileSyncFromEnd(this.path, bytesAfter || 4096);
- this.clear();
- this.writeLine(`[log cropped]${os$1.EOL}${content}`);
- } catch (e) {
- this.emit(
- "error",
- new Error(`Couldn't crop file ${this.path}. ${e.message}`),
- this
- );
- }
- }
- getSize() {
- if (this.initialSize === void 0) {
- try {
- const stats = fs$2.statSync(this.path);
- this.initialSize = stats.size;
- } catch (e) {
- this.initialSize = 0;
- }
- }
- return this.initialSize + this.bytesWritten;
- }
- increaseBytesWrittenCounter(text) {
- this.bytesWritten += Buffer.byteLength(text, this.writeOptions.encoding);
- }
- isNull() {
- return false;
- }
- nextAsyncWrite() {
- const file2 = this;
- if (this.hasActiveAsyncWriting || this.asyncWriteQueue.length === 0) {
- return;
- }
- const text = this.asyncWriteQueue.join("");
- this.asyncWriteQueue = [];
- this.hasActiveAsyncWriting = true;
- fs$2.writeFile(this.path, text, this.writeOptions, (e) => {
- file2.hasActiveAsyncWriting = false;
- if (e) {
- file2.emit(
- "error",
- new Error(`Couldn't write to ${file2.path}. ${e.message}`),
- this
- );
- } else {
- file2.increaseBytesWrittenCounter(text);
- }
- file2.nextAsyncWrite();
- });
- }
- reset() {
- this.initialSize = void 0;
- this.bytesWritten = 0;
- }
- toString() {
- return this.path;
- }
- writeLine(text) {
- text += os$1.EOL;
- if (this.writeAsync) {
- this.asyncWriteQueue.push(text);
- this.nextAsyncWrite();
- return;
- }
- try {
- fs$2.writeFileSync(this.path, text, this.writeOptions);
- this.increaseBytesWrittenCounter(text);
- } catch (e) {
- this.emit(
- "error",
- new Error(`Couldn't write to ${this.path}. ${e.message}`),
- this
- );
- }
- }
- };
- var File_1 = File$2;
- function readFileSyncFromEnd(filePath, bytesCount) {
- const buffer = Buffer.alloc(bytesCount);
- const stats = fs$2.statSync(filePath);
- const readLength = Math.min(stats.size, bytesCount);
- const offset = Math.max(0, stats.size - bytesCount);
- const fd = fs$2.openSync(filePath, "r");
- const totalBytes = fs$2.readSync(fd, buffer, 0, readLength, offset);
- fs$2.closeSync(fd);
- return buffer.toString("utf8", 0, totalBytes);
- }
- const File$1 = File_1;
- let NullFile$1 = class NullFile extends File$1 {
- clear() {
- }
- crop() {
- }
- getSize() {
- return 0;
- }
- isNull() {
- return true;
- }
- writeLine() {
- }
- };
- var NullFile_1 = NullFile$1;
- const EventEmitter = require$$0$2;
- const fs$1 = fs$5;
- const path$1 = require$$2;
- const File2 = File_1;
- const NullFile2 = NullFile_1;
- let FileRegistry$1 = class FileRegistry extends EventEmitter {
- constructor() {
- super();
- __publicField(this, "store", {});
- this.emitError = this.emitError.bind(this);
- }
- /**
- * Provide a File object corresponding to the filePath
- * @param {string} filePath
- * @param {WriteOptions} [writeOptions]
- * @param {boolean} [writeAsync]
- * @return {File}
- */
- provide({ filePath, writeOptions = {}, writeAsync = false }) {
- let file2;
- try {
- filePath = path$1.resolve(filePath);
- if (this.store[filePath]) {
- return this.store[filePath];
- }
- file2 = this.createFile({ filePath, writeOptions, writeAsync });
- } catch (e) {
- file2 = new NullFile2({ path: filePath });
- this.emitError(e, file2);
- }
- file2.on("error", this.emitError);
- this.store[filePath] = file2;
- return file2;
- }
- /**
- * @param {string} filePath
- * @param {WriteOptions} writeOptions
- * @param {boolean} async
- * @return {File}
- * @private
- */
- createFile({ filePath, writeOptions, writeAsync }) {
- this.testFileWriting({ filePath, writeOptions });
- return new File2({ path: filePath, writeOptions, writeAsync });
- }
- /**
- * @param {Error} error
- * @param {File} file
- * @private
- */
- emitError(error, file2) {
- this.emit("error", error, file2);
- }
- /**
- * @param {string} filePath
- * @param {WriteOptions} writeOptions
- * @private
- */
- testFileWriting({ filePath, writeOptions }) {
- fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
- fs$1.writeFileSync(filePath, "", { flag: "a", mode: writeOptions.mode });
- }
- };
- var FileRegistry_1 = FileRegistry$1;
- const fs = fs$5;
- const os = require$$1;
- const path = require$$2;
- const FileRegistry2 = FileRegistry_1;
- const { transform: transform$2 } = transform_1;
- const { removeStyles: removeStyles$1 } = style;
- const {
- format,
- concatFirstStringElements
- } = format$2;
- const { toString } = objectExports;
- var file = fileTransportFactory;
- const globalRegistry = new FileRegistry2();
- function fileTransportFactory(logger, { registry = globalRegistry, externalApi: externalApi2 } = {}) {
- let pathVariables;
- if (registry.listenerCount("error") < 1) {
- registry.on("error", (e, file2) => {
- logConsole(`Can't write to ${file2}`, e);
- });
- }
- return Object.assign(transport, {
- fileName: getDefaultFileName(logger.variables.processType),
- format: "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}",
- getFile,
- inspectOptions: { depth: 5 },
- level: "silly",
- maxSize: 1024 ** 2,
- readAllLogs,
- sync: true,
- transforms: [removeStyles$1, format, concatFirstStringElements, toString],
- writeOptions: { flag: "a", mode: 438, encoding: "utf8" },
- archiveLogFn(file2) {
- const oldPath = file2.toString();
- const inf = path.parse(oldPath);
- try {
- fs.renameSync(oldPath, path.join(inf.dir, `${inf.name}.old${inf.ext}`));
- } catch (e) {
- logConsole("Could not rotate log", e);
- const quarterOfMaxSize = Math.round(transport.maxSize / 4);
- file2.crop(Math.min(quarterOfMaxSize, 256 * 1024));
- }
- },
- resolvePathFn(vars) {
- return path.join(vars.libraryDefaultDir, vars.fileName);
- },
- setAppName(name) {
- logger.dependencies.externalApi.setAppName(name);
- }
- });
- function transport(message) {
- const file2 = getFile(message);
- const needLogRotation = transport.maxSize > 0 && file2.size > transport.maxSize;
- if (needLogRotation) {
- transport.archiveLogFn(file2);
- file2.reset();
- }
- const content = transform$2({ logger, message, transport });
- file2.writeLine(content);
- }
- function initializeOnFirstAccess() {
- if (pathVariables) {
- return;
- }
- pathVariables = Object.create(
- Object.prototype,
- {
- ...Object.getOwnPropertyDescriptors(
- externalApi2.getPathVariables()
- ),
- fileName: {
- get() {
- return transport.fileName;
- },
- enumerable: true
- }
- }
- );
- if (typeof transport.archiveLog === "function") {
- transport.archiveLogFn = transport.archiveLog;
- logConsole("archiveLog is deprecated. Use archiveLogFn instead");
- }
- if (typeof transport.resolvePath === "function") {
- transport.resolvePathFn = transport.resolvePath;
- logConsole("resolvePath is deprecated. Use resolvePathFn instead");
- }
- }
- function logConsole(message, error = null, level = "error") {
- const data = [`electron-log.transports.file: ${message}`];
- if (error) {
- data.push(error);
- }
- logger.transports.console({ data, date: /* @__PURE__ */ new Date(), level });
- }
- function getFile(msg) {
- initializeOnFirstAccess();
- const filePath = transport.resolvePathFn(pathVariables, msg);
- return registry.provide({
- filePath,
- writeAsync: !transport.sync,
- writeOptions: transport.writeOptions
- });
- }
- function readAllLogs({ fileFilter = (f) => f.endsWith(".log") } = {}) {
- initializeOnFirstAccess();
- const logsPath = path.dirname(transport.resolvePathFn(pathVariables));
- if (!fs.existsSync(logsPath)) {
- return [];
- }
- return fs.readdirSync(logsPath).map((fileName) => path.join(logsPath, fileName)).filter(fileFilter).map((logPath) => {
- try {
- return {
- path: logPath,
- lines: fs.readFileSync(logPath, "utf8").split(os.EOL)
- };
- } catch {
- return null;
- }
- }).filter(Boolean);
- }
- }
- function getDefaultFileName(processType = process.type) {
- switch (processType) {
- case "renderer":
- return "renderer.log";
- case "worker":
- return "worker.log";
- default:
- return "main.log";
- }
- }
- const { maxDepth: maxDepth$1, toJSON: toJSON$1 } = objectExports;
- const { transform: transform$1 } = transform_1;
- var ipc = ipcTransportFactory;
- function ipcTransportFactory(logger, { externalApi: externalApi2 }) {
- Object.assign(transport, {
- depth: 3,
- eventId: "__ELECTRON_LOG_IPC__",
- level: logger.isDev ? "silly" : false,
- transforms: [toJSON$1, maxDepth$1]
- });
- return (externalApi2 == null ? void 0 : externalApi2.isElectron()) ? transport : void 0;
- function transport(message) {
- var _a2;
- if (((_a2 = message == null ? void 0 : message.variables) == null ? void 0 : _a2.processType) === "renderer") {
- return;
- }
- externalApi2 == null ? void 0 : externalApi2.sendIpc(transport.eventId, {
- ...message,
- data: transform$1({ logger, message, transport })
- });
- }
- }
- const http = require$$0$3;
- const https = require$$1$1;
- const { transform } = transform_1;
- const { removeStyles } = style;
- const { toJSON, maxDepth } = objectExports;
- var remote = remoteTransportFactory;
- function remoteTransportFactory(logger) {
- return Object.assign(transport, {
- client: { name: "electron-application" },
- depth: 6,
- level: false,
- requestOptions: {},
- transforms: [removeStyles, toJSON, maxDepth],
- makeBodyFn({ message }) {
- return JSON.stringify({
- client: transport.client,
- data: message.data,
- date: message.date.getTime(),
- level: message.level,
- scope: message.scope,
- variables: message.variables
- });
- },
- processErrorFn({ error }) {
- logger.processMessage(
- {
- data: [`electron-log: can't POST ${transport.url}`, error],
- level: "warn"
- },
- { transports: ["console", "file"] }
- );
- },
- sendRequestFn({ serverUrl, requestOptions, body }) {
- const httpTransport = serverUrl.startsWith("https:") ? https : http;
- const request = httpTransport.request(serverUrl, {
- method: "POST",
- ...requestOptions,
- headers: {
- "Content-Type": "application/json",
- "Content-Length": body.length,
- ...requestOptions.headers
- }
- });
- request.write(body);
- request.end();
- return request;
- }
- });
- function transport(message) {
- if (!transport.url) {
- return;
- }
- const body = transport.makeBodyFn({
- logger,
- message: { ...message, data: transform({ logger, message, transport }) },
- transport
- });
- const request = transport.sendRequestFn({
- serverUrl: transport.url,
- requestOptions: transport.requestOptions,
- body: Buffer.from(body, "utf8")
- });
- request.on("error", (error) => transport.processErrorFn({
- error,
- logger,
- message,
- request,
- transport
- }));
- }
- }
- const Logger = Logger_1;
- const ErrorHandler2 = ErrorHandler_1;
- const EventLogger2 = EventLogger_1;
- const transportConsole = console_1;
- const transportFile = file;
- const transportIpc = ipc;
- const transportRemote = remote;
- var createDefaultLogger_1 = createDefaultLogger$1;
- function createDefaultLogger$1({ dependencies, initializeFn }) {
- var _a2;
- const defaultLogger2 = new Logger({
- dependencies,
- errorHandler: new ErrorHandler2(),
- eventLogger: new EventLogger2(),
- initializeFn,
- isDev: (_a2 = dependencies.externalApi) == null ? void 0 : _a2.isDev(),
- logId: "default",
- transportFactories: {
- console: transportConsole,
- file: transportFile,
- ipc: transportIpc,
- remote: transportRemote
- },
- variables: {
- processType: "main"
- }
- });
- defaultLogger2.default = defaultLogger2;
- defaultLogger2.Logger = Logger;
- defaultLogger2.processInternalErrorFn = (e) => {
- defaultLogger2.transports.console.writeFn({
- message: {
- data: ["Unhandled electron-log error", e],
- level: "error"
- }
- });
- };
- return defaultLogger2;
- }
- const electron = require$$0$4;
- const ElectronExternalApi2 = ElectronExternalApi_1;
- const { initialize } = initialize$1;
- const createDefaultLogger = createDefaultLogger_1;
- const externalApi = new ElectronExternalApi2({ electron });
- const defaultLogger = createDefaultLogger({
- dependencies: { externalApi },
- initializeFn: initialize
- });
- var main$1 = defaultLogger;
- externalApi.onIpc("__ELECTRON_LOG__", (_, message) => {
- if (message.scope) {
- defaultLogger.Logger.getInstance(message).scope(message.scope);
- }
- const date = new Date(message.date);
- processMessage({
- ...message,
- date: date.getTime() ? date : /* @__PURE__ */ new Date()
- });
- });
- externalApi.onIpcInvoke("__ELECTRON_LOG__", (_, { cmd = "", logId }) => {
- switch (cmd) {
- case "getOptions": {
- const logger = defaultLogger.Logger.getInstance({ logId });
- return {
- levels: logger.levels,
- logId
- };
- }
- default: {
- processMessage({ data: [`Unknown cmd '${cmd}'`], level: "error" });
- return {};
- }
- }
- });
- function processMessage(message) {
- var _a2;
- (_a2 = defaultLogger.Logger.getInstance(message)) == null ? void 0 : _a2.processMessage(message);
- }
- const main = main$1;
- var main_1 = main;
- const log = /* @__PURE__ */ getDefaultExportFromCjs(main_1);
- const url = process.env.VITE_DEV_SERVER_URL;
- process.env.NODE_ENV === "development";
- const DIST_ELECTRON = path$6.join(__dirname, "../");
- const DIST = path$6.join(DIST_ELECTRON, "../dist-electron");
- const preload = path$6.join(__dirname, "../preload/index.js");
- const PUBLIC = url ? path$6.join(DIST_ELECTRON, "../public") : process.env.DIST;
- const ICON = url ? path$6.join(PUBLIC, "./logo.ico") : path$6.join(DIST, "./logo.ico");
- path$6.join(DIST, "./app.json");
- process.env.NODE_ENV;
- const indexHtml = path$6.join(DIST, "./index.html");
- let mainWindow;
- const extra = {
- activeClose: false
- };
- const createWindow = () => {
- const { width, height } = require$$0$4.screen.getPrimaryDisplay().workAreaSize;
- const winWidth = 420;
- const winHeight = 700;
- const x = width - winWidth;
- const y = 10;
- mainWindow = new require$$0$4.BrowserWindow({
- title: "菁苗健康",
- icon: ICON,
- x,
- y,
- width: winWidth,
- height: winHeight,
- frame: true,
- show: false,
- // transparent: true,
- backgroundColor: "#fff",
- webPreferences: {
- preload,
- webviewTag: true
- // 启用webview标签
- // webSecurity: false,
- }
- });
- mainWindow.setMenu(null);
- if (url) {
- mainWindow.loadURL(url);
- } else {
- mainWindow.loadFile(indexHtml);
- }
- mainWindow.once("ready-to-show", () => {
- log.info("启动参数process.argv==> hidden表示开机重启成功", process.argv);
- if (process.argv.indexOf("--hidden") < 0) {
- showMainWin();
- }
- });
- mainWindow.on("close", (e) => {
- if (!extra.activeClose) {
- e.preventDefault();
- hideMainWin();
- } else {
- extra.activeClose = true;
- }
- });
- return mainWindow;
- };
- function showMainWin() {
- if (!mainWindow || (mainWindow == null ? void 0 : mainWindow.isDestroyed())) {
- mainWindow = createWindow();
- }
- mainWindow.show();
- }
- function hideMainWin() {
- mainWindow.hide();
- }
- function minimizeMainWin() {
- mainWindow.minimize();
- }
- function maximizeMainWin() {
- mainWindow.maximize();
- }
- function unmaximizeMainWin() {
- mainWindow.unmaximize();
- }
- function isMaximized() {
- return mainWindow.isMaximized();
- }
- const initIpcMain = () => {
- const handle = (name, callback) => {
- require$$0$4.ipcMain.handle(name, (e, ...par) => callback(e, ...par));
- };
- handle("close", () => hideMainWin());
- handle("min", () => minimizeMainWin());
- handle("max", () => {
- let obj = { type: "max", data: "unmax" };
- if (isMaximized()) {
- unmaximizeMainWin();
- } else {
- obj.data = "max";
- maximizeMainWin();
- }
- return obj;
- });
- };
- const Store = require("electron-store");
- const schema = {
- isFocusOpenWin: {
- type: "number",
- default: 1
- }
- };
- const store = new Store({ schema });
- const handeSet = (key, value) => {
- store.set(key, value);
- };
- const handeGet = (key) => {
- const data = store.get(key);
- return data;
- };
- const initTray = () => {
- let appIcon = new require$$0$4.Tray(ICON);
- const isFocusOpenWin = handeGet("isFocusOpenWin");
- let contextMenu = require$$0$4.Menu.buildFromTemplate([
- {
- id: "open-win",
- label: `${isFocusOpenWin == 1 ? "关闭" : "开启"}主动弹窗`,
- click: () => {
- updateItem();
- }
- },
- {
- label: "打开弹窗",
- click: () => {
- showMainWin();
- }
- },
- {
- label: "退出弹窗",
- click: () => {
- extra.activeClose = true;
- setTimeout(() => {
- require$$0$4.app.quit();
- });
- }
- }
- ]);
- appIcon.setToolTip("菁苗健康");
- appIcon.setContextMenu(contextMenu);
- appIcon.addListener("click", function() {
- showMainWin();
- });
- const updateItem = async () => {
- let isFocusOpenWin2 = handeGet("isFocusOpenWin");
- const openMenuItem = contextMenu.getMenuItemById("open-win");
- if (isFocusOpenWin2 == 1) {
- isFocusOpenWin2 = 2;
- openMenuItem.label = `开启主动弹窗`;
- } else {
- isFocusOpenWin2 = 1;
- openMenuItem.label = `关闭主动弹窗`;
- }
- contextMenu = require$$0$4.Menu.buildFromTemplate(contextMenu.items);
- appIcon.setContextMenu(contextMenu);
- handeSet("isFocusOpenWin", isFocusOpenWin2);
- log.info("isFocusOpenWin==>", isFocusOpenWin2);
- };
- return appIcon;
- };
- const initExpress = () => {
- const app = express();
- app.use(express.json());
- app.use(express.urlencoded({ extended: false }));
- app.use(cors());
- app.get("/iframe", async (req, res) => {
- const { path: path2, Path } = req.query;
- console.log("🚀 ~ app.get ~ req.query:", req.query);
- const url2 = path2 || Path;
- if (!url2) {
- res.send({
- code: 10001,
- msg: "缺少path参数" + /* @__PURE__ */ new Date()
- });
- log.error("缺少path参数" + /* @__PURE__ */ new Date());
- return;
- }
- mainWindow.webContents.loadURL(decodeURIComponent(url2));
- const isFocusOpenWin = handeGet("isFocusOpenWin");
- if (isFocusOpenWin == 1) {
- mainWindow.show();
- mainWindow.setAlwaysOnTop(true);
- }
- res.send({
- code: 200,
- msg: "成功" + /* @__PURE__ */ new Date()
- });
- });
- app.get("/iframe/:path", async (req, res) => {
- const { path: path2 } = req.params;
- if (!path2) {
- res.send({
- code: 10001,
- msg: "缺少path参数" + /* @__PURE__ */ new Date()
- });
- log.error("缺少path参数" + /* @__PURE__ */ new Date());
- return;
- }
- mainWindow.webContents.loadURL(decodeURIComponent(path2));
- const isFocusOpenWin = handeGet("isFocusOpenWin");
- if (isFocusOpenWin == 1) {
- mainWindow.show();
- mainWindow.setAlwaysOnTop(true);
- }
- res.send({
- code: 200,
- msg: "成功" + /* @__PURE__ */ new Date()
- });
- });
- app.post("/iframe", async (req, res) => {
- const body = req.body;
- console.log("🚀 ~ app.get ~ req.body:", body);
- const { path: path2 } = req.body;
- if (!path2) {
- res.send({
- code: 10001,
- msg: "缺少path参数" + /* @__PURE__ */ new Date()
- });
- log.error("缺少path参数" + /* @__PURE__ */ new Date());
- return;
- }
- mainWindow.webContents.loadURL(decodeURIComponent(path2));
- const isFocusOpenWin = handeGet("isFocusOpenWin");
- if (isFocusOpenWin == 1) {
- mainWindow.show();
- mainWindow.setAlwaysOnTop(true);
- }
- res.send({
- code: 200,
- msg: "成功" + /* @__PURE__ */ new Date()
- });
- });
- app.listen(3003, () => console.log("Example app listening on port 3003!"));
- };
- process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = true;
- if (!require$$0$4.app.requestSingleInstanceLock()) {
- require$$0$4.app.quit();
- process.exit(0);
- } else {
- require$$0$4.app.on("second-instance", (event, commandLine, workingDirectory) => {
- if (mainWindow) {
- if (mainWindow.isMinimized()) mainWindow.restore();
- mainWindow.show();
- mainWindow.focus();
- }
- });
- }
- require$$0$4.app.whenReady().then(() => {
- AtLogin();
- createWindow();
- initTray();
- initExpress();
- });
- const AtLogin = async () => {
- if (require$$0$4.app.isPackaged) {
- require$$0$4.app.setLoginItemSettings({
- openAtLogin: true,
- // 设置为 true 可以隐藏启动时的窗口
- path: require$$0$4.app.getPath("exe"),
- // 可选,指定要启动的应用路径
- args: ["--openAsHidden"]
- });
- }
- };
- require$$0$4.app.on("activate", function() {
- console.log("activate=====>");
- const allWindows = require$$0$4.BrowserWindow.getAllWindows();
- if (!allWindows.length) {
- createWindow();
- }
- });
- require$$0$4.app.on("window-all-closed", function() {
- if (process.platform !== "darwin") require$$0$4.app.quit();
- });
- initIpcMain();
- //# sourceMappingURL=index.js.map
|