Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Changelog

## Unreleased
## 19.9.1
Changed: when `Gleap.identify` or `Gleap.updateContact` fails, the promise it returns rejects with an `Error`, for example `Gleap updateContact failed: network error`, `Gleap identify failed: HTTP 500` or `Gleap identify failed: refused (token_invalid)`. Until this version it rejected with `undefined` or the string `'Session not ready yet.'`, which error trackers such as Bugsnag and Sentry report as a non-error unhandled rejection with no message. A logout while one of these requests was still on its way now resolves instead of rejecting. If your app does not want failed requests (for example a user who is offline) in its error tracker, catch them with `Promise.resolve(Gleap.identify(...)).catch(() => {})`. Wrap the call in `Promise.resolve`, because these calls return nothing when there is nothing to send. `Gleap.setLanguage` catches its own contact update.
Changed: a product tour that is not live on the current page no longer writes to `console.error`.
Fixed: `index.d.ts` declared `Gleap.setStyles` with one object, but the SDK takes positional arguments: `setStyles(primaryColor, headerColor, buttonColor, backgroundColor?, borderRadius?, buttonX?, buttonY?, buttonStyle?, headerColor2?, headerColor3?)`. A call in the declared object form threw an error on the page and injected no styles. TypeScript projects that call `setStyles` with an object now get a compile error pointing at that call, which never worked; pass the values as arguments instead. No runtime change.

## 19.9.0
Expand Down
2 changes: 1 addition & 1 deletion build/browser/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/browser/index.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/cjs/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/cjs/index.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/esm/index.mjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/esm/index.mjs.map

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,7 +1,7 @@
{
"description": "JavaScript and TypeScript SDK for Gleap, an Intercom alternative with AI customer support, live chat, in-app bug reporting and customer feedback.",
"name": "gleap",
"version": "19.9.0",
"version": "19.9.1",
"main": "build/cjs/index.js",
"module": "build/esm/index.mjs",
"exports": {
Expand Down
2 changes: 2 additions & 0 deletions published/19.9.1/index.js

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions published/19.9.1/index.js.map

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions published/19.9.1/survey-embed.js

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

2 changes: 1 addition & 1 deletion published/latest/index.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion published/latest/index.js.map

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion src/Gleap.js
Original file line number Diff line number Diff line change
Expand Up @@ -926,9 +926,10 @@ class Gleap {
Gleap.getInstance().softReInitialize();

// Update language for contact.
// The SDK makes this call, so the host app can't catch a failed request.
Gleap.updateContact({
lang: language,
});
})?.catch?.(() => {});
}, 1000);
}
}
Expand Down
7 changes: 4 additions & 3 deletions src/GleapProductTours.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,10 @@ export default class GleapProductTours {
}
})
.catch((error) => {
console.log('Product tour is not live. Cleaning up...');
console.error(error);

// A tour that is not live on this page (or a failed request) is a normal case, not an error.
if (!(error && error.gleapReason)) {
console.error(error);
}
self.onComplete(false);
});
}
Expand Down
52 changes: 32 additions & 20 deletions src/GleapSession.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import ChecklistNetworkManager from './ChecklistNetworkManager';

Check warning on line 1 in src/GleapSession.js

View workflow job for this annotation

GitHub Actions / quality

quality file-lines

[file-lines] src/GleapSession.js:1 file: 1501 -> 1507 code lines (limit 400) Fix: Move one responsibility into its own file next to this one. Never squeeze code onto fewer lines.
import AgentNetworkManager from './AgentNetworkManager';
import {
GleapBannerManager,
Expand Down Expand Up @@ -35,6 +35,18 @@
const GRANT_REFRESH_MIN_INTERVAL_MS = 60 * 1000;
// A refresh that failed or could not run yet is tried again after this pause.
const GRANT_REFRESH_RETRY_MS = 60 * 1000;

// identify and updateContact reject with an Error, so error trackers show a
// message and a stack trace instead of a non-error rejection. `gleapReason`
// marks it as a failed Gleap request (not a bug) and keeps the short reason.
const requestError = (action, reason) => {
const error = new Error(`Gleap ${action} failed: ${reason}`);
error.gleapReason = reason;
return error;
};
// Browsers end a failed request with status 0 before its error event fires.
const httpFailure = (status) => (status === 0 ? 'network error' : `HTTP ${status}`);

// A signed session whose grant runs out while the messenger is open ends
// once it closes, at the latest this long after the grant expired (Intercom's
// one-hour cookie for activity after expiry). Checked once a minute.
Expand Down Expand Up @@ -1403,7 +1415,7 @@
// Wait for gleap session to be ready.
this.setOnSessionReady(function () {
if (!self.session.gleapId || !self.session.gleapHash) {
return reject('Session not ready yet.');
return reject(requestError('updateContact', 'session not ready'));
}

const http = new XMLHttpRequest();
Expand All @@ -1418,13 +1430,13 @@

const generationAtSend = self.logoutGeneration;
http.onerror = () => {
reject();
reject(requestError('updateContact', 'network error'));
};
http.onreadystatechange = function (e) {
if (http.readyState === 4) {
// A logout meanwhile: this answer describes the previous contact.
// A logout meanwhile: this answer describes the previous contact. Not a failure.
if (self.logoutGeneration !== generationAtSend) {
return reject();
return resolve();
}
if (http.status === 200 || http.status === 201) {
try {
Expand All @@ -1436,7 +1448,7 @@
reject(exp);
}
} else {
reject();
reject(requestError('updateContact', httpFailure(http.status)));
}
}
};
Expand Down Expand Up @@ -1557,7 +1569,7 @@
// Wait for gleap session to be ready.
this.setOnSessionReady(function () {
if (!self.session.gleapId || !self.session.gleapHash) {
return reject('Session not ready yet.');
return reject(requestError('identify', 'session not ready'));
}

const http = new XMLHttpRequest();
Expand Down Expand Up @@ -1585,17 +1597,17 @@

http.onerror = () => {
if (loggedOutMeanwhile()) {
return reject();
return resolve();
}
self.identifyInFlight = false;
self.lastIdentifyFailure = 'network error';
self.identifyFailedTransiently = true;
reject();
reject(requestError('identify', 'network error'));
};
http.onreadystatechange = function (e) {
if (http.readyState === 4) {
if (loggedOutMeanwhile()) {
return reject();
return resolve();
}
self.identifyInFlight = false;
if (http.status === 200 || http.status === 201) {
Expand Down Expand Up @@ -1626,7 +1638,7 @@
console.warn('Gleap: the identity token has expired and the JWT provider returned no fresh one.');
}
self.lastIdentifyFailure = 'refused';
return Promise.reject();
return Promise.reject(requestError('identify', 'identity token expired'));
}
const renewedUserId = decodeUserJwt(token).userId;
self.lastIdentify = { userId: renewedUserId, userData, userHash: token };
Expand Down Expand Up @@ -1665,8 +1677,8 @@
if (!refusal && (http.status === 0 || http.status >= 500)) {
self.identifyFailedTransiently = true;
}
self.lastIdentifyFailure = refusal ? 'refused' : `HTTP ${http.status}`;
reject();
self.lastIdentifyFailure = refusal ? 'refused' : httpFailure(http.status);
reject(requestError('identify', refusal ? `refused (${refusal})` : self.lastIdentifyFailure));
}
}
};
Expand Down Expand Up @@ -1751,7 +1763,7 @@
if (this.lastIdentifyFailure === 'refused' || this.lastIdentifyFailure === 'superseded') {
return;
}
const reason = error ? (error.message || error) : this.lastIdentifyFailure || 'unknown error';
const reason = (error && (error.gleapReason || error.message || error)) || this.lastIdentifyFailure || 'unknown error';
console.warn(`Gleap: setUserJwt could not identify the user (${reason}). Nothing changed; call it again later.`);
}
);
Expand Down Expand Up @@ -1833,7 +1845,7 @@
return new Promise((resolve, reject) => {
this.setOnSessionReady(function () {
if (!self.session.gleapId || !self.session.gleapHash) {
return reject('Session not ready yet.');
return reject(requestError('product tour', 'session not ready'));
}

const http = new XMLHttpRequest();
Expand All @@ -1847,7 +1859,7 @@
} catch (exp) {}

http.onerror = () => {
reject();
reject(requestError('product tour', 'network error'));
};
http.onreadystatechange = function (e) {
if (http.readyState === 4) {
Expand All @@ -1861,7 +1873,7 @@
reject(exp);
}
} else {
reject();
reject(requestError('product tour', httpFailure(http.status)));
}
}
};
Expand All @@ -1879,7 +1891,7 @@
return new Promise((resolve, reject) => {
this.setOnSessionReady(function () {
if (!self.session.gleapId || !self.session.gleapHash) {
return reject('Session not ready yet.');
return reject(requestError('product tour', 'session not ready'));
}

const http = new XMLHttpRequest();
Expand All @@ -1893,7 +1905,7 @@
} catch (exp) {}

http.onerror = () => {
reject();
reject(requestError('product tour', 'network error'));
};
http.onreadystatechange = function (e) {
if (http.readyState === 4) {
Expand All @@ -1903,13 +1915,13 @@
if (tourData && tourData.status === 'live' && tourData.passedPageFilter) {
resolve(tourData.config);
} else {
reject();
reject(requestError('product tour', 'not live on this page'));
}
} catch (exp) {
reject(exp);
}
} else {
reject();
reject(requestError('product tour', httpFailure(http.status)));
}
}
};
Expand Down
64 changes: 64 additions & 0 deletions src/GleapSession.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ class MockXhr {
}
}

// Like a browser: the request ends with status 0, then the error event fires.
error() {
this.respond(0);
if (this.onerror) {
this.onerror();
}
Expand Down Expand Up @@ -1559,3 +1561,65 @@ describe('grant (signed session credential)', () => {
expect(JSON.parse(identifyRequests()[0].body).sessionDuration).toBe(3600000);
});
});

describe('failed requests reject with an Error', () => {
beforeEach(() => {
global.SDK_VERSION = '0.0.0-test';
});
afterEach(() => {
delete global.SDK_VERSION;
});

const readySession = () => {
seedCachedSession();
const session = buildSession();
session.startSession();
return session;
};
const partialUpdates = () => MockXhr.instances.filter((xhr) => xhr.url && xhr.url.endsWith('/sessions/partialupdate'));

it('updateContact rejects with an Error on a network error', async () => {
const session = readySession();
const done = session.updateSession({ name: 'Other' });
partialUpdates()[0].error();
await expect(done).rejects.toThrow('Gleap updateContact failed: network error');
await expect(done).rejects.toMatchObject({ gleapReason: 'network error' });
});

it('updateContact rejects with an Error on a server error', async () => {
const session = readySession();
const done = session.updateSession({ name: 'Other' });
partialUpdates()[0].respond(500);
await expect(done).rejects.toThrow('Gleap updateContact failed: HTTP 500');
});

it('identify names the refusal in its Error', async () => {
const session = readySession();
const done = session.identifySession('user-2', { email: 'other@example.com' });
identifyRequests()[0].respond(401, JSON.stringify({ detail: { value: 'token_invalid' } }));
await expect(done).rejects.toThrow('Gleap identify failed: refused (token_invalid)');
});

it('updateContact resolves when a logout happened meanwhile', async () => {
const session = readySession();
const done = session.updateSession({ name: 'Other' });
session.clearSession(0, false);
partialUpdates()[0].respond(200, JSON.stringify({ gleapId: 'gleap-id-1', gleapHash: 'gleap-hash-1' }));
await expect(done).resolves.toBeUndefined();
});

it('identify resolves when a logout happened meanwhile', async () => {
const session = readySession();
const done = session.identifySession('user-2', { email: 'other@example.com' });
session.clearSession(0, false);
identifyRequests()[0].error();
await expect(done).resolves.toBeUndefined();
});

it('identify rejects with an Error on a network error', async () => {
const session = readySession();
const done = session.identifySession('user-2', { email: 'other@example.com' });
identifyRequests()[0].error();
await expect(done).rejects.toThrow('Gleap identify failed: network error');
});
});
Loading