mirror of
https://github.com/cinnyapp/cinny.git
synced 2025-11-10 01:00:28 +03:00
Convert to a more generic implementation for communicating with the client
This commit is contained in:
parent
4cc1179a4f
commit
14085c7ccf
1 changed files with 24 additions and 10 deletions
34
src/sw.ts
34
src/sw.ts
|
|
@ -3,19 +3,33 @@
|
||||||
export type {};
|
export type {};
|
||||||
declare const self: ServiceWorkerGlobalScope;
|
declare const self: ServiceWorkerGlobalScope;
|
||||||
|
|
||||||
async function askForAccessToken(client: Client): Promise<string | undefined> {
|
const DEFAULT_NOTIFICATION_ICON = '/icons/icon-192x192.png'; // Replace with your actual default icon path
|
||||||
return new Promise((resolve) => {
|
const DEFAULT_NOTIFICATION_BADGE = '/icons/badge-72x72.png'; // Replace with your actual default badge icon path (for notification UI)
|
||||||
const responseKey = Math.random().toString(36);
|
|
||||||
const listener = (event: ExtendableMessageEvent) => {
|
const pendingReplies = new Map();
|
||||||
if (event.data.responseKey !== responseKey) return;
|
let messageIdCounter = 0;
|
||||||
resolve(event.data.token);
|
function sendAndWaitForReply(client: WindowClient, type: string, payload: object) {
|
||||||
self.removeEventListener('message', listener);
|
messageIdCounter += 1;
|
||||||
};
|
const id = messageIdCounter;
|
||||||
self.addEventListener('message', listener);
|
const promise = new Promise((resolve) => {
|
||||||
client.postMessage({ responseKey, type: 'token' });
|
pendingReplies.set(id, resolve);
|
||||||
});
|
});
|
||||||
|
client.postMessage({ type, id, payload });
|
||||||
|
return promise;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
self.addEventListener('message', (event) => {
|
||||||
|
const { replyTo } = event.data;
|
||||||
|
if (replyTo) {
|
||||||
|
const resolve = pendingReplies.get(replyTo);
|
||||||
|
if (resolve) {
|
||||||
|
pendingReplies.delete(replyTo);
|
||||||
|
resolve(event.data.payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
|
||||||
function fetchConfig(token?: string): RequestInit | undefined {
|
function fetchConfig(token?: string): RequestInit | undefined {
|
||||||
if (!token) return undefined;
|
if (!token) return undefined;
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue