@flighthq/notification 0.5.0-next.1944.cd6b6e7 → 0.5.1-edge.638.d4dbd4e

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.
@@ -1,715 +1,276 @@
1
- // Cancels a pending scheduled notification by id. No-ops when the id is unknown.
2
- export function cancelScheduledNotification(id) {
3
- getNotificationBackend().cancelScheduledNotification(id);
4
- }
5
- // Dismisses all currently-shown notifications.
6
- export function closeAllNotifications() {
7
- getNotificationBackend().closeAllNotifications();
8
- }
9
- // Dismisses the notification with the given id. No-ops when the id is unknown or already dismissed.
10
- export function closeNotification(id) {
11
- getNotificationBackend().closeNotification(id);
12
- }
13
- // Creates or updates a notification channel. No-ops on backends without channel support.
14
- export function createNotificationChannel(channel) {
15
- const backend = getNotificationBackend();
16
- backend.createNotificationChannel?.(channel);
17
- }
18
- // Builds a web backend backed by the Service Worker Notifications API. Unlike the basic web
19
- // backend, this variant can deliver action-button activations because it uses
20
- // `registration.showNotification`, which triggers the SW `notificationclick` event globally.
21
- //
22
- // The caller must supply an active ServiceWorkerRegistration (e.g. from
23
- // `navigator.serviceWorker.ready`). The backend uses `registration.showNotification` and
24
- // `registration.getNotifications` to manage notification identity and lifecycle.
25
- //
26
- // Action delivery requires a service worker that forwards `notificationclick` messages back to the
27
- // page. Wire the SW side like this:
28
- //
29
- // self.addEventListener('notificationclick', (event) => {
30
- // event.notification.close();
31
- // const { notificationId, actionId } = event.notification.data ?? {};
32
- // if (event.source) event.source.postMessage({ type: 'notificationclick', notificationId, actionId });
33
- // });
34
- //
35
- // Then call `notifyServiceWorkerBackendAction(backend, event.data)` in the page's message handler.
36
- // This two-step wiring is necessary because SW events fire in the worker thread, not the page.
37
- export function createServiceWorkerNotificationBackend(registration) {
38
- let _idCounter = 0;
39
- const _clickListeners = new Set();
40
- const _actionListeners = new Set();
41
- const _dismissListeners = new Set();
42
- const _replyListeners = new Set();
43
- const _showListeners = new Set();
44
- const _scheduled = new Map();
45
- function _generateId() {
46
- _idCounter += 1;
47
- return `sw-notif-${_idCounter}`;
1
+ import { createEntity } from '@flighthq/entity/contract';
2
+ import { clearSignal, createSignal, emitSignal } from '@flighthq/signals/contract';
3
+ export async function attachNotificationActionSubscription(host, subscription) {
4
+ return attachNotificationSubscription(subscription, (listener) => host.notification.action.attach(listener), (notification, actionId) => emitSignal(subscription.onNotificationAction, notification, actionId));
5
+ }
6
+ export async function attachNotificationClickSubscription(host, subscription) {
7
+ return attachNotificationSubscription(subscription, (listener) => host.notification.click.attach(listener), (notification) => emitSignal(subscription.onNotificationClick, notification));
8
+ }
9
+ export async function attachNotificationDismissSubscription(host, subscription) {
10
+ return attachNotificationSubscription(subscription, (listener) => host.notification.dismiss.attach(listener), (notification) => emitSignal(subscription.onNotificationDismiss, notification));
11
+ }
12
+ export async function attachNotificationReceivedSubscription(host, subscription) {
13
+ return attachNotificationSubscription(subscription, (listener) => host.notification.received.attach(listener), (notification) => emitSignal(subscription.onNotificationReceived, notification));
14
+ }
15
+ export async function attachNotificationReplySubscription(host, subscription) {
16
+ return attachNotificationSubscription(subscription, (listener) => host.notification.reply.attach(listener), (notification, actionId, text) => emitSignal(subscription.onNotificationReply, notification, actionId, text));
17
+ }
18
+ // Provider-contract hook: binds one public Entity to the exact native close operation that created it.
19
+ // Kept out of the package root; host providers consume it from /contract.
20
+ export function bindNotificationClose(notification, close) {
21
+ _notificationClose.set(notification, close);
22
+ }
23
+ // Provider-contract hook: same origin pin for one scheduled native resource.
24
+ export function bindScheduledNotificationCancel(scheduled, cancel) {
25
+ _scheduledNotificationCancel.set(scheduled, cancel);
26
+ }
27
+ export async function cancelScheduledNotification(scheduled) {
28
+ if (_cancelledScheduledNotifications.has(scheduled))
29
+ return { reason: 'already-cancelled' };
30
+ const cancel = _scheduledNotificationCancel.get(scheduled);
31
+ if (cancel === undefined)
32
+ return { reason: 'operation-failed' };
33
+ let outcome;
34
+ try {
35
+ outcome = await cancel();
48
36
  }
49
- function _fire(listeners, arg) {
50
- for (const fn of listeners)
51
- fn(arg);
37
+ catch {
38
+ outcome = { reason: 'operation-failed' };
52
39
  }
53
- async function _show(request) {
54
- if (typeof Notification === 'undefined')
55
- return '';
56
- try {
57
- if (Notification.permission !== 'granted')
58
- return '';
59
- const id = request.id ?? _generateId();
60
- await registration.showNotification(request.title, {
61
- body: request.body,
62
- badge: request.badge,
63
- dir: request.dir,
64
- icon: request.icon,
65
- image: request.image,
66
- lang: request.lang,
67
- renotify: request.renotify,
68
- requireInteraction: request.requireInteraction,
69
- silent: request.silent,
70
- tag: request.tag ?? id,
71
- timestamp: request.timestamp,
72
- vibrate: request.vibrate ? [...request.vibrate] : undefined,
73
- // Store the Flight id in data so SW click handlers can forward it back.
74
- data: { ...request.data, notificationId: id },
75
- actions: request.actions?.map((a) => ({ action: a.id, title: a.title, icon: a.icon })),
76
- });
77
- _fire(_showListeners, id);
78
- return id;
79
- }
80
- catch {
81
- return '';
82
- }
40
+ if (outcome.reason === 'ok' || outcome.reason === 'already-cancelled') {
41
+ _scheduledNotificationCancel.delete(scheduled);
42
+ _cancelledScheduledNotifications.add(scheduled);
83
43
  }
84
- const backend = {
85
- cancelScheduledNotification(id) {
86
- const entry = _scheduled.get(id);
87
- if (entry !== undefined) {
88
- clearTimeout(entry.timeout);
89
- _scheduled.delete(id);
90
- }
91
- },
92
- async closeAllNotifications() {
93
- try {
94
- const notifications = await registration.getNotifications();
95
- for (const n of notifications) {
96
- n.close();
97
- }
98
- }
99
- catch {
100
- // Guarded.
101
- }
102
- },
103
- async closeNotification(id) {
104
- try {
105
- const notifications = await registration.getNotifications({ tag: id });
106
- for (const n of notifications) {
107
- n.close();
108
- }
109
- }
110
- catch {
111
- // Guarded.
112
- }
113
- },
114
- getCapabilities() {
115
- return {
116
- actions: true,
117
- channels: false,
118
- coldStart: false,
119
- image: true,
120
- listActive: true,
121
- scheduling: true,
122
- textReply: false,
123
- };
124
- },
125
- async getLaunchNotification() {
126
- return null;
127
- },
128
- async getActiveNotifications() {
129
- try {
130
- const notifications = await registration.getNotifications();
131
- return notifications.map((n) => ({ title: n.title, tag: n.tag }));
132
- }
133
- catch {
134
- return [];
135
- }
136
- },
137
- async getPendingNotifications() {
138
- return Array.from(_scheduled.values()).map((e) => e.entry);
139
- },
140
- getPermission() {
141
- if (typeof Notification === 'undefined')
142
- return 'denied';
143
- return Notification.permission;
144
- },
145
- isSupported() {
146
- return typeof Notification !== 'undefined' && 'serviceWorker' in navigator;
147
- },
148
- notify: _show,
149
- async requestPermission() {
150
- if (typeof Notification === 'undefined' || typeof Notification.requestPermission !== 'function')
151
- return 'denied';
152
- try {
153
- return (await Notification.requestPermission());
154
- }
155
- catch {
156
- return 'denied';
157
- }
158
- },
159
- async scheduleNotification(request, schedule) {
160
- const id = request.id ?? _generateId();
161
- const delay = Math.max(0, schedule.at - Date.now());
162
- const entry = { id, request, schedule };
163
- const fireAndReschedule = () => {
164
- _scheduled.delete(id);
165
- void _show({ ...request, id });
166
- if (schedule.repeat !== undefined) {
167
- const ms = _repeatMs(schedule.repeat);
168
- const timeout = setTimeout(fireAndReschedule, ms);
169
- _scheduled.set(id, {
170
- timeout,
171
- entry: { id, request, schedule: { ...schedule, at: Date.now() + ms } },
172
- });
173
- }
174
- };
175
- const timeout = setTimeout(fireAndReschedule, delay);
176
- _scheduled.set(id, { timeout, entry });
177
- return id;
178
- },
179
- subscribeAction(listener) {
180
- _actionListeners.add(listener);
181
- return () => {
182
- _actionListeners.delete(listener);
183
- };
184
- },
185
- subscribeClick(listener) {
186
- _clickListeners.add(listener);
187
- return () => {
188
- _clickListeners.delete(listener);
189
- };
190
- },
191
- subscribeDismiss(listener) {
192
- _dismissListeners.add(listener);
193
- return () => {
194
- _dismissListeners.delete(listener);
195
- };
196
- },
197
- subscribeReply(listener) {
198
- _replyListeners.add(listener);
199
- return () => {
200
- _replyListeners.delete(listener);
201
- };
202
- },
203
- subscribeShow(listener) {
204
- _showListeners.add(listener);
205
- return () => {
206
- _showListeners.delete(listener);
207
- };
208
- },
209
- async updateNotification(id, partial) {
210
- // Close existing and re-show with merged fields.
211
- await backend.closeNotification(id);
212
- // Merge the partial on top; since we don't retain the original request in the SW backend
213
- // (the SW doesn't expose it), callers must include at least a title in partial or this
214
- // cannot reconstruct the notification.
215
- const merged = { ...partial, id };
216
- if (merged.title === undefined)
217
- return false;
218
- await _show(merged);
219
- return true;
220
- },
221
- };
222
- // Exposes internal dispatch hooks so page-side message handlers can forward SW events.
223
- // Use notifyServiceWorkerBackendAction() rather than calling these directly.
224
- const internal = backend;
225
- internal._dispatchAction = (notificationId, actionId) => {
226
- // Action button tap: deliver to both action listeners (id + actionId) and click listeners (id).
227
- for (const fn of _actionListeners)
228
- fn(notificationId, actionId);
229
- _fire(_clickListeners, notificationId);
230
- };
231
- internal._dispatchClick = (notificationId) => {
232
- _fire(_clickListeners, notificationId);
233
- };
234
- internal._dispatchDismiss = (notificationId) => {
235
- _fire(_dismissListeners, notificationId);
236
- };
237
- internal._dispatchReply = (notificationId, actionId, text) => {
238
- // Inline-reply submission (a `text-input` action): deliver the reply text to reply listeners.
239
- for (const fn of _replyListeners)
240
- fn(notificationId, actionId, text);
241
- };
242
- return backend;
243
- }
244
- // Builds the default web backend over the global Notification API. Every touch is guarded for hosts
245
- // where Notification is absent (jsdom, non-secure contexts) and wrapped in try/catch; notify and
246
- // requestPermission resolve to '' / 'default' when unsupported or denied rather than throwing.
247
- // Per-instance onclick is wired so clicks are actually delivered; action buttons require the
248
- // service-worker backend variant and never fire on this basic backend.
249
- export function createWebNotificationBackend() {
250
- // Live map of id → Notification instance so we can close them and wire onclick.
251
- const _live = new Map();
252
- // Live request registry: id → the original request, needed to merge partial updates.
253
- const _requests = new Map();
254
- const _clickListeners = new Set();
255
- const _actionListeners = new Set();
256
- const _dismissListeners = new Set();
257
- const _replyListeners = new Set();
258
- const _showListeners = new Set();
259
- // Scheduled-notification registry (best-effort setTimeout — cleared on page reload).
260
- const _scheduled = new Map();
261
- let _idCounter = 0;
262
- function _generateId() {
263
- _idCounter += 1;
264
- return `web-notif-${_idCounter}`;
44
+ return outcome;
45
+ }
46
+ export function closeAllNotifications(host) {
47
+ return host.notification.close.closeAllNotifications();
48
+ }
49
+ export async function closeNotification(notification) {
50
+ if (_closedNotifications.has(notification))
51
+ return { reason: 'already-closed' };
52
+ const close = _notificationClose.get(notification);
53
+ if (close === undefined)
54
+ return { reason: 'operation-failed' };
55
+ let outcome;
56
+ try {
57
+ outcome = await close();
265
58
  }
266
- function _fire(listeners, arg) {
267
- for (const fn of listeners)
268
- fn(arg);
59
+ catch {
60
+ outcome = { reason: 'operation-failed' };
269
61
  }
270
- // Extracted as a closure function so scheduleNotification can call it without a `this` reference.
271
- async function _notify(request) {
272
- if (typeof Notification === 'undefined')
273
- return '';
274
- try {
275
- if (Notification.permission !== 'granted')
276
- return '';
277
- const id = request.id ?? _generateId();
278
- const n = new Notification(request.title, {
279
- body: request.body,
280
- badge: request.badge,
281
- data: request.data,
282
- dir: request.dir,
283
- icon: request.icon,
284
- image: request.image,
285
- lang: request.lang,
286
- renotify: request.renotify,
287
- requireInteraction: request.requireInteraction,
288
- silent: request.silent,
289
- tag: request.tag ?? id,
290
- timestamp: request.timestamp,
291
- vibrate: request.vibrate ? [...request.vibrate] : undefined,
292
- });
293
- _live.set(id, n);
294
- _requests.set(id, request);
295
- n.onshow = () => {
296
- _fire(_showListeners, id);
297
- };
298
- n.onclick = () => {
299
- _fire(_clickListeners, id);
300
- };
301
- n.onclose = () => {
302
- _live.delete(id);
303
- _requests.delete(id);
304
- _fire(_dismissListeners, id);
305
- };
306
- n.onerror = () => {
307
- _live.delete(id);
308
- _requests.delete(id);
309
- };
310
- return id;
311
- }
312
- catch {
313
- return '';
314
- }
315
- }
316
- return {
317
- cancelScheduledNotification(id) {
318
- const entry = _scheduled.get(id);
319
- if (entry !== undefined) {
320
- clearTimeout(entry.timeout);
321
- _scheduled.delete(id);
322
- }
323
- },
324
- closeAllNotifications() {
325
- for (const [id, n] of _live) {
326
- try {
327
- n.close();
328
- }
329
- catch {
330
- // Guarded — some browsers disallow closing programmatically.
331
- }
332
- _live.delete(id);
333
- _requests.delete(id);
334
- }
335
- },
336
- closeNotification(id) {
337
- const n = _live.get(id);
338
- if (n !== undefined) {
339
- try {
340
- n.close();
341
- }
342
- catch {
343
- // Guarded.
344
- }
345
- _live.delete(id);
346
- _requests.delete(id);
347
- }
348
- },
349
- getCapabilities() {
350
- return {
351
- actions: false,
352
- channels: false,
353
- coldStart: false,
354
- image: false,
355
- listActive: false,
356
- scheduling: true,
357
- textReply: false,
358
- };
359
- },
360
- async getLaunchNotification() {
361
- // Web pages are not launched from a notification; always null.
362
- return null;
363
- },
364
- async getActiveNotifications() {
365
- return [];
366
- },
367
- async getPendingNotifications() {
368
- return Array.from(_scheduled.values()).map((e) => e.entry);
369
- },
370
- getPermission() {
371
- if (typeof Notification === 'undefined')
372
- return 'denied';
373
- const p = Notification.permission;
374
- // The web API uses 'default' / 'granted' / 'denied' — same union values.
375
- return p;
376
- },
377
- isSupported() {
378
- return typeof Notification !== 'undefined';
379
- },
380
- notify: _notify,
381
- async requestPermission() {
382
- if (typeof Notification === 'undefined' || typeof Notification.requestPermission !== 'function')
383
- return 'denied';
384
- try {
385
- const result = (await Notification.requestPermission());
386
- return result;
387
- }
388
- catch {
389
- return 'denied';
390
- }
391
- },
392
- async scheduleNotification(request, schedule) {
393
- const id = request.id ?? _generateId();
394
- const delay = Math.max(0, schedule.at - Date.now());
395
- const entry = { id, request, schedule };
396
- const fireAndReschedule = () => {
397
- _scheduled.delete(id);
398
- void _notify({ ...request, id });
399
- if (schedule.repeat !== undefined) {
400
- const ms = _repeatMs(schedule.repeat);
401
- const timeout = setTimeout(fireAndReschedule, ms);
402
- _scheduled.set(id, {
403
- timeout,
404
- entry: { id, request, schedule: { ...schedule, at: Date.now() + ms } },
405
- });
406
- }
407
- };
408
- const timeout = setTimeout(fireAndReschedule, delay);
409
- _scheduled.set(id, { timeout, entry });
410
- return id;
411
- },
412
- subscribeAction(listener) {
413
- // Web notifications have no global action feed — action buttons require the Service Worker
414
- // Notifications API. A native host (Electron/Tauri) or the SW backend is required.
415
- _actionListeners.add(listener);
416
- return () => {
417
- _actionListeners.delete(listener);
418
- };
419
- },
420
- subscribeClick(listener) {
421
- _clickListeners.add(listener);
422
- return () => {
423
- _clickListeners.delete(listener);
424
- };
425
- },
426
- subscribeDismiss(listener) {
427
- _dismissListeners.add(listener);
428
- return () => {
429
- _dismissListeners.delete(listener);
430
- };
431
- },
432
- subscribeReply(listener) {
433
- // Inline reply requires the SW backend; this basic backend never fires it.
434
- _replyListeners.add(listener);
435
- return () => {
436
- _replyListeners.delete(listener);
437
- };
438
- },
439
- subscribeShow(listener) {
440
- _showListeners.add(listener);
441
- return () => {
442
- _showListeners.delete(listener);
443
- };
444
- },
445
- async updateNotification(id, partial) {
446
- // The basic Notification API has no update mechanism. Simulate by closing and re-opening.
447
- const existing = _live.get(id);
448
- const originalRequest = _requests.get(id);
449
- if (existing === undefined || originalRequest === undefined)
450
- return false;
451
- try {
452
- existing.close();
453
- _live.delete(id);
454
- _requests.delete(id);
455
- }
456
- catch {
457
- // Guarded — some browsers disallow closing programmatically.
458
- }
459
- // Merge the partial fields into the original request, preserving the stable id.
460
- const merged = { ...originalRequest, ...partial, id };
461
- await _notify(merged);
462
- return true;
463
- },
464
- };
465
- }
466
- // Deletes the notification channel with the given id. No-ops on backends without channel support.
467
- export function deleteNotificationChannel(id) {
468
- const backend = getNotificationBackend();
469
- backend.deleteNotificationChannel?.(id);
470
- }
471
- export function explainNotificationBackend() {
472
- if (_custom !== null) {
473
- return { conflict: _hostConflict, layer: 'custom', operation: null, viability: 'unobserved' };
62
+ if (outcome.reason === 'ok' || outcome.reason === 'already-closed') {
63
+ _notificationClose.delete(notification);
64
+ _closedNotifications.add(notification);
474
65
  }
475
- if (_host !== null) {
66
+ return outcome;
67
+ }
68
+ export function createNotificationActionSubscription() {
69
+ return createNotificationSubscription({
70
+ onNotificationAction: createSignal(),
71
+ });
72
+ }
73
+ export function createNotificationClickSubscription() {
74
+ return createNotificationSubscription({
75
+ onNotificationClick: createSignal(),
76
+ });
77
+ }
78
+ export function createNotificationDismissSubscription() {
79
+ return createNotificationSubscription({
80
+ onNotificationDismiss: createSignal(),
81
+ });
82
+ }
83
+ export function createNotificationReceivedSubscription() {
84
+ return createNotificationSubscription({
85
+ onNotificationReceived: createSignal(),
86
+ });
87
+ }
88
+ export function createNotificationReplySubscription() {
89
+ return createNotificationSubscription({
90
+ onNotificationReply: createSignal(),
91
+ });
92
+ }
93
+ // Provider-contract constructor. Provider-local native keys never enter this public Entity.
94
+ export function createNotificationResource(id, title, tag = '') {
95
+ return createEntity({ id, tag, title });
96
+ }
97
+ // Provider-contract constructor for one pending native schedule.
98
+ export function createScheduledNotificationResource(id, request, schedule) {
99
+ return createEntity({ id, request, schedule });
100
+ }
101
+ export function destroyNotificationCapabilities(host) {
102
+ return host.notification.lifecycle.destroy();
103
+ }
104
+ export function detachNotificationActionSubscription(subscription) {
105
+ return detachNotificationSubscription(subscription);
106
+ }
107
+ export function detachNotificationClickSubscription(subscription) {
108
+ return detachNotificationSubscription(subscription);
109
+ }
110
+ export function detachNotificationDismissSubscription(subscription) {
111
+ return detachNotificationSubscription(subscription);
112
+ }
113
+ export function detachNotificationReceivedSubscription(subscription) {
114
+ return detachNotificationSubscription(subscription);
115
+ }
116
+ export function detachNotificationReplySubscription(subscription) {
117
+ return detachNotificationSubscription(subscription);
118
+ }
119
+ export async function disposeNotificationActionSubscription(subscription) {
120
+ return disposeNotificationSubscription(subscription, subscription.onNotificationAction);
121
+ }
122
+ export async function disposeNotificationClickSubscription(subscription) {
123
+ return disposeNotificationSubscription(subscription, subscription.onNotificationClick);
124
+ }
125
+ export async function disposeNotificationDismissSubscription(subscription) {
126
+ return disposeNotificationSubscription(subscription, subscription.onNotificationDismiss);
127
+ }
128
+ export async function disposeNotificationReceivedSubscription(subscription) {
129
+ return disposeNotificationSubscription(subscription, subscription.onNotificationReceived);
130
+ }
131
+ export async function disposeNotificationReplySubscription(subscription) {
132
+ return disposeNotificationSubscription(subscription, subscription.onNotificationReply);
133
+ }
134
+ export function getActiveNotifications(host) {
135
+ return host.notification.activeList.getActiveNotifications();
136
+ }
137
+ export function getNotificationPermission(host) {
138
+ return host.notification.permission.getPermission();
139
+ }
140
+ export function getPendingNotifications(host) {
141
+ return host.notification.scheduling.getPendingNotifications();
142
+ }
143
+ export function requestNotificationPermission(host) {
144
+ return host.notification.permission.requestPermission();
145
+ }
146
+ export function scheduleNotification(host, request, schedule) {
147
+ return host.notification.scheduling.scheduleNotification(request, schedule);
148
+ }
149
+ export function showNotification(host, request) {
150
+ return host.notification.delivery.notify(request);
151
+ }
152
+ function createNotificationSubscription(fields) {
153
+ const subscription = createEntity(fields);
154
+ _notificationSubscriptions.set(subscription, {
155
+ attachment: null,
156
+ disposeCompleted: false,
157
+ disposed: false,
158
+ generation: 0,
159
+ pending: null,
160
+ });
161
+ return subscription;
162
+ }
163
+ async function attachNotificationSubscription(subscription, attach, listener) {
164
+ const runtime = _notificationSubscriptions.get(subscription);
165
+ if (runtime === undefined || runtime.disposed) {
476
166
  return {
477
- conflict: _hostConflict,
478
- layer: 'host',
479
- operation: _hostObservation !== null ? _hostObservation.operation : null,
480
- viability: _hostObservation !== null ? _hostObservation.viability : 'unobserved',
167
+ attachFailed: true,
168
+ reason: 'operation-failed',
169
+ releaseFailed: false,
481
170
  };
482
171
  }
483
- return { conflict: false, layer: 'host-not-enabled', operation: null, viability: 'unobserved' };
484
- }
485
- // Returns all currently-displayed notifications. Returns an empty array on backends that do not
486
- // support active-notification introspection.
487
- export function getActiveNotifications() {
488
- return getNotificationBackend().getActiveNotifications();
489
- }
490
- // Returns the notification the app was launched from, or null when the app was not launched via
491
- // a notification tap. On web this always returns null.
492
- export function getLaunchNotification() {
493
- return getNotificationBackend().getLaunchNotification();
494
- }
495
- export function getNotificationBackend() {
496
- return _custom ?? _host ?? _sentinel;
497
- }
498
- // Returns a plain-data record of what the active backend supports.
499
- export function getNotificationCapabilities() {
500
- return getNotificationBackend().getCapabilities();
501
- }
502
- // Returns the list of currently-registered notification channels. Returns an empty array on
503
- // backends that do not support channels (e.g. web).
504
- export function getNotificationChannels() {
505
- const backend = getNotificationBackend();
506
- return backend.getNotificationChannels?.() ?? [];
507
- }
508
- // Returns the current notification permission state: 'default' (not yet asked), 'granted', or 'denied'.
509
- export function getNotificationPermission() {
510
- return getNotificationBackend().getPermission();
511
- }
512
- // Returns all locally-scheduled (not yet delivered) notifications.
513
- export function getPendingNotifications() {
514
- return getNotificationBackend().getPendingNotifications();
515
- }
516
- export function installNotificationHostBackend(backend) {
517
- if (_host !== null) {
518
- if (_host !== backend)
519
- _hostConflict = true;
520
- return;
172
+ const detached = await detachNotificationSubscription(subscription);
173
+ if (detached.reason === 'operation-failed') {
174
+ return {
175
+ attachFailed: false,
176
+ reason: 'operation-failed',
177
+ releaseFailed: true,
178
+ };
521
179
  }
522
- const previous = getNotificationBackend();
523
- _host = backend;
524
- rebindNotificationSubscriptions(previous, getNotificationBackend());
525
- }
526
- // True when the host can show notifications. Cheap; reads the active backend.
527
- export function isNotificationSupported() {
528
- return getNotificationBackend().isSupported();
529
- }
530
- // Forwards a service-worker click/action event received via postMessage to the given SW backend's
531
- // listeners. Call this from your page's `navigator.serviceWorker.addEventListener('message', ...)`
532
- // handler when the SW posts a `{ type: 'notificationclick', notificationId, actionId?, reply? }`
533
- // message. When `reply` is present alongside `actionId` (a `text-input` action), the reply text is
534
- // routed to onNotificationReply listeners; otherwise an `actionId` routes to action listeners and a
535
- // bare message routes to click listeners.
536
- export function notifyServiceWorkerBackendAction(backend, message) {
537
- if (message.type !== 'notificationclick')
538
- return;
539
- const b = backend;
540
- if (message.actionId !== undefined && message.reply !== undefined && b._dispatchReply !== undefined) {
541
- b._dispatchReply(message.notificationId, message.actionId, message.reply);
180
+ const generation = ++runtime.generation;
181
+ let pending;
182
+ try {
183
+ pending = attach(listener);
542
184
  }
543
- else if (message.actionId !== undefined && b._dispatchAction !== undefined) {
544
- b._dispatchAction(message.notificationId, message.actionId);
185
+ catch {
186
+ return {
187
+ attachFailed: true,
188
+ reason: 'operation-failed',
189
+ releaseFailed: false,
190
+ };
545
191
  }
546
- else if (b._dispatchClick !== undefined) {
547
- b._dispatchClick(message.notificationId);
192
+ runtime.pending = pending;
193
+ let outcome;
194
+ try {
195
+ outcome = await pending;
548
196
  }
549
- }
550
- export function observeNotificationHostResult(operation, succeeded) {
551
- _hostObservation = {
552
- operation,
553
- viability: succeeded ? 'available' : 'runtime-api-unavailable',
554
- };
555
- }
556
- // Subscribes to notification action-button activations, delivering the notification id and action id.
557
- // Returns an unsubscribe function. On the basic web backend this never fires; a native host or the
558
- // service-worker web backend is required for action delivery.
559
- export function onNotificationAction(listener) {
560
- return registerNotificationSubscription(listener, (backend, handler) => backend.subscribeAction(handler));
561
- }
562
- // Subscribes to notification body clicks, delivering the notification id.
563
- // Returns an unsubscribe function. On the basic web backend clicks are delivered per-instance via
564
- // the onclick event (wired by createWebNotificationBackend); a native host delivers a global feed.
565
- export function onNotificationClick(listener) {
566
- return registerNotificationSubscription(listener, (backend, handler) => backend.subscribeClick(handler));
567
- }
568
- // Subscribes to notification dismiss/close events, delivering the notification id.
569
- // Returns an unsubscribe function.
570
- export function onNotificationDismiss(listener) {
571
- return registerNotificationSubscription(listener, (backend, handler) => backend.subscribeDismiss(handler));
572
- }
573
- // Subscribes to inline-reply text actions, delivering the notification id, action id, and reply text.
574
- // Returns an unsubscribe function. Requires native host or service-worker backend; never fires on
575
- // the basic web backend.
576
- export function onNotificationReply(listener) {
577
- return registerNotificationSubscription(listener, (backend, handler) => backend.subscribeReply(handler));
578
- }
579
- // Subscribes to notification show events, delivering the notification id. Returns an unsubscribe function.
580
- export function onNotificationShow(listener) {
581
- return registerNotificationSubscription(listener, (backend, handler) => backend.subscribeShow(handler));
582
- }
583
- // Requests notification permission. Returns the tri-state result: 'granted', 'denied', or 'default'
584
- // (user dismissed the prompt without deciding). 'denied' is also returned when the host lacks the
585
- // notification surface. Use getNotificationPermission() to read the current state without prompting.
586
- export function requestNotificationPermission() {
587
- return getNotificationBackend().requestPermission();
588
- }
589
- export function resetNotificationBackendForTest() {
590
- const previous = getNotificationBackend();
591
- _custom = null;
592
- _host = null;
593
- _hostConflict = false;
594
- _hostObservation = null;
595
- rebindNotificationSubscriptions(previous, getNotificationBackend());
596
- }
597
- // Schedules a local notification for delivery at the time specified in the schedule. Returns the
598
- // notification id (echoes request.id when provided, else a generated id). Returns '' when
599
- // scheduling is not supported. On the basic web backend this uses setTimeout (best-effort,
600
- // cleared on page reload); native backends use the OS scheduler.
601
- export function scheduleNotification(request, schedule) {
602
- return getNotificationBackend().scheduleNotification(request, schedule);
603
- }
604
- export function setNotificationBackend(backend) {
605
- const previous = getNotificationBackend();
606
- _custom = backend;
607
- rebindNotificationSubscriptions(previous, getNotificationBackend());
608
- }
609
- // Shows a notification. Returns the notification id (echoes request.id when provided, else a
610
- // generated id). Returns '' when permission is not granted or the host lacks the surface.
611
- export function showNotification(request) {
612
- return getNotificationBackend().notify(request);
613
- }
614
- // Updates a live notification. Partial fields are merged into the existing notification — useful for
615
- // progress bars and live-content updates (e.g. download percentage). Returns true when the update
616
- // was applied; false when the notification is no longer visible or the backend does not support
617
- // updates. The basic web backend simulates updates by closing and re-opening the notification.
618
- export function updateNotification(id, partial) {
619
- return getNotificationBackend().updateNotification(id, partial);
620
- }
621
- function _repeatMs(repeat) {
622
- switch (repeat) {
623
- case 'minute':
624
- return 60_000;
625
- case 'hour':
626
- return 3_600_000;
627
- case 'day':
628
- return 86_400_000;
629
- case 'week':
630
- return 604_800_000;
631
- case 'month':
632
- return 2_592_000_000;
633
- case 'year':
634
- return 31_536_000_000;
197
+ catch {
198
+ outcome = { reason: 'operation-failed', releaseFailed: false };
635
199
  }
636
- }
637
- const _noop = () => () => { };
638
- let _custom = null;
639
- let _host = null;
640
- let _hostConflict = false;
641
- let _hostObservation = null;
642
- const _sentinel = {
643
- cancelScheduledNotification() { },
644
- closeAllNotifications() { },
645
- closeNotification() { },
646
- getCapabilities() {
200
+ if (runtime.pending === pending)
201
+ runtime.pending = null;
202
+ if (outcome.reason === 'operation-failed') {
647
203
  return {
648
- actions: false,
649
- channels: false,
650
- coldStart: false,
651
- image: false,
652
- listActive: false,
653
- scheduling: false,
654
- textReply: false,
204
+ attachFailed: true,
205
+ reason: 'operation-failed',
206
+ releaseFailed: outcome.releaseFailed,
655
207
  };
656
- },
657
- async getActiveNotifications() {
658
- return [];
659
- },
660
- async getLaunchNotification() {
661
- return null;
662
- },
663
- async getPendingNotifications() {
664
- return [];
665
- },
666
- getPermission() {
667
- return 'denied';
668
- },
669
- isSupported() {
670
- return false;
671
- },
672
- async notify() {
673
- return '';
674
- },
675
- async requestPermission() {
676
- return 'denied';
677
- },
678
- async scheduleNotification() {
679
- return '';
680
- },
681
- subscribeAction: _noop,
682
- subscribeClick: _noop,
683
- subscribeDismiss: _noop,
684
- subscribeReply: _noop,
685
- subscribeShow: _noop,
686
- async updateNotification() {
687
- return false;
688
- },
689
- };
690
- // Module-level notification listeners are unbounded relationships: they survive provider swaps.
691
- // The registry owns only these public subscriptions; backend-internal resources remain backend-owned.
692
- const _notificationSubscriptions = new Set();
693
- function registerNotificationSubscription(listener, subscribe) {
694
- let activeUnsubscribe = subscribe(getNotificationBackend(), listener);
695
- const entry = {
696
- rebind(backend) {
697
- activeUnsubscribe();
698
- activeUnsubscribe = subscribe(backend, listener);
699
- },
700
- unsubscribe() {
701
- if (!_notificationSubscriptions.delete(entry))
702
- return;
703
- activeUnsubscribe();
704
- },
705
- };
706
- _notificationSubscriptions.add(entry);
707
- return entry.unsubscribe;
708
- }
709
- function rebindNotificationSubscriptions(previous, next) {
710
- if (previous === next)
711
- return;
712
- for (const subscription of _notificationSubscriptions)
713
- subscription.rebind(next);
208
+ }
209
+ if (runtime.disposed || runtime.generation !== generation) {
210
+ const release = await releaseNotificationAttachment(outcome.attachment);
211
+ return release.reason === 'ok'
212
+ ? { reason: 'ok' }
213
+ : {
214
+ attachFailed: false,
215
+ reason: 'operation-failed',
216
+ releaseFailed: true,
217
+ };
218
+ }
219
+ runtime.attachment = outcome.attachment;
220
+ return { reason: 'ok' };
221
+ }
222
+ async function detachNotificationSubscription(subscription) {
223
+ const runtime = _notificationSubscriptions.get(subscription);
224
+ if (runtime === undefined || runtime.attachment === null)
225
+ return { reason: 'not-attached' };
226
+ const attachment = runtime.attachment;
227
+ const outcome = await releaseNotificationAttachment(attachment);
228
+ if (outcome.reason === 'operation-failed')
229
+ return { reason: 'operation-failed', releaseFailed: true };
230
+ runtime.attachment = null;
231
+ return { reason: 'ok' };
232
+ }
233
+ async function disposeNotificationSubscription(subscription, signal) {
234
+ const runtime = _notificationSubscriptions.get(subscription);
235
+ if (runtime === undefined || runtime.disposeCompleted)
236
+ return { reason: 'already-disposed' };
237
+ runtime.disposed = true;
238
+ runtime.generation++;
239
+ let attachFailed = false;
240
+ let releaseFailed = false;
241
+ if (runtime.pending !== null) {
242
+ let outcome;
243
+ try {
244
+ outcome = await runtime.pending;
245
+ }
246
+ catch {
247
+ outcome = { reason: 'operation-failed', releaseFailed: false };
248
+ }
249
+ if (outcome.reason === 'operation-failed') {
250
+ attachFailed = true;
251
+ releaseFailed = outcome.releaseFailed;
252
+ }
253
+ }
254
+ const detached = await detachNotificationSubscription(subscription);
255
+ if (detached.reason === 'operation-failed')
256
+ releaseFailed = true;
257
+ clearSignal(signal);
258
+ if (attachFailed || releaseFailed)
259
+ return { attachFailed, reason: 'operation-failed', releaseFailed };
260
+ runtime.disposeCompleted = true;
261
+ return { reason: 'ok' };
262
+ }
263
+ async function releaseNotificationAttachment(attachment) {
264
+ try {
265
+ return await attachment.release();
266
+ }
267
+ catch {
268
+ return { reason: 'operation-failed' };
269
+ }
714
270
  }
271
+ const _notificationClose = new WeakMap();
272
+ const _closedNotifications = new WeakSet();
273
+ const _scheduledNotificationCancel = new WeakMap();
274
+ const _cancelledScheduledNotifications = new WeakSet();
275
+ const _notificationSubscriptions = new WeakMap();
715
276
  //# sourceMappingURL=notification.js.map