From bfc6625f5c3b5d0900af40cde651cb5277e05962 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Thu, 29 Oct 2026 16:59:13 -0400 Subject: [PATCH 01/13] feat!: make beforeSend callbacks synchronous Event and log beforeSend callbacks no longer return FutureOr, matching the native SDKs and the before-send-hook spec. The event is handed to the SDK in the same call, so calls made right after an un-awaited capture can no longer reach the SDK first, on every platform including Windows and Linux. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-sync-before-send.md | 5 + api/posthog_flutter.api.json | 10 +- posthog_flutter/lib/posthog_flutter_web.dart | 8 +- posthog_flutter/lib/src/posthog.dart | 3 +- posthog_flutter/lib/src/posthog_config.dart | 35 +- .../lib/src/posthog_flutter_desktop.dart | 52 +-- .../lib/src/posthog_flutter_io.dart | 8 +- .../lib/src/utils/before_send.dart | 28 +- .../test/posthog_flutter_desktop_test.dart | 309 ++---------------- .../test/posthog_flutter_io_test.dart | 239 ++------------ posthog_flutter/test/posthog_logs_test.dart | 16 - .../test/web_before_send_test.dart | 32 ++ 12 files changed, 124 insertions(+), 621 deletions(-) create mode 100644 .changeset/v6-sync-before-send.md diff --git a/.changeset/v6-sync-before-send.md b/.changeset/v6-sync-before-send.md new file mode 100644 index 00000000..3244ad8c --- /dev/null +++ b/.changeset/v6-sync-before-send.md @@ -0,0 +1,5 @@ +--- +"posthog_flutter": major +--- + +- **Breaking:** `beforeSend` and `logsConfig.beforeSend` callbacks are now synchronous (`PostHogEvent? Function(PostHogEvent)` and `PostHogLogRecord? Function(PostHogLogRecord)`), as in the native SDKs. An event is now handed to the SDK in the same call, so a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` no longer applies to it first, and Windows and Linux no longer drop it. Callbacks that used `await` must load what they need ahead of time diff --git a/api/posthog_flutter.api.json b/api/posthog_flutter.api.json index 1499e991..bf420f96 100644 --- a/api/posthog_flutter.api.json +++ b/api/posthog_flutter.api.json @@ -2310,7 +2310,7 @@ "isRequired": false, "name": "beforeSend", "relativePath": "lib/src/posthog_config.dart", - "typeName": "List Function(PostHogEvent)>?" + "typeName": "List?" } ], "relativePath": "lib/src/posthog_config.dart", @@ -2626,7 +2626,7 @@ "isWriteable": true, "name": "beforeSend", "relativePath": "lib/src/posthog_config.dart", - "typeName": "List Function(PostHogEvent)>" + "typeName": "List" } ], "isDeprecated": false, @@ -3440,7 +3440,7 @@ "isWriteable": true, "name": "beforeSend", "relativePath": "lib/src/posthog_config.dart", - "typeName": "List Function(PostHogLogRecord)>" + "typeName": "List" } ], "isDeprecated": false, @@ -6068,7 +6068,7 @@ ], "typeAliasDeclarations": [ { - "aliasedTypeName": "FutureOr Function(PostHogEvent)", + "aliasedTypeName": "PostHogEvent? Function(PostHogEvent)", "entryPoints": [ "posthog_flutter.dart" ], @@ -6078,7 +6078,7 @@ "relativePath": "lib/src/posthog_config.dart" }, { - "aliasedTypeName": "FutureOr Function(PostHogLogRecord)", + "aliasedTypeName": "PostHogLogRecord? Function(PostHogLogRecord)", "entryPoints": [ "posthog_flutter.dart" ], diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 2e783f2b..0aacc9dd 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -39,7 +39,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { // its final name, until close(). String? _currentScreen; - Future _runBeforeSend( + PostHogEvent? _runBeforeSend( String eventName, Map? properties, { Map? userProperties, @@ -182,7 +182,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userProperties, Map? userPropertiesSetOnce, }) async { - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( eventName, properties, userProperties: userProperties, @@ -263,7 +263,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { PostHogPropertyName.screenName: screenName, }; - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( PostHogEventName.screen, propsWithScreenName, ); @@ -557,7 +557,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { inAppByDefault: _config?.errorTrackingConfig.inAppByDefault ?? true, ); - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( PostHogEventName.exception, exceptionData.cast(), ); diff --git a/posthog_flutter/lib/src/posthog.dart b/posthog_flutter/lib/src/posthog.dart index 495f1927..36c2f87d 100644 --- a/posthog_flutter/lib/src/posthog.dart +++ b/posthog_flutter/lib/src/posthog.dart @@ -13,7 +13,6 @@ import 'posthog_flutter_platform_interface.dart'; import 'posthog_internal_events.dart'; import 'posthog_observer.dart'; import 'replay/mask/posthog_mask_controller.dart'; -import 'utils/before_send.dart'; /// Entry point for the PostHog Flutter SDK. /// @@ -320,7 +319,7 @@ class Posthog { _config?.logsConfig.beforeSend ?? const []; for (final callback in callbacks) { try { - final result = await runBeforeSend(callback, record); + final result = callback(record); if (result == null) { debugPrint('[PostHog] Log dropped by beforeSend'); return; diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index fcbd806f..dc846b0d 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -14,9 +14,9 @@ import 'replay/mask/posthog_text_mask.dart'; /// that are about to be captured. Return a possibly modified event to send it, /// or return `null` to drop it. /// -/// Callbacks can be synchronous or asynchronous (returning -/// `FutureOr`). -typedef BeforeSendCallback = FutureOr Function( +/// Callbacks are synchronous, as in the native SDKs, so the event is sent +/// with the user and properties it was captured under. +typedef BeforeSendCallback = PostHogEvent? Function( PostHogEvent event, ); @@ -27,9 +27,8 @@ typedef BeforeSendCallback = FutureOr Function( /// attributes that are about to be captured. Return a possibly modified record /// to send it, or return `null` to drop it. /// -/// Callbacks can be synchronous or asynchronous (returning -/// `FutureOr`). -typedef BeforeSendLogCallback = FutureOr Function( +/// Callbacks are synchronous, as in the native SDKs. +typedef BeforeSendLogCallback = PostHogLogRecord? Function( PostHogLogRecord record, ); @@ -361,23 +360,6 @@ class PostHogConfig { /// ]; /// ``` /// - /// **Example (async callback):** - /// ```dart - /// config.beforeSend = [ - /// (event) async { - /// // Perform async operations - /// final shouldSend = await checkIfEventAllowed(event.event); - /// if (!shouldSend) { - /// return null; // Drop the event - /// } - /// // Enrich event with async data - /// final extraData = await fetchExtraContext(); - /// event.properties = {...?event.properties, ...extraData}; - /// return event; - /// }, - /// ]; - /// ``` - /// /// **Limitations:** /// - These callbacks do NOT intercept native-initiated events such as: /// - Session replay events (`$snapshot`) when `config.sessionReplay` is @@ -393,8 +375,8 @@ class PostHogConfig { /// stage. /// /// **Note:** - /// - Callbacks can be synchronous or asynchronous (via - /// `FutureOr`) + /// - Callbacks are synchronous. Load anything they need (such as remote + /// config) ahead of time. /// - 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 @@ -574,8 +556,7 @@ class PostHogLogsConfig { /// native SDKs' own `beforeSend`. Dart callbacks cannot cross the platform /// channel, and running it here gives identical behavior everywhere /// (including web). This mirrors the event [PostHogConfig.beforeSend]. - /// - Callbacks can be synchronous or asynchronous (via - /// `FutureOr`). + /// - Callbacks are synchronous. /// - A callback that throws is logged, and the record is dropped. /// - The W3C trace fields (`traceId`, `spanId`, `traceFlags`) are **not** /// part of [PostHogLogRecord] and are not visible here. They pass straight diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index cf883e54..508a97db 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -253,14 +253,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final distinctId = client.getDistinctId(); final exceptionSteps = _exceptionSteps; - final hooked = _runBeforeSend( + final processed = _runBeforeSend( eventName, properties, userProperties: userProperties, userPropertiesSetOnce: userPropertiesSetOnce, ); - final processed = - hooked is Future ? await hooked : hooked; if (processed == null) { printIfDebug('[PostHog] Event dropped by beforeSend: $eventName'); return; @@ -285,15 +283,13 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final distinctId = client.getDistinctId(); final exceptionSteps = _exceptionSteps; - final hooked = _runBeforeSend( + final processed = _runBeforeSend( PostHogEventName.screen, { ...?properties, PostHogPropertyName.screenName: screenName, }, ); - final processed = - hooked is Future ? await hooked : hooked; if (processed == null) { printIfDebug( '[PostHog] Screen event dropped by beforeSend: $screenName'); @@ -551,12 +547,10 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { inAppByDefault: _config?.errorTrackingConfig.inAppByDefault ?? true, ); - final hooked = _runBeforeSend( + final processed = _runBeforeSend( PostHogEventName.exception, exceptionProps.cast(), ); - final processed = - hooked is Future ? await hooked : hooked; if (processed == null) { printIfDebug( '[PostHog] Exception event dropped by beforeSend: ${error.runtimeType}', @@ -651,39 +645,21 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// /// Returns the possibly modified event, or null if any callback drops it /// or throws. - /// - /// Without callbacks the event is returned synchronously and the caller - /// must not await it: an identify(), reset() or opt-out made right after - /// an unawaited capture would otherwise run first, and the event would be - /// dropped as belonging to another user. - FutureOr _runBeforeSend( + PostHogEvent? _runBeforeSend( String eventName, Map? properties, { Map? userProperties, Map? userPropertiesSetOnce, - }) { - final event = PostHogEvent( - event: eventName, - properties: properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, - ); - final callbacks = _config?.beforeSend ?? const []; - return callbacks.isEmpty ? event : _applyCallbacks(callbacks, event); - } - - /// Applies [callbacks], then waits for a setup() in progress: an event - /// whose callbacks finish while the previous client is still closing - /// goes to the next client rather than finding none. - Future _applyCallbacks( - List callbacks, - PostHogEvent event, - ) async { - final processed = await applyBeforeSend(callbacks, event); - final setup = _setupFuture; - if (_client == null && setup != null) await setup; - return processed; - } + }) => + applyBeforeSend( + _config?.beforeSend ?? const [], + PostHogEvent( + event: eventName, + properties: properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + ), + ); void _captureProcessed( DesktopPostHog client, diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index c69deb2c..08ec5cd8 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -45,7 +45,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { /// Applies the beforeSend callbacks to an event in order. /// Returns the possibly modified event, or null if any callback drops it. - Future _runBeforeSend( + PostHogEvent? _runBeforeSend( String eventName, Map? properties, { Map? userProperties, @@ -300,7 +300,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } // Apply beforeSend callback - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( eventName, properties, userProperties: userProperties, @@ -365,7 +365,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { }; // Apply beforeSend callback - screen events are captured as $screen - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( PostHogEventName.screen, propsWithScreenName, ); @@ -818,7 +818,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ); // Apply beforeSend callback - exception events are captured as $exception - final processedEvent = await _runBeforeSend( + final processedEvent = _runBeforeSend( PostHogEventName.exception, exceptionProps.cast(), ); diff --git a/posthog_flutter/lib/src/utils/before_send.dart b/posthog_flutter/lib/src/utils/before_send.dart index 3554ded9..3344d9bb 100644 --- a/posthog_flutter/lib/src/utils/before_send.dart +++ b/posthog_flutter/lib/src/utils/before_send.dart @@ -1,37 +1,17 @@ -import 'dart:async'; - import '../posthog_event.dart'; import '../util/logging.dart'; -/// Runs a single beforeSend [callback] against [record], awaiting an async -/// result. Returns the (possibly modified) record, or `null` to drop it. -/// -/// A throw propagates. [applyBeforeSend] is the event policy: it drops the -/// event. Log capture drops the record in its own loop. -Future runBeforeSend( - FutureOr Function(T) callback, - T record, -) async { - final result = callback(record); - if (result is Future) { - return await result; - } - return result; -} - /// Runs [callbacks] in order against [event]. /// /// A null return drops the event and skips the rest of the list. A throw drops /// the event too. -Future applyBeforeSend( - List Function(PostHogEvent)> callbacks, +PostHogEvent? applyBeforeSend( + List callbacks, PostHogEvent event, -) async { - if (callbacks.isEmpty) return event; - +) { for (final callback in callbacks) { try { - final result = await runBeforeSend(callback, event); + final result = callback(event); if (result == null) return null; event = result; } catch (e) { diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 36517dd8..b380930d 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -234,22 +234,18 @@ void main() { test('does not admit a capture made while opted out', () async { final server = await LocalPostHogServer.start(); final callbackEvents = []; - final releaseHook = Completer(); final config = configFor(server) ..beforeSend = [ - (event) async { + (event) { callbackEvents.add(event.event); - if (event.event == 'blocked capture') await releaseHook.future; return event; }, ]; final platform = await setUpPlatform(config); await platform.optOut(); - final blocked = platform.capture(eventName: 'blocked capture'); + await platform.capture(eventName: 'blocked capture'); await platform.optIn(); - releaseHook.complete(); - await blocked; await platform.capture(eventName: 'sentinel event'); await server.waitForEvent('sentinel event'); @@ -356,36 +352,6 @@ void main() { reason: 'the screen did not become the current one'); }); - test('does not remember a screen when consent changes during its hook', - () async { - final server = await LocalPostHogServer.start(); - final hookStarted = Completer(); - final releaseHook = Completer(); - final config = configFor(server) - ..beforeSend = [ - (event) async { - if (event.event == r'$screen') { - hookStarted.complete(); - await releaseHook.future; - } - return event; - }, - ]; - final platform = await setUpPlatform(config); - - final screen = platform.screen(screenName: 'Blocked'); - await hookStarted.future; - await platform.optOut(); - releaseHook.complete(); - await screen; - await platform.optIn(); - await platform.capture(eventName: 'sentinel event'); - - final event = await server.waitForEvent('sentinel event'); - expect(server.eventNames, ['sentinel event']); - expect(_propertiesOf(event), isNot(contains(r'$screen_name'))); - }); - test('runs the hook once when it renames a screen event', () async { final server = await LocalPostHogServer.start(); var callbackCount = 0; @@ -664,22 +630,18 @@ void main() { test('does not admit an exception made while opted out', () async { final server = await LocalPostHogServer.start(); final callbackEvents = []; - final releaseHook = Completer(); final config = configFor(server) ..beforeSend = [ - (event) async { + (event) { callbackEvents.add(event.event); - if (event.event == r'$exception') await releaseHook.future; return event; }, ]; final platform = await setUpPlatform(config); await platform.optOut(); - final blocked = platform.captureException(error: StateError('blocked')); + await platform.captureException(error: StateError('blocked')); await platform.optIn(); - releaseHook.complete(); - await blocked; await platform.capture(eventName: 'sentinel event'); await server.waitForEvent('sentinel event'); @@ -773,69 +735,6 @@ void main() { expect(stepMessagesOf(sentinel), isNull); }); - for (final call in ['capture', 'screen', 'captureException']) { - for (final enabled in [true, false]) { - test( - '$call keeps its original exception steps across close/setup ' - '(initially enabled: $enabled)', () async { - final server = await LocalPostHogServer.start(); - final entered = Completer(); - final release = Completer(); - final config = configFor(server) - ..errorTrackingConfig.exceptionSteps.enabled = enabled - ..beforeSend = [ - (event) async { - entered.complete(); - await release.future; - event.event = r'$exception'; - return event; - }, - ]; - final platform = await setUpPlatform(config); - await platform.addExceptionStep('original client'); - - final pending = switch (call) { - 'capture' => platform.capture(eventName: 'custom error'), - 'screen' => platform.screen(screenName: 'Error'), - _ => platform.captureException(error: StateError('pending')), - }; - await entered.future; - await platform.close(); - await platform.setup(configFor(server)); - await platform.addExceptionStep('replacement client'); - release.complete(); - await pending; - - final event = await server.waitForEvent(r'$exception'); - expect(stepMessagesOf(event), enabled ? ['original client'] : null); - }); - } - } - - test('includes steps recorded while the same client awaits beforeSend', - () async { - final server = await LocalPostHogServer.start(); - final entered = Completer(); - final release = Completer(); - final platform = await setUpPlatform(configFor(server) - ..beforeSend = [ - (event) async { - entered.complete(); - await release.future; - return event; - }, - ]); - await platform.addExceptionStep('before capture'); - final pending = platform.captureException(error: StateError('pending')); - await entered.future; - await platform.addExceptionStep('during beforeSend'); - release.complete(); - await pending; - - expect(stepMessagesOf(await server.waitForEvent(r'$exception')), - ['before capture', 'during beforeSend']); - }); - test('normalize non-finite step and event properties identically', () async { final server = await LocalPostHogServer.start(); @@ -1350,44 +1249,6 @@ void main() { await Future.wait([firstClose, repeatedClose]); }); - test( - 'an event whose callbacks finish while close sends the queue reaches ' - 'the next client', () async { - final server = await LocalPostHogServer.start(); - final releaseHook = Completer(); - final config = configFor(server) - ..flushAt = 20 - ..beforeSend = [ - (event) async { - if (event.event == 'slow event') await releaseHook.future; - return event; - }, - ]; - final platform = await setUpPlatform(config); - await platform.capture(eventName: 'queued event'); - final batch = Completer(); - final batchReceived = Completer(); - server.respond = (_) { - if (batchReceived.isCompleted) { - return const PostHogResponse(HttpStatus.ok); - } - batchReceived.complete(); - return batch.future; - }; - - final slowCapture = platform.capture(eventName: 'slow event'); - final close = platform.close(); - final setup = platform.setup(config); - await batchReceived.future; - releaseHook.complete(); - await Future.delayed(const Duration(milliseconds: 50)); - batch.complete(const PostHogResponse(HttpStatus.ok)); - await Future.wait([slowCapture, close, setup]); - await platform.flush(); - - expect(server.eventNames, ['queued event', 'slow event']); - }); - test('close sends the queued events', () async { final server = await LocalPostHogServer.start(); final platform = await setUpPlatform(configFor(server)..flushAt = 20); @@ -1424,30 +1285,6 @@ void main() { ]); }); - test('an event whose callbacks finish after close reaches the next client', - () async { - final server = await LocalPostHogServer.start(); - final release = Completer(); - final config = configFor(server) - ..beforeSend = [ - (event) async { - if (event.event == 'slow event') await release.future; - return event; - }, - ]; - final platform = await setUpPlatform(config); - - final slowCapture = platform.capture(eventName: 'slow event'); - await platform.close(); - await platform.setup(config); - release.complete(); - await slowCapture; - await platform.capture(eventName: 'sentinel event'); - - await server.waitForEvent('sentinel event'); - expect(server.eventNames, ['slow event', 'sentinel event']); - }); - final pendingCalls = (); - final releaseHook = Completer(); - final config = configFor(server) - ..beforeSend = [ - (event) async { - hookStarted.complete(); - await releaseHook.future; - return event; - }, - ]; - final platform = await setUpPlatform(config); - - final pending = entry.value.call(platform); - await hookStarted.future; - await platform.close(); - await platform.setup( - configFor(server, projectToken: 'next_project'), - ); - releaseHook.complete(); - await pending; - await platform.capture(eventName: 'sentinel event'); - - await server.waitForEvent('sentinel event'); - expect(server.eventNames, ['sentinel event']); - }); - } - - for (final entry in pendingCalls.entries) { - test('${entry.key} pending in a hook does not cross host scope', - () async { - final firstServer = await LocalPostHogServer.start(); - final nextServer = await LocalPostHogServer.start(); - final hookStarted = Completer(); - final releaseHook = Completer(); - final config = configFor(firstServer) - ..beforeSend = [ - (event) async { - hookStarted.complete(); - await releaseHook.future; - return event; - }, - ]; - final platform = await setUpPlatform(config); - - final pending = entry.value.call(platform); - await hookStarted.future; - await platform.close(); - await platform.setup(configFor(nextServer)); - releaseHook.complete(); - await pending; - await platform.capture(eventName: 'sentinel event'); - - await nextServer.waitForEvent('sentinel event'); - expect(firstServer.eventNames, isNot(contains(entry.value.eventName))); - expect(nextServer.eventNames, ['sentinel event']); - }); - } - final identityChanges = Function(PosthogFlutterDesktop)>{ 'identify': (platform) => platform.identify(userId: 'next-user'), @@ -1538,62 +1313,26 @@ void main() { for (final identityChange in identityChanges.entries) { for (final entry in pendingCalls.entries) { - test( - '${entry.key} without hooks is sent before an unawaited ' - '${identityChange.key}', () async { - final server = await LocalPostHogServer.start(); - final platform = await setUpPlatform(configFor(server)); - final distinctId = await platform.getDistinctId(); - - final call = entry.value.call(platform); - final change = identityChange.value(platform); - await Future.wait([call, change]); - await platform.capture(eventName: 'sentinel event'); - - await server.waitForEvent('sentinel event'); - final event = server.events - .singleWhere((event) => event['event'] == entry.value.eventName); - expect(event['distinct_id'], distinctId); - }); - } - } - - for (final identityChange in ['identify', 'reset']) { - for (final entry in pendingCalls.entries) { - test('${entry.key} pending in a hook does not cross $identityChange', - () async { - final server = await LocalPostHogServer.start(); - final hookStarted = Completer(); - final releaseHook = Completer(); - final config = configFor(server) - ..beforeSend = [ - (event) async { - if (event.event == entry.value.eventName) { - hookStarted.complete(); - await releaseHook.future; - } - return event; - }, - ]; - final platform = await setUpPlatform(config); - final initialDistinctId = await platform.getDistinctId(); - - final pending = entry.value.call(platform); - await hookStarted.future; - if (identityChange == 'identify') { - await platform.identify(userId: 'identified_user'); - expect(await platform.getDistinctId(), 'identified_user'); - } else { - await platform.reset(); - expect(await platform.getDistinctId(), isNot(initialDistinctId)); - } - releaseHook.complete(); - await pending; - await platform.capture(eventName: 'sentinel event'); - - await server.waitForEvent('sentinel event'); - expect(server.eventNames, isNot(contains(entry.value.eventName))); - }); + for (final hooked in [false, true]) { + test( + '${entry.key} ${hooked ? 'with' : 'without'} hooks is sent before ' + 'an unawaited ${identityChange.key}', () async { + final server = await LocalPostHogServer.start(); + final platform = await setUpPlatform( + configFor(server)..beforeSend = [if (hooked) (event) => event]); + final distinctId = await platform.getDistinctId(); + + final call = entry.value.call(platform); + final change = identityChange.value(platform); + await Future.wait([call, change]); + await platform.capture(eventName: 'sentinel event'); + + await server.waitForEvent('sentinel event'); + final event = server.events.singleWhere( + (event) => event['event'] == entry.value.eventName); + expect(event['distinct_id'], distinctId); + }); + } } } diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index 76d1f39c..c385aeaa 100644 --- a/posthog_flutter/test/posthog_flutter_io_test.dart +++ b/posthog_flutter/test/posthog_flutter_io_test.dart @@ -1,5 +1,3 @@ -import 'dart:async'; - import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:posthog_flutter/src/feature_flag_result.dart'; @@ -808,220 +806,6 @@ void main() { final args = Map.from(captureCall.arguments as Map); expect(args.containsKey('userProperties'), isFalse); }); - - test('async beforeSend can modify event', () async { - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - await Future.delayed(const Duration(milliseconds: 10)); - event.event = 'async_modified_event'; - return event; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - await posthogFlutterIO.capture(eventName: 'original_event'); - - final captureCall = log.firstWhere((c) => c.method == 'capture'); - final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'async_modified_event'); - }); - - test('async beforeSend can drop event by returning null', () async { - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - await Future.delayed(const Duration(milliseconds: 100)); - return null; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - await posthogFlutterIO.capture(eventName: 'dropped_event'); - - final captureCalls = log.where((c) => c.method == 'capture'); - expect(captureCalls, isEmpty); - }); - - test('mixed sync and async beforeSend callbacks work correctly', () async { - final callOrder = []; - - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) { - callOrder.add('sync1'); - event.event = '${event.event}_sync1'; - return event; - }, - (event) async { - await Future.delayed(const Duration(milliseconds: 100)); - callOrder.add('async1'); - event.event = '${event.event}_async1'; - return event; - }, - (event) { - callOrder.add('sync2'); - event.event = '${event.event}_sync2'; - return event; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - await posthogFlutterIO.capture(eventName: 'original'); - - final captureCall = log.firstWhere((c) => c.method == 'capture'); - final args = Map.from(captureCall.arguments as Map); - expect(args['eventName'], 'original_sync1_async1_sync2'); - expect(callOrder, ['sync1', 'async1', 'sync2']); - }); - - test('async beforeSend exception drops event without throwing', () async { - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - await Future.delayed(Duration.zero); - throw Exception('Async error'); - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - log.clear(); - - await expectLater( - posthogFlutterIO.capture( - eventName: 'test_event', - properties: {'key': 'value'}, - ), - completes, - ); - - expect(log, isEmpty); - }); - - test( - 'async beforeSend drops event and stops chain when returning null', - () async { - final callOrder = []; - - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - callOrder.add(1); - await Future.delayed(const Duration(milliseconds: 100)); - return null; // Drop event - }, - (event) { - callOrder.add(2); // Should not be called - return event; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - await posthogFlutterIO.capture(eventName: 'test_event'); - - final captureCalls = log.where((c) => c.method == 'capture'); - expect(captureCalls, isEmpty); - expect(callOrder, [1]); // Only first callback should have been called - }, - ); - - test( - 'multiple events with async beforeSend are captured in order when capture is awaited', - () async { - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - // Add delay only for second event - if (event.event == 'event_2') { - await Future.delayed(const Duration(milliseconds: 500)); - } - return event; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - await posthogFlutterIO.capture(eventName: 'event_1'); - await posthogFlutterIO.capture(eventName: 'event_2'); - await posthogFlutterIO.capture(eventName: 'event_3'); - - final captureCalls = log.where((c) => c.method == 'capture').toList(); - expect(captureCalls.length, 3); - - final event1Args = Map.from( - captureCalls[0].arguments as Map, - ); - final event2Args = Map.from( - captureCalls[1].arguments as Map, - ); - final event3Args = Map.from( - captureCalls[2].arguments as Map, - ); - - final eventOrder = [ - event1Args['eventName'], - event2Args['eventName'], - event3Args['eventName'], - ]; - expect(eventOrder, ['event_1', 'event_2', 'event_3']); - }, - ); - - test( - 'multiple events with async beforeSend are captured out of order when capture is NOT awaited', - () async { - final releaseFirst = Completer(); - testConfig = PostHogConfig( - 'test_project_token', - beforeSend: [ - (event) async { - if (event.event == 'event_1') { - await releaseFirst.future; - } - return event; - }, - ], - ); - await posthogFlutterIO.setup(testConfig); - - final first = posthogFlutterIO.capture(eventName: 'event_1'); - await posthogFlutterIO.capture(eventName: 'event_2'); - await posthogFlutterIO.capture(eventName: 'event_3'); - expect(log.where((c) => c.method == 'capture'), hasLength(2)); - releaseFirst.complete(); - await first; - - final captureCalls = log.where((c) => c.method == 'capture').toList(); - expect(captureCalls.length, 3); - - final event1Args = Map.from( - captureCalls[0].arguments as Map, - ); - final event2Args = Map.from( - captureCalls[1].arguments as Map, - ); - final event3Args = Map.from( - captureCalls[2].arguments as Map, - ); - - final eventOrder = [ - event1Args['eventName'], - event2Args['eventName'], - event3Args['eventName'], - ]; - expect(eventOrder, ['event_2', 'event_3', 'event_1']); - }, - ); }); group('PosthogFlutterIO captureLog', () { @@ -1106,6 +890,29 @@ void main() { }); }); + group('PosthogFlutterIO calls made right after an event', () { + for (final hooked in [false, true]) { + test( + 'reach native after the event ' + '(${hooked ? 'with' : 'without'} beforeSend)', () async { + await posthogFlutterIO.setup(PostHogConfig('test_project_token', + beforeSend: [if (hooked) (event) => event])); + log.clear(); + + final sent = [ + posthogFlutterIO.capture(eventName: 'checkout'), + posthogFlutterIO.screen(screenName: 'Cart'), + posthogFlutterIO.captureException(error: StateError('boom')), + ]; + await posthogFlutterIO.reset(); + await Future.wait(sent); + + expect(log.map((c) => c.method), + ['capture', 'screen', 'captureException', 'reset']); + }); + } + }); + group('PosthogFlutterIO addExceptionStep', () { test('sends message and normalized properties', () async { await posthogFlutterIO.addExceptionStep( diff --git a/posthog_flutter/test/posthog_logs_test.dart b/posthog_flutter/test/posthog_logs_test.dart index 624822a8..20c8e147 100644 --- a/posthog_flutter/test/posthog_logs_test.dart +++ b/posthog_flutter/test/posthog_logs_test.dart @@ -218,22 +218,6 @@ void main() { expect(fake.capturedLogs.single.body, 'x-1-2'); }); - - test('async hook is awaited', () async { - final config = PostHogConfig('test_token'); - config.logsConfig.beforeSend = [ - (record) async { - await Future.delayed(Duration.zero); - record.body = 'async'; - return record; - }, - ]; - await setupWith(config); - - await Posthog().captureLog(body: 'x'); - - expect(fake.capturedLogs.single.body, 'async'); - }); }); group('PostHogLogsConfig.toMap', () { diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index ad57000a..7eee0a6e 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -55,6 +55,38 @@ void main() { expect((captures.last['properties'] as Map)[r'$screen_name'], 'Basket'); }); + for (final hooked in [false, true]) { + test( + 'events reach posthog-js before a reset made right after them ' + '(${hooked ? 'with' : 'without'} beforeSend)', () 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( + 'captureException'.toJS, + (([JSAny? a, JSAny? b]) => calls.add('captureException')).toJS, + ); + fake.setProperty('reset'.toJS, (([JSAny? a]) => calls.add('reset')).toJS); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', + beforeSend: [if (hooked) (event) => event])); + + final sent = [ + web.capture(eventName: 'checkout'), + web.screen(screenName: 'Cart'), + web.captureException(error: StateError('boom')), + ]; + await web.reset(); + await Future.wait(sent); + + expect(calls, ['checkout', r'$screen', 'captureException', 'reset']); + }); + } + test('beforeSend null drops capture on web', () async { final web = PosthogFlutterWeb(); await web.setup( From 41ea6b0be468ce2445947ebf242ade1fe8f0b1d0 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 12:43:49 -0400 Subject: [PATCH 02/13] fix: keep the call queue on iOS, macOS and Android With #682 and beforeSend set, an event takes two native calls. Without the queue, an optOut(), close() or setup() made right after capture() reaches native between them and the event is lost. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-sync-before-send.md | 2 +- .../lib/src/posthog_flutter_io.dart | 191 ++++++++++-------- posthog_flutter/lib/src/utils/call_order.dart | 103 ++++++++++ posthog_flutter/test/call_order_test.dart | 136 +++++++++++++ 4 files changed, 349 insertions(+), 83 deletions(-) create mode 100644 posthog_flutter/lib/src/utils/call_order.dart create mode 100644 posthog_flutter/test/call_order_test.dart diff --git a/.changeset/v6-sync-before-send.md b/.changeset/v6-sync-before-send.md index 3244ad8c..344fd64f 100644 --- a/.changeset/v6-sync-before-send.md +++ b/.changeset/v6-sync-before-send.md @@ -2,4 +2,4 @@ "posthog_flutter": major --- -- **Breaking:** `beforeSend` and `logsConfig.beforeSend` callbacks are now synchronous (`PostHogEvent? Function(PostHogEvent)` and `PostHogLogRecord? Function(PostHogLogRecord)`), as in the native SDKs. An event is now handed to the SDK in the same call, so a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` no longer applies to it first, and Windows and Linux no longer drop it. Callbacks that used `await` must load what they need ahead of time +- **Breaking:** `beforeSend` and `logsConfig.beforeSend` callbacks are now synchronous (`PostHogEvent? Function(PostHogEvent)` and `PostHogLogRecord? Function(PostHogLogRecord)`), as in the native SDKs. A `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` no longer applies to the event first, and Windows and Linux no longer drop it. Callbacks that used `await` must load what they need ahead of time diff --git a/posthog_flutter/lib/src/posthog_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 08ec5cd8..ef6d1ddf 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -11,6 +11,7 @@ import 'surveys/models/posthog_display_survey.dart' as models; import 'surveys/models/survey_callbacks.dart'; import 'error_tracking/dart_exception_processor.dart'; import 'utils/before_send.dart'; +import 'utils/call_order.dart'; import 'utils/capture_utils.dart'; import 'utils/channel_serialization.dart'; import 'utils/flutter_version.dart'; @@ -43,6 +44,11 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { /// Stored beforeSend callbacks for dropping/modifying events List _beforeSendCallbacks = []; + final _order = CallOrder(); + + Future _invoke(String method, [Object? arguments]) => + _order.run(() => _methodChannel.invokeMethod(method, arguments)); + /// Applies the beforeSend callbacks to an event in order. /// Returns the possibly modified event, or null if any callback drops it. PostHogEvent? _runBeforeSend( @@ -135,7 +141,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { (survey) async { // onShown try { - await _methodChannel.invokeMethod('surveyAction', { + await _invoke('surveyAction', { 'type': 'shown', 'presentationId': survey.presentationId, }); @@ -146,7 +152,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { (survey, index, response) async { // onResponse try { - final result = await _methodChannel.invokeMethod('surveyAction', { + final result = await _invoke('surveyAction', { 'type': 'response', 'presentationId': survey.presentationId, 'index': index, @@ -169,7 +175,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { (survey) async { // onClose try { - await _methodChannel.invokeMethod('surveyAction', { + await _invoke('surveyAction', { 'type': 'closed', 'presentationId': survey.presentationId, }); @@ -206,7 +212,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { _beforeSendCallbacks = config.beforeSend; try { - await _methodChannel.invokeMethod('setup', { + await _invoke('setup', { ...config.toMap(), ...flutterVersionSetupArguments(), }); @@ -221,7 +227,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return; } try { - await _methodChannel.invokeMethod( + await _invoke( 'setCaptureNativeScreens', {'enabled': enabled}, ); @@ -248,7 +254,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ? PropertyNormalizer.normalize(userPropertiesSetOnce) : null; - await _methodChannel.invokeMethod('identify', { + await _invoke('identify', { 'userId': userId, if (normalizedUserProperties != null) 'userProperties': normalizedUserProperties, @@ -277,7 +283,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ? PropertyNormalizer.normalize(userPropertiesToSetOnce) : null; - await _methodChannel.invokeMethod('setPersonProperties', { + await _invoke('setPersonProperties', { if (normalizedUserPropertiesToSet != null) 'userPropertiesToSet': normalizedUserPropertiesToSet, if (normalizedUserPropertiesToSetOnce != null) @@ -299,14 +305,21 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { return; } - // Apply beforeSend callback - final processedEvent = _runBeforeSend( - eventName, - properties, - userProperties: userProperties, - userPropertiesSetOnce: userPropertiesSetOnce, + return _order.event( + () => _runBeforeSend( + eventName, + properties, + userProperties: userProperties, + userPropertiesSetOnce: userPropertiesSetOnce, + ), + (processedEvent) => _sendCapture(eventName, processedEvent), ); + } + Future _sendCapture( + String eventName, + PostHogEvent? processedEvent, + ) async { if (processedEvent == null) { printIfDebug('[PostHog] Event dropped by beforeSend: $eventName'); return; @@ -335,7 +348,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ? PropertyNormalizer.normalize(extractedUserPropertiesSetOnce) : null; - await _methodChannel.invokeMethod('capture', { + await _invoke('capture', { 'eventName': processedEvent.event, if (normalizedProperties != null) 'properties': normalizedProperties, if (normalizedUserProperties != null) @@ -365,10 +378,16 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { }; // Apply beforeSend callback - screen events are captured as $screen - final processedEvent = _runBeforeSend( - PostHogEventName.screen, - propsWithScreenName, + return _order.event( + () => _runBeforeSend(PostHogEventName.screen, propsWithScreenName), + (processedEvent) => _sendScreen(screenName, processedEvent), ); + } + + Future _sendScreen( + String screenName, + PostHogEvent? processedEvent, + ) async { if (processedEvent == null) { printIfDebug('[PostHog] Screen event dropped by beforeSend: $screenName'); return; @@ -397,7 +416,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ) : null; - await _methodChannel.invokeMethod('screen', { + await _invoke('screen', { 'screenName': finalScreenName, if (normalizedProperties != null) 'properties': normalizedProperties, }); @@ -425,7 +444,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { // Trace fields are camelCase here; the web handler remaps them to // snake_case for posthog-js. - await _methodChannel.invokeMethod('captureLog', { + await _invoke('captureLog', { 'body': body, 'level': level.name, if (normalizedAttributes != null) 'attributes': normalizedAttributes, @@ -446,7 +465,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('alias', {'alias': alias}); + await _invoke('alias', {'alias': alias}); } on PlatformException catch (exception) { printIfDebug('Exeption on alias: $exception'); } @@ -476,7 +495,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod(method, { + await _invoke(method, { 'flag': flag, if (flagVariant != null) 'flagVariant': flagVariant, }); @@ -492,7 +511,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('distinctId'); + return await _invoke('distinctId'); } on PlatformException catch (exception) { printIfDebug('Exeption on getDistinctId: $exception'); return ""; @@ -506,7 +525,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('reset'); + await _invoke('reset'); } on PlatformException catch (exception) { printIfDebug('Exeption on reset: $exception'); } @@ -519,7 +538,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('disable'); + await _invoke('disable'); } on PlatformException catch (exception) { printIfDebug('Exeption on disable: $exception'); } @@ -532,7 +551,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('enable'); + await _invoke('enable'); } on PlatformException catch (exception) { printIfDebug('Exeption on enable: $exception'); } @@ -545,7 +564,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - final result = await _methodChannel.invokeMethod('isOptOut'); + final result = await _invoke('isOptOut'); return result as bool? ?? true; } on PlatformException catch (exception) { printIfDebug('Exception on isOptOut: $exception'); @@ -560,7 +579,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('debug', {'debug': enabled}); + await _invoke('debug', {'debug': enabled}); } on PlatformException catch (exception) { printIfDebug('Exeption on debug: $exception'); } @@ -574,7 +593,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('isFeatureEnabled', { + return await _invoke('isFeatureEnabled', { 'key': key, if (sendFeatureFlagEvent != null) 'sendEvent': sendFeatureFlagEvent, }); @@ -591,7 +610,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('reloadFeatureFlags'); + await _invoke('reloadFeatureFlags'); } on PlatformException catch (exception) { printIfDebug('Exeption on reloadFeatureFlags: $exception'); } @@ -609,7 +628,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { final normalizedUserProperties = PropertyNormalizer.normalize(userProperties); - await _methodChannel.invokeMethod('setPersonPropertiesForFlags', { + await _invoke('setPersonPropertiesForFlags', { 'userProperties': normalizedUserProperties, }); } on PlatformException catch (exception) { @@ -624,7 +643,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('resetPersonPropertiesForFlags'); + await _invoke('resetPersonPropertiesForFlags'); } on PlatformException catch (exception) { printIfDebug('Exception on resetPersonPropertiesForFlags: $exception'); } @@ -643,7 +662,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { final normalizedGroupProperties = PropertyNormalizer.normalize(groupProperties); - await _methodChannel.invokeMethod('setGroupPropertiesForFlags', { + await _invoke('setGroupPropertiesForFlags', { 'groupType': groupType, 'groupProperties': normalizedGroupProperties, }); @@ -659,7 +678,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('resetGroupPropertiesForFlags', { + await _invoke('resetGroupPropertiesForFlags', { if (groupType != null) 'groupType': groupType, }); } on PlatformException catch (exception) { @@ -682,7 +701,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ? PropertyNormalizer.normalize(groupProperties) : null; - await _methodChannel.invokeMethod('group', { + await _invoke('group', { 'groupType': groupType, 'groupKey': groupKey, if (normalizedGroupProperties != null) @@ -703,7 +722,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('getFeatureFlag', { + return await _invoke('getFeatureFlag', { 'key': key, if (sendFeatureFlagEvent != null) 'sendEvent': sendFeatureFlagEvent, }); @@ -723,7 +742,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - final result = await _methodChannel.invokeMethod('getFeatureFlagResult', { + final result = await _invoke('getFeatureFlagResult', { 'key': key, if (sendFeatureFlagEvent != null) 'sendEvent': sendFeatureFlagEvent, }); @@ -743,8 +762,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - final results = await _methodChannel - .invokeMethod>('getAllFeatureFlags'); + final results = await _invoke('getAllFeatureFlags') as List?; return results ?.map((result) => featureFlagResultFromMap(result, '')) .nonNulls @@ -762,7 +780,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('register', { + return await _invoke('register', { 'key': key, 'value': value, }); @@ -778,7 +796,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('unregister', {'key': key}); + return await _invoke('unregister', {'key': key}); } on PlatformException catch (exception) { printIfDebug('Exeption on unregister: $exception'); } @@ -791,7 +809,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('flush'); + return await _invoke('flush'); } on PlatformException catch (exception) { printIfDebug('Exeption on flush: $exception'); } @@ -818,43 +836,52 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { ); // Apply beforeSend callback - exception events are captured as $exception - final processedEvent = _runBeforeSend( - PostHogEventName.exception, - exceptionProps.cast(), + await _order.event( + () => _runBeforeSend( + PostHogEventName.exception, + exceptionProps.cast(), + ), + (processedEvent) => _sendException(error, processedEvent), ); - if (processedEvent == null) { - printIfDebug( - '[PostHog] Exception event dropped by beforeSend: ${error.runtimeType}', - ); - return; - } - - // If event name was changed, use capture() instead - if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - ); - return; - } - - // 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(), - ) - : {}; - - await _methodChannel.invokeMethod('captureException', { - 'timestamp': timestamp, - 'properties': normalizedData, - }); } on PlatformException catch (exception) { printIfDebug('Exception in captureException: $exception'); } } + Future _sendException( + Object error, + PostHogEvent? processedEvent, + ) async { + if (processedEvent == null) { + printIfDebug( + '[PostHog] Exception event dropped by beforeSend: ${error.runtimeType}', + ); + return; + } + + // If event name was changed, use capture() instead + if (processedEvent.event != PostHogEventName.exception) { + await capture( + eventName: processedEvent.event, + properties: processedEvent.properties?.cast(), + ); + return; + } + + // 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(), + ) + : {}; + + await _invoke('captureException', { + 'timestamp': timestamp, + 'properties': normalizedData, + }); + } + @override Future addExceptionStep( String message, { @@ -868,7 +895,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { final normalizedProperties = properties != null ? PropertyNormalizer.normalize(properties) : null; - await _methodChannel.invokeMethod('addExceptionStep', { + await _invoke('addExceptionStep', { 'message': message, if (normalizedProperties != null) 'properties': normalizedProperties, }); @@ -884,7 +911,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - return await _methodChannel.invokeMethod('close'); + return await _invoke('close'); } on PlatformException catch (exception) { printIfDebug('Exeption on close: $exception'); } @@ -897,7 +924,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - final sessionId = await _methodChannel.invokeMethod('getSessionId'); + final sessionId = await _invoke('getSessionId'); return sessionId; } on PlatformException catch (exception) { printIfDebug('Exception on getSessionId: $exception'); @@ -914,7 +941,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('openUrl', url); + await _invoke('openUrl', url); } on PlatformException catch (exception) { printIfDebug('Exception on openUrl: $exception'); } @@ -936,7 +963,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('registerPushNotificationToken', { + await _invoke('registerPushNotificationToken', { 'deviceToken': deviceToken, if (appId != null) 'appId': appId, }); @@ -958,7 +985,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('unregisterPushNotificationToken'); + await _invoke('unregisterPushNotificationToken'); } on PlatformException catch (exception) { printIfDebug('Exception on unregisterPushNotificationToken: $exception'); } @@ -977,7 +1004,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('capturePushNotificationOpened', { + await _invoke('capturePushNotificationOpened', { if (title != null) 'title': title, if (subtitle != null) 'subtitle': subtitle, if (body != null) 'body': body, @@ -996,7 +1023,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('startSessionRecording', resumeCurrent); + await _invoke('startSessionRecording', resumeCurrent); } on PlatformException catch (exception) { printIfDebug('Exception on startSessionRecording: $exception'); } @@ -1009,7 +1036,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - await _methodChannel.invokeMethod('stopSessionRecording'); + await _invoke('stopSessionRecording'); } on PlatformException catch (exception) { printIfDebug('Exception on stopSessionRecording: $exception'); } @@ -1022,7 +1049,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { } try { - final result = await _methodChannel.invokeMethod('isSessionReplayActive'); + final result = await _invoke('isSessionReplayActive'); return result as bool? ?? false; } on PlatformException catch (exception) { printIfDebug('Exception on isSessionReplayActive: $exception'); diff --git a/posthog_flutter/lib/src/utils/call_order.dart b/posthog_flutter/lib/src/utils/call_order.dart new file mode 100644 index 00000000..9dbb430a --- /dev/null +++ b/posthog_flutter/lib/src/utils/call_order.dart @@ -0,0 +1,103 @@ +import 'dart:async'; + +import '../util/logging.dart'; + +/// Hands calls to the underlying SDK in the order the app made them. +/// +/// An event always has to go out with the user, super properties, groups and +/// consent it was captured under, but handing it over can take more than one +/// async step. While it does, later calls such as reset() or optOut() wait here +/// until the event has been handed over, so they still apply after it. +class CallOrder { + /// An event that takes longer than this stops holding back later calls. It + /// is still sent when it is ready. + static const maxWait = Duration(seconds: 10); + + // Set while a turn is being used: calls made from beforeSend, or from the + // call that hands an event over, must not wait for the turn they run in. + static final Object _inTurn = Object(); + + Future? _last; + + /// Runs [call] now when nothing is waiting, otherwise after every earlier + /// call has been handed over. [call] must hand over before its first await. + Future run(Future Function() call) { + if (_last == null || _isInTurn) return call(); + final turn = _take(); + return turn.ahead.then((_) { + try { + return _inZone(call); + } finally { + turn.end(); + } + }); + } + + /// 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). + Future event( + FutureOr Function() hook, + Future Function(E event) send, + ) async { + if (_isInTurn) { + final hooked = hook(); + return send(hooked is Future ? await hooked : hooked); + } + if (_last == null) { + final hooked = _inZone(hook); + if (hooked is! Future) return send(hooked); + return _hold(_take(), () => hooked, send); + } + return _hold(_take(), () => _inZone(hook), send); + } + + // maxWait counts from the capture, not from when the hook starts, so hooks + // that never finish hold later calls back for maxWait in total rather than + // once per queued event. + Future _hold( + _Turn turn, + FutureOr Function() hook, + 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.'); + turn.ahead.then((_) => turn.end()); + }); + try { + await turn.ahead; + final hooked = hook(); + final processed = hooked is Future ? await hooked : hooked; + await _inZone(() => send(processed)); + } finally { + timer.cancel(); + turn.ahead.then((_) => turn.end()); + } + } + + bool get _isInTurn => Zone.current[_inTurn] == true; + + R _inZone(R Function() body) => + runZoned(body, zoneValues: {_inTurn: true}); + + _Turn _take() { + final ahead = _last ?? Future.value(); + final done = Completer(); + final mine = done.future; + _last = mine; + return _Turn(ahead, () { + if (done.isCompleted) return; + if (identical(_last, mine)) _last = null; + done.complete(); + }); + } +} + +class _Turn { + _Turn(this.ahead, this.end); + + final Future ahead; + final void Function() end; +} diff --git a/posthog_flutter/test/call_order_test.dart b/posthog_flutter/test/call_order_test.dart new file mode 100644 index 00000000..25bfe3b4 --- /dev/null +++ b/posthog_flutter/test/call_order_test.dart @@ -0,0 +1,136 @@ +import 'dart:async'; + +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:posthog_flutter/src/utils/call_order.dart'; + +void main() { + late CallOrder order; + late List calls; + + setUp(() { + order = CallOrder(); + calls = []; + }); + + Future record(String name) async => calls.add(name); + + test('runs a call immediately when nothing is in flight', () { + order.run(() => record('reset')); + order.event(() => 'checkout', record); + + expect(calls, ['reset', 'checkout']); + }); + + test('a call waits for an event whose hook is still running', () async { + final hook = Completer(); + final sent = order.event(() => hook.future, record); + final reset = order.run(() => record('reset')); + await pumpEventQueue(); + expect(calls, isEmpty); + + hook.complete('checkout'); + await Future.wait([sent, reset]); + + expect(calls, ['checkout', 'reset']); + }); + + test('events go out in call order whichever hook finishes first', () async { + final slow = Completer(); + final sent = [ + order.event(() => slow.future, record), + order.event(() => Future.value('fast'), record), + order.event(() => 'sync', record), + ]; + await pumpEventQueue(); + slow.complete('slow'); + await Future.wait(sent); + + expect(calls, ['slow', 'fast', 'sync']); + }); + + test('a hook sees calls made before its event', () async { + var user = 'old-user'; + final slow = Completer(); + final sent = [ + order.event(() => slow.future, record), + order.run(() async => user = 'new-user'), + order.event(() => 'checkout as $user', record), + ]; + await pumpEventQueue(); + slow.complete('slow'); + await Future.wait(sent); + + expect(calls, ['slow', 'checkout as new-user']); + }); + + test('a call made from the hook does not wait for its own event', () async { + final sent = order.event(() async { + await order.run(() => record('from_hook')); + return 'checkout'; + }, record); + final reset = order.run(() => record('reset')); + await Future.wait([sent, reset]); + + expect(calls, ['from_hook', 'checkout', 'reset']); + }); + + test('a call waits for an event sent again from the send step', () async { + final sent = order.event( + () => Future.value('renamed'), + (name) => order.event( + () => Future.delayed(Duration.zero).then((_) => name), + record, + ), + ); + final reset = order.run(() => record('reset')); + await Future.wait([sent, reset]); + + expect(calls, ['renamed', 'reset']); + }); + + test('a hook that throws still lets later calls through, in order', () async { + final earlier = Completer(); + final sentEarlier = order.event(() => earlier.future, record); + final sent = order.event( + () => Future.error(StateError('boom')), + record, + ); + final reset = order.run(() => record('reset')); + + earlier.complete('checkout'); + await expectLater(sent, throwsStateError); + await Future.wait([sentEarlier, reset]); + expect(calls, ['checkout', 'reset']); + }); + + test('hooks that never finish hold later calls back for maxWait in total', + () { + fakeAsync((async) { + for (var i = 0; i < 5; i++) { + order.event(() => Completer().future, record); + } + order.run(() => record('reset')); + + async.elapse(CallOrder.maxWait); + expect(calls, ['reset']); + }); + }); + + test('stops holding calls back after maxWait, and still sends', () { + fakeAsync((async) { + final hook = Completer(); + order.event(() => hook.future, record); + order.run(() => record('reset')); + + async.elapse(CallOrder.maxWait - const Duration(milliseconds: 1)); + expect(calls, isEmpty); + async.elapse(const Duration(milliseconds: 1)); + expect(calls, ['reset']); + + hook.complete('checkout'); + async.flushMicrotasks(); + expect(calls, ['reset', 'checkout']); + }); + }); +} From fe0a6ff101a8c4a35ce456d990f58ec5c0564859 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 13:18:56 -0400 Subject: [PATCH 03/13] test(android): restore the screenshot scale expectation lost in the main merge --- .../test/kotlin/com/posthog/flutter/PosthogFlutterPluginTest.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 fc526752..7a56bac9 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 @@ -267,7 +267,7 @@ internal class PosthogFlutterPluginTest { ) val replay = assertNotNull(plugin.lastBuiltConfig).sessionReplayConfig - assertEquals(1f, replay.screenshotScale) + assertNull(replay.screenshotScale) assertEquals(30, replay.screenshotCompressionQuality) assertEquals(PostHogScreenshotColorMode.ARGB_8888, replay.screenshotColorMode) } finally { From 3157fc1116d99e23ce8157312a2c66d9ec6c5fd2 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 18:23:40 -0400 Subject: [PATCH 04/13] fix(web): hand feature events to posthog-js before yielding Without CallOrder the await on the flag lookup let a reset() made right after an un-awaited captureFeatureView or captureFeatureInteraction overtake it, so the event went out as the new anonymous user with the previous user's flag. Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/posthog_flutter_web.dart | 7 ++++- .../lib/src/posthog_flutter_web_handler.dart | 19 +++++++++----- .../test/web_before_send_test.dart | 26 +++++++++++++++++++ 3 files changed, 44 insertions(+), 8 deletions(-) diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 0aacc9dd..40d1a9c0 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -320,6 +320,8 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { }) => _captureFeatureEvent(r'$feature_interaction', flag, flagVariant); + // Looks up the flag and starts the capture without an await in between, so + // a reset() right after the call cannot move the event to the next user. Future _captureFeatureEvent( String event, String flag, @@ -327,7 +329,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { ) async { final screenName = _currentScreen; final result = flagVariant == null - ? await getFeatureFlagResult(key: flag, sendFeatureFlagEvent: false) + ? featureFlagResultFromMap( + readFeatureFlagResult(flag, sendEvent: false), + flag, + ) : null; final captured = featureEvent( event, flag, flagVariant ?? result?.variant ?? result?.enabled); diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index d35dd08d..d4487599 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -124,6 +124,15 @@ JSAny? _flagOptions(Map args) { return {if (sendEvent != null) 'send_event': sendEvent}.jsify(); } +Object? readFeatureFlagResult(String key, {bool? sendEvent}) { + return posthog + ?.getFeatureFlagResult( + stringToJSAny(key), + {if (sendEvent != null) 'send_event': sendEvent}.jsify(), + ) + ?.dartify(); +} + bool _sdkInfoOverridden = false; void _maybeOverrideSDKInfo() { @@ -378,14 +387,10 @@ Future handleWebMethodCall(MethodCall call) async { posthog?.getFeatureFlag(stringToJSAny(key), _flagOptions(args)); return featureFlag?.dartify(); case 'getFeatureFlagResult': - final key = args['key'] as String; - final sendEvent = args['sendEvent'] as bool?; - - final result = posthog?.getFeatureFlagResult( - stringToJSAny(key), - {if (sendEvent != null) 'send_event': sendEvent}.jsify(), + return readFeatureFlagResult( + args['key'] as String, + sendEvent: args['sendEvent'] as bool?, ); - return result?.dartify(); case 'getAllFeatureFlags': try { return posthog?.getAllFeatureFlags()?.dartify(); diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index 7eee0a6e..8bb97f9f 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -87,6 +87,32 @@ void main() { }); } + test('a feature event looks up its flag and captures before a reset', + () async { + final calls = []; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'getFeatureFlagResult'.toJS, + ((JSString key, [JSAny? options]) { + calls.add('getFeatureFlagResult'); + return {'key': key.toDart, 'enabled': true}.jsify(); + }).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); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token')); + + final sent = web.captureFeatureView(flag: 'checkout'); + await web.reset(); + await sent; + + expect(calls, ['getFeatureFlagResult', r'$feature_view', 'reset']); + }); + test('beforeSend null drops capture on web', () async { final web = PosthogFlutterWeb(); await web.setup( From 26380a1a19b7345c24809cf25ed4996c598e122d Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 22:13:41 -0400 Subject: [PATCH 05/13] docs: fold #686 release notes into the 6.0 docs --- .changeset/v6-major-release.md | 2 ++ .changeset/v6-sync-before-send.md | 5 ----- posthog_flutter/MIGRATION.md | 20 ++++++++++++++++++++ 3 files changed, 22 insertions(+), 5 deletions(-) delete mode 100644 .changeset/v6-sync-before-send.md diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 9d30fb0e..9b301a04 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -12,6 +12,8 @@ - **Breaking:** remove `Posthog().getFeatureFlagPayload()` — use `getFeatureFlagResult(key, sendFeatureFlagEvent: false)` and read `payload` - **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 - **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` - Declare Android `minSdkVersion` 23 to match `posthog-android` diff --git a/.changeset/v6-sync-before-send.md b/.changeset/v6-sync-before-send.md deleted file mode 100644 index 344fd64f..00000000 --- a/.changeset/v6-sync-before-send.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"posthog_flutter": major ---- - -- **Breaking:** `beforeSend` and `logsConfig.beforeSend` callbacks are now synchronous (`PostHogEvent? Function(PostHogEvent)` and `PostHogLogRecord? Function(PostHogLogRecord)`), as in the native SDKs. A `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` no longer applies to the event first, and Windows and Linux no longer drop it. Callbacks that used `await` must load what they need ahead of time diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index 0ba88922..4f852c0e 100644 --- a/posthog_flutter/MIGRATION.md +++ b/posthog_flutter/MIGRATION.md @@ -181,6 +181,26 @@ config.dataMode = PostHogDataMode.any; They serialized the internal platform-channel format and have no replacement. `toMap()` is gone from `PostHogConfig`, `PostHogBootstrapConfig`, `PostHogLogsConfig`, `PostHogRageClickConfig`, `PostHogSessionReplayConfig`, `PostHogErrorTrackingConfig` and `PostHogExceptionStepsConfig`. To build a result, for example in a test, call the `PostHogFeatureFlagResult` constructor, which stays public. +### `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. + +```dart +// Before +config.beforeSend = [ + (event) async { + final allowed = await loadAllowList(); + return allowed.contains(event.event) ? event : null; + }, +]; + +// After +final allowed = await loadAllowList(); +config.beforeSend = [ + (event) => allowed.contains(event.event) ? event : null, +]; +``` + ### Platform interface changes These affect only code that calls, extends or fakes `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` or `PosthogFlutterWeb` directly, such as test mocks. `Posthog().optIn()` and `optOut()` are unaffected. From 193b92ef1aa47db8f0ccf22e5e7cfce9c19cef55 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Fri, 30 Oct 2026 19:04:39 -0400 Subject: [PATCH 06/13] fix: run a renaming beforeSend once and keep its user properties A hook that renamed a screen or exception ran again through capture() and lost its userProperties on web, iOS, Android and macOS. Also covers calls made from inside a hook and bursts of events, and documents that a hook blocks the UI. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-major-release.md | 3 +- posthog_flutter/lib/posthog_flutter_web.dart | 14 +- posthog_flutter/lib/src/posthog_config.dart | 8 +- .../lib/src/posthog_flutter_io.dart | 10 +- posthog_flutter/lib/src/utils/call_order.dart | 7 +- .../test/posthog_flutter_desktop_test.dart | 71 ++++++++ .../test/posthog_flutter_io_test.dart | 156 ++++++++++++++++++ posthog_flutter/test/posthog_logs_test.dart | 33 ++++ .../test/web_before_send_test.dart | 143 ++++++++++++++++ 9 files changed, 422 insertions(+), 23 deletions(-) diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 21899ad7..9c8e3980 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -13,7 +13,8 @@ - **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` - **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` - Declare Android `minSdkVersion` 23 to match `posthog-android` diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 7cd97469..f6ff95b7 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -193,6 +193,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { return; } + return _sendCapture(processedEvent); + } + + Future _sendCapture(PostHogEvent processedEvent) { final extracted = CaptureUtils.extractUserProperties( properties: processedEvent.properties, userProperties: processedEvent.userProperties, @@ -273,10 +277,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - ); + await _sendCapture(processedEvent); return; } @@ -575,10 +576,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - ); + await _sendCapture(processedEvent); return; } diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index e79abe6b..d4315315 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -375,8 +375,12 @@ class PostHogConfig { /// stage. /// /// **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. /// - 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_flutter_io.dart b/posthog_flutter/lib/src/posthog_flutter_io.dart index 48d82365..329fd1c2 100644 --- a/posthog_flutter/lib/src/posthog_flutter_io.dart +++ b/posthog_flutter/lib/src/posthog_flutter_io.dart @@ -395,10 +395,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { // If event name was changed, use regular capture() instead if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - ); + await _sendCapture(processedEvent.event, processedEvent); return; } @@ -869,10 +866,7 @@ class PosthogFlutterIO extends PosthogFlutterPlatformInterface { // If event name was changed, use capture() instead if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - ); + await _sendCapture(processedEvent.event, processedEvent); return; } 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/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 9acf09c0..f62d53d1 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -456,6 +456,77 @@ 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)); + }); + }); + }); + + 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) diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index e061e195..fdfc3537 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'; @@ -998,6 +1000,160 @@ isolate_dso_base: 7000000000 } }); + 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); + final args = Map.from( + log.singleWhere((c) => c.method == 'capture').arguments as Map); + expect(args['eventName'], 'renamed'); + expect(args['userProperties'], {'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.map((c) => (c.arguments as Map)['eventName']), + 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, + _ => 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('capture')); + }); + }); + + 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), ['capture']); + }); + + 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.single.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.map((c) => + c.method == 'reset' ? 'reset' : (c.arguments as Map)['eventName']), + expected, + ); + }); + }); + group('PosthogFlutterIO addExceptionStep', () { test('sends message and normalized properties', () async { await posthogFlutterIO.addExceptionStep( 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/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index 8bb97f9f..07dc42f0 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -22,6 +22,7 @@ void main() { captures.add({ 'event': event.toDart, 'properties': properties?.dartify(), + 'options': options?.dartify(), }); }).toJS, ); @@ -113,6 +114,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( From 28f8761158bc69868912ba6985b7eff3cfa87f33 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 19:42:15 -0500 Subject: [PATCH 07/13] fix: keep events when beforeSend resets on desktop or sets user properties on web On Windows and Linux, a callback calling reset() or identify() dropped the event. It now goes out as the user it was prepared for, as on iOS, Android and macOS. On web, userProperties set on a screen or exception that kept its name were lost. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-major-release.md | 2 + posthog_flutter/lib/posthog_flutter_web.dart | 38 +++++++++++---- .../lib/src/core/posthog_core.dart | 12 ++++- .../lib/src/posthog_flutter_desktop.dart | 42 ++++++++--------- .../lib/src/posthog_flutter_web_handler.dart | 35 ++++++++------ .../test/posthog_flutter_desktop_test.dart | 47 +++++++++++++++++++ .../test/web_before_send_test.dart | 34 ++++++++++++++ 7 files changed, 164 insertions(+), 46 deletions(-) diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 360534b5..a4d97170 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -15,6 +15,8 @@ - **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()`, `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 - **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 diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 4759babf..e68d615d 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -342,16 +342,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), }), ); } @@ -649,14 +661,24 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { 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 903dae8a..7b31a1b2 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -449,16 +449,21 @@ abstract class PostHogCore extends PostHogCoreStateless { /// With [ai], the event goes to PostHog's AI endpoint from a queue of its /// own, which drops a serialized event over its size limit. /// + /// [distinctId] is the user the event was prepared for, which a callback + /// calling `reset()` or `identify()` may have replaced. The event stays + /// theirs, and doesn't update the replacement's person state. + /// /// Returns the event's uuid, or null when it is not queued: the client /// is closed or opted out, or the AI event is over the size limit. String? capturePrepared( String event, PostHogPreparedEvent prepared, { + String? distinctId, bool ai = false, }) => wrap(() { if (_ignoredWhileOptedOut('posthog.capture')) return null; - return _queuePrepared(event, prepared, ai: ai); + return _queuePrepared(event, prepared, distinctId: distinctId, ai: ai); }); /// [options] with `process_person_profile: false` added when person @@ -498,12 +503,15 @@ abstract class PostHogCore extends PostHogCoreStateless { String? _queuePrepared( String event, PostHogPreparedEvent prepared, { + String? distinctId, bool ai = false, }) { final (:properties, :options, :timestamp) = prepared; - final uuid = captureStateless(getDistinctId(), event, + final currentDistinctId = getDistinctId(); + final uuid = captureStateless(distinctId ?? currentDistinctId, event, properties: properties, options: options, timestamp: timestamp, ai: ai); if (uuid == null) return null; + if (distinctId != null && distinctId != currentDistinctId) return uuid; // 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. diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 7164eca7..49468262 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -87,18 +87,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; @@ -275,9 +269,10 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('capture', scope, distinctId); + final current = _clientForContinuation('capture', scope); if (current == null) return; - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed( + current, processed, exceptionSteps, prepared, distinctId); }); @override @@ -316,9 +311,10 @@ 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, + return _captureProcessed( + current, processed, exceptionSteps, prepared, distinctId, ai: true); }); @@ -354,12 +350,13 @@ 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) { - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed( + current, processed, exceptionSteps, prepared, distinctId); return; } @@ -375,7 +372,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { current.registerForSession( {PostHogPropertyName.screenName: finalScreenName}); } - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed( + current, processed, exceptionSteps, prepared, distinctId); }); /// Structured logs are not supported on the desktop implementation. @@ -631,10 +629,10 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = - _clientForContinuation('captureException', scope, distinctId); + final current = _clientForContinuation('captureException', scope); if (current == null) return; - _captureProcessed(current, processed, exceptionSteps, prepared); + _captureProcessed( + current, processed, exceptionSteps, prepared, distinctId); }); @override @@ -794,7 +792,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { DesktopPostHog client, PostHogEvent event, ExceptionStepsBuffer? exceptionSteps, - _PreparedEvent prepared, { + _PreparedEvent prepared, + String distinctId, { bool ai = false, }) { if (!_hasName(event.event)) return null; @@ -825,6 +824,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: options, timestamp: prepared.timestamp, ), + distinctId: distinctId, ai: ai); } diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 2772007e..4d885355 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -296,6 +296,19 @@ Future> _reloadFeatureFlags(PostHog? ph) async { } } +/// 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(); @@ -338,20 +351,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), @@ -366,7 +366,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/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index a16fbf77..79dd66c5 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -546,6 +546,53 @@ void main() { }); }); + 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('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]; diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index 665b956d..9188a75c 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -38,6 +38,40 @@ void main() { globalContext.setProperty('posthog'.toJS, fake); }); + 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: [ From 025cf377a15007e3f5c44ec977d8b12f056d0545 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 20:00:32 -0500 Subject: [PATCH 08/13] fix(web): keep an event on its user when beforeSend changes the user posthog-js builds the event after the callbacks, so one calling reset() or identify() moved the event to the new user. It now stays on the earlier user, as on the other platforms. Co-Authored-By: Claude Opus 5.5 --- .changeset/v6-major-release.md | 2 +- posthog_flutter/MIGRATION.md | 2 +- posthog_flutter/lib/posthog_flutter_web.dart | 16 +++++++- .../lib/src/posthog_flutter_web_handler.dart | 4 ++ .../test/web_before_send_test.dart | 38 +++++++++++++++++++ 5 files changed, 59 insertions(+), 3 deletions(-) diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index a4d97170..02e29786 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -16,7 +16,7 @@ - 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 +- 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 diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index 45a8d6a6..626d2f7e 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 diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index e68d615d..b29e4297 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -48,7 +48,9 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userPropertiesSetOnce, Map? options, }) { - return applyBeforeSend( + final distinctId = + _beforeSendCallbacks.isEmpty ? null : currentWebDistinctId(); + final processed = applyBeforeSend( _beforeSendCallbacks, PostHogEvent( event: eventName, @@ -58,6 +60,18 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { options: options == null ? null : {...options}, ), ); + // 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. + if (processed != null && + distinctId != null && + distinctId != currentWebDistinctId()) { + processed.properties = { + 'distinct_id': distinctId, + ...?processed.properties, + }; + } + return processed; } /// posthog-js sends these calls' events without event properties, so diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 4d885355..d567691f 100644 --- a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart +++ b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart @@ -296,6 +296,10 @@ 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?; + /// 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) { diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index 9188a75c..e267ecb3 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -12,6 +12,7 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); final captures = >[]; + late String distinctId; setUp(() { captures.clear(); @@ -26,6 +27,8 @@ void main() { }); }).toJS, ); + distinctId = 'first-user'; + fake.setProperty('get_distinct_id'.toJS, (() => distinctId.toJS).toJS); fake.setProperty( 'captureException'.toJS, ((JSAny? error, JSAny? properties) { @@ -38,6 +41,41 @@ 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('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 sets user properties without renaming', () { PostHogConfig hooked() => PostHogConfig('test_token', beforeSend: [ (event) { From 9a09d0653d7e8bf294d2cd85e5388f408fb00fd3 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 21:04:18 -0500 Subject: [PATCH 09/13] fix(desktop): keep the prepared user's person and session state when beforeSend changes the user A hook calling reset() or identify() left the event on its original user, but person processing was recomputed from the replacement's state, and a $screen hook calling reset() put the old screen in the new session. Co-Authored-By: Claude Opus 5.5 --- .../lib/src/core/posthog_core.dart | 26 +++--- .../lib/src/posthog_flutter_desktop.dart | 11 ++- .../test/posthog_flutter_desktop_test.dart | 83 +++++++++++++++++++ 3 files changed, 107 insertions(+), 13 deletions(-) diff --git a/posthog_flutter/lib/src/core/posthog_core.dart b/posthog_flutter/lib/src/core/posthog_core.dart index 7b31a1b2..97d45f66 100644 --- a/posthog_flutter/lib/src/core/posthog_core.dart +++ b/posthog_flutter/lib/src/core/posthog_core.dart @@ -182,16 +182,15 @@ abstract class PostHogCore extends PostHogCoreStateless { } /// The [options] of an event with [properties], with - /// `process_person_profile: false` added when person processing is off, - /// the event is not [requested] to update the person, and neither an - /// option nor a `$process_person_profile` property says otherwise. + /// `process_person_profile: false` added when the event doesn't [update] + /// the person, and neither an option nor a `$process_person_profile` + /// property says otherwise. Map? _personProcessingOptions( Map? options, Map properties, { - required bool requested, + required bool update, }) { - if (requested || - _hasPersonProcessing() || + if (update || properties[r'$process_person_profile'] != null || options?['process_person_profile'] != null) { return options; @@ -469,12 +468,19 @@ abstract class PostHogCore extends PostHogCoreStateless { /// [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. + /// + /// [hadPersonProcessing] is [hasPersonProcessing] when the event was + /// prepared: an event keeps the state of the user it belongs to. Map? personProcessingOptions( Map? options, - Map properties, - ) => + Map properties, { + required bool hadPersonProcessing, + }) => _personProcessingOptions(options, properties, - requested: _requestsPersonProcessing(properties)); + update: hadPersonProcessing || _requestsPersonProcessing(properties)); + + /// Whether events of the current user update their person profile. + bool get hasPersonProcessing => _hasPersonProcessing(); PostHogPreparedEvent? _prepareEvent( String event, { @@ -494,7 +500,7 @@ abstract class PostHogCore extends PostHogCoreStateless { options: _personProcessingOptions( options, allProperties, - requested: _requestsPersonProcessing(properties), + update: _hasPersonProcessing() || _requestsPersonProcessing(properties), ), timestamp: currentISOTime(), ); diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 49468262..5b4cc6ea 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -343,6 +343,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: options, ); if (prepared == null) return; + final sessionId = client.getSessionId(); final processed = _runBeforeSend(prepared.event); if (processed == null) { printIfDebug( @@ -367,8 +368,9 @@ 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}); } @@ -761,6 +763,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { implicitPersonProcessing: callerOptions?['process_person_profile'] == null, sdkPersonProcessing: preparedOptions?['process_person_profile'], + hadPersonProcessing: client.hasPersonProcessing, ); } @@ -815,7 +818,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (prepared.implicitPersonProcessing && options?['process_person_profile'] == prepared.sdkPersonProcessing) { options = client.personProcessingOptions( - {...?options}..remove('process_person_profile'), properties); + {...?options}..remove('process_person_profile'), properties, + hadPersonProcessing: prepared.hadPersonProcessing); } return client.capturePrepared( event.event, @@ -888,4 +892,5 @@ typedef _PreparedEvent = ({ String timestamp, bool implicitPersonProcessing, Object? sdkPersonProcessing, + bool hadPersonProcessing, }); diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 79dd66c5..aa945719 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -573,6 +573,89 @@ void main() { }); } + 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; From 5f627efbfeed14ecb8f5ea278ea6e6dbb4139e89 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 21:04:18 -0500 Subject: [PATCH 10/13] fix(web): don't restore the distinct id across a beforeSend consent change Under cookieless_mode on_reject, restoring the id reattached the opted-out user to a cookieless event, or sent the shared cookieless id after opting in. Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/posthog_flutter_web.dart | 8 +++-- .../test/web_before_send_test.dart | 34 +++++++++++++++++++ 2 files changed, 40 insertions(+), 2 deletions(-) diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index b29e4297..5c18429d 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -62,10 +62,14 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { ); // 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. + // 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 (processed != null && distinctId != null && - distinctId != currentWebDistinctId()) { + distinctId != r'$posthog_cookieless' && + distinctId != currentWebDistinctId() && + !(posthog?.has_opted_out_capturing() ?? true)) { processed.properties = { 'distinct_id': distinctId, ...?processed.properties, diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index e267ecb3..fbe3e21c 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -13,6 +13,7 @@ void main() { final captures = >[]; late String distinctId; + late bool optedOut; setUp(() { captures.clear(); @@ -29,6 +30,9 @@ void main() { ); distinctId = 'first-user'; fake.setProperty('get_distinct_id'.toJS, (() => distinctId.toJS).toJS); + optedOut = false; + fake.setProperty( + 'has_opted_out_capturing'.toJS, (() => optedOut.toJS).toJS); fake.setProperty( 'captureException'.toJS, ((JSAny? error, JSAny? properties) { @@ -66,6 +70,36 @@ void main() { }); }); + 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])); From 9dde196149e9c3057777147f205d06110ffd55ec Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 21:38:59 -0500 Subject: [PATCH 11/13] fix(web): drop user properties when beforeSend resets the user posthog-js stores an event's $set as the current user's person properties for flags, so after a reset() in the callback they reached the next user. identify() of an anonymous user links the two, so they stay. Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/posthog_flutter_web.dart | 22 +++++- .../lib/src/posthog_flutter_web_handler.dart | 6 ++ .../test/web_before_send_test.dart | 74 +++++++++++++++++++ 3 files changed, 98 insertions(+), 4 deletions(-) diff --git a/posthog_flutter/lib/posthog_flutter_web.dart b/posthog_flutter/lib/posthog_flutter_web.dart index 5c18429d..0c587883 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -50,6 +50,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { }) { final distinctId = _beforeSendCallbacks.isEmpty ? null : currentWebDistinctId(); + final wasIdentified = distinctId != null && currentWebUserIdentified(); final processed = applyBeforeSend( _beforeSendCallbacks, PostHogEvent( @@ -60,15 +61,28 @@ 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 (processed != null && - distinctId != null && - distinctId != r'$posthog_cookieless' && - distinctId != currentWebDistinctId() && + if (distinctId != r'$posthog_cookieless' && !(posthog?.has_opted_out_capturing() ?? true)) { processed.properties = { 'distinct_id': distinctId, diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index d567691f..856e5690 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); external JSFunction onFeatureFlags(JSFunction callback); external void startSessionRecording(); external void stopSessionRecording(); @@ -300,6 +302,10 @@ Future> _reloadFeatureFlags(PostHog? ph) async { 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) { diff --git a/posthog_flutter/test/web_before_send_test.dart b/posthog_flutter/test/web_before_send_test.dart index fbe3e21c..b1bc73cc 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -14,6 +14,7 @@ void main() { final captures = >[]; late String distinctId; late bool optedOut; + late String userState; setUp(() { captures.clear(); @@ -31,6 +32,12 @@ void main() { 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( @@ -110,6 +117,73 @@ void main() { }); }); + 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) { From a48d07c88eed0ba7f29daead1bb56f5b36f2c70a Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Mon, 2 Nov 2026 21:39:08 -0500 Subject: [PATCH 12/13] docs: note what a web beforeSend calling reset() keeps Co-Authored-By: Claude Opus 5.5 --- posthog_flutter/lib/src/posthog_config.dart | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 2c7bc736..a3dd10ef 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -447,6 +447,10 @@ class PostHogConfig { /// 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 From c0374cb0c77a03b926994e065280ae4efb935604 Mon Sep 17 00:00:00 2001 From: Anna Garcia Date: Tue, 3 Nov 2026 12:38:51 -0500 Subject: [PATCH 13/13] fix: add exception steps before beforeSend on Windows and Linux beforeSend can now read, change or remove $exception_steps, as on iOS and Android. Claude-Session: https://claude.ai/code/session_019xLynws83apuXa9LfRy9Aq --- .../lib/src/posthog_flutter_desktop.dart | 58 ++++++------------- .../test/posthog_flutter_desktop_test.dart | 24 ++++++++ 2 files changed, 42 insertions(+), 40 deletions(-) diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 474c7bd2..14ba88be 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -254,7 +254,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -273,8 +272,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('capture', scope); if (current == null) return; - await _captureProcessed( - current, processed, exceptionSteps, prepared, distinctId); + await _captureProcessed(current, processed, prepared, distinctId); }); @override @@ -296,7 +294,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return null; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -315,8 +312,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('captureAi', scope); if (current == null) return null; - return _captureProcessed( - current, processed, exceptionSteps, prepared, distinctId, + return _captureProcessed(current, processed, prepared, distinctId, ai: true); }); @@ -333,7 +329,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final prepared = _prepare( client, @@ -358,8 +353,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { // A renamed event is no longer a screen view. if (processed.event != PostHogEventName.screen) { - await _captureProcessed( - current, processed, exceptionSteps, prepared, distinctId); + await _captureProcessed(current, processed, prepared, distinctId); return; } @@ -376,8 +370,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { current.registerForSession( {PostHogPropertyName.screenName: finalScreenName}); } - await _captureProcessed( - current, processed, exceptionSteps, prepared, distinctId); + await _captureProcessed(current, processed, prepared, distinctId); }); /// Structured logs are not supported on the desktop implementation. @@ -608,7 +601,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final scope = _clientScope; if (scope == null) return; final distinctId = client.getDistinctId(); - final exceptionSteps = _exceptionSteps; final exceptionProps = DartExceptionProcessor.processException( error: error, @@ -636,8 +628,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { final current = _clientForContinuation('captureException', scope); if (current == null) return; - await _captureProcessed( - current, processed, exceptionSteps, prepared, distinctId); + await _captureProcessed(current, processed, prepared, distinctId); }); @override @@ -740,6 +731,8 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { /// 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. + /// An `$exception` event gets the exception steps recorded up to now, + /// unless its properties set `$exception_steps` themselves. _PreparedEvent? _prepare( DesktopPostHog client, String eventName, @@ -756,7 +749,12 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: callerOptions, ); if (prepared == null) return null; - final eventProperties = _nonNull(prepared.properties)!; + final steps = + eventName == PostHogEventName.exception ? _exceptionSteps?.steps : null; + final eventProperties = _nonNull({ + if (steps != null && steps.isNotEmpty) r'$exception_steps': steps, + ...prepared.properties, + })!; for (final (key, explicit) in [ (r'$set', userProperties), (r'$set_once', userPropertiesSetOnce), @@ -807,25 +805,19 @@ 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. FutureOr _captureProcessed( DesktopPostHog client, PostHogEvent event, - ExceptionStepsBuffer? exceptionSteps, _PreparedEvent prepared, String distinctId, { 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 @@ -856,20 +848,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, diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index 8d038232..2cdc49a0 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -1324,6 +1324,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)