Skip to content

Commit

Permalink
release: SDK 4.1.2
Browse files Browse the repository at this point in the history
  • Loading branch information
arnaud-roland committed Nov 25, 2024
1 parent 8589f4b commit 4cada79
Show file tree
Hide file tree
Showing 34 changed files with 2,099 additions and 1,601 deletions.
1 change: 0 additions & 1 deletion Sources/__tests__/system-parameter-provider.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ test("resolves to a type date for da", () => {

test("throws when passing an unknown key", () => {
return provider.getParameterForKey("toto").then(
// eslint-disable-next-line @typescript-eslint/no-empty-function
() => {},
err => {
expect(err.message).toBe("toto is not a managed system key");
Expand Down
10 changes: 10 additions & 0 deletions Sources/lib/dom/sdk-impl/__tests__/sdk-base.subscription.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,13 @@ it("sanitizes the last subscription on start", async () => {

expect(safariSDK["sanitizeSubscription"]).toHaveBeenCalled();
});

it("test hasSubscriptionChanged", async () => {
const standardSDK = new StandardSDK();
const last = {"endpoint":"testlast","expirationTime":null,"keys":{"p256dh":"osef","auth":"osef2"}}
const current = {"endpoint":"testcurrent","expirationTime":null,"keys":{"p256dh":"osef","auth":"osef2"}}
expect(standardSDK["hasSubscriptionChanged"](last, last)).toBeFalsy()
expect(standardSDK["hasSubscriptionChanged"](last, current)).toBeTruthy()
expect(standardSDK["hasSubscriptionChanged"](null, current)).toBeTruthy()
expect(standardSDK["hasSubscriptionChanged"](last, null)).toBeTruthy()
});
80 changes: 41 additions & 39 deletions Sources/lib/dom/sdk-impl/sdk-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export default abstract class BaseSDK implements ISDK {
}
private onProbationChanged(param: { type: ProbationType }): void {
if (param.type === ProbationType.Push) {
Log.info(logModuleName, InternalSDKEvent.FirstSubscription + "event sent");
Log.info(logModuleName, InternalSDKEvent.FirstSubscription + " event sent");
this.eventTracker?.track(new Event(InternalSDKEvent.FirstSubscription));
}
}
Expand Down Expand Up @@ -91,18 +91,18 @@ export default abstract class BaseSDK implements ISDK {
const lastConfig = await parameterStore.getParameterValue<IPrivateBatchSDKConfiguration>(keysByProvider.profile.LastConfiguration);
// Remove un-persistable config objects
delete configClone.internalTransient;
parameterStore.setParameterValue(keysByProvider.profile.LastConfiguration, configClone);
await parameterStore.setParameterValue(keysByProvider.profile.LastConfiguration, configClone);

/**
* Init installation id
*/
try {
const installationID = await parameterStore.getParameterValue(keysByProvider.profile.InstallationID);
if (installationID == null) {
this.createInstallationID();
await this.createInstallationID();
}
} catch (e) {
this.createInstallationID();
await this.createInstallationID();
}

/**
Expand Down Expand Up @@ -275,7 +275,8 @@ export default abstract class BaseSDK implements ISDK {
return Promise.reject("Push messaging isn't supported.");
}
const permission = await this.getPermission();
if (permission !== "granted" || !(await this.readAndCheckSubscribed())) {
const { subscribed } = await this.readAndCheckSubscription();
if (permission !== "granted" || !subscribed) {
return false;
}
return this.getSubscription().then(sub => sub != null);
Expand Down Expand Up @@ -312,7 +313,7 @@ export default abstract class BaseSDK implements ISDK {
}
const perm = await this.getPermission();
if (perm === "granted") {
this.updateSubscribed(true);
await this.updateSubscribed(true);
return this.isSubscribed();
}
throw new Error("Permission denied");
Expand All @@ -333,8 +334,9 @@ export default abstract class BaseSDK implements ISDK {
*
* @return Promise<any>
*/
public getSubscription(): Promise<unknown | null | undefined> {
return this.readAndCheckSubscription();
public async getSubscription(): Promise<unknown | null | undefined> {
const { subscription } = await this.readAndCheckSubscription();
return subscription;
}

/**
Expand Down Expand Up @@ -406,43 +408,43 @@ export default abstract class BaseSDK implements ISDK {
}

/**
* Read the subscribed flag and check if something changed
* Read the subscription and the state in database and check if something changed
*/
public async readAndCheckSubscribed(): Promise<boolean> {
let sub = await (await this.getParameterStore()).getParameterValue<boolean>(keysByProvider.profile.Subscribed);
sub = sub === true; // Sanitize
const last = this.lastSubscribed;
// check if the subscription changed
if (last !== sub) {
Log.info(logModuleName, "Subscribed updated from " + last + " to " + sub);
this.lastSubscribed = sub;
this.subscriptionChanged(true);
}
return sub;
}
public async readAndCheckSubscription(): Promise<{ subscribed: boolean; subscription: unknown }> {
let subscriptionHasChanged = false;

/**
* Read the subscription in database and check if something changed
*/
public async readAndCheckSubscription(): Promise<unknown> {
let currentSubscription = await (await this.getParameterStore()).getParameterValue<unknown>(keysByProvider.profile.Subscription);
currentSubscription = this.sanitizeSubscription(currentSubscription);
// Check whether the subscription has changed
const parameterStore = await this.getParameterStore();
let subscription = await parameterStore.getParameterValue<unknown>(keysByProvider.profile.Subscription);
subscription = this.sanitizeSubscription(subscription);
const lastSubscription = this.lastSubscription;

if (this.hasSubscriptionChanged(currentSubscription, lastSubscription)) {
Log.info(logModuleName, "Subscription updated", currentSubscription);
this.lastSubscription = currentSubscription;
this.subscriptionChanged(true);
if (this.hasSubscriptionChanged(subscription, lastSubscription)) {
Log.info(logModuleName, "Subscription updated", subscription);
this.lastSubscription = subscription;
subscriptionHasChanged = true;
}

return currentSubscription;
// Check whether the subscription state has changed
let subscribed = await parameterStore.getParameterValue<boolean>(keysByProvider.profile.Subscribed);
subscribed = subscribed === true; // Sanitize
const lastSubscribed = this.lastSubscribed;
if (lastSubscribed !== subscribed) {
Log.info(logModuleName, "Subscribed updated from " + lastSubscribed + " to " + subscribed);
this.lastSubscribed = subscribed;
subscriptionHasChanged = true;
}
// Trigger sub/unsub event if subscription has changed
if (subscriptionHasChanged) {
await this.subscriptionChanged(true);
}
return { subscription, subscribed };
}

// check if the subscription changed
protected hasSubscriptionChanged = (current: unknown, last: unknown): boolean => {
if (current === last) return false;
if (current == null || last == null) return true;
if (current === typeof Object && last === typeof Object) {
if (typeof current === "object" && typeof last === "object") {
if ((current as PushSubscriptionJSON)?.endpoint != (last as PushSubscriptionJSON)?.endpoint) return true;
}
return false;
Expand All @@ -454,9 +456,9 @@ export default abstract class BaseSDK implements ISDK {
*/
public async updateSubscribed(subscribed: boolean): Promise<boolean> {
const parameterStore = await this.getParameterStore();
parameterStore.setParameterValue(keysByProvider.profile.Subscribed, subscribed);
Log.debug(logModuleName, "Writing subscribed:", subscribed);
return this.readAndCheckSubscribed();
await parameterStore.setParameterValue(keysByProvider.profile.Subscribed, subscribed);
return (await this.readAndCheckSubscription()).subscribed;
}

/**
Expand All @@ -473,11 +475,11 @@ export default abstract class BaseSDK implements ISDK {
}

if (typeof subscribed === "boolean") {
parameterStore.setParameterValue(keysByProvider.profile.Subscribed, subscribed);
Log.debug(logModuleName, "Writing subscribed:", subscribed);
await parameterStore.setParameterValue(keysByProvider.profile.Subscribed, subscribed);
}

return this.readAndCheckSubscription();
return (await this.readAndCheckSubscription()).subscription;
}

/**
Expand All @@ -488,7 +490,7 @@ export default abstract class BaseSDK implements ISDK {
const last = this.lastPermission;
if (last !== perm) {
this.lastPermission = perm;
this.subscriptionChanged(false);
await this.subscriptionChanged(false);
}
return perm;
}
Expand Down
6 changes: 3 additions & 3 deletions Sources/lib/dom/sdk-impl/sdk-safari.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export class SafariSDK extends BaseSDK implements ISDK {
if (!subscription || subscription !== remotePermission.deviceToken) {
const newSubscription = remotePermission.deviceToken;
if (newSubscription) {
this.updateSubscription(newSubscription, true);
await this.updateSubscription(newSubscription, true);
}
return this.isSubscribed();
}
Expand Down Expand Up @@ -157,7 +157,7 @@ export class SafariSDK extends BaseSDK implements ISDK {
try {
const response: void | ResponseDiagnostic = await Promise.race([this.fetchDiagnostics(), Timeout(10000)]);
if (!response) throw new Error("Invalid diagnostics server response");
if (response.status === "FAIL") return Log.publicError("[Diagnostics] " + response?.error ?? "Unknown server error");
if (response.status === "FAIL") return Log.publicError("[Diagnostics] " + (response?.error ?? "Unknown server error"));
if (response.status === "OK") return Log.info(logModuleName, "User has denied permission");
} catch (err) {
Log.publicError("[Diagnostics] Cannot diagnose registration issue: Internal server error");
Expand Down Expand Up @@ -252,7 +252,7 @@ export class SafariSDK extends BaseSDK implements ISDK {
return null;
} else if (permission == Permission.Denied && window.Notification.permission !== Permission.Denied) {
Log.info(logModuleName, "Unknown state: requesting diagnostics");
this.printDiagnostics();
void this.printDiagnostics();
return null;
} else if (permission === Permission.Granted) {
Log.info(logModuleName, "User granted permission");
Expand Down
4 changes: 2 additions & 2 deletions Sources/lib/dom/sdk-impl/sdk-standard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ export class StandardSDK extends BaseSDK implements ISDK {
sub = null;
}

this.updateSubscription(sub ? sub.toJSON() : null);
await this.updateSubscription(sub ? sub.toJSON() : null);
return super.unsubscribe();
}

Expand All @@ -250,7 +250,7 @@ export class StandardSDK extends BaseSDK implements ISDK {
try {
const pushManager = await this.getPushManager();
const sub = await pushManager.getSubscription();
return this.updateSubscription(sub ? sub.toJSON() : null);
return await this.updateSubscription(sub ? sub.toJSON() : null);
} catch (e) {
Log.warn(logModuleName, "get subscription failed, reading it from the database. error:", e);
return super.getSubscription();
Expand Down
1 change: 0 additions & 1 deletion Sources/lib/dom/sdk-impl/types/window-safari.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ export interface ISafari {
}

declare global {
// eslint-disable-next-line @typescript-eslint/interface-name-prefix
interface Window {
safari: ISafari;
}
Expand Down
2 changes: 0 additions & 2 deletions Sources/lib/dom/ui/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,7 +256,6 @@ export class DOMElement {
return this;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
public listenTo(evt: AnyEvent, callback: EventListenerOrEventListenerObject): DOMElement {
if (evt != null && callback != null) {
this.wrapped.forEach(e => e.addEventListener(evt as string, callback));
Expand Down Expand Up @@ -455,7 +454,6 @@ export class DOMElement {
}
}

// eslint-disable-next-line no-use-before-define
return DOMElement.EMPTY;
}
}
Expand Down
22 changes: 12 additions & 10 deletions Sources/lib/dom/ui/uicomponent-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,21 +73,21 @@ export class UIComponent {
// ----------------------------------->

/**
* Detemrines whether the component is ready
* Determines whether the component is ready
*/
public ready(): boolean {
return this.component != null;
}

/**
* Determines whether the component is intialized
* Determines whether the component is initialized
*/
public initialized(): boolean {
return this.promise != null;
}

/**
* Determines whether we're currently intializing the component
* Determines whether we're currently initializing the component
*/
public intializing(): boolean {
return this.initialized() && !this.ready();
Expand Down Expand Up @@ -123,11 +123,13 @@ export class UIComponent {
});

// emit events
this.promise.then(() => {
if (this.success) {
LocalEventBus.emit(LocalSDKEvent.UiComponentReady, { code: this.code, component: this.component }, false);
}
});
this.promise
.then(() => {
if (this.success) {
LocalEventBus.emit(LocalSDKEvent.UiComponentReady, { code: this.code, component: this.component }, false);
}
})
.catch(e => Log.warn(logModuleName, "Error while initializing the component", this.code, e));

return this.promise;
}
Expand Down Expand Up @@ -165,7 +167,7 @@ export class UIComponentHandler {

private onHashChanged(args: IHashChangedEventArgs): void {
if (args.hash === "#_batchsdk_show_identifiers") {
this.showPublicIdentifiers();
void this.showPublicIdentifiers();
}
}

Expand All @@ -187,7 +189,7 @@ export class UIComponentHandler {
this.components.set(code, component);

if (this.config != null) {
component.init(this.config[code] || {});
void component.init(this.config[code] || {});
}

return component;
Expand Down
3 changes: 2 additions & 1 deletion Sources/lib/shared/event/event-data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,8 @@ export class EventData {
}

private parseTypedEventAttribute(key: string, v: BatchSDK.EventAttributeValue): EventAttributeType | undefined {
const { value, type } = v;
const type = v.type;
const value: unknown = v.value;
switch (type) {
case TypedEventAttributeType.URL: {
if (isURL(value)) {
Expand Down
4 changes: 2 additions & 2 deletions Sources/lib/shared/event/event-tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ export default class EventTracker {
// TODO: Log this, as this eats the WS error
// TODO: Check the statuscode before retrying? Or should the executor tell more
// Retry up to X times, and add a minimal delay between attempts
// eslint-disable-next-line no-param-reassign

retryCount += 1;
if (retryCount < RETRY_MAX_ATTEMPTS) {
Delay(RETRY_MIN_INTERVAL_MS).then(() => {
void Delay(RETRY_MIN_INTERVAL_MS).then(() => {
this.send(retryCount);
});
} else {
Expand Down
10 changes: 6 additions & 4 deletions Sources/lib/shared/helpers/__tests__/task-queue.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,12 @@ describe("Task Queue", () => {
lastTask = taskQueue.postAsync(() => {
actual.push(i);
return new Promise(resolve => {
setTimeout(() => {
resolve(undefined);
}, Math.ceil(Math.random() * 45));
setTimeout(
() => {
resolve(undefined);
},
Math.ceil(Math.random() * 45)
);
});
});
}
Expand All @@ -107,7 +110,6 @@ describe("Task Queue", () => {
it("should chain tasks even if they're erroring", async () => {
// We need to stop errored promises from bubbling as this will make the test fail
const postCaughtPromise = (promise: any): any => {
// eslint-disable-next-line @typescript-eslint/no-empty-function
taskQueue.postAsync(promise).catch(() => {});
};

Expand Down
4 changes: 1 addition & 3 deletions Sources/lib/shared/helpers/uuid.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,16 @@ export default function uuid(): string {
const prngRandomBytes = new Uint8Array(randomNumbers.length);
self.crypto.getRandomValues(prngRandomBytes);
for (let i = 0; i < randomNumbers.length; i += 1) {
// eslint-disable-next-line no-bitwise
randomNumbers[i] = prngRandomBytes[i] % 16 | 0;
}
} else {
for (let i = 0; i < randomNumbers.length; i += 1) {
// eslint-disable-next-line no-bitwise
randomNumbers[i] = (Math.random() * 16) | 0;
}
}

// The 16th number needs to be ‘8’, ‘9’, ‘A’, or ‘B’. We can bitmask that.
// eslint-disable-next-line no-bitwise, no-mixed-operators

randomNumbers[15] = (randomNumbers[15] & 0x3) | 0x8;

let uuidString = "";
Expand Down
Loading

0 comments on commit 4cada79

Please sign in to comment.