@morlay/zephyr-desktop-shell 0.0.0-stage → 0.2.0-alpha.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.
@@ -0,0 +1,402 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ // src/window.ts
4
+ /** 缺省尺寸:够放下侧栏与一栏对话(也是第一次启动的尺寸)。 */
5
+ const DEFAULT_WINDOW_SIZE = {
6
+ width: 1280,
7
+ height: 800
8
+ };
9
+ /** 缺省最小尺寸。 */
10
+ const DEFAULT_MIN_SIZE = {
11
+ minWidth: 800,
12
+ minHeight: 600
13
+ };
14
+ /**
15
+ * 按平台给窗口外观:**无标题栏**,窗口内容顶到顶边。
16
+ *
17
+ * macOS 保留红绿灯(`hiddenInset` + 指定内缩),左侧栏因此要给顶部留白(页面侧按
18
+ * `document.documentElement.dataset.titlebar` 折叠);Windows 用 `titleBarOverlay`。
19
+ * @param platform - 平台(注入以便测三个平台)。
20
+ * @returns 外观选项。
21
+ */
22
+ function windowFrameOf(platform) {
23
+ if (platform === "darwin") return {
24
+ titleBarStyle: "hiddenInset",
25
+ trafficLightPosition: {
26
+ x: 16,
27
+ y: 18
28
+ },
29
+ vibrancy: "sidebar",
30
+ visualEffectState: "active",
31
+ backgroundColor: "#00000000"
32
+ };
33
+ if (platform === "win32") return {
34
+ frame: false,
35
+ titleBarOverlay: {
36
+ color: "#00000000",
37
+ symbolColor: "#e5e5e5",
38
+ height: 40
39
+ },
40
+ backgroundColor: "#111111"
41
+ };
42
+ return {
43
+ frame: false,
44
+ backgroundColor: "#111111"
45
+ };
46
+ }
47
+ /**
48
+ * 从配置与上次关窗的状态推导窗口选项。
49
+ *
50
+ * `nodeIntegration: false` + `contextIsolation: true` 不是保守,是**必须**:页面来自 dev server
51
+ * (打包形态也走它),内容里跑的是客户端的整棵 React 树,给渲染进程 node 权限等于把宿主的文件系统交出去。
52
+ * @param desktop - 配置里的 `desktop` 段(可能没有 `window`)。
53
+ * @param platform - 平台(注入以便测三个平台)。
54
+ * @param sizing - preload 路径与上次关窗的状态。
55
+ * @returns 窗口选项。
56
+ */
57
+ function windowOptionsOf(desktop, platform = process.platform, sizing = {}) {
58
+ const window = desktop?.window;
59
+ const bounds = sizing.state?.bounds;
60
+ return {
61
+ ...windowFrameOf(platform),
62
+ ...bounds === void 0 ? {} : {
63
+ x: bounds.x,
64
+ y: bounds.y
65
+ },
66
+ width: bounds?.width ?? window?.width ?? DEFAULT_WINDOW_SIZE.width,
67
+ height: bounds?.height ?? window?.height ?? DEFAULT_WINDOW_SIZE.height,
68
+ minWidth: window?.minWidth ?? DEFAULT_MIN_SIZE.minWidth,
69
+ minHeight: window?.minHeight ?? DEFAULT_MIN_SIZE.minHeight,
70
+ show: false,
71
+ webPreferences: {
72
+ contextIsolation: true,
73
+ nodeIntegration: false,
74
+ sandbox: false,
75
+ ...sizing.preload === void 0 ? {} : { preload: sizing.preload }
76
+ }
77
+ };
78
+ }
79
+ // src/window-state.ts
80
+ /** 状态文件名(在 `userData` 下)。 */
81
+ const WINDOW_STATE_FILE = "window-state.json";
82
+ /**
83
+ * 从存档与当前显示器算出这次要用的窗口状态。
84
+ *
85
+ * 存档是**外部输入**(上一个版本的进程写的文件),形状不可信:坏掉就当没有存档。
86
+ * @param saved - 存档内容(`loadWindowState` 的原样返回,或 `undefined`)。
87
+ * @param workArea - 主显示器的可用区域。
88
+ * @param fallback - 配置给的初始尺寸(第一次启动用)。
89
+ * @returns 已夹进工作区的状态。
90
+ */
91
+ function windowStateOf(saved, workArea, fallback) {
92
+ const bounds = boundsOf(saved);
93
+ if (bounds === void 0) return {
94
+ bounds: centered(fallback, workArea),
95
+ maximized: false
96
+ };
97
+ return {
98
+ bounds: clampInto(bounds, workArea),
99
+ maximized: maximizedOf(saved)
100
+ };
101
+ }
102
+ /**
103
+ * 读 `userData` 里的存档(原样返回:形状由 {@link windowStateOf} 判)。
104
+ * @param userData - `userData` 目录。
105
+ * @returns 解析后的 JSON,或 `undefined`(没有文件 / 不是 JSON)。
106
+ */
107
+ async function loadWindowState(userData) {
108
+ const raw = await readFile(join(userData, WINDOW_STATE_FILE), "utf8").catch(() => void 0);
109
+ if (raw === void 0) return void 0;
110
+ try {
111
+ return JSON.parse(raw);
112
+ } catch {
113
+ return;
114
+ }
115
+ }
116
+ /**
117
+ * 写回存档(写不了就算了:下次启动回到配置尺寸,不是功能故障)。
118
+ * @param userData - `userData` 目录。
119
+ * @param state - 关窗时的状态。
120
+ * @returns 写完成。
121
+ */
122
+ async function saveWindowState(userData, state) {
123
+ await writeFile(join(userData, WINDOW_STATE_FILE), `${JSON.stringify(state, null, 2)}\n`, "utf8").catch(() => void 0);
124
+ }
125
+ /**
126
+ * 取存档里的矩形(四项都得是有限数且宽高为正)。
127
+ * @param saved - 存档内容。
128
+ * @returns 矩形,或 `undefined`(形状不成立)。
129
+ */
130
+ function boundsOf(saved) {
131
+ if (typeof saved !== "object" || saved === null) return void 0;
132
+ const bounds = saved.bounds;
133
+ if (typeof bounds !== "object" || bounds === null) return void 0;
134
+ const { x, y, width, height } = bounds;
135
+ if (!isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height)) return void 0;
136
+ if (width <= 0 || height <= 0) return void 0;
137
+ return {
138
+ x,
139
+ y,
140
+ width,
141
+ height
142
+ };
143
+ }
144
+ /**
145
+ * @param saved - 存档内容。
146
+ * @returns 存档里的最大化标记(缺省 `false`)。
147
+ */
148
+ function maximizedOf(saved) {
149
+ if (typeof saved !== "object" || saved === null) return false;
150
+ return saved.maximized === true;
151
+ }
152
+ /**
153
+ * 把矩形夹进工作区:窗口整个落在可见区域内(换显示器 / 拔掉外接屏之后都还在眼前)。
154
+ * @param bounds - 存档里的矩形。
155
+ * @param area - 主显示器的可用区域。
156
+ * @returns 夹好的矩形。
157
+ */
158
+ function clampInto(bounds, area) {
159
+ const width = Math.min(bounds.width, area.width);
160
+ const height = Math.min(bounds.height, area.height);
161
+ return {
162
+ x: Math.min(Math.max(bounds.x, area.x), area.x + area.width - width),
163
+ y: Math.min(Math.max(bounds.y, area.y), area.y + area.height - height),
164
+ width,
165
+ height
166
+ };
167
+ }
168
+ /**
169
+ * 第一次启动:用配置尺寸,在工作区里居中(与不给 `x/y` 时 Electron 自己的居中一致)。
170
+ * @param size - 配置给的尺寸。
171
+ * @param area - 主显示器的可用区域。
172
+ * @returns 居中后的矩形。
173
+ */
174
+ function centered(size, area) {
175
+ const width = Math.min(size.width, area.width);
176
+ const height = Math.min(size.height, area.height);
177
+ return {
178
+ x: Math.round(area.x + (area.width - width) / 2),
179
+ y: Math.round(area.y + (area.height - height) / 2),
180
+ width,
181
+ height
182
+ };
183
+ }
184
+ /**
185
+ * @param value - 待判的值。
186
+ * @returns 是不是有限数。
187
+ */
188
+ function isNumber(value) {
189
+ return typeof value === "number" && Number.isFinite(value);
190
+ }
191
+ // src/menu.ts
192
+ /** 「开发者模式」的快捷键(`CmdOrCtrl` 在两个平台上就是 ⌘⇧D / Ctrl+Shift+D)。 */
193
+ const DEV_MODE_ACCELERATOR = "CmdOrCtrl+Shift+D";
194
+ /** 分隔线。 */
195
+ const SEPARATOR = { type: "separator" };
196
+ /**
197
+ * 按平台、开发者模式与 Inspector 状态给出菜单模板。
198
+ * @param input - 平台、应用名、开发者模式、Inspector 状态与点击回调。
199
+ * @returns 顶层菜单项(可直接交给 `Menu.buildFromTemplate`)。
200
+ */
201
+ function menuTemplateOf(input) {
202
+ const menus = [
203
+ {
204
+ label: "编辑",
205
+ submenu: editMenu()
206
+ },
207
+ {
208
+ label: "视图",
209
+ submenu: viewMenu(input)
210
+ },
211
+ {
212
+ label: "窗口",
213
+ submenu: windowMenu()
214
+ }
215
+ ];
216
+ if (input.platform !== "darwin") return menus;
217
+ return [{
218
+ label: input.appName,
219
+ submenu: appMenu()
220
+ }, ...menus];
221
+ }
222
+ /**
223
+ * @returns 应用菜单(macOS)。
224
+ */
225
+ function appMenu() {
226
+ return [
227
+ { role: "about" },
228
+ SEPARATOR,
229
+ { role: "services" },
230
+ SEPARATOR,
231
+ { role: "hide" },
232
+ { role: "hideOthers" },
233
+ { role: "unhide" },
234
+ SEPARATOR,
235
+ { role: "quit" }
236
+ ];
237
+ }
238
+ /**
239
+ * @returns 编辑菜单(全是 role:剪贴板的规则不自己实现)。
240
+ */
241
+ function editMenu() {
242
+ return [
243
+ { role: "undo" },
244
+ { role: "redo" },
245
+ SEPARATOR,
246
+ { role: "cut" },
247
+ { role: "copy" },
248
+ { role: "paste" },
249
+ { role: "pasteAndMatchStyle" },
250
+ { role: "delete" },
251
+ { role: "selectAll" }
252
+ ];
253
+ }
254
+ /**
255
+ * @param input - 开发者模式与 Inspector 状态(点击回调从这里透给自造项)。
256
+ * @returns 视图菜单:开发者模式关着时开发项整体收起,开关本身一直在最底下。
257
+ */
258
+ function viewMenu(input) {
259
+ const dev = input.debug ? [
260
+ { role: "reload" },
261
+ { role: "forceReload" },
262
+ { role: "toggleDevTools" },
263
+ SEPARATOR,
264
+ ...inspectorMenu(input.inspector ?? { opened: false }, input.on),
265
+ SEPARATOR
266
+ ] : [];
267
+ const devMode = {
268
+ label: "开发者模式",
269
+ type: "checkbox",
270
+ checked: input.debug,
271
+ accelerator: DEV_MODE_ACCELERATOR,
272
+ ...input.on === void 0 ? {} : { click: input.on.toggleDevMode }
273
+ };
274
+ return [
275
+ ...dev,
276
+ { role: "resetZoom" },
277
+ { role: "zoomIn" },
278
+ { role: "zoomOut" },
279
+ SEPARATOR,
280
+ { role: "togglefullscreen" },
281
+ SEPARATOR,
282
+ devMode
283
+ ];
284
+ }
285
+ /**
286
+ * @param inspector - Inspector 的状态(勾选 / 地址 / 打不开过)。
287
+ * @param on - 点击回调。
288
+ * @returns 开发项里与 Inspector 有关的两项。
289
+ */
290
+ function inspectorMenu(inspector, on) {
291
+ const failed = inspector.failed === true;
292
+ return [{
293
+ label: "打开主进程 Inspector",
294
+ type: "checkbox",
295
+ checked: inspector.opened,
296
+ enabled: !failed,
297
+ ...on === void 0 ? {} : { click: on.toggleInspector }
298
+ }, {
299
+ label: "复制 Inspector 地址",
300
+ enabled: !failed && inspector.address !== void 0,
301
+ ...on === void 0 ? {} : { click: on.copyInspectorAddress }
302
+ }];
303
+ }
304
+ /**
305
+ * @returns 窗口菜单(关窗走这里:快捷键录制期间壳会把菜单快捷键让给页面)。
306
+ */
307
+ function windowMenu() {
308
+ return [
309
+ { role: "minimize" },
310
+ { role: "zoom" },
311
+ SEPARATOR,
312
+ { role: "close" }
313
+ ];
314
+ }
315
+ // src/navigation.ts
316
+ /** 交给系统浏览器的 scheme(页面自己的源走 allow,不走这里)。 */
317
+ const EXTERNAL_PROTOCOLS = /* @__PURE__ */ new Set([
318
+ "http:",
319
+ "https:",
320
+ "mailto:"
321
+ ]);
322
+ /**
323
+ * 判一次跳转。
324
+ * @param target - 目标 URL(可以是相对路径)。
325
+ * @param origin - 页面自己的源(`http://127.0.0.1:<port>`)。
326
+ * @returns 处理方式。
327
+ */
328
+ function navigationPlanOf(target, origin) {
329
+ const base = urlOf(origin);
330
+ const url = urlOf(target, origin);
331
+ if (base === void 0 || url === void 0) return { kind: "deny" };
332
+ if (url.origin === base.origin) return { kind: "allow" };
333
+ if (EXTERNAL_PROTOCOLS.has(url.protocol)) return {
334
+ kind: "external",
335
+ url: url.href
336
+ };
337
+ return { kind: "deny" };
338
+ }
339
+ /**
340
+ * @param target - 目标 URL。
341
+ * @param base - 相对路径的基准(缺省不解析相对路径)。
342
+ * @returns URL,或 `undefined`(解析不出来)。
343
+ */
344
+ function urlOf(target, base) {
345
+ try {
346
+ return base === void 0 ? new URL(target) : new URL(target, base);
347
+ } catch {
348
+ return;
349
+ }
350
+ }
351
+ // src/single-instance.ts
352
+ /**
353
+ * 把已有窗口抬到前台(最小化时先恢复——`focus()` 对最小化窗口无效)。
354
+ * @param target - 当前窗口。
355
+ * @returns 是否聚焦到了一个活着的窗口。
356
+ */
357
+ function focusWindowOf(target) {
358
+ if (target === void 0 || target.isDestroyed()) return "none";
359
+ if (target.isMinimized()) target.restore();
360
+ target.show();
361
+ target.focus();
362
+ return "focused";
363
+ }
364
+ // src/debug.ts
365
+ /**
366
+ * 造调试面:只读投影,不持有状态。
367
+ * @param source - 开发者模式(读它的 `enabled`)。
368
+ * @returns 调试面。
369
+ */
370
+ function shellDebugOf(source) {
371
+ return {
372
+ get enabled() {
373
+ return source.enabled;
374
+ },
375
+ log: (message) => {
376
+ if (source.enabled) process.stderr.write(`[shell] ${message}\n`);
377
+ },
378
+ fail: (message) => process.stderr.write(`[shell] ${message}\n`),
379
+ renderer: (message) => {
380
+ if (source.enabled) process.stderr.write(`[renderer] ${message}\n`);
381
+ }
382
+ };
383
+ }
384
+ // src/deployment-line.ts
385
+ /**
386
+ * 拼启动那一行(字段顺序固定:mode / workspace / profileDir / dataDir / dataDirSpec / userData / packaged)。
387
+ * @param input - 形态、部署值与 userData。
388
+ * @returns 一行的文本(含 `[desktop-shell]` 前缀,不换行)。
389
+ */
390
+ function deploymentLineOf(input) {
391
+ return [
392
+ "[desktop-shell]",
393
+ `mode=${input.form}`,
394
+ `workspace=${input.mode.workspace}`,
395
+ `profileDir=${input.mode.profileDir}`,
396
+ `dataDir=${input.mode.dataDir}`,
397
+ `dataDirSpec=${input.mode.dataDirSpec}`,
398
+ `userData=${input.userData ?? "?"}`,
399
+ `packaged=${input.packaged ? "1" : "0"}`
400
+ ].join(" ");
401
+ }
402
+ export { menuTemplateOf as a, saveWindowState as c, windowFrameOf as d, windowOptionsOf as f, navigationPlanOf as i, windowStateOf as l, shellDebugOf as n, WINDOW_STATE_FILE as o, focusWindowOf as r, loadWindowState as s, deploymentLineOf as t, DEFAULT_WINDOW_SIZE as u };
@@ -0,0 +1,40 @@
1
+ import { appendFile, mkdir } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join } from "node:path";
4
+ // src/failure.ts
5
+ /** 日志目录(macOS 的习惯位置;不依赖 Electron 的 app 生命周期)。 */
6
+ function logDir() {
7
+ if (process.platform === "darwin") return join(homedir(), "Library", "Logs", "zephyr-desktop");
8
+ if (process.platform === "win32") return join(process.env.LOCALAPPDATA ?? homedir(), "zephyr-desktop", "logs");
9
+ return join(process.env.XDG_STATE_HOME ?? join(homedir(), ".local", "state"), "zephyr-desktop");
10
+ }
11
+ /**
12
+ * 记一条生命周期事件(**始终落文件**:打包形态没有 stderr,出问题只剩这条线)。
13
+ * @param stage - 阶段名。
14
+ * @param detail - 细节(可选)。
15
+ * @returns 记录完成。
16
+ */
17
+ async function reportEvent(stage, detail) {
18
+ try {
19
+ const dir = logDir();
20
+ await mkdir(dir, { recursive: true });
21
+ const line = `${(/* @__PURE__ */ new Date()).toISOString()} [event] ${stage}${detail === void 0 ? "" : ` ${detail}`}\n`;
22
+ await appendFile(join(dir, "shell-entry.log"), line, "utf8");
23
+ } catch {}
24
+ }
25
+ /**
26
+ * 记录一次入口失败。
27
+ * @param stage - 阶段名(`引导` / `加载入口` / `启动`),用来区分崩在哪一段。
28
+ * @param error - 抛出来的东西。
29
+ * @returns 记录完成。
30
+ */
31
+ async function reportFailure(stage, error) {
32
+ const text = error instanceof Error ? error.stack ?? error.message : String(error);
33
+ console.error(`[zephyr-shell] ${stage}失败:`, text);
34
+ try {
35
+ const dir = logDir();
36
+ await mkdir(dir, { recursive: true });
37
+ await appendFile(join(dir, "shell-entry.log"), `${(/* @__PURE__ */ new Date()).toISOString()} ${stage} ${text}\n`, "utf8");
38
+ } catch {}
39
+ }
40
+ export { reportFailure as n, reportEvent as t };