Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

2.8 KB
Raw Blame
export type SnippetOption = {
    content: string
    enabled: boolean
    comment?: string
}

export const DEFAULT_SNIPPET_METHODS =
    'init capture register register_once register_for_session unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group identify setPersonProperties setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags resetGroups onFeatureFlags addFeatureFlagsHandler onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep'.split(
        ' '
    )

export function snippetFunctions(methods: readonly string[], arrayJs = '/static/array.js'): string {
    const snippetMethods = methods.join(' ')

    return `!function(t,e){var o,n,p,r;e.__SV||(window.posthog && window.posthog.__loaded)||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}p||((p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"${arrayJs}",p.onerror=function(){p=null},(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r));var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="${snippetMethods}".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);`
}

export interface BuildJsHtmlSnippetConfig {
    projectToken: string
    methods: string[]
    options: Record<string, SnippetOption>
    indent?: number
    arrayJs?: string
    scriptAttributes?: string
}

export function buildJsHtmlSnippet({
    projectToken,
    methods,
    options,
    indent = 0,
    arrayJs,
    scriptAttributes,
}: BuildJsHtmlSnippetConfig): string {
    const scriptTag = scriptAttributes ? `<script ${scriptAttributes}>` : '<script>'

    return [
        scriptTag,
        `    ${snippetFunctions(methods, arrayJs)}`,
        `    posthog.init('${projectToken}', {`,
        ...Object.entries(options)
            .map(([key, value]) => {
                if (value.enabled) {
                    return `        ${key}: '${value.content}',${value.comment ? ` // ${value.comment}` : ''}`
                }
            })
            .filter(Boolean),
        `    })`,
        '</script>',
    ]
        .map((x) => ' '.repeat(indent) + x)
        .join('\n')
}