diff --git a/.changeset/v6-major-release.md b/.changeset/v6-major-release.md index 69b3667e..ea60402a 100644 --- a/.changeset/v6-major-release.md +++ b/.changeset/v6-major-release.md @@ -13,7 +13,10 @@ - **Breaking:** remove the `PostHogSessionReplayConfig.debouncerDelay` setter — use `throttleDelay` - **Breaking:** remove `PostHogDataMode.cellular` — use `PostHogDataMode.any` - **Breaking:** make `beforeSend` and `logsConfig.beforeSend` callbacks synchronous — load what they need ahead of time instead of using `await` -- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()` or `captureException()` from applying to that event first, and stop dropping that event on Windows and Linux +- Keep a `reset()`, `identify()` or `optOut()` made right after an un-awaited `capture()`, `screen()`, `captureException()`, `captureFeatureView()` or `captureFeatureInteraction()` from applying to that event first, and stop dropping that event on Windows and Linux +- Run a `beforeSend` callback that renames a screen or exception event once, and keep its `userProperties` +- Keep `userProperties` and `userPropertiesSetOnce` that a `beforeSend` callback sets on a screen or exception event on web +- Send an event as its original user when a `beforeSend` callback calls `reset()` or `identify()` on Windows and Linux, instead of dropping it, and on web, instead of sending it as the new user - **Breaking:** remove `toMap()` from the config classes and `PostHogFeatureFlagResult.fromMap()` from the public API - **Breaking:** rename `enable()` and `disable()` to `optIn()` and `optOut()` on `PosthogFlutterPlatformInterface`, `PosthogFlutterIO` and `PosthogFlutterWeb` - **Breaking:** adopt `posthog-ios` 4.x, which requires Xcode 26 diff --git a/posthog_flutter/MIGRATION.md b/posthog_flutter/MIGRATION.md index fdde6d8c..f2c7c513 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 994a2779..0c587883 100644 --- a/posthog_flutter/lib/posthog_flutter_web.dart +++ b/posthog_flutter/lib/posthog_flutter_web.dart @@ -48,7 +48,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { Map? userPropertiesSetOnce, Map? options, }) { - return applyBeforeSend( + final distinctId = + _beforeSendCallbacks.isEmpty ? null : currentWebDistinctId(); + final wasIdentified = distinctId != null && currentWebUserIdentified(); + final processed = applyBeforeSend( _beforeSendCallbacks, PostHogEvent( event: eventName, @@ -58,6 +61,35 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { options: options == null ? null : {...options}, ), ); + if (processed == null || + distinctId == null || + distinctId == currentWebDistinctId()) { + return processed; + } + // posthog-js stores an event's `$set` as the current user's person + // properties for flags, so after a reset() they would reach the next user. + // identify() of an anonymous user links the two, so they stay. + if (wasIdentified || !currentWebUserIdentified()) { + processed + ..userProperties = null + ..userPropertiesSetOnce = null + ..properties = {...?processed.properties} + ..properties!.remove(r'$set') + ..properties!.remove(r'$set_once'); + } + // posthog-js builds the event only after the callbacks, so one calling + // reset() or identify() would otherwise move the event to the new user. + // Event properties win over the stored distinct id. A callback changing + // consent under cookieless_mode swaps the id on purpose: neither the user + // who opted out nor the shared cookieless id may come back. + if (distinctId != r'$posthog_cookieless' && + !(posthog?.has_opted_out_capturing() ?? true)) { + processed.properties = { + 'distinct_id': distinctId, + ...?processed.properties, + }; + } + return processed; } /// posthog-js sends these calls' events without event properties, so @@ -216,6 +248,10 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { return; } + return _sendCapture(processedEvent); + } + + Future _sendCapture(PostHogEvent processedEvent) { final extracted = CaptureUtils.extractUserProperties( properties: processedEvent.properties, userProperties: processedEvent.userProperties, @@ -329,11 +365,7 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.screen) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } @@ -342,16 +374,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), }), ); } @@ -645,22 +689,28 @@ class PosthogFlutterWeb extends PosthogFlutterPlatformInterface { } if (processedEvent.event != PostHogEventName.exception) { - await capture( - eventName: processedEvent.event, - properties: processedEvent.properties?.cast(), - options: processedEvent.options, - ); + await _sendCapture(processedEvent); return; } - final normalizedData = PropertyNormalizer.normalize( - _withOptionProperties( - processedEvent.properties?.cast(), - processedEvent.options, - PostHogEventName.exception, - ) ?? - {}, + final extracted = CaptureUtils.extractUserProperties( + properties: processedEvent.properties?.cast(), + userProperties: processedEvent.userProperties, + userPropertiesSetOnce: processedEvent.userPropertiesSetOnce, ); + final userProperties = extracted.userProperties; + final userPropertiesSetOnce = extracted.userPropertiesSetOnce; + // posthog-js's captureException takes no capture options, but capture + // merges `$set` and `$set_once` from the event's properties. + final normalizedData = PropertyNormalizer.normalize({ + ...?_withOptionProperties( + extracted.properties, + processedEvent.options, + PostHogEventName.exception, + ), + if (userProperties != null) r'$set': userProperties, + if (userPropertiesSetOnce != null) r'$set_once': userPropertiesSetOnce, + }); return await handleWebMethodCall( MethodCall('captureException', {'properties': normalizedData}), diff --git a/posthog_flutter/lib/src/posthog_config.dart b/posthog_flutter/lib/src/posthog_config.dart index 27484b6a..3ce8ac56 100644 --- a/posthog_flutter/lib/src/posthog_config.dart +++ b/posthog_flutter/lib/src/posthog_config.dart @@ -456,8 +456,16 @@ class PostHogConfig { /// rest later. /// /// **Note:** - /// - Callbacks are synchronous. Load anything they need (such as remote - /// config) ahead of time. + /// - Callbacks are synchronous and run on the calling isolate, so a slow one + /// blocks the UI. Load anything they need (such as remote config or feature + /// flags) ahead of time; a change made after the callback returns is not + /// sent. + /// - A callback that captures an event must not do so for that event too, or + /// it never finishes. + /// - On web, an event whose callback calls `reset()` stays on its user but + /// joins the next user's session and person processing, and its user + /// properties are dropped, because posthog-js builds the event after the + /// callbacks. /// - If a callback throws, the event is dropped and later callbacks are not /// called. /// - If any callback returns `null`, the event is dropped and subsequent diff --git a/posthog_flutter/lib/src/posthog_flutter_desktop.dart b/posthog_flutter/lib/src/posthog_flutter_desktop.dart index 25335cc0..48acbe49 100644 --- a/posthog_flutter/lib/src/posthog_flutter_desktop.dart +++ b/posthog_flutter/lib/src/posthog_flutter_desktop.dart @@ -88,18 +88,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; @@ -260,7 +254,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -277,7 +270,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = _clientForContinuation('capture', scope, distinctId); + final current = _clientForContinuation('capture', scope); if (current == null) return; await _captureProcessed(current, processed, prepared); }); @@ -300,7 +293,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (!_hasName(eventName)) return null; final scope = _clientScope; if (scope == null) return null; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -317,7 +309,7 @@ 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, prepared, ai: true); }); @@ -334,7 +326,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final prepared = _prepare( client, @@ -346,6 +337,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { options: options, ); if (prepared == null) return; + final sessionId = client.getSessionId(); final processed = _runBeforeSend(prepared.event); if (processed == null) { printIfDebug( @@ -353,7 +345,7 @@ 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. @@ -369,8 +361,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}); } @@ -604,7 +597,6 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { if (client.optedOut) return; final scope = _clientScope; if (scope == null) return; - final distinctId = client.getDistinctId(); final exceptionProps = DartExceptionProcessor.processException( error: error, @@ -630,8 +622,7 @@ class PosthogFlutterDesktop extends PosthogFlutterPlatformInterface { return; } - final current = - _clientForContinuation('captureException', scope, distinctId); + final current = _clientForContinuation('captureException', scope); if (current == null) return; await _captureProcessed(current, processed, prepared); }); diff --git a/posthog_flutter/lib/src/posthog_flutter_web_handler.dart b/posthog_flutter/lib/src/posthog_flutter_web_handler.dart index 2772007e..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(); @@ -296,6 +298,27 @@ Future> _reloadFeatureFlags(PostHog? ph) async { } } +/// The user posthog-js would send an event as right now. +String? currentWebDistinctId() => + posthog?.get_distinct_id()?.dartify() as String?; + +/// Whether posthog-js's current user is identified. +bool currentWebUserIdentified() => + posthog?.get_property(r'$user_state'.toJS)?.dartify() == 'identified'; + +/// posthog-js capture options carrying `$set` and `$set_once`. +/// See: https://github.com/PostHog/posthog-js/blob/main/packages/types/src/capture.ts +Map _personCaptureOptions(Map args) { + final userProperties = safeMapConversion(args['userProperties']); + final userPropertiesSetOnce = safeMapConversion( + args['userPropertiesSetOnce'], + ); + return { + if (userProperties.isNotEmpty) '\$set': userProperties, + if (userPropertiesSetOnce.isNotEmpty) '\$set_once': userPropertiesSetOnce, + }; +} + Future handleWebMethodCall(MethodCall call) async { _maybeOverrideSDKInfo(); @@ -338,20 +361,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 +376,12 @@ Future handleWebMethodCall(MethodCall call) async { properties.addAll(_getLocationProperties()); _addAppVersionProperties(properties); - posthog?.capture(stringToJSAny('\$screen'), mapToJSAny(properties), null); + final options = _personCaptureOptions(args); + posthog?.capture( + stringToJSAny('\$screen'), + mapToJSAny(properties), + options.isNotEmpty ? mapToJSAny(options) : null, + ); break; case 'captureLog': final body = args['body'] as String; diff --git a/posthog_flutter/lib/src/utils/call_order.dart b/posthog_flutter/lib/src/utils/call_order.dart index 9dbb430a..42b6af6e 100644 --- a/posthog_flutter/lib/src/utils/call_order.dart +++ b/posthog_flutter/lib/src/utils/call_order.dart @@ -35,8 +35,7 @@ class CallOrder { /// Runs [hook] once every earlier call has been handed over, so it sees /// the state the app left before capturing, then hands its result to - /// [send]. Later calls wait for [send] to finish, so it may itself capture - /// (a beforeSend that renames a `$screen` does). + /// [send]. Later calls wait for [send] to finish. Future event( FutureOr Function() hook, Future Function(E event) send, @@ -62,8 +61,8 @@ class CallOrder { Future Function(E event) send, ) async { final timer = Timer(maxWait, () { - printIfDebug('[PostHog] beforeSend took longer than ' - '${maxWait.inSeconds}s; later calls no longer wait for it.'); + printIfDebug('[PostHog] An event took longer than ' + '${maxWait.inSeconds}s to hand over; later calls no longer wait for it.'); turn.ahead.then((_) => turn.end()); }); try { diff --git a/posthog_flutter/test/posthog_flutter_desktop_test.dart b/posthog_flutter/test/posthog_flutter_desktop_test.dart index bf6d322e..f8972fd8 100644 --- a/posthog_flutter/test/posthog_flutter_desktop_test.dart +++ b/posthog_flutter/test/posthog_flutter_desktop_test.dart @@ -573,6 +573,207 @@ void main() { }); group('beforeSend hook', () { + group('that calls the SDK', () { + test('can capture another event without running forever', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.event); + if (event.event == 'outer') { + platform.capture(eventName: 'inner'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'outer'); + await server.waitForEvent('inner'); + await server.waitForEvent('outer'); + + expect(seen, ['outer', 'inner']); + }); + + final calls = Function(PosthogFlutterDesktop)>{ + 'reset': (platform) => platform.reset(), + 'identify': (platform) => platform.identify(userId: 'user-1'), + 'optOut': (platform) => platform.optOut(), + 'getDistinctId': (platform) => platform.getDistinctId(), + 'getFeatureFlag': (platform) => platform.getFeatureFlag(key: 'flag'), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform + .capture(eventName: 'trigger') + .timeout(const Duration(seconds: 2)); + }); + }); + }); + + for (final (name, call) + in <(String, Future Function(PosthogFlutterDesktop))>[ + ('reset', (platform) => platform.reset()), + ('identify', (platform) => platform.identify(userId: 'user-1')), + ]) { + test('$name inside the hook keeps the event on the earlier user', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') call(platform); + return event; + }, + ]; + platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], firstUser); + expect(await platform.getDistinctId(), isNot(firstUser)); + }); + } + + test('reset inside the hook leaves an identified event person-processed', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + await platform.identify(userId: 'user-1'); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(event['distinct_id'], 'user-1'); + expect(_optionsOf(event), isNot(contains('process_person_profile'))); + }); + + test('identify inside the hook leaves an anonymous event personless', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + + final event = await server.waitForEvent('trigger'); + expect(_optionsOf(event)['process_person_profile'], isFalse); + }); + + test('reset inside the hook keeps the screen from the next user', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') platform.reset(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after reset'); + + final event = await server.waitForEvent('after reset'); + expect(_propertiesOf(event), isNot(contains(r'$screen_name'))); + }); + + test('identify inside the hook keeps the screen for later events', + () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == r'$screen') { + platform.identify(userId: 'user-1'); + } + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.screen(screenName: 'Checkout'); + await platform.capture(eventName: 'after identify'); + + final event = await server.waitForEvent('after identify'); + expect(_propertiesOf(event)[r'$screen_name'], 'Checkout'); + }); + + test('optOut inside the hook drops the event', () async { + final server = await LocalPostHogServer.start(); + late final PosthogFlutterDesktop platform; + final config = configFor(server) + ..beforeSend = [ + (event) { + if (event.event == 'trigger') platform.optOut(); + return event; + }, + ]; + platform = await setUpPlatform(config); + + await platform.capture(eventName: 'trigger'); + await platform.optIn(); + await platform.capture(eventName: 'after'); + await server.waitForEvent('after'); + + expect(server.eventNames, isNot(contains('trigger'))); + }); + + test('calls after a burst of events apply in order', () async { + final server = await LocalPostHogServer.start(); + final config = configFor(server)..beforeSend = [(event) => event]; + final platform = await setUpPlatform(config); + final firstUser = await platform.getDistinctId(); + + final sent = [ + for (var i = 0; i < 100; i++) platform.capture(eventName: 'event $i'), + platform.reset(), + platform.capture(eventName: 'after reset'), + ]; + await Future.wait(sent); + + final last = await server.waitForEvent('event 99'); + expect(last['distinct_id'], firstUser); + final after = await server.waitForEvent('after reset'); + expect(after['distinct_id'], isNot(firstUser)); + }); + test('dropping an event keeps it off the wire', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) @@ -1196,25 +1397,6 @@ void main() { expect(stepMessagesOf(sentinel), isNull); }); - test('are seen by beforeSend, which can remove them', () async { - final server = await LocalPostHogServer.start(); - Object? seen; - final platform = await setUpPlatform(configFor(server) - ..beforeSend = [ - (event) { - seen = event.properties?[r'$exception_steps']; - event.properties?.remove(r'$exception_steps'); - return event; - }, - ]); - await platform.addExceptionStep('step'); - await platform.captureException(error: StateError('error')); - - final event = await server.waitForEvent(r'$exception'); - expect(seen, isA()); - expect(_propertiesOf(event), isNot(contains(r'$exception_steps'))); - }); - test('normalize non-finite step and event properties identically', () async { final server = await LocalPostHogServer.start(); @@ -1278,6 +1460,30 @@ void main() { expect(stepMessagesOf(event), ['custom']); }); + test('are visible to beforeSend, which can remove them', () async { + final server = await LocalPostHogServer.start(); + final seen = []; + final config = configFor(server) + ..beforeSend = [ + (event) { + seen.add(event.properties?.remove(r'$exception_steps')); + return event; + }, + ]; + final platform = await setUpPlatform(config); + + await platform.addExceptionStep('recorded'); + await platform.captureException(error: StateError('removed steps')); + + final event = await server.waitForEvent(r'$exception'); + expect(seen, [ + [ + {r'$message': 'recorded', r'$timestamp': isA()}, + ], + ]); + expect(stepMessagesOf(event), isNull); + }); + test('are not attached while disabled', () async { final server = await LocalPostHogServer.start(); final config = configFor(server) diff --git a/posthog_flutter/test/posthog_flutter_io_test.dart b/posthog_flutter/test/posthog_flutter_io_test.dart index ced1a7f1..d39dca9b 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'; @@ -1329,6 +1331,167 @@ 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); + expect(log.where((c) => c.method == 'buildEvent'), hasLength(1)); + final args = Map.from(log + .singleWhere((c) => c.method == 'sendBuiltEvent') + .arguments as Map); + expect(args['event'], 'renamed'); + expect((args['properties'] as Map)[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('PosthogFlutterIO hook that calls the SDK', () { + Future setUpWith( + PostHogEvent? Function(PostHogEvent event) hook, + ) async { + await posthogFlutterIO + .setup(PostHogConfig('test_project_token', beforeSend: [hook])); + log.clear(); + } + + test('can capture another event without running forever', () async { + final seen = []; + await setUpWith((event) { + seen.add(event.event); + if (event.event == 'outer') { + posthogFlutterIO.capture(eventName: 'inner'); + } + return event; + }); + + await posthogFlutterIO.capture(eventName: 'outer'); + await pumpEventQueue(); + + expect(seen, ['outer', 'inner']); + expect( + log + .where((c) => c.method == 'sendBuiltEvent') + .map((c) => (c.arguments as Map)['event']), + unorderedEquals(['inner', 'outer']), + ); + }); + + final calls = Function(PosthogFlutterIO)>{ + 'reset': (io) => io.reset(), + 'identify': (io) => io.identify(userId: 'user-1'), + 'optOut': (io) => io.optOut(), + 'close': (io) => io.close(), + 'getFeatureFlag': (io) => io.getFeatureFlag(key: 'flag'), + 'getDistinctId': (io) => io.getDistinctId(), + 'isOptOut': (io) => io.isOptOut(), + }; + + calls.forEach((name, call) { + test('$name inside the hook does not deadlock the event', () async { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(channel, (methodCall) async { + log.add(methodCall); + return switch (methodCall.method) { + 'distinctId' => 'user-1', + 'isOptOut' => false, + 'buildEvent' => nativeBuiltEvent(methodCall.arguments as Map), + 'sendBuiltEvent' => (methodCall.arguments as Map)['uuid'], + _ => null, + }; + }); + await setUpWith((event) { + call(posthogFlutterIO); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout') + .timeout(const Duration(seconds: 2)); + await pumpEventQueue(); + + expect(log.map((c) => c.method), contains('sendBuiltEvent')); + }); + }); + + test('an error in unawaited work does not drop the event', () async { + final errors = []; + await runZonedGuarded(() async { + await setUpWith((event) { + Future.error(StateError('late failure')); + return event; + }); + await posthogFlutterIO.capture(eventName: 'checkout'); + await pumpEventQueue(); + }, (error, _) => errors.add(error)); + + expect(errors, hasLength(1)); + expect(log.map((c) => c.method), ['buildEvent', 'sendBuiltEvent']); + }); + + test('a change made after the hook returned is not sent', () async { + await setUpWith((event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }); + + await posthogFlutterIO + .capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + final args = + log.singleWhere((c) => c.method == 'sendBuiltEvent').arguments as Map; + expect(args['properties'], {'plan': 'pro'}); + }); + }); + + group('PosthogFlutterIO calls after a burst of events', () { + test('keep the order the app made them in', () async { + await posthogFlutterIO.setup( + PostHogConfig('test_project_token', beforeSend: [(event) => event])); + log.clear(); + + final sent = >[]; + final expected = []; + for (var i = 0; i < 1000; i++) { + sent.add(posthogFlutterIO.capture(eventName: 'event $i')); + expected.add('event $i'); + if (i % 100 == 99) { + sent.add(posthogFlutterIO.reset()); + expected.add('reset'); + } + } + await Future.wait(sent); + + expect( + log.where((c) => c.method != 'buildEvent').map((c) => + c.method == 'reset' ? 'reset' : (c.arguments as Map)['event']), + expected, + ); + }); + }); + group('PosthogFlutterIO addExceptionStep', () { 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 ba633255..b1bc73cc 100644 --- a/posthog_flutter/test/web_before_send_test.dart +++ b/posthog_flutter/test/web_before_send_test.dart @@ -12,6 +12,9 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); final captures = >[]; + late String distinctId; + late bool optedOut; + late String userState; setUp(() { captures.clear(); @@ -22,9 +25,21 @@ void main() { captures.add({ 'event': event.toDart, 'properties': properties?.dartify(), + 'options': options?.dartify(), }); }).toJS, ); + distinctId = 'first-user'; + fake.setProperty('get_distinct_id'.toJS, (() => distinctId.toJS).toJS); + optedOut = false; + userState = 'anonymous'; + fake.setProperty( + 'get_property'.toJS, + ((JSString name) => name.toDart == r'$user_state' ? userState.toJS : null) + .toJS, + ); + fake.setProperty( + 'has_opted_out_capturing'.toJS, (() => optedOut.toJS).toJS); fake.setProperty( 'captureException'.toJS, ((JSAny? error, JSAny? properties) { @@ -37,6 +52,172 @@ void main() { globalContext.setProperty('posthog'.toJS, fake); }); + group('a hook that changes the user', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'checkout'), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + sends.forEach((name, send) { + test('keeps $name on the earlier user', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await send(web); + + final properties = captures.single['properties'] as Map; + expect(properties['distinct_id'], 'first-user'); + }); + }); + + test('does not bring back the user who opted out', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + optedOut = true; + distinctId = r'$posthog_cookieless'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('does not send the cookieless id after opting in', () async { + distinctId = r'$posthog_cookieless'; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + distinctId = 'next-user'; + return event; + }, + ])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + + test('leaves the user alone when the hook does not change it', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [(e) => e])); + + await web.capture(eventName: 'checkout'); + + expect(captures.single['properties'], isNot(contains('distinct_id'))); + }); + }); + + group('a hook that changes the user drops user properties', () { + final sends = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture( + eventName: 'checkout', + userProperties: {'email': 'a@example.com'}, + userPropertiesSetOnce: {'first': 'yes'}, + ), + 'screen': (web) => web.screen(screenName: 'Cart'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + PostHogConfig hooked(void Function() changeUser) => + PostHogConfig('test_token', beforeSend: [ + (event) { + changeUser(); + return event + ..userProperties = {'email': 'a@example.com'} + ..userPropertiesSetOnce = {'first': 'yes'}; + }, + ]); + + Map sentPersonProperties() { + final capture = captures.single; + final options = capture['options'] as Map? ?? const {}; + final properties = capture['properties'] as Map? ?? const {}; + return { + for (final key in [r'$set', r'$set_once']) + if (options[key] != null) key: options[key], + for (final key in [r'$set', r'$set_once']) + if (properties[key] != null) key: properties[key], + }; + } + + sends.forEach((name, send) { + test('on $name after reset() of an identified user', () async { + userState = 'identified'; + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'next-user'; + userState = 'anonymous'; + })); + + await send(web); + + expect(sentPersonProperties(), isEmpty); + expect((captures.single['properties'] as Map)['distinct_id'], + 'first-user'); + }); + + test('on $name not after identify() of an anonymous user', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked(() { + distinctId = 'user-1'; + userState = 'identified'; + })); + + await send(web); + + expect(sentPersonProperties(), { + r'$set': {'email': 'a@example.com'}, + r'$set_once': {'first': 'yes'}, + }); + }); + }); + }); + + group('a hook that sets user properties without renaming', () { + PostHogConfig hooked() => PostHogConfig('test_token', beforeSend: [ + (event) { + event.userProperties = {'plan': 'pro'}; + event.userPropertiesSetOnce = {'first': 'yes'}; + return event; + }, + ]); + + test('keeps them on a screen', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.screen(screenName: 'Cart'); + + expect(captures.single['event'], r'$screen'); + expect(captures.single['options'], { + r'$set': {'plan': 'pro'}, + r'$set_once': {'first': 'yes'}, + }); + }); + + test('keeps them on an exception', () async { + final web = PosthogFlutterWeb(); + await web.setup(hooked()); + + await web.captureException(error: StateError('boom')); + + final properties = captures.single['properties'] as Map; + expect(properties[r'$set'], {'plan': 'pro'}); + expect(properties[r'$set_once'], {'first': 'yes'}); + }); + }); + test('feature events carry the screen name beforeSend accepted', () async { final web = PosthogFlutterWeb(); await web.setup(PostHogConfig('test_token', beforeSend: [ @@ -113,6 +294,148 @@ void main() { expect(calls, ['getFeatureFlagResult', r'$feature_view', 'reset']); }); + for (final hooked in [false, true]) { + test( + 'feature events read the flag and reach posthog-js before a reset made ' + 'right after them (${hooked ? 'with' : 'without'} beforeSend)', + () async { + final calls = []; + var variant = 'for-the-old-user'; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, JSAny? properties, [JSAny? options]) { + final flagged = properties?.dartify() as Map?; + calls.add('${event.toDart}:${flagged?['feature_flag_variant']}'); + }).toJS, + ); + fake.setProperty( + 'getFeatureFlagResult'.toJS, + ((JSString key, [JSAny? options]) => { + 'key': key.toDart, + 'enabled': true, + 'variant': variant, + }.jsify()).toJS, + ); + fake.setProperty( + 'reset'.toJS, + (([JSAny? a]) { + calls.add('reset'); + variant = 'for-the-new-user'; + }).toJS, + ); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', + beforeSend: [if (hooked) (event) => event])); + + final sent = [ + web.captureFeatureView(flag: 'checkout'), + web.captureFeatureInteraction(flag: 'checkout'), + ]; + await web.reset(); + await Future.wait(sent); + + expect(calls, [ + r'$feature_view:for-the-old-user', + r'$feature_interaction:for-the-old-user', + 'reset', + ]); + }); + } + + group('a hook that renames an event', () { + final renames = Function(PosthogFlutterWeb)>{ + 'capture': (web) => web.capture(eventName: 'original'), + 'screen': (web) => web.screen(screenName: 'Checkout'), + 'captureException': (web) => + web.captureException(error: StateError('boom')), + }; + + renames.forEach((name, send) { + test('$name runs the hook once and keeps its user properties', () async { + var runs = 0; + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + runs++; + event.event = 'renamed'; + event.userProperties = {'source': 'hook'}; + return event; + }, + ])); + + await send(web); + + expect(runs, 1); + expect(captures.single['event'], 'renamed'); + final options = captures.single['options'] as Map; + expect(options[r'$set'], {'source': 'hook'}); + }); + }); + }); + + group('a hook that calls the SDK', () { + test('can capture another event without running forever', () async { + final web = PosthogFlutterWeb(); + final seen = []; + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + seen.add(event.event); + if (event.event == 'outer') web.capture(eventName: 'inner'); + return event; + }, + ])); + + await web.capture(eventName: 'outer'); + + expect(seen, ['outer', 'inner']); + expect(captures.map((c) => c['event']), ['inner', 'outer']); + }); + + test('an unawaited getter inside the hook does not delay the event', + () async { + final calls = []; + final fake = globalContext.getProperty('posthog'.toJS); + fake.setProperty( + 'capture'.toJS, + ((JSString event, [JSAny? a, JSAny? b]) => calls.add(event.toDart)) + .toJS, + ); + fake.setProperty('reset'.toJS, (([JSAny? a]) => calls.add('reset')).toJS); + fake.setProperty('has_opted_out_capturing'.toJS, (() => false.toJS).toJS); + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + web.isOptOut(); + return event; + }, + ])); + + final sent = web.capture(eventName: 'checkout'); + await web.reset(); + await sent; + + expect(calls, ['checkout', 'reset']); + }); + }); + + test('a change made after the hook returned is not sent', () async { + final web = PosthogFlutterWeb(); + await web.setup(PostHogConfig('test_token', beforeSend: [ + (event) { + Future.delayed(Duration.zero, () { + event.properties?['late'] = true; + }); + return event; + }, + ])); + + await web.capture(eventName: 'checkout', properties: {'plan': 'pro'}); + await Future.delayed(const Duration(milliseconds: 10)); + + expect((captures.single['properties'] as Map).containsKey('late'), isFalse); + }); + test('beforeSend null drops capture on web', () async { final web = PosthogFlutterWeb(); await web.setup(