Skip to content

Commit

Permalink
Merge pull request #1031 from OneSignal/user-model/rename-sw-file
Browse files Browse the repository at this point in the history
User model/rename sw file
  • Loading branch information
rgomezp authored May 8, 2023
2 parents 500d8cd + e97a5aa commit 008f636
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 23 deletions.
2 changes: 0 additions & 2 deletions express_webpack/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@
OneSignalDeferred.push(async function(onesignal) {
await onesignal.init({
appId,
serviceWorkerParam: { scope: "/" + SERVICE_WORKER_PATH },
serviceWorkerPath: SERVICE_WORKER_PATH + "OneSignalSDK.sw.js",
notifyButton: {
enable: true
},
Expand Down
2 changes: 1 addition & 1 deletion src/shared/helpers/ConfigHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ export class ConfigHelper {
Except injecting some default values for prompts.
*/
const defaultServiceWorkerParam = { scope: '/' };
const defaultServiceWorkerPath = 'OneSignalSDK.sw.js';
const defaultServiceWorkerPath = 'OneSignalSDKWorker.js';

const config = {
...userConfig,
Expand Down
4 changes: 1 addition & 3 deletions src/shared/helpers/ContextHelper.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { ServiceWorkerManager } from '../managers/ServiceWorkerManager';
import { SubscriptionManager, SubscriptionManagerConfig } from '../managers/SubscriptionManager';
import SdkEnvironment from '../managers/SdkEnvironment';
import { ContextSWInterface } from "../models/ContextSW";
import { AppConfig } from '../models/AppConfig';
import Path from '../models/Path';
Expand All @@ -9,9 +8,8 @@ export class ContextHelper {
public static getServiceWorkerManager(context: ContextSWInterface): ServiceWorkerManager {
const config: AppConfig = context.appConfig;

const envPrefix = SdkEnvironment.getBuildEnvPrefix();
const serviceWorkerManagerConfig = {
workerPath: new Path(`/${envPrefix}OneSignalSDK.sw.js`),
workerPath: new Path(`OneSignalSDKWorker.js`),
registrationOptions: { scope: '/' }
};

Expand Down
6 changes: 3 additions & 3 deletions src/shared/helpers/ServiceWorkerHelper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,11 @@ export default class ServiceWorkerHelper {

export enum ServiceWorkerActiveState {
/**
* OneSignalSDK.sw.js, or the equivalent custom file name, is active.
* OneSignalSDKWorker.js, or the equivalent custom file name, is active.
*/
OneSignalWorker = 'OneSignal Worker',
/**
* A service worker is active, but it is not OneSignalSDK.sw.js
* A service worker is active, but it is not OneSignalSDKWorker.js
* (or the equivalent custom file names as provided by user config).
*/
ThirdParty = '3rd Party',
Expand All @@ -270,7 +270,7 @@ export enum ServiceWorkerActiveState {

export interface ServiceWorkerManagerConfig {
/**
* The path and filename of the "main" worker (e.g. '/OneSignalSDK.sw.js');
* The path and filename of the "main" worker (e.g. '/OneSignalSDKWorker.js');
*/
workerPath: Path;
/**
Expand Down
2 changes: 1 addition & 1 deletion src/shared/libraries/WorkerMessenger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export class WorkerMessenger {
public async directPostMessageToSW(command: WorkerMessengerCommand, payload?: WorkerMessengerPayload): Promise<void> {
Log.debug(`[Worker Messenger] [Page -> SW] Direct command '${command.toString()}' to service worker.`);

const workerRegistration = await this.context.serviceWorkerManager.getRegistration();
const workerRegistration = await this.context?.serviceWorkerManager.getRegistration();
if (!workerRegistration) {
Log.error("`[Worker Messenger] [Page -> SW] Could not get ServiceWorkerRegistration to postMessage!");
return;
Expand Down
2 changes: 1 addition & 1 deletion src/shared/managers/SdkEnvironment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ export default class SdkEnvironment {
* service worker.
*
* For example, in staging the registered service worker filename is
* Staging-OneSignalSDK.sw.js.
* Staging-OneSignalSDKWorker.js.
*/
public static getBuildEnvPrefix(buildEnv: EnvironmentKind = SdkEnvironment.getBuildEnv()) : string {
switch (buildEnv) {
Expand Down
67 changes: 55 additions & 12 deletions src/shared/managers/ServiceWorkerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,10 +105,16 @@ export class ServiceWorkerManager {

// Check if the ServiceWorker file name is ours or a third party's
private swActiveStateByFileName(fileName?: string | null): ServiceWorkerActiveState {
if (!fileName)
if (!fileName) {
return ServiceWorkerActiveState.None;
if (fileName == this.config.workerPath.getFileName())
}
const isValidOSWorker =
fileName == this.config.workerPath.getFileName() ||
fileName == 'OneSignalSDK.sw.js'; // For backwards compatibility with temporary v16 user model beta filename (remove after 5/5/24 deprecation)

if (isValidOSWorker) {
return ServiceWorkerActiveState.OneSignalWorker;
}
return ServiceWorkerActiveState.ThirdParty;
}

Expand Down Expand Up @@ -353,7 +359,7 @@ export class ServiceWorkerManager {
* We have a couple different models of installing service workers:
*
* a) Originally, we provided users with two worker files:
* OneSignalSDK.sw.js and OneSignalSDKUpdaterWorker.js. Two workers were
* OneSignalSDKWorker.js and OneSignalSDKUpdaterWorker.js. Two workers were
* provided so each could be swapped with the other when the worker needed to
* update. The contents of both workers were identical; only the filenames
* were different, which is enough to update the worker.
Expand All @@ -363,22 +369,22 @@ export class ServiceWorkerManager {
* version as a query parameter. This is enough for the browser to detect a
* change and re-install the worker.
*
* b) With AMP web push, users specify the worker file OneSignalSDK.sw.js
* b) With AMP web push, users specify the worker file OneSignalSDKWorker.js
* with an app ID parameter ?appId=12345. AMP web push
* is vendor agnostic and doesn't know about OneSignal, so all relevant
* information has to be passed to the service worker, which is the only
* vendor-specific file.
*
* If AMP web push sees another worker like OneSignalSDKUpdaterWorker.js (deprecated), or
* even the same OneSignalSDK.sw.js without the app ID query parameter, the
* even the same OneSignalSDKWorker.js without the app ID query parameter, the
* user is considered unsubscribed.
*
* c) Due to b's restriction, we must always install
* OneSignalSDK.sw.js?appId=xxx. We also have to appropriately handle the
* OneSignalSDKWorker.js?appId=xxx. We also have to appropriately handle the
* legacy case:
*
* c-1) Where developers running progressive web apps force-register
* OneSignalSDK.sw.js
* OneSignalSDKWorker.js
*
* Actually, users can customize the file names of the Service Worker but
* it's up to them to be consistent with their naming. For AMP web push, users
Expand Down Expand Up @@ -415,17 +421,54 @@ export class ServiceWorkerManager {
// If we are inside the popup and service worker fails to register, it's not developer's fault.
// No need to report it to the api then.
const env = SdkEnvironment.getWindowEnv();
if (env === WindowEnvironmentKind.OneSignalSubscriptionPopup)
if (env === WindowEnvironmentKind.OneSignalSubscriptionPopup) {
throw error;
}

await this.fallbackToUserModelBetaWorker();
}
Log.debug(`[Service Worker Installation] Service worker installed.`);

await this.establishServiceWorkerChannel();
}

async fallbackToUserModelBetaWorker() {
const BETA_WORKER_NAME = 'OneSignalSDK.sw.js';

const configWithBetaWorkerName: ServiceWorkerManagerConfig = {
workerPath: new Path(`/${BETA_WORKER_NAME}`),
registrationOptions: this.config.registrationOptions,
};

const workerHref = ServiceWorkerHelper.getServiceWorkerHref(
configWithBetaWorkerName,
this.context.appConfig.appId,
Environment.version()
);

const scope = `${OneSignalUtils.getBaseUrl()}${this.config.registrationOptions.scope}`;

Log.info(`[Service Worker Installation] Attempting to install v16 Beta Worker ${workerHref} ${scope}.`);

try {
await navigator.serviceWorker.register(workerHref, { scope });

const DEPRECATION_ERROR = `
[Service Worker Installation] Successfully installed v16 Beta Worker.
Deprecation warning: support for the v16 beta worker name of ${BETA_WORKER_NAME}
will be removed May 5 2024. We have decided to keep the v15 name.
To avoid breaking changes for your users, please host both worker files:
OneSignalSDK.sw.js & OneSignalSDKWorker.js.
`;

Log.error(DEPRECATION_ERROR);
} catch (error) {
const response = await fetch(workerHref);
if (response.status === 403 || response.status === 404)
if (response.status === 403 || response.status === 404) {
throw new ServiceWorkerRegistrationError(response.status, response.statusText);
}

throw error;
}
Log.debug(`[Service Worker Installation] Service worker installed.`);

await this.establishServiceWorkerChannel();
}
}

0 comments on commit 008f636

Please sign in to comment.