posthog-react-native 2.2.0-alpha1 → 2.2.0-alpha2

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