Skip to content

Commit 1e73757

Browse files
authored
fix: segment plugin abstract nested instance (#158)
1 parent b03996f commit 1e73757

File tree

2 files changed

+10
-6
lines changed

2 files changed

+10
-6
lines changed

packages/plugin-segment/src/plugin.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,24 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
1515
return options.instance || snippetInstance(options.instanceKey);
1616
};
1717
getInstance();
18-
let initialized = false;
18+
let ready = false;
1919
const plugin: IntegrationPlugin = {
2020
name: '@amplitude/experiment-plugin-segment',
2121
type: 'integration',
2222
setup(): Promise<void> {
2323
const instance = getInstance();
2424
return new Promise<void>((resolve) => {
2525
instance.ready(() => {
26-
initialized = true;
26+
ready = true;
2727
resolve();
2828
});
2929
// If the segment SDK is installed via the @segment/analytics-next npm
3030
// package then function calls to the snippet are not respected.
3131
if (!options.instance) {
3232
const interval = safeGlobal.setInterval(() => {
3333
const instance = getInstance();
34-
if (instance.initialized || instance.instance?.initialized) {
35-
initialized = true;
34+
if (instance.initialized) {
35+
ready = true;
3636
safeGlobal.clearInterval(interval);
3737
resolve();
3838
}
@@ -42,7 +42,7 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
4242
},
4343
getUser(): ExperimentUser {
4444
const instance = getInstance();
45-
if (initialized) {
45+
if (ready) {
4646
return {
4747
user_id: instance.user().id(),
4848
device_id: instance.user().anonymousId(),
@@ -60,7 +60,7 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
6060
},
6161
track(event: ExperimentEvent): boolean {
6262
const instance = getInstance();
63-
if (!initialized) return false;
63+
if (!ready) return false;
6464
instance.track(event.eventType, event.eventProperties);
6565
return true;
6666
},

packages/plugin-segment/src/snippet.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@ export const snippetInstance = (
1717
// Create a queue, but don't obliterate an existing one!
1818
const analytics = (safeGlobal[key] = safeGlobal[key] || []);
1919

20+
// Return the actual instance if the global analytics is nested in an instance.
21+
if (analytics.instance && analytics.instance.initialize) {
22+
return analytics.instance;
23+
}
2024
// If the real analytics.js is already on the page return.
2125
if (analytics.initialize) {
2226
return analytics;

0 commit comments

Comments
 (0)