ably / ably-js

Javascript, Node, Typescript, React, React Native client library SDK for Ably realtime messaging service
https://ably.com/download
Apache License 2.0
309 stars 55 forks source link

Library is currently incompatible with Salesforce Lightning Locker #994

Open owenpearson opened 2 years ago

owenpearson commented 2 years ago

Currently when using ably-js with Salesforce Lightning Locker the library throws the following error on import: Error: Cannot read properties of undefined (reading 'navigator')

The root cause is that the global object comes out undefined which is caused by the following logic automatically added by webpack:

var g;

// This works in non-strict mode
g = (function() {
    return this;
})();

try {
    // This works if eval is allowed (see CSP)
    g = g || new Function("return this")();
} catch (e) {
    // This works if the window reference is available
    if (typeof window === "object") g = window;
}

In lightning locker the function constructor invocation doesn't error here and just returns undefined, so the catch statement is never executed.

It looks like this logic no longer exists in webpack v5 so it is possible that upgrading webpack will resolve this. I've also created https://github.com/ably/ably-js/pull/993 which fixes compatibility with lightning locker without upgrading webpack, although it's an inelegant solution and I still need to test how this affects support for other platforms.

The simplest workaround currently is to just open the ably.js bundle and replace

g = (function() {
    return this;
})();

with

g = window;

Although bear in mind that this will only work for the unminified distribution of ably-js.

┆Issue is synchronized with this Jira Task by Unito

VeskeR commented 3 months ago

It looks like this logic no longer exists in webpack v5 so it is possible that upgrading webpack will resolve this.

We upgraded to webpack v5 in ably-js v2 in https://github.com/ably/ably-js/pull/1201, so should investigate if that fixed the issue and if we no longer need the workaround from https://github.com/ably/ably-js/pull/993