Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

1.4 KB
Raw Blame
/* Copyright 2026 BoxLite AI. SPDX-License-Identifier: AGPL-3.0 */
import { AsyncLocalStorage } from 'node:async_hooks'
import { PostHog } from 'posthog-node'
import { logSignupAttribution, signupAttributionEvent } from '../signup-attribution-log'

export class ConsentBoundPostHog extends PostHog {
  private readonly signupDelivery = new AsyncLocalStorage<boolean>()

  // The public captureImmediate in posthog-node 4.18 resolves before its HTTP request.
  // Track the HTTP attempt through shutdown and report transport failures.
  deliver({
    distinctId,
    event,
    properties,
    groups,
    timestamp,
    uuid,
  }: Parameters<PostHog['capture']>[0]): Promise<void> {
    const capture = () =>
      this.captureStatelessImmediate(distinctId, event, { ...properties, $groups: groups }, { timestamp, uuid })
    return event === signupAttributionEvent ? this.signupDelivery.run(true, capture) : capture()
  }

  override fetch(...args: Parameters<PostHog['fetch']>): ReturnType<PostHog['fetch']> {
    if (!this.signupDelivery.getStore()) return super.fetch(...args)

    // sendImmediate catches HTTP errors, so its completion alone does not prove delivery.
    logSignupAttribution({ outcome: 'sending' })
    return super.fetch(...args).then((response) => {
      if (response.status >= 200 && response.status < 300) {
        logSignupAttribution({ outcome: 'delivered', http_status: response.status })
      }
      return response
    })
  }
}