index.js 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231
  1. "use strict";
  2. var __defProp = Object.defineProperty;
  3. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  4. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  5. var _a;
  6. const require$$0$4 = require("electron");
  7. const path$6 = require("node:path");
  8. const fs$5 = require("fs");
  9. const require$$2 = require("path");
  10. const require$$0 = require("child_process");
  11. const require$$1 = require("os");
  12. const require$$0$1 = require("util");
  13. const require$$0$2 = require("events");
  14. const require$$0$3 = require("http");
  15. const require$$1$1 = require("https");
  16. const express = require("express");
  17. const cors = require("cors");
  18. function getDefaultExportFromCjs(x) {
  19. return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x;
  20. }
  21. const fs$4 = fs$5;
  22. const path$5 = require$$2;
  23. var packageJson$1 = {
  24. findAndReadPackageJson,
  25. tryReadJsonAt
  26. };
  27. function findAndReadPackageJson() {
  28. return tryReadJsonAt(getMainModulePath()) || tryReadJsonAt(extractPathFromArgs()) || tryReadJsonAt(process.resourcesPath, "app.asar") || tryReadJsonAt(process.resourcesPath, "app") || tryReadJsonAt(process.cwd()) || { name: void 0, version: void 0 };
  29. }
  30. function tryReadJsonAt(...searchPaths) {
  31. if (!searchPaths[0]) {
  32. return void 0;
  33. }
  34. try {
  35. const searchPath = path$5.join(...searchPaths);
  36. const fileName = findUp("package.json", searchPath);
  37. if (!fileName) {
  38. return void 0;
  39. }
  40. const json = JSON.parse(fs$4.readFileSync(fileName, "utf8"));
  41. const name = (json == null ? void 0 : json.productName) || (json == null ? void 0 : json.name);
  42. if (!name || name.toLowerCase() === "electron") {
  43. return void 0;
  44. }
  45. if (name) {
  46. return { name, version: json == null ? void 0 : json.version };
  47. }
  48. return void 0;
  49. } catch (e) {
  50. return void 0;
  51. }
  52. }
  53. function findUp(fileName, cwd) {
  54. let currentPath = cwd;
  55. while (true) {
  56. const parsedPath = path$5.parse(currentPath);
  57. const root = parsedPath.root;
  58. const dir = parsedPath.dir;
  59. if (fs$4.existsSync(path$5.join(currentPath, fileName))) {
  60. return path$5.resolve(path$5.join(currentPath, fileName));
  61. }
  62. if (currentPath === root) {
  63. return null;
  64. }
  65. currentPath = dir;
  66. }
  67. }
  68. function extractPathFromArgs() {
  69. const matchedArgs = process.argv.filter((arg) => {
  70. return arg.indexOf("--user-data-dir=") === 0;
  71. });
  72. if (matchedArgs.length === 0 || typeof matchedArgs[0] !== "string") {
  73. return null;
  74. }
  75. const userDataDir = matchedArgs[0];
  76. return userDataDir.replace("--user-data-dir=", "");
  77. }
  78. function getMainModulePath() {
  79. var _a2;
  80. try {
  81. return (_a2 = require.main) == null ? void 0 : _a2.filename;
  82. } catch {
  83. return void 0;
  84. }
  85. }
  86. const childProcess = require$$0;
  87. const os$3 = require$$1;
  88. const path$4 = require$$2;
  89. const packageJson = packageJson$1;
  90. let NodeExternalApi$1 = class NodeExternalApi {
  91. constructor() {
  92. __publicField(this, "appName");
  93. __publicField(this, "appPackageJson");
  94. __publicField(this, "platform", process.platform);
  95. }
  96. getAppLogPath(appName = this.getAppName()) {
  97. if (this.platform === "darwin") {
  98. return path$4.join(this.getSystemPathHome(), "Library/Logs", appName);
  99. }
  100. return path$4.join(this.getAppUserDataPath(appName), "logs");
  101. }
  102. getAppName() {
  103. var _a2;
  104. const appName = this.appName || ((_a2 = this.getAppPackageJson()) == null ? void 0 : _a2.name);
  105. if (!appName) {
  106. throw new Error(
  107. "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()"
  108. );
  109. }
  110. return appName;
  111. }
  112. /**
  113. * @private
  114. * @returns {undefined}
  115. */
  116. getAppPackageJson() {
  117. if (typeof this.appPackageJson !== "object") {
  118. this.appPackageJson = packageJson.findAndReadPackageJson();
  119. }
  120. return this.appPackageJson;
  121. }
  122. getAppUserDataPath(appName = this.getAppName()) {
  123. return appName ? path$4.join(this.getSystemPathAppData(), appName) : void 0;
  124. }
  125. getAppVersion() {
  126. var _a2;
  127. return (_a2 = this.getAppPackageJson()) == null ? void 0 : _a2.version;
  128. }
  129. getElectronLogPath() {
  130. return this.getAppLogPath();
  131. }
  132. getMacOsVersion() {
  133. const release = Number(os$3.release().split(".")[0]);
  134. if (release <= 19) {
  135. return `10.${release - 4}`;
  136. }
  137. return release - 9;
  138. }
  139. /**
  140. * @protected
  141. * @returns {string}
  142. */
  143. getOsVersion() {
  144. let osName = os$3.type().replace("_", " ");
  145. let osVersion = os$3.release();
  146. if (osName === "Darwin") {
  147. osName = "macOS";
  148. osVersion = this.getMacOsVersion();
  149. }
  150. return `${osName} ${osVersion}`;
  151. }
  152. /**
  153. * @return {PathVariables}
  154. */
  155. getPathVariables() {
  156. const appName = this.getAppName();
  157. const appVersion = this.getAppVersion();
  158. const self = this;
  159. return {
  160. appData: this.getSystemPathAppData(),
  161. appName,
  162. appVersion,
  163. get electronDefaultDir() {
  164. return self.getElectronLogPath();
  165. },
  166. home: this.getSystemPathHome(),
  167. libraryDefaultDir: this.getAppLogPath(appName),
  168. libraryTemplate: this.getAppLogPath("{appName}"),
  169. temp: this.getSystemPathTemp(),
  170. userData: this.getAppUserDataPath(appName)
  171. };
  172. }
  173. getSystemPathAppData() {
  174. const home = this.getSystemPathHome();
  175. switch (this.platform) {
  176. case "darwin": {
  177. return path$4.join(home, "Library/Application Support");
  178. }
  179. case "win32": {
  180. return process.env.APPDATA || path$4.join(home, "AppData/Roaming");
  181. }
  182. default: {
  183. return process.env.XDG_CONFIG_HOME || path$4.join(home, ".config");
  184. }
  185. }
  186. }
  187. getSystemPathHome() {
  188. var _a2;
  189. return ((_a2 = os$3.homedir) == null ? void 0 : _a2.call(os$3)) || process.env.HOME;
  190. }
  191. getSystemPathTemp() {
  192. return os$3.tmpdir();
  193. }
  194. getVersions() {
  195. return {
  196. app: `${this.getAppName()} ${this.getAppVersion()}`,
  197. electron: void 0,
  198. os: this.getOsVersion()
  199. };
  200. }
  201. isDev() {
  202. return process.env.NODE_ENV === "development" || process.env.ELECTRON_IS_DEV === "1";
  203. }
  204. isElectron() {
  205. return Boolean(process.versions.electron);
  206. }
  207. onAppEvent(_eventName, _handler) {
  208. }
  209. onAppReady(handler) {
  210. handler();
  211. }
  212. onEveryWebContentsEvent(eventName, handler) {
  213. }
  214. /**
  215. * Listen to async messages sent from opposite process
  216. * @param {string} channel
  217. * @param {function} listener
  218. */
  219. onIpc(channel, listener) {
  220. }
  221. onIpcInvoke(channel, listener) {
  222. }
  223. /**
  224. * @param {string} url
  225. * @param {Function} [logFunction]
  226. */
  227. openUrl(url2, logFunction = console.error) {
  228. const startMap = { darwin: "open", win32: "start", linux: "xdg-open" };
  229. const start = startMap[process.platform] || "xdg-open";
  230. childProcess.exec(`${start} ${url2}`, {}, (err) => {
  231. if (err) {
  232. logFunction(err);
  233. }
  234. });
  235. }
  236. setAppName(appName) {
  237. this.appName = appName;
  238. }
  239. setPlatform(platform) {
  240. this.platform = platform;
  241. }
  242. setPreloadFileForSessions({
  243. filePath,
  244. // eslint-disable-line no-unused-vars
  245. includeFutureSession = true,
  246. // eslint-disable-line no-unused-vars
  247. getSessions = () => []
  248. // eslint-disable-line no-unused-vars
  249. }) {
  250. }
  251. /**
  252. * Sent a message to opposite process
  253. * @param {string} channel
  254. * @param {any} message
  255. */
  256. sendIpc(channel, message) {
  257. }
  258. showErrorBox(title, message) {
  259. }
  260. };
  261. var NodeExternalApi_1 = NodeExternalApi$1;
  262. const path$3 = require$$2;
  263. const NodeExternalApi2 = NodeExternalApi_1;
  264. let ElectronExternalApi$1 = class ElectronExternalApi extends NodeExternalApi2 {
  265. /**
  266. * @param {object} options
  267. * @param {typeof Electron} [options.electron]
  268. */
  269. constructor({ electron: electron2 } = {}) {
  270. super();
  271. /**
  272. * @type {typeof Electron}
  273. */
  274. __publicField(this, "electron");
  275. this.electron = electron2;
  276. }
  277. getAppName() {
  278. var _a2, _b;
  279. let appName;
  280. try {
  281. appName = this.appName || ((_a2 = this.electron.app) == null ? void 0 : _a2.name) || ((_b = this.electron.app) == null ? void 0 : _b.getName());
  282. } catch {
  283. }
  284. return appName || super.getAppName();
  285. }
  286. getAppUserDataPath(appName) {
  287. return this.getPath("userData") || super.getAppUserDataPath(appName);
  288. }
  289. getAppVersion() {
  290. var _a2;
  291. let appVersion;
  292. try {
  293. appVersion = (_a2 = this.electron.app) == null ? void 0 : _a2.getVersion();
  294. } catch {
  295. }
  296. return appVersion || super.getAppVersion();
  297. }
  298. getElectronLogPath() {
  299. return this.getPath("logs") || super.getElectronLogPath();
  300. }
  301. /**
  302. * @private
  303. * @param {any} name
  304. * @returns {string|undefined}
  305. */
  306. getPath(name) {
  307. var _a2;
  308. try {
  309. return (_a2 = this.electron.app) == null ? void 0 : _a2.getPath(name);
  310. } catch {
  311. return void 0;
  312. }
  313. }
  314. getVersions() {
  315. return {
  316. app: `${this.getAppName()} ${this.getAppVersion()}`,
  317. electron: `Electron ${process.versions.electron}`,
  318. os: this.getOsVersion()
  319. };
  320. }
  321. getSystemPathAppData() {
  322. return this.getPath("appData") || super.getSystemPathAppData();
  323. }
  324. isDev() {
  325. var _a2;
  326. if (((_a2 = this.electron.app) == null ? void 0 : _a2.isPackaged) !== void 0) {
  327. return !this.electron.app.isPackaged;
  328. }
  329. if (typeof process.execPath === "string") {
  330. const execFileName = path$3.basename(process.execPath).toLowerCase();
  331. return execFileName.startsWith("electron");
  332. }
  333. return super.isDev();
  334. }
  335. onAppEvent(eventName, handler) {
  336. var _a2;
  337. (_a2 = this.electron.app) == null ? void 0 : _a2.on(eventName, handler);
  338. return () => {
  339. var _a3;
  340. (_a3 = this.electron.app) == null ? void 0 : _a3.off(eventName, handler);
  341. };
  342. }
  343. onAppReady(handler) {
  344. var _a2, _b, _c;
  345. if ((_a2 = this.electron.app) == null ? void 0 : _a2.isReady()) {
  346. handler();
  347. } else if ((_b = this.electron.app) == null ? void 0 : _b.once) {
  348. (_c = this.electron.app) == null ? void 0 : _c.once("ready", handler);
  349. } else {
  350. handler();
  351. }
  352. }
  353. onEveryWebContentsEvent(eventName, handler) {
  354. var _a2, _b, _c;
  355. (_b = (_a2 = this.electron.webContents) == null ? void 0 : _a2.getAllWebContents()) == null ? void 0 : _b.forEach((webContents) => {
  356. webContents.on(eventName, handler);
  357. });
  358. (_c = this.electron.app) == null ? void 0 : _c.on("web-contents-created", onWebContentsCreated);
  359. return () => {
  360. var _a3, _b2;
  361. (_a3 = this.electron.webContents) == null ? void 0 : _a3.getAllWebContents().forEach((webContents) => {
  362. webContents.off(eventName, handler);
  363. });
  364. (_b2 = this.electron.app) == null ? void 0 : _b2.off("web-contents-created", onWebContentsCreated);
  365. };
  366. function onWebContentsCreated(_, webContents) {
  367. webContents.on(eventName, handler);
  368. }
  369. }
  370. /**
  371. * Listen to async messages sent from opposite process
  372. * @param {string} channel
  373. * @param {function} listener
  374. */
  375. onIpc(channel, listener) {
  376. var _a2;
  377. (_a2 = this.electron.ipcMain) == null ? void 0 : _a2.on(channel, listener);
  378. }
  379. onIpcInvoke(channel, listener) {
  380. var _a2, _b;
  381. (_b = (_a2 = this.electron.ipcMain) == null ? void 0 : _a2.handle) == null ? void 0 : _b.call(_a2, channel, listener);
  382. }
  383. /**
  384. * @param {string} url
  385. * @param {Function} [logFunction]
  386. */
  387. openUrl(url2, logFunction = console.error) {
  388. var _a2;
  389. (_a2 = this.electron.shell) == null ? void 0 : _a2.openExternal(url2).catch(logFunction);
  390. }
  391. setPreloadFileForSessions({
  392. filePath,
  393. includeFutureSession = true,
  394. getSessions = () => {
  395. var _a2;
  396. return [(_a2 = this.electron.session) == null ? void 0 : _a2.defaultSession];
  397. }
  398. }) {
  399. for (const session of getSessions().filter(Boolean)) {
  400. setPreload(session);
  401. }
  402. if (includeFutureSession) {
  403. this.onAppEvent("session-created", (session) => {
  404. setPreload(session);
  405. });
  406. }
  407. function setPreload(session) {
  408. session.setPreloads([...session.getPreloads(), filePath]);
  409. }
  410. }
  411. /**
  412. * Sent a message to opposite process
  413. * @param {string} channel
  414. * @param {any} message
  415. */
  416. sendIpc(channel, message) {
  417. var _a2, _b;
  418. (_b = (_a2 = this.electron.BrowserWindow) == null ? void 0 : _a2.getAllWindows()) == null ? void 0 : _b.forEach((wnd) => {
  419. var _a3;
  420. if (((_a3 = wnd.webContents) == null ? void 0 : _a3.isDestroyed()) === false) {
  421. wnd.webContents.send(channel, message);
  422. }
  423. });
  424. }
  425. showErrorBox(title, message) {
  426. var _a2;
  427. (_a2 = this.electron.dialog) == null ? void 0 : _a2.showErrorBox(title, message);
  428. }
  429. };
  430. var ElectronExternalApi_1 = ElectronExternalApi$1;
  431. var electronLogPreload = { exports: {} };
  432. (function(module2) {
  433. let electron2 = {};
  434. try {
  435. electron2 = require("electron");
  436. } catch (e) {
  437. }
  438. if (electron2.ipcRenderer) {
  439. initialize2(electron2);
  440. }
  441. {
  442. module2.exports = initialize2;
  443. }
  444. function initialize2({ contextBridge, ipcRenderer }) {
  445. if (!ipcRenderer) {
  446. return;
  447. }
  448. ipcRenderer.on("__ELECTRON_LOG_IPC__", (_, message) => {
  449. window.postMessage({ cmd: "message", ...message });
  450. });
  451. ipcRenderer.invoke("__ELECTRON_LOG__", { cmd: "getOptions" }).catch((e) => console.error(new Error(
  452. `electron-log isn't initialized in the main process. Please call log.initialize() before. ${e.message}`
  453. )));
  454. const electronLog = {
  455. sendToMain(message) {
  456. try {
  457. ipcRenderer.send("__ELECTRON_LOG__", message);
  458. } catch (e) {
  459. console.error("electronLog.sendToMain ", e, "data:", message);
  460. ipcRenderer.send("__ELECTRON_LOG__", {
  461. cmd: "errorHandler",
  462. error: { message: e == null ? void 0 : e.message, stack: e == null ? void 0 : e.stack },
  463. errorName: "sendToMain"
  464. });
  465. }
  466. },
  467. log(...data) {
  468. electronLog.sendToMain({ data, level: "info" });
  469. }
  470. };
  471. for (const level of ["error", "warn", "info", "verbose", "debug", "silly"]) {
  472. electronLog[level] = (...data) => electronLog.sendToMain({
  473. data,
  474. level
  475. });
  476. }
  477. if (contextBridge && process.contextIsolated) {
  478. try {
  479. contextBridge.exposeInMainWorld("__electronLog", electronLog);
  480. } catch {
  481. }
  482. }
  483. if (typeof window === "object") {
  484. window.__electronLog = electronLog;
  485. } else {
  486. __electronLog = electronLog;
  487. }
  488. }
  489. })(electronLogPreload);
  490. var electronLogPreloadExports = electronLogPreload.exports;
  491. const fs$3 = fs$5;
  492. const os$2 = require$$1;
  493. const path$2 = require$$2;
  494. const preloadInitializeFn = electronLogPreloadExports;
  495. var initialize$1 = {
  496. initialize({
  497. externalApi: externalApi2,
  498. getSessions,
  499. includeFutureSession,
  500. logger,
  501. preload: preload2 = true,
  502. spyRendererConsole = false
  503. }) {
  504. externalApi2.onAppReady(() => {
  505. try {
  506. if (preload2) {
  507. initializePreload({
  508. externalApi: externalApi2,
  509. getSessions,
  510. includeFutureSession,
  511. preloadOption: preload2
  512. });
  513. }
  514. if (spyRendererConsole) {
  515. initializeSpyRendererConsole({ externalApi: externalApi2, logger });
  516. }
  517. } catch (err) {
  518. logger.warn(err);
  519. }
  520. });
  521. }
  522. };
  523. function initializePreload({
  524. externalApi: externalApi2,
  525. getSessions,
  526. includeFutureSession,
  527. preloadOption
  528. }) {
  529. let preloadPath = typeof preloadOption === "string" ? preloadOption : void 0;
  530. try {
  531. preloadPath = path$2.resolve(
  532. __dirname,
  533. "../renderer/electron-log-preload.js"
  534. );
  535. } catch {
  536. }
  537. if (!preloadPath || !fs$3.existsSync(preloadPath)) {
  538. preloadPath = path$2.join(
  539. externalApi2.getAppUserDataPath() || os$2.tmpdir(),
  540. "electron-log-preload.js"
  541. );
  542. const preloadCode = `
  543. try {
  544. (${preloadInitializeFn.toString()})(require('electron'));
  545. } catch(e) {
  546. console.error(e);
  547. }
  548. `;
  549. fs$3.writeFileSync(preloadPath, preloadCode, "utf8");
  550. }
  551. externalApi2.setPreloadFileForSessions({
  552. filePath: preloadPath,
  553. includeFutureSession,
  554. getSessions
  555. });
  556. }
  557. function initializeSpyRendererConsole({ externalApi: externalApi2, logger }) {
  558. const levels = ["verbose", "info", "warning", "error"];
  559. externalApi2.onEveryWebContentsEvent(
  560. "console-message",
  561. (event, level, message) => {
  562. logger.processMessage({
  563. data: [message],
  564. level: levels[level],
  565. variables: { processType: "renderer" }
  566. });
  567. }
  568. );
  569. }
  570. var scope = scopeFactory$1;
  571. function scopeFactory$1(logger) {
  572. return Object.defineProperties(scope2, {
  573. defaultLabel: { value: "", writable: true },
  574. labelPadding: { value: true, writable: true },
  575. maxLabelLength: { value: 0, writable: true },
  576. labelLength: {
  577. get() {
  578. switch (typeof scope2.labelPadding) {
  579. case "boolean":
  580. return scope2.labelPadding ? scope2.maxLabelLength : 0;
  581. case "number":
  582. return scope2.labelPadding;
  583. default:
  584. return 0;
  585. }
  586. }
  587. }
  588. });
  589. function scope2(label) {
  590. scope2.maxLabelLength = Math.max(scope2.maxLabelLength, label.length);
  591. const newScope = {};
  592. for (const level of [...logger.levels, "log"]) {
  593. newScope[level] = (...d) => logger.logData(d, { level, scope: label });
  594. }
  595. return newScope;
  596. }
  597. }
  598. const scopeFactory = scope;
  599. let Logger$1 = (_a = class {
  600. constructor({
  601. allowUnknownLevel = false,
  602. dependencies = {},
  603. errorHandler,
  604. eventLogger,
  605. initializeFn,
  606. isDev = false,
  607. levels = ["error", "warn", "info", "verbose", "debug", "silly"],
  608. logId,
  609. transportFactories = {},
  610. variables
  611. } = {}) {
  612. __publicField(this, "dependencies", {});
  613. __publicField(this, "errorHandler", null);
  614. __publicField(this, "eventLogger", null);
  615. __publicField(this, "functions", {});
  616. __publicField(this, "hooks", []);
  617. __publicField(this, "isDev", false);
  618. __publicField(this, "levels", null);
  619. __publicField(this, "logId", null);
  620. __publicField(this, "scope", null);
  621. __publicField(this, "transports", {});
  622. __publicField(this, "variables", {});
  623. this.addLevel = this.addLevel.bind(this);
  624. this.create = this.create.bind(this);
  625. this.initialize = this.initialize.bind(this);
  626. this.logData = this.logData.bind(this);
  627. this.processMessage = this.processMessage.bind(this);
  628. this.allowUnknownLevel = allowUnknownLevel;
  629. this.dependencies = dependencies;
  630. this.initializeFn = initializeFn;
  631. this.isDev = isDev;
  632. this.levels = levels;
  633. this.logId = logId;
  634. this.transportFactories = transportFactories;
  635. this.variables = variables || {};
  636. this.scope = scopeFactory(this);
  637. for (const name of this.levels) {
  638. this.addLevel(name, false);
  639. }
  640. this.log = this.info;
  641. this.functions.log = this.log;
  642. this.errorHandler = errorHandler;
  643. errorHandler == null ? void 0 : errorHandler.setOptions({ ...dependencies, logFn: this.error });
  644. this.eventLogger = eventLogger;
  645. eventLogger == null ? void 0 : eventLogger.setOptions({ ...dependencies, logger: this });
  646. for (const [name, factory] of Object.entries(transportFactories)) {
  647. this.transports[name] = factory(this, dependencies);
  648. }
  649. _a.instances[logId] = this;
  650. }
  651. static getInstance({ logId }) {
  652. return this.instances[logId] || this.instances.default;
  653. }
  654. addLevel(level, index = this.levels.length) {
  655. if (index !== false) {
  656. this.levels.splice(index, 0, level);
  657. }
  658. this[level] = (...args) => this.logData(args, { level });
  659. this.functions[level] = this[level];
  660. }
  661. catchErrors(options) {
  662. this.processMessage(
  663. {
  664. data: ["log.catchErrors is deprecated. Use log.errorHandler instead"],
  665. level: "warn"
  666. },
  667. { transports: ["console"] }
  668. );
  669. return this.errorHandler.startCatching(options);
  670. }
  671. create(options) {
  672. if (typeof options === "string") {
  673. options = { logId: options };
  674. }
  675. return new _a({
  676. dependencies: this.dependencies,
  677. errorHandler: this.errorHandler,
  678. initializeFn: this.initializeFn,
  679. isDev: this.isDev,
  680. transportFactories: this.transportFactories,
  681. variables: { ...this.variables },
  682. ...options
  683. });
  684. }
  685. compareLevels(passLevel, checkLevel, levels = this.levels) {
  686. const pass = levels.indexOf(passLevel);
  687. const check = levels.indexOf(checkLevel);
  688. if (check === -1 || pass === -1) {
  689. return true;
  690. }
  691. return check <= pass;
  692. }
  693. initialize(options = {}) {
  694. this.initializeFn({ logger: this, ...this.dependencies, ...options });
  695. }
  696. logData(data, options = {}) {
  697. this.processMessage({ data, ...options });
  698. }
  699. processMessage(message, { transports = this.transports } = {}) {
  700. if (message.cmd === "errorHandler") {
  701. this.errorHandler.handle(message.error, {
  702. errorName: message.errorName,
  703. processType: "renderer",
  704. showDialog: Boolean(message.showDialog)
  705. });
  706. return;
  707. }
  708. let level = message.level;
  709. if (!this.allowUnknownLevel) {
  710. level = this.levels.includes(message.level) ? message.level : "info";
  711. }
  712. const normalizedMessage = {
  713. date: /* @__PURE__ */ new Date(),
  714. logId: this.logId,
  715. ...message,
  716. level,
  717. variables: {
  718. ...this.variables,
  719. ...message.variables
  720. }
  721. };
  722. for (const [transName, transFn] of this.transportEntries(transports)) {
  723. if (typeof transFn !== "function" || transFn.level === false) {
  724. continue;
  725. }
  726. if (!this.compareLevels(transFn.level, message.level)) {
  727. continue;
  728. }
  729. try {
  730. const transformedMsg = this.hooks.reduce((msg, hook) => {
  731. return msg ? hook(msg, transFn, transName) : msg;
  732. }, normalizedMessage);
  733. if (transformedMsg) {
  734. transFn({ ...transformedMsg, data: [...transformedMsg.data] });
  735. }
  736. } catch (e) {
  737. this.processInternalErrorFn(e);
  738. }
  739. }
  740. }
  741. processInternalErrorFn(_e) {
  742. }
  743. transportEntries(transports = this.transports) {
  744. const transportArray = Array.isArray(transports) ? transports : Object.entries(transports);
  745. return transportArray.map((item) => {
  746. switch (typeof item) {
  747. case "string":
  748. return this.transports[item] ? [item, this.transports[item]] : null;
  749. case "function":
  750. return [item.name, item];
  751. default:
  752. return Array.isArray(item) ? item : null;
  753. }
  754. }).filter(Boolean);
  755. }
  756. }, __publicField(_a, "instances", {}), _a);
  757. var Logger_1 = Logger$1;
  758. let ErrorHandler$1 = class ErrorHandler {
  759. constructor({
  760. externalApi: externalApi2,
  761. logFn = void 0,
  762. onError = void 0,
  763. showDialog = void 0
  764. } = {}) {
  765. __publicField(this, "externalApi");
  766. __publicField(this, "isActive", false);
  767. __publicField(this, "logFn");
  768. __publicField(this, "onError");
  769. __publicField(this, "showDialog", true);
  770. this.createIssue = this.createIssue.bind(this);
  771. this.handleError = this.handleError.bind(this);
  772. this.handleRejection = this.handleRejection.bind(this);
  773. this.setOptions({ externalApi: externalApi2, logFn, onError, showDialog });
  774. this.startCatching = this.startCatching.bind(this);
  775. this.stopCatching = this.stopCatching.bind(this);
  776. }
  777. handle(error, {
  778. logFn = this.logFn,
  779. onError = this.onError,
  780. processType = "browser",
  781. showDialog = this.showDialog,
  782. errorName = ""
  783. } = {}) {
  784. var _a2;
  785. error = normalizeError(error);
  786. try {
  787. if (typeof onError === "function") {
  788. const versions = ((_a2 = this.externalApi) == null ? void 0 : _a2.getVersions()) || {};
  789. const createIssue = this.createIssue;
  790. const result = onError({
  791. createIssue,
  792. error,
  793. errorName,
  794. processType,
  795. versions
  796. });
  797. if (result === false) {
  798. return;
  799. }
  800. }
  801. errorName ? logFn(errorName, error) : logFn(error);
  802. if (showDialog && !errorName.includes("rejection") && this.externalApi) {
  803. this.externalApi.showErrorBox(
  804. `A JavaScript error occurred in the ${processType} process`,
  805. error.stack
  806. );
  807. }
  808. } catch {
  809. console.error(error);
  810. }
  811. }
  812. setOptions({ externalApi: externalApi2, logFn, onError, showDialog }) {
  813. if (typeof externalApi2 === "object") {
  814. this.externalApi = externalApi2;
  815. }
  816. if (typeof logFn === "function") {
  817. this.logFn = logFn;
  818. }
  819. if (typeof onError === "function") {
  820. this.onError = onError;
  821. }
  822. if (typeof showDialog === "boolean") {
  823. this.showDialog = showDialog;
  824. }
  825. }
  826. startCatching({ onError, showDialog } = {}) {
  827. if (this.isActive) {
  828. return;
  829. }
  830. this.isActive = true;
  831. this.setOptions({ onError, showDialog });
  832. process.on("uncaughtException", this.handleError);
  833. process.on("unhandledRejection", this.handleRejection);
  834. }
  835. stopCatching() {
  836. this.isActive = false;
  837. process.removeListener("uncaughtException", this.handleError);
  838. process.removeListener("unhandledRejection", this.handleRejection);
  839. }
  840. createIssue(pageUrl, queryParams) {
  841. var _a2;
  842. (_a2 = this.externalApi) == null ? void 0 : _a2.openUrl(
  843. `${pageUrl}?${new URLSearchParams(queryParams).toString()}`
  844. );
  845. }
  846. handleError(error) {
  847. this.handle(error, { errorName: "Unhandled" });
  848. }
  849. handleRejection(reason) {
  850. const error = reason instanceof Error ? reason : new Error(JSON.stringify(reason));
  851. this.handle(error, { errorName: "Unhandled rejection" });
  852. }
  853. };
  854. function normalizeError(e) {
  855. if (e instanceof Error) {
  856. return e;
  857. }
  858. if (e && typeof e === "object") {
  859. if (e.message) {
  860. return Object.assign(new Error(e.message), e);
  861. }
  862. try {
  863. return new Error(JSON.stringify(e));
  864. } catch (serErr) {
  865. return new Error(`Couldn't normalize error ${String(e)}: ${serErr}`);
  866. }
  867. }
  868. return new Error(`Can't normalize error ${String(e)}`);
  869. }
  870. var ErrorHandler_1 = ErrorHandler$1;
  871. let EventLogger$1 = class EventLogger {
  872. constructor(options = {}) {
  873. __publicField(this, "disposers", []);
  874. __publicField(this, "format", "{eventSource}#{eventName}:");
  875. __publicField(this, "formatters", {
  876. app: {
  877. "certificate-error": ({ args }) => {
  878. return this.arrayToObject(args.slice(1, 4), [
  879. "url",
  880. "error",
  881. "certificate"
  882. ]);
  883. },
  884. "child-process-gone": ({ args }) => {
  885. return args.length === 1 ? args[0] : args;
  886. },
  887. "render-process-gone": ({ args: [webContents, details] }) => {
  888. return details && typeof details === "object" ? { ...details, ...this.getWebContentsDetails(webContents) } : [];
  889. }
  890. },
  891. webContents: {
  892. "console-message": ({ args: [level, message, line, sourceId] }) => {
  893. if (level < 3) {
  894. return void 0;
  895. }
  896. return { message, source: `${sourceId}:${line}` };
  897. },
  898. "did-fail-load": ({ args }) => {
  899. return this.arrayToObject(args, [
  900. "errorCode",
  901. "errorDescription",
  902. "validatedURL",
  903. "isMainFrame",
  904. "frameProcessId",
  905. "frameRoutingId"
  906. ]);
  907. },
  908. "did-fail-provisional-load": ({ args }) => {
  909. return this.arrayToObject(args, [
  910. "errorCode",
  911. "errorDescription",
  912. "validatedURL",
  913. "isMainFrame",
  914. "frameProcessId",
  915. "frameRoutingId"
  916. ]);
  917. },
  918. "plugin-crashed": ({ args }) => {
  919. return this.arrayToObject(args, ["name", "version"]);
  920. },
  921. "preload-error": ({ args }) => {
  922. return this.arrayToObject(args, ["preloadPath", "error"]);
  923. }
  924. }
  925. });
  926. __publicField(this, "events", {
  927. app: {
  928. "certificate-error": true,
  929. "child-process-gone": true,
  930. "render-process-gone": true
  931. },
  932. webContents: {
  933. // 'console-message': true,
  934. "did-fail-load": true,
  935. "did-fail-provisional-load": true,
  936. "plugin-crashed": true,
  937. "preload-error": true,
  938. "unresponsive": true
  939. }
  940. });
  941. __publicField(this, "externalApi");
  942. __publicField(this, "level", "error");
  943. __publicField(this, "scope", "");
  944. this.setOptions(options);
  945. }
  946. setOptions({
  947. events,
  948. externalApi: externalApi2,
  949. level,
  950. logger,
  951. format: format2,
  952. formatters,
  953. scope: scope2
  954. }) {
  955. if (typeof events === "object") {
  956. this.events = events;
  957. }
  958. if (typeof externalApi2 === "object") {
  959. this.externalApi = externalApi2;
  960. }
  961. if (typeof level === "string") {
  962. this.level = level;
  963. }
  964. if (typeof logger === "object") {
  965. this.logger = logger;
  966. }
  967. if (typeof format2 === "string" || typeof format2 === "function") {
  968. this.format = format2;
  969. }
  970. if (typeof formatters === "object") {
  971. this.formatters = formatters;
  972. }
  973. if (typeof scope2 === "string") {
  974. this.scope = scope2;
  975. }
  976. }
  977. startLogging(options = {}) {
  978. this.setOptions(options);
  979. this.disposeListeners();
  980. for (const eventName of this.getEventNames(this.events.app)) {
  981. this.disposers.push(
  982. this.externalApi.onAppEvent(eventName, (...handlerArgs) => {
  983. this.handleEvent({ eventSource: "app", eventName, handlerArgs });
  984. })
  985. );
  986. }
  987. for (const eventName of this.getEventNames(this.events.webContents)) {
  988. this.disposers.push(
  989. this.externalApi.onEveryWebContentsEvent(
  990. eventName,
  991. (...handlerArgs) => {
  992. this.handleEvent(
  993. { eventSource: "webContents", eventName, handlerArgs }
  994. );
  995. }
  996. )
  997. );
  998. }
  999. }
  1000. stopLogging() {
  1001. this.disposeListeners();
  1002. }
  1003. arrayToObject(array, fieldNames) {
  1004. const obj = {};
  1005. fieldNames.forEach((fieldName, index) => {
  1006. obj[fieldName] = array[index];
  1007. });
  1008. if (array.length > fieldNames.length) {
  1009. obj.unknownArgs = array.slice(fieldNames.length);
  1010. }
  1011. return obj;
  1012. }
  1013. disposeListeners() {
  1014. this.disposers.forEach((disposer) => disposer());
  1015. this.disposers = [];
  1016. }
  1017. formatEventLog({ eventName, eventSource, handlerArgs }) {
  1018. var _a2;
  1019. const [event, ...args] = handlerArgs;
  1020. if (typeof this.format === "function") {
  1021. return this.format({ args, event, eventName, eventSource });
  1022. }
  1023. const formatter = (_a2 = this.formatters[eventSource]) == null ? void 0 : _a2[eventName];
  1024. let formattedArgs = args;
  1025. if (typeof formatter === "function") {
  1026. formattedArgs = formatter({ args, event, eventName, eventSource });
  1027. }
  1028. if (!formattedArgs) {
  1029. return void 0;
  1030. }
  1031. const eventData = {};
  1032. if (Array.isArray(formattedArgs)) {
  1033. eventData.args = formattedArgs;
  1034. } else if (typeof formattedArgs === "object") {
  1035. Object.assign(eventData, formattedArgs);
  1036. }
  1037. if (eventSource === "webContents") {
  1038. Object.assign(eventData, this.getWebContentsDetails(event == null ? void 0 : event.sender));
  1039. }
  1040. const title = this.format.replace("{eventSource}", eventSource === "app" ? "App" : "WebContents").replace("{eventName}", eventName);
  1041. return [title, eventData];
  1042. }
  1043. getEventNames(eventMap) {
  1044. if (!eventMap || typeof eventMap !== "object") {
  1045. return [];
  1046. }
  1047. return Object.entries(eventMap).filter(([_, listen]) => listen).map(([eventName]) => eventName);
  1048. }
  1049. getWebContentsDetails(webContents) {
  1050. if (!(webContents == null ? void 0 : webContents.loadURL)) {
  1051. return {};
  1052. }
  1053. try {
  1054. return {
  1055. webContents: {
  1056. id: webContents.id,
  1057. url: webContents.getURL()
  1058. }
  1059. };
  1060. } catch {
  1061. return {};
  1062. }
  1063. }
  1064. handleEvent({ eventName, eventSource, handlerArgs }) {
  1065. var _a2;
  1066. const log2 = this.formatEventLog({ eventName, eventSource, handlerArgs });
  1067. if (log2) {
  1068. const logFns = this.scope ? this.logger.scope(this.scope) : this.logger;
  1069. (_a2 = logFns == null ? void 0 : logFns[this.level]) == null ? void 0 : _a2.call(logFns, ...log2);
  1070. }
  1071. }
  1072. };
  1073. var EventLogger_1 = EventLogger$1;
  1074. var transform_1 = { transform: transform$5 };
  1075. function transform$5({
  1076. logger,
  1077. message,
  1078. transport,
  1079. initialData = (message == null ? void 0 : message.data) || [],
  1080. transforms = transport == null ? void 0 : transport.transforms
  1081. }) {
  1082. return transforms.reduce((data, trans) => {
  1083. if (typeof trans === "function") {
  1084. return trans({ data, logger, message, transport });
  1085. }
  1086. return data;
  1087. }, initialData);
  1088. }
  1089. const { transform: transform$4 } = transform_1;
  1090. var format$2 = {
  1091. concatFirstStringElements: concatFirstStringElements$2,
  1092. formatScope,
  1093. formatText,
  1094. formatVariables,
  1095. timeZoneFromOffset,
  1096. format({ message, logger, transport, data = message == null ? void 0 : message.data }) {
  1097. switch (typeof transport.format) {
  1098. case "string": {
  1099. return transform$4({
  1100. message,
  1101. logger,
  1102. transforms: [formatVariables, formatScope, formatText],
  1103. transport,
  1104. initialData: [transport.format, ...data]
  1105. });
  1106. }
  1107. case "function": {
  1108. return transport.format({
  1109. data,
  1110. level: (message == null ? void 0 : message.level) || "info",
  1111. logger,
  1112. message,
  1113. transport
  1114. });
  1115. }
  1116. default: {
  1117. return data;
  1118. }
  1119. }
  1120. }
  1121. };
  1122. function concatFirstStringElements$2({ data }) {
  1123. if (typeof data[0] !== "string" || typeof data[1] !== "string") {
  1124. return data;
  1125. }
  1126. if (data[0].match(/%[1cdfiOos]/)) {
  1127. return data;
  1128. }
  1129. return [`${data[0]} ${data[1]}`, ...data.slice(2)];
  1130. }
  1131. function timeZoneFromOffset(minutesOffset) {
  1132. const minutesPositive = Math.abs(minutesOffset);
  1133. const sign = minutesOffset > 0 ? "-" : "+";
  1134. const hours = Math.floor(minutesPositive / 60).toString().padStart(2, "0");
  1135. const minutes = (minutesPositive % 60).toString().padStart(2, "0");
  1136. return `${sign}${hours}:${minutes}`;
  1137. }
  1138. function formatScope({ data, logger, message }) {
  1139. const { defaultLabel, labelLength } = (logger == null ? void 0 : logger.scope) || {};
  1140. const template = data[0];
  1141. let label = message.scope;
  1142. if (!label) {
  1143. label = defaultLabel;
  1144. }
  1145. let scopeText;
  1146. if (label === "") {
  1147. scopeText = labelLength > 0 ? "".padEnd(labelLength + 3) : "";
  1148. } else if (typeof label === "string") {
  1149. scopeText = ` (${label})`.padEnd(labelLength + 3);
  1150. } else {
  1151. scopeText = "";
  1152. }
  1153. data[0] = template.replace("{scope}", scopeText);
  1154. return data;
  1155. }
  1156. function formatVariables({ data, message }) {
  1157. let template = data[0];
  1158. if (typeof template !== "string") {
  1159. return data;
  1160. }
  1161. template = template.replace("{level}]", `${message.level}]`.padEnd(6, " "));
  1162. const date = message.date || /* @__PURE__ */ new Date();
  1163. data[0] = template.replace(/\{(\w+)}/g, (substring, name) => {
  1164. var _a2;
  1165. switch (name) {
  1166. case "level":
  1167. return message.level || "info";
  1168. case "logId":
  1169. return message.logId;
  1170. case "y":
  1171. return date.getFullYear().toString(10);
  1172. case "m":
  1173. return (date.getMonth() + 1).toString(10).padStart(2, "0");
  1174. case "d":
  1175. return date.getDate().toString(10).padStart(2, "0");
  1176. case "h":
  1177. return date.getHours().toString(10).padStart(2, "0");
  1178. case "i":
  1179. return date.getMinutes().toString(10).padStart(2, "0");
  1180. case "s":
  1181. return date.getSeconds().toString(10).padStart(2, "0");
  1182. case "ms":
  1183. return date.getMilliseconds().toString(10).padStart(3, "0");
  1184. case "z":
  1185. return timeZoneFromOffset(date.getTimezoneOffset());
  1186. case "iso":
  1187. return date.toISOString();
  1188. default: {
  1189. return ((_a2 = message.variables) == null ? void 0 : _a2[name]) || substring;
  1190. }
  1191. }
  1192. }).trim();
  1193. return data;
  1194. }
  1195. function formatText({ data }) {
  1196. const template = data[0];
  1197. if (typeof template !== "string") {
  1198. return data;
  1199. }
  1200. const textTplPosition = template.lastIndexOf("{text}");
  1201. if (textTplPosition === template.length - 6) {
  1202. data[0] = template.replace(/\s?{text}/, "");
  1203. if (data[0] === "") {
  1204. data.shift();
  1205. }
  1206. return data;
  1207. }
  1208. const templatePieces = template.split("{text}");
  1209. let result = [];
  1210. if (templatePieces[0] !== "") {
  1211. result.push(templatePieces[0]);
  1212. }
  1213. result = result.concat(data.slice(1));
  1214. if (templatePieces[1] !== "") {
  1215. result.push(templatePieces[1]);
  1216. }
  1217. return result;
  1218. }
  1219. var object = { exports: {} };
  1220. (function(module2) {
  1221. const util = require$$0$1;
  1222. module2.exports = {
  1223. serialize,
  1224. maxDepth({ data, transport, depth = (transport == null ? void 0 : transport.depth) ?? 6 }) {
  1225. if (!data) {
  1226. return data;
  1227. }
  1228. if (depth < 1) {
  1229. if (Array.isArray(data)) return "[array]";
  1230. if (typeof data === "object" && data) return "[object]";
  1231. return data;
  1232. }
  1233. if (Array.isArray(data)) {
  1234. return data.map((child) => module2.exports.maxDepth({
  1235. data: child,
  1236. depth: depth - 1
  1237. }));
  1238. }
  1239. if (typeof data !== "object") {
  1240. return data;
  1241. }
  1242. if (data && typeof data.toISOString === "function") {
  1243. return data;
  1244. }
  1245. if (data === null) {
  1246. return null;
  1247. }
  1248. if (data instanceof Error) {
  1249. return data;
  1250. }
  1251. const newJson = {};
  1252. for (const i in data) {
  1253. if (!Object.prototype.hasOwnProperty.call(data, i)) continue;
  1254. newJson[i] = module2.exports.maxDepth({
  1255. data: data[i],
  1256. depth: depth - 1
  1257. });
  1258. }
  1259. return newJson;
  1260. },
  1261. toJSON({ data }) {
  1262. return JSON.parse(JSON.stringify(data, createSerializer()));
  1263. },
  1264. toString({ data, transport }) {
  1265. const inspectOptions = (transport == null ? void 0 : transport.inspectOptions) || {};
  1266. const simplifiedData = data.map((item) => {
  1267. if (item === void 0) {
  1268. return void 0;
  1269. }
  1270. try {
  1271. const str = JSON.stringify(item, createSerializer(), " ");
  1272. return str === void 0 ? void 0 : JSON.parse(str);
  1273. } catch (e) {
  1274. return item;
  1275. }
  1276. });
  1277. return util.formatWithOptions(inspectOptions, ...simplifiedData);
  1278. }
  1279. };
  1280. function createSerializer(options = {}) {
  1281. const seen = /* @__PURE__ */ new WeakSet();
  1282. return function(key, value) {
  1283. if (typeof value === "object" && value !== null) {
  1284. if (seen.has(value)) {
  1285. return void 0;
  1286. }
  1287. seen.add(value);
  1288. }
  1289. return serialize(key, value, options);
  1290. };
  1291. }
  1292. function serialize(key, value, options = {}) {
  1293. const serializeMapAndSet = (options == null ? void 0 : options.serializeMapAndSet) !== false;
  1294. if (value instanceof Error) {
  1295. return value.stack;
  1296. }
  1297. if (!value) {
  1298. return value;
  1299. }
  1300. if (typeof value === "function") {
  1301. return `[function] ${value.toString()}`;
  1302. }
  1303. if (value instanceof Date) {
  1304. return value.toISOString();
  1305. }
  1306. if (serializeMapAndSet && value instanceof Map && Object.fromEntries) {
  1307. return Object.fromEntries(value);
  1308. }
  1309. if (serializeMapAndSet && value instanceof Set && Array.from) {
  1310. return Array.from(value);
  1311. }
  1312. return value;
  1313. }
  1314. })(object);
  1315. var objectExports = object.exports;
  1316. var style = {
  1317. transformStyles,
  1318. applyAnsiStyles({ data }) {
  1319. return transformStyles(data, styleToAnsi, resetAnsiStyle);
  1320. },
  1321. removeStyles({ data }) {
  1322. return transformStyles(data, () => "");
  1323. }
  1324. };
  1325. const ANSI_COLORS = {
  1326. unset: "\x1B[0m",
  1327. black: "\x1B[30m",
  1328. red: "\x1B[31m",
  1329. green: "\x1B[32m",
  1330. yellow: "\x1B[33m",
  1331. blue: "\x1B[34m",
  1332. magenta: "\x1B[35m",
  1333. cyan: "\x1B[36m",
  1334. white: "\x1B[37m"
  1335. };
  1336. function styleToAnsi(style2) {
  1337. const color = style2.replace(/color:\s*(\w+).*/, "$1").toLowerCase();
  1338. return ANSI_COLORS[color] || "";
  1339. }
  1340. function resetAnsiStyle(string) {
  1341. return string + ANSI_COLORS.unset;
  1342. }
  1343. function transformStyles(data, onStyleFound, onStyleApplied) {
  1344. const foundStyles = {};
  1345. return data.reduce((result, item, index, array) => {
  1346. if (foundStyles[index]) {
  1347. return result;
  1348. }
  1349. if (typeof item === "string") {
  1350. let valueIndex = index;
  1351. let styleApplied = false;
  1352. item = item.replace(/%[1cdfiOos]/g, (match) => {
  1353. valueIndex += 1;
  1354. if (match !== "%c") {
  1355. return match;
  1356. }
  1357. const style2 = array[valueIndex];
  1358. if (typeof style2 === "string") {
  1359. foundStyles[valueIndex] = true;
  1360. styleApplied = true;
  1361. return onStyleFound(style2, item);
  1362. }
  1363. return match;
  1364. });
  1365. if (styleApplied && onStyleApplied) {
  1366. item = onStyleApplied(item);
  1367. }
  1368. }
  1369. result.push(item);
  1370. return result;
  1371. }, []);
  1372. }
  1373. const { concatFirstStringElements: concatFirstStringElements$1, format: format$1 } = format$2;
  1374. const { maxDepth: maxDepth$2, toJSON: toJSON$2 } = objectExports;
  1375. const { applyAnsiStyles, removeStyles: removeStyles$2 } = style;
  1376. const { transform: transform$3 } = transform_1;
  1377. const consoleMethods = {
  1378. error: console.error,
  1379. warn: console.warn,
  1380. info: console.info,
  1381. verbose: console.info,
  1382. debug: console.debug,
  1383. silly: console.debug,
  1384. log: console.log
  1385. };
  1386. var console_1 = consoleTransportFactory;
  1387. const separator = process.platform === "win32" ? ">" : "›";
  1388. const DEFAULT_FORMAT = `%c{h}:{i}:{s}.{ms}{scope}%c ${separator} {text}`;
  1389. Object.assign(consoleTransportFactory, {
  1390. DEFAULT_FORMAT
  1391. });
  1392. function consoleTransportFactory(logger) {
  1393. return Object.assign(transport, {
  1394. format: DEFAULT_FORMAT,
  1395. level: "silly",
  1396. transforms: [
  1397. addTemplateColors,
  1398. format$1,
  1399. formatStyles,
  1400. concatFirstStringElements$1,
  1401. maxDepth$2,
  1402. toJSON$2
  1403. ],
  1404. useStyles: process.env.FORCE_STYLES,
  1405. writeFn({ message }) {
  1406. const consoleLogFn = consoleMethods[message.level] || consoleMethods.info;
  1407. consoleLogFn(...message.data);
  1408. }
  1409. });
  1410. function transport(message) {
  1411. const data = transform$3({ logger, message, transport });
  1412. transport.writeFn({
  1413. message: { ...message, data }
  1414. });
  1415. }
  1416. }
  1417. function addTemplateColors({ data, message, transport }) {
  1418. if (transport.format !== DEFAULT_FORMAT) {
  1419. return data;
  1420. }
  1421. return [`color:${levelToStyle(message.level)}`, "color:unset", ...data];
  1422. }
  1423. function canUseStyles(useStyleValue, level) {
  1424. if (typeof useStyleValue === "boolean") {
  1425. return useStyleValue;
  1426. }
  1427. const useStderr = level === "error" || level === "warn";
  1428. const stream = useStderr ? process.stderr : process.stdout;
  1429. return stream && stream.isTTY;
  1430. }
  1431. function formatStyles(args) {
  1432. const { message, transport } = args;
  1433. const useStyles = canUseStyles(transport.useStyles, message.level);
  1434. const nextTransform = useStyles ? applyAnsiStyles : removeStyles$2;
  1435. return nextTransform(args);
  1436. }
  1437. function levelToStyle(level) {
  1438. const map = { error: "red", warn: "yellow", info: "cyan", default: "unset" };
  1439. return map[level] || map.default;
  1440. }
  1441. const EventEmitter$1 = require$$0$2;
  1442. const fs$2 = fs$5;
  1443. const os$1 = require$$1;
  1444. let File$2 = class File extends EventEmitter$1 {
  1445. constructor({
  1446. path: path2,
  1447. writeOptions = { encoding: "utf8", flag: "a", mode: 438 },
  1448. writeAsync = false
  1449. }) {
  1450. super();
  1451. __publicField(this, "asyncWriteQueue", []);
  1452. __publicField(this, "bytesWritten", 0);
  1453. __publicField(this, "hasActiveAsyncWriting", false);
  1454. __publicField(this, "path", null);
  1455. __publicField(this, "initialSize");
  1456. __publicField(this, "writeOptions", null);
  1457. __publicField(this, "writeAsync", false);
  1458. this.path = path2;
  1459. this.writeOptions = writeOptions;
  1460. this.writeAsync = writeAsync;
  1461. }
  1462. get size() {
  1463. return this.getSize();
  1464. }
  1465. clear() {
  1466. try {
  1467. fs$2.writeFileSync(this.path, "", {
  1468. mode: this.writeOptions.mode,
  1469. flag: "w"
  1470. });
  1471. this.reset();
  1472. return true;
  1473. } catch (e) {
  1474. if (e.code === "ENOENT") {
  1475. return true;
  1476. }
  1477. this.emit("error", e, this);
  1478. return false;
  1479. }
  1480. }
  1481. crop(bytesAfter) {
  1482. try {
  1483. const content = readFileSyncFromEnd(this.path, bytesAfter || 4096);
  1484. this.clear();
  1485. this.writeLine(`[log cropped]${os$1.EOL}${content}`);
  1486. } catch (e) {
  1487. this.emit(
  1488. "error",
  1489. new Error(`Couldn't crop file ${this.path}. ${e.message}`),
  1490. this
  1491. );
  1492. }
  1493. }
  1494. getSize() {
  1495. if (this.initialSize === void 0) {
  1496. try {
  1497. const stats = fs$2.statSync(this.path);
  1498. this.initialSize = stats.size;
  1499. } catch (e) {
  1500. this.initialSize = 0;
  1501. }
  1502. }
  1503. return this.initialSize + this.bytesWritten;
  1504. }
  1505. increaseBytesWrittenCounter(text) {
  1506. this.bytesWritten += Buffer.byteLength(text, this.writeOptions.encoding);
  1507. }
  1508. isNull() {
  1509. return false;
  1510. }
  1511. nextAsyncWrite() {
  1512. const file2 = this;
  1513. if (this.hasActiveAsyncWriting || this.asyncWriteQueue.length === 0) {
  1514. return;
  1515. }
  1516. const text = this.asyncWriteQueue.join("");
  1517. this.asyncWriteQueue = [];
  1518. this.hasActiveAsyncWriting = true;
  1519. fs$2.writeFile(this.path, text, this.writeOptions, (e) => {
  1520. file2.hasActiveAsyncWriting = false;
  1521. if (e) {
  1522. file2.emit(
  1523. "error",
  1524. new Error(`Couldn't write to ${file2.path}. ${e.message}`),
  1525. this
  1526. );
  1527. } else {
  1528. file2.increaseBytesWrittenCounter(text);
  1529. }
  1530. file2.nextAsyncWrite();
  1531. });
  1532. }
  1533. reset() {
  1534. this.initialSize = void 0;
  1535. this.bytesWritten = 0;
  1536. }
  1537. toString() {
  1538. return this.path;
  1539. }
  1540. writeLine(text) {
  1541. text += os$1.EOL;
  1542. if (this.writeAsync) {
  1543. this.asyncWriteQueue.push(text);
  1544. this.nextAsyncWrite();
  1545. return;
  1546. }
  1547. try {
  1548. fs$2.writeFileSync(this.path, text, this.writeOptions);
  1549. this.increaseBytesWrittenCounter(text);
  1550. } catch (e) {
  1551. this.emit(
  1552. "error",
  1553. new Error(`Couldn't write to ${this.path}. ${e.message}`),
  1554. this
  1555. );
  1556. }
  1557. }
  1558. };
  1559. var File_1 = File$2;
  1560. function readFileSyncFromEnd(filePath, bytesCount) {
  1561. const buffer = Buffer.alloc(bytesCount);
  1562. const stats = fs$2.statSync(filePath);
  1563. const readLength = Math.min(stats.size, bytesCount);
  1564. const offset = Math.max(0, stats.size - bytesCount);
  1565. const fd = fs$2.openSync(filePath, "r");
  1566. const totalBytes = fs$2.readSync(fd, buffer, 0, readLength, offset);
  1567. fs$2.closeSync(fd);
  1568. return buffer.toString("utf8", 0, totalBytes);
  1569. }
  1570. const File$1 = File_1;
  1571. let NullFile$1 = class NullFile extends File$1 {
  1572. clear() {
  1573. }
  1574. crop() {
  1575. }
  1576. getSize() {
  1577. return 0;
  1578. }
  1579. isNull() {
  1580. return true;
  1581. }
  1582. writeLine() {
  1583. }
  1584. };
  1585. var NullFile_1 = NullFile$1;
  1586. const EventEmitter = require$$0$2;
  1587. const fs$1 = fs$5;
  1588. const path$1 = require$$2;
  1589. const File2 = File_1;
  1590. const NullFile2 = NullFile_1;
  1591. let FileRegistry$1 = class FileRegistry extends EventEmitter {
  1592. constructor() {
  1593. super();
  1594. __publicField(this, "store", {});
  1595. this.emitError = this.emitError.bind(this);
  1596. }
  1597. /**
  1598. * Provide a File object corresponding to the filePath
  1599. * @param {string} filePath
  1600. * @param {WriteOptions} [writeOptions]
  1601. * @param {boolean} [writeAsync]
  1602. * @return {File}
  1603. */
  1604. provide({ filePath, writeOptions = {}, writeAsync = false }) {
  1605. let file2;
  1606. try {
  1607. filePath = path$1.resolve(filePath);
  1608. if (this.store[filePath]) {
  1609. return this.store[filePath];
  1610. }
  1611. file2 = this.createFile({ filePath, writeOptions, writeAsync });
  1612. } catch (e) {
  1613. file2 = new NullFile2({ path: filePath });
  1614. this.emitError(e, file2);
  1615. }
  1616. file2.on("error", this.emitError);
  1617. this.store[filePath] = file2;
  1618. return file2;
  1619. }
  1620. /**
  1621. * @param {string} filePath
  1622. * @param {WriteOptions} writeOptions
  1623. * @param {boolean} async
  1624. * @return {File}
  1625. * @private
  1626. */
  1627. createFile({ filePath, writeOptions, writeAsync }) {
  1628. this.testFileWriting({ filePath, writeOptions });
  1629. return new File2({ path: filePath, writeOptions, writeAsync });
  1630. }
  1631. /**
  1632. * @param {Error} error
  1633. * @param {File} file
  1634. * @private
  1635. */
  1636. emitError(error, file2) {
  1637. this.emit("error", error, file2);
  1638. }
  1639. /**
  1640. * @param {string} filePath
  1641. * @param {WriteOptions} writeOptions
  1642. * @private
  1643. */
  1644. testFileWriting({ filePath, writeOptions }) {
  1645. fs$1.mkdirSync(path$1.dirname(filePath), { recursive: true });
  1646. fs$1.writeFileSync(filePath, "", { flag: "a", mode: writeOptions.mode });
  1647. }
  1648. };
  1649. var FileRegistry_1 = FileRegistry$1;
  1650. const fs = fs$5;
  1651. const os = require$$1;
  1652. const path = require$$2;
  1653. const FileRegistry2 = FileRegistry_1;
  1654. const { transform: transform$2 } = transform_1;
  1655. const { removeStyles: removeStyles$1 } = style;
  1656. const {
  1657. format,
  1658. concatFirstStringElements
  1659. } = format$2;
  1660. const { toString } = objectExports;
  1661. var file = fileTransportFactory;
  1662. const globalRegistry = new FileRegistry2();
  1663. function fileTransportFactory(logger, { registry = globalRegistry, externalApi: externalApi2 } = {}) {
  1664. let pathVariables;
  1665. if (registry.listenerCount("error") < 1) {
  1666. registry.on("error", (e, file2) => {
  1667. logConsole(`Can't write to ${file2}`, e);
  1668. });
  1669. }
  1670. return Object.assign(transport, {
  1671. fileName: getDefaultFileName(logger.variables.processType),
  1672. format: "[{y}-{m}-{d} {h}:{i}:{s}.{ms}] [{level}]{scope} {text}",
  1673. getFile,
  1674. inspectOptions: { depth: 5 },
  1675. level: "silly",
  1676. maxSize: 1024 ** 2,
  1677. readAllLogs,
  1678. sync: true,
  1679. transforms: [removeStyles$1, format, concatFirstStringElements, toString],
  1680. writeOptions: { flag: "a", mode: 438, encoding: "utf8" },
  1681. archiveLogFn(file2) {
  1682. const oldPath = file2.toString();
  1683. const inf = path.parse(oldPath);
  1684. try {
  1685. fs.renameSync(oldPath, path.join(inf.dir, `${inf.name}.old${inf.ext}`));
  1686. } catch (e) {
  1687. logConsole("Could not rotate log", e);
  1688. const quarterOfMaxSize = Math.round(transport.maxSize / 4);
  1689. file2.crop(Math.min(quarterOfMaxSize, 256 * 1024));
  1690. }
  1691. },
  1692. resolvePathFn(vars) {
  1693. return path.join(vars.libraryDefaultDir, vars.fileName);
  1694. },
  1695. setAppName(name) {
  1696. logger.dependencies.externalApi.setAppName(name);
  1697. }
  1698. });
  1699. function transport(message) {
  1700. const file2 = getFile(message);
  1701. const needLogRotation = transport.maxSize > 0 && file2.size > transport.maxSize;
  1702. if (needLogRotation) {
  1703. transport.archiveLogFn(file2);
  1704. file2.reset();
  1705. }
  1706. const content = transform$2({ logger, message, transport });
  1707. file2.writeLine(content);
  1708. }
  1709. function initializeOnFirstAccess() {
  1710. if (pathVariables) {
  1711. return;
  1712. }
  1713. pathVariables = Object.create(
  1714. Object.prototype,
  1715. {
  1716. ...Object.getOwnPropertyDescriptors(
  1717. externalApi2.getPathVariables()
  1718. ),
  1719. fileName: {
  1720. get() {
  1721. return transport.fileName;
  1722. },
  1723. enumerable: true
  1724. }
  1725. }
  1726. );
  1727. if (typeof transport.archiveLog === "function") {
  1728. transport.archiveLogFn = transport.archiveLog;
  1729. logConsole("archiveLog is deprecated. Use archiveLogFn instead");
  1730. }
  1731. if (typeof transport.resolvePath === "function") {
  1732. transport.resolvePathFn = transport.resolvePath;
  1733. logConsole("resolvePath is deprecated. Use resolvePathFn instead");
  1734. }
  1735. }
  1736. function logConsole(message, error = null, level = "error") {
  1737. const data = [`electron-log.transports.file: ${message}`];
  1738. if (error) {
  1739. data.push(error);
  1740. }
  1741. logger.transports.console({ data, date: /* @__PURE__ */ new Date(), level });
  1742. }
  1743. function getFile(msg) {
  1744. initializeOnFirstAccess();
  1745. const filePath = transport.resolvePathFn(pathVariables, msg);
  1746. return registry.provide({
  1747. filePath,
  1748. writeAsync: !transport.sync,
  1749. writeOptions: transport.writeOptions
  1750. });
  1751. }
  1752. function readAllLogs({ fileFilter = (f) => f.endsWith(".log") } = {}) {
  1753. initializeOnFirstAccess();
  1754. const logsPath = path.dirname(transport.resolvePathFn(pathVariables));
  1755. if (!fs.existsSync(logsPath)) {
  1756. return [];
  1757. }
  1758. return fs.readdirSync(logsPath).map((fileName) => path.join(logsPath, fileName)).filter(fileFilter).map((logPath) => {
  1759. try {
  1760. return {
  1761. path: logPath,
  1762. lines: fs.readFileSync(logPath, "utf8").split(os.EOL)
  1763. };
  1764. } catch {
  1765. return null;
  1766. }
  1767. }).filter(Boolean);
  1768. }
  1769. }
  1770. function getDefaultFileName(processType = process.type) {
  1771. switch (processType) {
  1772. case "renderer":
  1773. return "renderer.log";
  1774. case "worker":
  1775. return "worker.log";
  1776. default:
  1777. return "main.log";
  1778. }
  1779. }
  1780. const { maxDepth: maxDepth$1, toJSON: toJSON$1 } = objectExports;
  1781. const { transform: transform$1 } = transform_1;
  1782. var ipc = ipcTransportFactory;
  1783. function ipcTransportFactory(logger, { externalApi: externalApi2 }) {
  1784. Object.assign(transport, {
  1785. depth: 3,
  1786. eventId: "__ELECTRON_LOG_IPC__",
  1787. level: logger.isDev ? "silly" : false,
  1788. transforms: [toJSON$1, maxDepth$1]
  1789. });
  1790. return (externalApi2 == null ? void 0 : externalApi2.isElectron()) ? transport : void 0;
  1791. function transport(message) {
  1792. var _a2;
  1793. if (((_a2 = message == null ? void 0 : message.variables) == null ? void 0 : _a2.processType) === "renderer") {
  1794. return;
  1795. }
  1796. externalApi2 == null ? void 0 : externalApi2.sendIpc(transport.eventId, {
  1797. ...message,
  1798. data: transform$1({ logger, message, transport })
  1799. });
  1800. }
  1801. }
  1802. const http = require$$0$3;
  1803. const https = require$$1$1;
  1804. const { transform } = transform_1;
  1805. const { removeStyles } = style;
  1806. const { toJSON, maxDepth } = objectExports;
  1807. var remote = remoteTransportFactory;
  1808. function remoteTransportFactory(logger) {
  1809. return Object.assign(transport, {
  1810. client: { name: "electron-application" },
  1811. depth: 6,
  1812. level: false,
  1813. requestOptions: {},
  1814. transforms: [removeStyles, toJSON, maxDepth],
  1815. makeBodyFn({ message }) {
  1816. return JSON.stringify({
  1817. client: transport.client,
  1818. data: message.data,
  1819. date: message.date.getTime(),
  1820. level: message.level,
  1821. scope: message.scope,
  1822. variables: message.variables
  1823. });
  1824. },
  1825. processErrorFn({ error }) {
  1826. logger.processMessage(
  1827. {
  1828. data: [`electron-log: can't POST ${transport.url}`, error],
  1829. level: "warn"
  1830. },
  1831. { transports: ["console", "file"] }
  1832. );
  1833. },
  1834. sendRequestFn({ serverUrl, requestOptions, body }) {
  1835. const httpTransport = serverUrl.startsWith("https:") ? https : http;
  1836. const request = httpTransport.request(serverUrl, {
  1837. method: "POST",
  1838. ...requestOptions,
  1839. headers: {
  1840. "Content-Type": "application/json",
  1841. "Content-Length": body.length,
  1842. ...requestOptions.headers
  1843. }
  1844. });
  1845. request.write(body);
  1846. request.end();
  1847. return request;
  1848. }
  1849. });
  1850. function transport(message) {
  1851. if (!transport.url) {
  1852. return;
  1853. }
  1854. const body = transport.makeBodyFn({
  1855. logger,
  1856. message: { ...message, data: transform({ logger, message, transport }) },
  1857. transport
  1858. });
  1859. const request = transport.sendRequestFn({
  1860. serverUrl: transport.url,
  1861. requestOptions: transport.requestOptions,
  1862. body: Buffer.from(body, "utf8")
  1863. });
  1864. request.on("error", (error) => transport.processErrorFn({
  1865. error,
  1866. logger,
  1867. message,
  1868. request,
  1869. transport
  1870. }));
  1871. }
  1872. }
  1873. const Logger = Logger_1;
  1874. const ErrorHandler2 = ErrorHandler_1;
  1875. const EventLogger2 = EventLogger_1;
  1876. const transportConsole = console_1;
  1877. const transportFile = file;
  1878. const transportIpc = ipc;
  1879. const transportRemote = remote;
  1880. var createDefaultLogger_1 = createDefaultLogger$1;
  1881. function createDefaultLogger$1({ dependencies, initializeFn }) {
  1882. var _a2;
  1883. const defaultLogger2 = new Logger({
  1884. dependencies,
  1885. errorHandler: new ErrorHandler2(),
  1886. eventLogger: new EventLogger2(),
  1887. initializeFn,
  1888. isDev: (_a2 = dependencies.externalApi) == null ? void 0 : _a2.isDev(),
  1889. logId: "default",
  1890. transportFactories: {
  1891. console: transportConsole,
  1892. file: transportFile,
  1893. ipc: transportIpc,
  1894. remote: transportRemote
  1895. },
  1896. variables: {
  1897. processType: "main"
  1898. }
  1899. });
  1900. defaultLogger2.default = defaultLogger2;
  1901. defaultLogger2.Logger = Logger;
  1902. defaultLogger2.processInternalErrorFn = (e) => {
  1903. defaultLogger2.transports.console.writeFn({
  1904. message: {
  1905. data: ["Unhandled electron-log error", e],
  1906. level: "error"
  1907. }
  1908. });
  1909. };
  1910. return defaultLogger2;
  1911. }
  1912. const electron = require$$0$4;
  1913. const ElectronExternalApi2 = ElectronExternalApi_1;
  1914. const { initialize } = initialize$1;
  1915. const createDefaultLogger = createDefaultLogger_1;
  1916. const externalApi = new ElectronExternalApi2({ electron });
  1917. const defaultLogger = createDefaultLogger({
  1918. dependencies: { externalApi },
  1919. initializeFn: initialize
  1920. });
  1921. var main$1 = defaultLogger;
  1922. externalApi.onIpc("__ELECTRON_LOG__", (_, message) => {
  1923. if (message.scope) {
  1924. defaultLogger.Logger.getInstance(message).scope(message.scope);
  1925. }
  1926. const date = new Date(message.date);
  1927. processMessage({
  1928. ...message,
  1929. date: date.getTime() ? date : /* @__PURE__ */ new Date()
  1930. });
  1931. });
  1932. externalApi.onIpcInvoke("__ELECTRON_LOG__", (_, { cmd = "", logId }) => {
  1933. switch (cmd) {
  1934. case "getOptions": {
  1935. const logger = defaultLogger.Logger.getInstance({ logId });
  1936. return {
  1937. levels: logger.levels,
  1938. logId
  1939. };
  1940. }
  1941. default: {
  1942. processMessage({ data: [`Unknown cmd '${cmd}'`], level: "error" });
  1943. return {};
  1944. }
  1945. }
  1946. });
  1947. function processMessage(message) {
  1948. var _a2;
  1949. (_a2 = defaultLogger.Logger.getInstance(message)) == null ? void 0 : _a2.processMessage(message);
  1950. }
  1951. const main = main$1;
  1952. var main_1 = main;
  1953. const log = /* @__PURE__ */ getDefaultExportFromCjs(main_1);
  1954. const url = process.env.VITE_DEV_SERVER_URL;
  1955. process.env.NODE_ENV === "development";
  1956. const DIST_ELECTRON = path$6.join(__dirname, "../");
  1957. const DIST = path$6.join(DIST_ELECTRON, "../dist-electron");
  1958. const preload = path$6.join(__dirname, "../preload/index.js");
  1959. const PUBLIC = url ? path$6.join(DIST_ELECTRON, "../public") : process.env.DIST;
  1960. const ICON = url ? path$6.join(PUBLIC, "./logo.ico") : path$6.join(DIST, "./logo.ico");
  1961. path$6.join(DIST, "./app.json");
  1962. process.env.NODE_ENV;
  1963. const indexHtml = path$6.join(DIST, "./index.html");
  1964. let mainWindow;
  1965. const extra = {
  1966. activeClose: false
  1967. };
  1968. const createWindow = () => {
  1969. const { width, height } = require$$0$4.screen.getPrimaryDisplay().workAreaSize;
  1970. const winWidth = 420;
  1971. const winHeight = 700;
  1972. const x = width - winWidth;
  1973. const y = 10;
  1974. mainWindow = new require$$0$4.BrowserWindow({
  1975. title: "菁苗健康",
  1976. icon: ICON,
  1977. x,
  1978. y,
  1979. width: winWidth,
  1980. height: winHeight,
  1981. frame: true,
  1982. show: false,
  1983. // transparent: true,
  1984. backgroundColor: "#fff",
  1985. webPreferences: {
  1986. preload,
  1987. webviewTag: true
  1988. // 启用webview标签
  1989. // webSecurity: false,
  1990. }
  1991. });
  1992. mainWindow.setMenu(null);
  1993. if (url) {
  1994. mainWindow.loadURL(url);
  1995. } else {
  1996. mainWindow.loadFile(indexHtml);
  1997. }
  1998. mainWindow.once("ready-to-show", () => {
  1999. log.info("启动参数process.argv==> hidden表示开机重启成功", process.argv);
  2000. if (process.argv.indexOf("--hidden") < 0) {
  2001. showMainWin();
  2002. }
  2003. });
  2004. mainWindow.on("close", (e) => {
  2005. if (!extra.activeClose) {
  2006. e.preventDefault();
  2007. hideMainWin();
  2008. } else {
  2009. extra.activeClose = true;
  2010. }
  2011. });
  2012. return mainWindow;
  2013. };
  2014. function showMainWin() {
  2015. if (!mainWindow || (mainWindow == null ? void 0 : mainWindow.isDestroyed())) {
  2016. mainWindow = createWindow();
  2017. }
  2018. mainWindow.show();
  2019. }
  2020. function hideMainWin() {
  2021. mainWindow.hide();
  2022. }
  2023. function minimizeMainWin() {
  2024. mainWindow.minimize();
  2025. }
  2026. function maximizeMainWin() {
  2027. mainWindow.maximize();
  2028. }
  2029. function unmaximizeMainWin() {
  2030. mainWindow.unmaximize();
  2031. }
  2032. function isMaximized() {
  2033. return mainWindow.isMaximized();
  2034. }
  2035. const initIpcMain = () => {
  2036. const handle = (name, callback) => {
  2037. require$$0$4.ipcMain.handle(name, (e, ...par) => callback(e, ...par));
  2038. };
  2039. handle("close", () => hideMainWin());
  2040. handle("min", () => minimizeMainWin());
  2041. handle("max", () => {
  2042. let obj = { type: "max", data: "unmax" };
  2043. if (isMaximized()) {
  2044. unmaximizeMainWin();
  2045. } else {
  2046. obj.data = "max";
  2047. maximizeMainWin();
  2048. }
  2049. return obj;
  2050. });
  2051. };
  2052. const Store = require("electron-store");
  2053. const schema = {
  2054. isFocusOpenWin: {
  2055. type: "number",
  2056. default: 1
  2057. }
  2058. };
  2059. const store = new Store({ schema });
  2060. const handeSet = (key, value) => {
  2061. store.set(key, value);
  2062. };
  2063. const handeGet = (key) => {
  2064. const data = store.get(key);
  2065. return data;
  2066. };
  2067. const initTray = () => {
  2068. let appIcon = new require$$0$4.Tray(ICON);
  2069. const isFocusOpenWin = handeGet("isFocusOpenWin");
  2070. let contextMenu = require$$0$4.Menu.buildFromTemplate([
  2071. {
  2072. id: "open-win",
  2073. label: `${isFocusOpenWin == 1 ? "关闭" : "开启"}主动弹窗`,
  2074. click: () => {
  2075. updateItem();
  2076. }
  2077. },
  2078. {
  2079. label: "打开弹窗",
  2080. click: () => {
  2081. showMainWin();
  2082. }
  2083. },
  2084. {
  2085. label: "退出弹窗",
  2086. click: () => {
  2087. extra.activeClose = true;
  2088. setTimeout(() => {
  2089. require$$0$4.app.quit();
  2090. });
  2091. }
  2092. }
  2093. ]);
  2094. appIcon.setToolTip("菁苗健康");
  2095. appIcon.setContextMenu(contextMenu);
  2096. appIcon.addListener("click", function() {
  2097. showMainWin();
  2098. });
  2099. const updateItem = async () => {
  2100. let isFocusOpenWin2 = handeGet("isFocusOpenWin");
  2101. const openMenuItem = contextMenu.getMenuItemById("open-win");
  2102. if (isFocusOpenWin2 == 1) {
  2103. isFocusOpenWin2 = 2;
  2104. openMenuItem.label = `开启主动弹窗`;
  2105. } else {
  2106. isFocusOpenWin2 = 1;
  2107. openMenuItem.label = `关闭主动弹窗`;
  2108. }
  2109. contextMenu = require$$0$4.Menu.buildFromTemplate(contextMenu.items);
  2110. appIcon.setContextMenu(contextMenu);
  2111. handeSet("isFocusOpenWin", isFocusOpenWin2);
  2112. log.info("isFocusOpenWin==>", isFocusOpenWin2);
  2113. };
  2114. return appIcon;
  2115. };
  2116. const initExpress = () => {
  2117. const app = express();
  2118. app.use(express.json());
  2119. app.use(express.urlencoded({ extended: false }));
  2120. app.use(cors());
  2121. app.get("/iframe", async (req, res) => {
  2122. const { path: path2, Path } = req.query;
  2123. console.log("🚀 ~ app.get ~ req.query:", req.query);
  2124. const url2 = path2 || Path;
  2125. if (!url2) {
  2126. res.send({
  2127. code: 10001,
  2128. msg: "缺少path参数" + /* @__PURE__ */ new Date()
  2129. });
  2130. log.error("缺少path参数" + /* @__PURE__ */ new Date());
  2131. return;
  2132. }
  2133. mainWindow.webContents.loadURL(decodeURIComponent(url2));
  2134. const isFocusOpenWin = handeGet("isFocusOpenWin");
  2135. if (isFocusOpenWin == 1) {
  2136. mainWindow.show();
  2137. mainWindow.setAlwaysOnTop(true);
  2138. }
  2139. res.send({
  2140. code: 200,
  2141. msg: "成功" + /* @__PURE__ */ new Date()
  2142. });
  2143. });
  2144. app.get("/iframe/:path", async (req, res) => {
  2145. const { path: path2 } = req.params;
  2146. if (!path2) {
  2147. res.send({
  2148. code: 10001,
  2149. msg: "缺少path参数" + /* @__PURE__ */ new Date()
  2150. });
  2151. log.error("缺少path参数" + /* @__PURE__ */ new Date());
  2152. return;
  2153. }
  2154. mainWindow.webContents.loadURL(decodeURIComponent(path2));
  2155. const isFocusOpenWin = handeGet("isFocusOpenWin");
  2156. if (isFocusOpenWin == 1) {
  2157. mainWindow.show();
  2158. mainWindow.setAlwaysOnTop(true);
  2159. }
  2160. res.send({
  2161. code: 200,
  2162. msg: "成功" + /* @__PURE__ */ new Date()
  2163. });
  2164. });
  2165. app.post("/iframe", async (req, res) => {
  2166. const body = req.body;
  2167. console.log("🚀 ~ app.get ~ req.body:", body);
  2168. const { path: path2 } = req.body;
  2169. if (!path2) {
  2170. res.send({
  2171. code: 10001,
  2172. msg: "缺少path参数" + /* @__PURE__ */ new Date()
  2173. });
  2174. log.error("缺少path参数" + /* @__PURE__ */ new Date());
  2175. return;
  2176. }
  2177. mainWindow.webContents.loadURL(decodeURIComponent(path2));
  2178. const isFocusOpenWin = handeGet("isFocusOpenWin");
  2179. if (isFocusOpenWin == 1) {
  2180. mainWindow.show();
  2181. mainWindow.setAlwaysOnTop(true);
  2182. }
  2183. res.send({
  2184. code: 200,
  2185. msg: "成功" + /* @__PURE__ */ new Date()
  2186. });
  2187. });
  2188. app.listen(3003, () => console.log("Example app listening on port 3003!"));
  2189. };
  2190. process.env["ELECTRON_DISABLE_SECURITY_WARNINGS"] = true;
  2191. if (!require$$0$4.app.requestSingleInstanceLock()) {
  2192. require$$0$4.app.quit();
  2193. process.exit(0);
  2194. } else {
  2195. require$$0$4.app.on("second-instance", (event, commandLine, workingDirectory) => {
  2196. if (mainWindow) {
  2197. if (mainWindow.isMinimized()) mainWindow.restore();
  2198. mainWindow.show();
  2199. mainWindow.focus();
  2200. }
  2201. });
  2202. }
  2203. require$$0$4.app.whenReady().then(() => {
  2204. AtLogin();
  2205. createWindow();
  2206. initTray();
  2207. initExpress();
  2208. });
  2209. const AtLogin = async () => {
  2210. if (require$$0$4.app.isPackaged) {
  2211. require$$0$4.app.setLoginItemSettings({
  2212. openAtLogin: true,
  2213. // 设置为 true 可以隐藏启动时的窗口
  2214. path: require$$0$4.app.getPath("exe"),
  2215. // 可选,指定要启动的应用路径
  2216. args: ["--openAsHidden"]
  2217. });
  2218. }
  2219. };
  2220. require$$0$4.app.on("activate", function() {
  2221. console.log("activate=====>");
  2222. const allWindows = require$$0$4.BrowserWindow.getAllWindows();
  2223. if (!allWindows.length) {
  2224. createWindow();
  2225. }
  2226. });
  2227. require$$0$4.app.on("window-all-closed", function() {
  2228. if (process.platform !== "darwin") require$$0$4.app.quit();
  2229. });
  2230. initIpcMain();
  2231. //# sourceMappingURL=index.js.map