posthog-react-native 1.1.4 → 2.0.0-alpha8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +9 -0
  2. package/lib/index.cjs.js +1761 -0
  3. package/lib/index.cjs.js.map +1 -0
  4. package/lib/index.d.ts +211 -0
  5. package/lib/index.esm.js +1725 -0
  6. package/lib/index.esm.js.map +1 -0
  7. package/lib/node_modules/tslib/tslib.es6.d.ts +35 -0
  8. package/lib/posthog-core/src/eventemitter.d.ts +8 -0
  9. package/lib/posthog-core/src/index.d.ts +84 -0
  10. package/lib/posthog-core/src/lz-string.d.ts +8 -0
  11. package/lib/posthog-core/src/types.d.ts +68 -0
  12. package/lib/posthog-core/src/utils.d.ts +13 -0
  13. package/lib/posthog-react-native/index.d.ts +10 -0
  14. package/lib/posthog-react-native/src/PostHogProvider.d.ts +13 -0
  15. package/lib/posthog-react-native/src/PosthogContext.d.ts +5 -0
  16. package/lib/posthog-react-native/src/autocapture.d.ts +3 -0
  17. package/lib/posthog-react-native/src/hooks/useFeatureFlag.d.ts +1 -0
  18. package/lib/posthog-react-native/src/hooks/useFeatureFlags.d.ts +3 -0
  19. package/lib/posthog-react-native/src/hooks/useLifecycleTracker.d.ts +2 -0
  20. package/lib/posthog-react-native/src/hooks/useNavigationTracker.d.ts +5 -0
  21. package/lib/posthog-react-native/src/hooks/usePostHog.d.ts +2 -0
  22. package/lib/posthog-react-native/src/legacy.d.ts +4 -0
  23. package/lib/posthog-react-native/src/optional-imports.d.ts +6 -0
  24. package/lib/posthog-react-native/src/posthog-rn.d.ts +14 -0
  25. package/lib/posthog-react-native/src/storage.d.ts +8 -0
  26. package/lib/posthog-react-native/src/types.d.ts +12 -0
  27. package/package.json +35 -51
  28. package/RNPostHog.podspec +0 -21
  29. package/android/build.gradle +0 -46
  30. package/android/src/main/AndroidManifest.xml +0 -1
  31. package/android/src/main/java/com/posthog/reactnative/core/RNPostHogModule.kt +0 -251
  32. package/android/src/main/java/com/posthog/reactnative/core/RNPostHogPackage.kt +0 -44
  33. package/build/cjs/__mocks__/bridge.d.ts +0 -14
  34. package/build/cjs/__mocks__/bridge.js +0 -15
  35. package/build/cjs/__mocks__/bridge.js.map +0 -1
  36. package/build/cjs/__tests__/bridge.spec.d.ts +0 -1
  37. package/build/cjs/__tests__/bridge.spec.js +0 -19
  38. package/build/cjs/__tests__/bridge.spec.js.map +0 -1
  39. package/build/cjs/__tests__/configuration.spec.d.ts +0 -1
  40. package/build/cjs/__tests__/configuration.spec.js +0 -131
  41. package/build/cjs/__tests__/configuration.spec.js.map +0 -1
  42. package/build/cjs/__tests__/index.spec.d.ts +0 -1
  43. package/build/cjs/__tests__/index.spec.js +0 -9
  44. package/build/cjs/__tests__/index.spec.js.map +0 -1
  45. package/build/cjs/__tests__/posthog.spec.d.ts +0 -1
  46. package/build/cjs/__tests__/posthog.spec.js +0 -193
  47. package/build/cjs/__tests__/posthog.spec.js.map +0 -1
  48. package/build/cjs/bridge.d.ts +0 -50
  49. package/build/cjs/bridge.js +0 -9
  50. package/build/cjs/bridge.js.map +0 -1
  51. package/build/cjs/configuration.d.ts +0 -3
  52. package/build/cjs/configuration.js +0 -94
  53. package/build/cjs/configuration.js.map +0 -1
  54. package/build/cjs/index.d.ts +0 -5
  55. package/build/cjs/index.js +0 -6
  56. package/build/cjs/index.js.map +0 -1
  57. package/build/cjs/make-pkg.d.ts +0 -1
  58. package/build/cjs/make-pkg.js +0 -5
  59. package/build/cjs/make-pkg.js.map +0 -1
  60. package/build/cjs/middleware.d.ts +0 -41
  61. package/build/cjs/middleware.js +0 -114
  62. package/build/cjs/middleware.js.map +0 -1
  63. package/build/cjs/posthog.d.ts +0 -228
  64. package/build/cjs/posthog.js +0 -309
  65. package/build/cjs/posthog.js.map +0 -1
  66. package/build/cjs/utils.d.ts +0 -1
  67. package/build/cjs/utils.js +0 -7
  68. package/build/cjs/utils.js.map +0 -1
  69. package/build/cjs/wrapper.d.ts +0 -22
  70. package/build/cjs/wrapper.js +0 -114
  71. package/build/cjs/wrapper.js.map +0 -1
  72. package/build/esm/__mocks__/bridge.d.ts +0 -14
  73. package/build/esm/__mocks__/bridge.js +0 -13
  74. package/build/esm/__mocks__/bridge.js.map +0 -1
  75. package/build/esm/__tests__/bridge.spec.d.ts +0 -1
  76. package/build/esm/__tests__/bridge.spec.js +0 -19
  77. package/build/esm/__tests__/bridge.spec.js.map +0 -1
  78. package/build/esm/__tests__/configuration.spec.d.ts +0 -1
  79. package/build/esm/__tests__/configuration.spec.js +0 -129
  80. package/build/esm/__tests__/configuration.spec.js.map +0 -1
  81. package/build/esm/__tests__/index.spec.d.ts +0 -1
  82. package/build/esm/__tests__/index.spec.js +0 -7
  83. package/build/esm/__tests__/index.spec.js.map +0 -1
  84. package/build/esm/__tests__/posthog.spec.d.ts +0 -1
  85. package/build/esm/__tests__/posthog.spec.js +0 -191
  86. package/build/esm/__tests__/posthog.spec.js.map +0 -1
  87. package/build/esm/bridge.d.ts +0 -50
  88. package/build/esm/bridge.js +0 -7
  89. package/build/esm/bridge.js.map +0 -1
  90. package/build/esm/configuration.d.ts +0 -3
  91. package/build/esm/configuration.js +0 -92
  92. package/build/esm/configuration.js.map +0 -1
  93. package/build/esm/index.d.ts +0 -5
  94. package/build/esm/index.js +0 -4
  95. package/build/esm/index.js.map +0 -1
  96. package/build/esm/make-pkg.d.ts +0 -1
  97. package/build/esm/make-pkg.js +0 -3
  98. package/build/esm/make-pkg.js.map +0 -1
  99. package/build/esm/middleware.d.ts +0 -41
  100. package/build/esm/middleware.js +0 -112
  101. package/build/esm/middleware.js.map +0 -1
  102. package/build/esm/posthog.d.ts +0 -228
  103. package/build/esm/posthog.js +0 -307
  104. package/build/esm/posthog.js.map +0 -1
  105. package/build/esm/utils.d.ts +0 -1
  106. package/build/esm/utils.js +0 -4
  107. package/build/esm/utils.js.map +0 -1
  108. package/build/esm/wrapper.d.ts +0 -22
  109. package/build/esm/wrapper.js +0 -112
  110. package/build/esm/wrapper.js.map +0 -1
  111. package/build/package.json +0 -3
  112. package/ios/RNPostHog/RNPostHog.h +0 -9
  113. package/ios/RNPostHog/RNPostHog.m +0 -128
  114. package/ios/RNPostHog.xcodeproj/project.pbxproj +0 -336
  115. package/ios/RNPostHog.xcodeproj/project.xcworkspace/contents.xcworkspacedata +0 -7
  116. package/src/__mocks__/bridge.ts +0 -12
  117. package/src/__tests__/bridge.spec.ts +0 -23
  118. package/src/__tests__/configuration.spec.ts +0 -79
  119. package/src/__tests__/index.spec.ts +0 -7
  120. package/src/__tests__/posthog.spec.ts +0 -108
  121. package/src/bridge.ts +0 -61
  122. package/src/configuration.ts +0 -61
  123. package/src/index.ts +0 -5
  124. package/src/make-pkg.ts +0 -3
  125. package/src/middleware.ts +0 -128
  126. package/src/modules.d.ts +0 -2
  127. package/src/posthog.ts +0 -305
  128. package/src/utils.ts +0 -3
  129. package/src/wrapper.ts +0 -61
@@ -0,0 +1,1725 @@
1
+ import { Platform, Dimensions, AppState, View } from 'react-native';
2
+ import * as ExpoApplication from 'expo-application';
3
+ import * as ExpoDevice from 'expo-device';
4
+ import * as FileSystem from 'expo-file-system';
5
+ import React, { useRef, useEffect, useState, useCallback } from 'react';
6
+
7
+ /******************************************************************************
8
+ Copyright (c) Microsoft Corporation.
9
+
10
+ Permission to use, copy, modify, and/or distribute this software for any
11
+ purpose with or without fee is hereby granted.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
14
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
15
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
16
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
17
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
18
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
19
+ PERFORMANCE OF THIS SOFTWARE.
20
+ ***************************************************************************** */
21
+ /* global Reflect, Promise */
22
+ var extendStatics = function (d, b) {
23
+ extendStatics = Object.setPrototypeOf ||
24
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
25
+ function (d, b) { for (var p in b)
26
+ if (Object.prototype.hasOwnProperty.call(b, p))
27
+ d[p] = b[p]; };
28
+ return extendStatics(d, b);
29
+ };
30
+ function __extends(d, b) {
31
+ if (typeof b !== "function" && b !== null)
32
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
33
+ extendStatics(d, b);
34
+ function __() { this.constructor = d; }
35
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
36
+ }
37
+ var __assign = function () {
38
+ __assign = Object.assign || function __assign(t) {
39
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
40
+ s = arguments[i];
41
+ for (var p in s)
42
+ if (Object.prototype.hasOwnProperty.call(s, p))
43
+ t[p] = s[p];
44
+ }
45
+ return t;
46
+ };
47
+ return __assign.apply(this, arguments);
48
+ };
49
+ function __awaiter(thisArg, _arguments, P, generator) {
50
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
51
+ return new (P || (P = Promise))(function (resolve, reject) {
52
+ function fulfilled(value) { try {
53
+ step(generator.next(value));
54
+ }
55
+ catch (e) {
56
+ reject(e);
57
+ } }
58
+ function rejected(value) { try {
59
+ step(generator["throw"](value));
60
+ }
61
+ catch (e) {
62
+ reject(e);
63
+ } }
64
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
65
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
66
+ });
67
+ }
68
+ function __generator(thisArg, body) {
69
+ var _ = { label: 0, sent: function () { if (t[0] & 1)
70
+ throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
71
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
72
+ function verb(n) { return function (v) { return step([n, v]); }; }
73
+ function step(op) {
74
+ if (f)
75
+ throw new TypeError("Generator is already executing.");
76
+ while (_)
77
+ try {
78
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
79
+ return t;
80
+ if (y = 0, t)
81
+ op = [op[0] & 2, t.value];
82
+ switch (op[0]) {
83
+ case 0:
84
+ case 1:
85
+ t = op;
86
+ break;
87
+ case 4:
88
+ _.label++;
89
+ return { value: op[1], done: false };
90
+ case 5:
91
+ _.label++;
92
+ y = op[1];
93
+ op = [0];
94
+ continue;
95
+ case 7:
96
+ op = _.ops.pop();
97
+ _.trys.pop();
98
+ continue;
99
+ default:
100
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
101
+ _ = 0;
102
+ continue;
103
+ }
104
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
105
+ _.label = op[1];
106
+ break;
107
+ }
108
+ if (op[0] === 6 && _.label < t[1]) {
109
+ _.label = t[1];
110
+ t = op;
111
+ break;
112
+ }
113
+ if (t && _.label < t[2]) {
114
+ _.label = t[2];
115
+ _.ops.push(op);
116
+ break;
117
+ }
118
+ if (t[2])
119
+ _.ops.pop();
120
+ _.trys.pop();
121
+ continue;
122
+ }
123
+ op = body.call(thisArg, _);
124
+ }
125
+ catch (e) {
126
+ op = [6, e];
127
+ y = 0;
128
+ }
129
+ finally {
130
+ f = t = 0;
131
+ }
132
+ if (op[0] & 5)
133
+ throw op[1];
134
+ return { value: op[0] ? op[1] : void 0, done: true };
135
+ }
136
+ }
137
+
138
+ var PostHogPersistedProperty;
139
+ (function (PostHogPersistedProperty) {
140
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
141
+ PostHogPersistedProperty["Props"] = "props";
142
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
143
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
144
+ PostHogPersistedProperty["Queue"] = "queue";
145
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
146
+ PostHogPersistedProperty["SessionId"] = "session_id";
147
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
148
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
149
+
150
+ function assert(truthyValue, message) {
151
+ if (!truthyValue) {
152
+ throw new Error(message);
153
+ }
154
+ }
155
+ function removeTrailingSlash(url) {
156
+ return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
157
+ }
158
+ function retriable(fn, props) {
159
+ if (props === void 0) { props = {}; }
160
+ return __awaiter(this, void 0, void 0, function () {
161
+ var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
162
+ return __generator(this, function (_d) {
163
+ switch (_d.label) {
164
+ case 0:
165
+ _a = props.retryCount, retryCount = _a === void 0 ? 3 : _a, _b = props.retryDelay, retryDelay = _b === void 0 ? 1000 : _b, _c = props.retryCheck, retryCheck = _c === void 0 ? function () { return true; } : _c;
166
+ lastError = null;
167
+ i = 0;
168
+ _d.label = 1;
169
+ case 1:
170
+ if (!(i < retryCount + 1)) return [3 /*break*/, 8];
171
+ _d.label = 2;
172
+ case 2:
173
+ _d.trys.push([2, 4, , 5]);
174
+ return [4 /*yield*/, fn()];
175
+ case 3:
176
+ res = _d.sent();
177
+ return [2 /*return*/, res];
178
+ case 4:
179
+ e_1 = _d.sent();
180
+ lastError = e_1;
181
+ if (!retryCheck(e_1)) {
182
+ throw e_1;
183
+ }
184
+ return [3 /*break*/, 5];
185
+ case 5: return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
186
+ case 6:
187
+ _d.sent();
188
+ _d.label = 7;
189
+ case 7:
190
+ i++;
191
+ return [3 /*break*/, 1];
192
+ case 8: throw lastError;
193
+ }
194
+ });
195
+ });
196
+ }
197
+ // https://stackoverflow.com/a/8809472
198
+ function generateUUID(globalThis) {
199
+ // Public Domain/MIT
200
+ var d = new Date().getTime(); //Timestamp
201
+ var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
202
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
203
+ var r = Math.random() * 16; //random number between 0 and 16
204
+ if (d > 0) {
205
+ //Use timestamp until depleted
206
+ r = (d + r) % 16 | 0;
207
+ d = Math.floor(d / 16);
208
+ }
209
+ else {
210
+ //Use microseconds since page-load if supported
211
+ r = (d2 + r) % 16 | 0;
212
+ d2 = Math.floor(d2 / 16);
213
+ }
214
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
215
+ });
216
+ }
217
+ function currentTimestamp() {
218
+ return new Date().getTime();
219
+ }
220
+ function currentISOTime() {
221
+ return new Date().toISOString();
222
+ }
223
+ function safeSetTimeout(fn, timeout) {
224
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
225
+ // rather than setImmediate.
226
+ var t = setTimeout(fn, timeout);
227
+ // We unref if available to prevent Node.js hanging on exit
228
+ (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
229
+ return t;
230
+ }
231
+
232
+ // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
233
+ // This work is free. You can redistribute it and/or modify it
234
+ // under the terms of the WTFPL, Version 2
235
+ // For more information see LICENSE.txt or http://www.wtfpl.net/
236
+ //
237
+ // For more information, the home page:
238
+ // http://pieroxy.net/blog/pages/lz-string/testing.html
239
+ //
240
+ // LZ-based compression algorithm, version 1.4.4
241
+ // private property
242
+ var f = String.fromCharCode;
243
+ var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
244
+ var baseReverseDic = {};
245
+ function getBaseValue(alphabet, character) {
246
+ if (!baseReverseDic[alphabet]) {
247
+ baseReverseDic[alphabet] = {};
248
+ for (var i = 0; i < alphabet.length; i++) {
249
+ baseReverseDic[alphabet][alphabet.charAt(i)] = i;
250
+ }
251
+ }
252
+ return baseReverseDic[alphabet][character];
253
+ }
254
+ var LZString = {
255
+ compressToBase64: function (input) {
256
+ if (input == null) {
257
+ return '';
258
+ }
259
+ var res = LZString._compress(input, 6, function (a) {
260
+ return keyStrBase64.charAt(a);
261
+ });
262
+ switch (res.length % 4 // To produce valid Base64
263
+ ) {
264
+ default: // When could this happen ?
265
+ case 0:
266
+ return res;
267
+ case 1:
268
+ return res + '===';
269
+ case 2:
270
+ return res + '==';
271
+ case 3:
272
+ return res + '=';
273
+ }
274
+ },
275
+ decompressFromBase64: function (input) {
276
+ if (input == null) {
277
+ return '';
278
+ }
279
+ if (input == '') {
280
+ return null;
281
+ }
282
+ return LZString._decompress(input.length, 32, function (index) {
283
+ return getBaseValue(keyStrBase64, input.charAt(index));
284
+ });
285
+ },
286
+ compress: function (uncompressed) {
287
+ return LZString._compress(uncompressed, 16, function (a) {
288
+ return f(a);
289
+ });
290
+ },
291
+ _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
292
+ if (uncompressed == null) {
293
+ return '';
294
+ }
295
+ var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
296
+ var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
297
+ context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
298
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
299
+ context_c = uncompressed.charAt(ii);
300
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
301
+ context_dictionary[context_c] = context_dictSize++;
302
+ context_dictionaryToCreate[context_c] = true;
303
+ }
304
+ context_wc = context_w + context_c;
305
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
306
+ context_w = context_wc;
307
+ }
308
+ else {
309
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
310
+ if (context_w.charCodeAt(0) < 256) {
311
+ for (i = 0; i < context_numBits; i++) {
312
+ context_data_val = context_data_val << 1;
313
+ if (context_data_position == bitsPerChar - 1) {
314
+ context_data_position = 0;
315
+ context_data.push(getCharFromInt(context_data_val));
316
+ context_data_val = 0;
317
+ }
318
+ else {
319
+ context_data_position++;
320
+ }
321
+ }
322
+ value = context_w.charCodeAt(0);
323
+ for (i = 0; i < 8; i++) {
324
+ context_data_val = (context_data_val << 1) | (value & 1);
325
+ if (context_data_position == bitsPerChar - 1) {
326
+ context_data_position = 0;
327
+ context_data.push(getCharFromInt(context_data_val));
328
+ context_data_val = 0;
329
+ }
330
+ else {
331
+ context_data_position++;
332
+ }
333
+ value = value >> 1;
334
+ }
335
+ }
336
+ else {
337
+ value = 1;
338
+ for (i = 0; i < context_numBits; i++) {
339
+ context_data_val = (context_data_val << 1) | value;
340
+ if (context_data_position == bitsPerChar - 1) {
341
+ context_data_position = 0;
342
+ context_data.push(getCharFromInt(context_data_val));
343
+ context_data_val = 0;
344
+ }
345
+ else {
346
+ context_data_position++;
347
+ }
348
+ value = 0;
349
+ }
350
+ value = context_w.charCodeAt(0);
351
+ for (i = 0; i < 16; i++) {
352
+ context_data_val = (context_data_val << 1) | (value & 1);
353
+ if (context_data_position == bitsPerChar - 1) {
354
+ context_data_position = 0;
355
+ context_data.push(getCharFromInt(context_data_val));
356
+ context_data_val = 0;
357
+ }
358
+ else {
359
+ context_data_position++;
360
+ }
361
+ value = value >> 1;
362
+ }
363
+ }
364
+ context_enlargeIn--;
365
+ if (context_enlargeIn == 0) {
366
+ context_enlargeIn = Math.pow(2, context_numBits);
367
+ context_numBits++;
368
+ }
369
+ delete context_dictionaryToCreate[context_w];
370
+ }
371
+ else {
372
+ value = context_dictionary[context_w];
373
+ for (i = 0; i < context_numBits; i++) {
374
+ context_data_val = (context_data_val << 1) | (value & 1);
375
+ if (context_data_position == bitsPerChar - 1) {
376
+ context_data_position = 0;
377
+ context_data.push(getCharFromInt(context_data_val));
378
+ context_data_val = 0;
379
+ }
380
+ else {
381
+ context_data_position++;
382
+ }
383
+ value = value >> 1;
384
+ }
385
+ }
386
+ context_enlargeIn--;
387
+ if (context_enlargeIn == 0) {
388
+ context_enlargeIn = Math.pow(2, context_numBits);
389
+ context_numBits++;
390
+ }
391
+ // Add wc to the dictionary.
392
+ context_dictionary[context_wc] = context_dictSize++;
393
+ context_w = String(context_c);
394
+ }
395
+ }
396
+ // Output the code for w.
397
+ if (context_w !== '') {
398
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
399
+ if (context_w.charCodeAt(0) < 256) {
400
+ for (i = 0; i < context_numBits; i++) {
401
+ context_data_val = context_data_val << 1;
402
+ if (context_data_position == bitsPerChar - 1) {
403
+ context_data_position = 0;
404
+ context_data.push(getCharFromInt(context_data_val));
405
+ context_data_val = 0;
406
+ }
407
+ else {
408
+ context_data_position++;
409
+ }
410
+ }
411
+ value = context_w.charCodeAt(0);
412
+ for (i = 0; i < 8; i++) {
413
+ context_data_val = (context_data_val << 1) | (value & 1);
414
+ if (context_data_position == bitsPerChar - 1) {
415
+ context_data_position = 0;
416
+ context_data.push(getCharFromInt(context_data_val));
417
+ context_data_val = 0;
418
+ }
419
+ else {
420
+ context_data_position++;
421
+ }
422
+ value = value >> 1;
423
+ }
424
+ }
425
+ else {
426
+ value = 1;
427
+ for (i = 0; i < context_numBits; i++) {
428
+ context_data_val = (context_data_val << 1) | value;
429
+ if (context_data_position == bitsPerChar - 1) {
430
+ context_data_position = 0;
431
+ context_data.push(getCharFromInt(context_data_val));
432
+ context_data_val = 0;
433
+ }
434
+ else {
435
+ context_data_position++;
436
+ }
437
+ value = 0;
438
+ }
439
+ value = context_w.charCodeAt(0);
440
+ for (i = 0; i < 16; i++) {
441
+ context_data_val = (context_data_val << 1) | (value & 1);
442
+ if (context_data_position == bitsPerChar - 1) {
443
+ context_data_position = 0;
444
+ context_data.push(getCharFromInt(context_data_val));
445
+ context_data_val = 0;
446
+ }
447
+ else {
448
+ context_data_position++;
449
+ }
450
+ value = value >> 1;
451
+ }
452
+ }
453
+ context_enlargeIn--;
454
+ if (context_enlargeIn == 0) {
455
+ context_enlargeIn = Math.pow(2, context_numBits);
456
+ context_numBits++;
457
+ }
458
+ delete context_dictionaryToCreate[context_w];
459
+ }
460
+ else {
461
+ value = context_dictionary[context_w];
462
+ for (i = 0; i < context_numBits; i++) {
463
+ context_data_val = (context_data_val << 1) | (value & 1);
464
+ if (context_data_position == bitsPerChar - 1) {
465
+ context_data_position = 0;
466
+ context_data.push(getCharFromInt(context_data_val));
467
+ context_data_val = 0;
468
+ }
469
+ else {
470
+ context_data_position++;
471
+ }
472
+ value = value >> 1;
473
+ }
474
+ }
475
+ context_enlargeIn--;
476
+ if (context_enlargeIn == 0) {
477
+ context_enlargeIn = Math.pow(2, context_numBits);
478
+ context_numBits++;
479
+ }
480
+ }
481
+ // Mark the end of the stream
482
+ value = 2;
483
+ for (i = 0; i < context_numBits; i++) {
484
+ context_data_val = (context_data_val << 1) | (value & 1);
485
+ if (context_data_position == bitsPerChar - 1) {
486
+ context_data_position = 0;
487
+ context_data.push(getCharFromInt(context_data_val));
488
+ context_data_val = 0;
489
+ }
490
+ else {
491
+ context_data_position++;
492
+ }
493
+ value = value >> 1;
494
+ }
495
+ // Flush the last char
496
+ while (true) {
497
+ context_data_val = context_data_val << 1;
498
+ if (context_data_position == bitsPerChar - 1) {
499
+ context_data.push(getCharFromInt(context_data_val));
500
+ break;
501
+ }
502
+ else {
503
+ context_data_position++;
504
+ }
505
+ }
506
+ return context_data.join('');
507
+ },
508
+ decompress: function (compressed) {
509
+ if (compressed == null) {
510
+ return '';
511
+ }
512
+ if (compressed == '') {
513
+ return null;
514
+ }
515
+ return LZString._decompress(compressed.length, 32768, function (index) {
516
+ return compressed.charCodeAt(index);
517
+ });
518
+ },
519
+ _decompress: function (length, resetValue, getNextValue) {
520
+ var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
521
+ var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
522
+ for (i = 0; i < 3; i += 1) {
523
+ dictionary[i] = i;
524
+ }
525
+ bits = 0;
526
+ maxpower = Math.pow(2, 2);
527
+ power = 1;
528
+ while (power != maxpower) {
529
+ resb = data.val & data.position;
530
+ data.position >>= 1;
531
+ if (data.position == 0) {
532
+ data.position = resetValue;
533
+ data.val = getNextValue(data.index++);
534
+ }
535
+ bits |= (resb > 0 ? 1 : 0) * power;
536
+ power <<= 1;
537
+ }
538
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
539
+ switch ((bits)) {
540
+ case 0:
541
+ bits = 0;
542
+ maxpower = Math.pow(2, 8);
543
+ power = 1;
544
+ while (power != maxpower) {
545
+ resb = data.val & data.position;
546
+ data.position >>= 1;
547
+ if (data.position == 0) {
548
+ data.position = resetValue;
549
+ data.val = getNextValue(data.index++);
550
+ }
551
+ bits |= (resb > 0 ? 1 : 0) * power;
552
+ power <<= 1;
553
+ }
554
+ c = f(bits);
555
+ break;
556
+ case 1:
557
+ bits = 0;
558
+ maxpower = Math.pow(2, 16);
559
+ power = 1;
560
+ while (power != maxpower) {
561
+ resb = data.val & data.position;
562
+ data.position >>= 1;
563
+ if (data.position == 0) {
564
+ data.position = resetValue;
565
+ data.val = getNextValue(data.index++);
566
+ }
567
+ bits |= (resb > 0 ? 1 : 0) * power;
568
+ power <<= 1;
569
+ }
570
+ c = f(bits);
571
+ break;
572
+ case 2:
573
+ return '';
574
+ }
575
+ dictionary[3] = c;
576
+ w = c;
577
+ result.push(c);
578
+ while (true) {
579
+ if (data.index > length) {
580
+ return '';
581
+ }
582
+ bits = 0;
583
+ maxpower = Math.pow(2, numBits);
584
+ power = 1;
585
+ while (power != maxpower) {
586
+ resb = data.val & data.position;
587
+ data.position >>= 1;
588
+ if (data.position == 0) {
589
+ data.position = resetValue;
590
+ data.val = getNextValue(data.index++);
591
+ }
592
+ bits |= (resb > 0 ? 1 : 0) * power;
593
+ power <<= 1;
594
+ }
595
+ switch ((c = bits)) {
596
+ case 0:
597
+ bits = 0;
598
+ maxpower = Math.pow(2, 8);
599
+ power = 1;
600
+ while (power != maxpower) {
601
+ resb = data.val & data.position;
602
+ data.position >>= 1;
603
+ if (data.position == 0) {
604
+ data.position = resetValue;
605
+ data.val = getNextValue(data.index++);
606
+ }
607
+ bits |= (resb > 0 ? 1 : 0) * power;
608
+ power <<= 1;
609
+ }
610
+ dictionary[dictSize++] = f(bits);
611
+ c = dictSize - 1;
612
+ enlargeIn--;
613
+ break;
614
+ case 1:
615
+ bits = 0;
616
+ maxpower = Math.pow(2, 16);
617
+ power = 1;
618
+ while (power != maxpower) {
619
+ resb = data.val & data.position;
620
+ data.position >>= 1;
621
+ if (data.position == 0) {
622
+ data.position = resetValue;
623
+ data.val = getNextValue(data.index++);
624
+ }
625
+ bits |= (resb > 0 ? 1 : 0) * power;
626
+ power <<= 1;
627
+ }
628
+ dictionary[dictSize++] = f(bits);
629
+ c = dictSize - 1;
630
+ enlargeIn--;
631
+ break;
632
+ case 2:
633
+ return result.join('');
634
+ }
635
+ if (enlargeIn == 0) {
636
+ enlargeIn = Math.pow(2, numBits);
637
+ numBits++;
638
+ }
639
+ if (dictionary[c]) {
640
+ entry = dictionary[c];
641
+ }
642
+ else {
643
+ if (c === dictSize) {
644
+ entry = w + w.charAt(0);
645
+ }
646
+ else {
647
+ return null;
648
+ }
649
+ }
650
+ result.push(entry);
651
+ // Add w+entry[0] to the dictionary.
652
+ dictionary[dictSize++] = w + entry.charAt(0);
653
+ enlargeIn--;
654
+ w = entry;
655
+ if (enlargeIn == 0) {
656
+ enlargeIn = Math.pow(2, numBits);
657
+ numBits++;
658
+ }
659
+ }
660
+ },
661
+ };
662
+
663
+ var SimpleEventEmitter = /** @class */ (function () {
664
+ function SimpleEventEmitter() {
665
+ this.events = {};
666
+ this.events = {};
667
+ }
668
+ SimpleEventEmitter.prototype.on = function (event, listener) {
669
+ var _this = this;
670
+ if (!this.events[event]) {
671
+ this.events[event] = [];
672
+ }
673
+ this.events[event].push(listener);
674
+ return function () {
675
+ _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
676
+ };
677
+ };
678
+ SimpleEventEmitter.prototype.emit = function (event, payload) {
679
+ if (!this.events[event]) {
680
+ return;
681
+ }
682
+ for (var _i = 0, _a = this.events[event]; _i < _a.length; _i++) {
683
+ var listener = _a[_i];
684
+ listener(payload);
685
+ }
686
+ };
687
+ return SimpleEventEmitter;
688
+ }());
689
+
690
+ var PostHogCore = /** @class */ (function () {
691
+ function PostHogCore(apiKey, options) {
692
+ var _this = this;
693
+ var _a, _b, _c, _d, _e, _f;
694
+ this.flagCallReported = {};
695
+ // internal
696
+ this._events = new SimpleEventEmitter();
697
+ assert(apiKey, "You must pass your PostHog project's api key.");
698
+ this.apiKey = apiKey;
699
+ this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
700
+ this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
701
+ this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
702
+ this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
703
+ this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
704
+ this._decidePollInterval = Math.max(0, (_c = options === null || options === void 0 ? void 0 : options.decidePollInterval) !== null && _c !== void 0 ? _c : 30000);
705
+ // If enable is explicitly set to false we override the optout
706
+ this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
707
+ this._retryOptions = {
708
+ retryCount: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _d !== void 0 ? _d : 3,
709
+ retryDelay: (_e = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _e !== void 0 ? _e : 3000,
710
+ };
711
+ this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
712
+ // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
713
+ if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
714
+ safeSetTimeout(function () {
715
+ void _this.reloadFeatureFlagsAsync();
716
+ }, 1);
717
+ }
718
+ }
719
+ PostHogCore.prototype.getCommonEventProperties = function () {
720
+ var featureFlags = this.getFeatureFlags();
721
+ return {
722
+ $lib: this.getLibraryId(),
723
+ $lib_version: this.getLibraryVersion(),
724
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
725
+ $enabled_feature_flags: featureFlags,
726
+ };
727
+ };
728
+ Object.defineProperty(PostHogCore.prototype, "props", {
729
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
730
+ get: function () {
731
+ if (!this._props) {
732
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
733
+ }
734
+ return this._props || {};
735
+ },
736
+ set: function (val) {
737
+ this._props = val;
738
+ },
739
+ enumerable: false,
740
+ configurable: true
741
+ });
742
+ Object.defineProperty(PostHogCore.prototype, "optedOut", {
743
+ get: function () {
744
+ var _a, _b;
745
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
746
+ },
747
+ enumerable: false,
748
+ configurable: true
749
+ });
750
+ PostHogCore.prototype.optIn = function () {
751
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
752
+ };
753
+ PostHogCore.prototype.optOut = function () {
754
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
755
+ };
756
+ PostHogCore.prototype.on = function (event, cb) {
757
+ return this._events.on(event, cb);
758
+ };
759
+ PostHogCore.prototype.reset = function () {
760
+ for (var key in PostHogPersistedProperty) {
761
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
762
+ }
763
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, generateUUID(globalThis));
764
+ };
765
+ PostHogCore.prototype.buildPayload = function (payload) {
766
+ return {
767
+ distinct_id: payload.distinct_id || this.getDistinctId(),
768
+ event: payload.event,
769
+ properties: __assign(__assign(__assign(__assign({}, this.props), (payload.properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() }),
770
+ };
771
+ };
772
+ PostHogCore.prototype.getSessionId = function () {
773
+ var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
774
+ var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
775
+ if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
776
+ sessionId = generateUUID(globalThis);
777
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
778
+ }
779
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
780
+ return sessionId;
781
+ };
782
+ PostHogCore.prototype.getDistinctId = function () {
783
+ var distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
784
+ if (!distinctId) {
785
+ distinctId = generateUUID(globalThis);
786
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
787
+ }
788
+ return distinctId;
789
+ };
790
+ PostHogCore.prototype.register = function (properties) {
791
+ this.props = __assign(__assign({}, this.props), properties);
792
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
793
+ };
794
+ PostHogCore.prototype.unregister = function (property) {
795
+ delete this.props[property];
796
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
797
+ };
798
+ /***
799
+ *** TRACKING
800
+ ***/
801
+ PostHogCore.prototype.identify = function (distinctId, properties) {
802
+ distinctId = distinctId || this.getDistinctId();
803
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
804
+ this.groups(properties.$groups);
805
+ }
806
+ var payload = __assign(__assign({}, this.buildPayload({
807
+ distinct_id: distinctId,
808
+ event: '$identify',
809
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getDistinctId() }),
810
+ })), { $set: properties });
811
+ if (distinctId !== this.getDistinctId()) {
812
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
813
+ }
814
+ this.enqueue('identify', payload);
815
+ return this;
816
+ };
817
+ PostHogCore.prototype.capture = function (event, properties) {
818
+ // NOTE: Legacy nodejs implementation uses groups
819
+ if (properties && properties['groups']) {
820
+ properties.$groups = properties.groups;
821
+ delete properties.groups;
822
+ }
823
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
824
+ this.groups(properties.$groups);
825
+ }
826
+ var payload = this.buildPayload({ event: event, properties: properties });
827
+ this.enqueue('capture', payload);
828
+ return this;
829
+ };
830
+ PostHogCore.prototype.alias = function (alias) {
831
+ var distinctId = this.getDistinctId();
832
+ var payload = this.buildPayload({
833
+ event: '$create_alias',
834
+ properties: {
835
+ distinct_id: distinctId,
836
+ alias: alias,
837
+ },
838
+ });
839
+ this.enqueue('alias', payload);
840
+ return this;
841
+ };
842
+ PostHogCore.prototype.autocapture = function (eventType, elements, properties) {
843
+ if (properties === void 0) { properties = {}; }
844
+ var payload = this.buildPayload({
845
+ event: '$autocapture',
846
+ properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
847
+ });
848
+ this.enqueue('autocapture', payload);
849
+ return this;
850
+ };
851
+ /***
852
+ *** GROUPS
853
+ ***/
854
+ PostHogCore.prototype.groups = function (groups) {
855
+ // Get persisted groups
856
+ var existingGroups = this.props.$groups || {};
857
+ // NOTE: Should we do the same for groups listed in identify / capture?
858
+ this.register({
859
+ $groups: __assign(__assign({}, existingGroups), groups),
860
+ });
861
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this._decideResponsePromise) {
862
+ void this.reloadFeatureFlagsAsync();
863
+ }
864
+ return this;
865
+ };
866
+ PostHogCore.prototype.group = function (groupType, groupKey, groupProperties) {
867
+ var _a;
868
+ this.groups((_a = {},
869
+ _a[groupType] = groupKey,
870
+ _a));
871
+ if (groupProperties) {
872
+ this.groupIdentify(groupType, groupKey, groupProperties);
873
+ }
874
+ return this;
875
+ };
876
+ PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties) {
877
+ var payload = {
878
+ event: '$groupidentify',
879
+ distinctId: "$".concat(groupType, "_").concat(groupKey),
880
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
881
+ };
882
+ this.enqueue('capture', payload);
883
+ return this;
884
+ };
885
+ /***
886
+ *** FEATURE FLAGS
887
+ ***/
888
+ PostHogCore.prototype.decideAsync = function () {
889
+ if (this._decideResponsePromise) {
890
+ return this._decideResponsePromise;
891
+ }
892
+ return this._decideAsync();
893
+ };
894
+ PostHogCore.prototype._decideAsync = function () {
895
+ return __awaiter(this, void 0, void 0, function () {
896
+ var url, distinctId, groups, fetchOptions;
897
+ var _this = this;
898
+ return __generator(this, function (_a) {
899
+ url = "".concat(this.host, "/decide/?v=2");
900
+ distinctId = this.getDistinctId();
901
+ groups = this.props.$groups || {};
902
+ fetchOptions = {
903
+ method: 'POST',
904
+ headers: { 'Content-Type': 'application/json' },
905
+ body: JSON.stringify({ groups: groups, distinct_id: distinctId, token: this.apiKey }),
906
+ };
907
+ this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
908
+ .then(function (r) { return r.json(); })
909
+ .then(function (res) {
910
+ if (res.featureFlags) {
911
+ _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
912
+ }
913
+ _this._events.emit('featureflags', res.featureFlags);
914
+ return res;
915
+ });
916
+ return [2 /*return*/, this._decideResponsePromise];
917
+ });
918
+ });
919
+ };
920
+ PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
921
+ var _a;
922
+ if (defaultResult === void 0) { defaultResult = false; }
923
+ var featureFlags = this.getFeatureFlags();
924
+ if (!featureFlags) {
925
+ // If we haven't loaded flags yet we respond undefined to indicate this
926
+ return undefined;
927
+ }
928
+ if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
929
+ this.flagCallReported[key] = true;
930
+ this.capture('$feature_flag_called', {
931
+ $feature_flag: key,
932
+ $feature_flag_response: featureFlags[key],
933
+ });
934
+ }
935
+ // If we have flags we either return the value (true or string) or the defaultResult
936
+ return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
937
+ };
938
+ PostHogCore.prototype.getFeatureFlags = function () {
939
+ var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
940
+ var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
941
+ if (!overriddenFlags) {
942
+ return flags;
943
+ }
944
+ flags = flags || {};
945
+ for (var key in overriddenFlags) {
946
+ if (!overriddenFlags[key]) {
947
+ delete flags[key];
948
+ }
949
+ else {
950
+ flags[key] = overriddenFlags[key];
951
+ }
952
+ }
953
+ return flags;
954
+ };
955
+ PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
956
+ var _a;
957
+ if (defaultResult === void 0) { defaultResult = false; }
958
+ var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
959
+ return !!flag;
960
+ };
961
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
962
+ return __awaiter(this, void 0, void 0, function () {
963
+ var _this = this;
964
+ return __generator(this, function (_a) {
965
+ switch (_a.label) {
966
+ case 0:
967
+ clearTimeout(this._decideTimer);
968
+ if (this._decidePollInterval) {
969
+ this._decideTimer = safeSetTimeout(function () { return _this.reloadFeatureFlagsAsync(); }, this._decidePollInterval);
970
+ }
971
+ this._decideResponsePromise = undefined;
972
+ return [4 /*yield*/, this.decideAsync()];
973
+ case 1: return [2 /*return*/, (_a.sent()).featureFlags];
974
+ }
975
+ });
976
+ });
977
+ };
978
+ // When listening to feature flags polling is active
979
+ PostHogCore.prototype.onFeatureFlags = function (cb) {
980
+ var _this = this;
981
+ if (!this._decideTimer) {
982
+ void this.reloadFeatureFlagsAsync();
983
+ }
984
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
985
+ var flags;
986
+ return __generator(this, function (_a) {
987
+ flags = this.getFeatureFlags();
988
+ if (flags) {
989
+ cb(flags);
990
+ }
991
+ return [2 /*return*/];
992
+ });
993
+ }); });
994
+ };
995
+ PostHogCore.prototype.overrideFeatureFlag = function (flags) {
996
+ if (flags === null) {
997
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
998
+ }
999
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
1000
+ };
1001
+ /***
1002
+ *** QUEUEING AND FLUSHING
1003
+ ***/
1004
+ PostHogCore.prototype.enqueue = function (type, _message) {
1005
+ var _this = this;
1006
+ if (this.optedOut) {
1007
+ return;
1008
+ }
1009
+ var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: _message.timestamp ? _message.timestamp : currentISOTime() });
1010
+ if (message.distinctId) {
1011
+ message.distinct_id = message.distinctId;
1012
+ delete message.distinctId;
1013
+ }
1014
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1015
+ queue.push({ message: message });
1016
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1017
+ this._events.emit(type, message);
1018
+ // Flush queued events if we meet the flushAt length
1019
+ if (queue.length >= this.flushAt) {
1020
+ this.flush();
1021
+ }
1022
+ if (this.flushInterval && !this._flushTimer) {
1023
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1024
+ }
1025
+ };
1026
+ PostHogCore.prototype.flushAsync = function () {
1027
+ var _this = this;
1028
+ return new Promise(function (resolve, reject) {
1029
+ _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1030
+ });
1031
+ };
1032
+ PostHogCore.prototype.flush = function (callback) {
1033
+ var _this = this;
1034
+ if (this.optedOut) {
1035
+ return callback && safeSetTimeout(callback, 0);
1036
+ }
1037
+ if (this._flushTimer) {
1038
+ clearTimeout(this._flushTimer);
1039
+ this._flushTimer = null;
1040
+ }
1041
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1042
+ if (!queue.length) {
1043
+ return callback && safeSetTimeout(callback, 0);
1044
+ }
1045
+ var items = queue.splice(0, this.flushAt);
1046
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1047
+ var messages = items.map(function (item) { return item.message; });
1048
+ var data = {
1049
+ api_key: this.apiKey,
1050
+ batch: messages,
1051
+ sent_at: currentISOTime(),
1052
+ };
1053
+ var done = function (err) {
1054
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
1055
+ _this._events.emit('flush', messages);
1056
+ };
1057
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1058
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1059
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1060
+ // but browsers such as Chrome and Safari have not caught up.
1061
+ this.getCustomUserAgent();
1062
+ var payload = JSON.stringify(data);
1063
+ var url = this.captureMode === 'form'
1064
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1065
+ : "".concat(this.host, "/batch/");
1066
+ var fetchOptions = this.captureMode === 'form'
1067
+ ? {
1068
+ method: 'POST',
1069
+ mode: 'no-cors',
1070
+ credentials: 'omit',
1071
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1072
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1073
+ }
1074
+ : {
1075
+ method: 'POST',
1076
+ headers: { 'Content-Type': 'application/json' },
1077
+ body: payload,
1078
+ };
1079
+ this.fetchWithRetry(url, fetchOptions)
1080
+ .then(function () { return done(); })
1081
+ .catch(function (err) {
1082
+ if (err.response) {
1083
+ var error = new Error(err.response.statusText);
1084
+ return done(error);
1085
+ }
1086
+ done(err);
1087
+ });
1088
+ };
1089
+ PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1090
+ return __awaiter(this, void 0, void 0, function () {
1091
+ var _this = this;
1092
+ return __generator(this, function (_a) {
1093
+ return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1094
+ });
1095
+ });
1096
+ };
1097
+ PostHogCore.prototype.shutdownAsync = function () {
1098
+ return __awaiter(this, void 0, void 0, function () {
1099
+ return __generator(this, function (_a) {
1100
+ switch (_a.label) {
1101
+ case 0:
1102
+ clearTimeout(this._decideTimer);
1103
+ clearTimeout(this._flushTimer);
1104
+ return [4 /*yield*/, this.flushAsync()];
1105
+ case 1:
1106
+ _a.sent();
1107
+ return [2 /*return*/];
1108
+ }
1109
+ });
1110
+ });
1111
+ };
1112
+ PostHogCore.prototype.shutdown = function () {
1113
+ void this.shutdownAsync();
1114
+ };
1115
+ return PostHogCore;
1116
+ }());
1117
+
1118
+ var getLegacyValues = function () {
1119
+ return __awaiter(void 0, void 0, void 0, function () {
1120
+ var posthogFileDirectory, posthogDistinctIdFile, posthogAnonymousIdFile, res, _a, _b, _c, _d, _e, _f;
1121
+
1122
+ return __generator(this, function (_g) {
1123
+ switch (_g.label) {
1124
+ case 0:
1125
+ if (!(Platform.OS === 'ios')) return [3
1126
+ /*break*/
1127
+ , 8];
1128
+ posthogFileDirectory = "".concat(FileSystem.documentDirectory, "../Library/Application%20Support/").concat(ExpoApplication.applicationId, "/");
1129
+ posthogDistinctIdFile = posthogFileDirectory + 'posthog.distinctId';
1130
+ posthogAnonymousIdFile = posthogFileDirectory + 'posthog.anonymousId';
1131
+ res = {
1132
+ distinctId: undefined,
1133
+ anonymousId: undefined
1134
+ };
1135
+ _g.label = 1;
1136
+
1137
+ case 1:
1138
+ _g.trys.push([1, 3,, 4]);
1139
+
1140
+ _a = res;
1141
+ _c = (_b = JSON).parse;
1142
+ return [4
1143
+ /*yield*/
1144
+ , FileSystem.readAsStringAsync(posthogDistinctIdFile)];
1145
+
1146
+ case 2:
1147
+ _a.distinctId = _c.apply(_b, [_g.sent()])['posthog.distinctId'];
1148
+ return [3
1149
+ /*break*/
1150
+ , 4];
1151
+
1152
+ case 3:
1153
+ _g.sent();
1154
+ return [3
1155
+ /*break*/
1156
+ , 4];
1157
+
1158
+ case 4:
1159
+ _g.trys.push([4, 6,, 7]);
1160
+
1161
+ _d = res;
1162
+ _f = (_e = JSON).parse;
1163
+ return [4
1164
+ /*yield*/
1165
+ , FileSystem.readAsStringAsync(posthogAnonymousIdFile)];
1166
+
1167
+ case 5:
1168
+ _d.anonymousId = _f.apply(_e, [_g.sent()])['posthog.anonymousId'];
1169
+ return [3
1170
+ /*break*/
1171
+ , 7];
1172
+
1173
+ case 6:
1174
+ _g.sent();
1175
+ return [3
1176
+ /*break*/
1177
+ , 7];
1178
+
1179
+ case 7:
1180
+ return [2
1181
+ /*return*/
1182
+ , res];
1183
+
1184
+ case 8:
1185
+ return [2
1186
+ /*return*/
1187
+ ];
1188
+ }
1189
+ });
1190
+ });
1191
+ };
1192
+
1193
+ var POSTHOG_STORAGE_KEY = '.posthog-rn.json';
1194
+ var POSTHOG_STORAGE_VERSION = 'v1';
1195
+
1196
+ var loadStorageAsync = function () {
1197
+ return __awaiter(void 0, void 0, void 0, function () {
1198
+ var uri, stringContent;
1199
+ return __generator(this, function (_a) {
1200
+ switch (_a.label) {
1201
+ case 0:
1202
+ uri = FileSystem.documentDirectory + POSTHOG_STORAGE_KEY;
1203
+ _a.label = 1;
1204
+
1205
+ case 1:
1206
+ _a.trys.push([1, 3,, 4]);
1207
+
1208
+ return [4
1209
+ /*yield*/
1210
+ , FileSystem.readAsStringAsync(uri)];
1211
+
1212
+ case 2:
1213
+ stringContent = _a.sent();
1214
+ return [2
1215
+ /*return*/
1216
+ , JSON.parse(stringContent).content];
1217
+
1218
+ case 3:
1219
+ _a.sent();
1220
+ return [2
1221
+ /*return*/
1222
+ , {}];
1223
+
1224
+ case 4:
1225
+ return [2
1226
+ /*return*/
1227
+ ];
1228
+ }
1229
+ });
1230
+ });
1231
+ };
1232
+
1233
+ var persitStorageAsync = function (content) {
1234
+ return __awaiter(void 0, void 0, void 0, function () {
1235
+ var uri, data;
1236
+ return __generator(this, function (_a) {
1237
+ switch (_a.label) {
1238
+ case 0:
1239
+ uri = FileSystem.documentDirectory + POSTHOG_STORAGE_KEY;
1240
+ data = {
1241
+ version: POSTHOG_STORAGE_VERSION,
1242
+ content: content
1243
+ };
1244
+ return [4
1245
+ /*yield*/
1246
+ , FileSystem.writeAsStringAsync(uri, JSON.stringify(data)).catch(function (e) {
1247
+ console.error('PostHog failed to persist data to storage', e);
1248
+ })];
1249
+
1250
+ case 1:
1251
+ _a.sent();
1252
+
1253
+ return [2
1254
+ /*return*/
1255
+ ];
1256
+ }
1257
+ });
1258
+ });
1259
+ }; // NOTE: The core prefers a synchronous storage so we mimic this by pre-loading all keys
1260
+
1261
+
1262
+ var _memoryCache = {};
1263
+ var SemiAsyncStorage = {
1264
+ getItem: function (key) {
1265
+ return _memoryCache[key];
1266
+ },
1267
+ setItem: function (key, value) {
1268
+ _memoryCache[key] = value;
1269
+ void persitStorageAsync(_memoryCache);
1270
+ },
1271
+ removeItem: function (key) {
1272
+ delete _memoryCache[key];
1273
+ void persitStorageAsync(_memoryCache);
1274
+ },
1275
+ clear: function () {
1276
+ for (var key in _memoryCache) {
1277
+ delete _memoryCache[key];
1278
+ }
1279
+
1280
+ void persitStorageAsync(_memoryCache);
1281
+ },
1282
+ getAllKeys: function () {
1283
+ return Object.keys(_memoryCache);
1284
+ }
1285
+ };
1286
+
1287
+ var _preloadSemiAsyncStoragePromise;
1288
+
1289
+ var preloadSemiAsyncStorage = function () {
1290
+ if (_preloadSemiAsyncStoragePromise) {
1291
+ return _preloadSemiAsyncStoragePromise;
1292
+ }
1293
+
1294
+ _preloadSemiAsyncStoragePromise = loadStorageAsync().then(function (res) {
1295
+ for (var key in res) {
1296
+ _memoryCache[key] = res[key];
1297
+ }
1298
+ });
1299
+ return _preloadSemiAsyncStoragePromise;
1300
+ };
1301
+
1302
+ var _OptionalReactNativeNavigation = undefined;
1303
+ var _OptionalExpoLocalization = undefined;
1304
+ var _OptionalExpoNetwork = undefined;
1305
+
1306
+ var warn = function (name) {
1307
+ console.warn("PostHog: Missing ".concat(name, " optional dependency. Some functions may not work as expected..."));
1308
+ };
1309
+
1310
+ try {
1311
+ _OptionalReactNativeNavigation = require('@react-navigation/native');
1312
+ } catch (e) {
1313
+ warn('@react-navigation/native');
1314
+ }
1315
+
1316
+ try {
1317
+ _OptionalExpoLocalization = require('expo-localization');
1318
+ } catch (e) {
1319
+ warn('expo-localization');
1320
+ }
1321
+
1322
+ try {
1323
+ _OptionalExpoNetwork = require('expo-network');
1324
+ } catch (e) {
1325
+ warn('expo-network');
1326
+ }
1327
+
1328
+ var OptionalReactNativeNavigation = _OptionalReactNativeNavigation;
1329
+ var OptionalExpoLocalization = _OptionalExpoLocalization;
1330
+
1331
+ var version = "2.0.0-alpha8";
1332
+
1333
+ var PostHog =
1334
+ /** @class */
1335
+ function (_super) {
1336
+ __extends(PostHog, _super);
1337
+
1338
+ function PostHog(apiKey, options) {
1339
+ var _this = _super.call(this, apiKey, options) || this;
1340
+
1341
+ AppState.addEventListener('change', function () {
1342
+ _this.flush();
1343
+ }); // Ensure the async storage has been preloaded (this call is cached)
1344
+ // It is possible that the old library was used so we try to get the legacy distinctID
1345
+
1346
+ void preloadSemiAsyncStorage().then(function () {
1347
+ if (!SemiAsyncStorage.getItem(PostHogPersistedProperty.DistinctId)) {
1348
+ getLegacyValues().then(function (legacyValues) {
1349
+ if (legacyValues === null || legacyValues === void 0 ? void 0 : legacyValues.distinctId) {
1350
+ SemiAsyncStorage.setItem(PostHogPersistedProperty.DistinctId, legacyValues.distinctId);
1351
+ }
1352
+ });
1353
+ }
1354
+ });
1355
+ return _this;
1356
+ }
1357
+
1358
+ PostHog.initAsync = function () {
1359
+ return preloadSemiAsyncStorage();
1360
+ };
1361
+
1362
+ PostHog.prototype.getPersistedProperty = function (key) {
1363
+ return SemiAsyncStorage.getItem(key) || undefined;
1364
+ };
1365
+
1366
+ PostHog.prototype.setPersistedProperty = function (key, value) {
1367
+ return value !== null ? SemiAsyncStorage.setItem(key, value) : SemiAsyncStorage.removeItem(key);
1368
+ };
1369
+
1370
+ PostHog.prototype.fetch = function (url, options) {
1371
+ return fetch(url, options);
1372
+ };
1373
+
1374
+ PostHog.prototype.getLibraryId = function () {
1375
+ return 'posthog-react-native';
1376
+ };
1377
+
1378
+ PostHog.prototype.getLibraryVersion = function () {
1379
+ return version;
1380
+ };
1381
+
1382
+ PostHog.prototype.getCustomUserAgent = function () {
1383
+ // TODO
1384
+ return;
1385
+ };
1386
+
1387
+ PostHog.prototype.getCommonEventProperties = function () {
1388
+ return __assign(__assign({}, _super.prototype.getCommonEventProperties.call(this)), {
1389
+ $app_build: '1',
1390
+ $app_name: ExpoApplication === null || ExpoApplication === void 0 ? void 0 : ExpoApplication.applicationName,
1391
+ $app_namespace: ExpoApplication === null || ExpoApplication === void 0 ? void 0 : ExpoApplication.applicationId,
1392
+ $app_version: ExpoApplication === null || ExpoApplication === void 0 ? void 0 : ExpoApplication.nativeApplicationVersion,
1393
+ // "$device_id": "F31C35E8-5B28-4626-8AFC-213D1C655FF9",
1394
+ $device_manufacturer: ExpoDevice === null || ExpoDevice === void 0 ? void 0 : ExpoDevice.manufacturer,
1395
+ // "$device_model": "x86_64",
1396
+ $device_name: ExpoDevice === null || ExpoDevice === void 0 ? void 0 : ExpoDevice.modelName,
1397
+ // "$device_type": "ios",
1398
+ $locale: OptionalExpoLocalization === null || OptionalExpoLocalization === void 0 ? void 0 : OptionalExpoLocalization.locale,
1399
+ // "$network_cellular": false,
1400
+ // "$network_wifi": true,
1401
+ $os_name: ExpoDevice === null || ExpoDevice === void 0 ? void 0 : ExpoDevice.osName,
1402
+ $os_version: ExpoDevice === null || ExpoDevice === void 0 ? void 0 : ExpoDevice.osVersion,
1403
+ $screen_height: Dimensions.get('screen').height,
1404
+ $screen_width: Dimensions.get('screen').width,
1405
+ $timezone: OptionalExpoLocalization === null || OptionalExpoLocalization === void 0 ? void 0 : OptionalExpoLocalization.timezone
1406
+ });
1407
+ }; // Custom methods
1408
+
1409
+
1410
+ PostHog.prototype.screen = function (name, properties) {
1411
+ return this.capture('$screen', __assign(__assign({}, properties), {
1412
+ $screen_name: name
1413
+ }));
1414
+ };
1415
+
1416
+ return PostHog;
1417
+ }(PostHogCore);
1418
+ // is used
1419
+
1420
+ void PostHog.initAsync();
1421
+
1422
+ var PostHogContext = /*#__PURE__*/React.createContext({
1423
+ client: undefined
1424
+ });
1425
+
1426
+ var usePostHog = function () {
1427
+ var client = React.useContext(PostHogContext).client;
1428
+ return client;
1429
+ };
1430
+
1431
+ function useLifecycleTracker(client) {
1432
+ var openTrackedRef = useRef(false);
1433
+ var contextClient = usePostHog();
1434
+ var posthog = client || contextClient;
1435
+ return useEffect(function () {
1436
+ if (!posthog) {
1437
+ return;
1438
+ }
1439
+
1440
+ if (!openTrackedRef.current) {
1441
+ openTrackedRef.current = true;
1442
+ posthog.capture('Application Opened');
1443
+ }
1444
+
1445
+ var subscription = AppState.addEventListener('change', function (nextAppState) {
1446
+ switch (nextAppState) {
1447
+ case 'active':
1448
+ return posthog.capture('Application Became Active');
1449
+
1450
+ case 'background':
1451
+ return posthog.capture('Application Backgrounded');
1452
+
1453
+ default:
1454
+ return;
1455
+ }
1456
+ });
1457
+ return function () {
1458
+ return subscription.remove();
1459
+ };
1460
+ }, [posthog]);
1461
+ }
1462
+
1463
+ function _useNavigationTrackerDisabled() {
1464
+ return;
1465
+ }
1466
+
1467
+ function _useNavigationTracker(options, client) {
1468
+ var contextClient = usePostHog();
1469
+ var posthog = client || contextClient;
1470
+
1471
+ if (!OptionalReactNativeNavigation) {
1472
+ // NOTE: This is taken care of by the export but we keep this here for TS
1473
+ return;
1474
+ }
1475
+
1476
+ var routes = OptionalReactNativeNavigation.useNavigationState(function (state) {
1477
+ return state === null || state === void 0 ? void 0 : state.routes;
1478
+ });
1479
+ var navigation = OptionalReactNativeNavigation.useNavigation();
1480
+
1481
+ var trackRoute = function () {
1482
+ var _a, _b, _c;
1483
+
1484
+ if (!posthog) {
1485
+ return;
1486
+ } // NOTE: This method is not typed correctly but is available and takes care of parsing the router state correctly
1487
+
1488
+
1489
+ var currentRoute = navigation.getCurrentRoute();
1490
+
1491
+ if (!currentRoute) {
1492
+ return;
1493
+ }
1494
+
1495
+ var state = currentRoute.state;
1496
+ var name = currentRoute.name,
1497
+ params = currentRoute.params;
1498
+
1499
+ if ((_a = state === null || state === void 0 ? void 0 : state.routes) === null || _a === void 0 ? void 0 : _a.length) {
1500
+ var route = state.routes[state.routes.length - 1];
1501
+ name = route.name;
1502
+ params = route.params;
1503
+ }
1504
+
1505
+ var currentRouteName = ((_b = options === null || options === void 0 ? void 0 : options.routeToName) === null || _b === void 0 ? void 0 : _b.call(options, name, params)) || name || 'Unknown';
1506
+
1507
+ if (currentRouteName) {
1508
+ var properties = (_c = options === null || options === void 0 ? void 0 : options.routeToProperties) === null || _c === void 0 ? void 0 : _c.call(options, currentRouteName, params);
1509
+ posthog.screen(currentRouteName, properties);
1510
+ }
1511
+ };
1512
+
1513
+ useEffect(function () {
1514
+ // NOTE: The navigation stacks may not be fully rendered initially. This means the first route can be missed (it doesn't update useNavigationState)
1515
+ // If missing we simply wait a tick and call it again.
1516
+ if (!routes) {
1517
+ setTimeout(trackRoute, 1);
1518
+ return;
1519
+ }
1520
+
1521
+ trackRoute();
1522
+ }, [routes]);
1523
+ }
1524
+
1525
+ var useNavigationTracker = OptionalReactNativeNavigation ? _useNavigationTracker : _useNavigationTrackerDisabled;
1526
+
1527
+ function useFeatureFlags(client) {
1528
+ var contextClient = usePostHog();
1529
+ var posthog = client || contextClient;
1530
+
1531
+ var _a = useState(posthog === null || posthog === void 0 ? void 0 : posthog.getFeatureFlags()),
1532
+ featureFlags = _a[0],
1533
+ setFeatureFlags = _a[1];
1534
+
1535
+ if (!posthog) {
1536
+ return featureFlags;
1537
+ }
1538
+
1539
+ useEffect(function () {
1540
+ setFeatureFlags(posthog.getFeatureFlags());
1541
+ return posthog.onFeatureFlags(function (flags) {
1542
+ setFeatureFlags(flags);
1543
+ });
1544
+ }, [posthog]);
1545
+ return featureFlags;
1546
+ }
1547
+
1548
+ function useFeatureFlag(flag, defaultValue) {
1549
+ var posthog = usePostHog();
1550
+
1551
+ var _a = useState(posthog === null || posthog === void 0 ? void 0 : posthog.getFeatureFlag(flag, defaultValue)),
1552
+ featureFlag = _a[0],
1553
+ setFeatureFlag = _a[1];
1554
+
1555
+ if (!posthog) {
1556
+ return featureFlag;
1557
+ }
1558
+
1559
+ useEffect(function () {
1560
+ setFeatureFlag(posthog.getFeatureFlag(flag, defaultValue));
1561
+ return posthog.onFeatureFlags(function () {
1562
+ setFeatureFlag(posthog.getFeatureFlag(flag, defaultValue));
1563
+ });
1564
+ }, [posthog, flag, defaultValue]);
1565
+ return featureFlag;
1566
+ }
1567
+
1568
+ var flattenStyles = function (styles) {
1569
+ var flattened = {};
1570
+
1571
+ if (Array.isArray(styles)) {
1572
+ for (var _i = 0, styles_1 = styles; _i < styles_1.length; _i++) {
1573
+ var style = styles_1[_i];
1574
+ Object.assign(flattened, flattenStyles(style));
1575
+ }
1576
+ } else {
1577
+ Object.assign(flattened, styles);
1578
+ }
1579
+
1580
+ return flattened;
1581
+ };
1582
+
1583
+ var stringifyStyle = function (styles) {
1584
+ var flattened = flattenStyles(styles);
1585
+ var str = Object.keys(flattened).map(function (x) {
1586
+ return "".concat(x, ":").concat(flattened[x]);
1587
+ }).join(';');
1588
+ return str;
1589
+ };
1590
+
1591
+ var sanitiseLabel = function (label) {
1592
+ return label.replace(/[^a-z0-9]+/gi, '-');
1593
+ };
1594
+
1595
+ var autocaptureFromTouchEvent = function (e, posthog, options) {
1596
+ var _a, _b;
1597
+
1598
+ if (options === void 0) {
1599
+ options = {};
1600
+ }
1601
+
1602
+ var _c = options.noCaptureProp,
1603
+ noCaptureProp = _c === void 0 ? 'ph-no-capture' : _c,
1604
+ _d = options.customLabelProp,
1605
+ customLabelProp = _d === void 0 ? 'ph-label' : _d,
1606
+ _e = options.maxElementsCaptured,
1607
+ maxElementsCaptured = _e === void 0 ? 20 : _e,
1608
+ _f = options.ignoreLabels,
1609
+ ignoreLabels = _f === void 0 ? [] : _f;
1610
+
1611
+ if (!e._targetInst) {
1612
+ return;
1613
+ }
1614
+
1615
+ var elements = [];
1616
+ var currentInst = e._targetInst;
1617
+
1618
+ var _loop_1 = function () {
1619
+ var el = {
1620
+ tag_name: ''
1621
+ };
1622
+ var props = currentInst.memoizedProps;
1623
+
1624
+ if (props) {
1625
+ Object.keys(props).forEach(function (key) {
1626
+ var value = props[key];
1627
+
1628
+ if (key === 'style') {
1629
+ el.attr__style = stringifyStyle(value);
1630
+ } else if (['string', 'number', 'boolean'].includes(typeof value)) {
1631
+ if (key === 'children') {
1632
+ el.$el_text = typeof value === 'string' ? value : JSON.stringify(value);
1633
+ } else {
1634
+ el["attr__".concat(key)] = value;
1635
+ }
1636
+ }
1637
+ });
1638
+ }
1639
+
1640
+ if (props === null || props === void 0 ? void 0 : props[noCaptureProp]) {
1641
+ return {
1642
+ value: void 0
1643
+ };
1644
+ } // Try and find a sensible label
1645
+
1646
+
1647
+ var label = typeof (props === null || props === void 0 ? void 0 : props[customLabelProp]) !== 'undefined' ? "".concat(props[customLabelProp]) : ((_a = currentInst.elementType) === null || _a === void 0 ? void 0 : _a.displayName) || ((_b = currentInst.elementType) === null || _b === void 0 ? void 0 : _b.name);
1648
+
1649
+ if (label && !ignoreLabels.includes(label)) {
1650
+ el.tag_name = sanitiseLabel(label);
1651
+ elements.push(el);
1652
+ }
1653
+
1654
+ currentInst = currentInst.return;
1655
+ };
1656
+
1657
+ while (currentInst && // maxComponentTreeSize will always be defined as we have a defaultProps. But ts needs a check so this is here.
1658
+ elements.length < maxElementsCaptured) {
1659
+ var state_1 = _loop_1();
1660
+
1661
+ if (typeof state_1 === "object") return state_1.value;
1662
+ }
1663
+
1664
+ if (elements.length) {
1665
+ posthog.autocapture('touch', elements, {
1666
+ $touch_x: e.nativeEvent.pageX,
1667
+ $touch_y: e.nativeEvent.pageY
1668
+ });
1669
+ }
1670
+ };
1671
+
1672
+ function PostHogHooks(_a) {
1673
+ var options = _a.options;
1674
+ useNavigationTracker(options === null || options === void 0 ? void 0 : options.navigation);
1675
+ useLifecycleTracker();
1676
+ return null;
1677
+ }
1678
+
1679
+ var PostHogProvider = function (_a) {
1680
+ var children = _a.children,
1681
+ client = _a.client,
1682
+ options = _a.options,
1683
+ apiKey = _a.apiKey,
1684
+ autocapture = _a.autocapture,
1685
+ style = _a.style;
1686
+ var posthogRef = useRef();
1687
+
1688
+ if (!posthogRef.current) {
1689
+ posthogRef.current = client ? client : apiKey ? new PostHog(apiKey, options) : undefined;
1690
+ }
1691
+
1692
+ var autocaptureEnabled = !!autocapture;
1693
+ var autocaptureOptions = autocapture && typeof autocapture !== 'boolean' ? autocapture : {};
1694
+ var posthog = posthogRef.current;
1695
+ var captureTouches = posthog && (autocapture === true || (autocaptureOptions === null || autocaptureOptions === void 0 ? void 0 : autocaptureOptions.captureTouches));
1696
+ var onTouch = useCallback(function (type, e) {
1697
+ // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example
1698
+ if (!captureTouches) {
1699
+ return;
1700
+ }
1701
+
1702
+ if (type === 'end') {
1703
+ autocaptureFromTouchEvent(e, posthog, autocaptureOptions);
1704
+ }
1705
+ }, [posthog, autocapture]); // TODO: Improve this to ensure we only capture presses and not just ends of a drag for example
1706
+
1707
+ return /*#__PURE__*/React.createElement(View, {
1708
+ "ph-label": "PostHogProvider",
1709
+ style: style || {
1710
+ flex: 1
1711
+ },
1712
+ onTouchEndCapture: captureTouches ? function (e) {
1713
+ return onTouch('end', e);
1714
+ } : undefined
1715
+ }, /*#__PURE__*/React.createElement(PostHogContext.Provider, {
1716
+ value: {
1717
+ client: posthogRef.current
1718
+ }
1719
+ }, autocaptureEnabled ? /*#__PURE__*/React.createElement(PostHogHooks, {
1720
+ options: autocaptureOptions
1721
+ }) : null, children));
1722
+ };
1723
+
1724
+ export { PostHog, PostHogProvider, PostHog as default, useFeatureFlag, useFeatureFlags, useLifecycleTracker, useNavigationTracker, usePostHog };
1725
+ //# sourceMappingURL=index.esm.js.map