@thirty-coder/electron-base-kit 0.2.2 → 0.3.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
@@ -84,6 +84,7 @@ createWindow({ id: 'settings', preload, renderer, width: 640, height: 480, remem
84
84
  "url": "https://dl.example.com/myapp"
85
85
  },
86
86
  "license": { "publicKey": "" },
87
+ "log": { "level": "info", "maxDays": 7, "console": true },
87
88
  "window": { "width": 1200, "height": 800, "minWidth": 900, "minHeight": 600, "remember": true, "ensureVisible": true }
88
89
  }
89
90
  ```
@@ -110,6 +111,35 @@ settings.filePath
110
111
 
111
112
  `bootstrap` 之后才能用,提前访问会抛错。
112
113
 
114
+ ## 日志
115
+
116
+ ```ts
117
+ import { logger } from '@thirty-coder/electron-base-kit'
118
+
119
+ logger.info('窗口已创建', { id: 'main' })
120
+ logger.warn('配置项缺失,使用默认值')
121
+ logger.error('写盘失败', err)
122
+
123
+ const log = logger.child('window')
124
+ log.debug('bounds 已保存', bounds)
125
+
126
+ logger.dir // <userData>/logs
127
+ logger.file // 当天文件绝对路径
128
+ await logger.exportTo('/tmp/logs.txt') // 所有日志拼成一个文件
129
+ ```
130
+
131
+ 写 `<userData>/logs/2026-12-04.log`,一行一条:
132
+
133
+ ```
134
+ 2026-12-04 11:57:10.123 INFO [window] 窗口已创建 {"id":"main"}
135
+ 2026-12-04 11:57:11.045 ERROR [settings] 写入失败 Error: EACCES: permission denied
136
+ at writeNow (...)
137
+ ```
138
+
139
+ 同步追加,崩溃前最后几条一定在文件里。按天换文件,启动时删掉超过 `maxDays` 天的。`Error` 会展开成 `name: message` 加堆栈,循环引用、BigInt 之类序列化失败降级成 `String`,不抛错。
140
+
141
+ `level` 默认打包后 `info`、开发时 `debug`;`console` 默认打包后关、开发时开。`warn` / `error` 无论配置都打终端。
142
+
113
143
  ## 升级
114
144
 
115
145
  ```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;
@@ -89,5 +114,5 @@ declare function createWindow(options: CreateWindowOptions): BrowserWindow;
89
114
  */
90
115
  declare function bootstrap(config: AppConfig): void;
91
116
 
92
- export { bootstrap, createWindow, settings };
93
- export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
117
+ export { bootstrap, createWindow, logger, settings };
118
+ export type { AppConfig, CreateWindowOptions, FeatureFlags, LicenseConfig, LogConfig, LogLevel, LoggerApi, SettingsApi, UpdateConfig, UpdateProvider, WindowConfig };
package/dist/index.js CHANGED
@@ -22,15 +22,153 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  bootstrap: () => bootstrap,
24
24
  createWindow: () => createWindow,
25
+ logger: () => logger,
25
26
  settings: () => settings
26
27
  });
27
28
  module.exports = __toCommonJS(index_exports);
28
29
 
29
- // src/settings.ts
30
+ // src/logger.ts
30
31
  var import_electron = require("electron");
31
32
  var import_node_fs = require("fs");
33
+ var import_promises = require("fs/promises");
32
34
  var import_node_path = require("path");
35
+ var LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
36
+ var FILE_PATTERN = /^\d{4}-\d{2}-\d{2}\.log$/;
37
+ var DAY = 24 * 60 * 60 * 1e3;
38
+ var dir = "";
39
+ var level = "info";
40
+ var consoleOn = true;
41
+ var initialized = false;
42
+ function pad(value, width = 2) {
43
+ return String(value).padStart(width, "0");
44
+ }
45
+ function dateStamp(date) {
46
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
47
+ }
48
+ function timeStamp(date) {
49
+ const time = `${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
50
+ return `${dateStamp(date)} ${time}.${pad(date.getMilliseconds(), 3)}`;
51
+ }
52
+ function currentFile() {
53
+ return dir ? (0, import_node_path.join)(dir, `${dateStamp(/* @__PURE__ */ new Date())}.log`) : "";
54
+ }
55
+ function formatExtra(args) {
56
+ if (args.length === 0) return "";
57
+ const parts = args.map((arg) => {
58
+ if (arg instanceof Error) {
59
+ const head = `${arg.name}: ${arg.message}`;
60
+ const lines = (arg.stack ?? "").split("\n").slice(1).filter((line) => line.trim() !== "").map((line) => ` ${line.trim()}`);
61
+ return lines.length > 0 ? [head, ...lines].join("\n") : head;
62
+ }
63
+ if (typeof arg === "string") return arg;
64
+ try {
65
+ return JSON.stringify(arg) ?? String(arg);
66
+ } catch {
67
+ return String(arg);
68
+ }
69
+ });
70
+ return ` ${parts.join(" ")}`;
71
+ }
72
+ function formatLine(at, tag, message, args) {
73
+ const tagPart = tag ? ` [${tag}]` : "";
74
+ return `${timeStamp(/* @__PURE__ */ new Date())} ${at.toUpperCase().padEnd(5)}${tagPart} ${message}${formatExtra(args)}
75
+ `;
76
+ }
77
+ function cleanOldFiles(maxDays) {
78
+ let names;
79
+ try {
80
+ names = (0, import_node_fs.readdirSync)(dir);
81
+ } catch {
82
+ return;
83
+ }
84
+ const cutoff = Date.now() - maxDays * DAY;
85
+ for (const name of names) {
86
+ if (!FILE_PATTERN.test(name)) continue;
87
+ const full = (0, import_node_path.join)(dir, name);
88
+ try {
89
+ if ((0, import_node_fs.statSync)(full).mtimeMs < cutoff) (0, import_node_fs.unlinkSync)(full);
90
+ } catch {
91
+ }
92
+ }
93
+ }
94
+ function emit(at, tag, message, args) {
95
+ if (LEVELS[at] < LEVELS[level]) return;
96
+ const line = formatLine(at, tag, message, args);
97
+ if (!initialized) {
98
+ console[at](`[logger not initialized] ${line.trimEnd()}`);
99
+ return;
100
+ }
101
+ try {
102
+ (0, import_node_fs.appendFileSync)(currentFile(), line);
103
+ } catch (err) {
104
+ console.error("[electron-base-kit] \u5199\u65E5\u5FD7\u5931\u8D25\uFF1A", err);
105
+ }
106
+ if (at === "warn" || at === "error" || consoleOn) {
107
+ console[at](line.trimEnd());
108
+ }
109
+ }
110
+ function initLogger(config) {
111
+ if (initialized) return;
112
+ const packaged = import_electron.app.isPackaged === true;
113
+ level = config?.level ?? (packaged ? "info" : "debug");
114
+ consoleOn = config?.console ?? !packaged;
115
+ dir = (0, import_node_path.join)(import_electron.app.getPath("userData"), "logs");
116
+ initialized = true;
117
+ try {
118
+ (0, import_node_fs.mkdirSync)(dir, { recursive: true });
119
+ } catch (err) {
120
+ console.error("[electron-base-kit] \u521B\u5EFA\u65E5\u5FD7\u76EE\u5F55\u5931\u8D25\uFF1A", err);
121
+ return;
122
+ }
123
+ cleanOldFiles(config?.maxDays ?? 7);
124
+ }
125
+ function createLogger(tag) {
126
+ return {
127
+ debug: (message, ...args) => emit("debug", tag, message, args),
128
+ info: (message, ...args) => emit("info", tag, message, args),
129
+ warn: (message, ...args) => emit("warn", tag, message, args),
130
+ error: (message, ...args) => emit("error", tag, message, args),
131
+ child(next) {
132
+ return createLogger(tag ? `${tag}:${next}` : next);
133
+ },
134
+ async exportTo(target) {
135
+ if (!initialized) {
136
+ throw new Error("logger \u672A\u521D\u59CB\u5316\uFF1A\u8BF7\u5148\u5728 app.whenReady() \u4E2D\u8C03\u7528 bootstrap(config)");
137
+ }
138
+ let names = [];
139
+ try {
140
+ names = (0, import_node_fs.readdirSync)(dir).filter((name) => FILE_PATTERN.test(name)).sort();
141
+ } catch {
142
+ names = [];
143
+ }
144
+ const chunks = [];
145
+ for (const name of names) {
146
+ try {
147
+ chunks.push((0, import_node_fs.readFileSync)((0, import_node_path.join)(dir, name), "utf8"));
148
+ } catch {
149
+ }
150
+ }
151
+ await (0, import_promises.writeFile)(target, chunks.join(""), "utf8");
152
+ },
153
+ get dir() {
154
+ return dir;
155
+ },
156
+ get file() {
157
+ return currentFile();
158
+ },
159
+ get level() {
160
+ return level;
161
+ }
162
+ };
163
+ }
164
+ var logger = createLogger("");
165
+
166
+ // src/settings.ts
167
+ var import_electron2 = require("electron");
168
+ var import_node_fs2 = require("fs");
169
+ var import_node_path2 = require("path");
33
170
  var WRITE_DELAY = 100;
171
+ var log = logger.child("settings");
34
172
  var store = null;
35
173
  var filePath = "";
36
174
  var dirty = false;
@@ -43,12 +181,12 @@ function assertInit() {
43
181
  return store;
44
182
  }
45
183
  function load() {
46
- if (!(0, import_node_fs.existsSync)(filePath)) return {};
184
+ if (!(0, import_node_fs2.existsSync)(filePath)) return {};
47
185
  let raw;
48
186
  try {
49
- raw = (0, import_node_fs.readFileSync)(filePath, "utf8");
187
+ raw = (0, import_node_fs2.readFileSync)(filePath, "utf8");
50
188
  } catch (err) {
51
- console.error("[electron-base-kit] \u8BFB\u53D6 settings \u5931\u8D25\uFF1A", err);
189
+ log.error("\u8BFB\u53D6 settings \u5931\u8D25", err);
52
190
  return {};
53
191
  }
54
192
  try {
@@ -58,11 +196,11 @@ function load() {
58
196
  }
59
197
  return parsed;
60
198
  } catch (err) {
61
- console.error("[electron-base-kit] settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863\uFF1A", err);
199
+ log.error("settings \u5185\u5BB9\u65E0\u6548\uFF0C\u5DF2\u6539\u540D\u7559\u6863", err);
62
200
  try {
63
- (0, import_node_fs.renameSync)(filePath, (0, import_node_path.join)((0, import_node_path.dirname)(filePath), "settings.bad.json"));
201
+ (0, import_node_fs2.renameSync)(filePath, (0, import_node_path2.join)((0, import_node_path2.dirname)(filePath), "settings.bad.json"));
64
202
  } catch (renameErr) {
65
- console.error("[electron-base-kit] \u7559\u6863\u5931\u8D25\uFF1A", renameErr);
203
+ log.error("\u7559\u6863\u5931\u8D25", renameErr);
66
204
  }
67
205
  return {};
68
206
  }
@@ -71,12 +209,12 @@ function writeNow() {
71
209
  if (!dirty || store === null) return;
72
210
  try {
73
211
  const tmp = `${filePath}.tmp`;
74
- (0, import_node_fs.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
212
+ (0, import_node_fs2.writeFileSync)(tmp, `${JSON.stringify(store, null, 2)}
75
213
  `);
76
- (0, import_node_fs.renameSync)(tmp, filePath);
214
+ (0, import_node_fs2.renameSync)(tmp, filePath);
77
215
  dirty = false;
78
216
  } catch (err) {
79
- console.error("[electron-base-kit] \u5199\u5165 settings \u5931\u8D25\uFF1A", err);
217
+ log.error("\u5199\u5165 settings \u5931\u8D25", err);
80
218
  }
81
219
  }
82
220
  function schedule() {
@@ -88,21 +226,21 @@ function schedule() {
88
226
  }, WRITE_DELAY);
89
227
  timer.unref?.();
90
228
  }
91
- function emit(key, value) {
229
+ function emit2(key, value) {
92
230
  const set = listeners.get(key);
93
231
  if (!set) return;
94
232
  for (const fn of [...set]) {
95
233
  try {
96
234
  fn(value);
97
235
  } catch (err) {
98
- console.error(`[electron-base-kit] settings.onChange(${key}) \u56DE\u8C03\u629B\u9519\uFF1A`, err);
236
+ log.error(`onChange(${key}) \u56DE\u8C03\u629B\u9519`, err);
99
237
  }
100
238
  }
101
239
  }
102
240
  function initSettings() {
103
241
  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 });
242
+ filePath = (0, import_node_path2.join)(import_electron2.app.getPath("userData"), "settings.json");
243
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)(filePath), { recursive: true });
106
244
  store = load();
107
245
  const flushNow = () => {
108
246
  if (timer) {
@@ -111,8 +249,8 @@ function initSettings() {
111
249
  }
112
250
  writeNow();
113
251
  };
114
- import_electron.app.on("before-quit", flushNow);
115
- import_electron.app.on("will-quit", flushNow);
252
+ import_electron2.app.on("before-quit", flushNow);
253
+ import_electron2.app.on("will-quit", flushNow);
116
254
  }
117
255
  var settings = {
118
256
  get(key, fallback) {
@@ -134,7 +272,7 @@ var settings = {
134
272
  if (previous === serialized) return;
135
273
  data[key] = value;
136
274
  schedule();
137
- emit(key, value);
275
+ emit2(key, value);
138
276
  },
139
277
  has(key) {
140
278
  const data = assertInit();
@@ -145,7 +283,7 @@ var settings = {
145
283
  if (!(key in data)) return;
146
284
  delete data[key];
147
285
  schedule();
148
- emit(key, void 0);
286
+ emit2(key, void 0);
149
287
  },
150
288
  all() {
151
289
  return { ...assertInit() };
@@ -180,7 +318,7 @@ var settings = {
180
318
  };
181
319
 
182
320
  // src/window.ts
183
- var import_electron2 = require("electron");
321
+ var import_electron3 = require("electron");
184
322
  var FALLBACK = { width: 1200, height: 800, minWidth: 900, minHeight: 600 };
185
323
  var VISIBLE_RATIO = 0.3;
186
324
  var SAVE_DELAY = 300;
@@ -205,9 +343,9 @@ function isBounds(value) {
205
343
  return bounds.width > 0 && bounds.height > 0;
206
344
  }
207
345
  function bestWorkArea(rect) {
208
- let best = import_electron2.screen.getPrimaryDisplay().workArea;
346
+ let best = import_electron3.screen.getPrimaryDisplay().workArea;
209
347
  let bestArea = 0;
210
- for (const display of import_electron2.screen.getAllDisplays()) {
348
+ for (const display of import_electron3.screen.getAllDisplays()) {
211
349
  const area = intersectArea(rect, display.workArea);
212
350
  if (area > bestArea) {
213
351
  bestArea = area;
@@ -217,7 +355,7 @@ function bestWorkArea(rect) {
217
355
  return best;
218
356
  }
219
357
  function centerOnPrimary(size) {
220
- const primary = import_electron2.screen.getPrimaryDisplay().workArea;
358
+ const primary = import_electron3.screen.getPrimaryDisplay().workArea;
221
359
  const width = Math.min(size.width, primary.width);
222
360
  const height = Math.min(size.height, primary.height);
223
361
  return {
@@ -298,8 +436,8 @@ function attachDisplayGuard(win) {
298
436
  guarded.add(win);
299
437
  if (!screenHooked) {
300
438
  screenHooked = true;
301
- import_electron2.screen.on("display-removed", guardAll);
302
- import_electron2.screen.on("display-metrics-changed", guardAll);
439
+ import_electron3.screen.on("display-removed", guardAll);
440
+ import_electron3.screen.on("display-metrics-changed", guardAll);
303
441
  }
304
442
  win.once("closed", () => {
305
443
  guarded.delete(win);
@@ -323,7 +461,7 @@ function createWindow(options) {
323
461
  settings.remove(`${key}.maximized`);
324
462
  }
325
463
  const { bounds, center } = resolveBounds(isBounds(saved) ? saved : void 0, size, ensureVisible);
326
- const win = new import_electron2.BrowserWindow({
464
+ const win = new import_electron3.BrowserWindow({
327
465
  ...bounds,
328
466
  minWidth,
329
467
  minHeight,
@@ -368,6 +506,7 @@ function assertConfig(config) {
368
506
  }
369
507
  function bootstrap(config) {
370
508
  assertConfig(config);
509
+ initLogger(config.log);
371
510
  initSettings();
372
511
  setWindowDefaults(config.window);
373
512
  if (config.features?.updater) {
@@ -393,5 +532,6 @@ function bootstrap(config) {
393
532
  0 && (module.exports = {
394
533
  bootstrap,
395
534
  createWindow,
535
+ logger,
396
536
  settings
397
537
  });
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.3.0",
4
4
  "description": "Electron 桌面应用基础能力",
5
5
  "license": "MIT",
6
6
  "repository": {