@thirty-coder/electron-base-kit 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -37,7 +37,7 @@ import { join } from 'node:path'
37
37
  import config from '../app.config.json'
38
38
 
39
39
  app.whenReady().then(() => {
40
- bootstrap(config)
40
+ if (!bootstrap(config)) return
41
41
 
42
42
  createWindow({
43
43
  preload: join(__dirname, '../preload/preload.js'),
@@ -48,6 +48,8 @@ app.whenReady().then(() => {
48
48
 
49
49
  框架不读配置文件,config 由项目传入。`preload`、`renderer` 必须是业务传的绝对路径,因为本包装在 `node_modules` 里拿不到业务的目录结构。
50
50
 
51
+ `bootstrap` 返回 `false` 表示已有实例在跑,本进程正在退出,直接 `return` 别建窗口。
52
+
51
53
  ## 窗口
52
54
 
53
55
  `createWindow` 接管了这些事:
@@ -65,6 +67,29 @@ createWindow({ id: 'settings', preload, renderer, width: 640, height: 480, remem
65
67
 
66
68
  不传 `id` 就是 `main`。窗口尺寸和开关默认读 `app.config.json` 的 `window`,只有需要和主窗口不同的窗口才在参数里覆盖。
67
69
 
70
+ ## 单实例
71
+
72
+ `bootstrap` 内部拿锁。二次启动时新进程直接退出,主进程收到 `second-instance` 后唤起 `main` 窗口:最小化就还原、隐藏就显示、然后聚焦。
73
+
74
+ 窗口引用和唤起:
75
+
76
+ ```ts
77
+ import { getWindow, focusWindow } from '@thirty-coder/electron-base-kit'
78
+
79
+ getWindow('main') // BrowserWindow | undefined
80
+ focusWindow('main') // 还原 + 显示 + 聚焦,返回是否找到
81
+ ```
82
+
83
+ 托盘、自动更新这些能力用 `getWindow` 拿主窗口。窗口已经关掉时返回 `undefined`,要重建就自己监听:
84
+
85
+ ```ts
86
+ app.on('second-instance', () => {
87
+ if (!getWindow('main')) createWindow({ preload, renderer })
88
+ })
89
+ ```
90
+
91
+ 锁以 `userData` 为界,改 `userData` 就能跑多个独立实例。macOS 上双击图标是系统保证单实例,验证本能力要用 `open -n`。
92
+
68
93
  ## 配置
69
94
 
70
95
  `app.config.json` 由业务项目维护,结构对应 `AppConfig` 类型:
@@ -84,6 +109,7 @@ createWindow({ id: 'settings', preload, renderer, width: 640, height: 480, remem
84
109
  "url": "https://dl.example.com/myapp"
85
110
  },
86
111
  "license": { "publicKey": "" },
112
+ "log": { "level": "info", "maxDays": 7, "console": true },
87
113
  "window": { "width": 1200, "height": 800, "minWidth": 900, "minHeight": 600, "remember": true, "ensureVisible": true }
88
114
  }
89
115
  ```
@@ -110,6 +136,35 @@ settings.filePath
110
136
 
111
137
  `bootstrap` 之后才能用,提前访问会抛错。
112
138
 
139
+ ## 日志
140
+
141
+ ```ts
142
+ import { logger } from '@thirty-coder/electron-base-kit'
143
+
144
+ logger.info('窗口已创建', { id: 'main' })
145
+ logger.warn('配置项缺失,使用默认值')
146
+ logger.error('写盘失败', err)
147
+
148
+ const log = logger.child('window')
149
+ log.debug('bounds 已保存', bounds)
150
+
151
+ logger.dir // <userData>/logs
152
+ logger.file // 当天文件绝对路径
153
+ await logger.exportTo('/tmp/logs.txt') // 所有日志拼成一个文件
154
+ ```
155
+
156
+ 写 `<userData>/logs/2026-12-04.log`,一行一条:
157
+
158
+ ```
159
+ 2026-12-04 11:57:10.123 INFO [window] 窗口已创建 {"id":"main"}
160
+ 2026-12-04 11:57:11.045 ERROR [settings] 写入失败 Error: EACCES: permission denied
161
+ at writeNow (...)
162
+ ```
163
+
164
+ 同步追加,崩溃前最后几条一定在文件里。按天换文件,启动时删掉超过 `maxDays` 天的。`Error` 会展开成 `name: message` 加堆栈,循环引用、BigInt 之类序列化失败降级成 `String`,不抛错。
165
+
166
+ `level` 默认打包后 `info`、开发时 `debug`;`console` 默认打包后关、开发时开。`warn` / `error` 无论配置都打终端。
167
+
113
168
  ## 升级
114
169
 
115
170
  ```bash
package/dist/index.d.ts CHANGED
@@ -26,6 +26,15 @@ interface LicenseConfig {
26
26
  /** 验签公钥,签发私钥不在此处 */
27
27
  publicKey: string;
28
28
  }
29
+ type LogLevel = 'debug' | 'info' | 'warn' | 'error';
30
+ interface LogConfig {
31
+ /** 默认打包后 info,开发时 debug */
32
+ level?: LogLevel;
33
+ /** 保留天数,启动时删掉更早的。默认 7 */
34
+ maxDays?: number;
35
+ /** 是否同时打到终端。默认开发时 true,打包后 false */
36
+ console?: boolean;
37
+ }
29
38
  interface WindowConfig {
30
39
  width?: number;
31
40
  height?: number;
@@ -45,9 +54,25 @@ interface AppConfig {
45
54
  features?: FeatureFlags;
46
55
  update?: UpdateConfig;
47
56
  license?: LicenseConfig;
57
+ log?: LogConfig;
48
58
  window?: WindowConfig;
49
59
  }
50
60
 
61
+ interface LoggerApi {
62
+ debug(message: string, ...args: unknown[]): void;
63
+ info(message: string, ...args: unknown[]): void;
64
+ warn(message: string, ...args: unknown[]): void;
65
+ error(message: string, ...args: unknown[]): void;
66
+ /** 加一个来源标签,文件、级别、配置共用同一份 */
67
+ child(tag: string): LoggerApi;
68
+ /** 把所有日志按时间顺序拼成一个文本文件 */
69
+ exportTo(target: string): Promise<void>;
70
+ readonly dir: string;
71
+ readonly file: string;
72
+ readonly level: LogLevel;
73
+ }
74
+ declare const logger: LoggerApi;
75
+
51
76
  type Listener = (value: unknown) => void;
52
77
  interface SettingsApi {
53
78
  get<T>(key: string, fallback: T): T;
@@ -61,6 +86,21 @@ interface SettingsApi {
61
86
  }
62
87
  declare const settings: SettingsApi;
63
88
 
89
+ interface SingleInstanceOptions {
90
+ /** 二次启动时唤起的窗口 id,默认 main。传 false 不自动唤起 */
91
+ windowId?: string | false;
92
+ }
93
+ /**
94
+ * 拿单实例锁。拿不到时本进程会被 quit,返回 false。
95
+ *
96
+ * 重复调用返回第一次的结果。必须在创建任何窗口之前调用。
97
+ */
98
+ declare function acquireSingleInstance(options?: SingleInstanceOptions): boolean;
99
+
100
+ /** 取窗口引用。已销毁的当作不存在。 */
101
+ declare function getWindow(id?: string): BrowserWindow | undefined;
102
+ /** 还原、显示、聚焦。窗口不存在时返回 false,不抛错。 */
103
+ declare function focusWindow(id?: string): boolean;
64
104
  interface CreateWindowOptions {
65
105
  /** preload 脚本绝对路径 */
66
106
  preload: string;
@@ -85,9 +125,10 @@ declare function createWindow(options: CreateWindowOptions): BrowserWindow;
85
125
  /**
86
126
  * 初始化框架。
87
127
  *
128
+ * 返回 false 表示已有实例持锁,本进程正在退出,业务不要再建窗口。
88
129
  * 常开能力初始化失败直接抛;可选能力失败只记错误,继续启动。
89
130
  */
90
- declare function bootstrap(config: AppConfig): void;
131
+ declare function bootstrap(config: AppConfig): boolean;
91
132
 
92
- export { bootstrap, createWindow, settings };
93
- export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
133
+ export { acquireSingleInstance, bootstrap, createWindow, focusWindow, getWindow, logger, settings };
134
+ export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, LogConfig, LogLevel, LoggerApi, SettingsApi, SingleInstanceOptions, UpdateConfig, UpdateProvider, WindowConfig };
package/dist/index.js CHANGED
@@ -20,17 +20,158 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
20
20
  // index.ts
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
+ acquireSingleInstance: () => acquireSingleInstance,
23
24
  bootstrap: () => bootstrap,
24
25
  createWindow: () => createWindow,
26
+ focusWindow: () => focusWindow,
27
+ getWindow: () => getWindow,
28
+ logger: () => logger,
25
29
  settings: () => settings
26
30
  });
27
31
  module.exports = __toCommonJS(index_exports);
28
32
 
29
- // src/settings.ts
33
+ // src/logger.ts
30
34
  var import_electron = require("electron");
31
35
  var import_node_fs = require("fs");
36
+ var import_promises = require("fs/promises");
32
37
  var import_node_path = require("path");
38
+ var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
39
+ var FILE_PATTERN = /^\d{4}-\d{2}-\d{2}\.log$/;
40
+ var DAY = 24 * 60 * 60 * 1e3;
41
+ var dir = "";
42
+ var level = "info";
43
+ var consoleOn = true;
44
+ var initialized = false;
45
+ function pad(value, width = 2) {
46
+ return String(value).padStart(width, "0");
47
+ }
48
+ function dateStamp(date) {
49
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
50
+ }
51
+ function timeStamp(date) {
52
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
53
+ return `${dateStamp(date)} ${time}.${pad(date.getMilliseconds(), 3)}`;
54
+ }
55
+ function currentFile() {
56
+ return dir ? (0, import_node_path.join)(dir, `${dateStamp(/* @__PURE__ */ new Date())}.log`) : "";
57
+ }
58
+ function formatExtra(args) {
59
+ if (args.length === 0) return "";
60
+ const parts = args.map((arg) => {
61
+ if (arg instanceof Error) {
62
+ const head = `${arg.name}: ${arg.message}`;
63
+ const lines = (arg.stack ?? "").split("\n").slice(1).filter((line) => line.trim() !== "").map((line) => ` ${line.trim()}`);
64
+ return lines.length > 0 ? [head, ...lines].join("\n") : head;
65
+ }
66
+ if (typeof arg === "string") return arg;
67
+ try {
68
+ return JSON.stringify(arg) ?? String(arg);
69
+ } catch {
70
+ return String(arg);
71
+ }
72
+ });
73
+ return ` ${parts.join(" ")}`;
74
+ }
75
+ function formatLine(at, tag, message, args) {
76
+ const tagPart = tag ? ` [${tag}]` : "";
77
+ return `${timeStamp(/* @__PURE__ */ new Date())} ${at.toUpperCase().padEnd(5)}${tagPart} ${message}${formatExtra(args)}
78
+ `;
79
+ }
80
+ function cleanOldFiles(maxDays) {
81
+ let names;
82
+ try {
83
+ names = (0, import_node_fs.readdirSync)(dir);
84
+ } catch {
85
+ return;
86
+ }
87
+ const cutoff = Date.now() - maxDays * DAY;
88
+ for (const name of names) {
89
+ if (!FILE_PATTERN.test(name)) continue;
90
+ const full = (0, import_node_path.join)(dir, name);
91
+ try {
92
+ if ((0, import_node_fs.statSync)(full).mtimeMs < cutoff) (0, import_node_fs.unlinkSync)(full);
93
+ } catch {
94
+ }
95
+ }
96
+ }
97
+ function emit(at, tag, message, args) {
98
+ if (LEVELS[at] < LEVELS[level]) return;
99
+ const line = formatLine(at, tag, message, args);
100
+ if (!initialized) {
101
+ console[at](`[logger not initialized] ${line.trimEnd()}`);
102
+ return;
103
+ }
104
+ try {
105
+ (0, import_node_fs.appendFileSync)(currentFile(), line);
106
+ } catch (err) {
107
+ console.error("[electron-base-kit] \u5199\u65E5\u5FD7\u5931\u8D25\uFF1A", err);
108
+ }
109
+ if (at === "warn" || at === "error" || consoleOn) {
110
+ console[at](line.trimEnd());
111
+ }
112
+ }
113
+ function initLogger(config) {
114
+ if (initialized) return;
115
+ const packaged = import_electron.app.isPackaged === true;
116
+ level = config?.level ?? (packaged ? "info" : "debug");
117
+ consoleOn = config?.console ?? !packaged;
118
+ dir = (0, import_node_path.join)(import_electron.app.getPath("userData"), "logs");
119
+ initialized = true;
120
+ try {
121
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
122
+ } catch (err) {
123
+ console.error("[electron-base-kit] \u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55\u5931\u8D25\uFF1A", err);
124
+ return;
125
+ }
126
+ cleanOldFiles(config?.maxDays ?? 7);
127
+ }
128
+ function createLogger(tag) {
129
+ return {
130
+ debug: (message, ...args) => emit("debug", tag, message, args),
131
+ info: (message, ...args) => emit("info", tag, message, args),
132
+ warn: (message, ...args) => emit("warn", tag, message, args),
133
+ error: (message, ...args) => emit("error", tag, message, args),
134
+ child(next) {
135
+ return createLogger(tag ? `${tag}:${next}` : next);
136
+ },
137
+ async exportTo(target) {
138
+ if (!initialized) {
139
+ throw new Error("logger \u672A\u521D\u59CB\u5316\uFF1A\u8BF7\u5148\u5728 app.whenReady() \u4E2D\u8C03\u7528 bootstrap(config)");
140
+ }
141
+ let names = [];
142
+ try {
143
+ names = (0, import_node_fs.readdirSync)(dir).filter((name) => FILE_PATTERN.test(name)).sort();
144
+ } catch {
145
+ names = [];
146
+ }
147
+ const chunks = [];
148
+ for (const name of names) {
149
+ try {
150
+ chunks.push((0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, name), "utf8"));
151
+ } catch {
152
+ }
153
+ }
154
+ await (0, import_promises.writeFile)(target, chunks.join(""), "utf8");
155
+ },
156
+ get dir() {
157
+ return dir;
158
+ },
159
+ get file() {
160
+ return currentFile();
161
+ },
162
+ get level() {
163
+ return level;
164
+ }
165
+ };
166
+ }
167
+ var logger = createLogger("");
168
+
169
+ // src/settings.ts
170
+ var import_electron2 = require("electron");
171
+ var import_node_fs2 = require("fs");
172
+ var import_node_path2 = require("path");
33
173
  var WRITE_DELAY = 100;
174
+ var log = logger.child("settings");
34
175
  var store = null;
35
176
  var filePath = "";
36
177
  var dirty = false;
@@ -43,12 +184,12 @@ function assertInit() {
43
184
  return store;
44
185
  }
45
186
  function load() {
46
- if (!(0, import_node_fs.existsSync)(filePath)) return {};
187
+ if (!(0, import_node_fs2.existsSync)(filePath)) return {};
47
188
  let raw;
48
189
  try {
49
- raw = (0, import_node_fs.readFileSync)(filePath, "utf8");
190
+ raw = (0, import_node_fs2.readFileSync)(filePath, "utf8");
50
191
  } catch (err) {
51
- console.error("[electron-base-kit] \u8BFB\u53D6 settings \u5931\u8D25\uFF1A", err);
192
+ log.error("\u8BFB\u53D6 settings \u5931\u8D25", err);
52
193
  return {};
53
194
  }
54
195
  try {
@@ -58,11 +199,11 @@ function load() {
58
199
  }
59
200
  return parsed;
60
201
  } catch (err) {
61
- console.error("[electron-base-kit] settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863\uFF1A", err);
202
+ log.error("settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863", err);
62
203
  try {
63
- (0, import_node_fs.renameSync)(filePath, (0, import_node_path.join)((0, import_node_path.dirname)(filePath), "settings.bad.json"));
204
+ (0, import_node_fs2.renameSync)(filePath, (0, import_node_path2.join)((0, import_node_path2.dirname)(filePath), "settings.bad.json"));
64
205
  } catch (renameErr) {
65
- console.error("[electron-base-kit] \u7559\u6863\u5931\u8D25\uFF1A", renameErr);
206
+ log.error("\u7559\u6863\u5931\u8D25", renameErr);
66
207
  }
67
208
  return {};
68
209
  }
@@ -71,12 +212,12 @@ function writeNow() {
71
212
  if (!dirty || store === null) return;
72
213
  try {
73
214
  const tmp = `${filePath}.tmp`;
74
- (0, import_node_fs.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
215
+ (0, import_node_fs2.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
75
216
  `);
76
- (0, import_node_fs.renameSync)(tmp, filePath);
217
+ (0, import_node_fs2.renameSync)(tmp, filePath);
77
218
  dirty = false;
78
219
  } catch (err) {
79
- console.error("[electron-base-kit] \u5199\u5165 settings \u5931\u8D25\uFF1A", err);
220
+ log.error("\u5199\u5165 settings \u5931\u8D25", err);
80
221
  }
81
222
  }
82
223
  function schedule() {
@@ -88,21 +229,21 @@ function schedule() {
88
229
  }, WRITE_DELAY);
89
230
  timer.unref?.();
90
231
  }
91
- function emit(key, value) {
232
+ function emit2(key, value) {
92
233
  const set = listeners.get(key);
93
234
  if (!set) return;
94
235
  for (const fn of [...set]) {
95
236
  try {
96
237
  fn(value);
97
238
  } catch (err) {
98
- console.error(`[electron-base-kit] settings.onChange(${key}) \u56DE\u8C03\u629B\u9519\uFF1A`, err);
239
+ log.error(`onChange(${key}) \u56DE\u8C03\u629B\u9519`, err);
99
240
  }
100
241
  }
101
242
  }
102
243
  function initSettings() {
103
244
  if (store !== null) return;
104
- filePath = (0, import_node_path.join)(import_electron.app.getPath("userData"), "settings.json");
105
- (0, import_node_fs.mkdirSync)((0, import_node_path.dirname)(filePath), { recursive: true });
245
+ filePath = (0, import_node_path2.join)(import_electron2.app.getPath("userData"), "settings.json");
246
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(filePath), { recursive: true });
106
247
  store = load();
107
248
  const flushNow = () => {
108
249
  if (timer) {
@@ -111,8 +252,8 @@ function initSettings() {
111
252
  }
112
253
  writeNow();
113
254
  };
114
- import_electron.app.on("before-quit", flushNow);
115
- import_electron.app.on("will-quit", flushNow);
255
+ import_electron2.app.on("before-quit", flushNow);
256
+ import_electron2.app.on("will-quit", flushNow);
116
257
  }
117
258
  var settings = {
118
259
  get(key, fallback) {
@@ -134,7 +275,7 @@ var settings = {
134
275
  if (previous === serialized) return;
135
276
  data[key] = value;
136
277
  schedule();
137
- emit(key, value);
278
+ emit2(key, value);
138
279
  },
139
280
  has(key) {
140
281
  const data = assertInit();
@@ -145,7 +286,7 @@ var settings = {
145
286
  if (!(key in data)) return;
146
287
  delete data[key];
147
288
  schedule();
148
- emit(key, void 0);
289
+ emit2(key, void 0);
149
290
  },
150
291
  all() {
151
292
  return { ...assertInit() };
@@ -179,15 +320,36 @@ var settings = {
179
320
  }
180
321
  };
181
322
 
323
+ // src/single-instance.ts
324
+ var import_electron4 = require("electron");
325
+
182
326
  // src/window.ts
183
- var import_electron2 = require("electron");
327
+ var import_electron3 = require("electron");
184
328
  var FALLBACK = { width: 1200, height: 800, minWidth: 900, minHeight: 600 };
185
329
  var VISIBLE_RATIO = 0.3;
186
330
  var SAVE_DELAY = 300;
187
331
  var defaults = {};
332
+ var registry = /* @__PURE__ */ new Map();
188
333
  function setWindowDefaults(config) {
189
334
  defaults = config ?? {};
190
335
  }
336
+ function getWindow(id = "main") {
337
+ const win = registry.get(id);
338
+ if (!win) return void 0;
339
+ if (win.isDestroyed()) {
340
+ registry.delete(id);
341
+ return void 0;
342
+ }
343
+ return win;
344
+ }
345
+ function focusWindow(id = "main") {
346
+ const win = getWindow(id);
347
+ if (!win) return false;
348
+ if (win.isMinimized()) win.restore();
349
+ win.show();
350
+ win.focus();
351
+ return true;
352
+ }
191
353
  function clamp(value, min, max) {
192
354
  return Math.min(Math.max(value, min), max);
193
355
  }
@@ -205,9 +367,9 @@ function isBounds(value) {
205
367
  return bounds.width > 0 && bounds.height > 0;
206
368
  }
207
369
  function bestWorkArea(rect) {
208
- let best = import_electron2.screen.getPrimaryDisplay().workArea;
370
+ let best = import_electron3.screen.getPrimaryDisplay().workArea;
209
371
  let bestArea = 0;
210
- for (const display of import_electron2.screen.getAllDisplays()) {
372
+ for (const display of import_electron3.screen.getAllDisplays()) {
211
373
  const area = intersectArea(rect, display.workArea);
212
374
  if (area > bestArea) {
213
375
  bestArea = area;
@@ -217,7 +379,7 @@ function bestWorkArea(rect) {
217
379
  return best;
218
380
  }
219
381
  function centerOnPrimary(size) {
220
- const primary = import_electron2.screen.getPrimaryDisplay().workArea;
382
+ const primary = import_electron3.screen.getPrimaryDisplay().workArea;
221
383
  const width = Math.min(size.width, primary.width);
222
384
  const height = Math.min(size.height, primary.height);
223
385
  return {
@@ -298,8 +460,8 @@ function attachDisplayGuard(win) {
298
460
  guarded.add(win);
299
461
  if (!screenHooked) {
300
462
  screenHooked = true;
301
- import_electron2.screen.on("display-removed", guardAll);
302
- import_electron2.screen.on("display-metrics-changed", guardAll);
463
+ import_electron3.screen.on("display-removed", guardAll);
464
+ import_electron3.screen.on("display-metrics-changed", guardAll);
303
465
  }
304
466
  win.once("closed", () => {
305
467
  guarded.delete(win);
@@ -323,7 +485,7 @@ function createWindow(options) {
323
485
  settings.remove(`${key}.maximized`);
324
486
  }
325
487
  const { bounds, center } = resolveBounds(isBounds(saved) ? saved : void 0, size, ensureVisible);
326
- const win = new import_electron2.BrowserWindow({
488
+ const win = new import_electron3.BrowserWindow({
327
489
  ...bounds,
328
490
  minWidth,
329
491
  minHeight,
@@ -351,9 +513,33 @@ function createWindow(options) {
351
513
  }
352
514
  if (remember) attachPersistence(win, key);
353
515
  if (ensureVisible) attachDisplayGuard(win);
516
+ registry.set(id, win);
517
+ win.once("closed", () => {
518
+ if (registry.get(id) === win) registry.delete(id);
519
+ });
354
520
  return win;
355
521
  }
356
522
 
523
+ // src/single-instance.ts
524
+ var log2 = logger.child("single-instance");
525
+ var locked = null;
526
+ function acquireSingleInstance(options = {}) {
527
+ if (locked !== null) return locked;
528
+ const windowId = options.windowId ?? "main";
529
+ locked = import_electron4.app.requestSingleInstanceLock();
530
+ if (!locked) {
531
+ log2.info("\u5DF2\u6709\u5B9E\u4F8B\u5728\u8FD0\u884C\uFF0C\u672C\u8FDB\u7A0B\u9000\u51FA");
532
+ import_electron4.app.quit();
533
+ return false;
534
+ }
535
+ import_electron4.app.on("second-instance", (_event, argv, workingDirectory) => {
536
+ log2.info("\u68C0\u6D4B\u5230\u4E8C\u6B21\u542F\u52A8", { cwd: workingDirectory });
537
+ log2.debug("\u4E8C\u6B21\u542F\u52A8\u53C2\u6570", { argv: argv.slice(1) });
538
+ if (windowId) focusWindow(windowId);
539
+ });
540
+ return true;
541
+ }
542
+
357
543
  // src/bootstrap.ts
358
544
  function assertConfig(config) {
359
545
  if (!config || typeof config !== "object") {
@@ -368,6 +554,8 @@ function assertConfig(config) {
368
554
  }
369
555
  function bootstrap(config) {
370
556
  assertConfig(config);
557
+ initLogger(config.log);
558
+ if (!acquireSingleInstance()) return false;
371
559
  initSettings();
372
560
  setWindowDefaults(config.window);
373
561
  if (config.features?.updater) {
@@ -388,10 +576,15 @@ function bootstrap(config) {
388
576
  }
389
577
  if (config.features?.deeplink) {
390
578
  }
579
+ return true;
391
580
  }
392
581
  // Annotate the CommonJS export names for ESM import in node:
393
582
  0 && (module.exports = {
583
+ acquireSingleInstance,
394
584
  bootstrap,
395
585
  createWindow,
586
+ focusWindow,
587
+ getWindow,
588
+ logger,
396
589
  settings
397
590
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thirty-coder/electron-base-kit",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "description": "Electron 桌面应用基础能力",
5
5
  "license": "MIT",
6
6
  "repository": {