@posthog/browser 0.1.0 → 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.
Files changed (72) hide show
  1. package/ARCHITECTURE.md +29 -23
  2. package/README.md +66 -30
  3. package/dist/analytics-api.d.ts +26 -0
  4. package/dist/analytics-api.js +18 -0
  5. package/dist/analytics-api.mjs +1 -0
  6. package/dist/analytics-buffer.d.ts +3 -3
  7. package/dist/analytics-buffer.js +2 -161
  8. package/dist/analytics-buffer.mjs +2 -161
  9. package/dist/analytics-extension.d.ts +76 -0
  10. package/dist/analytics-extension.js +589 -0
  11. package/dist/analytics-extension.mjs +551 -0
  12. package/dist/analytics-internal.d.ts +32 -18
  13. package/dist/analytics-options.d.ts +7 -2
  14. package/dist/analytics-options.js +38 -1
  15. package/dist/analytics-options.mjs +17 -1
  16. package/dist/analytics.d.ts +4 -3
  17. package/dist/autocapture.d.ts +2 -2
  18. package/dist/autocapture.js +21 -10
  19. package/dist/autocapture.mjs +21 -10
  20. package/dist/automatic-analytics.d.ts +2 -2
  21. package/dist/browser-client.d.ts +44 -4
  22. package/dist/capture-properties.d.ts +9 -0
  23. package/dist/capture-properties.js +68 -0
  24. package/dist/capture-properties.mjs +30 -0
  25. package/dist/capture-v1.js +7 -19
  26. package/dist/capture-v1.mjs +1 -13
  27. package/dist/core.d.ts +7 -5
  28. package/dist/extensions/registry.d.ts +42 -7
  29. package/dist/extensions/registry.js +194 -37
  30. package/dist/extensions/registry.mjs +194 -37
  31. package/dist/flags-token.d.ts +4 -4
  32. package/dist/flags.js +16 -2
  33. package/dist/flags.mjs +16 -2
  34. package/dist/immutable.d.ts +1 -0
  35. package/dist/immutable.js +46 -0
  36. package/dist/immutable.mjs +8 -0
  37. package/dist/index.d.ts +7 -5
  38. package/dist/index.js +3 -67
  39. package/dist/index.mjs +3 -67
  40. package/dist/lane.js +1 -1
  41. package/dist/lane.mjs +1 -1
  42. package/dist/logs-internal.d.ts +2 -2
  43. package/dist/logs.js +5 -2
  44. package/dist/logs.mjs +5 -2
  45. package/dist/person-processing.d.ts +11 -0
  46. package/dist/person-processing.js +84 -0
  47. package/dist/person-processing.mjs +37 -0
  48. package/dist/posthog.d.ts +4 -3
  49. package/dist/posthog.js +155 -349
  50. package/dist/posthog.mjs +155 -349
  51. package/dist/rate-limiter.d.ts +5 -0
  52. package/dist/rate-limiter.js +14 -8
  53. package/dist/rate-limiter.mjs +14 -8
  54. package/dist/root-composition.d.ts +11 -0
  55. package/dist/root-composition.js +138 -0
  56. package/dist/root-composition.mjs +100 -0
  57. package/dist/state.d.ts +1 -0
  58. package/dist/state.js +4 -0
  59. package/dist/state.mjs +4 -0
  60. package/dist/surveys-extension.js +11 -6
  61. package/dist/surveys-extension.mjs +11 -6
  62. package/dist/surveys-internal.d.ts +3 -2
  63. package/dist/surveys.d.ts +0 -1
  64. package/dist/surveys.js +1 -4
  65. package/dist/surveys.mjs +1 -4
  66. package/dist/types.d.ts +13 -19
  67. package/dist/utf8.d.ts +1 -0
  68. package/dist/utf8.js +52 -0
  69. package/dist/utf8.mjs +14 -0
  70. package/dist/version.js +1 -1
  71. package/dist/version.mjs +1 -1
  72. package/package.json +3 -3
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 { createAnalyticsExtension } from "./analytics-buffer.mjs";
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 { createId } from "./id.mjs";
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
- const eventTimestamp = (timestamp)=>{
63
- try {
64
- return (timestamp ?? new Date()).toISOString();
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._captureSink?.purge();
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._captureSink = capture;
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,220 +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
- capture(event, properties = null, options = {}) {
202
- try {
203
- if ('unload' === options.delivery && !this._captureSink?.isTearingDown) {
204
- const authority = this._immediateAuthority;
205
- const message = this._admitCapture(event, properties, options, false, true);
206
- if (message) this._captureSink?.deliverUnload(message, ()=>this._immediateAuthority === authority);
207
- return;
208
- }
209
- } catch (error) {
210
- this.logger.error('Unload capture failed', error);
211
- return;
212
- }
213
- this._capture(event, properties, options);
214
- }
215
- async captureImmediate(event, properties = null, options = {}) {
216
- try {
217
- const authority = this._immediateAuthority;
218
- const message = this._admitCapture(event, properties, options, false, true);
219
- if (!message) return EMPTY_CAPTURE_SUMMARY;
220
- const capture = this._captureSink;
221
- if (!capture) return captureFailure(new Error('Immediate analytics delivery is unavailable'));
222
- return await capture.deliverImmediate(message, ()=>this._immediateAuthority === authority);
223
- } catch (error) {
224
- return captureFailure(error);
225
- }
226
- }
227
- _capture(event, properties = null, options = {}, skipRateLimit = false) {
228
- return void 0 !== this._admitCapture(event, properties, options, skipRateLimit, false);
229
- }
230
- _admitCapture(event, properties, options, skipRateLimit, immediate) {
231
- if (!isNonEmptyString(event) || this._closing || this._disposed || this._blocked || this.hasOptedOut() || !this._state.prepare()) return;
232
- if (!skipRateLimit) {
233
- const rateLimit = this._rateLimiter.consume();
234
- if (!rateLimit.allowed) {
235
- if (void 0 !== rateLimit.reportDropped) {
236
- const warning = `${rateLimit.reportDropped} event(s) dropped since the last warning. Client limit is 10 events per second with a burst of 100.`;
237
- this.logger.warn(`PostHog client rate limited: ${warning}`);
238
- if (this._capture(CLIENT_RATE_LIMIT_WARNING, {
239
- $$client_ingestion_warning_message: `posthog-js client rate limited: ${warning}`
240
- }, {}, true)) this._rateLimiter.reported();
241
- }
242
- return;
243
- }
244
- }
245
- const dynamicProperties = {};
246
- for (const producer of this._dynamicEventProperties.slice())try {
247
- Object.assign(dynamicProperties, producer());
248
- } catch (error) {
249
- this.logger.error('An event property producer failed', error);
250
- }
251
- let messageProperties;
252
- let observedProperties;
253
- let uuid;
254
- let timestamp;
255
- try {
256
- const callerProperties = {
257
- ...dynamicProperties,
258
- ...properties ?? {}
259
- };
260
- const set = options.set;
261
- const setOnce = options.setOnce;
262
- uuid = options.uuid;
263
- timestamp = options.timestamp;
264
- if (set) callerProperties['$set'] = set;
265
- if (setOnce) callerProperties['$set_once'] = setOnce;
266
- const serializedProperties = JSON.stringify(callerProperties);
267
- const parsedMessageProperties = JSON.parse(serializedProperties, function(_key, value) {
268
- return null !== value || Array.isArray(this) ? value : void 0;
269
- });
270
- const parsedObservedProperties = JSON.parse(serializedProperties);
271
- if (!isRecord(parsedMessageProperties) || !isRecord(parsedObservedProperties)) throw new Error('Event properties must serialize to an object');
272
- messageProperties = parsedMessageProperties;
273
- observedProperties = parsedObservedProperties;
274
- } catch (error) {
275
- this.logger.error('Event properties are not JSON-serializable', error);
276
- return;
277
- }
278
- const preparedSession = this._state.prepareSessionForEvent();
279
- const session = preparedSession.context;
280
- const distinctId = this._state.distinctId;
281
- const deviceId = this._state.deviceId;
282
- const groups = this._state.groups;
283
- Object.assign(messageProperties, {
284
- token: this.projectToken,
285
- distinct_id: distinctId,
286
- $device_id: deviceId,
287
- $groups: groups,
288
- $session_id: session.sessionId,
289
- $window_id: session.windowId,
290
- $lib: 'web',
291
- $lib_version: version
292
- });
293
- Object.assign(observedProperties, {
294
- token: this.projectToken,
295
- distinct_id: distinctId,
296
- $device_id: deviceId,
297
- $groups: {
298
- ...groups
299
- },
300
- $session_id: session.sessionId,
301
- $window_id: session.windowId,
302
- $lib: 'web',
303
- $lib_version: version
304
- });
305
- const message = {
306
- uuid: uuid ?? createId(),
307
- event,
308
- distinct_id: distinctId,
309
- properties: messageProperties,
310
- timestamp: eventTimestamp(timestamp)
311
- };
312
- let bytes;
313
- try {
314
- bytes = utf8Bytes(JSON.stringify(message));
315
- } catch (error) {
316
- this.logger.error('The finalized event could not be measured', error);
317
- return;
318
- }
319
- const capture = this._captureSink;
320
- if (immediate ? bytes > MAX_ANALYTICS_BYTES : !capture?.enqueue(message, bytes)) {
321
- if (bytes > MAX_ANALYTICS_BYTES) this.logger.warn(`Event "${event}" (${bytes} bytes) exceeds the local analytics limit and was dropped`);
322
- return;
323
- }
324
- if (!this._state.sessionAdmitted(preparedSession)) {
325
- if (!immediate) capture?.discardQueued(message);
326
- return;
327
- }
328
- if (preparedSession.reason) this._newSessionPublisher.publish({
329
- ...session,
330
- reason: preparedSession.reason
331
- });
332
- this._eventPublisher.publish(deepFreeze({
333
- event,
334
- properties: observedProperties
335
- }));
336
- if (!immediate) capture?.admitted();
337
- return message;
338
- }
339
- async identify(distinctId, set, setOnce) {
340
- if (!isValidDistinctId(distinctId) || this._closing || this._disposed) return;
341
- this._state.prepare();
342
- const previousDistinctId = this._state.distinctId;
343
- const wasIdentified = this._state.isIdentified;
344
- const captureOptions = {};
345
- if (set) captureOptions.set = set;
346
- if (setOnce) captureOptions.setOnce = setOnce;
347
- const hasPersonProperties = !!set || !!setOnce;
348
- if (distinctId === previousDistinctId) {
349
- if (wasIdentified) {
350
- if (hasPersonProperties) {
351
- this._identifyPublisher.publish({
352
- distinctId,
353
- previousDistinctId,
354
- wasIdentified,
355
- set,
356
- setOnce
357
- });
358
- this.capture('$set', null, captureOptions);
359
- }
360
- } else {
361
- this._state.identify(distinctId);
362
- this._identifyPublisher.publish({
363
- distinctId,
364
- previousDistinctId,
365
- wasIdentified,
366
- set,
367
- setOnce
368
- });
369
- this.capture('$set', null, {
370
- set: set ?? {},
371
- setOnce: setOnce ?? {}
372
- });
373
- }
374
- return;
375
- }
376
- this._state.identify(distinctId);
377
- this._identifyPublisher.publish({
378
- distinctId,
379
- previousDistinctId,
380
- wasIdentified,
381
- set,
382
- setOnce
383
- });
384
- if (wasIdentified) {
385
- if (hasPersonProperties) this.capture('$set', null, captureOptions);
386
- } else this.capture('$identify', {
387
- $anon_distinct_id: previousDistinctId
388
- }, captureOptions);
389
- }
390
- async group(type, key, properties) {
391
- if (!isNonEmptyString(type) || !isNonEmptyString(key) || this._closing || this._disposed) return;
392
- this._state.prepare();
393
- const changed = this._state.group(type, key);
394
- if (!changed && !properties) return;
395
- this._groupPublisher.publish({
396
- type,
397
- key,
398
- changed,
399
- properties
400
- });
401
- this.capture('$groupidentify', {
402
- $group_type: type,
403
- $group_key: key,
404
- ...properties ? {
405
- $group_set: properties
406
- } : {}
407
- });
408
- }
409
- reset() {
410
- if (this._closing || this._disposed) return;
411
- this._state.prepare();
412
- this._state.reset();
413
- this._resetPublisher.publish(void 0);
414
- }
415
162
  async flush() {
416
163
  await this._registry.flush();
417
164
  }
@@ -426,21 +173,6 @@ class PostHogBrowserClient {
426
173
  hasOptedOut() {
427
174
  return 'denied' === this._state.consent;
428
175
  }
429
- registerDynamicEventProperties(producer) {
430
- if (this._disposed) return {
431
- dispose () {}
432
- };
433
- this._dynamicEventProperties.push(producer);
434
- let active = true;
435
- return {
436
- dispose: ()=>{
437
- if (!active) return;
438
- active = false;
439
- const index = this._dynamicEventProperties.indexOf(producer);
440
- if (-1 !== index) this._dynamicEventProperties.splice(index, 1);
441
- }
442
- };
443
- }
444
176
  sendRequest(path, init) {
445
177
  return sendRequest(this._requestRuntime, path, init, ()=>!this._blocked && !this.hasOptedOut());
446
178
  }
@@ -516,8 +248,8 @@ class PostHogBrowserClient {
516
248
  }
517
249
  return this._remoteConfigPromise;
518
250
  }
519
- getExtension(name) {
520
- return this._registry.get(name);
251
+ resolveExtension(name) {
252
+ return this._closing || this._disposed ? Promise.resolve(void 0) : this._registry.resolve(name);
521
253
  }
522
254
  shutdown(shutdownTimeoutMs = DEFAULT_SHUTDOWN_TIMEOUT_MS) {
523
255
  if (!this._shutdownPromise) {
@@ -563,16 +295,17 @@ class PostHogBrowserClient {
563
295
  } catch (error) {
564
296
  this.logger.error('Failed to dispose browser state', error);
565
297
  }
566
- this._captureSink = void 0;
298
+ this._analytics = void 0;
567
299
  const cleanup = this._registry.dispose().catch((error)=>this.logger.error('Failed to dispose extensions', error));
568
300
  this._remoteConfigPublisher.dispose();
569
301
  this._eventPublisher.dispose();
570
302
  this._identifyPublisher.dispose();
303
+ this._changePropertiesPublisher.dispose();
571
304
  this._groupPublisher.dispose();
305
+ this._groupsResetPublisher.dispose();
572
306
  this._resetPublisher.dispose();
573
307
  this._consentChangePublisher.dispose();
574
308
  this._newSessionPublisher.dispose();
575
- this._dynamicEventProperties.splice(0);
576
309
  await Promise.race([
577
310
  cleanup,
578
311
  timeout
@@ -586,43 +319,63 @@ class PostHogBrowserClient {
586
319
  } catch {}
587
320
  }
588
321
  }
322
+ async _completeInitialization() {
323
+ await this._analytics?.start();
324
+ this._ready = true;
325
+ this._startInitialPageview();
326
+ await this._pageviewLoading;
327
+ }
589
328
  _startInitialPageview() {
590
- 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() {
591
336
  let document;
592
337
  let visibility;
593
338
  try {
594
339
  document = globalThis.document;
595
340
  visibility = document?.visibilityState;
596
341
  } catch {
597
- this._removePageviewListener();
598
- this._initialPageviewPending = false;
599
- return;
342
+ this._cancelInitialPageview();
343
+ return false;
600
344
  }
601
345
  if (!document || void 0 === visibility) {
602
- this._removePageviewListener();
603
- this._initialPageviewPending = false;
604
- return;
346
+ this._cancelInitialPageview();
347
+ return false;
605
348
  }
606
349
  if ('visible' !== visibility) {
607
- if (this._pageviewListener?.[0] !== document) this._removePageviewListener();
608
- if (!this._pageviewListener) {
609
- const listener = ()=>this._startInitialPageview();
610
- this._pageviewListener = [
611
- document,
612
- listener
613
- ];
614
- try {
615
- document.addEventListener('visibilitychange', listener);
616
- } catch {
617
- this._removePageviewListener();
618
- this._initialPageviewPending = false;
619
- }
620
- }
621
- return;
350
+ this._watchPageviewVisibility(document);
351
+ return false;
622
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() {
623
370
  this._removePageviewListener();
624
371
  this._initialPageviewPending = false;
625
- if (!this._capture('$pageview')) this._initialPageviewPending = !this._disposed && !this._blocked;
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
+ });
626
379
  }
627
380
  _removePageviewListener() {
628
381
  const listener = this._pageviewListener;
@@ -692,7 +445,7 @@ class PostHogBrowserClient {
692
445
  }));
693
446
  } catch {}
694
447
  }
695
- _createExtensionClient(extensionName) {
448
+ _createSharedExtensionClient(extensionName) {
696
449
  const host = this;
697
450
  const logger = this.logger.createLogger(extensionName);
698
451
  const kv = this._state.keyValueStore(extensionName, ()=>!this._closing && !this._disposed && this._state.prepare());
@@ -724,62 +477,115 @@ class PostHogBrowserClient {
724
477
  get canCapture () {
725
478
  return host.canCapture;
726
479
  },
727
- capture: (event, properties, options)=>host.capture(event, properties, options),
728
- registerDynamicEventProperties: (producer)=>host.registerDynamicEventProperties(producer),
729
- getExtension: (name)=>host.getExtension(name),
480
+ get isRateLimited () {
481
+ return host._analytics?.isRateLimited ?? false;
482
+ },
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),
730
488
  get projectToken () {
731
489
  return host.projectToken;
732
490
  },
733
491
  sendRequest: (path, init)=>host.sendRequest(path, init),
734
- onConsentChange: host.onConsentChange,
735
492
  onRemoteConfig: host.onRemoteConfig,
736
- onEvent: host.onEvent,
737
- onIdentify: host.onIdentify,
738
- onGroup: host.onGroup,
739
- onReset: host.onReset,
493
+ onEvent: host._eventPublisher.listener,
740
494
  onSession: host.onSession,
741
495
  kv,
742
496
  logger
743
497
  };
744
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
+ }
745
563
  _canDeliver() {
746
564
  return !this._disposed && !this._blocked && !this.hasOptedOut();
747
565
  }
748
566
  }
749
- const createPostHogCore = async (options, configured = options?.extensions ?? [])=>{
750
- const analytics = configured.find(isAnalyticsExtension) ?? createAnalyticsExtension();
751
- const extensions = configured.filter((extension)=>extension !== analytics);
752
- const client = PostHogBrowserClient.create(options ?? {
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 ?? {
753
582
  projectToken: ''
754
- }, analytics);
583
+ }, loaders);
755
584
  client.getRemoteConfig();
756
- let analyticsReady = false;
757
- try {
758
- await client._registry.install(analytics);
759
- analytics.initialize({
760
- runtime: client._requestRuntime,
761
- canRetry: ()=>client._canDeliver(),
762
- reportFailure: (error)=>client.logger.error('Event delivery failed', error),
763
- reportWarning: (message)=>client.logger.warn(message),
764
- onAvailable: ()=>client._startInitialPageview()
765
- });
766
- analyticsReady = true;
767
- } catch (error) {
768
- client._captureSink = void 0;
769
- try {
770
- await client._registry.rollback(analytics);
771
- } catch (cleanupError) {
772
- client.logger.error(`Failed to dispose disabled extension "${analytics.name}"`, cleanupError);
773
- }
774
- client.logger.error(`Failed to install configured extension "${analytics.name}"`, error);
775
- }
776
- for (const extension of extensions)try {
777
- await client._registry.install(extension);
778
- } catch (error) {
779
- client.logger.error(`Failed to install configured extension "${extension.name}"`, error);
780
- }
781
- if (analyticsReady) await analytics.start();
782
- 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();
783
589
  return client;
784
590
  };
785
591
  export { createPostHogCore };
@@ -14,6 +14,11 @@ export declare class ClientRateLimiter {
14
14
  private _unreportedDropped;
15
15
  constructor(_eventsPerSecond?: number, _burst?: number, _clock?: () => number);
16
16
  consume(): ClientRateLimitResult;
17
+ /** Whether `consume()` refuses a token now. It changes no state. */
18
+ get wouldLimit(): boolean;
19
+ /** Whether the last consumed token was refused. */
20
+ get limited(): boolean;
17
21
  reported(): void;
22
+ private _tokensAt;
18
23
  private _now;
19
24
  }