@posthog/browser 0.1.1 → 0.3.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 (73) hide show
  1. package/ARCHITECTURE.md +28 -22
  2. package/README.md +94 -29
  3. package/dist/analytics-api.d.ts +32 -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 +87 -0
  10. package/dist/analytics-extension.js +649 -0
  11. package/dist/analytics-extension.mjs +611 -0
  12. package/dist/analytics-internal.d.ts +33 -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-properties.d.ts +12 -0
  17. package/dist/analytics-properties.js +88 -0
  18. package/dist/analytics-properties.mjs +46 -0
  19. package/dist/analytics-session-properties.d.ts +12 -0
  20. package/dist/analytics-session-properties.js +84 -0
  21. package/dist/analytics-session-properties.mjs +46 -0
  22. package/dist/analytics.d.ts +4 -3
  23. package/dist/autocapture.d.ts +2 -2
  24. package/dist/autocapture.js +21 -10
  25. package/dist/autocapture.mjs +21 -10
  26. package/dist/automatic-analytics.d.ts +2 -2
  27. package/dist/browser-client.d.ts +44 -4
  28. package/dist/capture-properties.d.ts +15 -0
  29. package/dist/capture-properties.js +101 -0
  30. package/dist/capture-properties.mjs +57 -0
  31. package/dist/capture-v1.js +7 -19
  32. package/dist/capture-v1.mjs +1 -13
  33. package/dist/core.d.ts +7 -5
  34. package/dist/extensions/registry.d.ts +42 -7
  35. package/dist/extensions/registry.js +194 -37
  36. package/dist/extensions/registry.mjs +194 -37
  37. package/dist/flags-token.d.ts +4 -4
  38. package/dist/flags.js +15 -2
  39. package/dist/flags.mjs +15 -2
  40. package/dist/immutable.d.ts +1 -0
  41. package/dist/immutable.js +46 -0
  42. package/dist/immutable.mjs +8 -0
  43. package/dist/index.d.ts +7 -5
  44. package/dist/index.js +3 -67
  45. package/dist/index.mjs +3 -67
  46. package/dist/key-value-store.d.ts +21 -0
  47. package/dist/key-value-store.js +117 -0
  48. package/dist/key-value-store.mjs +72 -0
  49. package/dist/logs-internal.d.ts +2 -2
  50. package/dist/logs.js +5 -2
  51. package/dist/logs.mjs +5 -2
  52. package/dist/person-processing.d.ts +11 -0
  53. package/dist/person-processing.js +84 -0
  54. package/dist/person-processing.mjs +37 -0
  55. package/dist/posthog.d.ts +4 -3
  56. package/dist/posthog.js +154 -353
  57. package/dist/posthog.mjs +154 -353
  58. package/dist/root-composition.d.ts +11 -0
  59. package/dist/root-composition.js +138 -0
  60. package/dist/root-composition.mjs +100 -0
  61. package/dist/state.d.ts +6 -0
  62. package/dist/state.js +50 -56
  63. package/dist/state.mjs +50 -56
  64. package/dist/surveys-extension.js +11 -6
  65. package/dist/surveys-extension.mjs +11 -6
  66. package/dist/surveys-internal.d.ts +3 -2
  67. package/dist/types.d.ts +13 -19
  68. package/dist/utf8.d.ts +1 -0
  69. package/dist/utf8.js +52 -0
  70. package/dist/utf8.mjs +14 -0
  71. package/dist/version.js +1 -1
  72. package/dist/version.mjs +1 -1
  73. package/package.json +3 -3
@@ -1,60 +1,137 @@
1
1
  class ExtensionRegistry {
2
- constructor(createClient, logger){
2
+ constructor(_createClient, _logger, _loaders = {}, _setup = (extension, host)=>extension.setup(host), _canInstall = ()=>true){
3
+ this._createClient = _createClient;
4
+ this._logger = _logger;
5
+ this._loaders = _loaders;
6
+ this._setup = _setup;
7
+ this._canInstall = _canInstall;
3
8
  this._records = new Map();
9
+ this._retired = new WeakSet();
4
10
  this._extensions = new Map();
11
+ this._shared = new Map();
12
+ this._sharedReservations = new Set();
13
+ this._pending = new Map();
14
+ this._dependencies = new Map();
15
+ this._views = new Set();
16
+ this._clients = new Map();
17
+ this._publications = new WeakMap();
5
18
  this._disposed = false;
6
- this._createClient = createClient;
7
- this._logger = logger;
19
+ }
20
+ expose(target) {
21
+ if (this._disposed || this._views.has(target)) return;
22
+ const publications = new Map();
23
+ this._publications.set(target, publications);
24
+ try {
25
+ for (const extension of this._extensions.values())this._publish(target, extension.name);
26
+ } catch (error) {
27
+ for (const name of publications.keys())this._removePublication(target, name);
28
+ this._publications.delete(target);
29
+ throw error;
30
+ }
31
+ this._views.add(target);
8
32
  }
9
33
  get(name) {
10
34
  return this._extensions.get(name);
11
35
  }
12
- async install(extension) {
13
- if (this._disposed) throw new Error('The extension registry is disposed');
14
- const { name } = extension;
15
- const bindings = [
16
- [
17
- name,
18
- extension
19
- ],
20
- ...Object.entries(extension.bindings ?? {})
21
- ];
22
- const names = new Set();
23
- for (const [key] of bindings){
24
- if (!key || names.has(key) || this._extensions.has(key)) throw new Error(`An extension named "${key}" is already installed or the name is invalid`);
25
- names.add(key);
36
+ getShared(name) {
37
+ return this._shared.get(name);
38
+ }
39
+ resolve(name) {
40
+ if (this._disposed || !this._canInstall()) return Promise.resolve(void 0);
41
+ const existing = this._existingResolution(name);
42
+ if (existing) return existing;
43
+ const load = Object.hasOwn(this._loaders, name) ? this._loaders[name] : void 0;
44
+ if (!load) return Promise.resolve(void 0);
45
+ const loading = Promise.resolve().then(()=>this._load(name, load));
46
+ this._pending.set(name, loading);
47
+ loading.then(()=>{
48
+ if (this._pending.get(name) === loading) this._pending.delete(name);
49
+ });
50
+ return loading;
51
+ }
52
+ async activate({ name, activate }) {
53
+ if (this._disposed || !this._canInstall() || this.get(name)) return;
54
+ try {
55
+ const host = this._client(name);
56
+ this._assertNameAvailable(name);
57
+ await activate(host, ()=>this.resolve(name));
58
+ } catch (error) {
59
+ this._logger.error(`Extension "${name}" activation failed`, error);
26
60
  }
27
- const record = [
28
- extension,
29
- false,
30
- [
31
- ...names
32
- ]
33
- ];
34
- this._records.set(name, record);
35
- for (const [key, target] of bindings)this._extensions.set(key, target);
61
+ }
62
+ async install(extension) {
63
+ const installation = this._reserveInstallation(extension);
64
+ const { name, record } = installation;
36
65
  try {
37
- await extension.setup(this._createClient(name));
38
- if (this._disposed || record[1]) throw new Error('The extension registry was disposed during setup');
66
+ const host = this._client(name);
67
+ this._assertNameAvailable(name);
68
+ await this._setup(extension, host);
69
+ this._publishInstallation(installation);
39
70
  } catch (error) {
40
- if (this._records.get(name) === record) this._removeRecord(record);
71
+ this._removeRecord(record);
72
+ record.finish(void 0);
41
73
  try {
42
74
  await this._disposeRecord(record);
43
75
  } catch (disposeError) {
44
76
  this._logger.error('Extension cleanup failed after setup failed', disposeError);
45
77
  }
46
78
  throw error;
79
+ } finally{
80
+ this._dependencies.delete(name);
47
81
  }
48
82
  }
83
+ _existingResolution(name) {
84
+ const installed = this.get(name);
85
+ if (installed) return Promise.resolve(installed);
86
+ return this._pending.get(name) ?? this._records.get(name)?.ready;
87
+ }
88
+ _reserveInstallation(extension) {
89
+ if (this._disposed) throw new Error('The extension registry is disposed');
90
+ if (this._retired.has(extension)) throw new Error('The extension instance has already been disposed');
91
+ const { name } = extension;
92
+ if (!name || this._records.has(name)) throw new Error(`An extension named "${name}" is already installed or the name is invalid`);
93
+ this._assertNameAvailable(name);
94
+ const bindings = this._bindingEntries(extension);
95
+ let finish;
96
+ const record = {
97
+ extension,
98
+ disposed: false,
99
+ sharedNames: bindings.map(([key])=>key),
100
+ ready: new Promise((resolve)=>{
101
+ finish = resolve;
102
+ }),
103
+ finish: (value)=>finish(value)
104
+ };
105
+ this._records.set(name, record);
106
+ for (const [key] of bindings)this._sharedReservations.add(key);
107
+ return {
108
+ name,
109
+ bindings,
110
+ record
111
+ };
112
+ }
113
+ _bindingEntries(extension) {
114
+ const bindings = Object.entries(extension.bindings ?? {});
115
+ for (const [key] of bindings)if (!key || this._sharedReservations.has(key)) throw new Error(`A shared extension named "${key}" is already installed or the name is invalid`);
116
+ return bindings;
117
+ }
118
+ _publishInstallation({ name, bindings, record }) {
119
+ if (this._disposed || record.disposed || !this._canInstall()) throw new Error('Extension installation stopped during setup');
120
+ this._extensions.set(name, record.extension);
121
+ for (const view of this._views)this._publish(view, name);
122
+ for (const [key, target] of bindings)this._shared.set(key, target);
123
+ record.finish(record.extension);
124
+ }
49
125
  async rollback(extension) {
50
126
  const record = this._records.get(extension.name);
51
- if (record?.[0] === extension) {
127
+ if (record?.extension === extension) {
52
128
  this._removeRecord(record);
129
+ record.finish(void 0);
53
130
  await this._disposeRecord(record);
54
131
  }
55
132
  }
56
133
  async flush(reason = 'flush') {
57
- await Promise.all(Array.from(this._records.values()).map(async ([extension])=>{
134
+ await Promise.all(Array.from(this._extensions.values()).map(async (extension)=>{
58
135
  try {
59
136
  await extension.flush?.(reason);
60
137
  } catch (error) {
@@ -67,23 +144,103 @@ class ExtensionRegistry {
67
144
  this._disposed = true;
68
145
  const records = Array.from(this._records.values()).reverse();
69
146
  this._records.clear();
147
+ for (const name of this._extensions.keys())this._unpublish(name);
70
148
  this._extensions.clear();
149
+ this._shared.clear();
150
+ this._sharedReservations.clear();
151
+ this._dependencies.clear();
152
+ this._views.clear();
153
+ this._clients.clear();
71
154
  await Promise.all(records.map(async (record)=>{
155
+ record.finish(void 0);
72
156
  try {
73
157
  await this._disposeRecord(record);
74
158
  } catch (error) {
75
- this._logger.error(`Extension "${record[0].name}" cleanup failed`, error);
159
+ this._logger.error(`Extension "${record.extension.name}" cleanup failed`, error);
76
160
  }
77
161
  }));
78
162
  }
163
+ _client(name) {
164
+ const existing = this._clients.get(name);
165
+ if (void 0 !== existing) return existing;
166
+ const host = this._createClient(name, (target)=>this._resolveDependency(name, target));
167
+ if (!this._disposed) this._clients.set(name, host);
168
+ return host;
169
+ }
170
+ async _load(name, load) {
171
+ try {
172
+ const host = this._client(name);
173
+ this._assertNameAvailable(name);
174
+ const extension = await load(host);
175
+ if (this._disposed || extension.name !== name) {
176
+ await extension.dispose?.();
177
+ if (!this._disposed) throw new Error(`Loader for "${name}" returned extension "${extension.name}"`);
178
+ return;
179
+ }
180
+ await this.install(extension);
181
+ return this.get(name);
182
+ } catch (error) {
183
+ this._logger.error(`Extension "${name}" loading failed`, error);
184
+ return;
185
+ } finally{
186
+ this._dependencies.delete(name);
187
+ }
188
+ }
189
+ _resolveDependency(owner, target) {
190
+ if (this.get(owner) || this.get(target)) return this.resolve(target);
191
+ if (owner === target || this._reaches(target, owner, new Set())) {
192
+ this._logger.error(`Circular extension dependency: "${owner}" -> "${target}"`, new Error('Circular extension dependency'));
193
+ return Promise.resolve(void 0);
194
+ }
195
+ let dependencies = this._dependencies.get(owner);
196
+ if (!dependencies) this._dependencies.set(owner, dependencies = new Set());
197
+ dependencies.add(target);
198
+ return this.resolve(target);
199
+ }
200
+ _reaches(from, target, visited) {
201
+ if (from === target) return true;
202
+ if (visited.has(from)) return false;
203
+ visited.add(from);
204
+ for (const next of this._dependencies.get(from) ?? [])if (this._reaches(next, target, visited)) return true;
205
+ return false;
206
+ }
79
207
  _removeRecord(record) {
80
- this._records.delete(record[0].name);
81
- for (const name of record[2])this._extensions.delete(name);
208
+ const name = record.extension.name;
209
+ if (this._records.get(name) !== record) return;
210
+ this._records.delete(name);
211
+ this._extensions.delete(name);
212
+ this._unpublish(name);
213
+ for (const key of record.sharedNames){
214
+ this._shared.delete(key);
215
+ this._sharedReservations.delete(key);
216
+ }
217
+ }
218
+ _assertNameAvailable(name) {
219
+ for (const view of this._views)if (name in view) throw new Error(`Extension name "${name}" conflicts with a client capability`);
220
+ }
221
+ _publish(view, name) {
222
+ if (name in view) throw new Error(`Extension name "${name}" conflicts with a client capability`);
223
+ const read = ()=>this.get(name);
224
+ Object.defineProperty(view, name, {
225
+ enumerable: true,
226
+ configurable: true,
227
+ get: read
228
+ });
229
+ this._publications.get(view)?.set(name, read);
230
+ }
231
+ _removePublication(view, name) {
232
+ const read = this._publications.get(view)?.get(name);
233
+ if (read && Object.getOwnPropertyDescriptor(view, name)?.get === read) Reflect.deleteProperty(view, name);
234
+ this._publications.get(view)?.delete(name);
235
+ }
236
+ _unpublish(name) {
237
+ for (const view of this._views)this._removePublication(view, name);
82
238
  }
83
239
  async _disposeRecord(record) {
84
- if (!record[1]) {
85
- record[1] = true;
86
- await record[0].dispose?.();
240
+ if (!record.disposed) {
241
+ record.disposed = true;
242
+ this._retired.add(record.extension);
243
+ await record.extension.dispose?.();
87
244
  }
88
245
  }
89
246
  }
@@ -1,8 +1,8 @@
1
- import type { Disposable, Extension, ExtensionToken } from '@posthog/browser-common';
1
+ import type { Disposable, ExtensionToken } from '@posthog/browser-common';
2
2
  import type { FeatureFlagResult, FeatureFlagsReloadResult, FlagsCallback, JsonType } from './flags-options';
3
- import type { BrowserClient } from './browser-client';
4
- export interface FeatureFlags extends Extension {
5
- setup(client: BrowserClient): void | Promise<void>;
3
+ import type { IPostHogInternal, BrowserExtension } from './browser-client';
4
+ export interface FeatureFlags extends BrowserExtension {
5
+ setup(client: IPostHogInternal): void | Promise<void>;
6
6
  getFeatureFlag(key: string): FeatureFlagResult | undefined;
7
7
  /** Refresh remotely and await its outcome. Calls during an active evaluation wait for a follow-up request. */
8
8
  reloadFeatureFlags(): Promise<FeatureFlagsReloadResult>;
package/dist/flags.js CHANGED
@@ -63,6 +63,7 @@ const flags = (options = {})=>{
63
63
  const extension = {
64
64
  name: external_flags_token_js_namespaceObject.FeatureFlagsExtension,
65
65
  bindings: {
66
+ featureFlags: shared,
66
67
  [extension_tokens_namespaceObject.FeatureFlagsCommonExtension]: shared
67
68
  },
68
69
  getSurveyContext: ()=>({
@@ -71,17 +72,25 @@ const flags = (options = {})=>{
71
72
  }),
72
73
  setup: async (value)=>{
73
74
  client = value;
74
- await shared.setup(value);
75
+ await value.resolveExtension('analytics');
75
76
  if (disposed) return;
76
- subscriptions.push(value.onIdentify(({ distinctId, previousDistinctId, wasIdentified, set, setOnce })=>{
77
+ await shared.setup(value.sharedClient);
78
+ if (disposed) return;
79
+ subscriptions.push(value.onIdentify(({ distinctId, previousDistinctId, wasIdentified })=>{
77
80
  if (distinctId !== previousDistinctId) {
78
81
  shared.resetFlagCallReported();
79
82
  if (!wasIdentified) shared.setAnonymousDistinctId(previousDistinctId);
80
83
  }
84
+ shared.reloadFeatureFlags();
85
+ }));
86
+ subscriptions.push(value.onChangeProperties(({ set, setOnce, unset })=>{
81
87
  if (set || setOnce) shared.setPersonPropertiesForFlags({
82
88
  $set: set ?? {},
83
89
  $set_once: setOnce ?? {}
84
90
  }, false);
91
+ if (unset) shared.unsetPersonPropertiesForFlags([
92
+ ...unset
93
+ ], false);
85
94
  shared.reloadFeatureFlags();
86
95
  }));
87
96
  subscriptions.push(value.onGroup(({ type, changed, properties })=>{
@@ -91,6 +100,10 @@ const flags = (options = {})=>{
91
100
  }, false);
92
101
  shared.reloadFeatureFlags();
93
102
  }));
103
+ subscriptions.push(value.onGroupsReset(()=>{
104
+ shared.resetGroupPropertiesForFlags();
105
+ shared.reloadFeatureFlags();
106
+ }));
94
107
  subscriptions.push(value.onEvent(()=>shared.sendFlagCallsPendingCapture()));
95
108
  subscriptions.push(value.onReset(()=>{
96
109
  shared.reset();
package/dist/flags.mjs CHANGED
@@ -30,6 +30,7 @@ const flags = (options = {})=>{
30
30
  const extension = {
31
31
  name: FeatureFlagsExtension,
32
32
  bindings: {
33
+ featureFlags: shared,
33
34
  [FeatureFlagsCommonExtension]: shared
34
35
  },
35
36
  getSurveyContext: ()=>({
@@ -38,17 +39,25 @@ const flags = (options = {})=>{
38
39
  }),
39
40
  setup: async (value)=>{
40
41
  client = value;
41
- await shared.setup(value);
42
+ await value.resolveExtension('analytics');
42
43
  if (disposed) return;
43
- subscriptions.push(value.onIdentify(({ distinctId, previousDistinctId, wasIdentified, set, setOnce })=>{
44
+ await shared.setup(value.sharedClient);
45
+ if (disposed) return;
46
+ subscriptions.push(value.onIdentify(({ distinctId, previousDistinctId, wasIdentified })=>{
44
47
  if (distinctId !== previousDistinctId) {
45
48
  shared.resetFlagCallReported();
46
49
  if (!wasIdentified) shared.setAnonymousDistinctId(previousDistinctId);
47
50
  }
51
+ shared.reloadFeatureFlags();
52
+ }));
53
+ subscriptions.push(value.onChangeProperties(({ set, setOnce, unset })=>{
48
54
  if (set || setOnce) shared.setPersonPropertiesForFlags({
49
55
  $set: set ?? {},
50
56
  $set_once: setOnce ?? {}
51
57
  }, false);
58
+ if (unset) shared.unsetPersonPropertiesForFlags([
59
+ ...unset
60
+ ], false);
52
61
  shared.reloadFeatureFlags();
53
62
  }));
54
63
  subscriptions.push(value.onGroup(({ type, changed, properties })=>{
@@ -58,6 +67,10 @@ const flags = (options = {})=>{
58
67
  }, false);
59
68
  shared.reloadFeatureFlags();
60
69
  }));
70
+ subscriptions.push(value.onGroupsReset(()=>{
71
+ shared.resetGroupPropertiesForFlags();
72
+ shared.reloadFeatureFlags();
73
+ }));
61
74
  subscriptions.push(value.onEvent(()=>shared.sendFlagCallsPendingCapture()));
62
75
  subscriptions.push(value.onReset(()=>{
63
76
  shared.reset();
@@ -0,0 +1 @@
1
+ export declare const deepFreeze: <T>(value: T) => T;
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.d = (exports1, getters, values)=>{
5
+ var define = (defs, kind)=>{
6
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
7
+ enumerable: true,
8
+ [kind]: defs[key]
9
+ });
10
+ };
11
+ define(getters, "get");
12
+ define(values, "value");
13
+ };
14
+ })();
15
+ (()=>{
16
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
17
+ })();
18
+ (()=>{
19
+ __webpack_require__.r = (exports1)=>{
20
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
21
+ value: 'Module'
22
+ });
23
+ Object.defineProperty(exports1, '__esModule', {
24
+ value: true
25
+ });
26
+ };
27
+ })();
28
+ var __webpack_exports__ = {};
29
+ __webpack_require__.r(__webpack_exports__);
30
+ const deepFreeze = (value)=>{
31
+ if (value && 'object' == typeof value) {
32
+ Object.values(value).forEach(deepFreeze);
33
+ Object.freeze(value);
34
+ }
35
+ return value;
36
+ };
37
+ __webpack_require__.d(__webpack_exports__, {}, {
38
+ deepFreeze: deepFreeze
39
+ });
40
+ exports.deepFreeze = __webpack_exports__.deepFreeze;
41
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
42
+ "deepFreeze"
43
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
44
+ Object.defineProperty(exports, '__esModule', {
45
+ value: true
46
+ });
@@ -0,0 +1,8 @@
1
+ const deepFreeze = (value)=>{
2
+ if (value && 'object' == typeof value) {
3
+ Object.values(value).forEach(deepFreeze);
4
+ Object.freeze(value);
5
+ }
6
+ return value;
7
+ };
8
+ export { deepFreeze };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,13 @@
1
- import type { PostHog, PostHogOptions } from './types';
2
- /** Creates a browser client with first-party analytics delivery loaded lazily by default. */
3
- export declare const createPostHog: (options: PostHogOptions) => Promise<PostHog>;
1
+ import type { IPostHog, PostHogOptions } from './types';
2
+ /** Creates a browser host with on-demand first-party analytics acquisition. */
3
+ export declare const createPostHog: (options: PostHogOptions) => Promise<IPostHog>;
4
+ export type { IAnalytics } from './analytics-api';
4
5
  export { version } from './version';
5
6
  export { FeatureFlagsExtension, type FeatureFlags } from './flags-token';
6
- export type { BrowserClient, IdentifyInfo, GroupInfo } from './browser-client';
7
- export type { AnalyticsConfiguration, AnalyticsOptions, ApiResponse, AutomaticAnalyticsOptions, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, LoadStrategy, NewSessionInfo, NewSessionReason, PostHog, PostHogOptions, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from './types';
7
+ export type { IPostHogInternal, BrowserExtension, IdentifyInfo, GroupInfo } from './browser-client';
8
+ export type { AnalyticsConfiguration, AnalyticsOptions, ApiResponse, AutomaticAnalyticsOptions, BrowserFetch, BrowserNavigator, CaptureOptions, CaptureOutcome, CaptureOutcomeStatus, CaptureSummary, CorePostHogOptions, Disposable, Extension, LoadStrategy, NewSessionInfo, NewSessionReason, IPostHog, PostHogOptions, RemoteConfig, SendRequestInit, SessionContext, StorageLike, } from './types';
8
9
  export type { FlagsOptions, FlagsConfiguration, FlagsCallback, FeatureFlagResult, FeatureFlagsReloadResult, } from './flags-options';
9
10
  export type { LogsOptions, LogsConfiguration, CaptureLogOptions } from './logs-options';
10
11
  export type { SurveysOptions, SurveysConfiguration, Survey, SurveyCallback, DisplaySurveyOptions, SurveyRenderReason, } from './surveys-options';
11
12
  export type { AutocaptureOptions, AutocaptureConfiguration, RageclickOptions } from './autocapture-options';
13
+ export type { PersonProfileMode } from './analytics-options';
package/dist/index.js CHANGED
@@ -32,77 +32,13 @@ __webpack_require__.d(__webpack_exports__, {
32
32
  createPostHog: ()=>createPostHog,
33
33
  version: ()=>external_version_js_namespaceObject.version
34
34
  });
35
- const external_autocapture_options_js_namespaceObject = require("./autocapture-options.js");
36
- const external_surveys_options_js_namespaceObject = require("./surveys-options.js");
37
- const external_logs_options_js_namespaceObject = require("./logs-options.js");
38
35
  const external_posthog_js_namespaceObject = require("./posthog.js");
39
- const external_analytics_internal_js_namespaceObject = require("./analytics-internal.js");
40
- const external_automatic_analytics_js_namespaceObject = require("./automatic-analytics.js");
36
+ const external_root_composition_js_namespaceObject = require("./root-composition.js");
41
37
  const external_version_js_namespaceObject = require("./version.js");
42
38
  const external_flags_token_js_namespaceObject = require("./flags-token.js");
43
39
  const createPostHog = async (options)=>{
44
- const extensions = [
45
- ...options?.extensions ?? []
46
- ];
47
- const loadingErrors = [];
48
- const install = (label, matches, load, prepend = false)=>{
49
- if (extensions.some(matches)) return;
50
- const add = (extension)=>{
51
- if (prepend) extensions.unshift(extension);
52
- else extensions.push(extension);
53
- };
54
- const failed = (error)=>{
55
- if (error) loadingErrors.push([
56
- label,
57
- error
58
- ]);
59
- };
60
- try {
61
- const extension = load();
62
- if (extension instanceof Promise) return extension.then(add).catch(failed);
63
- if (extension) add(extension);
64
- } catch (error) {
65
- failed(error);
66
- }
67
- };
68
- install('analytics', external_analytics_internal_js_namespaceObject.isAnalyticsExtension, ()=>{
69
- let configuration = {
70
- load: 'lazy'
71
- };
72
- try {
73
- configuration = options?.analytics ?? configuration;
74
- } catch {}
75
- return false === configuration ? void 0 : (0, external_automatic_analytics_js_namespaceObject.analytics)(configuration);
76
- }, true);
77
- const flagsLoading = install('flags', (extension)=>'featureFlags' === extension.name, ()=>{
78
- const configuration = options?.flags;
79
- if (false === configuration) return;
80
- const snapshot = configuration && JSON.parse(JSON.stringify(configuration));
81
- return import("./flags.js").then(({ flags })=>flags(snapshot));
82
- });
83
- if (flagsLoading) await flagsLoading;
84
- const logsLoading = install('logs', (extension)=>'logs' === extension.name, ()=>{
85
- const configuration = options?.logs;
86
- if (false === configuration) return;
87
- const snapshot = (0, external_logs_options_js_namespaceObject.snapshotLogsOptions)(configuration);
88
- return import("./logs.js").then(({ logs })=>logs(snapshot));
89
- });
90
- if (logsLoading) await logsLoading;
91
- const surveysLoading = install('surveys', (extension)=>'surveys' === extension.name, ()=>{
92
- const configuration = options?.surveys;
93
- if (false === configuration) return;
94
- const snapshot = (0, external_surveys_options_js_namespaceObject.snapshotSurveysOptions)(configuration);
95
- return import("./automatic-surveys.js").then(({ surveys })=>surveys(snapshot));
96
- });
97
- if (surveysLoading) await surveysLoading;
98
- const autocaptureLoading = install('autocapture', (extension)=>'autocapture' === extension.name, ()=>{
99
- const configuration = options?.autocapture;
100
- if (false === configuration) return;
101
- const snapshot = (0, external_autocapture_options_js_namespaceObject.snapshotAutocaptureOptions)(configuration);
102
- return import("./autocapture.js").then(({ autocapture })=>autocapture(snapshot));
103
- });
104
- if (autocaptureLoading) await autocaptureLoading;
105
- const client = await (0, external_posthog_js_namespaceObject.createPostHogCore)(options, extensions);
40
+ const { extensions, loaders, automatic, loadingErrors } = (0, external_root_composition_js_namespaceObject.createProductComposition)(options);
41
+ const client = await (0, external_posthog_js_namespaceObject.createPostHogCore)(options, extensions, loaders, automatic);
106
42
  for (const [label, error] of loadingErrors.reverse())client.logger.error(`Automatic ${label} loading failed`, error);
107
43
  return client;
108
44
  };
package/dist/index.mjs CHANGED
@@ -1,72 +1,8 @@
1
- import { snapshotAutocaptureOptions } from "./autocapture-options.mjs";
2
- import { snapshotSurveysOptions } from "./surveys-options.mjs";
3
- import { snapshotLogsOptions } from "./logs-options.mjs";
4
1
  import { createPostHogCore } from "./posthog.mjs";
5
- import { isAnalyticsExtension } from "./analytics-internal.mjs";
6
- import { analytics } from "./automatic-analytics.mjs";
2
+ import { createProductComposition } from "./root-composition.mjs";
7
3
  const createPostHog = async (options)=>{
8
- const extensions = [
9
- ...options?.extensions ?? []
10
- ];
11
- const loadingErrors = [];
12
- const install = (label, matches, load, prepend = false)=>{
13
- if (extensions.some(matches)) return;
14
- const add = (extension)=>{
15
- if (prepend) extensions.unshift(extension);
16
- else extensions.push(extension);
17
- };
18
- const failed = (error)=>{
19
- if (error) loadingErrors.push([
20
- label,
21
- error
22
- ]);
23
- };
24
- try {
25
- const extension = load();
26
- if (extension instanceof Promise) return extension.then(add).catch(failed);
27
- if (extension) add(extension);
28
- } catch (error) {
29
- failed(error);
30
- }
31
- };
32
- install('analytics', isAnalyticsExtension, ()=>{
33
- let configuration = {
34
- load: 'lazy'
35
- };
36
- try {
37
- configuration = options?.analytics ?? configuration;
38
- } catch {}
39
- return false === configuration ? void 0 : analytics(configuration);
40
- }, true);
41
- const flagsLoading = install('flags', (extension)=>'featureFlags' === extension.name, ()=>{
42
- const configuration = options?.flags;
43
- if (false === configuration) return;
44
- const snapshot = configuration && JSON.parse(JSON.stringify(configuration));
45
- return import("./flags.mjs").then(({ flags })=>flags(snapshot));
46
- });
47
- if (flagsLoading) await flagsLoading;
48
- const logsLoading = install('logs', (extension)=>'logs' === extension.name, ()=>{
49
- const configuration = options?.logs;
50
- if (false === configuration) return;
51
- const snapshot = snapshotLogsOptions(configuration);
52
- return import("./logs.mjs").then(({ logs })=>logs(snapshot));
53
- });
54
- if (logsLoading) await logsLoading;
55
- const surveysLoading = install('surveys', (extension)=>'surveys' === extension.name, ()=>{
56
- const configuration = options?.surveys;
57
- if (false === configuration) return;
58
- const snapshot = snapshotSurveysOptions(configuration);
59
- return import("./automatic-surveys.mjs").then(({ surveys })=>surveys(snapshot));
60
- });
61
- if (surveysLoading) await surveysLoading;
62
- const autocaptureLoading = install('autocapture', (extension)=>'autocapture' === extension.name, ()=>{
63
- const configuration = options?.autocapture;
64
- if (false === configuration) return;
65
- const snapshot = snapshotAutocaptureOptions(configuration);
66
- return import("./autocapture.mjs").then(({ autocapture })=>autocapture(snapshot));
67
- });
68
- if (autocaptureLoading) await autocaptureLoading;
69
- const client = await createPostHogCore(options, extensions);
4
+ const { extensions, loaders, automatic, loadingErrors } = createProductComposition(options);
5
+ const client = await createPostHogCore(options, extensions, loaders, automatic);
70
6
  for (const [label, error] of loadingErrors.reverse())client.logger.error(`Automatic ${label} loading failed`, error);
71
7
  return client;
72
8
  };
@@ -0,0 +1,21 @@
1
+ import type { KeyValueStore } from '@posthog/browser-common';
2
+ import type { StorageLike } from './types';
3
+ export declare const cloneJson: <T>(value: T) => T;
4
+ interface StoreContext {
5
+ values(): Record<string, unknown>;
6
+ save(): void;
7
+ canAccess(): boolean;
8
+ }
9
+ /** Own, bound methods preserve the shared KV contract, including copied views. */
10
+ export declare const createKeyValueStore: (context: StoreContext) => KeyValueStore;
11
+ /** Core-owned per-tab buffer; failed native access falls back to this buffer. */
12
+ export declare class TabValues {
13
+ private readonly _key;
14
+ private readonly _storage;
15
+ private _values;
16
+ private _backend;
17
+ constructor(_key: string, _storage: () => StorageLike | undefined);
18
+ values(): Record<string, unknown>;
19
+ save(): void;
20
+ }
21
+ export {};