-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathposthog_flutter_web_handler.dart
More file actions
519 lines (453 loc) · 15.1 KB
/
posthog_flutter_web_handler.dart
File metadata and controls
519 lines (453 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// ignore_for_file: avoid_dynamic_calls, avoid_annotating_with_dynamic
import 'dart:js_interop';
import 'dart:js_interop_unsafe';
import 'package:flutter/services.dart';
// Definition of the JS interface for PostHog
@JS()
@staticInterop
class PostHog {}
extension PostHogExtension on PostHog {
external JSAny? identify(
JSAny userId, JSAny properties, JSAny propertiesSetOnce);
external JSAny? capture(JSAny eventName, JSAny? properties, JSAny? options);
external JSAny? alias(JSAny alias);
// ignore: non_constant_identifier_names
external JSAny? get_distinct_id();
external void reset();
external void debug(JSAny debug);
external JSAny? isFeatureEnabled(JSAny key);
external void group(JSAny type, JSAny key, JSAny properties);
external void reloadFeatureFlags();
// ignore: non_constant_identifier_names
external void opt_in_capturing();
// ignore: non_constant_identifier_names
external void opt_out_capturing();
// ignore: non_constant_identifier_names
external bool has_opted_out_capturing();
external JSAny? getFeatureFlag(JSAny key);
external JSAny? getFeatureFlagPayload(JSAny key);
external JSAny? getFeatureFlagResult(JSAny key, [JSAny? options]);
external void register(JSAny properties);
external void unregister(JSAny key);
// ignore: non_constant_identifier_names
external JSAny? get_session_id();
external void onFeatureFlags(JSFunction callback);
}
// Accessing PostHog from the window object
@JS('window.posthog')
external PostHog? get posthog;
@JS('globalThis')
external JSObject get globalThis;
// Conversion functions
JSAny stringToJSAny(String value) {
return value.toJS;
}
JSAny boolToJSAny(bool value) {
return value.toJS;
}
JSAny mapToJSAny(Map<dynamic, dynamic> map) {
return map.jsify() ?? JSObject();
}
// Function for safely converting maps
Map<String, dynamic> safeMapConversion(dynamic mapData) {
if (mapData == null) {
return {};
}
if (mapData is Map) {
return Map<String, dynamic>.from(
mapData.map((key, value) => MapEntry(key.toString(), value)));
}
return {};
}
// Stack frame data structure
class StackFrame {
final String? filename;
final String? function;
final int? lineno;
final int? colno;
final bool inApp;
StackFrame({
this.filename,
this.function,
this.lineno,
this.colno,
this.inApp = true,
});
Map<String, Object?> toMap() {
return {
'filename': filename,
'function': function ?? '<anonymous>',
'lineno': lineno,
'colno': colno,
'in_app': inApp,
};
}
}
// Stack line parser type
typedef StackLineParser = StackFrame? Function(String line, String platform);
// Global regex patterns (compiled once)
final _chromeRegexNoFnName =
RegExp(r'^\s*at\s+(\S+?)\s*:\s*(\d+)\s*:\s*(\d+)\s*$');
final _chromeRegex = RegExp(
r'^\s*at\s+(?:(.+?)\s+)?\((?:address\s+at\s+)?(?:async\s+)?((?:<anonymous>|[-a-z]+:|.*bundle|\/)?.*?)(?::(\d+))?(?::(\d+))?\)?\s*$');
final _chromeEvalRegex = RegExp(r'\((\S*)(?::(\d+))(?::(\d+))\)');
final _geckoRegex = RegExp(
r'^\s*(.*?)(?:\((.*?)\))?(?:^|@)?((?:[-a-z]+)?:\/.*?|\[native code\]|[^@]*(?:bundle|\d+\.js)|\/[\w\-\.\ \/=]+)(?::(\d+))?(?::(\d+))?\s*$');
final _geckoEvalRegex =
RegExp(r'(\S+)\s+line\s+(\d+)(?:\s+>\s+eval\s+line\s+\d+)*\s+>\s+eval');
final _errorWrapperRegex = RegExp(r'\(error: (.*)\)');
final _errorLineRegex = RegExp(r'\S*Error: ');
// Chrome stack line parser
StackFrame? chromeStackLineParser(String line, String platform) {
// Try no function name pattern first
final noFnMatch = _chromeRegexNoFnName.firstMatch(line);
if (noFnMatch != null) {
return StackFrame(
filename: noFnMatch.group(1),
function: '<anonymous>',
lineno: int.tryParse(noFnMatch.group(2) ?? ''),
colno: int.tryParse(noFnMatch.group(3) ?? ''),
);
}
// Try full pattern
final match = _chromeRegex.firstMatch(line);
if (match != null) {
String? filename = match.group(2);
String? functionName = match.group(1);
int? lineno = int.tryParse(match.group(3) ?? '');
int? colno = int.tryParse(match.group(4) ?? '');
// Handle eval cases
if (filename != null && filename.startsWith('eval')) {
final evalMatch = _chromeEvalRegex.firstMatch(filename);
if (evalMatch != null) {
filename = evalMatch.group(1);
lineno = int.tryParse(evalMatch.group(2) ?? '');
colno = int.tryParse(evalMatch.group(3) ?? '');
}
}
// Extract safari extension details
final safariDetails = extractSafariExtensionDetails(
functionName ?? '<anonymous>', filename ?? '');
functionName = safariDetails[0];
filename = safariDetails[1];
return StackFrame(
filename: filename,
function: functionName,
lineno: lineno,
colno: colno,
);
}
return null;
}
// Gecko (Firefox) stack line parser
StackFrame? geckoStackLineParser(String line, String platform) {
final match = _geckoRegex.firstMatch(line);
if (match != null) {
String? filename = match.group(3);
String? functionName = match.group(1);
int? lineno = int.tryParse(match.group(4) ?? '');
int? colno = int.tryParse(match.group(5) ?? '');
// Handle eval cases
if (filename != null && filename.contains(' > eval')) {
final evalMatch = _geckoEvalRegex.firstMatch(filename);
if (evalMatch != null) {
functionName = functionName == '<anonymous>' || functionName == null
? 'eval'
: functionName;
filename = evalMatch.group(1);
lineno = int.tryParse(evalMatch.group(2) ?? '');
colno = null;
}
}
// Extract safari extension details
final safariDetails = extractSafariExtensionDetails(
functionName ?? '<anonymous>', filename ?? '');
functionName = safariDetails[0];
filename = safariDetails[1];
return StackFrame(
filename: filename,
function: functionName,
lineno: lineno,
colno: colno,
);
}
return null;
}
// Extract Safari extension details (ported from JS)
List<String> extractSafariExtensionDetails(
String functionName, String filename) {
final isSafariExtension = filename.contains('safari-extension');
final isSafariWebExtension = filename.contains('safari-web-extension');
if (isSafariExtension || isSafariWebExtension) {
final extractedFunction =
filename.contains('@') ? filename.split('@')[0] : '<anonymous>';
final prefix =
isSafariExtension ? 'safari-extension:' : 'safari-web-extension:';
return [extractedFunction, '$prefix$filename'];
}
return [functionName, filename];
}
// Create stack parser function
List<StackFrame> Function(String, [int]) createStackParser(
String platform, List<StackLineParser> lineParsers) {
return (String stack, [int skipLines = 0]) {
final lines = stack.split('\n');
final frames = <StackFrame>[];
for (int i = skipLines; i < lines.length; i++) {
final line = lines[i];
// Skip lines over 1024 characters
if (line.length > 1024) continue;
// Skip lines that contain webpack error wrappers
final cleanedLine = line.replaceFirst(_errorWrapperRegex, r'$1');
// Skip "Error:" lines
if (cleanedLine.contains(_errorLineRegex)) continue;
// Try each parser
for (final parser in lineParsers) {
final frame = parser(cleanedLine, platform);
if (frame != null) {
frames.add(frame);
break;
}
}
// Limit to 50 frames
if (frames.length >= 50) break;
}
// Reverse and process frames (like the original implementation)
final reversedFrames = frames.reversed.toList();
// Ensure each frame has a filename if possible
for (int i = 0; i < reversedFrames.length; i++) {
if (reversedFrames[i].filename == null && reversedFrames.isNotEmpty) {
reversedFrames[i] = StackFrame(
filename: reversedFrames.last.filename,
function: reversedFrames[i].function,
lineno: reversedFrames[i].lineno,
colno: reversedFrames[i].colno,
inApp: reversedFrames[i].inApp,
);
}
}
return reversedFrames.take(50).toList();
};
}
// Create default stack parser
List<StackFrame> Function(String, [int]) createDefaultStackParser() {
return createStackParser(
'web:javascript', [chromeStackLineParser, geckoStackLineParser]);
}
int _lastKeysCount = 0;
final Set<String> _chunkIdsWithFilenames = {};
final Map<String, String> _filenameToDebugIds = {};
void _buildFilenameToDebugIdMapDart(
Map<dynamic, dynamic> debugIdMap,
List<StackFrame> Function(String, [int]) stackParser,
) {
for (final debugIdMapEntry in debugIdMap.entries) {
final String stackKeyStr = debugIdMapEntry.key.toString();
final String debugIdStr = debugIdMapEntry.value.toString();
final debugIdHasCachedFilename =
_chunkIdsWithFilenames.contains(debugIdStr);
if (!debugIdHasCachedFilename) {
final parsedStack = stackParser(stackKeyStr);
if (parsedStack.isEmpty) continue;
for (final stackFrame in parsedStack) {
final filename = stackFrame.filename;
if (filename != null) {
_filenameToDebugIds[filename] = debugIdStr;
_chunkIdsWithFilenames.add(debugIdStr);
break;
}
}
}
}
}
Map<String, String>? getPosthogChunkIds() {
final debugIdMapJS = globalThis['_posthogChunkIds'];
final debugIdMap = debugIdMapJS?.dartify() as Map<String, Object>?;
if (debugIdMap == null) {
return null;
}
// Use our pure Dart implementation of createDefaultStackParser
final stackParser = createDefaultStackParser();
if (debugIdMap.keys.length != _lastKeysCount) {
_buildFilenameToDebugIdMapDart(
debugIdMap,
stackParser,
);
_lastKeysCount = debugIdMap.keys.length;
}
return _filenameToDebugIds;
}
Future<dynamic> handleWebMethodCall(MethodCall call) async {
final args = call.arguments;
switch (call.method) {
case 'setup':
// not supported on Web
break;
case 'identify':
final userId = args['userId'] as String;
final userProperties = safeMapConversion(args['userProperties']);
final userPropertiesSetOnce =
safeMapConversion(args['userPropertiesSetOnce']);
posthog?.identify(
stringToJSAny(userId),
mapToJSAny(userProperties),
mapToJSAny(userPropertiesSetOnce),
);
break;
case 'capture':
final eventName = args['eventName'] as String;
final properties = safeMapConversion(args['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 = <String, Object>{};
if (userProperties.isNotEmpty) {
options['\$set'] = userProperties;
}
if (userPropertiesSetOnce.isNotEmpty) {
options['\$set_once'] = userPropertiesSetOnce;
}
posthog?.capture(
stringToJSAny(eventName),
properties.isNotEmpty ? mapToJSAny(properties) : null,
options.isNotEmpty ? mapToJSAny(options) : null,
);
break;
case 'screen':
final screenName = args['screenName'] as String;
final properties = safeMapConversion(args['properties']);
properties['\$screen_name'] = screenName;
posthog?.capture(
stringToJSAny('\$screen'),
mapToJSAny(properties),
null,
);
break;
case 'alias':
final alias = args['alias'] as String;
posthog?.alias(
stringToJSAny(alias),
);
break;
case 'distinctId':
final distinctId = posthog?.get_distinct_id();
return distinctId?.dartify() as String?;
case 'reset':
posthog?.reset();
break;
case 'debug':
final enabled = args['debug'] as bool;
posthog?.debug(boolToJSAny(enabled));
break;
case 'isFeatureEnabled':
final key = args['key'] as String;
final isFeatureEnabled = posthog
?.isFeatureEnabled(
stringToJSAny(key),
)
?.dartify() as bool? ??
false;
return isFeatureEnabled;
case 'group':
final groupType = args['groupType'] as String;
final groupKey = args['groupKey'] as String;
final groupProperties = safeMapConversion(args['groupProperties']);
posthog?.group(
stringToJSAny(groupType),
stringToJSAny(groupKey),
mapToJSAny(groupProperties),
);
break;
case 'reloadFeatureFlags':
posthog?.reloadFeatureFlags();
break;
case 'enable':
posthog?.opt_in_capturing();
break;
case 'disable':
posthog?.opt_out_capturing();
break;
case 'isOptOut':
return posthog?.has_opted_out_capturing() ?? true;
case 'getFeatureFlag':
final key = args['key'] as String;
final featureFlag = posthog?.getFeatureFlag(
stringToJSAny(key),
);
return featureFlag?.dartify();
case 'getFeatureFlagPayload':
final key = args['key'] as String;
final featureFlag = posthog?.getFeatureFlagPayload(
stringToJSAny(key),
);
return featureFlag?.dartify();
case 'getFeatureFlagResult':
final key = args['key'] as String;
final sendEvent = args['sendEvent'] as bool? ?? true;
final result = posthog?.getFeatureFlagResult(
stringToJSAny(key),
{'send_event': sendEvent}.jsify(),
);
return result?.dartify();
case 'register':
final key = args['key'] as String;
final value = args['value'];
final properties = {key: value};
posthog?.register(
mapToJSAny(properties),
);
break;
case 'unregister':
final key = args['key'] as String;
posthog?.unregister(
stringToJSAny(key),
);
break;
case 'getSessionId':
final sessionId = posthog?.get_session_id()?.dartify() as String?;
if (sessionId?.isEmpty == true) return null;
return sessionId;
case 'flush':
// not supported on Web
// analytics.callMethod('flush');
break;
case 'close':
// not supported on Web
// analytics.callMethod('close');
break;
case 'sendMetaEvent':
// not supported on Web
// Flutter Web uses the JS SDK for Session replay
break;
case 'sendFullSnapshot':
// not supported on Web
// Flutter Web uses the JS SDK for Session replay
break;
case 'isSessionReplayActive':
// not supported on Web
// Flutter Web uses the JS SDK for Session replay
return false;
case 'openUrl':
// not supported on Web
break;
case 'surveyAction':
// not supported on Web
break;
case 'captureException':
final properties = safeMapConversion(args['properties']);
posthog?.capture(
stringToJSAny('\$exception'),
mapToJSAny(properties),
null,
);
break;
default:
throw PlatformException(
code: 'Unimplemented',
details:
"The posthog plugin for web doesn't implement the method '${call.method}'",
);
}
}