Skip to content

Commit

Permalink
Worker custom path support (#60)
Browse files Browse the repository at this point in the history
* Worker custom path support

* Bump version & re-dist

---------

Co-authored-by: Konstantin Antipochkin <konstantin_a@optimove.com>
Co-authored-by: Christopher Wyllie <chris_w@optimove.com>
  • Loading branch information
3 people authored Apr 28, 2023
1 parent cd26fb6 commit d3c1c9c
Show file tree
Hide file tree
Showing 10 changed files with 61 additions and 33 deletions.
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion dist/worker.js

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@kumulos/web",
"version": "1.11.1",
"version": "1.12.0",
"description": "Official SDK for integrating Kumulos services with your web projects",
"main": "dist/index.js",
"types": "types/src/index.d.ts",
Expand Down
2 changes: 1 addition & 1 deletion src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { del, get, set } from './storage';

import { Channel } from './channels';

const SDK_VERSION = '1.11.1';
const SDK_VERSION = '1.12.0';
const SDK_TYPE = 10;
const EVENTS_BASE_URL = 'https://events.kumulos.com';
export const PUSH_BASE_URL = 'https://push.kumulos.com';
Expand Down
24 changes: 17 additions & 7 deletions src/core/push/w3c.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Context, EventType, trackEvent } from '..';
import { PushOpsManager, PushSubscriptionState, TokenType } from '.';
import { base64UrlEncode, cyrb53, getBrowserName } from '../utils';
import { base64UrlEncode, cyrb53, getBrowserName, getFullUrl } from '../utils';
import { get, set } from '../storage';

const BLUR_EVENT_TIMEOUT_MILLIS = 1000;
Expand All @@ -17,14 +17,20 @@ function hasSameKey(vapidKey: string, subscription: PushSubscription): boolean {
return subKey === vapidKey;
}

async function getActiveServiceWorkerReg(): Promise<ServiceWorkerRegistration> {
const workerReg = await navigator.serviceWorker.getRegistration();
async function getActiveServiceWorkerReg(
workerPath: string
): Promise<ServiceWorkerRegistration> {
const fullWorkerUrl = getFullUrl(workerPath);

const workerReg = await navigator.serviceWorker.getRegistration(
fullWorkerUrl
);

if (!workerReg) {
return Promise.reject('No service worker registration');
}

return navigator.serviceWorker.ready;
return workerReg;
}

function hashSubscription(ctx: Context, sub: PushSubscription): number {
Expand Down Expand Up @@ -58,7 +64,9 @@ export default class W3cPushManager implements PushOpsManager {
);
}

const workerReg = await getActiveServiceWorkerReg();
const workerReg = await getActiveServiceWorkerReg(
ctx.serviceWorkerPath
);
const existingSub = await workerReg.pushManager.getSubscription();

if (existingSub && !hasSameKey(ctx.vapidPublicKey, existingSub)) {
Expand Down Expand Up @@ -123,7 +131,7 @@ export default class W3cPushManager implements PushOpsManager {
return 'blocked';
}

const reg = await getActiveServiceWorkerReg();
const reg = await getActiveServiceWorkerReg(ctx.serviceWorkerPath);
const sub = await reg?.pushManager.getSubscription();

if (sub && perm === 'granted' && hasSameKey(ctx.vapidPublicKey, sub)) {
Expand Down Expand Up @@ -153,7 +161,9 @@ export default class W3cPushManager implements PushOpsManager {
'pushExpiresAt'
);

const workerReg = await getActiveServiceWorkerReg();
const workerReg = await getActiveServiceWorkerReg(
ctx.serviceWorkerPath
);
const existingSub = await workerReg.pushManager.getSubscription();

let existingSubHash = undefined;
Expand Down
49 changes: 34 additions & 15 deletions src/core/utils.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,24 @@
import { Context, SDKFeature } from './index';

type FeatureDependency = string | object | IDBFactory | PromiseConstructor | Notification | PushManager | ServiceWorkerContainer | SafariRemoteNotification;

const CORE_FEATURE_DEPENDENCIES : FeatureDependency[] = [typeof Promise, typeof fetch, typeof indexedDB];

const FEATURE_DEPENDENCY_CHECK : {[key in SDKFeature]: () => boolean} = {
'push': isBrowserSupportedForPush,
'ddl': isBrowserSupportedForDdl
type FeatureDependency =
| string
| object
| IDBFactory
| PromiseConstructor
| Notification
| PushManager
| ServiceWorkerContainer
| SafariRemoteNotification;

const CORE_FEATURE_DEPENDENCIES: FeatureDependency[] = [
typeof Promise,
typeof fetch,
typeof indexedDB
];

const FEATURE_DEPENDENCY_CHECK: { [key in SDKFeature]: () => boolean } = {
push: isBrowserSupportedForPush,
ddl: isBrowserSupportedForDdl
};

// See: https://stackoverflow.com/a/2117523
Expand Down Expand Up @@ -79,7 +91,8 @@ function isBrowserSupportedForDdl() {

function checkRequired(coreDependencies: FeatureDependency[]) {
return coreDependencies.reduce(
(supported: boolean, dependency: FeatureDependency) => supported && dependency !== 'undefined',
(supported: boolean, dependency: FeatureDependency) =>
supported && dependency !== 'undefined',
true
);
}
Expand Down Expand Up @@ -173,18 +186,24 @@ export function base64UrlEncode(buffer: ArrayBuffer): string {
return urlVariant;
}

export function registerServiceWorker(
path: string
): Promise<ServiceWorkerRegistration> {
export async function registerServiceWorker(workerPath: string) {
if (!('serviceWorker' in navigator)) {
return Promise.reject(
console.error(
'ServiceWorker is not supported in this browser, aborting...'
);
return;
}

return navigator.serviceWorker.register(path).then(() => {
return navigator.serviceWorker.ready;
});
const fullWorkerUrl = getFullUrl(workerPath);
try {
await navigator.serviceWorker.register(fullWorkerUrl);
} catch (e) {
console.error(e);
}
}

export function getFullUrl(path: string) {
return new URL(path, location.origin).href;
}

export function defer<T>() {
Expand Down
5 changes: 2 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ interface KumulosConfig extends Configuration {
export default class Kumulos {
private readonly config: KumulosConfig;
private readonly context: Context;
private readonly serviceWorkerReg?: Promise<ServiceWorkerRegistration>;
private readonly promptManager?: PromptManager;
private readonly ddlManager?: DdlManager;
private channelSubscriptionManager?: ChannelSubscriptionManager;
Expand All @@ -58,7 +57,7 @@ export default class Kumulos {
if (this.context.hasFeature(SDKFeature.PUSH)) {
trackOpenFromQuery(this.context);

this.serviceWorkerReg = registerServiceWorker(
registerServiceWorker(
this.context.serviceWorkerPath
);

Expand Down Expand Up @@ -166,4 +165,4 @@ export default class Kumulos {

this.config.onPushOpened?.(push);
}
}
}
3 changes: 2 additions & 1 deletion types/src/core/utils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ export declare class AuthedFetchError extends Error {
}
export declare function authedFetchJson<T>(ctx: Context, url: RequestInfo, options?: RequestInit): Promise<T>;
export declare function base64UrlEncode(buffer: ArrayBuffer): string;
export declare function registerServiceWorker(path: string): Promise<ServiceWorkerRegistration>;
export declare function registerServiceWorker(workerPath: string): Promise<void>;
export declare function getFullUrl(path: string): string;
export declare function defer<T>(): {
resolve: (value?: T | PromiseLike<T> | undefined) => void;
reject: (reason?: any) => void;
Expand Down
1 change: 0 additions & 1 deletion types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ interface KumulosConfig extends Configuration {
export default class Kumulos {
private readonly config;
private readonly context;
private readonly serviceWorkerReg?;
private readonly promptManager?;
private readonly ddlManager?;
private channelSubscriptionManager?;
Expand Down

0 comments on commit d3c1c9c

Please sign in to comment.