@posthog/electron 0.0.1 → 0.1.1

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.
@@ -0,0 +1,591 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _posthog_core_error_tracking = require("@posthog/core/error-tracking");
3
+ let _posthog_core_utils = require("@posthog/core/utils");
4
+ let _posthog_browser_common_autocapture = require("@posthog/browser-common/autocapture");
5
+ let _posthog_browser_common_constants = require("@posthog/browser-common/constants");
6
+ //#region src/shared/exception-autocapture.ts
7
+ /** Never let reporting failures escape a runtime's global error dispatch. */
8
+ function createExceptionObserver(canCapture, capture, isIgnored = () => false) {
9
+ const limiter = new _posthog_core_utils.BucketedRateLimiter({
10
+ ...(0, _posthog_core_utils.resolveExceptionRateLimiterConfig)(),
11
+ refillInterval: 1e3,
12
+ _logger: (0, _posthog_core_utils.createLogger)("[PostHog]", () => {})
13
+ });
14
+ let capturing = false;
15
+ return (error, mechanism, source) => {
16
+ try {
17
+ if (capturing || !canCapture()) return;
18
+ capturing = true;
19
+ try {
20
+ if (isIgnored(error, mechanism) || limiter.consumeRateLimit("exceptions")) return;
21
+ capture(error, { $exception_source: source }, { mechanism: {
22
+ type: mechanism,
23
+ handled: false
24
+ } }).catch(() => {});
25
+ } finally {
26
+ capturing = false;
27
+ }
28
+ } catch {}
29
+ };
30
+ }
31
+ //#endregion
32
+ //#region src/renderer/exception-autocapture.ts
33
+ function startRendererExceptionAutocapture(canCapture, capture) {
34
+ const observe = createExceptionObserver(canCapture, capture);
35
+ const error = (event) => {
36
+ if (event instanceof ErrorEvent) observe(event, "onerror", "browser.window_onerror");
37
+ };
38
+ const rejection = (event) => {
39
+ observe(event, "onunhandledrejection", "browser.unhandledrejection");
40
+ };
41
+ window.addEventListener("error", error);
42
+ window.addEventListener("unhandledrejection", rejection);
43
+ return () => {
44
+ window.removeEventListener("error", error);
45
+ window.removeEventListener("unhandledrejection", rejection);
46
+ };
47
+ }
48
+ //#endregion
49
+ //#region src/shared/protocol.ts
50
+ const BRIDGE_KEY = "__POSTHOG_ELECTRON__";
51
+ function isFlagContextCommand(command) {
52
+ return command.type === "setPersonPropertiesForFlags" || command.type === "setGroupPropertiesForFlags" || command.type === "resetPersonPropertiesForFlags" || command.type === "resetGroupPropertiesForFlags";
53
+ }
54
+ //#endregion
55
+ //#region src/renderer/autocapture.ts
56
+ const AUTOCAPTURE_CONFIG_KEYS = [
57
+ "maskAllText",
58
+ "maskAllElementAttributes",
59
+ "disableCaptureUrlHashes",
60
+ "url_allowlist",
61
+ "url_ignorelist",
62
+ "dom_event_allowlist",
63
+ "element_allowlist",
64
+ "css_selector_allowlist",
65
+ "css_selector_ignorelist",
66
+ "element_attribute_ignorelist"
67
+ ];
68
+ /** Volatile extension state only; main owns the durable project config cache. */
69
+ var AutocaptureStore = class {
70
+ constructor() {
71
+ this.values = /* @__PURE__ */ new Map();
72
+ }
73
+ initialize() {}
74
+ get(key) {
75
+ if (typeof key === "string") return this.values.get(key);
76
+ return Object.fromEntries(key.filter((name) => this.values.has(name)).map((name) => [name, this.values.get(name)]));
77
+ }
78
+ set(key, value) {
79
+ if (typeof key === "string") this.values.set(key, value);
80
+ else for (const [name, item] of Object.entries(key)) this.values.set(name, item);
81
+ }
82
+ remove(keys) {
83
+ for (const key of typeof keys === "string" ? [keys] : keys) this.values.delete(key);
84
+ }
85
+ };
86
+ var RendererAutocapture = class {
87
+ constructor(host, config) {
88
+ this.host = host;
89
+ this.config = config;
90
+ this.disposed = false;
91
+ this.active = false;
92
+ this.loading = false;
93
+ this.retryDelay = 1e3;
94
+ }
95
+ update(paused) {
96
+ if (this.disposed) return;
97
+ const state = this.host.getState();
98
+ if (paused || state.optedOut || state.generation !== this.generation) this.stop();
99
+ if (paused || state.optedOut) return;
100
+ this.active = true;
101
+ this.generation = state.generation;
102
+ if (!this.extension) {
103
+ const kv = new AutocaptureStore();
104
+ if (typeof state.autocapture?.autocapture_opt_out === "boolean") kv.set(_posthog_browser_common_constants.AUTOCAPTURE_DISABLED_SERVER_SIDE, state.autocapture.autocapture_opt_out);
105
+ const extension = new _posthog_browser_common_autocapture.Autocapture({ refresh: (config) => {
106
+ for (const key of AUTOCAPTURE_CONFIG_KEYS) if (this.config[key] !== void 0) Object.assign(config, { [key]: this.config[key] });
107
+ const current = this.host.getState();
108
+ config.enabled = !this.disposed && !current.optedOut && current.autocapture?.status !== "pending";
109
+ config.remoteRequestsDisabled = current.autocapture?.status === "disabled";
110
+ } });
111
+ this.extension = extension;
112
+ const host = this.host;
113
+ const adapter = {
114
+ get distinctId() {
115
+ return host.getState().distinctId;
116
+ },
117
+ kv,
118
+ onRemoteConfig: (listener) => {
119
+ this.remoteListener = listener;
120
+ return { dispose: () => {
121
+ this.remoteListener = void 0;
122
+ } };
123
+ },
124
+ capture: (event, properties) => {
125
+ host.capture(event, properties ?? void 0);
126
+ return true;
127
+ }
128
+ };
129
+ try {
130
+ extension.setup(adapter);
131
+ } catch (error) {
132
+ this.stop();
133
+ host.onError(error);
134
+ return;
135
+ }
136
+ }
137
+ const remote = state.autocapture;
138
+ if (remote?.status === "loaded") this.remoteListener?.({
139
+ ok: true,
140
+ config: remote
141
+ });
142
+ if (remote?.status === "failed") {
143
+ if (remote.elementsChainAsString) this.remoteListener?.({
144
+ ok: true,
145
+ config: {
146
+ elementsChainAsString: remote.elementsChainAsString,
147
+ ...typeof remote.autocapture_opt_out === "boolean" ? { autocapture_opt_out: remote.autocapture_opt_out } : {}
148
+ }
149
+ });
150
+ this.remoteListener?.({ ok: false });
151
+ }
152
+ if (remote?.status === "disabled") this.extension?.startIfEnabled();
153
+ if (remote?.status === "loaded" || remote?.status === "disabled") {
154
+ clearTimeout(this.retryTimer);
155
+ this.retryTimer = void 0;
156
+ this.retryDelay = 1e3;
157
+ }
158
+ if (this.requestedGeneration !== state.generation && remote?.status !== "disabled") this.loadConfig();
159
+ else if (remote?.status === "failed") this.scheduleRetry();
160
+ }
161
+ loadConfig() {
162
+ if (this.disposed || !this.active || this.loading) return;
163
+ this.loading = true;
164
+ this.requestedGeneration = this.host.getState().generation;
165
+ this.host.loadConfig().catch((error) => this.host.onError(error)).finally(() => {
166
+ this.loading = false;
167
+ if (this.disposed || !this.active) return;
168
+ if (this.requestedGeneration !== this.host.getState().generation) this.update(false);
169
+ else this.scheduleRetry();
170
+ });
171
+ }
172
+ scheduleRetry() {
173
+ const status = this.host.getState().autocapture?.status;
174
+ if (this.disposed || !this.active || this.loading || this.retryTimer || status === "loaded" || status === "disabled") return;
175
+ this.retryTimer = setTimeout(() => {
176
+ this.retryTimer = void 0;
177
+ this.loadConfig();
178
+ }, this.retryDelay);
179
+ this.retryDelay = Math.min(this.retryDelay * 2, 6e4);
180
+ }
181
+ stop() {
182
+ this.active = false;
183
+ clearTimeout(this.retryTimer);
184
+ this.retryTimer = void 0;
185
+ this.retryDelay = 1e3;
186
+ this.requestedGeneration = void 0;
187
+ this.extension?.dispose();
188
+ this.extension = void 0;
189
+ this.remoteListener = void 0;
190
+ }
191
+ dispose() {
192
+ this.disposed = true;
193
+ this.stop();
194
+ }
195
+ };
196
+ //#endregion
197
+ //#region src/renderer/index.ts
198
+ const bridgeSequences = /* @__PURE__ */ new WeakMap();
199
+ var PostHog = class {
200
+ constructor(_bridge, _options = {}) {
201
+ this._bridge = _bridge;
202
+ this._options = _options;
203
+ this._autocapturePauses = 0;
204
+ this._pendingOptOuts = 0;
205
+ this._reportedFlags = /* @__PURE__ */ new Set();
206
+ this._tail = Promise.resolve();
207
+ this._listeners = /* @__PURE__ */ new Set();
208
+ this._disposed = false;
209
+ this._builder = new _posthog_core_error_tracking.ErrorPropertiesBuilder([
210
+ new _posthog_core_error_tracking.ErrorEventCoercer(),
211
+ new _posthog_core_error_tracking.PromiseRejectionEventCoercer(),
212
+ new _posthog_core_error_tracking.ErrorCoercer(),
213
+ new _posthog_core_error_tracking.ObjectCoercer(),
214
+ new _posthog_core_error_tracking.StringCoercer(),
215
+ new _posthog_core_error_tracking.PrimitiveCoercer()
216
+ ], (0, _posthog_core_error_tracking.createDefaultStackParser)());
217
+ this._inOnError = false;
218
+ this._reportedFailures = /* @__PURE__ */ new WeakSet();
219
+ if (_options.autocapture) this._autocapture = new RendererAutocapture({
220
+ getState: () => {
221
+ const state = this._state;
222
+ if (!state) throw new Error("PostHog renderer is not ready");
223
+ return {
224
+ generation: state.generation,
225
+ distinctId: state.distinctId,
226
+ optedOut: state.optedOut,
227
+ autocapture: state.autocapture
228
+ };
229
+ },
230
+ capture: (event, properties) => this.capture(event, properties),
231
+ loadConfig: () => this._send({ type: "loadAutocaptureConfig" }),
232
+ onError: (error) => this._report(error)
233
+ }, typeof _options.autocapture === "object" ? _options.autocapture : {});
234
+ this._unsubscribe = this._bridge.subscribe((state) => this._update(state));
235
+ }
236
+ _update(state) {
237
+ if (this._disposed || this._state && state.revision <= this._state.revision) return;
238
+ if (this._state?.generation !== state.generation || this._state?.flagRevision !== state.flagRevision || this._state?.sessionId !== state.sessionId || this._state?.optedOut !== state.optedOut) this._reportedFlags = /* @__PURE__ */ new Set();
239
+ this._state = structuredClone(state);
240
+ this._autocapture?.update(this._autocapturePauses > 0);
241
+ for (const listener of this._listeners) try {
242
+ listener(this.getState());
243
+ } catch {}
244
+ }
245
+ async _send(command) {
246
+ const generation = this._state?.generation ?? 0;
247
+ structuredClone(command);
248
+ const snapshot = JSON.parse(JSON.stringify(command));
249
+ const dispatched = this._tail.then(() => {
250
+ if (this._disposed) throw new Error("PostHog renderer has been disposed");
251
+ if (command.type === "exception" && !this._canCaptureException()) return { response: void 0 };
252
+ const sequence = (bridgeSequences.get(this._bridge) ?? 0) + 1;
253
+ bridgeSequences.set(this._bridge, sequence);
254
+ return { response: this._bridge.request({
255
+ version: 1,
256
+ sequence,
257
+ generation,
258
+ command: snapshot
259
+ }) };
260
+ });
261
+ const operation = dispatched.then(async ({ response: pending }) => {
262
+ if (!pending) return;
263
+ const response = await pending;
264
+ if (!response.ok) throw new Error(response.error);
265
+ this._update(response.state);
266
+ });
267
+ const networkBound = command.type === "flush" || command.type === "reloadFeatureFlags" || command.type === "loadAutocaptureConfig" || isFlagContextCommand(command) && command.reloadFeatureFlags;
268
+ this._tail = (networkBound ? dispatched : operation).catch(() => {});
269
+ return operation;
270
+ }
271
+ _pauseAutocapture(command) {
272
+ this._autocapturePauses++;
273
+ if (this._state) this._autocapture?.update(true);
274
+ return this._send(command).finally(() => {
275
+ this._autocapturePauses--;
276
+ if (this._state) this._autocapture?.update(this._autocapturePauses > 0);
277
+ });
278
+ }
279
+ async ready() {
280
+ if (this._disposed) throw new Error("PostHog renderer has been disposed");
281
+ await (this._ready ??= this._send({ type: "hello" }).catch((error) => {
282
+ this._ready = void 0;
283
+ throw error;
284
+ }));
285
+ if (!this._disposed && !this._stopExceptionAutocapture && this._options.enableExceptionAutocapture === true && typeof window !== "undefined") this._stopExceptionAutocapture = startRendererExceptionAutocapture(() => this._canCaptureException(), (error, properties, hint) => this._captureException(error, properties, hint));
286
+ }
287
+ _report(error) {
288
+ const inOnError = this._inOnError;
289
+ this._inOnError = true;
290
+ try {
291
+ const result = this._options.onError?.(error);
292
+ if (typeof result?.then === "function") Promise.resolve(result).catch(() => {});
293
+ } catch {} finally {
294
+ this._inOnError = inOnError;
295
+ }
296
+ }
297
+ _reportFailure(promise, quiet = this._inOnError) {
298
+ promise.catch((error) => {
299
+ if (quiet) return;
300
+ if (typeof error === "object" && error !== null) this._reportedFailures.add(error);
301
+ this._report(error);
302
+ });
303
+ }
304
+ /** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
305
+ capture(event, properties) {
306
+ if (typeof event !== "string" || this.hasOptedOutCapturing()) return;
307
+ this._reportFailure(this._send({
308
+ type: "capture",
309
+ event,
310
+ ...properties ? { properties } : {}
311
+ }));
312
+ }
313
+ /**
314
+ * Link the current distinct ID to an alias without switching identity or reloading flags.
315
+ * Ignored when opted out or personProfiles is 'never'. Resolves after local persistence, not delivery.
316
+ */
317
+ alias(alias) {
318
+ if (!alias?.trim()) return Promise.resolve();
319
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
320
+ return this._send({
321
+ type: "alias",
322
+ alias
323
+ });
324
+ }
325
+ /**
326
+ * Capture an event-only $screen; name wins over properties.$screen_name without setting persistent screen context.
327
+ * Fire-and-forget: never throws or rejects; ignored when opted out.
328
+ */
329
+ screen(name, properties) {
330
+ if (typeof name !== "string" || !name.trim()) return;
331
+ if (this.hasOptedOutCapturing()) return;
332
+ this._reportFailure(this._send({
333
+ type: "screen",
334
+ name,
335
+ ...properties ? { properties } : {}
336
+ }));
337
+ }
338
+ /**
339
+ * Update the current person's $set/$set_once properties without changing identity; empty updates do nothing.
340
+ * Also updates flag context. Resolves after local persistence, not delivery or the background flag refresh.
341
+ * Ignored when opted out or personProfiles is 'never'.
342
+ */
343
+ setPersonProperties(properties, propertiesOnce) {
344
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
345
+ return this._send({
346
+ type: "setPersonProperties",
347
+ ...properties ? { properties } : {},
348
+ ...propertiesOnce ? { propertiesOnce } : {}
349
+ });
350
+ }
351
+ /**
352
+ * Merge a call-time copy of local person overrides for flag evaluation, without updating the person profile.
353
+ * Accepts nested $set/$set_once; empty input does nothing. Otherwise awaits persistence and, by default, a refresh attempt.
354
+ * With false, only saves context; cached flag values stay unchanged until a reload.
355
+ */
356
+ setPersonPropertiesForFlags(properties, reloadFeatureFlags = true) {
357
+ return this._send({
358
+ type: "setPersonPropertiesForFlags",
359
+ properties,
360
+ reloadFeatureFlags
361
+ });
362
+ }
363
+ /**
364
+ * Merge a call-time copy of local overrides by group type, without changing profiles or group membership.
365
+ * Empty input does nothing. Otherwise awaits persistence and, by default, a flag refresh attempt.
366
+ * With false, only saves context; cached flag values stay unchanged until a reload.
367
+ */
368
+ setGroupPropertiesForFlags(properties, reloadFeatureFlags = true) {
369
+ return this._send({
370
+ type: "setGroupPropertiesForFlags",
371
+ properties,
372
+ reloadFeatureFlags
373
+ });
374
+ }
375
+ /**
376
+ * Clear all local person flag overrides, not profile data or identity. Resolves after persistence.
377
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
378
+ */
379
+ resetPersonPropertiesForFlags(reloadFeatureFlags = false) {
380
+ return this._send({
381
+ type: "resetPersonPropertiesForFlags",
382
+ reloadFeatureFlags
383
+ });
384
+ }
385
+ /**
386
+ * Clear local flag overrides for every group type, not profiles or membership. Resolves after persistence.
387
+ * Cached flag values stay unchanged unless true is passed to also await a refresh attempt.
388
+ */
389
+ resetGroupPropertiesForFlags(reloadFeatureFlags = false) {
390
+ return this._send({
391
+ type: "resetGroupPropertiesForFlags",
392
+ reloadFeatureFlags
393
+ });
394
+ }
395
+ identify(distinctId, properties) {
396
+ return this._pauseAutocapture({
397
+ type: "identify",
398
+ distinctId,
399
+ ...properties ? { properties } : {}
400
+ });
401
+ }
402
+ reset() {
403
+ return this._pauseAutocapture({ type: "reset" });
404
+ }
405
+ group(groupType, groupKey, properties) {
406
+ if (this.hasOptedOutCapturing()) return Promise.resolve();
407
+ return this._send({
408
+ type: "group",
409
+ groupType,
410
+ groupKey,
411
+ ...properties ? { properties } : {}
412
+ });
413
+ }
414
+ register(properties) {
415
+ return this._send({
416
+ type: "register",
417
+ properties
418
+ });
419
+ }
420
+ unregister(key) {
421
+ return this._send({
422
+ type: "unregister",
423
+ key
424
+ });
425
+ }
426
+ optIn() {
427
+ return this._send({ type: "optIn" });
428
+ }
429
+ optOut() {
430
+ this._pendingOptOuts++;
431
+ return this._pauseAutocapture({ type: "optOut" }).finally(() => {
432
+ this._pendingOptOuts--;
433
+ });
434
+ }
435
+ /**
436
+ * Refresh flags using the shared identity/context after earlier mutations, then persist and synchronize the cache.
437
+ * A failed fetch normally retains cached flags and resolves; completion does not guarantee fresh values.
438
+ */
439
+ reloadFeatureFlags() {
440
+ return this._send({ type: "reloadFeatureFlags" });
441
+ }
442
+ /** Compatibility alias for reloadFeatureFlags(), with the same completion and failure semantics. */
443
+ reloadFeatureFlagsAsync() {
444
+ return this.reloadFeatureFlags();
445
+ }
446
+ flush() {
447
+ return this._send({ type: "flush" });
448
+ }
449
+ /** Fire-and-forget: never throws or rejects. Failed requests are reported through `onError`. */
450
+ captureException(error, properties) {
451
+ const reported = typeof error === "object" && error !== null && this._reportedFailures.has(error);
452
+ this._reportFailure(this._captureException(error, properties), this._inOnError || reported);
453
+ }
454
+ _canCaptureException() {
455
+ return !this._disposed && !this._pendingOptOuts && !this._state?.disabled && !this.hasOptedOutCapturing();
456
+ }
457
+ _captureException(error, properties, hint) {
458
+ if (!this._canCaptureException()) return Promise.resolve();
459
+ try {
460
+ const exception = this._builder.buildFromUnknown(error, hint);
461
+ return this._send({
462
+ type: "exception",
463
+ properties: {
464
+ ...properties,
465
+ ...exception
466
+ }
467
+ });
468
+ } catch {
469
+ return Promise.resolve();
470
+ }
471
+ }
472
+ getDistinctId() {
473
+ return this._state?.distinctId ?? "";
474
+ }
475
+ /** Return the shared anonymous ID, stable across identify and rotated by reset; '' before synchronization. */
476
+ getAnonymousId() {
477
+ return this._state?.anonymousId ?? "";
478
+ }
479
+ /** Cached consent state; conservatively true until the first synchronized snapshot. */
480
+ get optedOut() {
481
+ return this.hasOptedOutCapturing();
482
+ }
483
+ getSessionId() {
484
+ return this._state?.sessionId ?? "";
485
+ }
486
+ hasOptedOutCapturing() {
487
+ return this._state?.optedOut ?? true;
488
+ }
489
+ /**
490
+ * Read the cached value without fetching. A missing key is false with a nonempty cache, otherwise undefined.
491
+ * Reports a deduplicated exposure for the observed snapshot by default; sendFeatureFlagEvent: false suppresses it.
492
+ */
493
+ getFeatureFlag(key, options) {
494
+ const flags = this._state?.featureFlags;
495
+ const value = flags && Object.prototype.hasOwnProperty.call(flags, key) ? flags[key] : flags && Object.keys(flags).length > 0 ? false : void 0;
496
+ if ((options?.sendFeatureFlagEvent ?? options?.sendEvent) !== false && this._state) {
497
+ const reportedFlags = this._reportedFlags;
498
+ const reportKey = JSON.stringify([key, value ?? null]);
499
+ if (!reportedFlags.has(reportKey)) {
500
+ reportedFlags.add(reportKey);
501
+ this._send({
502
+ type: "flag",
503
+ key,
504
+ flagRevision: this._state.flagRevision,
505
+ value: value ?? null
506
+ }).catch(() => reportedFlags.delete(reportKey));
507
+ }
508
+ }
509
+ return value;
510
+ }
511
+ isFeatureEnabled(key, options) {
512
+ if (options?.defaultValue !== void 0) {
513
+ const result = this.getFeatureFlagResult(key, options);
514
+ return result === void 0 ? options.defaultValue : Boolean(result.variant ?? result.enabled);
515
+ }
516
+ const value = this.getFeatureFlag(key, options);
517
+ return value === void 0 ? void 0 : Boolean(value);
518
+ }
519
+ /**
520
+ * Return a copied cached result, or undefined for unknown/unavailable flags; never fetches.
521
+ * Empty variants are disabled. Reports exposure by default; sendFeatureFlagEvent: false suppresses it.
522
+ */
523
+ getFeatureFlagResult(key, options) {
524
+ this.getFeatureFlag(key, options);
525
+ if (!this._state || !Object.prototype.hasOwnProperty.call(this._state.featureFlags, key)) return void 0;
526
+ const value = this._state.featureFlags[key];
527
+ return {
528
+ key,
529
+ enabled: Boolean(value),
530
+ ...typeof value === "string" ? { variant: value } : {},
531
+ payload: this.getFeatureFlagPayload(key) ?? null
532
+ };
533
+ }
534
+ /** Return copied cached results (empty when unavailable), without fetching or reporting exposures. */
535
+ getAllFeatureFlags() {
536
+ return Object.keys(this._state?.featureFlags ?? {}).map((key) => this.getFeatureFlagResult(key, { sendFeatureFlagEvent: false }));
537
+ }
538
+ /**
539
+ * Read a copied, decoded cached payload without fetching or reporting exposure.
540
+ * Missing payloads are null once flags are loaded, otherwise undefined; strings are not decoded again.
541
+ */
542
+ getFeatureFlagPayload(key) {
543
+ const payloads = this._state?.featureFlagPayloads;
544
+ const value = payloads && Object.prototype.hasOwnProperty.call(payloads, key) ? payloads[key] : void 0;
545
+ return value === void 0 ? this._state?.flagsLoaded ? null : void 0 : structuredClone(value);
546
+ }
547
+ getState() {
548
+ if (!this._state) throw new Error("PostHog renderer is not ready");
549
+ return structuredClone(this._state);
550
+ }
551
+ onStateChange(callback) {
552
+ this._listeners.add(callback);
553
+ if (this._state) callback(this.getState());
554
+ return () => this._listeners.delete(callback);
555
+ }
556
+ dispose() {
557
+ if (this._disposed) return;
558
+ this._disposed = true;
559
+ this._stopExceptionAutocapture?.();
560
+ this._stopExceptionAutocapture = void 0;
561
+ this._autocapture?.dispose();
562
+ this._unsubscribe();
563
+ this._listeners.clear();
564
+ this._reportedFlags.clear();
565
+ if (singleton === this) singleton = void 0;
566
+ }
567
+ };
568
+ let singleton;
569
+ let initializing;
570
+ function init(options = {}) {
571
+ if (initializing) return initializing;
572
+ if (singleton) return Promise.resolve(singleton);
573
+ const bridge = globalThis[BRIDGE_KEY];
574
+ if (!bridge) return Promise.reject(/* @__PURE__ */ new Error("PostHog preload bridge is missing; configure your Electron preload"));
575
+ const client = new PostHog(bridge, options);
576
+ initializing = client.ready().then(() => {
577
+ singleton = client;
578
+ return client;
579
+ }).catch((error) => {
580
+ client.dispose();
581
+ throw error;
582
+ }).finally(() => {
583
+ initializing = void 0;
584
+ });
585
+ return initializing;
586
+ }
587
+ //#endregion
588
+ exports.PostHog = PostHog;
589
+ exports.init = init;
590
+
591
+ //# sourceMappingURL=renderer.cjs.map