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
12 changes: 6 additions & 6 deletions packages/plugin-segment/src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,24 +15,24 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
return options.instance || snippetInstance(options.instanceKey);
};
getInstance();
let initialized = false;
let ready = false;
const plugin: IntegrationPlugin = {
name: '@amplitude/experiment-plugin-segment',
type: 'integration',
setup(): Promise<void> {
const instance = getInstance();
return new Promise<void>((resolve) => {
instance.ready(() => {
initialized = true;
ready = true;
resolve();
});
// If the segment SDK is installed via the @segment/analytics-next npm
// package then function calls to the snippet are not respected.
if (!options.instance) {
const interval = safeGlobal.setInterval(() => {
const instance = getInstance();
if (instance.initialized || instance.instance?.initialized) {
initialized = true;
if (instance.initialized) {
ready = true;
safeGlobal.clearInterval(interval);
resolve();
}
Expand All @@ -42,7 +42,7 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
},
getUser(): ExperimentUser {
const instance = getInstance();
if (initialized) {
if (ready) {
return {
user_id: instance.user().id(),
device_id: instance.user().anonymousId(),
Expand All @@ -60,7 +60,7 @@ export const segmentIntegrationPlugin: SegmentIntegrationPlugin = (
},
track(event: ExperimentEvent): boolean {
const instance = getInstance();
if (!initialized) return false;
if (!ready) return false;
instance.track(event.eventType, event.eventProperties);
return true;
},
Expand Down
4 changes: 4 additions & 0 deletions packages/plugin-segment/src/snippet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ export const snippetInstance = (
// Create a queue, but don't obliterate an existing one!
const analytics = (safeGlobal[key] = safeGlobal[key] || []);

// Return the actual instance if the global analytics is nested in an instance.
if (analytics.instance && analytics.instance.initialize) {
return analytics.instance;
}
// If the real analytics.js is already on the page return.
if (analytics.initialize) {
return analytics;
Expand Down