posthog-react-native 2.2.0-alpha1 → 2.2.0-alpha3

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