@orielweb/api 0.0.0-stage → 0.4.14

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/src/mocks.js ADDED
@@ -0,0 +1,185 @@
1
+ // 对标 `@tauri-apps/api/mocks`:让前端能在 Node 里跑单测,不必起真实窗口。
2
+ //
3
+ // 为什么它必须与包同时提供(差异分析 §2.19):没有它,前端测试只能起真窗口,
4
+ // 而真窗口在 CI 里跑不动。这不是"锦上添花",是"这个包能不能被正经使用"的前提。
5
+ //
6
+ // 与 Tauri 的差别:
7
+ // * Tauri 的 `mockIPC` 回调签名是 `(cmd, payload) => ...`;这里一致。
8
+ // * 本库**没有 window 概念**(尚未有 window 模块),所以 `mockWindows` 只做占位——
9
+ // 它记录 label 列表,等 window 模块落地后由它读。现在调用不会报错,但也不影响任何行为。
10
+
11
+ import { setTransportOverride, hasTransportOverride } from './internal.js';
12
+
13
+ /**
14
+ * @typedef {{
15
+ * invoke: (name: string, args?: Record<string, unknown>) => Promise<unknown>,
16
+ * supportsPerCallTimeout?: boolean
17
+ * }} OrielTransport
18
+ *
19
+ * @typedef {(cmd: string, payload: Record<string, unknown> | null) => unknown} MockHandler
20
+ */
21
+
22
+ /**
23
+ * 当前 mock 的命令处理函数;`null` 表示没有装 mock。
24
+ * @type {MockHandler | null}
25
+ */
26
+ let handler = null;
27
+
28
+ /** `mockWindows` 登记的 label 列表(供将来 window 模块读取)。 */
29
+ let mockWindowLabels = ['main'];
30
+
31
+ /**
32
+ * mock 传输层的事件订阅表:事件名 → 处理器集合。
33
+ *
34
+ * 真实传输层由桥接脚本提供 `on()`;mock 侧必须自己实现一份,否则
35
+ * `listen`/`once` 在 Node 里根本没法测——而那正是 `mocks` 存在的理由。
36
+ *
37
+ * @type {Map<string, Set<(payload: unknown) => void>>}
38
+ */
39
+ let mockListeners = new Map();
40
+
41
+ /**
42
+ * 装一个假的 IPC 传输层。
43
+ *
44
+ * @param {MockHandler} invoke
45
+ * 处理函数。返回值会被当作命令结果;抛出的异常会变成 Promise 的 reject
46
+ * (与真实通道一致:页面侧拿到的都是 reject 的 Error)。
47
+ * @returns {void}
48
+ */
49
+ export function mockIPC(invoke) {
50
+ if (typeof invoke !== 'function') {
51
+ throw new Error('mockIPC: 需要一个 (cmd, payload) => unknown 形式的函数');
52
+ }
53
+
54
+ handler = invoke;
55
+ setTransportOverride({
56
+ // 声明支持 per-call timeout。
57
+ //
58
+ // 不声明的话,页面在测试里写 `invoke(cmd, args, { timeout })` 会被 core 的显式检查
59
+ // 拒掉——而那个检查的用意是"老宿主上别静默失效",不是"测试里也要拒"。
60
+ // mock 代表的是当前版本的宿主,它就该具备当前版本的能力。
61
+ supportsPerCallTimeout: true,
62
+ async invoke(name, args) {
63
+ // 真实通道里 `args` 缺省时宿主收到的是 `null`(见 oriel-bridge.js 的 invoke)。
64
+ // 这里保持一致,免得测试里 `args === undefined` 的分支与真机不同。
65
+ const current = handler;
66
+ if (current === null) {
67
+ throw new Error('mockIPC: 处理器已被 clearMocks 清掉');
68
+ }
69
+
70
+ return current(name, args ?? null);
71
+ },
72
+ on(name, listener) {
73
+ let set = mockListeners.get(name);
74
+ if (!set) {
75
+ set = new Set();
76
+ mockListeners.set(name, set);
77
+ }
78
+
79
+ set.add(listener);
80
+ return () => {
81
+ set.delete(listener);
82
+ if (set.size === 0) {
83
+ mockListeners.delete(name);
84
+ }
85
+ };
86
+ },
87
+ });
88
+ }
89
+
90
+ /**
91
+ * 模拟一次**宿主 → 页面**的事件(测试专用)。
92
+ *
93
+ * 对标真实宿主推事件的路径:`oriel._onEvent(name, payload)` 把裸 payload
94
+ * 交给订阅者。`@orielweb/api/event` 的 `listen` 再把它包成 `{ event, id, payload }`。
95
+ *
96
+ * @param {string} eventName
97
+ * @param {unknown} [payload]
98
+ * @returns {void}
99
+ */
100
+ export function mockEmit(eventName, payload) {
101
+ if (typeof eventName !== 'string' || eventName === '') {
102
+ throw new Error('mockEmit: eventName 必须为非空字符串');
103
+ }
104
+
105
+ const set = mockListeners.get(eventName);
106
+ if (!set) {
107
+ return;
108
+ }
109
+
110
+ // 复制一份再遍历:处理器内部退订不会影响本次派发(与桥接脚本一致)
111
+ for (const listener of Array.from(set)) {
112
+ try {
113
+ listener(payload === undefined ? null : payload);
114
+ } catch {
115
+ // 单个处理器抛出不该中断同一次派发里其它处理器——与桥接脚本的隔离策略一致
116
+ }
117
+ }
118
+ }
119
+
120
+ /**
121
+ * 登记"有哪些窗口"(供将来 window 模块的 `getAllWindows` 读取)。
122
+ *
123
+ * 现在调用不改变任何可观测行为——本包还没有 window 模块。提前提供是为了让
124
+ * 迁移过来的测试代码不必等到那时才写。
125
+ *
126
+ * @param {string[]} labels
127
+ * @returns {void}
128
+ */
129
+ export function mockWindows(...labels) {
130
+ if (labels.length === 0) {
131
+ throw new Error('mockWindows: 至少给一个窗口 label');
132
+ }
133
+
134
+ for (const label of labels) {
135
+ if (typeof label !== 'string' || label === '') {
136
+ throw new Error('mockWindows: label 必须是非空字符串');
137
+ }
138
+ }
139
+
140
+ mockWindowLabels = [...labels];
141
+ }
142
+
143
+ /**
144
+ * 取当前登记的窗口 label(内部用;window 模块落地后由它消费)。
145
+ * @returns {string[]}
146
+ */
147
+ export function getMockWindowLabels() {
148
+ return [...mockWindowLabels];
149
+ }
150
+
151
+ /**
152
+ * 占位:对标 Tauri 的 `mockConvertFileSrc`。
153
+ *
154
+ * 本库还没有文件 asset 协议(见 core.js 的 `convertFileSrc`),所以这里只记录
155
+ * 自定义协议名,供 `convertFileSrc` 实现时读取。
156
+ *
157
+ * @param {string} protocol
158
+ * @returns {void}
159
+ */
160
+ export function mockConvertFileSrc(protocol = 'oriel') {
161
+ if (typeof protocol !== 'string' || protocol === '') {
162
+ throw new Error('mockConvertFileSrc: protocol 必须是非空字符串');
163
+ }
164
+ }
165
+
166
+ /**
167
+ * 清掉全部 mock,恢复真实传输层。
168
+ * @returns {void}
169
+ */
170
+ export function clearMocks() {
171
+ handler = null;
172
+ mockWindowLabels = ['main'];
173
+ // 事件订阅表也要清:不清的话上一条用例订阅的处理器会在下一条用例的 mockEmit 里
174
+ // 继续被调用,而那两个用例本该互不干扰——这种污染最难查(症状是"单跑通过、连跑失败")。
175
+ mockListeners = new Map();
176
+ setTransportOverride(null);
177
+ }
178
+
179
+ /**
180
+ * 当前是否装了 mock(测试与 `isTauri` 用)。
181
+ * @returns {boolean}
182
+ */
183
+ export function isMocked() {
184
+ return hasTransportOverride();
185
+ }
@@ -0,0 +1,461 @@
1
+ // 对标 `@tauri-apps/plugin-notification` 的**桌面**实现。
2
+ //
3
+ // 与 Tauri 的差别(如实标注,不假装一致):
4
+ //
5
+ // * **函数都是异步的**(`isPermissionGranted` / `requestPermission` / `sendNotification`)。
6
+ // Tauri 的 `sendNotification` 在桌面端直接 `new window.Notification(...)`(走浏览器的通知
7
+ // API),所以是同步的;而本库走宿主命令,因为 WebView 的浏览器通知 API 三平台并不可靠
8
+ // (WKWebView 上基本没有),而 `OrielApp.ShowNotification` 三平台都是原生的。
9
+ // * **`active()` / `pending()` 是"本应用发过的通知"**,不是系统通知中心里的全部:
10
+ // 三平台都没有列出通知中心的 API。`removeActive()` 只从这份记账里移除,
11
+ // **不会撤下系统里已显示的那条**(投递走的是短命子进程,拿不到系统侧的句柄)——
12
+ // 要"点了就消失"请用系统通知自己的生命周期,而不是这个 API。
13
+ // * **`Schedule` 在桌面端真的排期**。Tauri 的桌面端忽略 `schedule`、立即显示
14
+ // ("Scheduling is only supported on mobile"),本库的调度器在宿主进程里,所以是真排期。
15
+ // 代价:**应用退出后就不再响**(没有系统级调度器);要跨进程可靠请用系统的计划任务 /
16
+ // systemd timer / launchd。
17
+ // * **`onAction` 在桌面上不可用**:三平台的投递机制都拿不到"用户点了通知"这件事
18
+ // (未打包的 Windows toast 要 AUMID + COM 激活器,macOS 的 osascript 与 Linux 的
19
+ // notify-send 都没有回调入口)。订阅时**立刻抛 `not_supported`**,而不是给一个永不触发的
20
+ // 订阅——后者不会报错,调用方只会在运行时才发现收不到。`onNotificationReceived` 是
21
+ // 真事件:宿主每次成功投递(含排期到点)都会触发。
22
+ // * 移动端专有的 8 个导出(`Importance` / `Visibility` / `channels` / `createChannel` /
23
+ // `deleteChannel` / `listChannels` / `registerActionTypes`)**不提供**:它们是 Android / iOS
24
+ // 的通知模型,桌面上没有对应概念。
25
+
26
+ import { invoke } from './core.js';
27
+ import { getTransport } from './internal.js';
28
+
29
+ /** 宿主推"这条通知已投递"时用的事件名。 */
30
+ const RECEIVED_EVENT = 'notification.received';
31
+
32
+ /** 宿主推"用户对通知做了动作"时用的事件名(当前三平台都不会来,见 onAction)。 */
33
+ const ACTION_EVENT = 'notification.action';
34
+
35
+ /** 页面侧订阅编号(`PluginListener.handlerId`;不是宿主侧 id)。 */
36
+ let nextHandlerId = 1;
37
+
38
+ /**
39
+ * 通知重复的周期单位(对标 Tauri 的 `ScheduleEvery`)。
40
+ *
41
+ * @readonly
42
+ * @remarks
43
+ * 取值与 Tauri 的 TS 枚举**逐字一致**(字符串枚举),所以直接把它交给
44
+ * {@link Schedule.every} 即可,不需要再翻译。
45
+ *
46
+ * 年/月按固定天数近似(365 / 30 天)——本库的调度器是"隔 N 天",不是"每年 1 月 1 日";
47
+ * 要按日历字段匹配请用 {@link Schedule.interval}。
48
+ */
49
+ export const ScheduleEvery = Object.freeze({
50
+ Year: 'year',
51
+ Month: 'month',
52
+ TwoWeeks: 'twoWeeks',
53
+ Week: 'week',
54
+ Day: 'day',
55
+ Hour: 'hour',
56
+ Minute: 'minute',
57
+ Second: 'second',
58
+ });
59
+
60
+ /**
61
+ * 通知的排期(对标 Tauri 的 `Schedule`)。
62
+ *
63
+ * @remarks
64
+ * 用三个静态构造器造它,三个字段**互斥**(同时给两个会被宿主拒绝):
65
+ *
66
+ * ```js
67
+ * import { Schedule, ScheduleEvery, sendNotification } from '@orielweb/api/notification';
68
+ *
69
+ * // 一分钟后一次
70
+ * await sendNotification({ title: '提醒', schedule: Schedule.at(new Date(Date.now() + 60_000)) });
71
+ *
72
+ * // 每天 9:00(按日历匹配)
73
+ * await sendNotification({ title: '早报', schedule: Schedule.interval({ hour: 9, minute: 0 }) });
74
+ *
75
+ * // 每两小时一次
76
+ * await sendNotification({ title: '喝水', schedule: Schedule.every(ScheduleEvery.Hour, 2) });
77
+ * ```
78
+ *
79
+ * **应用退出后排期不再触发**(调度器在宿主进程里)。
80
+ */
81
+ export class Schedule {
82
+ constructor() {
83
+ /**
84
+ * 固定时刻触发({@link Schedule.at} 设定)。
85
+ *
86
+ * @type {{ date: Date | string | number, repeating: boolean, allowWhileIdle: boolean } | undefined}
87
+ */
88
+ this.at = undefined;
89
+
90
+ /**
91
+ * 按日历字段匹配({@link Schedule.interval} 设定)。
92
+ *
93
+ * @type {{ interval: Record<string, number>, allowWhileIdle: boolean } | undefined}
94
+ */
95
+ this.interval = undefined;
96
+
97
+ /**
98
+ * 固定周期({@link Schedule.every} 设定)。
99
+ *
100
+ * @type {{ interval: string, count: number, allowWhileIdle: boolean } | undefined}
101
+ */
102
+ this.every = undefined;
103
+ }
104
+
105
+ /**
106
+ * 在某个时刻触发(对标 Tauri 的 `Schedule.at`)。
107
+ *
108
+ * @param {Date | string | number} date 触发时刻;**必须是将来的时刻**(宿主会拒绝过去的时刻)。
109
+ * `Date` 最直观;字符串按 ISO 8601 解释,数字按 Unix 毫秒解释。
110
+ * @param {boolean} [repeating] 是否重复:周期 = "排期时刻 → `date`"的距离。
111
+ * @param {boolean} [allowWhileIdle] Android 的低电量待机开关(桌面上接受并忽略)。
112
+ * @returns {Schedule}
113
+ * @throws {TypeError} `date` 不是 Date / 字符串 / 有限数字时。
114
+ */
115
+ static at(date, repeating = false, allowWhileIdle = false) {
116
+ const valid = date instanceof Date
117
+ || typeof date === 'string'
118
+ || (typeof date === 'number' && Number.isFinite(date));
119
+ if (!valid) {
120
+ throw new TypeError('Schedule.at: date 必须是 Date、ISO 8601 字符串或 Unix 毫秒数。');
121
+ }
122
+
123
+ const schedule = new Schedule();
124
+ schedule.at = { date, repeating: repeating === true, allowWhileIdle: allowWhileIdle === true };
125
+ return schedule;
126
+ }
127
+
128
+ /**
129
+ * 按日历字段匹配(对标 Tauri 的 `Schedule.interval`)。
130
+ *
131
+ * @param {{ year?: number, month?: number, day?: number, weekday?: number, hour?: number,
132
+ * minute?: number, second?: number }} interval 至少要给一个字段;**给了的字段都必须相等**。
133
+ * `weekday` 按 Tauri 的编号:1 = 周日 … 7 = 周六。
134
+ * @param {boolean} [allowWhileIdle] Android 的低电量待机开关(桌面上接受并忽略)。
135
+ * @returns {Schedule}
136
+ * @throws {TypeError} 一个字段都没给、给了不认识的字段,或字段类型不对时。
137
+ * @remarks 不认识的字段**当场拒绝**(比 Tauri 严):`{ munite: 30 }` 这种拼写错误在
138
+ * Tauri 那边等于"每秒都匹配",而这里会直接报错——静默变成"每秒响一次"没有任何好处。
139
+ */
140
+ static interval(interval, allowWhileIdle = false) {
141
+ if (interval === null || typeof interval !== 'object') {
142
+ throw new TypeError('Schedule.interval: interval 必须是对象。');
143
+ }
144
+
145
+ const known = ['year', 'month', 'day', 'weekday', 'hour', 'minute', 'second'];
146
+ /** @type {Record<string, number>} */
147
+ const fields = {};
148
+ for (const [key, value] of Object.entries(interval)) {
149
+ if (!known.includes(key)) {
150
+ throw new TypeError(
151
+ `Schedule.interval: 不认识的字段 '${key}'(可用:${known.join(' / ')})。`);
152
+ }
153
+
154
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
155
+ throw new TypeError(`Schedule.interval: '${key}' 必须是整数。`);
156
+ }
157
+
158
+ fields[key] = value;
159
+ }
160
+
161
+ if (Object.keys(fields).length === 0) {
162
+ throw new TypeError(
163
+ 'Schedule.interval: 至少要给一个字段(year / month / day / weekday / hour / minute / second)。');
164
+ }
165
+
166
+ const schedule = new Schedule();
167
+ schedule.interval = { interval: fields, allowWhileIdle: allowWhileIdle === true };
168
+ return schedule;
169
+ }
170
+
171
+ /**
172
+ * 固定周期重复(对标 Tauri 的 `Schedule.every`)。
173
+ *
174
+ * @param {string} kind 单位,取 {@link ScheduleEvery} 的值(如 `ScheduleEvery.Hour`)。
175
+ * @param {number} [count] 周期倍数:`every(Hour, 2)` = 每两小时一次。
176
+ * @param {boolean} [allowWhileIdle] Android 的低电量待机开关(桌面上接受并忽略)。
177
+ * @returns {Schedule}
178
+ * @throws {TypeError} 单位不认识,或 `count` 不是 ≥ 1 的整数时。
179
+ */
180
+ static every(kind, count = 1, allowWhileIdle = false) {
181
+ if (!/** @type {string[]} */ (Object.values(ScheduleEvery)).includes(kind)) {
182
+ throw new TypeError(
183
+ `Schedule.every: 未知的周期单位 '${kind}'(用 ScheduleEvery 里的值)。`);
184
+ }
185
+
186
+ if (!Number.isInteger(count) || count < 1) {
187
+ throw new TypeError('Schedule.every: count 必须是 ≥ 1 的整数。');
188
+ }
189
+
190
+ const schedule = new Schedule();
191
+ schedule.every = { interval: kind, count, allowWhileIdle: allowWhileIdle === true };
192
+ return schedule;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * 把 `Schedule`(或同形的裸对象)归一成要发的载荷。
198
+ *
199
+ * @param {any} schedule
200
+ * @returns {Record<string, unknown>}
201
+ */
202
+ function schedulePayload(schedule) {
203
+ if (schedule === null || typeof schedule !== 'object') {
204
+ throw new TypeError('sendNotification: schedule 必须是 Schedule 实例(或 at / interval / every 同形对象)。');
205
+ }
206
+
207
+ const keys = ['at', 'interval', 'every'].filter((key) => schedule[key] !== undefined && schedule[key] !== null);
208
+ const key = keys[0];
209
+ if (keys.length !== 1 || key === undefined) {
210
+ throw new TypeError(
211
+ `sendNotification: schedule 必须且只能给 at / interval / every 三者之一(实际给了 ${keys.length} 个)。`);
212
+ }
213
+
214
+ return { [key]: schedule[key] };
215
+ }
216
+
217
+ /**
218
+ * 把"编号数组"归一成整数数组。
219
+ *
220
+ * @param {any} notifications
221
+ * @param {string} name
222
+ * @returns {number[]}
223
+ */
224
+ function idList(notifications, name) {
225
+ if (!Array.isArray(notifications)) {
226
+ throw new TypeError(`notification.${name}: notifications 必须是数组。`);
227
+ }
228
+
229
+ return notifications.map((item) => {
230
+ const value = item !== null && typeof item === 'object' ? item.id : item;
231
+ if (!Number.isInteger(value)) {
232
+ throw new TypeError(
233
+ `notification.${name}: 通知编号必须是整数(编号来自 pending() / active() 的返回值)。`);
234
+ }
235
+
236
+ return value;
237
+ });
238
+ }
239
+
240
+ /**
241
+ * 宿主是否允许发送通知。
242
+ *
243
+ * @returns {Promise<boolean>}
244
+ * @remarks
245
+ * 桌面上没有"通知权限"这个概念(能显示就能显示),所以这里回的是
246
+ * **宿主是否支持通知**——与 Tauri 的语义一致(它在移动端才真的查权限)。
247
+ */
248
+ export function isPermissionGranted() {
249
+ return invoke('notification.isPermissionGranted');
250
+ }
251
+
252
+ /**
253
+ * 请求通知权限。
254
+ *
255
+ * @returns {Promise<'granted' | 'denied'>}
256
+ * @remarks
257
+ * 桌面端**不弹任何对话框**(没有可弹的东西),直接回结果。
258
+ * 返回字符串而不是布尔是为了与 Tauri 以及 Web Notification 规范一致。
259
+ */
260
+ export function requestPermission() {
261
+ return invoke('notification.requestPermission');
262
+ }
263
+
264
+ /**
265
+ * 发一条系统通知(带 `schedule` 时是**排期**)。
266
+ *
267
+ * @param {string | { title: string, body?: string, schedule?: Schedule }} options 标题,
268
+ * 或 `{ title, body, schedule }`。
269
+ * @returns {Promise<boolean>} 系统是否接受了它(带 `schedule` 时表示"已排期")。
270
+ * @throws {TypeError} 参数形状不对、或 `schedule` 的配置互斥/字段非法时(**在发 IPC 之前**)。
271
+ * @remarks
272
+ * 返回 `false` 而不是抛错,用于"用户关掉了这个应用的通知"这类**正常状态**——
273
+ * 那不是调用方的错误,逼它包 try 只会让代码更难读。
274
+ *
275
+ * 形状与 Tauri 的 `sendNotification` 一致(收字符串或 `{ title, body }`),
276
+ * 但**是异步的**(理由见文件头)。排期通知的编号经 {@link pending} 取。
277
+ */
278
+ export function sendNotification(options) {
279
+ if (typeof options === 'string') {
280
+ return invoke('notification.sendNotification', { title: options });
281
+ }
282
+
283
+ if (options === null || typeof options !== 'object' || typeof options.title !== 'string') {
284
+ throw new TypeError('sendNotification: 参数必须是字符串或 { title, body }');
285
+ }
286
+
287
+ /** @type {Record<string, unknown>} */
288
+ const args = {
289
+ title: options.title,
290
+ body: options.body,
291
+ };
292
+
293
+ if (options.schedule !== undefined && options.schedule !== null) {
294
+ args.schedule = schedulePayload(options.schedule);
295
+ }
296
+
297
+ return invoke('notification.sendNotification', args);
298
+ }
299
+
300
+ /**
301
+ * 本应用发出、仍在登记表里的通知(对标 Tauri 的 `active`)。
302
+ *
303
+ * @returns {Promise<Array<{ id: number, title?: string, body?: string, tag?: string,
304
+ * groupSummary: boolean, data: Record<string, string>, extra: Record<string, unknown>,
305
+ * attachments: unknown[] }>>}
306
+ * @remarks
307
+ * **不是"系统通知中心里的全部"**:别的应用发的、用户手动清掉的,本库都看不到
308
+ * (三平台都没有列出通知中心的 API)。
309
+ *
310
+ * `groupSummary` / `data` / `extra` / `attachments` 在 Tauri 的类型里是必填字段,
311
+ * 而它们分别是 Android / iOS 的概念——桌面上恒为空值(`false` / `{}` / `{}` / `[]`)。
312
+ */
313
+ export async function active() {
314
+ const records = await invoke('notification.active');
315
+ return Array.isArray(records) ? records : [];
316
+ }
317
+
318
+ /**
319
+ * 已排期、尚未到点的通知(对标 Tauri 的 `pending`)。
320
+ *
321
+ * @returns {Promise<Array<{ id: number, title?: string, body?: string, schedule: object }>>}
322
+ * @remarks `schedule` 的形状与 {@link Schedule} 序列化之后一致(`{ at }` / `{ interval }` / `{ every }`)。
323
+ */
324
+ export async function pending() {
325
+ const records = await invoke('notification.pending');
326
+ return Array.isArray(records) ? records : [];
327
+ }
328
+
329
+ /**
330
+ * 取消待发通知(**只对待发有效**,对标 Tauri 的 `cancel`)。
331
+ *
332
+ * @param {Array<number | { id: number }>} notifications 编号(来自 {@link pending})。
333
+ * 元素写成 `{ id }` 也接受——Tauri 的 `cancel` 收数字、`removeActive` 收对象,
334
+ * 混用是迁移里的常见错误。
335
+ * @returns {Promise<number>} 真正取消掉的条数(Tauri 返回 void,这里多给一个数;
336
+ * 编号不对/已经投递出去的那些不算在内)。
337
+ * @remarks 取消是**可靠**的:定时器在宿主进程里,取消就是取消。
338
+ */
339
+ export async function cancel(notifications) {
340
+ return invoke('notification.cancel', { notifications: idList(notifications, 'cancel') });
341
+ }
342
+
343
+ /**
344
+ * 取消全部待发通知(对标 Tauri 的 `cancelAll`)。
345
+ *
346
+ * @returns {Promise<number>} 取消掉的条数。
347
+ */
348
+ export async function cancelAll() {
349
+ return invoke('notification.cancelAll');
350
+ }
351
+
352
+ /**
353
+ * 从活动列表里移除通知(对标 Tauri 的 `removeActive`)。
354
+ *
355
+ * @param {Array<{ id: number } | number>} notifications 编号(来自 {@link active})。
356
+ * @returns {Promise<number>} 移除掉的条数。
357
+ * @remarks
358
+ * **只移除本库的记账,不撤下系统里已显示的那条**:投递走的是短命子进程
359
+ * (Windows PowerShell / macOS osascript / Linux notify-send),投递完就拿不到
360
+ * 系统侧的句柄了。详见文件头。
361
+ */
362
+ export async function removeActive(notifications) {
363
+ const ids = idList(notifications, 'removeActive');
364
+ return invoke('notification.removeActive', { notifications: ids.map((id) => ({ id })) });
365
+ }
366
+
367
+ /**
368
+ * 清空活动列表(对标 Tauri 的 `removeAllActive`)。
369
+ *
370
+ * @returns {Promise<number>} 移除掉的条数。
371
+ * @remarks 同 {@link removeActive}:只清记账,不撤系统里那些。
372
+ */
373
+ export async function removeAllActive() {
374
+ return invoke('notification.removeAllActive');
375
+ }
376
+
377
+ /**
378
+ * 订阅"通知已投递"(对标 Tauri 的 `onNotificationReceived`)。
379
+ *
380
+ * @param {(notification: { id: number, title: string, body: string | null }) => void} handler
381
+ * @returns {Promise<{ event: string, handlerId: number, unregister: () => Promise<void> }>}
382
+ * @throws {TypeError} `handler` 不是函数时。
383
+ * @throws {Error} 传输层不支持事件订阅时(不是运行在宿主里)。
384
+ * @remarks
385
+ * **"收到"= 宿主成功投递**(立即投递或排期到点触发),不是"用户看到了"。
386
+ * 这条事件是真事件;Tauri 的桌面端没有对应实现(它只有移动端)。
387
+ */
388
+ export async function onNotificationReceived(handler) {
389
+ return subscribe(RECEIVED_EVENT, handler, 'onNotificationReceived');
390
+ }
391
+
392
+ /**
393
+ * 订阅"用户对通知做了动作"(对标 Tauri 的 `onAction`)。
394
+ *
395
+ * @param {Function} handler
396
+ * @returns {Promise<{ event: string, handlerId: number, unregister: () => Promise<void> }>}
397
+ * @throws {TypeError} `handler` 不是函数时。
398
+ * @throws {Error} **当前桌面宿主一律抛 `not_supported`**(见下)。
399
+ * @remarks
400
+ * 三平台的投递机制都拿不到"用户点了通知":未打包的 Windows toast 激活需要开始菜单快捷方式
401
+ * 携带 AUMID 并注册 COM 激活器(打包器的职责),macOS 的 osascript 没有回调入口,
402
+ * Linux 的 notify-send 同样没有。
403
+ *
404
+ * 与其给一个**永不触发**的订阅(不会报错,调用方只会在运行时才发现收不到),不如在订阅时
405
+ * 就失败——`error.code === 'not_supported'`,调用方可以据此降级。
406
+ * 真要点击回传得先进 .app bundle / AUMID 打包,那是另一个量级的改动。
407
+ */
408
+ export async function onAction(handler) {
409
+ if (typeof handler !== 'function') {
410
+ throw new TypeError('notification.onAction: 需要一个函数。');
411
+ }
412
+
413
+ const supported = await invoke('notification.actionSupport');
414
+ if (supported !== true) {
415
+ const error = new Error(
416
+ 'notification.onAction: 当前宿主拿不到通知点击(三平台投递机制都没有回调入口)。' +
417
+ '要点击回传需打包并注册系统级通知激活器;在此之前请在页面里自行提供入口。');
418
+ // 与 invoke 的错误一样带机器可判别的 code
419
+ Reflect.defineProperty(error, 'code', { value: 'not_supported', enumerable: true });
420
+ throw error;
421
+ }
422
+
423
+ return subscribe(ACTION_EVENT, handler, 'onAction');
424
+ }
425
+
426
+ /**
427
+ * 订阅一个宿主事件并包成 Tauri 的 `PluginListener` 形状。
428
+ *
429
+ * @param {string} event 宿主事件名。
430
+ * @param {Function} handler 页面回调。
431
+ * @param {string} name 出错时用于文案的命令名。
432
+ * @returns {Promise<{ event: string, handlerId: number, unregister: () => Promise<void> }>}
433
+ */
434
+ async function subscribe(event, handler, name) {
435
+ if (typeof handler !== 'function') {
436
+ throw new TypeError(`notification.${name}: 需要一个函数。`);
437
+ }
438
+
439
+ const transport = getTransport();
440
+ if (typeof transport.on !== 'function') {
441
+ throw new Error(`notification.${name}: 传输层不支持 on()——无法订阅通知事件。`);
442
+ }
443
+
444
+ const off = transport.on(event, (/** @type {any} */ value) => {
445
+ try {
446
+ handler(value);
447
+ } catch (error) {
448
+ // 订阅者自己的异常不该让整条事件通道断掉(与 tray 的处理器同一个姿态)
449
+ console.error(`notification.${name} 处理器抛出`, error);
450
+ }
451
+ });
452
+
453
+ const handlerId = nextHandlerId++;
454
+ return {
455
+ event,
456
+ handlerId,
457
+ unregister: async () => {
458
+ off();
459
+ },
460
+ };
461
+ }