diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 56a21d4d..62ea30bf 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -13,7 +13,10 @@ - **Breaking:** remove the `PostHogSessionReplayConfig.debouncerDelay` setter — use `throttleDelay` - **Breaking:** remove `PostHogDataMode.cellular` — use `PostHogDataMode.any` - **Breaking:** make `beforeSend` and `logsConfig.beforeSend` callbacks synchronous — load what they need ahead of time instead of using `await` -- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` from applying to that event first, and stop dropping that event on Windows and Linux +- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()`, `captureException()`, `captureFeatureView()` or `captureFeatureInteraction()` from applying to that event first, and stop dropping that event on Windows and Linux +- Run a `beforeSend` callback that renames a screen or exception event once, and keep its `userProperties` +- Keep `userProperties` and `userPropertiesSetOnce` that a `beforeSend` callback sets on a screen or exception event on web +- Send an event as its original user when a `beforeSend` callback calls `reset()` or `identify()` on Windows and Linux, instead of dropping it, and on web, instead of sending it as the new user - **Breaking:** remove `toMap()` from the config classes and `PostHogFeatureFlagResult.fromMap()` from the public API - **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb` - **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26 @@ -30,6 +33,8 @@ - **Breaking:** apply SDK properties, then registered properties, then event properties on Windows and Linux, so your value wins for that event, and run `beforeSend` after that merge - **Breaking:** always set `$lib` and `$lib_version` from the `PostHog-Sdk-Info` header on Windows and Linux, ignoring changes made in `beforeSend` - **Breaking:** send person processing as the `process_person_profile: false` option on Windows and Linux, only while it's off, instead of a `$process_person_profile` property on every event +- **Breaking:** pass `beforeSend` callbacks the event the native SDK built on iOS, macOS and Android, with its system and registered properties, and make their changes final +- **Breaking:** decide person processing before `beforeSend` runs on iOS, macOS, Android, Windows and Linux — a callback that removes `$set` no longer prevents a person profile, and a callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option - Add an `options` parameter to `capture`, `screen`, `identify`, `setPersonProperties`, `alias`, `group` and `captureException`, and `PostHogEvent.options` for `beforeSend` callbacks - Add `captureAi` for AI observability events, a no-op that returns `null` on web - Add `Posthog().onFeatureFlags()` to get notified after every feature flags load, returning a `PostHogFeatureFlagsSubscription` you can `unsubscribe()` @@ -44,5 +49,8 @@ - Run queued event encoding, file work and request compression on a background isolate on Windows and Linux so they no longer drop frames - Limit AI events waiting to be written on Windows and Linux to about 50 MiB in memory, dropping the oldest first and completing `captureAi` with `null` for them - Take an event's timestamp before the `beforeSend` callbacks run on Windows and Linux +- Add `PostHogEvent.uuid`, `distinctId` and `timestamp`, set on every platform except web — a callback can change the distinct ID and timestamp, and the event keeps its uuid +- Attach `$exception_steps` before `beforeSend` runs on Windows and Linux so callbacks can read or remove them — steps recorded while a callback runs, or an event a callback renames to `$exception`, no longer get them +- Add `PosthogFlutterPlugin.addBeforeSend` in Swift and Kotlin to filter or edit events the native SDK captures itself, such as crashes, app lifecycle and `$feature_flag_called` events - Declare Android `minSdkVersion` 23 to match `posthog-android` - Add a `defaultValue` option to `isFeatureEnabled()`, returned when the flag has no value diff --git a/api/posthog_flutter.api.json b/api/posthog_flutter.api.json index 8eee77bc..89dc0b0d 100644 --- a/api/posthog_flutter.api.json +++ b/api/posthog_flutter.api.json @@ -5671,6 +5671,33 @@ "name": "options", "relativePath": "lib/src/posthog_event.dart", "typeName": "Map?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "uuid", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "distinctId", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "isDeprecated": false, + "isExperimental": false, + "isNamed": true, + "isRequired": false, + "name": "timestamp", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "DateTime?" } ], "relativePath": "lib/src/posthog_event.dart", @@ -5734,6 +5761,39 @@ "name": "options", "relativePath": "lib/src/posthog_event.dart", "typeName": "Map?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": false, + "name": "uuid", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": true, + "name": "distinctId", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "String?" + }, + { + "entryPoints": [], + "isDeprecated": false, + "isExperimental": false, + "isReadable": true, + "isStatic": false, + "isWriteable": true, + "name": "timestamp", + "relativePath": "lib/src/posthog_event.dart", + "typeName": "DateTime?" } ], "isDeprecated": false, diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index fc39ac48..7e40a1ba 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -177,7 +177,7 @@ They serialized the internal platform-channel format and have no replacement. `t ### `beforeSend` callbacks are synchronous -`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback is a compile error. Load what it needs ahead of time and read it synchronously. +`BeforeSendCallback` is now `PostHogEvent? Function(PostHogEvent)`, and `BeforeSendLogCallback` is `PostHogLogRecord? Function(PostHogLogRecord)`. An `async` callback, or one declared to return `FutureOr`, is a compile error. Load what it needs ahead of time and read it synchronously. ```dart // Before @@ -258,6 +258,16 @@ On iOS, macOS and Android, a malformed, empty or whitespace-only payload from `g On iOS and macOS, string values in `PostHogBootstrapConfig.featureFlagPayloads`, such as `"123"`, stay strings instead of being decoded to numbers or booleans. +### `beforeSend` on iOS, macOS and Android + +**This is a silent change.** Callbacks now get the event the native SDK built, including its system properties, such as `$device_type` and `$session_id`, and registered properties. Their changes are final. In 5.x they saw only the properties you passed, so a callback that loops over or strips every property now also touches the SDK's. `PostHogEvent` also has `uuid`, `distinctId` and `timestamp`, set on every platform except web. + +**Person processing is decided before the callbacks run.** In 5.x, a callback that removed `$set` prevented a person profile. Now the event is still person-processed, and so are later events. Return `null` to drop an event that must not create a profile. A callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option. + +Nested maps are `Map`, and a non-empty list of maps is `List>`. Any other list is `List`, even a `List` you passed to `capture`, so cast its items instead of the list. + +Events the native SDK captures itself don't go through Dart callbacks. Use `PosthogFlutterPlugin.addBeforeSend` in Swift or Kotlin for those. + ### Lifecycle events on iOS and macOS `Application Installed`, `Application Updated` and `Application Opened` no longer include `version` and `build`. Update insights, cohorts and filters that use them to `$app_version` and `$app_build`. Android still sends them. @@ -274,6 +284,7 @@ A personal API key (`phx_...`) in `projectToken` now skips `setup()` with one lo - **Property order:** an event's properties are the SDK's, then registered properties, then the event's own, so your value now wins for that event. `beforeSend` runs after that merge, except that `$lib` and `$lib_version` always come from the `PostHog-Sdk-Info` header. - **Person processing:** it's sent as the `process_person_profile: false` option only while it's off, instead of a `$process_person_profile` property on every event. +- **`beforeSend` and person processing:** person processing is decided before the callbacks run. A callback that adds `$set` to an anonymous event must also set the `process_person_profile: true` option. - **Redirects:** only same-origin 307 and 308 redirects are followed. Any other redirect drops the batch. - **Retries:** a failed batch waits 1 second, doubling up to 30 seconds with ±25% jitter, instead of retrying within the same flush. `Retry-After` is a floor under that wait, capped at 30 seconds. - **Writes to disk:** an event is no longer on disk when `capture`, `screen`, `captureException`, `captureFeatureView`, `captureFeatureInteraction`, `identify`, `alias`, `group` or `setPersonProperties` returns, only when the returned future completes. One you didn't await can be lost if the app crashes or calls `exit()` right after. Await the call, or `Posthog().close()`, before `exit()`. Only `close()` also covers events the SDK captures itself, such as `$feature_flag_called`. An `identify` not awaited before `exit()` can lose its `$identify` event for good, because the new ID is already saved. `close()` can now take up to 4 seconds, and a later `setup()` waits for the queue's file work. diff --git a/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt b/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt index 4b16c282..ad8cdf26 100644 --- a/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt +++ b/posthog_flutter/android/src/main/kotlin/com/posthog/flutter/PosthogFlutterPlugin.kt @@ -14,6 +14,7 @@ import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper +import android.os.SystemClock import android.util.Log import android.view.PixelCopy import android.view.SurfaceView @@ -28,6 +29,7 @@ import com.posthog.PostHogBeforeSend import com.posthog.PostHogBootstrapConfig import com.posthog.PostHogCompression import com.posthog.PostHogConfig +import com.posthog.PostHogEvent import com.posthog.PostHogFeatureFlagsLoaded import com.posthog.PostHogFeatureFlagsSubscription import com.posthog.android.PostHogAndroid @@ -63,6 +65,8 @@ private const val END_DEBOUNCE_TICKS = 1 private const val BRIDGE_FAILURE_STRIKE_LIMIT = 3 +private const val BUILT_EVENT_TIMEOUT_MS = 60_000L + /** PosthogFlutterPlugin */ class PosthogFlutterPlugin : FlutterPlugin, @@ -81,6 +85,14 @@ class PosthogFlutterPlugin : private var postHogConfig: PostHogAndroidConfig? = null + // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart + // sends or drops them. Main-thread confined, like the channel callbacks. + // An event whose callbacks haven't finished after BUILT_EVENT_TIMEOUT_MS is + // dropped on the next build, so a callback that never completes can't keep + // it in memory. + // setup and close clear it, so a build can't be sent through a reconfigured SDK. + private val builtEvents = mutableMapOf>() + // Test seam: captures the built config even if setup() throws (mock Context in // unit tests). postHogConfig is only published on success, so production readers // never see an uninstalled config. @@ -283,6 +295,18 @@ class PosthogFlutterPlugin : screen(call, result) } + "buildEvent" -> { + buildEvent(call, result) + } + + "sendBuiltEvent" -> { + sendBuiltEvent(call, result) + } + + "discardBuiltEvent" -> { + discardBuiltEvent(call, result) + } + "captureLog" -> { captureLog(call, result) } @@ -574,6 +598,7 @@ class PosthogFlutterPlugin : return } + builtEvents.clear() updateFlagsGeneration(call) setupPostHog(args) @@ -862,6 +887,7 @@ class PosthogFlutterPlugin : ) } } + nativeBeforeSendSnapshot().forEach { this.addBeforeSend(it) } } lastBuiltConfig = config @@ -1862,6 +1888,91 @@ class PosthogFlutterPlugin : } } + /** + * Builds the event a capture, screen or captureException call would send, for the + * Dart beforeSend callbacks, and returns it to Dart. Returns null when the SDK skips it. + */ + private fun buildEvent( + call: MethodCall, + result: Result, + ) { + try { + val timestampMs: Long? = call.argument("timestamp")?.toLong() + val built = + PostHog.buildEventForWrapper( + call.argument("eventName")!!, + properties = call.argument("properties"), + userProperties = call.argument("userProperties"), + userPropertiesSetOnce = call.argument("userPropertiesSetOnce"), + options = call.argument("options"), + ai = call.argument("ai") ?: false, + timestamp = timestampMs?.let { Date(it) }, + ) + val uuid = built?.uuid?.toString() + if (built == null || uuid == null) { + result.success(null) + return + } + val now = SystemClock.elapsedRealtime() + builtEvents.values.removeAll { (_, builtAt) -> now - builtAt >= BUILT_EVENT_TIMEOUT_MS } + builtEvents[uuid] = built to now + result.success( + mapOf( + "event" to built.event, + "uuid" to uuid, + "distinctId" to built.distinctId, + "timestamp" to built.timestamp.time, + "properties" to built.properties?.let(::toChannelValue), + "options" to built.options?.let(::toChannelValue), + ), + ) + } catch (e: Throwable) { + result.error("PosthogFlutterException", e.localizedMessage, null) + } + } + + /** + * Sends an event from [buildEvent] as the Dart beforeSend callbacks left it. + * Returns its uuid once queued, or null. + */ + private fun sendBuiltEvent( + call: MethodCall, + result: Result, + ) { + try { + val uuid: String = call.argument("uuid")!! + val built = builtEvents.remove(uuid)?.first + if (built == null) { + result.success(null) + return + } + val properties: Map? = call.argument("properties") + val options: Map? = call.argument("options") + val timestampMs: Long? = call.argument("timestamp")?.toLong() + val event = + built.copy( + event = call.argument("event")!!, + distinctId = call.argument("distinctId")?.takeIf { it.isNotBlank() } ?: built.distinctId, + properties = properties?.toMutableMap() ?: mutableMapOf(), + timestamp = timestampMs?.let { Date(it) } ?: built.timestamp, + options = options?.toMutableMap() ?: mutableMapOf(), + ) + val sent = PostHog.sendBuiltEventForWrapper(event, ai = call.argument("ai") ?: false) + result.success(sent?.toString()) + } catch (e: Throwable) { + result.error("PosthogFlutterException", e.localizedMessage, null) + } + } + + /** Drops an event from [buildEvent] that a Dart beforeSend callback dropped. */ + private fun discardBuiltEvent( + call: MethodCall, + result: Result, + ) { + call.argument("uuid")?.let { builtEvents.remove(it) } + result.success(null) + } + private fun captureLog( call: MethodCall, result: Result, @@ -2249,6 +2360,7 @@ class PosthogFlutterPlugin : private fun close(result: Result) { try { + builtEvents.clear() PostHog.close() result.success(null) } catch (e: Throwable) { @@ -2351,6 +2463,42 @@ class PosthogFlutterPlugin : } companion object { + private val nativeBeforeSend = mutableListOf() + + /** + * Adds a native `beforeSend` hook that runs on every event the PostHog Android + * SDK sends, including the ones Dart never sees. + * + * Dart `PostHogConfig.beforeSend` callbacks run only on events captured from + * Dart. Events the native SDK captures itself, such as crashes, app lifecycle + * events, `$feature_flag_called`, `$identify` and session replay, reach only + * native hooks. Hooks run in the order they're added, after the Dart callbacks. + * Return the event, changed or not, to send it, or `null` to drop it. No hooks + * are added by default. + * + * Add hooks before the SDK is set up: before `Posthog().setup()` runs in Dart, + * or in `Application.onCreate` when the SDK is set up from the manifest + * (`com.posthog.posthog.AUTO_INIT`). Hooks added later apply from the next setup. + * + * ```kotlin + * // MainApplication.onCreate + * PosthogFlutterPlugin.addBeforeSend { event -> + * if (event.event == "Application Backgrounded") null else event + * } + * ``` + */ + @JvmStatic + fun addBeforeSend(beforeSend: PostHogBeforeSend) { + synchronized(nativeBeforeSend) { nativeBeforeSend.add(beforeSend) } + } + + private fun nativeBeforeSendSnapshot(): List = synchronized(nativeBeforeSend) { nativeBeforeSend.toList() } + + @VisibleForTesting + internal fun resetNativeBeforeSendForTesting() { + synchronized(nativeBeforeSend) { nativeBeforeSend.clear() } + } + // Mint route for pushIdentityProvider, anchored to the engine whose setup() // installed the provider. A live owner is never displaced; provider-enabled // engines stay candidates so detach promotes the most recent survivor instead @@ -2394,6 +2542,21 @@ class PosthogFlutterPlugin : } } +/** + * Copies [value] into the types the Flutter channel codec can send. Values the + * codec can't send, such as a `Date` registered natively, are sent as strings. + */ +internal fun toChannelValue(value: Any?): Any? = + when (value) { + null, is String, is Boolean, is Int, is Long, is Double -> value + is ByteArray, is IntArray, is LongArray, is FloatArray, is DoubleArray -> value + is Number -> value.toDouble() + is Map<*, *> -> value.entries.associate { (k, v) -> k.toString() to toChannelValue(v) } + is Iterable<*> -> value.map(::toChannelValue) + is Array<*> -> value.map(::toChannelValue) + else -> value.toString() + } + @Suppress("UNCHECKED_CAST") internal fun bootstrapConfigFromMap(bootstrap: Map): PostHogBootstrapConfig = PostHogBootstrapConfig( diff --git a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt index 2026e8cc..9734070a 100644 --- a/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt +++ b/posthog_flutter/android/src/test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt @@ -7,6 +7,7 @@ import android.os.BadParcelableException import android.view.Window import android.view.WindowManager import com.google.firebase.FirebaseApp +import com.posthog.PostHogBeforeSend import com.posthog.PostHogCompression import com.posthog.PostHogConfig import com.posthog.PostHogEvent @@ -42,6 +43,7 @@ internal class PosthogFlutterPluginTest { @BeforeTest fun resetSharedRoute() { PosthogFlutterPlugin.resetPushIdentityRouteForTesting() + PosthogFlutterPlugin.resetNativeBeforeSendForTesting() } @Test @@ -292,6 +294,30 @@ internal class PosthogFlutterPluginTest { assertNull(propertiesOf("custom")?.get("\$flutter_version")) } + @Test + fun setup_addBeforeSend_runsAfterTheFlutterVersionHook() { + val seen = mutableListOf() + PosthogFlutterPlugin.addBeforeSend { event -> + seen.add(event.properties?.get("\$flutter_version")) + null + } + val plugin = PosthogFlutterPlugin() + attach(plugin, Mockito.mock(BinaryMessenger::class.java)) + plugin.onMethodCall( + MethodCall("setup", mapOf("projectToken" to "test-token", "flutterVersion" to "3.35.0")), + Mockito.mock(MethodChannel.Result::class.java), + ) + val beforeSend = assertNotNull(plugin.lastBuiltConfig).beforeSendList + + val result = + beforeSend.fold( + PostHogEvent("Application Installed", "id", properties = mutableMapOf()), + ) { event, hook -> event?.let { hook.run(it) } } + + assertNull(result) + assertEquals(listOf("3.35.0"), seen) + } + @Test fun setup_screenshotControls_preserveDefaults() { val plugin = PosthogFlutterPlugin() @@ -1038,4 +1064,11 @@ internal class PosthogFlutterPluginTest { .verify(backgroundMessenger, Mockito.never()) .send(Mockito.any(), Mockito.any(), Mockito.any()) } + + @Test + fun `toChannelValue keeps primitive arrays the codec can send`() { + val values = listOf(intArrayOf(1), longArrayOf(2L), floatArrayOf(3f), doubleArrayOf(4.0), byteArrayOf(5)) + + values.forEach { assertSame(it, toChannelValue(it)) } + } } diff --git a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift index e65aa02d..8d55ae92 100644 --- a/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift +++ b/posthog_flutter/darwin/posthog_flutter/Sources/posthog_flutter/PosthogFlutterPlugin.swift @@ -43,6 +43,18 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { private static var instance: PosthogFlutterPlugin? private var channel: FlutterMethodChannel? + + // Events built for the Dart beforeSend callbacks, keyed by uuid, until Dart + // sends or drops them. Main-thread confined, like the channel callbacks. + // An event whose callbacks haven't finished after builtEventTimeout is + // dropped on the next build, so a callback that never completes can't + // keep it in memory. + // setup and close clear it, so a build can't be sent through a reconfigured SDK. + private var builtEvents: [String: (event: PostHogEvent, builtAt: TimeInterval)] = [:] + private static let builtEventTimeout: TimeInterval = 60 + + private static let nativeBeforeSendLock = NSLock() + private static var nativeBeforeSend: [BeforeSendBlock] = [] private var featureFlagsSubscription: PostHogFeatureFlagsSubscription? // Dart's feature flags lifecycle, sent with setup, reset and close. Each @@ -74,6 +86,32 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { private static var pushChannelCandidates: [FlutterMethodChannel] = [] private static var pushChannel: FlutterMethodChannel? + /// Adds a native `beforeSend` block that runs on every event the PostHog iOS + /// or macOS SDK sends, including the ones Dart never sees. + /// + /// Dart `PostHogConfig.beforeSend` callbacks run only on events captured from + /// Dart. Events the native SDK captures itself, such as crashes, app + /// lifecycle events, `$feature_flag_called`, `$identify` and session replay, + /// reach only native blocks. Blocks run in the order they're added, after the + /// Dart callbacks. Return the event, changed or not, to send it, or `nil` to + /// drop it. No blocks are added by default. + /// + /// Add blocks before the SDK is set up: before `Posthog().setup()` runs in + /// Dart, or before the plugin registers when the SDK is set up from + /// `Info.plist`. Blocks added later apply from the next setup. + /// + /// ```swift + /// // AppDelegate.swift, before GeneratedPluginRegistrant.register(with: self) + /// PosthogFlutterPlugin.addBeforeSend { event in + /// event.event == "Application Backgrounded" ? nil : event + /// } + /// ``` + public static func addBeforeSend(_ block: @escaping BeforeSendBlock) { + nativeBeforeSendLock.lock() + defer { nativeBeforeSendLock.unlock() } + nativeBeforeSend.append(block) + } + public static func getInstance() -> PosthogFlutterPlugin? { instance } @@ -491,8 +529,11 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { } } - if let flutterVersionBeforeSend = flutterVersionBeforeSend(posthogConfig) { - config.setBeforeSend(flutterVersionBeforeSend) + nativeBeforeSendLock.lock() + let beforeSend = [flutterVersionBeforeSend(posthogConfig)].compactMap { $0 } + nativeBeforeSend + nativeBeforeSendLock.unlock() + if !beforeSend.isEmpty { + config.setBeforeSend(beforeSend) } // Update SDK name and version @@ -531,6 +572,12 @@ public class PosthogFlutterPlugin: NSObject, FlutterPlugin { captureAi(call, result: result) case "screen": screen(call, result: result) + case "buildEvent": + buildEvent(call, result: result) + case "sendBuiltEvent": + sendBuiltEvent(call, result: result) + case "discardBuiltEvent": + discardBuiltEvent(call, result: result) case "captureLog": captureLog(call, result: result) case "alias": @@ -1385,6 +1432,7 @@ extension PosthogFlutterPlugin { result: @escaping FlutterResult ) { if let args = call.arguments as? [String: Any] { + builtEvents.removeAll() PosthogFlutterPlugin.setupPostHog(args, anchor: self) result(nil) } else { @@ -1584,6 +1632,93 @@ extension PosthogFlutterPlugin { } } + /// Builds the event a capture, screen or captureException call would send, + /// for the Dart beforeSend callbacks, and returns it to Dart. Returns nil + /// when the SDK skips it. + private func buildEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + guard let args = call.arguments as? [String: Any], + let eventName = args["eventName"] as? String + else { + _badArgumentError(result) + return + } + let timestamp = (args["timestamp"] as? Int64).map { + Date(timeIntervalSince1970: TimeInterval($0) / 1000.0) + } + let built = PostHogSDK.shared.buildEventForWrapper( + event: eventName, + distinctId: nil, + properties: args["properties"] as? [String: Any], + userProperties: args["userProperties"] as? [String: Any], + userPropertiesSetOnce: args["userPropertiesSetOnce"] as? [String: Any], + groups: nil, + options: args["options"] as? [String: Any], + timestamp: timestamp, + ai: args["ai"] as? Bool ?? false + ) + guard let built else { + result(nil) + return + } + let uuid = built.uuid.uuidString.lowercased() + let now = ProcessInfo.processInfo.systemUptime + builtEvents = builtEvents.filter { now - $0.value.builtAt < Self.builtEventTimeout } + builtEvents[uuid] = (built, now) + result([ + "event": built.event, + "uuid": uuid, + "distinctId": built.distinctId, + "timestamp": Int64((built.timestamp.timeIntervalSince1970 * 1000).rounded()), + "properties": built.properties, + "options": built.options, + ]) + } + + /// Sends an event from `buildEvent` as the Dart beforeSend callbacks left + /// it. Returns its uuid once queued, or nil. + private func sendBuiltEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + guard let args = call.arguments as? [String: Any], + let uuid = args["uuid"] as? String, + let eventName = args["event"] as? String + else { + _badArgumentError(result) + return + } + guard let built = builtEvents.removeValue(forKey: uuid)?.event else { + result(nil) + return + } + built.event = eventName + built.properties = args["properties"] as? [String: Any] ?? [:] + built.options = args["options"] as? [String: Any] ?? [:] + if let distinctId = args["distinctId"] as? String, + !distinctId.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + { + built.distinctId = distinctId + } + if let timestampMs = args["timestamp"] as? Int64 { + built.timestamp = Date(timeIntervalSince1970: TimeInterval(timestampMs) / 1000.0) + } + result(PostHogSDK.shared.sendBuiltEventForWrapper(built, ai: args["ai"] as? Bool ?? false)) + } + + /// Drops an event from `buildEvent` that a Dart beforeSend callback dropped. + private func discardBuiltEvent( + _ call: FlutterMethodCall, + result: @escaping FlutterResult + ) { + if let uuid = (call.arguments as? [String: Any])?["uuid"] as? String { + builtEvents.removeValue(forKey: uuid) + } + result(nil) + } + private func captureLog( _ call: FlutterMethodCall, result: @escaping FlutterResult @@ -1910,6 +2045,7 @@ extension PosthogFlutterPlugin { } private func close(_ result: @escaping FlutterResult) { + builtEvents.removeAll() PostHogSDK.shared.close() result(nil) } diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index aebc8567..cc96fe4b 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -55,7 +55,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userPropertiesSetOnce, Map? options, }) { - return applyBeforeSend( + final distinctId = + _beforeSendCallbacks.isEmpty ? null : currentWebDistinctId(); + final wasIdentified = distinctId != null && currentWebUserIdentified(); + final processed = applyBeforeSend( _beforeSendCallbacks, PostHogEvent( event: eventName, @@ -65,6 +68,35 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { options: options == null ? null : {...options}, ), ); + if (processed == null || + distinctId == null || + distinctId == currentWebDistinctId()) { + return processed; + } + // posthog-js stores an event's `$set` as the current user's person + // properties for flags, so after a reset() they would reach the next user. + // identify() of an anonymous user links the two, so they stay. + if (wasIdentified || !currentWebUserIdentified()) { + processed + ..userProperties = null + ..userPropertiesSetOnce = null + ..properties = {...?processed.properties} + ..properties!.remove(r'$set') + ..properties!.remove(r'$set_once'); + } + // posthog-js builds the event only after the callbacks, so one calling + // reset() or identify() would otherwise move the event to the new user. + // Event properties win over the stored distinct id. A callback changing + // consent under cookieless_mode swaps the id on purpose: neither the user + // who opted out nor the shared cookieless id may come back. + if (distinctId != r'$posthog_cookieless' && + !(posthog?.has_opted_out_capturing() ?? true)) { + processed.properties = { + 'distinct_id': distinctId, + ...?processed.properties, + }; + } + return processed; } /// posthog-js sends these calls' events without event properties, so @@ -240,6 +272,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { return; } + return _sendCapture(processedEvent); + } + + Future _sendCapture(PostHogEvent processedEvent) { final extracted = CaptureUtils.extractUserProperties( properties: processedEvent.properties, userProperties: processedEvent.userProperties, @@ -357,11 +393,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } @@ -370,16 +402,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { screenName; _currentScreen = finalScreenName; processedEvent.properties?.remove(PostHogPropertyName.screenName); + final extracted = CaptureUtils.extractUserProperties( + properties: processedEvent.properties, + userProperties: processedEvent.userProperties, + userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, + ); final remaining = _withOptionProperties( - processedEvent.properties, + extracted.properties, processedEvent.options, PostHogEventName.screen, ); + final userProperties = extracted.userProperties; + final userPropertiesSetOnce = extracted.userPropertiesSetOnce; return handleWebMethodCall( MethodCall('screen', { 'screenName': finalScreenName, if (remaining != null && remaining.isNotEmpty) 'properties': remaining, + if (userProperties != null) + 'userProperties': PropertyNormalizer.normalize(userProperties), + if (userPropertiesSetOnce != null) + 'userPropertiesSetOnce': + PropertyNormalizer.normalize(userPropertiesSetOnce), }), ); } @@ -686,22 +730,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } - final normalizedData = PropertyNormalizer.normalize( - _withOptionProperties( - processedEvent.properties?.cast(), - processedEvent.options, - PostHogEventName.exception, - ) ?? - {}, + final extracted = CaptureUtils.extractUserProperties( + properties: processedEvent.properties?.cast(), + userProperties: processedEvent.userProperties, + userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, ); + final userProperties = extracted.userProperties; + final userPropertiesSetOnce = extracted.userPropertiesSetOnce; + // posthog-js's captureException takes no capture options, but capture + // merges `$set` and `$set_once` from the event's properties. + final normalizedData = PropertyNormalizer.normalize({ + ...?_withOptionProperties( + extracted.properties, + processedEvent.options, + PostHogEventName.exception, + ), + if (userProperties != null) r'$set': userProperties, + if (userPropertiesSetOnce != null) r'$set_once': userPropertiesSetOnce, + }); return await handleWebMethodCall( MethodCall('captureException', {'properties': normalizedData}), diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 1448388a..ba1141e9 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -17,11 +17,16 @@ import 'utils/utils.dart'; import 'uuid.dart'; /// An event built by [PostHogCore.prepareEvent]: its properties, its -/// capture v1 options and the time it happened, as an ISO 8601 string. +/// capture v1 options, the time it happened as an ISO 8601 string, its uuid, +/// the id of the person it is captured for, and whether it was captured with +/// person properties. typedef PostHogPreparedEvent = ({ Map properties, Map? options, String timestamp, + String uuid, + String distinctId, + bool requestsPersonProcessing, }); /// Stateful PostHog client with session management, identity, and feature flags. @@ -492,20 +497,34 @@ abstract class PostHogCore extends PostHogCoreStateless { if (_ignoredWhileOptedOut('posthog.capture')) { return SynchronousFuture(null); } - final (:properties, :options, :timestamp) = prepared; + final ( + :properties, + :options, + :timestamp, + :uuid, + :distinctId, + :requestsPersonProcessing, + ) = prepared; + final queued = captureAiStateless(distinctId, event, + properties: properties, + options: options, + timestamp: timestamp, + uuid: uuid); + // Sent for another distinct id, its person properties belong to that + // person, not to the current user. + if (distinctId != getDistinctId()) return queued; final generation = _resetGeneration; final capturedAt = ++_personPropertyClock; - final queued = captureAiStateless(getDistinctId(), event, - properties: properties, options: options, timestamp: timestamp); - final requestsPerson = _requestsPersonProcessing(properties); - if (requestsPerson) _aiEventsRequestingPerson++; + if (requestsPersonProcessing) _aiEventsRequestingPerson++; return queued.then((uuid) { if (uuid != null && generation == _resetGeneration) { - _applyPersonProperties(properties, capturedAt: capturedAt); + _applyPersonProperties(properties, + requestsPersonProcessing: requestsPersonProcessing, + capturedAt: capturedAt); } return uuid; }).whenComplete(() { - if (requestsPerson && generation == _resetGeneration) { + if (requestsPersonProcessing && generation == _resetGeneration) { _aiEventsRequestingPerson--; } }); @@ -513,16 +532,6 @@ abstract class PostHogCore extends PostHogCoreStateless { return queued ?? SynchronousFuture(null); } - /// [options] with `process_person_profile: false` added when person - /// processing is off and [properties] neither ask for it nor set - /// `$process_person_profile`, as [prepareEvent] decides it. - Map? personProcessingOptions( - Map? options, - Map properties, - ) => - _personProcessingOptions(options, properties, - requested: _requestsPersonProcessing(properties)); - PostHogPreparedEvent? _prepareEvent( String event, { Map? properties, @@ -531,6 +540,7 @@ abstract class PostHogCore extends PostHogCoreStateless { if (_ignoredWhileOptedOut('posthog.capture')) return null; final allProperties = _enrichProperties(properties); + final requestsPersonProcessing = _requestsPersonProcessing(properties); // Once an event is person-processed, all later ones are too. A value // passed for this event alone doesn't count. if (_hasPersonProcessing()) { @@ -541,9 +551,12 @@ abstract class PostHogCore extends PostHogCoreStateless { options: _personProcessingOptions( options, allProperties, - requested: _requestsPersonProcessing(properties), + requested: requestsPersonProcessing, ), timestamp: currentISOTime(), + uuid: generateUuidV7(), + distinctId: getDistinctId(), + requestsPersonProcessing: requestsPersonProcessing, ); } @@ -551,10 +564,25 @@ abstract class PostHogCore extends PostHogCoreStateless { String event, PostHogPreparedEvent prepared, ) { - final (:properties, :options, :timestamp) = prepared; - final queued = captureStateless(getDistinctId(), event, - properties: properties, options: options, timestamp: timestamp); - _applyPersonProperties(properties); + final ( + :properties, + :options, + :timestamp, + :uuid, + :distinctId, + :requestsPersonProcessing, + ) = prepared; + final queued = captureStateless(distinctId, event, + properties: properties, + options: options, + timestamp: timestamp, + uuid: uuid); + // A callback can send the event for another distinct id; its person + // properties then belong to that person, not to the current user's + // person processing, flags or person-properties hash. + if (distinctId != getDistinctId()) return queued; + _applyPersonProperties(properties, + requestsPersonProcessing: requestsPersonProcessing); if (event == r'$set' || event == r'$identify') { final set = properties[r'$set']; final setOnce = properties[r'$set_once']; @@ -569,15 +597,18 @@ abstract class PostHogCore extends PostHogCoreStateless { /// Applies the person properties of a queued event with [properties]: /// taken from the event as queued, after the beforeSend callbacks, so a - /// value they removed or an event they or the size limit dropped neither - /// reaches /flags nor turns on person processing for later events. + /// value they removed doesn't reach /flags. Person processing follows + /// [requestsPersonProcessing], what the app captured, like the event itself + /// and the native SDKs. An event they or the size limit dropped does + /// neither. /// /// With [capturedAt], person properties set since then are kept. void _applyPersonProperties( Map properties, { + required bool requestsPersonProcessing, int? capturedAt, }) { - if (_requestsPersonProcessing(properties)) _enablePersonProcessing(); + if (requestsPersonProcessing) _enablePersonProcessing(); final set = _asPropertyMap(properties[r'$set']); final setOnce = _asPropertyMap(properties[r'$set_once']); if (capturedAt == null) { diff --git a/posthog_flutter/lib/src/core/posthog_core_stateless.dart b/posthog_flutter/lib/src/core/posthog_core_stateless.dart index 89b79d6f..6ef448bb 100644 --- a/posthog_flutter/lib/src/core/posthog_core_stateless.dart +++ b/posthog_flutter/lib/src/core/posthog_core_stateless.dart @@ -360,6 +360,7 @@ abstract class PostHogCoreStateless { required Map properties, Map? options, String? timestamp, + String? uuid, }) => _enqueue( _analytics, @@ -371,6 +372,7 @@ abstract class PostHogCoreStateless { ), options: options, timestamp: timestamp, + uuid: uuid, ); /// Queues [event] on the AI queue, and completes with its uuid, or null @@ -382,8 +384,9 @@ abstract class PostHogCoreStateless { required Map properties, Map? options, String? timestamp, + String? uuid, }) { - final (:uuid, :queued) = _enqueue( + final enqueued = _enqueue( _ai, 'capture', _buildPayload( @@ -393,8 +396,9 @@ abstract class PostHogCoreStateless { ), options: options, timestamp: timestamp, + uuid: uuid, ); - return queued.then((kept) => kept ? uuid : null); + return enqueued.queued.then((kept) => kept ? enqueued.uuid : null); } @protected @@ -525,16 +529,18 @@ abstract class PostHogCoreStateless { }); } - /// Queues [message] on [lane] and returns its uuid, with whether the queue - /// keeps it: the AI queue drops an event over its size limit. Its capture - /// v1 [options] are queued with it; the legacy option properties are - /// converted only when the request is built, see [captureV1Event]. + /// Queues [message] on [lane], with [uuid] or a new one, and returns its + /// uuid, with whether the queue keeps it: the AI queue drops an event over + /// its size limit. Its capture v1 [options] are queued with it; the legacy + /// option properties are converted only when the request is built, see + /// [captureV1Event]. ({String uuid, Future queued}) _enqueue( _CaptureLane lane, String type, Map message, { Map? options, String? timestamp, + String? uuid, }) { final prepared = { ...message, @@ -546,7 +552,7 @@ abstract class PostHogCoreStateless { 'library': postHogFlutterSdkName, 'library_version': postHogFlutterVersion, 'timestamp': timestamp ?? currentISOTime(), - 'uuid': generateUuidV7(), + 'uuid': uuid ?? generateUuidV7(), }; final queue = lane.queue; diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 2f6562c3..20f6c9f9 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -415,17 +415,35 @@ class PostHogConfig { /// `config.captureApplicationLifecycleEvents` is enabled /// - Feature flag events (`$feature_flag_called`) when /// `config.sendFeatureFlagEvent` is enabled - /// - Identity events (`$set`) when `identify` is called + /// - Identity events (`$identify`, `$set`, `$create_alias`, + /// `$groupidentify`) from `identify`, `setPersonProperties`, `alias` + /// and `group` /// - Survey events (`survey shown`, etc.) when `config.surveys` is enabled - /// - Only user-provided properties are available; system properties (like - /// `$device_type`, `$session_id`) are added by the native SDK at a later - /// stage. On Windows and Linux, the callbacks see the system properties - /// and the options the SDK adds, and can change them for that event, - /// except `$lib` and `$lib_version`, which PostHog sets from the SDK. + /// On iOS, macOS and Android, add a native hook with + /// `PosthogFlutterPlugin.addBeforeSend` (Swift or Kotlin) to filter or + /// edit those events. + /// - On iOS, macOS, Android, Windows and Linux, the callbacks see the + /// system properties (like `$device_type` and `$session_id`), the + /// registered properties and the options the SDK adds, and can change + /// them for that event, except `$lib` and `$lib_version`, which PostHog + /// sets from the SDK. On iOS, macOS and Android, registering callbacks + /// adds one more call to the native SDK per event. The native SDK keeps + /// each built event until Dart sends it back, and discards one still + /// waiting after a minute (for example, after a hot restart). On web, + /// only the event's own properties are available; posthog-js adds the + /// rest later. /// /// **Note:** - /// - Callbacks are synchronous. Load anything they need (such as remote - /// config) ahead of time. + /// - Callbacks are synchronous and run on the calling isolate, so a slow one + /// blocks the UI. Load anything they need (such as remote config or feature + /// flags) ahead of time; a change made after the callback returns is not + /// sent. + /// - A callback that captures an event must not do so for that event too, or + /// it never finishes. + /// - On web, an event whose callback calls `reset()` stays on its user but + /// joins the next user's session and person processing, and its user + /// properties are dropped, because posthog-js builds the event after the + /// callbacks. /// - If a callback throws, the event is dropped and later callbacks are not /// called. /// - If any callback returns `null`, the event is dropped and subsequent diff --git a/posthog_flutter/lib/src/posthog_event.dart b/posthog_flutter/lib/src/posthog_event.dart index 7063dd89..c8a3e556 100644 --- a/posthog_flutter/lib/src/posthog_event.dart +++ b/posthog_flutter/lib/src/posthog_event.dart @@ -2,17 +2,33 @@ /// /// This class is used in before-send callbacks to allow modification of events /// before they are sent to PostHog. +/// +/// On iOS, macOS, Android, Windows and Linux the callbacks get the event the +/// SDK is about to send, with its system and registered properties already +/// added. It also carries its [uuid], [distinctId] and [timestamp]. +/// +/// ```dart +/// config.beforeSend = [ +/// (event) { +/// event.properties?.remove(r'$device_name'); +/// return event; +/// }, +/// ]; +/// ``` class PostHogEvent { /// The name of the event (e.g., 'button_clicked', '$screen', '$exception') String event; - /// User-provided properties for this event. + /// The event's properties. + /// + /// On iOS, macOS, Android, Windows and Linux, the map already holds the + /// system properties (like `$device_type` and `$session_id`), then the + /// registered properties, then the event's own, and the event is sent as + /// the callbacks leave it. `$set` and `$set_once` are in [userProperties] + /// and [userPropertiesSetOnce] instead. /// - /// On iOS, macOS, Android and web, system properties (like $device_type, - /// $session_id, etc.) are added by the native SDK at a later stage and are - /// not available in this map. On Windows and Linux, the map already holds - /// them, then the registered properties, then the event's own, and the - /// event is sent as the callbacks leave it. + /// On web, only the event's own properties are here; posthog-js adds the + /// rest later. Map? properties; /// User properties to set on the user profile ($set). @@ -32,6 +48,25 @@ class PostHogEvent { /// unset. Map? options; + /// The event's unique id, a lowercase UUID v7. + /// + /// Set on iOS, macOS, Android, Windows and Linux, where the SDK builds the + /// event before the callbacks run. `null` on web. The id is kept even when + /// a callback returns another [PostHogEvent]. + final String? uuid; + + /// The id of the person the event is captured for. + /// + /// Set on iOS, macOS, Android, Windows and Linux, where a callback can + /// change it. `null` on web. + String? distinctId; + + /// When the event happened. + /// + /// Set on iOS, macOS, Android, Windows and Linux, where a callback can + /// change it. `null` on web. + DateTime? timestamp; + /// Creates an event passed to a before-send callback. /// /// The [event] is the event name to capture. @@ -45,16 +80,22 @@ class PostHogEvent { /// `$set_once`. /// /// The optional [options] are the event's per-event options. + /// + /// The optional [uuid], [distinctId] and [timestamp] are set by the SDK on + /// every platform but web. PostHogEvent({ required this.event, this.properties, this.userProperties, this.userPropertiesSetOnce, this.options, + this.uuid, + this.distinctId, + this.timestamp, }); @override String toString() { - return 'PostHogEvent(event: $event, properties: $properties, userProperties: $userProperties, userPropertiesSetOnce: $userPropertiesSetOnce, options: $options)'; + return 'PostHogEvent(event: $event, uuid: $uuid, distinctId: $distinctId, timestamp: $timestamp, properties: $properties, userProperties: $userProperties, userPropertiesSetOnce: $userPropertiesSetOnce, options: $options)'; } } diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 94b16b02..57378cf3 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -3,6 +3,7 @@ import 'dart:async'; import 'package:flutter/widgets.dart'; import 'core/file_storage.dart'; +import 'core/posthog_core.dart' show PostHogPreparedEvent; import 'core/utils/utils.dart'; import 'error_tracking/dart_exception_processor.dart'; import 'feature_flag_result.dart'; @@ -100,18 +101,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return client; } - DesktopPostHog? _clientForContinuation( - String op, - _ClientScope scope, - String distinctId, - ) { + DesktopPostHog? _clientForContinuation(String op, _ClientScope scope) { final client = _clientFor(op); if (client == null) return null; - if (_clientScope != scope || - client.optedOut || - client.getDistinctId() != distinctId) { - printIfDebug('[PostHog] $op dropped: the project, the user or the ' - 'consent changed while beforeSend was running.'); + if (_clientScope != scope || client.optedOut) { + printIfDebug('[PostHog] $op dropped: the project or the consent changed ' + 'while beforeSend was running.'); return null; } return client; @@ -277,8 +272,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -295,9 +288,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('capture', scope, distinctId); + final current = _clientForContinuation('capture', scope); if (current == null) return; - await _captureProcessed(current, processed, exceptionSteps, prepared); + await _captureProcessed(current, processed, prepared); }); @override @@ -318,8 +311,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return null; final scope = _clientScope; if (scope == null) return null; - final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -336,10 +327,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return null; } - final current = _clientForContinuation('captureAi', scope, distinctId); + final current = _clientForContinuation('captureAi', scope); if (current == null) return null; - return _captureProcessed(current, processed, exceptionSteps, prepared, - ai: true); + return _captureProcessed(current, processed, prepared, ai: true); }); @override @@ -354,8 +344,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -367,6 +355,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: options, ); if (prepared == null) return; + final sessionId = client.getSessionId(); final processed = _runBeforeSend(prepared.event); if (processed == null) { printIfDebug( @@ -374,12 +363,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('screen', scope, distinctId); + final current = _clientForContinuation('screen', scope); if (current == null) return; // A renamed event is no longer a screen view. if (processed.event != PostHogEventName.screen) { - await _captureProcessed(current, processed, exceptionSteps, prepared); + await _captureProcessed(current, processed, prepared); return; } @@ -390,12 +379,13 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - // Later events that set no `$screen_name` of their own carry this one. - if (finalScreenName is String) { + // Later events that set no `$screen_name` of their own carry this one, + // unless a callback's reset() started a session for the next user. + if (finalScreenName is String && current.getSessionId() == sessionId) { current.registerForSession( {PostHogPropertyName.screenName: finalScreenName}); } - await _captureProcessed(current, processed, exceptionSteps, prepared); + await _captureProcessed(current, processed, prepared); }); /// Structured logs are not supported on the desktop implementation. @@ -625,8 +615,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final exceptionProps = DartExceptionProcessor.processException( error: error, @@ -652,10 +640,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = - _clientForContinuation('captureException', scope, distinctId); + final current = _clientForContinuation('captureException', scope); if (current == null) return; - await _captureProcessed(current, processed, exceptionSteps, prepared); + await _captureProcessed(current, processed, prepared); }); @override @@ -757,7 +744,9 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// [PostHogEvent.userPropertiesSetOnce]. Legacy `$set` and `$set_once` /// maps in [properties] stay in [PostHogEvent.properties], so a callback /// that removes them there still keeps them off the event. - /// The event's time is taken now, before the callbacks run. + /// The event's time, uuid and distinct id are taken now, before the + /// callbacks run. An `$exception` event gets the exception steps recorded + /// up to now, unless it sets its own. _PreparedEvent? _prepare( DesktopPostHog client, String eventName, @@ -767,10 +756,18 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { Map? options, }) { final callerOptions = cleanEventOptions(options); + final steps = _exceptionSteps?.steps; final prepared = client.prepareEvent( eventName, - properties: - _mergeUserProps(properties, userProperties, userPropertiesSetOnce), + properties: _mergeUserProps( + eventName == PostHogEventName.exception && + steps != null && + steps.isNotEmpty + ? {r'$exception_steps': steps, ...?properties} + : properties, + userProperties, + userPropertiesSetOnce, + ), options: callerOptions, ); if (prepared == null) return null; @@ -794,11 +791,11 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { userProperties: _nonNull(userProperties), userPropertiesSetOnce: _nonNull(userPropertiesSetOnce), options: preparedOptions == null ? null : {...preparedOptions}, + uuid: prepared.uuid, + distinctId: prepared.distinctId, + timestamp: DateTime.parse(prepared.timestamp), ), - timestamp: prepared.timestamp, - implicitPersonProcessing: - callerOptions?['process_person_profile'] == null, - sdkPersonProcessing: preparedOptions?['process_person_profile'], + prepared: prepared, ); } @@ -824,40 +821,40 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// Queues [event] as the beforeSend callbacks left it, on the AI queue /// with [ai], and returns its uuid, or null when it is not queued. The - /// client adds nothing to it; an `$exception` event gets the exception - /// steps recorded up to now. + /// client adds nothing to it. The event keeps the uuid it was prepared + /// with; a blank distinct id or a missing timestamp falls back to the + /// prepared one. FutureOr _captureProcessed( DesktopPostHog client, PostHogEvent event, - ExceptionStepsBuffer? exceptionSteps, _PreparedEvent prepared, { bool ai = false, }) { if (!_hasName(event.event)) return null; - final properties = _withExceptionSteps( - event.event, - exceptionSteps, - _mergeUserProps( - event.properties, - event.userProperties, - event.userPropertiesSetOnce, - ), + final properties = _mergeUserProps( + event.properties, + event.userProperties, + event.userPropertiesSetOnce, ) ?? const {}; // Options are sent as they are, unknown keys included. An option wins // over its legacy property on the event. - Map? options = cleanEventOptions(event.options); - // Person properties the callbacks added or removed decide person - // processing again, unless a callback changed the SDK's option. - if (prepared.implicitPersonProcessing && - options?['process_person_profile'] == prepared.sdkPersonProcessing) { - options = client.personProcessingOptions( - {...?options}..remove('process_person_profile'), properties); - } + final options = cleanEventOptions(event.options); + final base = prepared.prepared; + final distinctId = event.distinctId; + final timestamp = event.timestamp; final queued = ( properties: properties, options: options, - timestamp: prepared.timestamp, + timestamp: timestamp == null || + timestamp.isAtSameMomentAs(DateTime.parse(base.timestamp)) + ? base.timestamp + : timestamp.toUtc().toIso8601String(), + uuid: base.uuid, + distinctId: distinctId == null || distinctId.trim().isEmpty + ? base.distinctId + : distinctId, + requestsPersonProcessing: base.requestsPersonProcessing, ); return ai ? client.captureAiPrepared(event.event, queued) @@ -871,20 +868,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return false; } - /// Uses the originating client's steps even when a same-scope restart - /// happened during beforeSend. Explicit event steps take precedence. - Map? _withExceptionSteps( - String event, - ExceptionStepsBuffer? exceptionSteps, - Map? properties, - ) { - final steps = exceptionSteps?.steps; - if (event != PostHogEventName.exception || steps == null || steps.isEmpty) { - return properties; - } - return {r'$exception_steps': steps, ...?properties}; - } - Map? _mergeUserProps( Map? properties, Map? userProperties, @@ -916,12 +899,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { } } -/// An event built for the beforeSend callbacks, with the time it happened, -/// whether its person processing was left to its properties, and the -/// `process_person_profile` option the SDK gave it. +/// An event built for the beforeSend callbacks, and what it was built from. typedef _PreparedEvent = ({ PostHogEvent event, - String timestamp, - bool implicitPersonProcessing, - Object? sdkPersonProcessing, + PostHogPreparedEvent prepared, }); diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 18da22b0..6ba50646 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -1,4 +1,5 @@ import 'dart:async'; +import 'dart:typed_data'; import 'util/platform_io_stub.dart' if (dart.library.io) 'util/platform_io_real.dart'; @@ -52,6 +53,10 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { /// Stored beforeSend callbacks for dropping/modifying events List _beforeSendCallbacks = []; + /// Starts with `$` so the native SDKs treat it like `$screen` in every other + /// respect. Never sent: sendBuiltEvent sets the event's real name. + static const _capturedScreenBuildName = r'$captured_screen'; + final _order = CallOrder(); Future _invoke(String method, [Object? arguments]) { @@ -90,27 +95,152 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return _handlerInstalled; } - /// Applies the beforeSend callbacks to an event in order. - /// Returns the possibly modified event, or null if any callback drops it. - PostHogEvent? _runBeforeSend( - String eventName, - Map? properties, { - Map? userProperties, - Map? userPropertiesSetOnce, - Map? options, + /// Builds the event in the native SDK, runs the beforeSend callbacks on + /// the built event, then has the native SDK send what they return, so the + /// callbacks see what the SDK adds. [build] holds the `buildEvent` + /// arguments. + /// + /// Returns the native send result (the uuid on the AI lane), or null when + /// the native SDK skips the event or a callback drops it. + Future _buildRunBeforeSendAndSend( + Map build, { + bool ai = false, + String? eventName, + }) async { + // setup() replaces the callbacks at once but reaches native after this + // event, which must not run under the next setup's filters. + final callbacks = _beforeSendCallbacks; + Object? result; + await _order.event<({String uuid, Map? send})?>( + () => _buildAndRunBeforeSend(build, ai, callbacks, eventName), + (built) async { + if (built == null) return; + final send = built.send; + if (send == null) { + await _methodChannel + .invokeMethod('discardBuiltEvent', {'uuid': built.uuid}); + return; + } + result = await _methodChannel.invokeMethod( + 'sendBuiltEvent', + {...send, 'uuid': built.uuid, 'ai': ai}, + ); + }, + ); + return result; + } + + /// Has the native SDK build the event and runs the beforeSend callbacks on + /// it. Returns null when the native SDK skips the event; `send` is null when + /// a callback drops it. + Future<({String uuid, Map? send})?> _buildAndRunBeforeSend( + Map build, + bool ai, + List callbacks, + String? eventName, + ) async { + final built = await _methodChannel.invokeMapMethod( + 'buildEvent', + {...build, 'ai': ai}, + ); + final uuid = built?['uuid']; + if (built == null || uuid is! String) return null; + + Map? send; + try { + final processed = applyBeforeSend( + callbacks, + _eventFromNative(built, eventName: eventName), + ); + if (processed == null) { + printIfDebug( + '[PostHog] Event dropped by beforeSend: ${eventName ?? built['event']}'); + } else { + send = _eventToNative(processed); + } + } catch (e) { + printIfDebug('[PostHog] Event dropped, it could not be read: $e'); + } + return (uuid: uuid, send: send); + } + + static PostHogEvent _eventFromNative( + Map built, { + String? eventName, }) { - return applyBeforeSend( - _beforeSendCallbacks, - PostHogEvent( - event: eventName, - properties: properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - options: options == null ? null : {...options}, - ), + final properties = _stringKeyedMap(built['properties']) ?? {}; + final userProperties = _stringKeyedMap(properties.remove(r'$set')); + final userPropertiesSetOnce = + _stringKeyedMap(properties.remove(r'$set_once')); + final timestampMs = built['timestamp'] as int?; + return PostHogEvent( + event: eventName ?? built['event'] as String? ?? '', + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: (built['options'] as Map?)?.cast(), + uuid: built['uuid'] as String?, + distinctId: built['distinctId'] as String?, + timestamp: timestampMs == null + ? null + : DateTime.fromMillisecondsSinceEpoch(timestampMs, isUtc: true), ); } + static Map _eventToNative(PostHogEvent event) { + final extracted = CaptureUtils.extractUserProperties( + properties: event.properties, + userProperties: event.userProperties, + userPropertiesSetOnce: event.userPropertiesSetOnce, + ); + final properties = { + ...?extracted.properties, + if (extracted.userProperties != null) r'$set': extracted.userProperties!, + if (extracted.userPropertiesSetOnce != null) + r'$set_once': extracted.userPropertiesSetOnce!, + }; + return { + 'event': event.event, + 'properties': PropertyNormalizer.normalize(properties), + if (event.distinctId?.trim().isNotEmpty == true) + 'distinctId': event.distinctId, + if (event.timestamp != null) + 'timestamp': event.timestamp!.millisecondsSinceEpoch, + 'options': cleanEventOptions(event.options) ?? const {}, + }; + } + + /// Copies a map from the channel with its string keys and non-null values. + static Map? _stringKeyedMap(Object? value) { + if (value is! Map) return null; + return { + for (final entry in value.entries) + if (entry.key is String && entry.value != null) + entry.key as String: _valueFromNative(entry.value) as Object, + }; + } + + /// Gives a nested value from the channel, where every map and list is + /// untyped, the types `capture` callers pass: callbacks commonly cast + /// `$exception_list` to `List>`, and a failed cast + /// drops the event. + static Object? _valueFromNative(Object? value) { + if (value is Map) { + if (value.keys.any((key) => key is! String)) return value; + return { + for (final entry in value.entries) + entry.key as String: _valueFromNative(entry.value), + }; + } + if (value is List && value is! TypedData) { + final items = value.map(_valueFromNative).toList(); + return items.isNotEmpty && items.every((i) => i is Map) + ? List>.from(items) + : items; + } + return value; + } + /// Native plugin calls to Flutter /// Future _handleMethodCall(MethodCall call) async { @@ -407,71 +537,81 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return null; } - Object? result; - await _order.event( - () => _runBeforeSend( - eventName, - properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - options: options, - ), - (processedEvent) async { - result = await _sendCapture(method, eventName, processedEvent); - }, - ); - return result; - } - - Future _sendCapture( - String method, - String eventName, - PostHogEvent? processedEvent, - ) async { - if (processedEvent == null) { - printIfDebug('[PostHog] Event dropped by beforeSend: $eventName'); - return null; + if (_beforeSendCallbacks.isNotEmpty) { + final ai = method == 'captureAi'; + try { + return await _buildRunBeforeSendAndSend( + { + ..._captureArguments( + eventName: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: options, + ), + // The native builders treat `$screen` as a screen() call: it needs + // a `$screen_name` and, on iOS, loses person properties. A plain + // capture has neither rule, so it builds under another name. + if (!ai && eventName == PostHogEventName.screen) + 'eventName': _capturedScreenBuildName, + }, + ai: ai, + eventName: eventName, + ); + } on PlatformException catch (exception) { + printIfDebug('Exeption on $method: $exception'); + return null; + } } try { - // Use processed event properties (potentially modified by beforeSend) - final extracted = CaptureUtils.extractUserProperties( - properties: processedEvent.properties, - userProperties: processedEvent.userProperties, - userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, + return await _invoke( + method, + _captureArguments( + eventName: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + options: options, + ), ); - - final extractedProperties = extracted.properties; - final extractedUserProperties = extracted.userProperties; - final extractedUserPropertiesSetOnce = extracted.userPropertiesSetOnce; - - final normalizedProperties = extractedProperties != null - ? PropertyNormalizer.normalize(extractedProperties) - : null; - final normalizedUserProperties = extractedUserProperties != null - ? PropertyNormalizer.normalize(extractedUserProperties) - : null; - final normalizedUserPropertiesSetOnce = - extractedUserPropertiesSetOnce != null - ? PropertyNormalizer.normalize(extractedUserPropertiesSetOnce) - : null; - final cleanedOptions = cleanEventOptions(processedEvent.options); - - return await _invoke(method, { - 'eventName': processedEvent.event, - if (normalizedProperties != null) 'properties': normalizedProperties, - if (normalizedUserProperties != null) - 'userProperties': normalizedUserProperties, - if (normalizedUserPropertiesSetOnce != null) - 'userPropertiesSetOnce': normalizedUserPropertiesSetOnce, - if (cleanedOptions != null) 'options': cleanedOptions, - }); } on PlatformException catch (exception) { printIfDebug('Exeption on $method: $exception'); return null; } } + /// The `capture`, `captureAi` and `buildEvent` arguments, with `$set` and + /// `$set_once` moved out of [properties] and the values normalized. + static Map _captureArguments({ + required String eventName, + Map? properties, + Map? userProperties, + Map? userPropertiesSetOnce, + Map? options, + }) { + final extracted = CaptureUtils.extractUserProperties( + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + ); + final extractedProperties = extracted.properties; + final extractedUserProperties = extracted.userProperties; + final extractedUserPropertiesSetOnce = extracted.userPropertiesSetOnce; + final cleanedOptions = cleanEventOptions(options); + return { + 'eventName': eventName, + if (extractedProperties != null) + 'properties': PropertyNormalizer.normalize(extractedProperties), + if (extractedUserProperties != null) + 'userProperties': PropertyNormalizer.normalize(extractedUserProperties), + if (extractedUserPropertiesSetOnce != null) + 'userPropertiesSetOnce': + PropertyNormalizer.normalize(extractedUserPropertiesSetOnce), + if (cleanedOptions != null) 'options': cleanedOptions, + }; + } + @override Future screen({ required String screenName, @@ -482,62 +622,34 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return; } - // The screen name argument wins over a properties `$screen_name`. - // beforeSend still runs after this and can change the name. - final propsWithScreenName = { - ...?properties, - PostHogPropertyName.screenName: screenName, - }; - - // Apply beforeSend callback - screen events are captured as $screen - return _order.event( - () => _runBeforeSend( - PostHogEventName.screen, - propsWithScreenName, - options: options, - ), - (processedEvent) => _sendScreen(screenName, processedEvent), - ); - } - - Future _sendScreen( - String screenName, - PostHogEvent? processedEvent, - ) async { - if (processedEvent == null) { - printIfDebug('[PostHog] Screen event dropped by beforeSend: $screenName'); - return; - } - - // If event name was changed, use regular capture() instead - if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + if (_beforeSendCallbacks.isNotEmpty) { + try { + final cleanedOptions = cleanEventOptions(options); + await _buildRunBeforeSendAndSend({ + 'eventName': PostHogEventName.screen, + // The screen name argument wins over a properties `$screen_name`. + 'properties': PropertyNormalizer.normalize({ + ...?properties, + PostHogPropertyName.screenName: screenName, + }), + if (cleanedOptions != null) 'options': cleanedOptions, + }); + } on PlatformException catch (exception) { + printIfDebug('Exeption on screen: $exception'); + } return; } - // Get the (possibly modified) screen name from properties and remove it - final finalScreenName = - processedEvent.properties?[PostHogPropertyName.screenName] as String? ?? - screenName; - // It will be added back by native sdk - processedEvent.properties?.remove(PostHogPropertyName.screenName); - try { - final normalizedProperties = processedEvent.properties?.isNotEmpty == true - ? PropertyNormalizer.normalize( - processedEvent.properties!.cast(), - ) - : null; - - final cleanedOptions = cleanEventOptions(processedEvent.options); + // The native SDK adds the screen name back as `$screen_name`. + final screenProperties = {...?properties} + ..remove(PostHogPropertyName.screenName); + final cleanedOptions = cleanEventOptions(options); await _invoke('screen', { - 'screenName': finalScreenName, - if (normalizedProperties != null) 'properties': normalizedProperties, + 'screenName': screenName, + if (screenProperties.isNotEmpty) + 'properties': PropertyNormalizer.normalize(screenProperties), if (cleanedOptions != null) 'options': cleanedOptions, }); } on PlatformException catch (exception) { @@ -975,56 +1087,34 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { inAppByDefault: _config?.errorTrackingConfig.inAppByDefault ?? true, ); - // Apply beforeSend callback - exception events are captured as $exception - await _order.event( - () => _runBeforeSend( - PostHogEventName.exception, - exceptionProps.cast(), - options: options, - ), - (processedEvent) => _sendException(error, processedEvent), - ); - } on PlatformException catch (exception) { - printIfDebug('Exception in captureException: $exception'); - } - } + if (_beforeSendCallbacks.isNotEmpty) { + final cleanedOptions = cleanEventOptions(options); + await _buildRunBeforeSendAndSend({ + 'eventName': PostHogEventName.exception, + 'properties': PropertyNormalizer.normalize( + exceptionProps.cast(), + ), + 'timestamp': DateTime.now().millisecondsSinceEpoch, + if (cleanedOptions != null) 'options': cleanedOptions, + }); + return; + } - Future _sendException( - Object error, - PostHogEvent? processedEvent, - ) async { - if (processedEvent == null) { - printIfDebug( - '[PostHog] Exception event dropped by beforeSend: ${error.runtimeType}', + // Add timestamp from Flutter side (will be used and removed from native plugins) + final timestamp = DateTime.now().millisecondsSinceEpoch; + final normalizedData = PropertyNormalizer.normalize( + exceptionProps.cast(), ); - return; - } + final cleanedOptions = cleanEventOptions(options); - // If event name was changed, use capture() instead - if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); - return; + await _invoke('captureException', { + 'timestamp': timestamp, + 'properties': normalizedData, + if (cleanedOptions != null) 'options': cleanedOptions, + }); + } on PlatformException catch (exception) { + printIfDebug('Exception in captureException: $exception'); } - - // Add timestamp from Flutter side (will be used and removed from native plugins) - final timestamp = DateTime.now().millisecondsSinceEpoch; - final normalizedData = processedEvent.properties != null - ? PropertyNormalizer.normalize( - processedEvent.properties!.cast(), - ) - : {}; - - final cleanedOptions = cleanEventOptions(processedEvent.options); - - await _invoke('captureException', { - 'timestamp': timestamp, - 'properties': normalizedData, - if (cleanedOptions != null) 'options': cleanedOptions, - }); } @override diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 1f070ad7..a52b4d08 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -67,6 +67,8 @@ extension PostHogExtension on PostHog { external void unregister(JSAny key); // ignore: non_constant_identifier_names external JSAny? get_session_id(); + // ignore: non_constant_identifier_names + external JSAny? get_property(JSAny name); // The loader snippet's stub returns undefined until posthog-js loads. external JSFunction? onFeatureFlags(JSFunction callback); external void startSessionRecording(); @@ -297,6 +299,27 @@ Future> _reloadFeatureFlags(PostHog? ph) async { } } +/// The user posthog-js would send an event as right now. +String? currentWebDistinctId() => + posthog?.get_distinct_id()?.dartify() as String?; + +/// Whether posthog-js's current user is identified. +bool currentWebUserIdentified() => + posthog?.get_property(r'$user_state'.toJS)?.dartify() == 'identified'; + +/// posthog-js capture options carrying `$set` and `$set_once`. +/// See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts +Map _personCaptureOptions(Map args) { + final userProperties = safeMapConversion(args['userProperties']); + final userPropertiesSetOnce = safeMapConversion( + args['userPropertiesSetOnce'], + ); + return { + if (userProperties.isNotEmpty) '\$set': userProperties, + if (userPropertiesSetOnce.isNotEmpty) '\$set_once': userPropertiesSetOnce, + }; +} + Future handleWebMethodCall(MethodCall call) async { _maybeOverrideSDKInfo(); @@ -339,20 +362,7 @@ Future handleWebMethodCall(MethodCall call) async { final properties = safeMapConversion(args['properties']); properties.addAll(_getLocationProperties()); _addAppVersionProperties(properties); - final userProperties = safeMapConversion(args['userProperties']); - final userPropertiesSetOnce = safeMapConversion( - args['userPropertiesSetOnce'], - ); - - // Build options object for posthog-js capture with $set and $set_once - // See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts - final options = {}; - if (userProperties.isNotEmpty) { - options['\$set'] = userProperties; - } - if (userPropertiesSetOnce.isNotEmpty) { - options['\$set_once'] = userPropertiesSetOnce; - } + final options = _personCaptureOptions(args); posthog?.capture( stringToJSAny(eventName), @@ -367,7 +377,12 @@ Future handleWebMethodCall(MethodCall call) async { properties.addAll(_getLocationProperties()); _addAppVersionProperties(properties); - posthog?.capture(stringToJSAny('\$screen'), mapToJSAny(properties), null); + final options = _personCaptureOptions(args); + posthog?.capture( + stringToJSAny('\$screen'), + mapToJSAny(properties), + options.isNotEmpty ? mapToJSAny(options) : null, + ); break; case 'captureLog': final body = args['body'] as String; diff --git a/posthog_flutter/lib/src/utils/call_order.dart b/posthog_flutter/lib/src/utils/call_order.dart index 9dbb430a..42b6af6e 100644 --- a/posthog_flutter/lib/src/utils/call_order.dart +++ b/posthog_flutter/lib/src/utils/call_order.dart @@ -35,8 +35,7 @@ class CallOrder { /// Runs [hook] once every earlier call has been handed over, so it sees /// the state the app left before capturing, then hands its result to - /// [send]. Later calls wait for [send] to finish, so it may itself capture - /// (a beforeSend that renames a `$screen` does). + /// [send]. Later calls wait for [send] to finish. Future event( FutureOr Function() hook, Future Function(E event) send, @@ -62,8 +61,8 @@ class CallOrder { Future Function(E event) send, ) async { final timer = Timer(maxWait, () { - printIfDebug('[PostHog] beforeSend took longer than ' - '${maxWait.inSeconds}s; later calls no longer wait for it.'); + printIfDebug('[PostHog] An event took longer than ' + '${maxWait.inSeconds}s to hand over; later calls no longer wait for it.'); turn.ahead.then((_) => turn.end()); }); try { diff --git a/posthog_flutter/test/event_shape_snapshot_test.dart b/posthog_flutter/test/event_shape_snapshot_test.dart index 0320d7e0..b369d61f 100644 --- a/posthog_flutter/test/event_shape_snapshot_test.dart +++ b/posthog_flutter/test/event_shape_snapshot_test.dart @@ -21,6 +21,23 @@ void main() { setUp(() async { messenger.setMockMethodCallHandler(channel, (call) async { calls.add(call); + final arguments = call.arguments; + if (call.method == 'buildEvent' && arguments is Map) { + return { + 'event': arguments['eventName'], + 'uuid': 'snapshot-uuid', + 'distinctId': 'snapshot-user', + 'timestamp': 1709296200000, + 'properties': { + ...?(arguments['properties'] as Map?), + if (arguments['userProperties'] != null) + r'$set': arguments['userProperties'], + if (arguments['userPropertiesSetOnce'] != null) + r'$set_once': arguments['userPropertiesSetOnce'], + }, + 'options': arguments['options'] ?? {}, + }; + } return null; }); PosthogFlutterPlatformInterface.instance = PosthogFlutterIO(); @@ -268,17 +285,22 @@ void main() { ); final normalizedCalls = calls.map((call) { - if (call.method != 'captureException') { + final arguments = call.arguments is Map + ? Map.from(call.arguments as Map) + : null; + final rawProperties = arguments?['properties']; + if (arguments == null || + rawProperties is! Map || + !rawProperties.containsKey(r'$exception_list')) { return call; } - final arguments = Map.from(call.arguments as Map); - expect(arguments['timestamp'], isA()); - arguments['timestamp'] = ''; + if (call.method == 'buildEvent') { + expect(arguments['timestamp'], isA()); + arguments['timestamp'] = ''; + } - final properties = Map.from( - arguments['properties'] as Map, - ); + final properties = Map.from(rawProperties); final exceptionList = List.from( properties[r'$exception_list'] as List, ); diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 172ec20a..a1ec3bcd 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -574,6 +574,207 @@ void main() { }); group('beforeSend hook', () { + group('that calls the SDK', () { + test('can capture another event without running forever', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.event); + if (event.event == 'outer') { + platform.capture(eventName: 'inner'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'outer'); + await server.waitForEvent('inner'); + await server.waitForEvent('outer'); + + expect(seen, ['outer', 'inner']); + }); + + final calls = Function(PosthogFlutterDesktop)>{ + 'reset': (platform) => platform.reset(), + 'identify': (platform) => platform.identify(userId: 'user-1'), + 'optOut': (platform) => platform.optOut(), + 'getDistinctId': (platform) => platform.getDistinctId(), + 'getFeatureFlag': (platform) => platform.getFeatureFlag(key: 'flag'), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform + .capture(eventName: 'trigger') + .timeout(const Duration(seconds: 2)); + }); + }); + }); + + for (final (name, call) + in <(String, Future Function(PosthogFlutterDesktop))>[ + ('reset', (platform) => platform.reset()), + ('identify', (platform) => platform.identify(userId: 'user-1')), + ]) { + test('$name inside the hook keeps the event on the earlier user', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], firstUser); + expect(await platform.getDistinctId(), isNot(firstUser)); + }); + } + + test('reset inside the hook leaves an identified event person-processed', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + await platform.identify(userId: 'user-1'); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], 'user-1'); + expect(_optionsOf(event), isNot(contains('process_person_profile'))); + }); + + test('identify inside the hook leaves an anonymous event personless', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(_optionsOf(event)['process_person_profile'], isFalse); + }); + + test('reset inside the hook keeps the screen from the next user', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after reset'); + + final event = await server.waitForEvent('after reset'); + expect(_propertiesOf(event), isNot(contains(r'$screen_name'))); + }); + + test('identify inside the hook keeps the screen for later events', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after identify'); + + final event = await server.waitForEvent('after identify'); + expect(_propertiesOf(event)[r'$screen_name'], 'Checkout'); + }); + + test('optOut inside the hook drops the event', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.optOut(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + await platform.optIn(); + await platform.capture(eventName: 'after'); + await server.waitForEvent('after'); + + expect(server.eventNames, isNot(contains('trigger'))); + }); + + test('calls after a burst of events apply in order', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server)..beforeSend = [(event) => event]; + final platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + final sent = [ + for (var i = 0; i < 100; i++) platform.capture(eventName: 'event $i'), + platform.reset(), + platform.capture(eventName: 'after reset'), + ]; + await Future.wait(sent); + + final last = await server.waitForEvent('event 99'); + expect(last['distinct_id'], firstUser); + final after = await server.waitForEvent('after reset'); + expect(after['distinct_id'], isNot(firstUser)); + }); + test('dropping an event keeps it off the wire', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -591,6 +792,55 @@ void main() { expect(server.eventNames, isNot(contains('dropped event'))); }); + test( + 'a callback sees the uuid, distinct id and timestamp, and can change ' + 'the distinct id and timestamp but not the uuid', () async { + final server = await LocalPostHogServer.start(); + PostHogEvent? seen; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen = PostHogEvent( + event: event.event, + uuid: event.uuid, + distinctId: event.distinctId, + timestamp: event.timestamp, + ); + return PostHogEvent( + event: event.event, + properties: event.properties, + distinctId: 'changed-user', + timestamp: DateTime.utc(2025, 1, 2, 3, 4, 5, 678), + ); + }, + ]; + final platform = await setUpPlatform(config); + final distinctId = await platform.getDistinctId(); + + await platform.capture(eventName: 'identity'); + + final event = await server.waitForEvent('identity'); + expect(seen!.uuid, isNotNull); + expect(seen!.distinctId, distinctId); + expect(seen!.timestamp, isNotNull); + expect(event['uuid'], seen!.uuid); + expect(event['distinct_id'], 'changed-user'); + expect(event['timestamp'], '2025-01-02T03:04:05.678Z'); + }); + + test('a blank distinct id from a callback keeps the current one', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [(event) => event..distinctId = ' ']; + final platform = await setUpPlatform(config); + final distinctId = await platform.getDistinctId(); + + await platform.capture(eventName: 'blank'); + + final event = await server.waitForEvent('blank'); + expect(event['distinct_id'], distinctId); + }); + test('modifications made by a callback are delivered', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -691,6 +941,54 @@ void main() { expect(personProperties, isNot(contains('dropped'))); }); + test( + 'person properties of an event a callback sends for another distinct ' + 'id stay out of flag evaluation', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..preloadFeatureFlags = false + ..beforeSend = [(event) => event..distinctId = 'other-user']; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'other', + userProperties: {'email': 'other@example.com'}, + ); + await platform.reloadFeatureFlags(); + + final event = await server.waitForEvent('other'); + expect(event['distinct_id'], 'other-user'); + final personProperties = Map.from( + server.flagsRequests.single.body['person_properties']! as Map, + ); + expect(personProperties, isNot(contains('email'))); + }); + + test( + 'person properties of an event a callback sends for another distinct ' + 'id leave person processing off for the current user', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'other') event.distinctId = 'other-user'; + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'other', + userProperties: {'email': 'other@example.com'}, + ); + await platform.capture(eventName: 'next'); + + final event = await server.waitForEvent('other'); + expect(event['distinct_id'], 'other-user'); + final next = await server.waitForEvent('next'); + expect(_optionsOf(next)['process_person_profile'], isFalse); + }); + test('a dropped person update does not turn on person processing', () async { final server = await LocalPostHogServer.start(); @@ -710,7 +1008,7 @@ void main() { expect(_optionsOf(event)['process_person_profile'], isFalse); }); - test('an event whose person properties are removed is personless', + test('removing person properties leaves person processing as prepared', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -723,10 +1021,10 @@ void main() { ); final event = await server.waitForEvent('redacted'); - expect(_optionsOf(event)['process_person_profile'], isFalse); + expect(_optionsOf(event), isNot(contains('process_person_profile'))); }); - test('person properties a callback adds turn on person processing', + test('person properties a callback adds leave the event personless', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -738,10 +1036,49 @@ void main() { await platform.capture(eventName: 'signed up'); final event = await server.waitForEvent('signed up'); - expect(_optionsOf(event), isNot(contains('process_person_profile'))); + expect(_optionsOf(event)['process_person_profile'], isFalse); expect(_propertiesOf(event)[r'$set'], {'email': 'user@example.com'}); }); + test('person properties a callback adds leave later events personless', + () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'signed up') { + event.userProperties = {'email': 'user@example.com'}; + } + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.capture(eventName: 'signed up'); + await platform.capture(eventName: 'next'); + + final next = await server.waitForEvent('next'); + expect(_optionsOf(next)['process_person_profile'], isFalse); + }); + + test( + 'removing person properties keeps person processing on for later events', + () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server) + ..beforeSend = [(event) => event..userProperties = null]; + final platform = await setUpPlatform(config); + + await platform.capture( + eventName: 'redacted', + userProperties: {'email': 'user@example.com'}, + ); + await platform.capture(eventName: 'next'); + + final next = await server.waitForEvent('next'); + expect(_optionsOf(next), isNot(contains('process_person_profile'))); + }); + test('a callback can turn person processing back on', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -1118,6 +1455,30 @@ void main() { expect(stepMessagesOf(event), ['custom']); }); + test('are visible to beforeSend, which can remove them', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.properties?.remove(r'$exception_steps')); + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.addExceptionStep('recorded'); + await platform.captureException(error: StateError('removed steps')); + + final event = await server.waitForEvent(r'$exception'); + expect(seen, [ + [ + {r'$message': 'recorded', r'$timestamp': isA()}, + ], + ]); + expect(stepMessagesOf(event), isNull); + }); + test('are not attached while disabled', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index e4b59c14..eb4dc6b1 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -39,6 +41,12 @@ void main() { if (methodCall.method == 'setup') { return null; } + if (methodCall.method == 'buildEvent') { + return nativeBuiltEvent(methodCall.arguments as Map); + } + if (methodCall.method == 'sendBuiltEvent') { + return (methodCall.arguments as Map)['uuid']; + } return null; }); }); @@ -672,13 +680,14 @@ isolate_dso_base: 7000000000 eventName: r'$ai_span', options: options); await posthogFlutterIO.screen(screenName: 'Home', options: options); - expect(seen, [options, options]); + expect(seen, [sent, sent]); const changed = { 'process_person_profile': false, 'product_tour_id': 'tour-1', }; - expect(argsOf('captureAi')['options'], changed); - expect(argsOf('screen')['options'], changed); + final sends = log.where((c) => c.method == 'sendBuiltEvent').toList(); + expect(sends.map((c) => (c.arguments as Map)['options']), + [changed, changed]); }); test('a screen renamed by beforeSend keeps its options', () async { @@ -694,8 +703,8 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.screen(screenName: 'Home', options: options); - expect(argsOf('capture')['eventName'], 'screen viewed'); - expect(argsOf('capture')['options'], sent); + expect(argsOf('sendBuiltEvent')['event'], 'screen viewed'); + expect(argsOf('sendBuiltEvent')['options'], sent); }); test('captureAi dropped by beforeSend returns null', () async { @@ -708,7 +717,7 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.captureAi(eventName: r'$ai_generation'), isNull, ); - expect(log.where((c) => c.method == 'captureAi'), isEmpty); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); }); @@ -745,9 +754,9 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.capture(eventName: 'original_event'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'modified_event'); + expect(args['event'], 'modified_event'); }); test('beforeSend can modify properties', () async { @@ -767,7 +776,7 @@ isolate_dso_base: 7000000000 properties: {'original': true}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); expect(args['properties'], {'modified': true}); }); @@ -789,9 +798,11 @@ isolate_dso_base: 7000000000 userProperties: {'name': 'Original Name'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['userProperties'], {'name': 'Modified Name'}); + expect(args['properties'], { + r'$set': {'name': 'Modified Name'} + }); }); test('beforeSend can modify userPropertiesSetOnce', () async { @@ -811,10 +822,10 @@ isolate_dso_base: 7000000000 userPropertiesSetOnce: {'last_logged_in_at': '2024-01-01'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['userPropertiesSetOnce'], { - 'last_logged_in_at': '2025-01-01', + expect(args['properties'], { + r'$set_once': {'last_logged_in_at': '2025-01-01'}, }); }); @@ -825,7 +836,7 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.capture(eventName: 'dropped_event'); - final captureCalls = log.where((c) => c.method == 'capture'); + final captureCalls = log.where((c) => c.method == 'sendBuiltEvent'); expect(captureCalls, isEmpty); }); @@ -844,12 +855,13 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.capture(eventName: 'drop me'); await posthogFlutterIO.capture(eventName: 'keep me'); - final captureCalls = log.where((c) => c.method == 'capture').toList(); + final captureCalls = + log.where((c) => c.method == 'sendBuiltEvent').toList(); expect(captureCalls.length, 1); final args = Map.from( captureCalls.first.arguments as Map, ); - expect(args['eventName'], 'keep me'); + expect(args['event'], 'keep me'); }); test('beforeSend exception drops event and stops the chain', () async { @@ -885,7 +897,7 @@ isolate_dso_base: 7000000000 ); expect(callOrder, ['transform', 'throw']); - expect(log, isEmpty); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); test('multiple beforeSend callbacks are applied in order', () async { @@ -919,9 +931,9 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.capture(eventName: 'original'); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'original_first_second_third'); + expect(args['event'], 'original_first_second_third'); expect(callOrder, [1, 2, 3]); }); @@ -980,10 +992,12 @@ isolate_dso_base: 7000000000 properties: {'event_prop': 'value'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userProperties'], {'developer_name': 'John'}); + expect(args['properties'], { + 'event_prop': 'value', + r'$set': {'developer_name': 'John'}, + }); }, ); @@ -1009,10 +1023,12 @@ isolate_dso_base: 7000000000 properties: {'event_prop': 'value'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userPropertiesSetOnce'], {'first_seen': '2025-01-01'}); + expect(args['properties'], { + 'event_prop': 'value', + r'$set_once': {'first_seen': '2025-01-01'}, + }); }, ); @@ -1037,13 +1053,15 @@ isolate_dso_base: 7000000000 userProperties: {'from_direct': 'direct_value', 'shared': 'direct'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args['properties'], {'event_prop': 'value'}); - expect(args['userProperties'], { - 'from_legacy': 'legacy_value', - 'from_direct': 'direct_value', - 'shared': 'direct', + expect(args['properties'], { + 'event_prop': 'value', + r'$set': { + 'from_legacy': 'legacy_value', + 'from_direct': 'direct_value', + 'shared': 'direct', + }, }); }); @@ -1064,9 +1082,203 @@ isolate_dso_base: 7000000000 userProperties: {'name': 'John'}, ); - final captureCall = log.firstWhere((c) => c.method == 'capture'); + final captureCall = log.firstWhere((c) => c.method == 'sendBuiltEvent'); final args = Map.from(captureCall.arguments as Map); - expect(args.containsKey('userProperties'), isFalse); + expect(args['properties'], isNot(contains(r'$set'))); + }); + }); + + group('PosthogFlutterIO beforeSend on the native-built event', () { + Map argsOf(String method) => Map.from( + log.singleWhere((c) => c.method == method).arguments as Map, + ); + + Future setUpWith(BeforeSendCallback callback) => posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [callback])); + + test('without callbacks an event takes one native call', () async { + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + log.clear(); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(log.map((c) => c.method), ['capture']); + }); + + test('callbacks see what the native SDK added', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + if (call.method != 'buildEvent') return null; + return { + ...nativeBuiltEvent(call.arguments as Map), + 'properties': { + r'$lib': 'posthog-flutter', + 'plan': 'pro', + r'$set': {'name': 'Ada'}, + }, + }; + }); + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(seen!.uuid, 'built-uuid'); + expect(seen!.distinctId, 'user-1'); + expect(seen!.timestamp, DateTime.utc(2026)); + expect(seen!.properties, {r'$lib': 'posthog-flutter', 'plan': 'pro'}); + expect(seen!.userProperties, {'name': 'Ada'}); + }); + + test('callbacks can cast nested values from the native SDK', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + if (call.method != 'buildEvent') return null; + return { + ...nativeBuiltEvent(call.arguments as Map), + 'properties': { + r'$exception_list': [ + { + 'type': 'StateError', + 'stacktrace': { + 'frames': [ + {'in_app': true}, + ], + }, + }, + ], + 'bytes': Int32List.fromList([1, 2]), + 'empty': [], + }, + }; + }); + await setUpWith((event) { + final list = + event.properties![r'$exception_list'] as List>; + final stack = list.single['stacktrace'] as Map; + final frames = stack['frames'] as List>; + frames.single['in_app'] = false; + return event; + }); + + await posthogFlutterIO.capture(eventName: 'failed'); + + final sent = log.singleWhere((c) => c.method == 'sendBuiltEvent'); + expect((sent.arguments as Map)['properties'], { + r'$exception_list': [ + { + 'type': 'StateError', + 'stacktrace': { + 'frames': [ + {'in_app': false}, + ], + }, + }, + ], + 'bytes': [1, 2], + 'empty': [], + }); + }); + + test('sends what the callbacks return with the built uuid', () async { + await setUpWith((event) => PostHogEvent( + event: 'renamed', + properties: {'a': 1}, + distinctId: 'user-2', + timestamp: DateTime.utc(2025), + )); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(argsOf('sendBuiltEvent'), { + 'event': 'renamed', + 'properties': {'a': 1}, + 'distinctId': 'user-2', + 'timestamp': DateTime.utc(2025).millisecondsSinceEpoch, + 'options': {}, + 'uuid': 'built-uuid', + 'ai': false, + }); + }); + + test('captureAi builds and sends on the AI lane', () async { + await setUpWith((event) => event); + + final uuid = + await posthogFlutterIO.captureAi(eventName: r'$ai_generation'); + + expect(uuid, 'built-uuid'); + expect(argsOf('buildEvent')['ai'], isTrue); + expect(argsOf('sendBuiltEvent')['ai'], isTrue); + }); + + test('screen builds a \$screen event with its name', () async { + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.screen(screenName: 'Home', properties: {'a': 1}); + + expect(argsOf('buildEvent'), { + 'eventName': r'$screen', + 'properties': {'a': 1, r'$screen_name': 'Home'}, + 'ai': false, + }); + expect(seen!.event, r'$screen'); + expect(seen!.properties, {'a': 1, r'$screen_name': 'Home'}); + }); + + test('capturing \$screen keeps capture semantics', () async { + PostHogEvent? seen; + await setUpWith((event) => seen = event); + + await posthogFlutterIO.capture( + eventName: r'$screen', + userProperties: {'plan': 'pro'}, + ); + + expect(argsOf('buildEvent')['eventName'], isNot(r'$screen')); + expect(argsOf('buildEvent')['eventName'], startsWith(r'$')); + expect(seen!.event, r'$screen'); + expect(seen!.userProperties, {'plan': 'pro'}); + expect(argsOf('sendBuiltEvent')['event'], r'$screen'); + }); + + test('captureException builds with its own timestamp', () async { + await setUpWith((event) => event); + + await posthogFlutterIO.captureException(error: StateError('boom')); + + expect(argsOf('buildEvent')['eventName'], r'$exception'); + expect(argsOf('buildEvent')['timestamp'], isA()); + }); + + test('a dropped event is discarded, not sent', () async { + await setUpWith((event) => null); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(argsOf('discardBuiltEvent'), {'uuid': 'built-uuid'}); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); + }); + + test('an event the native SDK skips never reaches the callbacks', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (call) async { + log.add(call); + return null; + }); + var called = false; + await setUpWith((event) { + called = true; + return event; + }); + + await posthogFlutterIO.capture(eventName: 'clicked'); + + expect(called, isFalse); + expect(log.where((c) => c.method == 'sendBuiltEvent'), isEmpty); }); }); @@ -1169,10 +1381,213 @@ isolate_dso_base: 7000000000 await posthogFlutterIO.reset(); await Future.wait(sent); - expect(log.map((c) => c.method), - ['capture', 'screen', 'captureException', 'reset']); + expect(log.map((c) => c.method), [ + if (hooked) ...[ + for (var i = 0; i < 3; i++) ...['buildEvent', 'sendBuiltEvent'], + ] else ...[ + 'capture', + 'screen', + 'captureException' + ], + 'reset', + ]); }); } + + test('an event keeps the callbacks set when it was captured', () async { + await posthogFlutterIO.setup( + PostHogConfig('test_project_token', beforeSend: [(event) => null])); + log.clear(); + + final sent = posthogFlutterIO.capture(eventName: 'checkout'); + await posthogFlutterIO.setup(PostHogConfig('test_project_token')); + await sent; + + expect(log.map((c) => c.method), + ['buildEvent', 'discardBuiltEvent', 'setup']); + }); + + final lifecycleCalls = Function()>{ + 'disable': () => posthogFlutterIO.optOut(), + 'close': () => posthogFlutterIO.close(), + 'setup': () => + posthogFlutterIO.setup(PostHogConfig('test_project_token')), + }; + lifecycleCalls.forEach((method, call) { + test('$method waits for an event between its build and send', () async { + await posthogFlutterIO.setup(PostHogConfig('test_project_token', + beforeSend: [(event) => event])); + log.clear(); + + final sent = posthogFlutterIO.capture(eventName: 'checkout'); + await call(); + await sent; + + expect( + log.map((c) => c.method), ['buildEvent', 'sendBuiltEvent', method]); + }); + }); + }); + + group('PosthogFlutterIO hook that renames an event', () { + final renames = Function(PosthogFlutterIO)>{ + 'screen': (io) => io.screen(screenName: 'Checkout'), + 'captureException': (io) => + io.captureException(error: StateError('boom')), + }; + + renames.forEach((name, send) { + test('$name runs the hook once and keeps its user properties', () async { + var runs = 0; + await posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [ + (event) { + runs++; + event.event = 'renamed'; + event.userProperties = {'source': 'hook'}; + return event; + }, + ])); + log.clear(); + + await send(posthogFlutterIO); + + expect(runs, 1); + expect(log.where((c) => c.method == 'buildEvent'), hasLength(1)); + final args = Map.from(log + .singleWhere((c) => c.method == 'sendBuiltEvent') + .arguments as Map); + expect(args['event'], 'renamed'); + expect((args['properties'] as Map)[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('PosthogFlutterIO hook that calls the SDK', () { + Future setUpWith( + PostHogEvent? Function(PostHogEvent event) hook, + ) async { + await posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [hook])); + log.clear(); + } + + test('can capture another event without running forever', () async { + final seen = []; + await setUpWith((event) { + seen.add(event.event); + if (event.event == 'outer') { + posthogFlutterIO.capture(eventName: 'inner'); + } + return event; + }); + + await posthogFlutterIO.capture(eventName: 'outer'); + await pumpEventQueue(); + + expect(seen, ['outer', 'inner']); + expect( + log + .where((c) => c.method == 'sendBuiltEvent') + .map((c) => (c.arguments as Map)['event']), + unorderedEquals(['inner', 'outer']), + ); + }); + + final calls = Function(PosthogFlutterIO)>{ + 'reset': (io) => io.reset(), + 'identify': (io) => io.identify(userId: 'user-1'), + 'optOut': (io) => io.optOut(), + 'close': (io) => io.close(), + 'getFeatureFlag': (io) => io.getFeatureFlag(key: 'flag'), + 'getDistinctId': (io) => io.getDistinctId(), + 'isOptOut': (io) => io.isOptOut(), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock the event', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (methodCall) async { + log.add(methodCall); + return switch (methodCall.method) { + 'distinctId' => 'user-1', + 'isOptOut' => false, + 'buildEvent' => nativeBuiltEvent(methodCall.arguments as Map), + 'sendBuiltEvent' => (methodCall.arguments as Map)['uuid'], + _ => null, + }; + }); + await setUpWith((event) { + call(posthogFlutterIO); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout') + .timeout(const Duration(seconds: 2)); + await pumpEventQueue(); + + expect(log.map((c) => c.method), contains('sendBuiltEvent')); + }); + }); + + test('an error in unawaited work does not drop the event', () async { + final errors = []; + await runZonedGuarded(() async { + await setUpWith((event) { + Future.error(StateError('late failure')); + return event; + }); + await posthogFlutterIO.capture(eventName: 'checkout'); + await pumpEventQueue(); + }, (error, _) => errors.add(error)); + + expect(errors, hasLength(1)); + expect(log.map((c) => c.method), ['buildEvent', 'sendBuiltEvent']); + }); + + test('a change made after the hook returned is not sent', () async { + await setUpWith((event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + final args = + log.singleWhere((c) => c.method == 'sendBuiltEvent').arguments as Map; + expect(args['properties'], {'plan': 'pro'}); + }); + }); + + group('PosthogFlutterIO calls after a burst of events', () { + test('keep the order the app made them in', () async { + await posthogFlutterIO.setup( + PostHogConfig('test_project_token', beforeSend: [(event) => event])); + log.clear(); + + final sent = >[]; + final expected = []; + for (var i = 0; i < 1000; i++) { + sent.add(posthogFlutterIO.capture(eventName: 'event $i')); + expected.add('event $i'); + if (i % 100 == 99) { + sent.add(posthogFlutterIO.reset()); + expected.add('reset'); + } + } + await Future.wait(sent); + + expect( + log.where((c) => c.method != 'buildEvent').map((c) => + c.method == 'reset' ? 'reset' : (c.arguments as Map)['event']), + expected, + ); + }); }); group('PosthogFlutterIO addExceptionStep', () { @@ -1413,3 +1828,21 @@ isolate_dso_base: 7000000000 }); }); } + +/// What the native `buildEvent` handler returns for [args], without adding +/// SDK properties. +Map nativeBuiltEvent(Map args, {String uuid = 'built-uuid'}) { + return { + 'event': args['eventName'], + 'uuid': uuid, + 'distinctId': 'user-1', + 'timestamp': args['timestamp'] ?? 1767225600000, + 'properties': { + ...?(args['properties'] as Map?), + if (args['userProperties'] != null) r'$set': args['userProperties'], + if (args['userPropertiesSetOnce'] != null) + r'$set_once': args['userPropertiesSetOnce'], + }, + 'options': args['options'] ?? {}, + }; +} diff --git a/posthog_flutter/test/posthog_logs_test.dart b/posthog_flutter/test/posthog_logs_test.dart index 20c8e147..5a008f34 100644 --- a/posthog_flutter/test/posthog_logs_test.dart +++ b/posthog_flutter/test/posthog_logs_test.dart @@ -142,6 +142,39 @@ void main() { }); group('beforeSend hook', () { + test('runs before captureLog returns its first await', () async { + var ran = false; + final config = PostHogConfig('test_token'); + config.logsConfig.beforeSend = [ + (record) { + ran = true; + return record; + }, + ]; + await setupWith(config); + + final sent = Posthog().captureLog(body: 'hello'); + expect(ran, isTrue); + expect(fake.capturedLogs, hasLength(1)); + await sent; + }); + + test('a hook that logs does not run forever when it stops itself', + () async { + final config = PostHogConfig('test_token'); + config.logsConfig.beforeSend = [ + (record) { + if (record.body == 'outer') Posthog().captureLog(body: 'inner'); + return record; + }, + ]; + await setupWith(config); + + await Posthog().captureLog(body: 'outer'); + + expect(fake.capturedLogs.map((l) => l.body), ['inner', 'outer']); + }); + test('hook returning null drops the record', () async { final config = PostHogConfig('test_token'); config.logsConfig.beforeSend = [(record) => null]; diff --git a/posthog_flutter/test/snapshots/event_channel_shapes.json b/posthog_flutter/test/snapshots/event_channel_shapes.json index 2091d2e2..cac7582e 100644 --- a/posthog_flutter/test/snapshots/event_channel_shapes.json +++ b/posthog_flutter/test/snapshots/event_channel_shapes.json @@ -1,19 +1,39 @@ [ { - "method": "screen", + "method": "buildEvent", "arguments": { - "screenName": "Checkout", + "eventName": "$screen", "properties": { "cart_size": 3, "route": { "source": "email" }, + "$screen_name": "Checkout" + }, + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$screen", + "properties": { + "cart_size": 3, + "route": { + "source": "email" + }, + "$screen_name": "Checkout", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { - "method": "capture", + "method": "buildEvent", "arguments": { "eventName": "order completed", "properties": { @@ -26,8 +46,7 @@ } ], "placed_at": "2024-03-01 12:30:00.000Z", - "$screen_name": "Checkout", - "snapshot_before_send": "event" + "$screen_name": "Checkout" }, "userProperties": { "plan": "pro", @@ -37,7 +56,41 @@ "userPropertiesSetOnce": { "first_checkout_at": "2024-03-01", "signup_source": "invite" - } + }, + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "order completed", + "properties": { + "order_id": "ord_123", + "total": 42.5, + "items": [ + { + "sku": "sku_1", + "quantity": 2 + } + ], + "placed_at": "2024-03-01 12:30:00.000Z", + "$screen_name": "Checkout", + "snapshot_before_send": "event", + "$set": { + "plan": "pro", + "legacy_only": true, + "email_verified": true + }, + "$set_once": { + "first_checkout_at": "2024-03-01", + "signup_source": "invite" + } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { diff --git a/posthog_flutter/test/snapshots/special_event_channel_shapes.json b/posthog_flutter/test/snapshots/special_event_channel_shapes.json index 42be31cb..e695058e 100644 --- a/posthog_flutter/test/snapshots/special_event_channel_shapes.json +++ b/posthog_flutter/test/snapshots/special_event_channel_shapes.json @@ -15,9 +15,59 @@ } }, { - "method": "captureException", + "method": "buildEvent", "arguments": { + "eventName": "$exception", + "properties": { + "$exception_level": "error", + "$exception_list": [ + { + "type": "StateError", + "mechanism": { + "handled": true, + "synthetic": false, + "type": "generic" + }, + "value": "Bad state: checkout failed", + "stacktrace": { + "frames": [ + { + "platform": "dart", + "abs_path": "package:snapshot_app/main.dart", + "in_app": true, + "package": "snapshot_app", + "function": "main", + "filename": "main.dart", + "lineno": 10, + "colno": 3 + }, + { + "platform": "dart", + "abs_path": "package:snapshot_app/checkout.dart", + "in_app": true, + "package": "snapshot_app", + "function": "CheckoutService.submit", + "filename": "checkout.dart", + "lineno": 42, + "colno": 7 + } + ], + "type": "raw" + }, + "thread_id": "" + } + ], + "order_id": "ord_123", + "attempted_at": "2024-03-01 12:30:00.000Z" + }, "timestamp": "", + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$exception", "properties": { "$exception_level": "error", "$exception_list": [ @@ -60,13 +110,67 @@ "order_id": "ord_123", "attempted_at": "2024-03-01 12:30:00.000Z", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { - "method": "captureException", + "method": "buildEvent", "arguments": { + "eventName": "$exception", + "properties": { + "$exception_level": "error", + "$exception_list": [ + { + "type": "ArgumentError", + "mechanism": { + "handled": false, + "synthetic": false, + "type": "runZonedGuarded" + }, + "value": "Invalid argument(s): zoned checkout failure", + "stacktrace": { + "frames": [ + { + "platform": "dart", + "abs_path": "package:snapshot_app/main.dart", + "in_app": true, + "package": "snapshot_app", + "function": "main", + "filename": "main.dart", + "lineno": 12, + "colno": 3 + }, + { + "platform": "dart", + "abs_path": "package:snapshot_app/zone.dart", + "in_app": true, + "package": "snapshot_app", + "function": "CheckoutZone.run", + "filename": "zone.dart", + "lineno": 21, + "colno": 5 + } + ], + "type": "raw" + }, + "thread_id": "" + } + ], + "zone": "checkout" + }, "timestamp": "", + "ai": false + } + }, + { + "method": "sendBuiltEvent", + "arguments": { + "event": "$exception", "properties": { "$exception_level": "error", "$exception_list": [ @@ -108,7 +212,12 @@ ], "zone": "checkout", "snapshot_before_send": "event" - } + }, + "distinctId": "snapshot-user", + "timestamp": 1709296200000, + "options": {}, + "uuid": "snapshot-uuid", + "ai": false } }, { diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index ba633255..b1bc73cc 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -12,6 +12,9 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); final captures = >[]; + late String distinctId; + late bool optedOut; + late String userState; setUp(() { captures.clear(); @@ -22,9 +25,21 @@ void main() { captures.add({ 'event': event.toDart, 'properties': properties?.dartify(), + 'options': options?.dartify(), }); }).toJS, ); + distinctId = 'first-user'; + fake.setProperty('get_distinct_id'.toJS, (() => distinctId.toJS).toJS); + optedOut = false; + userState = 'anonymous'; + fake.setProperty( + 'get_property'.toJS, + ((JSString name) => name.toDart == r'$user_state' ? userState.toJS : null) + .toJS, + ); + fake.setProperty( + 'has_opted_out_capturing'.toJS, (() => optedOut.toJS).toJS); fake.setProperty( 'captureException'.toJS, ((JSAny? error, JSAny? properties) { @@ -37,6 +52,172 @@ void main() { globalContext.setProperty('posthog'.toJS, fake); }); + group('a hook that changes the user', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'checkout'), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + sends.forEach((name, send) { + test('keeps $name on the earlier user', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await send(web); + + final properties = captures.single['properties'] as Map; + expect(properties['distinct_id'], 'first-user'); + }); + }); + + test('does not bring back the user who opted out', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + optedOut = true; + distinctId = r'$posthog_cookieless'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('does not send the cookieless id after opting in', () async { + distinctId = r'$posthog_cookieless'; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('leaves the user alone when the hook does not change it', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [(e) => e])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + }); + + group('a hook that changes the user drops user properties', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture( + eventName: 'checkout', + userProperties: {'email': 'a@example.com'}, + userPropertiesSetOnce: {'first': 'yes'}, + ), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + PostHogConfig hooked(void Function() changeUser) => + PostHogConfig('test_token', beforeSend: [ + (event) { + changeUser(); + return event + ..userProperties = {'email': 'a@example.com'} + ..userPropertiesSetOnce = {'first': 'yes'}; + }, + ]); + + Map sentPersonProperties() { + final capture = captures.single; + final options = capture['options'] as Map? ?? const {}; + final properties = capture['properties'] as Map? ?? const {}; + return { + for (final key in [r'$set', r'$set_once']) + if (options[key] != null) key: options[key], + for (final key in [r'$set', r'$set_once']) + if (properties[key] != null) key: properties[key], + }; + } + + sends.forEach((name, send) { + test('on $name after reset() of an identified user', () async { + userState = 'identified'; + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'next-user'; + userState = 'anonymous'; + })); + + await send(web); + + expect(sentPersonProperties(), isEmpty); + expect((captures.single['properties'] as Map)['distinct_id'], + 'first-user'); + }); + + test('on $name not after identify() of an anonymous user', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'user-1'; + userState = 'identified'; + })); + + await send(web); + + expect(sentPersonProperties(), { + r'$set': {'email': 'a@example.com'}, + r'$set_once': {'first': 'yes'}, + }); + }); + }); + }); + + group('a hook that sets user properties without renaming', () { + PostHogConfig hooked() => PostHogConfig('test_token', beforeSend: [ + (event) { + event.userProperties = {'plan': 'pro'}; + event.userPropertiesSetOnce = {'first': 'yes'}; + return event; + }, + ]); + + test('keeps them on a screen', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.screen(screenName: 'Cart'); + + expect(captures.single['event'], r'$screen'); + expect(captures.single['options'], { + r'$set': {'plan': 'pro'}, + r'$set_once': {'first': 'yes'}, + }); + }); + + test('keeps them on an exception', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.captureException(error: StateError('boom')); + + final properties = captures.single['properties'] as Map; + expect(properties[r'$set'], {'plan': 'pro'}); + expect(properties[r'$set_once'], {'first': 'yes'}); + }); + }); + test('feature events carry the screen name beforeSend accepted', () async { final web = PosthogFlutterWeb(); await web.setup(PostHogConfig('test_token', beforeSend: [ @@ -113,6 +294,148 @@ void main() { expect(calls, ['getFeatureFlagResult', r'$feature_view', 'reset']); }); + for (final hooked in [false, true]) { + test( + 'feature events read the flag and reach posthog-js before a reset made ' + 'right after them (${hooked ? 'with' : 'without'} beforeSend)', + () async { + final calls = []; + var variant = 'for-the-old-user'; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, JSAny? properties, [JSAny? options]) { + final flagged = properties?.dartify() as Map?; + calls.add('${event.toDart}:${flagged?['feature_flag_variant']}'); + }).toJS, + ); + fake.setProperty( + 'getFeatureFlagResult'.toJS, + ((JSString key, [JSAny? options]) => { + 'key': key.toDart, + 'enabled': true, + 'variant': variant, + }.jsify()).toJS, + ); + fake.setProperty( + 'reset'.toJS, + (([JSAny? a]) { + calls.add('reset'); + variant = 'for-the-new-user'; + }).toJS, + ); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', + beforeSend: [if (hooked) (event) => event])); + + final sent = [ + web.captureFeatureView(flag: 'checkout'), + web.captureFeatureInteraction(flag: 'checkout'), + ]; + await web.reset(); + await Future.wait(sent); + + expect(calls, [ + r'$feature_view:for-the-old-user', + r'$feature_interaction:for-the-old-user', + 'reset', + ]); + }); + } + + group('a hook that renames an event', () { + final renames = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'original'), + 'screen': (web) => web.screen(screenName: 'Checkout'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + renames.forEach((name, send) { + test('$name runs the hook once and keeps its user properties', () async { + var runs = 0; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + runs++; + event.event = 'renamed'; + event.userProperties = {'source': 'hook'}; + return event; + }, + ])); + + await send(web); + + expect(runs, 1); + expect(captures.single['event'], 'renamed'); + final options = captures.single['options'] as Map; + expect(options[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('a hook that calls the SDK', () { + test('can capture another event without running forever', () async { + final web = PosthogFlutterWeb(); + final seen = []; + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + seen.add(event.event); + if (event.event == 'outer') web.capture(eventName: 'inner'); + return event; + }, + ])); + + await web.capture(eventName: 'outer'); + + expect(seen, ['outer', 'inner']); + expect(captures.map((c) => c['event']), ['inner', 'outer']); + }); + + test('an unawaited getter inside the hook does not delay the event', + () async { + final calls = []; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, [JSAny? a, JSAny? b]) => calls.add(event.toDart)) + .toJS, + ); + fake.setProperty('reset'.toJS, (([JSAny? a]) => calls.add('reset')).toJS); + fake.setProperty('has_opted_out_capturing'.toJS, (() => false.toJS).toJS); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + web.isOptOut(); + return event; + }, + ])); + + final sent = web.capture(eventName: 'checkout'); + await web.reset(); + await sent; + + expect(calls, ['checkout', 'reset']); + }); + }); + + test('a change made after the hook returned is not sent', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }, + ])); + + await web.capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + expect((captures.single['properties'] as Map).containsKey('late'), isFalse); + }); + test('beforeSend null drops capture on web', () async { final web = PosthogFlutterWeb(); await web.setup( diff --git a/sdk_compliance_adapter/lib/adapter_server.dart b/sdk_compliance_adapter/lib/adapter_server.dart index 8e6f0c3f..986c272d 100644 --- a/sdk_compliance_adapter/lib/adapter_server.dart +++ b/sdk_compliance_adapter/lib/adapter_server.dart @@ -312,6 +312,7 @@ class _CaptureClient extends DesktopPostHog { required Map properties, Map? options, String? timestamp, + String? uuid, }) { final queued = super.captureStateless( distinctId, @@ -319,6 +320,7 @@ class _CaptureClient extends DesktopPostHog { properties: properties, options: options, timestamp: timestamp, + uuid: uuid, ); onCaptured?.call(); return queued; @@ -331,16 +333,18 @@ class _CaptureClient extends DesktopPostHog { required Map properties, Map? options, String? timestamp, + String? uuid, }) async { - final uuid = await super.captureAiStateless( + final captured = await super.captureAiStateless( distinctId, event, properties: properties, options: options, timestamp: timestamp, + uuid: uuid, ); - if (uuid != null) onCaptured?.call(); - return uuid; + if (captured != null) onCaptured?.call(); + return captured; } void _actAs(String distinctId) { @@ -362,6 +366,9 @@ class _CaptureClient extends DesktopPostHog { properties: prepared.properties, options: prepared.options, timestamp: timestamp, + uuid: prepared.uuid, + distinctId: prepared.distinctId, + requestsPersonProcessing: prepared.requestsPersonProcessing, ); }