@posthog/browser 0.1.1 → 0.2.0
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.
- package/ARCHITECTURE.md +28 -22
- package/README.md +65 -29
- package/dist/analytics-api.d.ts +26 -0
- package/dist/analytics-api.js +18 -0
- package/dist/analytics-api.mjs +1 -0
- package/dist/analytics-buffer.d.ts +3 -3
- package/dist/analytics-buffer.js +2 -161
- package/dist/analytics-buffer.mjs +2 -161
- package/dist/analytics-extension.d.ts +76 -0
- package/dist/analytics-extension.js +589 -0
- package/dist/analytics-extension.mjs +551 -0
- package/dist/analytics-internal.d.ts +32 -18
- package/dist/analytics-options.d.ts +7 -2
- package/dist/analytics-options.js +38 -1
- package/dist/analytics-options.mjs +17 -1
- package/dist/analytics.d.ts +4 -3
- package/dist/autocapture.d.ts +2 -2
- package/dist/autocapture.js +21 -10
- package/dist/autocapture.mjs +21 -10
- package/dist/automatic-analytics.d.ts +2 -2
- package/dist/browser-client.d.ts +44 -4
- package/dist/capture-properties.d.ts +9 -0
- package/dist/capture-properties.js +68 -0
- package/dist/capture-properties.mjs +30 -0
- package/dist/capture-v1.js +7 -19
- package/dist/capture-v1.mjs +1 -13
- package/dist/core.d.ts +7 -5
- package/dist/extensions/registry.d.ts +42 -7
- package/dist/extensions/registry.js +194 -37
- package/dist/extensions/registry.mjs +194 -37
- package/dist/flags-token.d.ts +4 -4
- package/dist/flags.js +15 -2
- package/dist/flags.mjs +15 -2
- package/dist/immutable.d.ts +1 -0
- package/dist/immutable.js +46 -0
- package/dist/immutable.mjs +8 -0
- package/dist/index.d.ts +7 -5
- package/dist/index.js +3 -67
- package/dist/index.mjs +3 -67
- package/dist/logs-internal.d.ts +2 -2
- package/dist/logs.js +5 -2
- package/dist/logs.mjs +5 -2
- package/dist/person-processing.d.ts +11 -0
- package/dist/person-processing.js +84 -0
- package/dist/person-processing.mjs +37 -0
- package/dist/posthog.d.ts +4 -3
- package/dist/posthog.js +153 -353
- package/dist/posthog.mjs +153 -353
- package/dist/root-composition.d.ts +11 -0
- package/dist/root-composition.js +138 -0
- package/dist/root-composition.mjs +100 -0
- package/dist/state.d.ts +1 -0
- package/dist/state.js +4 -0
- package/dist/state.mjs +4 -0
- package/dist/surveys-extension.js +11 -6
- package/dist/surveys-extension.mjs +11 -6
- package/dist/surveys-internal.d.ts +3 -2
- package/dist/types.d.ts +13 -19
- package/dist/utf8.d.ts +1 -0
- package/dist/utf8.js +52 -0
- package/dist/utf8.mjs +14 -0
- package/dist/version.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +5 -5
package/dist/posthog.mjs
CHANGED
|
@@ -1,21 +1,15 @@
|
|
|
1
1
|
import { loadRemoteConfig } from "./remote-config.mjs";
|
|
2
2
|
import { Publisher } from "@posthog/browser-common/pubsub";
|
|
3
|
-
import {
|
|
4
|
-
import { MAX_ANALYTICS_BYTES, isAnalyticsExtension } from "./analytics-internal.mjs";
|
|
3
|
+
import { isAnalyticsExtension } from "./analytics-internal.mjs";
|
|
5
4
|
import { isLikelyBot } from "./bot-filter.mjs";
|
|
6
|
-
import { EMPTY_CAPTURE_SUMMARY, captureFailure } from "./capture-summary.mjs";
|
|
7
5
|
import { ExtensionRegistry } from "./extensions/registry.mjs";
|
|
8
|
-
import {
|
|
6
|
+
import { deepFreeze } from "./immutable.mjs";
|
|
9
7
|
import { createLogger } from "./logger.mjs";
|
|
10
|
-
import { ClientRateLimiter } from "./rate-limiter.mjs";
|
|
11
8
|
import { sendRequest } from "./request.mjs";
|
|
12
9
|
import { BrowserState, getDefaultSessionStorage, getDefaultStorage } from "./state.mjs";
|
|
13
10
|
import { version } from "./version.mjs";
|
|
14
11
|
const CONSENT_CHANGE_EVENT = '__posthog_browser_consent_change__';
|
|
15
12
|
const DEFAULT_SHUTDOWN_TIMEOUT_MS = 30000;
|
|
16
|
-
const CLIENT_RATE_LIMIT_WARNING = '$$client_ingestion_warning';
|
|
17
|
-
const isNonEmptyString = (value)=>'string' == typeof value && value.trim().length > 0;
|
|
18
|
-
const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
|
|
19
13
|
const normalizeHost = (host)=>{
|
|
20
14
|
let end = host.length;
|
|
21
15
|
while(end > 0 && 47 === host.charCodeAt(end - 1))end--;
|
|
@@ -31,20 +25,6 @@ const getAssetsHost = (apiHost)=>{
|
|
|
31
25
|
} catch {}
|
|
32
26
|
return apiHost;
|
|
33
27
|
};
|
|
34
|
-
const isValidDistinctId = (value)=>isNonEmptyString(value) && ![
|
|
35
|
-
'$posthog_cookieless',
|
|
36
|
-
'distinct_id',
|
|
37
|
-
'distinctid',
|
|
38
|
-
'undefined',
|
|
39
|
-
'null'
|
|
40
|
-
].includes(value.toLowerCase());
|
|
41
|
-
const deepFreeze = (value)=>{
|
|
42
|
-
if (value && 'object' == typeof value) {
|
|
43
|
-
Object.values(value).forEach(deepFreeze);
|
|
44
|
-
Object.freeze(value);
|
|
45
|
-
}
|
|
46
|
-
return value;
|
|
47
|
-
};
|
|
48
28
|
const getDefaultFetch = ()=>{
|
|
49
29
|
try {
|
|
50
30
|
return globalThis.fetch?.bind(globalThis);
|
|
@@ -59,41 +39,20 @@ const getDefaultNavigator = ()=>{
|
|
|
59
39
|
return;
|
|
60
40
|
}
|
|
61
41
|
};
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
return
|
|
65
|
-
} catch {
|
|
66
|
-
return new Date().toISOString();
|
|
42
|
+
class PostHog {
|
|
43
|
+
static create(options, loaders) {
|
|
44
|
+
return new PostHog(options, loaders);
|
|
67
45
|
}
|
|
68
|
-
|
|
69
|
-
const utf8Bytes = (value)=>{
|
|
70
|
-
let bytes = 0;
|
|
71
|
-
for(let index = 0; index < value.length; index++){
|
|
72
|
-
const code = value.charCodeAt(index);
|
|
73
|
-
if (code < 0x80) bytes++;
|
|
74
|
-
else if (code < 0x800) bytes += 2;
|
|
75
|
-
else if (code >= 0xd800 && code <= 0xdbff && value.charCodeAt(index + 1) >= 0xdc00) {
|
|
76
|
-
bytes += 4;
|
|
77
|
-
index++;
|
|
78
|
-
} else bytes += 3;
|
|
79
|
-
}
|
|
80
|
-
return bytes;
|
|
81
|
-
};
|
|
82
|
-
class PostHogBrowserClient {
|
|
83
|
-
static create(options, capture) {
|
|
84
|
-
return new PostHogBrowserClient(options, capture);
|
|
85
|
-
}
|
|
86
|
-
constructor(options, capture){
|
|
46
|
+
constructor(options, loaders){
|
|
87
47
|
this.library = Object.freeze({
|
|
88
48
|
name: 'web',
|
|
89
49
|
version: version
|
|
90
50
|
});
|
|
91
|
-
this._dynamicEventProperties = [];
|
|
92
|
-
this._rateLimiter = new ClientRateLimiter();
|
|
93
51
|
this._immediateAuthority = {};
|
|
94
52
|
this._closing = false;
|
|
95
53
|
this._disposed = false;
|
|
96
54
|
this._initialPageviewPending = true;
|
|
55
|
+
this._ready = false;
|
|
97
56
|
let projectToken = '';
|
|
98
57
|
try {
|
|
99
58
|
projectToken = options.projectToken ?? '';
|
|
@@ -111,7 +70,9 @@ class PostHogBrowserClient {
|
|
|
111
70
|
this._remoteConfigPublisher = new Publisher((error)=>this.logger.error('A remote configuration listener failed', error));
|
|
112
71
|
this._eventPublisher = new Publisher((error)=>this.logger.error('An event listener failed', error));
|
|
113
72
|
this._identifyPublisher = new Publisher((error)=>this.logger.error('An identify listener failed', error));
|
|
73
|
+
this._changePropertiesPublisher = new Publisher((error)=>this.logger.error('A person-property listener failed', error));
|
|
114
74
|
this._groupPublisher = new Publisher((error)=>this.logger.error('A group listener failed', error));
|
|
75
|
+
this._groupsResetPublisher = new Publisher((error)=>this.logger.error('A group reset listener failed', error));
|
|
115
76
|
this._resetPublisher = new Publisher((error)=>this.logger.error('A reset listener failed', error));
|
|
116
77
|
this._newSessionPublisher = new Publisher((error)=>this.logger.error('A session listener failed', error));
|
|
117
78
|
this._consentChangePublisher = new Publisher((error)=>this.logger.error('A consent change listener failed', error));
|
|
@@ -123,7 +84,7 @@ class PostHogBrowserClient {
|
|
|
123
84
|
this._state = new BrowserState(projectToken, storage, options.persistenceKey, options.consentPersistenceName, options.optOutByDefault ?? false, !this._blocked && void 0 === options.storage && void 0 !== requestedStorage ? getDefaultSessionStorage : void 0, (consent, previous)=>{
|
|
124
85
|
if ('denied' === consent) {
|
|
125
86
|
this._immediateAuthority = {};
|
|
126
|
-
this.
|
|
87
|
+
this._analytics?.purge();
|
|
127
88
|
}
|
|
128
89
|
this._consentChangePublisher.publish({
|
|
129
90
|
current: consent,
|
|
@@ -162,15 +123,15 @@ class PostHogBrowserClient {
|
|
|
162
123
|
else if (!this._closing && !this._disposed) this.getRemoteConfig();
|
|
163
124
|
return subscription;
|
|
164
125
|
};
|
|
165
|
-
this.onEvent = this._eventPublisher.listener;
|
|
166
126
|
this.onIdentify = this._identifyPublisher.listener;
|
|
167
127
|
this.onGroup = this._groupPublisher.listener;
|
|
128
|
+
this.onGroupsReset = this._groupsResetPublisher.listener;
|
|
168
129
|
this.onReset = this._resetPublisher.listener;
|
|
169
130
|
this.onConsentChange = this._consentChangePublisher.listener;
|
|
170
131
|
this.onNewSession = this._newSessionPublisher.listener;
|
|
171
132
|
this.onSession = (listener)=>this.onNewSession((session)=>listener(session.sessionId));
|
|
172
|
-
this._registry = new ExtensionRegistry((extensionName)=>this._createExtensionClient(extensionName), this.logger);
|
|
173
|
-
this.
|
|
133
|
+
this._registry = new ExtensionRegistry((extensionName, resolve)=>this._createExtensionClient(extensionName, resolve), this.logger, loaders, (extension, host)=>this._setupExtension(extension, host), ()=>!this._closing && !this._disposed);
|
|
134
|
+
this._registry.expose(this);
|
|
174
135
|
}
|
|
175
136
|
get distinctId() {
|
|
176
137
|
this._state.prepare();
|
|
@@ -198,223 +159,6 @@ class PostHogBrowserClient {
|
|
|
198
159
|
get canCapture() {
|
|
199
160
|
return !this._closing && !this._disposed && !this._blocked && !this.hasOptedOut() && this._state.prepare();
|
|
200
161
|
}
|
|
201
|
-
get isRateLimited() {
|
|
202
|
-
return this._rateLimiter.wouldLimit;
|
|
203
|
-
}
|
|
204
|
-
capture(event, properties = null, options = {}) {
|
|
205
|
-
try {
|
|
206
|
-
if ('unload' === options.delivery && !this._captureSink?.isTearingDown) {
|
|
207
|
-
const authority = this._immediateAuthority;
|
|
208
|
-
const message = this._admitCapture(event, properties, options, false, true);
|
|
209
|
-
if (message) this._captureSink?.deliverUnload(message, ()=>this._immediateAuthority === authority);
|
|
210
|
-
return !!message || !this._rateLimiter.limited;
|
|
211
|
-
}
|
|
212
|
-
} catch (error) {
|
|
213
|
-
this.logger.error('Unload capture failed', error);
|
|
214
|
-
return true;
|
|
215
|
-
}
|
|
216
|
-
return this._capture(event, properties, options) || !this._rateLimiter.limited;
|
|
217
|
-
}
|
|
218
|
-
async captureImmediate(event, properties = null, options = {}) {
|
|
219
|
-
try {
|
|
220
|
-
const authority = this._immediateAuthority;
|
|
221
|
-
const message = this._admitCapture(event, properties, options, false, true);
|
|
222
|
-
if (!message) return EMPTY_CAPTURE_SUMMARY;
|
|
223
|
-
const capture = this._captureSink;
|
|
224
|
-
if (!capture) return captureFailure(new Error('Immediate analytics delivery is unavailable'));
|
|
225
|
-
return await capture.deliverImmediate(message, ()=>this._immediateAuthority === authority);
|
|
226
|
-
} catch (error) {
|
|
227
|
-
return captureFailure(error);
|
|
228
|
-
}
|
|
229
|
-
}
|
|
230
|
-
_capture(event, properties = null, options = {}, skipRateLimit = false) {
|
|
231
|
-
return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false);
|
|
232
|
-
}
|
|
233
|
-
_admitCapture(event, properties, options, skipRateLimit, immediate) {
|
|
234
|
-
if (!isNonEmptyString(event) || this._closing || this._disposed || this._blocked || this.hasOptedOut() || !this._state.prepare()) return;
|
|
235
|
-
if (!skipRateLimit) {
|
|
236
|
-
const rateLimit = this._rateLimiter.consume();
|
|
237
|
-
if (!rateLimit.allowed) {
|
|
238
|
-
if (void 0 !== rateLimit.reportDropped) {
|
|
239
|
-
const warning = `${rateLimit.reportDropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
|
|
240
|
-
this.logger.warn(`PostHog client rate limited: ${warning}`);
|
|
241
|
-
if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
|
|
242
|
-
$$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
|
|
243
|
-
}, {}, true)) this._rateLimiter.reported();
|
|
244
|
-
}
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
}
|
|
248
|
-
const dynamicProperties = {};
|
|
249
|
-
for (const producer of this._dynamicEventProperties.slice())try {
|
|
250
|
-
Object.assign(dynamicProperties, producer());
|
|
251
|
-
} catch (error) {
|
|
252
|
-
this.logger.error('An event property producer failed', error);
|
|
253
|
-
}
|
|
254
|
-
let messageProperties;
|
|
255
|
-
let observedProperties;
|
|
256
|
-
let uuid;
|
|
257
|
-
let timestamp;
|
|
258
|
-
try {
|
|
259
|
-
const callerProperties = {
|
|
260
|
-
...dynamicProperties,
|
|
261
|
-
...properties ?? {}
|
|
262
|
-
};
|
|
263
|
-
const set = options.set;
|
|
264
|
-
const setOnce = options.setOnce;
|
|
265
|
-
uuid = options.uuid;
|
|
266
|
-
timestamp = options.timestamp;
|
|
267
|
-
if (set) callerProperties['$set'] = set;
|
|
268
|
-
if (setOnce) callerProperties['$set_once'] = setOnce;
|
|
269
|
-
const serializedProperties = JSON.stringify(callerProperties);
|
|
270
|
-
const parsedMessageProperties = JSON.parse(serializedProperties, function(_key, value) {
|
|
271
|
-
return null !== value || Array.isArray(this) ? value : void 0;
|
|
272
|
-
});
|
|
273
|
-
const parsedObservedProperties = JSON.parse(serializedProperties);
|
|
274
|
-
if (!isRecord(parsedMessageProperties) || !isRecord(parsedObservedProperties)) throw new Error('Event properties must serialize to an object');
|
|
275
|
-
messageProperties = parsedMessageProperties;
|
|
276
|
-
observedProperties = parsedObservedProperties;
|
|
277
|
-
} catch (error) {
|
|
278
|
-
this.logger.error('Event properties are not JSON-serializable', error);
|
|
279
|
-
return;
|
|
280
|
-
}
|
|
281
|
-
const preparedSession = this._state.prepareSessionForEvent();
|
|
282
|
-
const session = preparedSession.context;
|
|
283
|
-
const distinctId = this._state.distinctId;
|
|
284
|
-
const deviceId = this._state.deviceId;
|
|
285
|
-
const groups = this._state.groups;
|
|
286
|
-
Object.assign(messageProperties, {
|
|
287
|
-
token: this.projectToken,
|
|
288
|
-
distinct_id: distinctId,
|
|
289
|
-
$device_id: deviceId,
|
|
290
|
-
$groups: groups,
|
|
291
|
-
$session_id: session.sessionId,
|
|
292
|
-
$window_id: session.windowId,
|
|
293
|
-
$lib: 'web',
|
|
294
|
-
$lib_version: version
|
|
295
|
-
});
|
|
296
|
-
Object.assign(observedProperties, {
|
|
297
|
-
token: this.projectToken,
|
|
298
|
-
distinct_id: distinctId,
|
|
299
|
-
$device_id: deviceId,
|
|
300
|
-
$groups: {
|
|
301
|
-
...groups
|
|
302
|
-
},
|
|
303
|
-
$session_id: session.sessionId,
|
|
304
|
-
$window_id: session.windowId,
|
|
305
|
-
$lib: 'web',
|
|
306
|
-
$lib_version: version
|
|
307
|
-
});
|
|
308
|
-
const message = {
|
|
309
|
-
uuid: uuid ?? createId(),
|
|
310
|
-
event,
|
|
311
|
-
distinct_id: distinctId,
|
|
312
|
-
properties: messageProperties,
|
|
313
|
-
timestamp: eventTimestamp(timestamp)
|
|
314
|
-
};
|
|
315
|
-
let bytes;
|
|
316
|
-
try {
|
|
317
|
-
bytes = utf8Bytes(JSON.stringify(message));
|
|
318
|
-
} catch (error) {
|
|
319
|
-
this.logger.error('The finalized event could not be measured', error);
|
|
320
|
-
return;
|
|
321
|
-
}
|
|
322
|
-
const capture = this._captureSink;
|
|
323
|
-
if (immediate ? bytes > MAX_ANALYTICS_BYTES : !capture?.enqueue(message, bytes)) {
|
|
324
|
-
if (bytes > MAX_ANALYTICS_BYTES) this.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
|
|
325
|
-
return;
|
|
326
|
-
}
|
|
327
|
-
if (!this._state.sessionAdmitted(preparedSession)) {
|
|
328
|
-
if (!immediate) capture?.discardQueued(message);
|
|
329
|
-
return;
|
|
330
|
-
}
|
|
331
|
-
if (preparedSession.reason) this._newSessionPublisher.publish({
|
|
332
|
-
...session,
|
|
333
|
-
reason: preparedSession.reason
|
|
334
|
-
});
|
|
335
|
-
this._eventPublisher.publish(deepFreeze({
|
|
336
|
-
event,
|
|
337
|
-
properties: observedProperties
|
|
338
|
-
}));
|
|
339
|
-
if (!immediate) capture?.admitted();
|
|
340
|
-
return message;
|
|
341
|
-
}
|
|
342
|
-
async identify(distinctId, set, setOnce) {
|
|
343
|
-
if (!isValidDistinctId(distinctId) || this._closing || this._disposed) return;
|
|
344
|
-
this._state.prepare();
|
|
345
|
-
const previousDistinctId = this._state.distinctId;
|
|
346
|
-
const wasIdentified = this._state.isIdentified;
|
|
347
|
-
const captureOptions = {};
|
|
348
|
-
if (set) captureOptions.set = set;
|
|
349
|
-
if (setOnce) captureOptions.setOnce = setOnce;
|
|
350
|
-
const hasPersonProperties = !!set || !!setOnce;
|
|
351
|
-
if (distinctId === previousDistinctId) {
|
|
352
|
-
if (wasIdentified) {
|
|
353
|
-
if (hasPersonProperties) {
|
|
354
|
-
this._identifyPublisher.publish({
|
|
355
|
-
distinctId,
|
|
356
|
-
previousDistinctId,
|
|
357
|
-
wasIdentified,
|
|
358
|
-
set,
|
|
359
|
-
setOnce
|
|
360
|
-
});
|
|
361
|
-
this.capture('$set', null, captureOptions);
|
|
362
|
-
}
|
|
363
|
-
} else {
|
|
364
|
-
this._state.identify(distinctId);
|
|
365
|
-
this._identifyPublisher.publish({
|
|
366
|
-
distinctId,
|
|
367
|
-
previousDistinctId,
|
|
368
|
-
wasIdentified,
|
|
369
|
-
set,
|
|
370
|
-
setOnce
|
|
371
|
-
});
|
|
372
|
-
this.capture('$set', null, {
|
|
373
|
-
set: set ?? {},
|
|
374
|
-
setOnce: setOnce ?? {}
|
|
375
|
-
});
|
|
376
|
-
}
|
|
377
|
-
return;
|
|
378
|
-
}
|
|
379
|
-
this._state.identify(distinctId);
|
|
380
|
-
this._identifyPublisher.publish({
|
|
381
|
-
distinctId,
|
|
382
|
-
previousDistinctId,
|
|
383
|
-
wasIdentified,
|
|
384
|
-
set,
|
|
385
|
-
setOnce
|
|
386
|
-
});
|
|
387
|
-
if (wasIdentified) {
|
|
388
|
-
if (hasPersonProperties) this.capture('$set', null, captureOptions);
|
|
389
|
-
} else this.capture('$identify', {
|
|
390
|
-
$anon_distinct_id: previousDistinctId
|
|
391
|
-
}, captureOptions);
|
|
392
|
-
}
|
|
393
|
-
async group(type, key, properties) {
|
|
394
|
-
if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._closing || this._disposed) return;
|
|
395
|
-
this._state.prepare();
|
|
396
|
-
const changed = this._state.group(type, key);
|
|
397
|
-
if (!changed && !properties) return;
|
|
398
|
-
this._groupPublisher.publish({
|
|
399
|
-
type,
|
|
400
|
-
key,
|
|
401
|
-
changed,
|
|
402
|
-
properties
|
|
403
|
-
});
|
|
404
|
-
this.capture('$groupidentify', {
|
|
405
|
-
$group_type: type,
|
|
406
|
-
$group_key: key,
|
|
407
|
-
...properties ? {
|
|
408
|
-
$group_set: properties
|
|
409
|
-
} : {}
|
|
410
|
-
});
|
|
411
|
-
}
|
|
412
|
-
reset() {
|
|
413
|
-
if (this._closing || this._disposed) return;
|
|
414
|
-
this._state.prepare();
|
|
415
|
-
this._state.reset();
|
|
416
|
-
this._resetPublisher.publish(void 0);
|
|
417
|
-
}
|
|
418
162
|
async flush() {
|
|
419
163
|
await this._registry.flush();
|
|
420
164
|
}
|
|
@@ -429,21 +173,6 @@ class PostHogBrowserClient {
|
|
|
429
173
|
hasOptedOut() {
|
|
430
174
|
return 'denied' === this._state.consent;
|
|
431
175
|
}
|
|
432
|
-
registerDynamicEventProperties(producer) {
|
|
433
|
-
if (this._disposed) return {
|
|
434
|
-
dispose () {}
|
|
435
|
-
};
|
|
436
|
-
this._dynamicEventProperties.push(producer);
|
|
437
|
-
let active = true;
|
|
438
|
-
return {
|
|
439
|
-
dispose: ()=>{
|
|
440
|
-
if (!active) return;
|
|
441
|
-
active = false;
|
|
442
|
-
const index = this._dynamicEventProperties.indexOf(producer);
|
|
443
|
-
if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
|
|
444
|
-
}
|
|
445
|
-
};
|
|
446
|
-
}
|
|
447
176
|
sendRequest(path, init) {
|
|
448
177
|
return sendRequest(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
|
|
449
178
|
}
|
|
@@ -519,8 +248,8 @@ class PostHogBrowserClient {
|
|
|
519
248
|
}
|
|
520
249
|
return this._remoteConfigPromise;
|
|
521
250
|
}
|
|
522
|
-
|
|
523
|
-
return this._registry.
|
|
251
|
+
resolveExtension(name) {
|
|
252
|
+
return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
|
|
524
253
|
}
|
|
525
254
|
shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
|
|
526
255
|
if (!this._shutdownPromise) {
|
|
@@ -566,16 +295,17 @@ class PostHogBrowserClient {
|
|
|
566
295
|
} catch (error) {
|
|
567
296
|
this.logger.error('Failed to dispose browser state', error);
|
|
568
297
|
}
|
|
569
|
-
this.
|
|
298
|
+
this._analytics = void 0;
|
|
570
299
|
const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
|
|
571
300
|
this._remoteConfigPublisher.dispose();
|
|
572
301
|
this._eventPublisher.dispose();
|
|
573
302
|
this._identifyPublisher.dispose();
|
|
303
|
+
this._changePropertiesPublisher.dispose();
|
|
574
304
|
this._groupPublisher.dispose();
|
|
305
|
+
this._groupsResetPublisher.dispose();
|
|
575
306
|
this._resetPublisher.dispose();
|
|
576
307
|
this._consentChangePublisher.dispose();
|
|
577
308
|
this._newSessionPublisher.dispose();
|
|
578
|
-
this._dynamicEventProperties.splice(0);
|
|
579
309
|
await Promise.race([
|
|
580
310
|
cleanup,
|
|
581
311
|
timeout
|
|
@@ -589,43 +319,63 @@ class PostHogBrowserClient {
|
|
|
589
319
|
} catch {}
|
|
590
320
|
}
|
|
591
321
|
}
|
|
322
|
+
async _completeInitialization() {
|
|
323
|
+
await this._analytics?.start();
|
|
324
|
+
this._ready = true;
|
|
325
|
+
this._startInitialPageview();
|
|
326
|
+
await this._pageviewLoading;
|
|
327
|
+
}
|
|
592
328
|
_startInitialPageview() {
|
|
593
|
-
if (!this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed) return;
|
|
329
|
+
if (!this._ready || !this._capturePageview || !this._initialPageviewPending || this._closing || this._disposed || !this._pageviewIsVisible()) return;
|
|
330
|
+
this._removePageviewListener();
|
|
331
|
+
if (!this._analytics) return void this._loadInitialPageviewAnalytics();
|
|
332
|
+
this._initialPageviewPending = false;
|
|
333
|
+
if (!this._analytics.captureInitialPageview()) this._initialPageviewPending = !this._disposed && !this._blocked;
|
|
334
|
+
}
|
|
335
|
+
_pageviewIsVisible() {
|
|
594
336
|
let document;
|
|
595
337
|
let visibility;
|
|
596
338
|
try {
|
|
597
339
|
document = globalThis.document;
|
|
598
340
|
visibility = document?.visibilityState;
|
|
599
341
|
} catch {
|
|
600
|
-
this.
|
|
601
|
-
|
|
602
|
-
return;
|
|
342
|
+
this._cancelInitialPageview();
|
|
343
|
+
return false;
|
|
603
344
|
}
|
|
604
345
|
if (!document || void 0 === visibility) {
|
|
605
|
-
this.
|
|
606
|
-
|
|
607
|
-
return;
|
|
346
|
+
this._cancelInitialPageview();
|
|
347
|
+
return false;
|
|
608
348
|
}
|
|
609
349
|
if ('visible' !== visibility) {
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
const listener = ()=>this._startInitialPageview();
|
|
613
|
-
this._pageviewListener = [
|
|
614
|
-
document,
|
|
615
|
-
listener
|
|
616
|
-
];
|
|
617
|
-
try {
|
|
618
|
-
document.addEventListener('visibilitychange', listener);
|
|
619
|
-
} catch {
|
|
620
|
-
this._removePageviewListener();
|
|
621
|
-
this._initialPageviewPending = false;
|
|
622
|
-
}
|
|
623
|
-
}
|
|
624
|
-
return;
|
|
350
|
+
this._watchPageviewVisibility(document);
|
|
351
|
+
return false;
|
|
625
352
|
}
|
|
353
|
+
return true;
|
|
354
|
+
}
|
|
355
|
+
_watchPageviewVisibility(document) {
|
|
356
|
+
if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
|
|
357
|
+
if (this._pageviewListener) return;
|
|
358
|
+
const listener = ()=>this._startInitialPageview();
|
|
359
|
+
this._pageviewListener = [
|
|
360
|
+
document,
|
|
361
|
+
listener
|
|
362
|
+
];
|
|
363
|
+
try {
|
|
364
|
+
document.addEventListener('visibilitychange', listener);
|
|
365
|
+
} catch {
|
|
366
|
+
this._cancelInitialPageview();
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
_cancelInitialPageview() {
|
|
626
370
|
this._removePageviewListener();
|
|
627
371
|
this._initialPageviewPending = false;
|
|
628
|
-
|
|
372
|
+
}
|
|
373
|
+
_loadInitialPageviewAnalytics() {
|
|
374
|
+
if (this._pageviewLoading || this._blocked || this.hasOptedOut()) return;
|
|
375
|
+
this._pageviewLoading = this.resolveExtension('analytics').then(()=>{
|
|
376
|
+
this._pageviewLoading = void 0;
|
|
377
|
+
if (this._analytics) this._startInitialPageview();
|
|
378
|
+
});
|
|
629
379
|
}
|
|
630
380
|
_removePageviewListener() {
|
|
631
381
|
const listener = this._pageviewListener;
|
|
@@ -695,7 +445,7 @@ class PostHogBrowserClient {
|
|
|
695
445
|
}));
|
|
696
446
|
} catch {}
|
|
697
447
|
}
|
|
698
|
-
|
|
448
|
+
_createSharedExtensionClient(extensionName) {
|
|
699
449
|
const host = this;
|
|
700
450
|
const logger = this.logger.createLogger(extensionName);
|
|
701
451
|
const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
|
|
@@ -728,64 +478,114 @@ class PostHogBrowserClient {
|
|
|
728
478
|
return host.canCapture;
|
|
729
479
|
},
|
|
730
480
|
get isRateLimited () {
|
|
731
|
-
return host.isRateLimited;
|
|
481
|
+
return host._analytics?.isRateLimited ?? false;
|
|
732
482
|
},
|
|
733
|
-
capture: (event, properties, options)=>host.capture(event, properties, options),
|
|
734
|
-
registerDynamicEventProperties: (producer)=>host.registerDynamicEventProperties(producer)
|
|
735
|
-
|
|
483
|
+
capture: (event, properties, options)=>host._analytics?.capture(event, properties, options) ?? true,
|
|
484
|
+
registerDynamicEventProperties: (producer)=>host._analytics?.registerDynamicEventProperties(producer) ?? {
|
|
485
|
+
dispose () {}
|
|
486
|
+
},
|
|
487
|
+
getExtension: (name)=>host._registry.getShared(name),
|
|
736
488
|
get projectToken () {
|
|
737
489
|
return host.projectToken;
|
|
738
490
|
},
|
|
739
491
|
sendRequest: (path, init)=>host.sendRequest(path, init),
|
|
740
|
-
onConsentChange: host.onConsentChange,
|
|
741
492
|
onRemoteConfig: host.onRemoteConfig,
|
|
742
|
-
onEvent: host.
|
|
743
|
-
onIdentify: host.onIdentify,
|
|
744
|
-
onGroup: host.onGroup,
|
|
745
|
-
onReset: host.onReset,
|
|
493
|
+
onEvent: host._eventPublisher.listener,
|
|
746
494
|
onSession: host.onSession,
|
|
747
495
|
kv,
|
|
748
496
|
logger
|
|
749
497
|
};
|
|
750
498
|
}
|
|
499
|
+
_createExtensionClient(extensionName, resolve) {
|
|
500
|
+
const host = this;
|
|
501
|
+
const sharedClient = this._createSharedExtensionClient(extensionName);
|
|
502
|
+
const { getExtension: _lookup, capture: _capture, registerDynamicEventProperties: _registration, isRateLimited: _rateLimit, ...capabilities } = Object.getOwnPropertyDescriptors(sharedClient);
|
|
503
|
+
const browserClient = Object.defineProperties({
|
|
504
|
+
sharedClient,
|
|
505
|
+
resolveExtension: (name)=>this._closing || this._disposed ? Promise.resolve(void 0) : resolve(name),
|
|
506
|
+
onConsentChange: host.onConsentChange,
|
|
507
|
+
onIdentify: host.onIdentify,
|
|
508
|
+
onChangeProperties: host._changePropertiesPublisher.listener,
|
|
509
|
+
onGroup: host.onGroup,
|
|
510
|
+
onGroupsReset: host.onGroupsReset,
|
|
511
|
+
onReset: host.onReset
|
|
512
|
+
}, capabilities);
|
|
513
|
+
this._registry.expose(browserClient);
|
|
514
|
+
return browserClient;
|
|
515
|
+
}
|
|
516
|
+
async _setupExtension(extension, host) {
|
|
517
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
518
|
+
if (!isAnalyticsExtension(extension)) {
|
|
519
|
+
await extension.setup(host);
|
|
520
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
this._analytics = extension;
|
|
524
|
+
try {
|
|
525
|
+
extension.bindCaptureHost(this._analyticsCaptureHost(extension));
|
|
526
|
+
await extension.setup(host);
|
|
527
|
+
if (this._closing || this._disposed) throw new Error('The browser client is closing');
|
|
528
|
+
extension.initialize({
|
|
529
|
+
runtime: this._requestRuntime,
|
|
530
|
+
canRetry: ()=>this._canDeliver(),
|
|
531
|
+
reportFailure: (error)=>this.logger.error('Event delivery failed', error),
|
|
532
|
+
reportWarning: (message)=>this.logger.warn(message),
|
|
533
|
+
onAvailable: ()=>this._startInitialPageview()
|
|
534
|
+
});
|
|
535
|
+
} catch (error) {
|
|
536
|
+
if (this._analytics === extension) this._analytics = void 0;
|
|
537
|
+
throw error;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
_canUseAnalytics(owner) {
|
|
541
|
+
return this._analytics === owner && !this._closing && !this._disposed;
|
|
542
|
+
}
|
|
543
|
+
_analyticsCaptureHost(owner) {
|
|
544
|
+
const canMutate = ()=>this._canUseAnalytics(owner);
|
|
545
|
+
return {
|
|
546
|
+
projectToken: this.projectToken,
|
|
547
|
+
logger: this.logger,
|
|
548
|
+
state: this._state,
|
|
549
|
+
canCapture: ()=>canMutate() && !this._blocked && !this.hasOptedOut(),
|
|
550
|
+
canMutate,
|
|
551
|
+
isDisposed: ()=>this._disposed,
|
|
552
|
+
authority: ()=>this._immediateAuthority,
|
|
553
|
+
onEvent: this._eventPublisher.listener,
|
|
554
|
+
publishEvent: (event)=>this._eventPublisher.publish(event),
|
|
555
|
+
publishNewSession: (session)=>this._newSessionPublisher.publish(session),
|
|
556
|
+
publishIdentify: (info)=>this._identifyPublisher.publish(info),
|
|
557
|
+
publishChangeProperties: (info)=>this._changePropertiesPublisher.publish(info),
|
|
558
|
+
publishGroup: (info)=>this._groupPublisher.publish(info),
|
|
559
|
+
publishGroupsReset: ()=>this._groupsResetPublisher.publish(void 0),
|
|
560
|
+
publishReset: ()=>this._resetPublisher.publish(void 0)
|
|
561
|
+
};
|
|
562
|
+
}
|
|
751
563
|
_canDeliver() {
|
|
752
564
|
return !this._disposed && !this._blocked && !this.hasOptedOut();
|
|
753
565
|
}
|
|
754
566
|
}
|
|
755
|
-
const
|
|
756
|
-
const
|
|
757
|
-
const
|
|
758
|
-
|
|
567
|
+
const selectConfiguredExtensions = (configured)=>{
|
|
568
|
+
const selected = new Map();
|
|
569
|
+
for (const extension of configured)if (!selected.has(extension.name)) selected.set(extension.name, extension);
|
|
570
|
+
return selected;
|
|
571
|
+
};
|
|
572
|
+
const createPostHogCore = async (options, configured = options?.extensions ?? [], automaticLoaders = {}, automatic = [])=>{
|
|
573
|
+
const selected = selectConfiguredExtensions(configured);
|
|
574
|
+
const loaders = Object.fromEntries([
|
|
575
|
+
...Object.entries(automaticLoaders),
|
|
576
|
+
...Array.from(selected, ([name, extension])=>[
|
|
577
|
+
name,
|
|
578
|
+
()=>extension
|
|
579
|
+
])
|
|
580
|
+
]);
|
|
581
|
+
const client = PostHog.create(options ?? {
|
|
759
582
|
projectToken: ''
|
|
760
|
-
},
|
|
583
|
+
}, loaders);
|
|
761
584
|
client.getRemoteConfig();
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
runtime: client._requestRuntime,
|
|
767
|
-
canRetry: ()=>client._canDeliver(),
|
|
768
|
-
reportFailure: (error)=>client.logger.error('Event delivery failed', error),
|
|
769
|
-
reportWarning: (message)=>client.logger.warn(message),
|
|
770
|
-
onAvailable: ()=>client._startInitialPageview()
|
|
771
|
-
});
|
|
772
|
-
analyticsReady = true;
|
|
773
|
-
} catch (error) {
|
|
774
|
-
client._captureSink = void 0;
|
|
775
|
-
try {
|
|
776
|
-
await client._registry.rollback(analytics);
|
|
777
|
-
} catch (cleanupError) {
|
|
778
|
-
client.logger.error(`Failed to dispose disabled extension "${analytics.name}"`, cleanupError);
|
|
779
|
-
}
|
|
780
|
-
client.logger.error(`Failed to install configured extension "${analytics.name}"`, error);
|
|
781
|
-
}
|
|
782
|
-
for (const extension of extensions)try {
|
|
783
|
-
await client._registry.install(extension);
|
|
784
|
-
} catch (error) {
|
|
785
|
-
client.logger.error(`Failed to install configured extension "${extension.name}"`, error);
|
|
786
|
-
}
|
|
787
|
-
if (analyticsReady) await analytics.start();
|
|
788
|
-
client._startInitialPageview();
|
|
585
|
+
if (selected.has('analytics')) await client.resolveExtension('analytics');
|
|
586
|
+
for (const name of selected.keys())if ('analytics' !== name) await client.resolveExtension(name);
|
|
587
|
+
for (const extension of automatic)await client._registry.activate(extension);
|
|
588
|
+
await client._completeInitialization();
|
|
789
589
|
return client;
|
|
790
590
|
};
|
|
791
591
|
export { createPostHogCore };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { IPostHogInternal, BrowserExtension } from './browser-client';
|
|
2
|
+
import type { PostHogOptions } from './types';
|
|
3
|
+
import type { AutomaticExtension, ExtensionLoader } from './extensions/registry';
|
|
4
|
+
interface ProductComposition {
|
|
5
|
+
extensions: BrowserExtension[];
|
|
6
|
+
loaders: Record<string, ExtensionLoader<IPostHogInternal>>;
|
|
7
|
+
automatic: AutomaticExtension<IPostHogInternal>[];
|
|
8
|
+
loadingErrors: Array<[string, unknown]>;
|
|
9
|
+
}
|
|
10
|
+
export declare const createProductComposition: (options: PostHogOptions) => ProductComposition;
|
|
11
|
+
export {};
|