@philcrp/analytics 1.6.3 → 1.6.5

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/dist/server.js ADDED
@@ -0,0 +1,766 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/server.ts
21
+ var server_exports = {};
22
+ __export(server_exports, {
23
+ AnalyticsManager: () => AnalyticsManager,
24
+ PostHogAnalyticsProvider: () => PostHogAnalyticsProvider,
25
+ PostHogNodeAnalyticsProvider: () => PostHogNodeAnalyticsProvider,
26
+ clearGlobalAnalytics: () => clearGlobalAnalytics,
27
+ createServerAnalytics: () => createServerAnalytics,
28
+ getGlobalAnalytics: () => getGlobalAnalytics,
29
+ getGlobalAnalyticsNames: () => getGlobalAnalyticsNames,
30
+ getGlobalAnalyticsOptional: () => getGlobalAnalyticsOptional,
31
+ hasGlobalAnalytics: () => hasGlobalAnalytics,
32
+ removeGlobalAnalytics: () => removeGlobalAnalytics,
33
+ setGlobalAnalytics: () => setGlobalAnalytics
34
+ });
35
+ module.exports = __toCommonJS(server_exports);
36
+
37
+ // src/manager.ts
38
+ var AnalyticsManager = class {
39
+ constructor(business, debug = false) {
40
+ this.providers = /* @__PURE__ */ new Map();
41
+ this.globalContext = {};
42
+ this.initialized = false;
43
+ this.business = business;
44
+ this.debug = debug;
45
+ }
46
+ /**
47
+ * 注册分析工具提供商
48
+ */
49
+ registerProvider(name, provider) {
50
+ this.providers.set(name, provider);
51
+ this.log(`Registered provider: ${name}`);
52
+ return this;
53
+ }
54
+ /**
55
+ * 移除分析工具提供商
56
+ */
57
+ unregisterProvider(name) {
58
+ this.providers.delete(name);
59
+ this.log(`Unregistered provider: ${name}`);
60
+ return this;
61
+ }
62
+ getProvider(name) {
63
+ return this.providers.get(name);
64
+ }
65
+ /**
66
+ * 获取所有提供商
67
+ */
68
+ getAllProviders() {
69
+ return Array.from(this.providers.values());
70
+ }
71
+ /**
72
+ * 初始化所有提供商
73
+ */
74
+ async initialize() {
75
+ if (this.initialized) {
76
+ this.log("Already initialized");
77
+ return;
78
+ }
79
+ const results = await this.executeOnAllProviders("initialize");
80
+ this.initialized = true;
81
+ this.log(`Initialized ${results.success.length}/${this.providers.size} providers`);
82
+ if (results.errors.length > 0) {
83
+ console.warn(`[AnalyticsManager] ${results.errors.length} providers failed to initialize`);
84
+ }
85
+ }
86
+ /**
87
+ * 追踪事件到所有提供商
88
+ */
89
+ async track(event) {
90
+ if (!this.ensureInitialized()) return;
91
+ const enrichedEvent = this.enrichEvent(event);
92
+ await this.executeOnAllProviders("track", enrichedEvent);
93
+ }
94
+ /**
95
+ * 类型安全的事件追踪
96
+ */
97
+ async trackEvent(eventName, properties) {
98
+ await this.track({
99
+ name: eventName,
100
+ properties
101
+ });
102
+ }
103
+ /**
104
+ * 识别用户
105
+ */
106
+ async identify(userId, properties) {
107
+ if (!this.ensureInitialized()) return;
108
+ const mergedProperties = { ...this.globalContext, ...properties };
109
+ await this.executeOnAllProviders("identify", userId, mergedProperties);
110
+ }
111
+ /**
112
+ * 追踪页面浏览
113
+ */
114
+ async trackPageView(page, properties) {
115
+ if (!this.ensureInitialized()) return;
116
+ const mergedProperties = { ...this.globalContext, ...properties };
117
+ await this.executeOnAllProviders("trackPageView", page, mergedProperties);
118
+ }
119
+ /**
120
+ * 重置用户身份
121
+ */
122
+ async reset() {
123
+ if (!this.ensureInitialized()) return;
124
+ await this.executeOnAllProviders("reset");
125
+ }
126
+ /**
127
+ * 设置全局上下文
128
+ */
129
+ setGlobalContext(context) {
130
+ this.globalContext = { ...this.globalContext, ...context };
131
+ this.log("Updated global context", this.globalContext);
132
+ return this;
133
+ }
134
+ /**
135
+ * 获取全局上下文
136
+ */
137
+ getGlobalContext() {
138
+ return { ...this.globalContext };
139
+ }
140
+ /**
141
+ * 获取管理器状态
142
+ */
143
+ getStatus() {
144
+ return {
145
+ initialized: this.initialized,
146
+ providersCount: this.providers.size
147
+ };
148
+ }
149
+ /**
150
+ * 检查是否已初始化
151
+ */
152
+ ensureInitialized() {
153
+ if (!this.initialized) {
154
+ console.warn("[AnalyticsManager] Not initialized. Call initialize() first.");
155
+ return false;
156
+ }
157
+ return true;
158
+ }
159
+ /**
160
+ * 在所有提供商上执行操作
161
+ */
162
+ async executeOnAllProviders(method, ...args) {
163
+ const results = {
164
+ errors: [],
165
+ success: []
166
+ };
167
+ const promises = Array.from(this.providers.entries()).map(async ([name, provider]) => {
168
+ try {
169
+ await provider[method](...args);
170
+ results.success.push(name);
171
+ } catch (error) {
172
+ results.errors.push({ error, provider: name });
173
+ console.error(
174
+ `[AnalyticsManager] ${method} failed for ${provider.getProviderName()}:`,
175
+ error
176
+ );
177
+ }
178
+ });
179
+ await Promise.allSettled(promises);
180
+ return results;
181
+ }
182
+ /**
183
+ * 丰富事件数据
184
+ */
185
+ enrichEvent(event) {
186
+ return {
187
+ ...event,
188
+ properties: {
189
+ ...this.globalContext,
190
+ ...event.properties
191
+ },
192
+ timestamp: event.timestamp || /* @__PURE__ */ new Date()
193
+ };
194
+ }
195
+ /**
196
+ * 记录日志
197
+ */
198
+ log(message, data) {
199
+ if (this.debug) {
200
+ console.log(`[AnalyticsManager] ${message}`, data || "");
201
+ }
202
+ }
203
+ };
204
+
205
+ // src/providers/posthog.ts
206
+ var import_posthog_js = require("posthog-js");
207
+
208
+ // src/base.ts
209
+ var BaseAnalytics = class {
210
+ constructor(config) {
211
+ var _a, _b;
212
+ this.debug = (_a = config.debug) != null ? _a : false;
213
+ this.enabled = (_b = config.enabled) != null ? _b : true;
214
+ this.business = config.business;
215
+ }
216
+ /**
217
+ * Check if provider is enabled
218
+ */
219
+ isEnabled() {
220
+ if (!this.enabled) {
221
+ this.log("Provider is disabled");
222
+ return false;
223
+ }
224
+ return true;
225
+ }
226
+ /**
227
+ * Validate event data
228
+ */
229
+ validateEvent(event) {
230
+ if (!event.name) {
231
+ this.logError("Event name is required");
232
+ return false;
233
+ }
234
+ return true;
235
+ }
236
+ /**
237
+ * Log debug message
238
+ */
239
+ log(message, data) {
240
+ if (this.debug) {
241
+ console.log(`[${this.getProviderName()}] ${message}`, data || "");
242
+ }
243
+ }
244
+ /**
245
+ * Log error message
246
+ */
247
+ logError(message, error) {
248
+ console.error(`[${this.getProviderName()}] ${message}`, error || "");
249
+ }
250
+ /**
251
+ * 丰富属性数据,自动处理 spm 前缀
252
+ * 确保无论通过哪种方式调用都会添加 business 前缀
253
+ */
254
+ enrichProperties(properties) {
255
+ const enriched = { ...properties };
256
+ enriched.business = this.business;
257
+ if (enriched.spm && typeof enriched.spm === "string" && enriched.spm.trim()) {
258
+ if (enriched.spm !== this.business && !enriched.spm.startsWith(`${this.business}.`)) {
259
+ enriched.spm = `${this.business}.${enriched.spm}`;
260
+ }
261
+ } else {
262
+ enriched.spm = this.business;
263
+ }
264
+ return enriched;
265
+ }
266
+ };
267
+
268
+ // src/providers/posthog.ts
269
+ var PostHogAnalyticsProvider = class extends BaseAnalytics {
270
+ constructor(config, business) {
271
+ super({ business, debug: config.debug, enabled: config.enabled });
272
+ this.initialized = false;
273
+ this.config = config;
274
+ }
275
+ getProviderName() {
276
+ return "PostHog";
277
+ }
278
+ async initialize() {
279
+ if (!this.isEnabled() || this.initialized) {
280
+ return;
281
+ }
282
+ try {
283
+ const { key, host, ...posthogConfig } = this.config;
284
+ const initConfig = {
285
+ ...posthogConfig,
286
+ // User's posthog-js config options
287
+ api_host: host || posthogConfig.api_host || "https://app.posthog.com",
288
+ // Use before_send to dynamically add business context to all events
289
+ before_send: this.createBeforeSendHandler(posthogConfig.before_send),
290
+ debug: this.debug,
291
+ loaded: () => this.log("PostHog loaded and ready")
292
+ };
293
+ import_posthog_js.posthog.init(key, initConfig);
294
+ this.initialized = true;
295
+ this.log("PostHog initialized successfully");
296
+ this.log(`Using before_send to add business context: ${this.business}`);
297
+ } catch (error) {
298
+ this.logError("Failed to initialize PostHog", error);
299
+ throw error;
300
+ }
301
+ }
302
+ async track(event) {
303
+ if (!this.isEnabled() || !this.initialized || !this.validateEvent(event)) {
304
+ return;
305
+ }
306
+ try {
307
+ const enrichedProperties = this.enrichProperties(event.properties);
308
+ import_posthog_js.posthog.capture(event.name, {
309
+ ...enrichedProperties,
310
+ ...event.userId && { distinct_id: event.userId }
311
+ });
312
+ this.log(`Tracked event: ${event.name}`, { ...event, properties: enrichedProperties });
313
+ } catch (error) {
314
+ this.logError(`Failed to track event: ${event.name}`, error);
315
+ }
316
+ }
317
+ async identify(userId, properties) {
318
+ if (!this.isEnabled() || !this.initialized) {
319
+ return;
320
+ }
321
+ try {
322
+ const enrichedProperties = this.enrichProperties(properties);
323
+ import_posthog_js.posthog.identify(userId, enrichedProperties);
324
+ this.log(`Identified user: ${userId}`, enrichedProperties);
325
+ } catch (error) {
326
+ this.logError(`Failed to identify user: ${userId}`, error);
327
+ }
328
+ }
329
+ async trackPageView(page, properties) {
330
+ if (!this.isEnabled() || !this.initialized) {
331
+ return;
332
+ }
333
+ try {
334
+ const enrichedProperties = this.enrichProperties(properties);
335
+ await this.track({
336
+ name: "$pageview",
337
+ properties: { page, ...enrichedProperties }
338
+ });
339
+ this.log(`Tracked page view: ${page}`, enrichedProperties);
340
+ } catch (error) {
341
+ this.logError(`Failed to track page view: ${page}`, error);
342
+ }
343
+ }
344
+ async reset() {
345
+ if (!this.isEnabled() || !this.initialized) {
346
+ return;
347
+ }
348
+ try {
349
+ import_posthog_js.posthog.reset();
350
+ this.log("Reset user identity");
351
+ } catch (error) {
352
+ this.logError("Failed to reset user identity", error);
353
+ }
354
+ }
355
+ /**
356
+ * Check if feature flag is enabled
357
+ */
358
+ isFeatureEnabled(flag) {
359
+ if (!this.initialized) {
360
+ return false;
361
+ }
362
+ try {
363
+ return Boolean(import_posthog_js.posthog.isFeatureEnabled(flag));
364
+ } catch (error) {
365
+ this.logError(`Failed to check feature flag: ${flag}`, error);
366
+ return false;
367
+ }
368
+ }
369
+ /**
370
+ * Get the native PostHog instance for direct access to PostHog APIs
371
+ *
372
+ * Note: When using the native instance directly, events will still include
373
+ * the business spm prefix because it's registered as a global property.
374
+ *
375
+ * @returns PostHog native instance or null if not initialized
376
+ *
377
+ * @example
378
+ * ```typescript
379
+ * const analytics = createAnalytics({ business: 'myapp', ... });
380
+ * const posthogProvider = analytics.getProvider('posthog');
381
+ * const posthog = posthogProvider.getNativeInstance();
382
+ *
383
+ * // These calls will automatically include spm: 'myapp'
384
+ * posthog?.capture('custom_event', { custom: 'data' });
385
+ * posthog?.isFeatureEnabled('new_feature');
386
+ * posthog?.group('company', 'company_123');
387
+ * ```
388
+ */
389
+ getNativeInstance() {
390
+ if (!this.isEnabled() || !this.initialized) {
391
+ this.log("Cannot get native instance: provider not enabled or not initialized");
392
+ return null;
393
+ }
394
+ return import_posthog_js.posthog;
395
+ }
396
+ /**
397
+ * Create a before_send handler that adds business context to all events
398
+ * This ensures both wrapper calls and direct PostHog calls include business information
399
+ */
400
+ createBeforeSendHandler(userBeforeSend) {
401
+ return (event) => {
402
+ var _a;
403
+ if (!event) {
404
+ return null;
405
+ }
406
+ const originallyHadSpm = ((_a = event.properties) == null ? void 0 : _a.spm) !== void 0;
407
+ let processedEvent = event;
408
+ if (userBeforeSend) {
409
+ if (Array.isArray(userBeforeSend)) {
410
+ for (const fn of userBeforeSend) {
411
+ processedEvent = fn(processedEvent);
412
+ if (!processedEvent) {
413
+ return null;
414
+ }
415
+ }
416
+ } else if (typeof userBeforeSend === "function") {
417
+ processedEvent = userBeforeSend(processedEvent);
418
+ if (!processedEvent) {
419
+ return null;
420
+ }
421
+ }
422
+ }
423
+ if (!processedEvent.properties) {
424
+ processedEvent.properties = {};
425
+ }
426
+ processedEvent.properties.business = this.business;
427
+ const currentSpm = processedEvent.properties.spm;
428
+ const shouldSetDefaultSpm = !originallyHadSpm && (!currentSpm || typeof currentSpm === "string" && !currentSpm.trim());
429
+ if (shouldSetDefaultSpm) {
430
+ processedEvent.properties.spm = this.business;
431
+ }
432
+ return processedEvent;
433
+ };
434
+ }
435
+ /**
436
+ * Update the business context dynamically
437
+ * This will affect all future events
438
+ */
439
+ updateBusiness(newBusiness) {
440
+ if (!this.isEnabled() || !this.initialized) {
441
+ this.log("Cannot update business: provider not enabled or not initialized");
442
+ return;
443
+ }
444
+ this.log(`Business update requested: ${newBusiness} (current: ${this.business})`);
445
+ this.log("Note: Dynamic business updates require storing business in a mutable field");
446
+ }
447
+ /**
448
+ * Get current business context
449
+ */
450
+ getCurrentBusiness() {
451
+ return this.business;
452
+ }
453
+ };
454
+
455
+ // src/providers/posthog-node.ts
456
+ var import_posthog_node = require("posthog-node");
457
+ var PostHogNodeAnalyticsProvider = class extends BaseAnalytics {
458
+ constructor(config, business) {
459
+ super({ business, debug: config.debug, enabled: config.enabled });
460
+ this.client = null;
461
+ this.initialized = false;
462
+ this.config = config;
463
+ }
464
+ getProviderName() {
465
+ return "PostHogNode";
466
+ }
467
+ async initialize() {
468
+ if (!this.isEnabled() || this.initialized) {
469
+ return;
470
+ }
471
+ try {
472
+ const { key, debug, enabled, ...posthogNodeConfig } = this.config;
473
+ void debug;
474
+ void enabled;
475
+ this.client = new import_posthog_node.PostHog(key, {
476
+ flushAt: 20,
477
+ flushInterval: 1e4,
478
+ host: "https://app.posthog.com",
479
+ ...posthogNodeConfig
480
+ // Apply user's posthog-node config options
481
+ });
482
+ this.initialized = true;
483
+ this.log("PostHog Node.js initialized successfully");
484
+ this.log(`Using business context: ${this.business}`);
485
+ } catch (error) {
486
+ this.logError("Failed to initialize PostHog Node.js", error);
487
+ throw error;
488
+ }
489
+ }
490
+ async track(event) {
491
+ if (!this.isEnabled() || !this.initialized || !this.client || !this.validateEvent(event)) {
492
+ return;
493
+ }
494
+ try {
495
+ const enrichedProperties = this.enrichProperties(event.properties);
496
+ this.client.capture({
497
+ distinctId: event.userId || event.anonymousId || "anonymous",
498
+ event: event.name,
499
+ properties: enrichedProperties,
500
+ timestamp: event.timestamp
501
+ });
502
+ this.log(`Tracked event: ${event.name}`, { ...event, properties: enrichedProperties });
503
+ } catch (error) {
504
+ this.logError(`Failed to track event: ${event.name}`, error);
505
+ }
506
+ }
507
+ async identify(userId, properties) {
508
+ if (!this.isEnabled() || !this.initialized || !this.client) {
509
+ return;
510
+ }
511
+ try {
512
+ const enrichedProperties = this.enrichProperties(properties);
513
+ this.client.identify({
514
+ distinctId: userId,
515
+ properties: enrichedProperties
516
+ });
517
+ this.log(`Identified user: ${userId}`, enrichedProperties);
518
+ } catch (error) {
519
+ this.logError(`Failed to identify user: ${userId}`, error);
520
+ }
521
+ }
522
+ async trackPageView(page, properties) {
523
+ if (!this.isEnabled() || !this.initialized || !this.client) {
524
+ return;
525
+ }
526
+ try {
527
+ const enrichedProperties = this.enrichProperties({ page, ...properties });
528
+ await this.track({
529
+ name: "$pageview",
530
+ properties: enrichedProperties
531
+ });
532
+ this.log(`Tracked page view: ${page}`, enrichedProperties);
533
+ } catch (error) {
534
+ this.logError(`Failed to track page view: ${page}`, error);
535
+ }
536
+ }
537
+ async reset() {
538
+ if (!this.isEnabled() || !this.initialized) {
539
+ return;
540
+ }
541
+ try {
542
+ await this.flush();
543
+ this.log("Reset user identity (flushed pending events)");
544
+ } catch (error) {
545
+ this.logError("Failed to reset user identity", error);
546
+ }
547
+ }
548
+ /**
549
+ * Check if feature flag is enabled for a user
550
+ */
551
+ async isFeatureEnabled(flag, distinctId, groups) {
552
+ if (!this.initialized || !this.client) {
553
+ return false;
554
+ }
555
+ try {
556
+ const result = await this.client.isFeatureEnabled(flag, distinctId, groups);
557
+ return Boolean(result);
558
+ } catch (error) {
559
+ this.logError(`Failed to check feature flag: ${flag}`, error);
560
+ return false;
561
+ }
562
+ }
563
+ /**
564
+ * Get feature flag payload for a user
565
+ */
566
+ async getFeatureFlag(flag, distinctId, groups) {
567
+ if (!this.initialized || !this.client) {
568
+ return void 0;
569
+ }
570
+ try {
571
+ return await this.client.getFeatureFlag(flag, distinctId, groups);
572
+ } catch (error) {
573
+ this.logError(`Failed to get feature flag: ${flag}`, error);
574
+ return void 0;
575
+ }
576
+ }
577
+ /**
578
+ * Get all feature flags for a user
579
+ */
580
+ async getAllFlags(distinctId, groups) {
581
+ if (!this.initialized || !this.client) {
582
+ return {};
583
+ }
584
+ try {
585
+ const flags = await this.client.getAllFlags(distinctId, groups);
586
+ return flags || {};
587
+ } catch (error) {
588
+ this.logError("Failed to get all feature flags", error);
589
+ return {};
590
+ }
591
+ }
592
+ /**
593
+ * Flush pending events
594
+ */
595
+ async flush() {
596
+ if (!this.initialized || !this.client) {
597
+ return;
598
+ }
599
+ try {
600
+ await this.client.flush();
601
+ this.log("Flushed pending events");
602
+ } catch (error) {
603
+ this.logError("Failed to flush events", error);
604
+ }
605
+ }
606
+ /**
607
+ * Shutdown the client and flush remaining events
608
+ */
609
+ async shutdown() {
610
+ if (!this.initialized || !this.client) {
611
+ return;
612
+ }
613
+ try {
614
+ await this.client.shutdown();
615
+ this.initialized = false;
616
+ this.log("PostHog Node.js client shut down");
617
+ } catch (error) {
618
+ this.logError("Failed to shutdown PostHog Node.js client", error);
619
+ }
620
+ }
621
+ /**
622
+ * Get the native PostHog Node instance for direct access to PostHog APIs
623
+ */
624
+ getNativeInstance() {
625
+ if (!this.isEnabled() || !this.initialized) {
626
+ this.log("Cannot get native instance: provider not enabled or not initialized");
627
+ return null;
628
+ }
629
+ return this.client;
630
+ }
631
+ /**
632
+ * Group identify - associate user with a group
633
+ */
634
+ async groupIdentify(groupType, groupKey, properties) {
635
+ if (!this.isEnabled() || !this.initialized || !this.client) {
636
+ return;
637
+ }
638
+ try {
639
+ const enrichedProperties = this.enrichProperties(properties);
640
+ this.client.groupIdentify({
641
+ groupKey,
642
+ groupType,
643
+ properties: enrichedProperties
644
+ });
645
+ this.log(`Group identified: ${groupType}:${groupKey}`, enrichedProperties);
646
+ } catch (error) {
647
+ this.logError(`Failed to identify group: ${groupType}:${groupKey}`, error);
648
+ }
649
+ }
650
+ /**
651
+ * Create alias between user IDs
652
+ */
653
+ async alias(distinctId, alias) {
654
+ if (!this.isEnabled() || !this.initialized || !this.client) {
655
+ return;
656
+ }
657
+ try {
658
+ this.client.alias({
659
+ alias,
660
+ distinctId
661
+ });
662
+ this.log(`Created alias: ${distinctId} -> ${alias}`);
663
+ } catch (error) {
664
+ this.logError(`Failed to create alias: ${distinctId} -> ${alias}`, error);
665
+ }
666
+ }
667
+ /**
668
+ * Update the business context dynamically
669
+ * This will affect all future events
670
+ */
671
+ updateBusiness(newBusiness) {
672
+ if (!this.isEnabled() || !this.initialized) {
673
+ this.log("Cannot update business: provider not enabled or not initialized");
674
+ return;
675
+ }
676
+ this.log(`Business update requested: ${newBusiness} (current: ${this.business})`);
677
+ this.log("Note: Dynamic business updates require storing business in a mutable field");
678
+ }
679
+ /**
680
+ * Get current business context
681
+ */
682
+ getCurrentBusiness() {
683
+ return this.business;
684
+ }
685
+ };
686
+
687
+ // src/global.ts
688
+ var GLOBAL_STATE_KEY = "__LOBE_ANALYTICS_GLOBAL_STATE__";
689
+ function getGlobalState() {
690
+ if (!globalThis[GLOBAL_STATE_KEY]) {
691
+ globalThis[GLOBAL_STATE_KEY] = {
692
+ instances: /* @__PURE__ */ new Map(),
693
+ singletonConfig: null,
694
+ singletonInstance: null
695
+ };
696
+ }
697
+ return globalThis[GLOBAL_STATE_KEY];
698
+ }
699
+ var DEFAULT_INSTANCE_NAME = "__default__";
700
+ function setGlobalAnalytics(instance, name = DEFAULT_INSTANCE_NAME) {
701
+ const state = getGlobalState();
702
+ state.instances.set(name, instance);
703
+ }
704
+ function getGlobalAnalytics(name = DEFAULT_INSTANCE_NAME) {
705
+ const state = getGlobalState();
706
+ const instance = state.instances.get(name);
707
+ if (!instance) {
708
+ throw new Error(
709
+ `Global analytics instance "${name}" not found. Make sure to register it first using setGlobalAnalytics() or use AnalyticsProvider.`
710
+ );
711
+ }
712
+ return instance;
713
+ }
714
+ function getGlobalAnalyticsOptional(name = DEFAULT_INSTANCE_NAME) {
715
+ const state = getGlobalState();
716
+ return state.instances.get(name) || null;
717
+ }
718
+ function hasGlobalAnalytics(name = DEFAULT_INSTANCE_NAME) {
719
+ const state = getGlobalState();
720
+ return state.instances.has(name);
721
+ }
722
+ function removeGlobalAnalytics(name = DEFAULT_INSTANCE_NAME) {
723
+ const state = getGlobalState();
724
+ return state.instances.delete(name);
725
+ }
726
+ function clearGlobalAnalytics() {
727
+ const state = getGlobalState();
728
+ state.instances.clear();
729
+ }
730
+ function getGlobalAnalyticsNames() {
731
+ const state = getGlobalState();
732
+ return Array.from(state.instances.keys());
733
+ }
734
+
735
+ // src/server.ts
736
+ function createServerAnalytics(config) {
737
+ var _a, _b;
738
+ const manager = new AnalyticsManager(config.business, config.debug);
739
+ if ((_a = config.providers.posthog) == null ? void 0 : _a.enabled) {
740
+ const provider = new PostHogAnalyticsProvider(config.providers.posthog, config.business);
741
+ manager.registerProvider("posthog", provider);
742
+ }
743
+ if ((_b = config.providers.posthogNode) == null ? void 0 : _b.enabled) {
744
+ const provider = new PostHogNodeAnalyticsProvider(
745
+ config.providers.posthogNode,
746
+ config.business
747
+ );
748
+ manager.registerProvider("posthogNode", provider);
749
+ }
750
+ return manager;
751
+ }
752
+ // Annotate the CommonJS export names for ESM import in node:
753
+ 0 && (module.exports = {
754
+ AnalyticsManager,
755
+ PostHogAnalyticsProvider,
756
+ PostHogNodeAnalyticsProvider,
757
+ clearGlobalAnalytics,
758
+ createServerAnalytics,
759
+ getGlobalAnalytics,
760
+ getGlobalAnalyticsNames,
761
+ getGlobalAnalyticsOptional,
762
+ hasGlobalAnalytics,
763
+ removeGlobalAnalytics,
764
+ setGlobalAnalytics
765
+ });
766
+ //# sourceMappingURL=server.js.map