UNPKG

@segment/analytics-next

Version:

Analytics Next (aka Analytics 2.0) is the latest version of Segment’s JavaScript SDK - enabling you to send your data to any tool without having to learn, test, or use a new API every time.

88 lines (72 loc) 2.35 kB
import { getGlobalAnalytics } from './global-analytics-helper' import { embeddedWriteKey } from './embedded-write-key' const analyticsScriptRegex = /(https:\/\/.*)\/analytics\.js\/v1\/(?:.*?)\/(?:platform|analytics.*)?/ const getCDNUrlFromScriptTag = (): string | undefined => { let cdn: string | undefined const scripts = Array.prototype.slice.call( document.querySelectorAll('script') ) scripts.forEach((s) => { const src = s.getAttribute('src') ?? '' const result = analyticsScriptRegex.exec(src) if (result && result[1]) { cdn = result[1] } }) return cdn } let _globalCDN: string | undefined // set globalCDN as in-memory singleton const getGlobalCDNUrl = (): string | undefined => { const result = _globalCDN ?? getGlobalAnalytics()?._cdn return result } export const setGlobalCDNUrl = (cdn: string) => { const globalAnalytics = getGlobalAnalytics() if (globalAnalytics) { globalAnalytics._cdn = cdn } _globalCDN = cdn } export const getCDN = (): string => { const globalCdnUrl = getGlobalCDNUrl() if (globalCdnUrl) return globalCdnUrl const cdnFromScriptTag = getCDNUrlFromScriptTag() if (cdnFromScriptTag) { return cdnFromScriptTag } else { // it's possible that the CDN is not found in the page because: // - the script is loaded through a proxy // - the script is removed after execution // in this case, we fall back to the default Segment CDN return `https://cdn.segment.com` } } export const getNextIntegrationsURL = () => { const cdn = getCDN() return `${cdn}/next-integrations` } /** * Replaces the CDN URL in the script tag with the one from Analytics.js 1.0 * * @returns the path to Analytics JS 1.0 **/ export function getLegacyAJSPath(): string { const writeKey = embeddedWriteKey() ?? getGlobalAnalytics()?._writeKey const scripts = Array.prototype.slice.call( document.querySelectorAll('script') ) let path: string | undefined = undefined for (const s of scripts) { const src = s.getAttribute('src') ?? '' const result = analyticsScriptRegex.exec(src) if (result && result[1]) { path = src break } } if (path) { return path.replace('analytics.min.js', 'analytics.classic.js') } return `https://cdn.segment.com/analytics.js/v1/${writeKey}/analytics.classic.js` }