@ooneex/analytics 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Ooneex
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,420 @@
1
+ # @ooneex/analytics
2
+
3
+ A comprehensive TypeScript/JavaScript analytics library with PostHog integration for tracking user events and behavior. This package provides a clean, type-safe interface for capturing analytics events with support for user properties, groups, and custom event data.
4
+
5
+ ![Bun](https://img.shields.io/badge/Bun-Compatible-orange?style=flat-square&logo=bun)
6
+ ![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue?style=flat-square&logo=typescript)
7
+ ![MIT License](https://img.shields.io/badge/License-MIT-yellow?style=flat-square)
8
+
9
+ ## Features
10
+
11
+ ✅ **PostHog Integration** - Seamless PostHog analytics integration
12
+
13
+ ✅ **Type-Safe** - Full TypeScript support with proper type definitions
14
+
15
+ ✅ **Environment Configuration** - Flexible API key and host configuration
16
+
17
+ ✅ **Event Tracking** - Track user events with custom properties and groups
18
+
19
+ ✅ **User Properties** - Attach custom properties to user events
20
+
21
+ ✅ **Group Analytics** - Support for group-based analytics tracking
22
+
23
+ ✅ **Error Handling** - Comprehensive error handling with custom exceptions
24
+
25
+ ✅ **Bun Runtime** - Optimized for Bun runtime environment
26
+
27
+ ✅ **Zero Config** - Works out of the box with environment variables
28
+
29
+ ## Installation
30
+
31
+ ### Bun
32
+ ```bash
33
+ bun add @ooneex/analytics
34
+ ```
35
+
36
+ ## Setup
37
+
38
+ ### Environment Variables
39
+
40
+ Set the following environment variables in your project:
41
+
42
+ ```bash
43
+ # Required: Your PostHog API key
44
+ ANALYTICS_POSTHOG_API_KEY=your_posthog_api_key_here
45
+
46
+ # Optional: PostHog host (defaults to https://eu.i.posthog.com)
47
+ ANALYTICS_POSTHOG_HOST=https://eu.i.posthog.com
48
+ ```
49
+
50
+ ### Configuration Options
51
+
52
+ You can also configure the analytics adapter programmatically:
53
+
54
+ ```typescript
55
+ import { PostHogAdapter } from '@ooneex/analytics';
56
+
57
+ // Using constructor options (overrides environment variables)
58
+ const analytics = new PostHogAdapter({
59
+ apiKey: 'your_api_key',
60
+ host: 'https://your-posthog-instance.com'
61
+ });
62
+
63
+ // Using environment variables only
64
+ const analytics = new PostHogAdapter();
65
+ ```
66
+
67
+ ## Usage
68
+
69
+ ### Basic Event Tracking
70
+
71
+ ```typescript
72
+ import { PostHogAdapter } from '@ooneex/analytics';
73
+
74
+ const analytics = new PostHogAdapter();
75
+
76
+ // Track a simple event
77
+ analytics.capture({
78
+ id: 'user_123',
79
+ event: 'button_clicked',
80
+ properties: {
81
+ buttonId: 'signup-btn',
82
+ page: '/landing'
83
+ }
84
+ });
85
+ ```
86
+
87
+ ### Advanced Event Tracking with Groups
88
+
89
+ ```typescript
90
+ import { PostHogAdapter } from '@ooneex/analytics';
91
+
92
+ const analytics = new PostHogAdapter();
93
+
94
+ // Track event with user properties and groups
95
+ analytics.capture({
96
+ id: 'user_123',
97
+ event: 'feature_used',
98
+ properties: {
99
+ feature: 'advanced_search',
100
+ sessionDuration: 1200,
101
+ actionsCount: 15,
102
+ source: 'web_app'
103
+ },
104
+ groups: {
105
+ company: 'acme_corp',
106
+ plan: 'enterprise'
107
+ }
108
+ });
109
+ ```
110
+
111
+ ### E-commerce Tracking
112
+
113
+ ```typescript
114
+ // Track purchase events
115
+ analytics.capture({
116
+ id: 'user_123',
117
+ event: 'purchase_completed',
118
+ properties: {
119
+ orderId: 'order_456',
120
+ revenue: 99.99,
121
+ currency: 'USD',
122
+ products: ['product_1', 'product_2'],
123
+ paymentMethod: 'credit_card',
124
+ discount: 10.00
125
+ },
126
+ groups: {
127
+ store: 'online',
128
+ region: 'us_west'
129
+ }
130
+ });
131
+ ```
132
+
133
+ ### User Signup Tracking
134
+
135
+ ```typescript
136
+ // Track user registration
137
+ analytics.capture({
138
+ id: 'user_123',
139
+ event: 'user_signup',
140
+ properties: {
141
+ email: 'user@example.com',
142
+ source: 'google_ads',
143
+ plan: 'free',
144
+ referrer: 'https://example.com'
145
+ },
146
+ groups: {
147
+ company: 'new_company'
148
+ }
149
+ });
150
+ ```
151
+
152
+ ### Custom Implementation
153
+
154
+ ```typescript
155
+ import { IAnalytics, PostHogAdapterCaptureType } from '@ooneex/analytics';
156
+
157
+ class CustomAnalytics implements IAnalytics {
158
+ capture(options: PostHogAdapterCaptureType): void {
159
+ // Custom analytics implementation
160
+ console.log('Tracking event:', options.event, 'for user:', options.id);
161
+
162
+ // You can extend or modify the tracking logic here
163
+ }
164
+ }
165
+ ```
166
+
167
+ ## API Reference
168
+
169
+ ### `PostHogAdapter` Class
170
+
171
+ The main analytics adapter class that implements PostHog integration.
172
+
173
+ #### Constructor
174
+
175
+ ```typescript
176
+ new PostHogAdapter(options?: { apiKey?: string; host?: string })
177
+ ```
178
+
179
+ **Parameters:**
180
+ - `options.apiKey` - PostHog API key (optional, can use `ANALYTICS_POSTHOG_API_KEY` env var)
181
+ - `options.host` - PostHog host URL (optional, defaults to `https://eu.i.posthog.com`)
182
+
183
+ **Throws:** `AnalyticsException` if no API key is provided
184
+
185
+ **Example:**
186
+ ```typescript
187
+ // Using environment variables
188
+ const analytics = new PostHogAdapter();
189
+
190
+ // Using constructor options
191
+ const analytics = new PostHogAdapter({
192
+ apiKey: 'phc_your_key_here',
193
+ host: 'https://app.posthog.com'
194
+ });
195
+ ```
196
+
197
+ #### Methods
198
+
199
+ ##### `capture(options: PostHogAdapterCaptureType): void`
200
+
201
+ Captures an analytics event with user properties and groups.
202
+
203
+ **Parameters:**
204
+ - `options.id` - Unique user identifier (required)
205
+ - `options.event` - Event name (required)
206
+ - `options.properties` - Custom event properties (optional)
207
+ - `options.groups` - Group associations (optional)
208
+
209
+ **Example:**
210
+ ```typescript
211
+ analytics.capture({
212
+ id: 'user_123',
213
+ event: 'page_viewed',
214
+ properties: {
215
+ page: '/dashboard',
216
+ loadTime: 1.2,
217
+ userAgent: 'Chrome/91.0'
218
+ },
219
+ groups: {
220
+ company: 'acme_corp',
221
+ team: 'marketing'
222
+ }
223
+ });
224
+ ```
225
+
226
+ ### Types
227
+
228
+ #### `IAnalytics`
229
+
230
+ Interface defining the analytics contract.
231
+
232
+ ```typescript
233
+ interface IAnalytics {
234
+ capture: (options: PostHogAdapterCaptureType) => void;
235
+ }
236
+ ```
237
+
238
+ #### `PostHogAdapterCaptureType`
239
+
240
+ Type definition for capture event data.
241
+
242
+ ```typescript
243
+ type PostHogAdapterCaptureType = {
244
+ id: string; // User identifier
245
+ event: string; // Event name
246
+ properties?: Record<string, unknown>; // Custom properties
247
+ groups?: Record<string, string | number>; // Group associations
248
+ };
249
+ ```
250
+
251
+ ### Error Handling
252
+
253
+ #### `AnalyticsException`
254
+
255
+ Custom exception class for analytics-related errors.
256
+
257
+ ```typescript
258
+ import { AnalyticsException } from '@ooneex/analytics';
259
+
260
+ try {
261
+ const analytics = new PostHogAdapter(); // Missing API key
262
+ } catch (error) {
263
+ if (error instanceof AnalyticsException) {
264
+ console.error('Analytics Error:', error.message);
265
+ // Handle analytics-specific error
266
+ }
267
+ }
268
+ ```
269
+
270
+ **Common Error Scenarios:**
271
+ - Missing PostHog API key
272
+ - Invalid configuration options
273
+ - Network connectivity issues
274
+
275
+ ## Environment Setup
276
+
277
+ ### Required Environment Variables
278
+
279
+ ```bash
280
+ # PostHog API Key (required)
281
+ ANALYTICS_POSTHOG_API_KEY=phc_your_api_key_here
282
+ ```
283
+
284
+ ### Optional Environment Variables
285
+
286
+ ```bash
287
+ # PostHog Host (optional, defaults to EU instance)
288
+ ANALYTICS_POSTHOG_HOST=https://app.posthog.com
289
+
290
+ # For US instance
291
+ ANALYTICS_POSTHOG_HOST=https://us.i.posthog.com
292
+
293
+ # For self-hosted instance
294
+ ANALYTICS_POSTHOG_HOST=https://your-posthog-instance.com
295
+ ```
296
+
297
+ ## Best Practices
298
+
299
+ ### Event Naming
300
+
301
+ Use consistent, descriptive event names:
302
+
303
+ ```typescript
304
+ // ✅ Good
305
+ analytics.capture({
306
+ id: 'user_123',
307
+ event: 'button_clicked',
308
+ properties: { button: 'signup' }
309
+ });
310
+
311
+ // ❌ Avoid
312
+ analytics.capture({
313
+ id: 'user_123',
314
+ event: 'click',
315
+ properties: { what: 'something' }
316
+ });
317
+ ```
318
+
319
+ ### Property Structure
320
+
321
+ Keep properties flat and meaningful:
322
+
323
+ ```typescript
324
+ // ✅ Good
325
+ analytics.capture({
326
+ id: 'user_123',
327
+ event: 'purchase_completed',
328
+ properties: {
329
+ orderId: 'order_456',
330
+ revenue: 99.99,
331
+ currency: 'USD',
332
+ itemCount: 3
333
+ }
334
+ });
335
+
336
+ // ❌ Avoid deeply nested objects
337
+ analytics.capture({
338
+ id: 'user_123',
339
+ event: 'purchase_completed',
340
+ properties: {
341
+ order: {
342
+ details: {
343
+ nested: {
344
+ data: 'value'
345
+ }
346
+ }
347
+ }
348
+ }
349
+ });
350
+ ```
351
+
352
+ ### Error Handling
353
+
354
+ Always handle potential configuration errors:
355
+
356
+ ```typescript
357
+ import { PostHogAdapter, AnalyticsException } from '@ooneex/analytics';
358
+
359
+ try {
360
+ const analytics = new PostHogAdapter();
361
+
362
+ analytics.capture({
363
+ id: 'user_123',
364
+ event: 'app_started'
365
+ });
366
+ } catch (error) {
367
+ if (error instanceof AnalyticsException) {
368
+ console.error('Analytics configuration error:', error.message);
369
+ // Fallback analytics or silent failure
370
+ }
371
+ }
372
+ ```
373
+
374
+ ## Runtime Support
375
+
376
+ This package is optimized for **Bun runtime only**. It leverages Bun-specific features and environment variable access patterns.
377
+
378
+ ### Bun Environment
379
+
380
+ ```typescript
381
+ // Automatic environment variable access
382
+ const analytics = new PostHogAdapter(); // Uses Bun.env.ANALYTICS_POSTHOG_API_KEY
383
+ ```
384
+
385
+ ## License
386
+
387
+ This project is licensed under the MIT License - see the [LICENSE](./LICENSE) file for details.
388
+
389
+ ## Contributing
390
+
391
+ Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.
392
+
393
+ ### Development Setup
394
+
395
+ 1. Clone the repository
396
+ 2. Install dependencies: `bun install`
397
+ 3. Run tests: `bun run test`
398
+ 4. Build the project: `bun run build`
399
+
400
+ ### Guidelines
401
+
402
+ - Write tests for new features
403
+ - Follow the existing code style
404
+ - Update documentation for API changes
405
+ - Ensure all tests pass before submitting PR
406
+ - Test with Bun runtime environment
407
+
408
+ ### Running Tests
409
+
410
+ ```bash
411
+ # Run all tests
412
+ bun run test
413
+
414
+ # Run tests in watch mode
415
+ bun run test:watch
416
+ ```
417
+
418
+ ---
419
+
420
+ Made with ❤️ by the Ooneex team
@@ -0,0 +1,23 @@
1
+ import { Exception } from "@ooneex/exception";
2
+ declare class AnalyticsException extends Exception {
3
+ constructor(message: string, data?: Record<string, unknown>);
4
+ }
5
+ type AnalyticsClassType = new (...args: any[]) => IAnalytics;
6
+ interface IAnalytics {
7
+ capture: (options: PostHogAdapterCaptureType) => void;
8
+ }
9
+ type PostHogAdapterCaptureType = {
10
+ id: string;
11
+ event: string;
12
+ properties?: Record<string, unknown>;
13
+ groups?: Record<string, string | number>;
14
+ };
15
+ declare class PostHogAdapter implements IAnalytics {
16
+ private client;
17
+ constructor(options?: {
18
+ apiKey?: string;
19
+ host?: string;
20
+ });
21
+ capture<T extends PostHogAdapterCaptureType>(options: T): void;
22
+ }
23
+ export { PostHogAdapterCaptureType, PostHogAdapter, IAnalytics, AnalyticsException, AnalyticsClassType };
package/dist/index.js ADDED
@@ -0,0 +1,4 @@
1
+ // @bun
2
+ import{Exception as o}from"@ooneex/exception";import{HttpStatus as s}from"@ooneex/http-status";class r extends o{constructor(t,e={}){super(t,{status:s.Code.InternalServerError,data:e});this.name="AnalyticsException"}}import{PostHog as i}from"posthog-node";class n{client=null;constructor(t){let e=t?.apiKey||Bun.env.ANALYTICS_POSTHOG_API_KEY;if(!e)throw new r("PostHog API key is required. Please provide an API key either through the constructor options or set the ANALYTICS_POSTHOG_API_KEY environment variable.");if(t?.apiKey)this.client=new i(e,{host:t.host||Bun.env.ANALYTICS_POSTHOG_HOST||"https://eu.i.posthog.com"})}capture(t){this.client?.capture({distinctId:t.id,event:t.event,properties:{$set:t.properties},timestamp:new Date,...t.groups&&{groups:t.groups}}),this.client?.shutdown()}}export{n as PostHogAdapter,r as AnalyticsException};
3
+
4
+ //# debugId=D94B37C63C67FF1064756E2164756E21
@@ -0,0 +1,11 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["src/AnalyticsException.ts", "src/PostHogAdapter.ts"],
4
+ "sourcesContent": [
5
+ "import { Exception } from \"@ooneex/exception\";\nimport { HttpStatus } from \"@ooneex/http-status\";\n\nexport class AnalyticsException extends Exception {\n constructor(message: string, data: Record<string, unknown> = {}) {\n super(message, {\n status: HttpStatus.Code.InternalServerError,\n data,\n });\n\n this.name = \"AnalyticsException\";\n }\n}\n",
6
+ "import { PostHog } from \"posthog-node\";\nimport { AnalyticsException } from \"./AnalyticsException\";\nimport type { IAnalytics, PostHogAdapterCaptureType } from \"./types\";\n\nexport class PostHogAdapter implements IAnalytics {\n private client: PostHog | null = null;\n\n constructor(options?: { apiKey?: string; host?: string }) {\n const apiKey = options?.apiKey || Bun.env.ANALYTICS_POSTHOG_API_KEY;\n\n if (!apiKey) {\n throw new AnalyticsException(\n \"PostHog API key is required. Please provide an API key either through the constructor options or set the ANALYTICS_POSTHOG_API_KEY environment variable.\",\n );\n }\n\n if (options?.apiKey) {\n this.client = new PostHog(apiKey, {\n host: options.host || Bun.env.ANALYTICS_POSTHOG_HOST || \"https://eu.i.posthog.com\",\n });\n }\n }\n\n public capture<T extends PostHogAdapterCaptureType>(options: T): void {\n this.client?.capture({\n distinctId: options.id,\n event: options.event,\n properties: {\n $set: options.properties,\n },\n timestamp: new Date(),\n ...(options.groups && { groups: options.groups }),\n });\n this.client?.shutdown();\n }\n}\n"
7
+ ],
8
+ "mappings": ";AAAA,oBAAS,0BACT,qBAAS,4BAEF,MAAM,UAA2B,CAAU,CAChD,WAAW,CAAC,EAAiB,EAAgC,CAAC,EAAG,CAC/D,MAAM,EAAS,CACb,OAAQ,EAAW,KAAK,oBACxB,MACF,CAAC,EAED,KAAK,KAAO,qBAEhB,CCZA,kBAAS,qBAIF,MAAM,CAAqC,CACxC,OAAyB,KAEjC,WAAW,CAAC,EAA8C,CACxD,IAAM,EAAS,GAAS,QAAU,IAAI,IAAI,0BAE1C,GAAI,CAAC,EACH,MAAM,IAAI,EACR,0JACF,EAGF,GAAI,GAAS,OACX,KAAK,OAAS,IAAI,EAAQ,EAAQ,CAChC,KAAM,EAAQ,MAAQ,IAAI,IAAI,wBAA0B,0BAC1D,CAAC,EAIE,OAA4C,CAAC,EAAkB,CACpE,KAAK,QAAQ,QAAQ,CACnB,WAAY,EAAQ,GACpB,MAAO,EAAQ,MACf,WAAY,CACV,KAAM,EAAQ,UAChB,EACA,UAAW,IAAI,QACX,EAAQ,QAAU,CAAE,OAAQ,EAAQ,MAAO,CACjD,CAAC,EACD,KAAK,QAAQ,SAAS,EAE1B",
9
+ "debugId": "D94B37C63C67FF1064756E2164756E21",
10
+ "names": []
11
+ }
Binary file
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@ooneex/analytics",
3
+ "description": "",
4
+ "version": "0.0.1",
5
+ "type": "module",
6
+ "private": false,
7
+ "files": [
8
+ "dist",
9
+ "LICENSE",
10
+ "README.md",
11
+ "package.json"
12
+ ],
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "import": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "./package.json": "./package.json"
23
+ },
24
+ "license": "MIT",
25
+ "scripts": {
26
+ "test": "bun test tests",
27
+ "build": "bunup",
28
+ "lint": "tsgo --noEmit && bunx biome lint",
29
+ "publish:prod": "bun publish --access public",
30
+ "publish:pack": "bun pm pack --destination ./dist",
31
+ "publish:dry": "bun publish --dry-run"
32
+ },
33
+ "devDependencies": {},
34
+ "peerDependencies": {},
35
+ "dependencies": {
36
+ "@ooneex/exception": "0.0.1",
37
+ "@ooneex/http-status": "0.0.1",
38
+ "posthog-node": "^5.11.0"
39
+ }
40
+ }