@tingping/web 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +73 -2
- package/dist/cjs/device-id.d.ts +13 -0
- package/dist/cjs/device-id.d.ts.map +1 -0
- package/dist/cjs/device-id.js +40 -0
- package/dist/cjs/device-id.js.map +1 -0
- package/dist/cjs/index.d.ts +6 -0
- package/dist/cjs/index.d.ts.map +1 -0
- package/dist/cjs/index.js +27 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/package.json +3 -0
- package/dist/cjs/provider.d.ts +55 -0
- package/dist/cjs/provider.d.ts.map +1 -0
- package/dist/cjs/provider.js +178 -0
- package/dist/cjs/provider.js.map +1 -0
- package/dist/cjs/push.d.ts +26 -0
- package/dist/cjs/push.d.ts.map +1 -0
- package/dist/cjs/push.js +105 -0
- package/dist/cjs/push.js.map +1 -0
- package/dist/cjs/sw-handlers.d.ts +53 -0
- package/dist/cjs/sw-handlers.d.ts.map +1 -0
- package/dist/cjs/sw-handlers.js +113 -0
- package/dist/cjs/sw-handlers.js.map +1 -0
- package/dist/esm/device-id.d.ts +13 -0
- package/dist/esm/device-id.d.ts.map +1 -0
- package/dist/esm/device-id.js +36 -0
- package/dist/esm/device-id.js.map +1 -0
- package/dist/esm/index.d.ts +6 -0
- package/dist/esm/index.d.ts.map +1 -0
- package/dist/esm/index.js +6 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/package.json +3 -0
- package/dist/esm/provider.d.ts +55 -0
- package/dist/esm/provider.d.ts.map +1 -0
- package/dist/esm/provider.js +174 -0
- package/dist/esm/provider.js.map +1 -0
- package/dist/esm/push.d.ts +26 -0
- package/dist/esm/push.d.ts.map +1 -0
- package/dist/esm/push.js +97 -0
- package/dist/esm/push.js.map +1 -0
- package/dist/esm/sw-handlers.d.ts +53 -0
- package/dist/esm/sw-handlers.d.ts.map +1 -0
- package/dist/esm/sw-handlers.js +105 -0
- package/dist/esm/sw-handlers.js.map +1 -0
- package/dist/sw.js +97 -0
- package/package.json +69 -4
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
|
|
3
|
+
import { TingPingClient, } from '@tingping/client-core';
|
|
4
|
+
import { getOrCreateDeviceId } from './device-id.js';
|
|
5
|
+
import { currentPushPermission, fetchVapidPublicKey, isPushSupported, subscribeToPush, unsubscribeFromPush, } from './push.js';
|
|
6
|
+
import { SW_MESSAGE } from './sw-handlers.js';
|
|
7
|
+
const TingPingContext = createContext(null);
|
|
8
|
+
function stableKey(value) {
|
|
9
|
+
return JSON.stringify(value ?? null);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Declarative tingping for React web apps: registers the browser, keeps a live
|
|
13
|
+
* WebSocket, wires Web Push and exposes everything through `useTingPing()`.
|
|
14
|
+
*/
|
|
15
|
+
export function TingPingProvider(props) {
|
|
16
|
+
const { serverUrl, userId, tenantId = null, enablePush = true, vapidPublicKey, serviceWorkerUrl = '/sw.js', autoRequestPermission = false, children, } = props;
|
|
17
|
+
const [status, setStatus] = useState('idle');
|
|
18
|
+
const [notifications, setNotifications] = useState([]);
|
|
19
|
+
const [error, setError] = useState(null);
|
|
20
|
+
const [deviceId, setDeviceId] = useState(null);
|
|
21
|
+
const [pushPermission, setPushPermission] = useState(() => currentPushPermission());
|
|
22
|
+
const [pushEnabled, setPushEnabled] = useState(false);
|
|
23
|
+
// Callbacks and object props live in refs so that inline values do not reconnect.
|
|
24
|
+
const latest = useRef(props);
|
|
25
|
+
latest.current = props;
|
|
26
|
+
const clientRef = useRef(null);
|
|
27
|
+
const topicsKey = stableKey(props.topics);
|
|
28
|
+
const metaKey = stableKey(props.deviceMeta);
|
|
29
|
+
const optionsKey = stableKey(Object.keys(props.clientOptions ?? {}));
|
|
30
|
+
const subscribe = useCallback(async (requestPermission) => {
|
|
31
|
+
if (!enablePush || !isPushSupported())
|
|
32
|
+
return false;
|
|
33
|
+
const fetchImpl = latest.current.clientOptions?.fetch ?? fetch;
|
|
34
|
+
const key = vapidPublicKey ?? (await fetchVapidPublicKey(serverUrl, fetchImpl));
|
|
35
|
+
if (key === null)
|
|
36
|
+
return false;
|
|
37
|
+
const subscription = await subscribeToPush({ vapidPublicKey: key, serviceWorkerUrl, requestPermission });
|
|
38
|
+
setPushPermission(currentPushPermission());
|
|
39
|
+
if (subscription === null)
|
|
40
|
+
return false;
|
|
41
|
+
clientRef.current?.setSubscription(subscription);
|
|
42
|
+
setPushEnabled(true);
|
|
43
|
+
return true;
|
|
44
|
+
}, [enablePush, vapidPublicKey, serverUrl, serviceWorkerUrl]);
|
|
45
|
+
useEffect(() => {
|
|
46
|
+
if (!userId) {
|
|
47
|
+
setStatus('idle');
|
|
48
|
+
setDeviceId(null);
|
|
49
|
+
return undefined;
|
|
50
|
+
}
|
|
51
|
+
let cancelled = false;
|
|
52
|
+
const id = getOrCreateDeviceId();
|
|
53
|
+
setDeviceId(id);
|
|
54
|
+
setError(null);
|
|
55
|
+
const current = latest.current;
|
|
56
|
+
const client = new TingPingClient({
|
|
57
|
+
serverUrl,
|
|
58
|
+
userId,
|
|
59
|
+
tenantId,
|
|
60
|
+
deviceId: id,
|
|
61
|
+
platform: 'web',
|
|
62
|
+
authToken: async () => {
|
|
63
|
+
const source = latest.current.authToken;
|
|
64
|
+
return typeof source === 'function' ? source() : source;
|
|
65
|
+
},
|
|
66
|
+
topics: current.topics ?? [],
|
|
67
|
+
deviceMeta: current.deviceMeta ?? {},
|
|
68
|
+
...current.clientOptions,
|
|
69
|
+
});
|
|
70
|
+
clientRef.current = client;
|
|
71
|
+
const offs = [
|
|
72
|
+
client.on('status', (s) => {
|
|
73
|
+
if (!cancelled)
|
|
74
|
+
setStatus(s);
|
|
75
|
+
}),
|
|
76
|
+
client.on('notification', (frame) => {
|
|
77
|
+
if (cancelled)
|
|
78
|
+
return;
|
|
79
|
+
setNotifications((list) => [frame, ...list].slice(0, Math.max(1, latest.current.maxNotifications ?? 50)));
|
|
80
|
+
latest.current.onNotification?.(frame);
|
|
81
|
+
}),
|
|
82
|
+
client.on('error', (e) => {
|
|
83
|
+
if (!cancelled)
|
|
84
|
+
setError(e);
|
|
85
|
+
}),
|
|
86
|
+
];
|
|
87
|
+
void (async () => {
|
|
88
|
+
try {
|
|
89
|
+
if (currentPushPermission() === 'granted' || autoRequestPermission)
|
|
90
|
+
await subscribe(autoRequestPermission);
|
|
91
|
+
}
|
|
92
|
+
catch (e) {
|
|
93
|
+
if (!cancelled)
|
|
94
|
+
setError(e instanceof Error ? e : new Error(String(e)));
|
|
95
|
+
}
|
|
96
|
+
if (!cancelled)
|
|
97
|
+
await client.start();
|
|
98
|
+
})();
|
|
99
|
+
const reconnect = () => client.reconnectNow();
|
|
100
|
+
const onVisibility = () => {
|
|
101
|
+
if (document.visibilityState === 'visible')
|
|
102
|
+
client.reconnectNow();
|
|
103
|
+
};
|
|
104
|
+
globalThis.addEventListener?.('online', reconnect);
|
|
105
|
+
globalThis.document?.addEventListener('visibilitychange', onVisibility);
|
|
106
|
+
return () => {
|
|
107
|
+
cancelled = true;
|
|
108
|
+
for (const off of offs)
|
|
109
|
+
off();
|
|
110
|
+
client.disconnect();
|
|
111
|
+
if (clientRef.current === client)
|
|
112
|
+
clientRef.current = null;
|
|
113
|
+
globalThis.removeEventListener?.('online', reconnect);
|
|
114
|
+
globalThis.document?.removeEventListener('visibilitychange', onVisibility);
|
|
115
|
+
};
|
|
116
|
+
// Object props are compared by value (topicsKey, metaKey, optionsKey); callbacks are read from `latest`.
|
|
117
|
+
}, [serverUrl, userId, tenantId, topicsKey, metaKey, optionsKey, subscribe, autoRequestPermission]);
|
|
118
|
+
useEffect(() => {
|
|
119
|
+
const container = globalThis.navigator?.serviceWorker;
|
|
120
|
+
if (container === undefined)
|
|
121
|
+
return undefined;
|
|
122
|
+
const onMessage = (event) => {
|
|
123
|
+
const data = event.data;
|
|
124
|
+
if (data?.type === SW_MESSAGE.CLICK && data.frame)
|
|
125
|
+
latest.current.onNotificationTap?.(data.frame);
|
|
126
|
+
};
|
|
127
|
+
container.addEventListener('message', onMessage);
|
|
128
|
+
return () => container.removeEventListener('message', onMessage);
|
|
129
|
+
}, []);
|
|
130
|
+
const requestPushPermission = useCallback(async () => {
|
|
131
|
+
try {
|
|
132
|
+
if (await subscribe(true))
|
|
133
|
+
await clientRef.current?.register();
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
setError(e instanceof Error ? e : new Error(String(e)));
|
|
137
|
+
}
|
|
138
|
+
const permission = currentPushPermission();
|
|
139
|
+
setPushPermission(permission);
|
|
140
|
+
return permission;
|
|
141
|
+
}, [subscribe]);
|
|
142
|
+
const unregister = useCallback(async () => {
|
|
143
|
+
await clientRef.current?.unregister();
|
|
144
|
+
try {
|
|
145
|
+
await unsubscribeFromPush(serviceWorkerUrl);
|
|
146
|
+
}
|
|
147
|
+
finally {
|
|
148
|
+
setPushEnabled(false);
|
|
149
|
+
}
|
|
150
|
+
}, [serviceWorkerUrl]);
|
|
151
|
+
const clearNotifications = useCallback(() => setNotifications([]), []);
|
|
152
|
+
const value = useMemo(() => ({
|
|
153
|
+
status,
|
|
154
|
+
isConnected: status === 'open',
|
|
155
|
+
lastNotification: notifications[0] ?? null,
|
|
156
|
+
notifications,
|
|
157
|
+
error,
|
|
158
|
+
deviceId,
|
|
159
|
+
pushPermission,
|
|
160
|
+
pushEnabled,
|
|
161
|
+
requestPushPermission,
|
|
162
|
+
unregister,
|
|
163
|
+
clearNotifications,
|
|
164
|
+
}), [status, notifications, error, deviceId, pushPermission, pushEnabled, requestPushPermission, unregister, clearNotifications]);
|
|
165
|
+
return _jsx(TingPingContext.Provider, { value: value, children: children });
|
|
166
|
+
}
|
|
167
|
+
/** Live tingping state for the nearest `<TingPingProvider>`. */
|
|
168
|
+
export function useTingPing() {
|
|
169
|
+
const value = useContext(TingPingContext);
|
|
170
|
+
if (value === null)
|
|
171
|
+
throw new Error('useTingPing() must be used inside <TingPingProvider>');
|
|
172
|
+
return value;
|
|
173
|
+
}
|
|
174
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/provider.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,UAAU,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAkB,MAAM,OAAO,CAAC;AACrH,OAAO,EACL,cAAc,GAKf,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACrD,OAAO,EACL,qBAAqB,EACrB,mBAAmB,EACnB,eAAe,EACf,eAAe,EACf,mBAAmB,GAEpB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAkD9C,MAAM,eAAe,GAAG,aAAa,CAA8B,IAAI,CAAC,CAAC;AAEzE,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,IAAI,IAAI,CAAC,CAAC;AACvC,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,gBAAgB,CAAC,KAA4B;IAC3D,MAAM,EACJ,SAAS,EACT,MAAM,EACN,QAAQ,GAAG,IAAI,EACf,UAAU,GAAG,IAAI,EACjB,cAAc,EACd,gBAAgB,GAAG,QAAQ,EAC3B,qBAAqB,GAAG,KAAK,EAC7B,QAAQ,GACT,GAAG,KAAK,CAAC;IAEV,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,GAAG,QAAQ,CAAmB,MAAM,CAAC,CAAC;IAC/D,MAAM,CAAC,aAAa,EAAE,gBAAgB,CAAC,GAAG,QAAQ,CAAsB,EAAE,CAAC,CAAC;IAC5E,MAAM,CAAC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AAC;QACL,MAAM;QACN,WAAW,EAAE,MAAM,KAAK,MAAM;QAC9B,gBAAgB,EAAE,aAAa,CAAC,CAAC,CAAC,IAAI,IAAI;QAC1C,aAAa;QACb,KAAK;QACL,QAAQ;QACR,cAAc;QACd,WAAW;QACX,qBAAqB;QACrB,UAAU;QACV,kBAAkB;KACnB,CAAC,EACF,CAAC,MAAM,EAAE,aAAa,EAAE,KAAK,EAAE,QAAQ,EAAE,cAAc,EAAE,WAAW,EAAE,qBAAqB,EAAE,UAAU,EAAE,kBAAkB,CAAC,CAC7H,CAAC;IAEF,OAAO,KAAC,eAAe,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAA4B,CAAC;AACvF,CAAC;AAED,gEAAgE;AAChE,MAAM,UAAU,WAAW;IACzB,MAAM,KAAK,GAAG,UAAU,CAAC,eAAe,CAAC,CAAC;IAC1C,IAAI,KAAK,KAAK,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC5F,OAAO,KAAK,CAAC;AACf,CAAC"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { WebPushSubscriptionJSON } from '@tingping/client-core';
|
|
2
|
+
/** Whether this browser supports Service Workers + Push API + Notifications. */
|
|
3
|
+
export declare function isPushSupported(): boolean;
|
|
4
|
+
export type PushPermission = NotificationPermission | 'unsupported';
|
|
5
|
+
export declare function currentPushPermission(): PushPermission;
|
|
6
|
+
/** Decodes a URL-safe base64 VAPID key into the bytes `applicationServerKey` expects. */
|
|
7
|
+
export declare function urlBase64ToUint8Array(base64: string): Uint8Array<ArrayBuffer>;
|
|
8
|
+
/** Fetches the server's VAPID public key; null when Web Push is not configured. */
|
|
9
|
+
export declare function fetchVapidPublicKey(serverUrl: string, fetchImpl?: typeof fetch): Promise<string | null>;
|
|
10
|
+
export interface SubscribeOptions {
|
|
11
|
+
vapidPublicKey: string;
|
|
12
|
+
/** URL of the service worker script. Default `/sw.js`. */
|
|
13
|
+
serviceWorkerUrl?: string;
|
|
14
|
+
serviceWorkerScope?: string;
|
|
15
|
+
/** Ask for permission when it is still `default`. Browsers may require a user gesture. */
|
|
16
|
+
requestPermission?: boolean;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Registers the service worker and returns a Web Push subscription for the given
|
|
20
|
+
* VAPID key, reusing the current one when it matches. Returns null when push is
|
|
21
|
+
* unsupported or permission is not granted.
|
|
22
|
+
*/
|
|
23
|
+
export declare function subscribeToPush(options: SubscribeOptions): Promise<WebPushSubscriptionJSON | null>;
|
|
24
|
+
/** Removes the browser's push subscription, if any. */
|
|
25
|
+
export declare function unsubscribeFromPush(serviceWorkerUrl?: string): Promise<boolean>;
|
|
26
|
+
//# sourceMappingURL=push.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push.d.ts","sourceRoot":"","sources":["../../src/push.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,uBAAuB,CAAC;AAErE,gFAAgF;AAChF,wBAAgB,eAAe,IAAI,OAAO,CAOzC;AAED,MAAM,MAAM,cAAc,GAAG,sBAAsB,GAAG,aAAa,CAAC;AAEpE,wBAAgB,qBAAqB,IAAI,cAAc,CAGtD;AAED,yFAAyF;AACzF,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC,WAAW,CAAC,CAO7E;AAED,mFAAmF;AACnF,wBAAsB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,SAAS,GAAE,OAAO,KAAa,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,CAOpH;AA2BD,MAAM,WAAW,gBAAgB;IAC/B,cAAc,EAAE,MAAM,CAAC;IACvB,0DAA0D;IAC1D,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,0FAA0F;IAC1F,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;;GAIG;AACH,wBAAsB,eAAe,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,uBAAuB,GAAG,IAAI,CAAC,CAyBxG;AAED,uDAAuD;AACvD,wBAAsB,mBAAmB,CAAC,gBAAgB,SAAW,GAAG,OAAO,CAAC,OAAO,CAAC,CAKvF"}
|
package/dist/esm/push.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/** Whether this browser supports Service Workers + Push API + Notifications. */
|
|
2
|
+
export function isPushSupported() {
|
|
3
|
+
const g = globalThis;
|
|
4
|
+
return g.navigator?.serviceWorker !== undefined && g.PushManager !== undefined && g.Notification !== undefined;
|
|
5
|
+
}
|
|
6
|
+
export function currentPushPermission() {
|
|
7
|
+
if (!isPushSupported())
|
|
8
|
+
return 'unsupported';
|
|
9
|
+
return Notification.permission;
|
|
10
|
+
}
|
|
11
|
+
/** Decodes a URL-safe base64 VAPID key into the bytes `applicationServerKey` expects. */
|
|
12
|
+
export function urlBase64ToUint8Array(base64) {
|
|
13
|
+
const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
|
|
14
|
+
const standard = padded.replace(/-/g, '+').replace(/_/g, '/');
|
|
15
|
+
const raw = atob(standard);
|
|
16
|
+
const out = new Uint8Array(new ArrayBuffer(raw.length));
|
|
17
|
+
for (let i = 0; i < raw.length; i += 1)
|
|
18
|
+
out[i] = raw.charCodeAt(i);
|
|
19
|
+
return out;
|
|
20
|
+
}
|
|
21
|
+
/** Fetches the server's VAPID public key; null when Web Push is not configured. */
|
|
22
|
+
export async function fetchVapidPublicKey(serverUrl, fetchImpl = fetch) {
|
|
23
|
+
const base = serverUrl.endsWith('/') ? serverUrl.slice(0, -1) : serverUrl;
|
|
24
|
+
const response = await fetchImpl(`${base}/vapid-public-key`);
|
|
25
|
+
if (response.status === 404)
|
|
26
|
+
return null;
|
|
27
|
+
if (!response.ok)
|
|
28
|
+
throw new Error(`fetching the VAPID key failed with HTTP ${response.status}`);
|
|
29
|
+
const body = (await response.json());
|
|
30
|
+
return typeof body.public_key === 'string' ? body.public_key : null;
|
|
31
|
+
}
|
|
32
|
+
function waitForActivation(registration) {
|
|
33
|
+
if (registration.active !== null)
|
|
34
|
+
return Promise.resolve();
|
|
35
|
+
const worker = registration.installing ?? registration.waiting;
|
|
36
|
+
if (worker === null)
|
|
37
|
+
return Promise.resolve();
|
|
38
|
+
return new Promise((resolve, reject) => {
|
|
39
|
+
const onChange = () => {
|
|
40
|
+
if (worker.state === 'activated') {
|
|
41
|
+
worker.removeEventListener('statechange', onChange);
|
|
42
|
+
resolve();
|
|
43
|
+
}
|
|
44
|
+
else if (worker.state === 'redundant') {
|
|
45
|
+
worker.removeEventListener('statechange', onChange);
|
|
46
|
+
reject(new Error('the tingping service worker failed to install'));
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
worker.addEventListener('statechange', onChange);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
function sameKey(a, b) {
|
|
53
|
+
if (a === null || a === undefined)
|
|
54
|
+
return false;
|
|
55
|
+
const left = new Uint8Array(a);
|
|
56
|
+
if (left.length !== b.length)
|
|
57
|
+
return false;
|
|
58
|
+
return left.every((value, index) => value === b[index]);
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Registers the service worker and returns a Web Push subscription for the given
|
|
62
|
+
* VAPID key, reusing the current one when it matches. Returns null when push is
|
|
63
|
+
* unsupported or permission is not granted.
|
|
64
|
+
*/
|
|
65
|
+
export async function subscribeToPush(options) {
|
|
66
|
+
if (!isPushSupported())
|
|
67
|
+
return null;
|
|
68
|
+
let permission = Notification.permission;
|
|
69
|
+
if (permission === 'default' && options.requestPermission === true) {
|
|
70
|
+
permission = await Notification.requestPermission();
|
|
71
|
+
}
|
|
72
|
+
if (permission !== 'granted')
|
|
73
|
+
return null;
|
|
74
|
+
const registration = await navigator.serviceWorker.register(options.serviceWorkerUrl ?? '/sw.js', options.serviceWorkerScope === undefined ? undefined : { scope: options.serviceWorkerScope });
|
|
75
|
+
await waitForActivation(registration);
|
|
76
|
+
const key = urlBase64ToUint8Array(options.vapidPublicKey);
|
|
77
|
+
let subscription = await registration.pushManager.getSubscription();
|
|
78
|
+
if (subscription !== null && !sameKey(subscription.options.applicationServerKey, key)) {
|
|
79
|
+
await subscription.unsubscribe();
|
|
80
|
+
subscription = null;
|
|
81
|
+
}
|
|
82
|
+
subscription ??= await registration.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: key });
|
|
83
|
+
const json = subscription.toJSON();
|
|
84
|
+
if (!json.endpoint || !json.keys?.['p256dh'] || !json.keys['auth']) {
|
|
85
|
+
throw new Error('the browser returned an incomplete push subscription');
|
|
86
|
+
}
|
|
87
|
+
return { endpoint: json.endpoint, keys: { p256dh: json.keys['p256dh'], auth: json.keys['auth'] } };
|
|
88
|
+
}
|
|
89
|
+
/** Removes the browser's push subscription, if any. */
|
|
90
|
+
export async function unsubscribeFromPush(serviceWorkerUrl = '/sw.js') {
|
|
91
|
+
if (!isPushSupported())
|
|
92
|
+
return false;
|
|
93
|
+
const registration = await navigator.serviceWorker.getRegistration(serviceWorkerUrl);
|
|
94
|
+
const subscription = await registration?.pushManager.getSubscription();
|
|
95
|
+
return subscription ? subscription.unsubscribe() : false;
|
|
96
|
+
}
|
|
97
|
+
//# sourceMappingURL=push.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"push.js","sourceRoot":"","sources":["../../src/push.ts"],"names":[],"mappings":"AAEA,gFAAgF;AAChF,MAAM,UAAU,eAAe;IAC7B,MAAM,CAAC,GAAG,UAIT,CAAC;IACF,OAAO,CAAC,CAAC,SAAS,EAAE,aAAa,KAAK,SAAS,IAAI,CAAC,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,CAAC,YAAY,KAAK,SAAS,CAAC;AACjH,CAAC;AAID,MAAM,UAAU,qBAAqB;IACnC,IAAI,CAAC,eAAe,EAAE;QAAE,OAAO,aAAa,CAAC;IA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AAK,MAAM,YAAY,CAAC,WAAW,CAAC,SAAS,CAAC,EAAE,eAAe,EAAE,IAAI,EAAE,oBAAoB,EAAE,GAAG,EAAE,CAAC,CAAC;IAChH,MAAM,IAAI,GAAG,YAAY,CAAC,MAAM,EAAE,CAAC;IACnC,IAAI,CAAC,IAAI,CAAC,QAAQ,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;QACnE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IAC1E,CAAC;IACD,OAAO,EAAE,QAAQ,EAAE,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,EAAE,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC;AACrG,CAAC;AAED,uDAAuD;AACvD,MAAM,CAAC,KAAK,UAAU,mBAAmB,CAAC,gBAAgB,GAAG,QAAQ;IACnE,IAAI,CAAC,eAAe,EAAE;QAAE,OAAO,KAAK,CAAC;IACrC,MAAM,YAAY,GAAG,MAAM,SAAS,CAAC,aAAa,CAAC,eAAe,CAAC,gBAAgB,CAAC,CAAC;IACrF,MAAM,YAAY,GAAG,MAAM,YAAY,EAAE,WAAW,CAAC,eAAe,EAAE,CAAC;IACvE,OAAO,YAAY,CAAC,CAAC,CAAC,YAAY,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC;AAC3D,CAAC"}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { NotificationFrame } from '@tingping/client-core';
|
|
2
|
+
/**
|
|
3
|
+
* Service worker logic, kept free of global state so it can be unit-tested.
|
|
4
|
+
* `sw.ts` wires these handlers to the real `push` and `notificationclick` events.
|
|
5
|
+
*/
|
|
6
|
+
export declare const SW_MESSAGE: {
|
|
7
|
+
/** Posted to open windows for every push that arrives. */
|
|
8
|
+
readonly PUSH: 'TINGPING_PUSH';
|
|
9
|
+
/** Posted to open windows when the user taps a notification. */
|
|
10
|
+
readonly CLICK: 'TINGPING_NOTIFICATION_CLICK';
|
|
11
|
+
};
|
|
12
|
+
export interface SwClientLike {
|
|
13
|
+
url: string;
|
|
14
|
+
focused?: boolean;
|
|
15
|
+
visibilityState?: string;
|
|
16
|
+
postMessage(message: unknown): void;
|
|
17
|
+
focus?(): Promise<unknown>;
|
|
18
|
+
}
|
|
19
|
+
export interface SwScopeLike {
|
|
20
|
+
location: {
|
|
21
|
+
origin: string;
|
|
22
|
+
};
|
|
23
|
+
registration: {
|
|
24
|
+
showNotification(title: string, options?: Record<string, unknown>): Promise<void>;
|
|
25
|
+
};
|
|
26
|
+
clients: {
|
|
27
|
+
matchAll(options: {
|
|
28
|
+
type: 'window';
|
|
29
|
+
includeUncontrolled: boolean;
|
|
30
|
+
}): Promise<readonly SwClientLike[]>;
|
|
31
|
+
openWindow(url: string): Promise<unknown>;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export interface SwOptions {
|
|
35
|
+
/** Title for data-only pushes that arrive while no window is visible. Default "New update". */
|
|
36
|
+
fallbackTitle?: string;
|
|
37
|
+
/** Badge icon URL for every notification. */
|
|
38
|
+
badge?: string;
|
|
39
|
+
}
|
|
40
|
+
/** Parses a push message body into a NOTIFICATION frame, or null. */
|
|
41
|
+
export declare function parsePushPayload(text: string | null | undefined): NotificationFrame | null;
|
|
42
|
+
/** The `showNotification` arguments for a frame with visible content. */
|
|
43
|
+
export declare function notificationOptions(frame: NotificationFrame, options?: SwOptions): {
|
|
44
|
+
title: string;
|
|
45
|
+
options: Record<string, unknown>;
|
|
46
|
+
} | null;
|
|
47
|
+
/** Resolves a click_action into a safe same-origin or http(s) URL. */
|
|
48
|
+
export declare function resolveClickUrl(clickAction: string | null | undefined, origin: string): string;
|
|
49
|
+
/** Handles a `push` event. */
|
|
50
|
+
export declare function handlePush(scope: SwScopeLike, text: string | null, options?: SwOptions): Promise<void>;
|
|
51
|
+
/** Handles a `notificationclick` event, given the notification's `data`. */
|
|
52
|
+
export declare function handleNotificationClick(scope: SwScopeLike, data: unknown): Promise<void>;
|
|
53
|
+
//# sourceMappingURL=sw-handlers.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sw-handlers.d.ts","sourceRoot":"","sources":["../../src/sw-handlers.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE/D;;;GAGG;AAEH,eAAO,MAAM,UAAU;IACrB,0DAA0D;aAC1D,IAAI,EAAE,eAAe;IACrB,gEAAgE;aAChE,KAAK,EAAE,6BAA6B;CAC5B,CAAC;AAEX,MAAM,WAAW,YAAY;IAC3B,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,WAAW,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IACpC,KAAK,CAAC,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;CAC5B;AAED,MAAM,WAAW,WAAW;IAC1B,QAAQ,EAAE;QAAE,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IAC7B,YAAY,EAAE;QAAE,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;KAAE,CAAC;IACpG,OAAO,EAAE;QACP,QAAQ,CAAC,OAAO,EAAE;YAAE,IAAI,EAAE,QAAQ,CAAC;YAAC,mBAAmB,EAAE,OAAO,CAAA;SAAE,GAAG,OAAO,CAAC,SAAS,YAAY,EAAE,CAAC,CAAC;QACtG,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;KAC3C,CAAC;CACH;AAED,MAAM,WAAW,SAAS;IACxB,+FAA+F;IAC/F,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,6CAA6C;IAC7C,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,qEAAqE;AACrE,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,GAAG,iBAAiB,GAAG,IAAI,CAW1F;AAED,yEAAyE;AACzE,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,iBAAiB,EAAE,OAAO,GAAE,SAAc,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;CAAE,GAAG,IAAI,CAYjJ;AAED,sEAAsE;AACtE,wBAAgB,eAAe,CAAC,WAAW,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAS9F;AAMD,8BAA8B;AAC9B,wBAAsB,UAAU,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,GAAG,IAAI,EAAE,OAAO,GAAE,SAAc,GAAG,OAAO,CAAC,IAAI,CAAC,CAoBhH;AAED,4EAA4E;AAC5E,wBAAsB,uBAAuB,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,EAAE,OAAO,GAAG,OAAO,CAAC,IAAI,CAAC,CAmB9F"}
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Service worker logic, kept free of global state so it can be unit-tested.
|
|
3
|
+
* `sw.ts` wires these handlers to the real `push` and `notificationclick` events.
|
|
4
|
+
*/
|
|
5
|
+
export const SW_MESSAGE = {
|
|
6
|
+
/** Posted to open windows for every push that arrives. */
|
|
7
|
+
PUSH: 'TINGPING_PUSH',
|
|
8
|
+
/** Posted to open windows when the user taps a notification. */
|
|
9
|
+
CLICK: 'TINGPING_NOTIFICATION_CLICK',
|
|
10
|
+
};
|
|
11
|
+
/** Parses a push message body into a NOTIFICATION frame, or null. */
|
|
12
|
+
export function parsePushPayload(text) {
|
|
13
|
+
if (text === null || text === undefined || text === '')
|
|
14
|
+
return null;
|
|
15
|
+
try {
|
|
16
|
+
const value = JSON.parse(text);
|
|
17
|
+
if (value === null || typeof value !== 'object' || value.type !== 'NOTIFICATION' || typeof value.message_id !== 'string') {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
return value;
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The `showNotification` arguments for a frame with visible content. */
|
|
27
|
+
export function notificationOptions(frame, options = {}) {
|
|
28
|
+
if (frame.notification === null)
|
|
29
|
+
return null;
|
|
30
|
+
const out = {
|
|
31
|
+
body: frame.notification.body,
|
|
32
|
+
tag: frame.collapse_key ?? frame.message_id,
|
|
33
|
+
renotify: frame.collapse_key !== null,
|
|
34
|
+
timestamp: frame.timestamp,
|
|
35
|
+
data: { frame },
|
|
36
|
+
};
|
|
37
|
+
if (frame.notification.icon !== null)
|
|
38
|
+
out['icon'] = frame.notification.icon;
|
|
39
|
+
if (options.badge !== undefined)
|
|
40
|
+
out['badge'] = options.badge;
|
|
41
|
+
return { title: frame.notification.title, options: out };
|
|
42
|
+
}
|
|
43
|
+
/** Resolves a click_action into a safe same-origin or http(s) URL. */
|
|
44
|
+
export function resolveClickUrl(clickAction, origin) {
|
|
45
|
+
const fallback = new URL('/', origin).href;
|
|
46
|
+
if (!clickAction)
|
|
47
|
+
return fallback;
|
|
48
|
+
try {
|
|
49
|
+
const url = new URL(clickAction, origin);
|
|
50
|
+
return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : fallback;
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
return fallback;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
async function windows(scope) {
|
|
57
|
+
return scope.clients.matchAll({ type: 'window', includeUncontrolled: true });
|
|
58
|
+
}
|
|
59
|
+
/** Handles a `push` event. */
|
|
60
|
+
export async function handlePush(scope, text, options = {}) {
|
|
61
|
+
const frame = parsePushPayload(text);
|
|
62
|
+
if (frame === null)
|
|
63
|
+
return;
|
|
64
|
+
const clients = await windows(scope);
|
|
65
|
+
for (const client of clients)
|
|
66
|
+
client.postMessage({ type: SW_MESSAGE.PUSH, frame });
|
|
67
|
+
const visible = notificationOptions(frame, options);
|
|
68
|
+
if (visible !== null) {
|
|
69
|
+
await scope.registration.showNotification(visible.title, visible.options);
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
// Data-only push: open windows got it via postMessage. Browsers require a visible
|
|
73
|
+
// notification for every push, so show a quiet one when nothing is on screen.
|
|
74
|
+
const onScreen = clients.some((c) => c.focused === true || c.visibilityState === 'visible');
|
|
75
|
+
if (!onScreen) {
|
|
76
|
+
await scope.registration.showNotification(options.fallbackTitle ?? 'New update', {
|
|
77
|
+
tag: 'tingping-data',
|
|
78
|
+
silent: true,
|
|
79
|
+
data: { frame },
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
/** Handles a `notificationclick` event, given the notification's `data`. */
|
|
84
|
+
export async function handleNotificationClick(scope, data) {
|
|
85
|
+
const frame = data?.frame ?? null;
|
|
86
|
+
const target = resolveClickUrl(frame?.notification?.click_action, scope.location.origin);
|
|
87
|
+
const clients = await windows(scope);
|
|
88
|
+
const sameOrigin = clients.filter((c) => {
|
|
89
|
+
try {
|
|
90
|
+
return new URL(c.url).origin === scope.location.origin;
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
if (sameOrigin.length > 0) {
|
|
97
|
+
// An app window is open: focus it and let the app route (no full reload).
|
|
98
|
+
const client = sameOrigin.find((c) => c.focused === true) ?? sameOrigin[0];
|
|
99
|
+
client.postMessage({ type: SW_MESSAGE.CLICK, frame });
|
|
100
|
+
await client.focus?.();
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
await scope.clients.openWindow(target);
|
|
104
|
+
}
|
|
105
|
+
//# sourceMappingURL=sw-handlers.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sw-handlers.js","sourceRoot":"","sources":["../../src/sw-handlers.ts"],"names":[],"mappings":"AAEA;;;GAGG;AAEH,MAAM,CAAC,MAAM,UAAU,GAAG;IACxB,0DAA0D;IAC1D,IAAI,EAAE,eAAe;IACrB,gEAAgE;IAChE,KAAK,EAAE,6BAA6B;CAC5B,CAAC;AA0BX,qEAAqE;AACrE,MAAM,UAAU,gBAAgB,CAAC,IAA+B;IAC9D,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,IAAI,IAAI,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IACpE,IAAI,CAAC;QACH,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAsC,CAAC;QACpE,IAAI,KAAK,KAAK,IAAI,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,KAAK,cAAc,IAAI,OAAO,KAAK,CAAC,UAAU,KAAK,QAAQ,EAAE,CAAC;YACzH,OAAO,IAAI,CAAC;QACd,CAAC;QACD,OAAO,KAA0B,CAAC;IACpC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,mBAAmB,CAAC,KAAwB,EAAE,OAAO,GAAc,EAAE;IACnF,IAAI,KAAK,CAAC,YAAY,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC7C,MAAM,GAAG,GAA4B;QACnC,IAAI,EAAE,KAAK,CAAC,YAAY,CAAC,IAAI;QAC7B,GAAG,EAAE,KAAK,CAAC,YAAY,IAAI,KAAK,CAAC,UAAU;QAC3C,QAAQ,EAAE,KAAK,CAAC,YAAY,KAAK,IAAI;QACrC,SAAS,EAAE,K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AAC,CAAC;IACrC,MAAM,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE;QACtC,IAAI,CAAC;YACH,OAAO,IAAI,GAAG,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,MAAM,KAAK,KAAK,CAAC,QAAQ,CAAC,MAAM,CAAC;QACzD,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC,CAAC,CAAC;IACH,IAAI,UAAU,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;QAC1B,0EAA0E;QAC1E,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,OAAO,KAAK,IAAI,CAAC,IAAI,UAAU,CAAC,CAAC,CAAE,CAAC;QAC5E,MAAM,CAAC,WAAW,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC;QACtD,MAAM,MAAM,CAAC,KAAK,EAAE,EAAE,CAAC;QACvB,OAAO;IACT,CAAC;IACD,MAAM,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;AACzC,CAAC"}
|
package/dist/sw.js
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/* @tingping/web service worker - Apache-2.0, Copyright 2026 InnvoSols Technologies */
|
|
2
|
+
"use strict";
|
|
3
|
+
(() => {
|
|
4
|
+
// src/sw-handlers.ts
|
|
5
|
+
var SW_MESSAGE = {
|
|
6
|
+
/** Posted to open windows for every push that arrives. */
|
|
7
|
+
PUSH: "TINGPING_PUSH",
|
|
8
|
+
/** Posted to open windows when the user taps a notification. */
|
|
9
|
+
CLICK: "TINGPING_NOTIFICATION_CLICK"
|
|
10
|
+
};
|
|
11
|
+
function parsePushPayload(text) {
|
|
12
|
+
if (text === null || text === void 0 || text === "") return null;
|
|
13
|
+
try {
|
|
14
|
+
const value = JSON.parse(text);
|
|
15
|
+
if (value === null || typeof value !== "object" || value.type !== "NOTIFICATION" || typeof value.message_id !== "string") {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
return value;
|
|
19
|
+
} catch {
|
|
20
|
+
return null;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
function notificationOptions(frame, options = {}) {
|
|
24
|
+
if (frame.notification === null) return null;
|
|
25
|
+
const out = {
|
|
26
|
+
body: frame.notification.body,
|
|
27
|
+
tag: frame.collapse_key ?? frame.message_id,
|
|
28
|
+
renotify: frame.collapse_key !== null,
|
|
29
|
+
timestamp: frame.timestamp,
|
|
30
|
+
data: { frame }
|
|
31
|
+
};
|
|
32
|
+
if (frame.notification.icon !== null) out["icon"] = frame.notification.icon;
|
|
33
|
+
if (options.badge !== void 0) out["badge"] = options.badge;
|
|
34
|
+
return { title: frame.notification.title, options: out };
|
|
35
|
+
}
|
|
36
|
+
function resolveClickUrl(clickAction, origin) {
|
|
37
|
+
const fallback = new URL("/", origin).href;
|
|
38
|
+
if (!clickAction) return fallback;
|
|
39
|
+
try {
|
|
40
|
+
const url = new URL(clickAction, origin);
|
|
41
|
+
return url.protocol === "https:" || url.protocol === "http:" ? url.href : fallback;
|
|
42
|
+
} catch {
|
|
43
|
+
return fallback;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
async function windows(scope2) {
|
|
47
|
+
return scope2.clients.matchAll({ type: "window", includeUncontrolled: true });
|
|
48
|
+
}
|
|
49
|
+
async function handlePush(scope2, text, options = {}) {
|
|
50
|
+
const frame = parsePushPayload(text);
|
|
51
|
+
if (frame === null) return;
|
|
52
|
+
const clients = await windows(scope2);
|
|
53
|
+
for (const client of clients) client.postMessage({ type: SW_MESSAGE.PUSH, frame });
|
|
54
|
+
const visible = notificationOptions(frame, options);
|
|
55
|
+
if (visible !== null) {
|
|
56
|
+
await scope2.registration.showNotification(visible.title, visible.options);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
const onScreen = clients.some((c) => c.focused === true || c.visibilityState === "visible");
|
|
60
|
+
if (!onScreen) {
|
|
61
|
+
await scope2.registration.showNotification(options.fallbackTitle ?? "New update", {
|
|
62
|
+
tag: "tingping-data",
|
|
63
|
+
silent: true,
|
|
64
|
+
data: { frame }
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
async function handleNotificationClick(scope2, data) {
|
|
69
|
+
const frame = data?.frame ?? null;
|
|
70
|
+
const target = resolveClickUrl(frame?.notification?.click_action, scope2.location.origin);
|
|
71
|
+
const clients = await windows(scope2);
|
|
72
|
+
const sameOrigin = clients.filter((c) => {
|
|
73
|
+
try {
|
|
74
|
+
return new URL(c.url).origin === scope2.location.origin;
|
|
75
|
+
} catch {
|
|
76
|
+
return false;
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
if (sameOrigin.length > 0) {
|
|
80
|
+
const client = sameOrigin.find((c) => c.focused === true) ?? sameOrigin[0];
|
|
81
|
+
client.postMessage({ type: SW_MESSAGE.CLICK, frame });
|
|
82
|
+
await client.focus?.();
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
await scope2.clients.openWindow(target);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// src/sw.ts
|
|
89
|
+
var scope = self;
|
|
90
|
+
self.addEventListener("push", (event) => {
|
|
91
|
+
event.waitUntil(handlePush(scope, event.data ? event.data.text() : null, self.TINGPING_SW_OPTIONS));
|
|
92
|
+
});
|
|
93
|
+
self.addEventListener("notificationclick", (event) => {
|
|
94
|
+
event.notification.close();
|
|
95
|
+
event.waitUntil(handleNotificationClick(scope, event.notification.data));
|
|
96
|
+
});
|
|
97
|
+
})();
|