growlytics-tracking 1.0.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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +206 -0
  3. package/dist/cjs/engagement.d.ts +6 -0
  4. package/dist/cjs/engagement.js +46 -0
  5. package/dist/cjs/final_payload.d.ts +13 -0
  6. package/dist/cjs/final_payload.js +2 -0
  7. package/dist/cjs/growlytics.d.ts +16 -0
  8. package/dist/cjs/growlytics.js +55 -0
  9. package/dist/cjs/helper_types.d.ts +16 -0
  10. package/dist/cjs/helper_types.js +2 -0
  11. package/dist/cjs/http.d.ts +35 -0
  12. package/dist/cjs/http.js +176 -0
  13. package/dist/cjs/index.d.ts +2 -0
  14. package/dist/cjs/index.js +20 -0
  15. package/dist/cjs/package.json +3 -0
  16. package/dist/cjs/queue.d.ts +45 -0
  17. package/dist/cjs/queue.js +121 -0
  18. package/dist/cjs/tracker.d.ts +28 -0
  19. package/dist/cjs/tracker.js +177 -0
  20. package/dist/cjs/types.d.ts +16 -0
  21. package/dist/cjs/types.js +2 -0
  22. package/dist/cjs/utils.d.ts +15 -0
  23. package/dist/cjs/utils.js +88 -0
  24. package/dist/esm/engagement.d.ts +6 -0
  25. package/dist/esm/engagement.js +46 -0
  26. package/dist/esm/final_payload.d.ts +13 -0
  27. package/dist/esm/final_payload.js +2 -0
  28. package/dist/esm/growlytics.d.ts +16 -0
  29. package/dist/esm/growlytics.js +55 -0
  30. package/dist/esm/helper_types.d.ts +16 -0
  31. package/dist/esm/helper_types.js +2 -0
  32. package/dist/esm/http.d.ts +35 -0
  33. package/dist/esm/http.js +176 -0
  34. package/dist/esm/index.d.ts +2 -0
  35. package/dist/esm/index.js +20 -0
  36. package/dist/esm/package.json +3 -0
  37. package/dist/esm/queue.d.ts +45 -0
  38. package/dist/esm/queue.js +121 -0
  39. package/dist/esm/tracker.d.ts +28 -0
  40. package/dist/esm/tracker.js +177 -0
  41. package/dist/esm/types.d.ts +16 -0
  42. package/dist/esm/types.js +2 -0
  43. package/dist/esm/utils.d.ts +15 -0
  44. package/dist/esm/utils.js +88 -0
  45. package/package.json +56 -0
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.HttpClient = void 0;
37
+ const http = __importStar(require("http"));
38
+ const https = __importStar(require("https"));
39
+ const url_1 = require("url");
40
+ class HttpClient {
41
+ options;
42
+ url;
43
+ isHttps;
44
+ constructor(options) {
45
+ this.options = options;
46
+ // Standardize baseline endpoint
47
+ const urlString = options.baseUrl.endsWith('/')
48
+ ? options.baseUrl.slice(0, -1) + options.path
49
+ : options.baseUrl + options.path;
50
+ this.url = new url_1.URL(urlString);
51
+ this.isHttps = this.url.protocol === 'https:';
52
+ }
53
+ log(message, ...args) {
54
+ if (this.options.debug) {
55
+ console.log(`[Growlytics-SDK][HTTP] ${message}`, ...args);
56
+ }
57
+ }
58
+ logError(message, ...args) {
59
+ if (this.options.debug) {
60
+ console.error(`[Growlytics-SDK][HTTP][ERROR] ${message}`, ...args);
61
+ }
62
+ }
63
+ /**
64
+ * Sends a batch of tracking events with automatic retries and exponential backoff.
65
+ */
66
+ async sendEvents(events) {
67
+ let attempt = 0;
68
+ const maxAttempts = this.options.maxRetries + 1;
69
+ while (attempt < maxAttempts) {
70
+ try {
71
+ await this.post(events);
72
+ this.log(`Successfully sent batch of ${events.length} events.`);
73
+ return; // Success!
74
+ }
75
+ catch (error) {
76
+ attempt++;
77
+ const isRetryable = this.isRetryableError(error);
78
+ if (attempt >= maxAttempts || !isRetryable) {
79
+ this.logError(`Failed to send batch of ${events.length} events after ${attempt} attempts. Permanent failure.`);
80
+ throw error;
81
+ }
82
+ // Calculate backoff delay with jitter
83
+ const delay = this.calculateBackoff(attempt);
84
+ this.logError(`Attempt ${attempt} failed: ${error.message || error}. Retrying in ${delay}ms...`);
85
+ await this.sleep(delay);
86
+ }
87
+ }
88
+ }
89
+ /**
90
+ * Determine if the error is retryable (network drops, 5xx server errors, or 429 rate limits)
91
+ */
92
+ isRetryableError(error) {
93
+ // If it's a network-level connection error, it's retryable
94
+ if (error.code) {
95
+ const retryableCodes = ['ECONNRESET', 'EADDRINUSE', 'ETIMEDOUT', 'ECONNREFUSED', 'ENOTFOUND', 'EPIPE'];
96
+ if (retryableCodes.includes(error.code)) {
97
+ return true;
98
+ }
99
+ }
100
+ // Check status code if it's an HTTP response error
101
+ if (error.statusCode) {
102
+ const status = error.statusCode;
103
+ // Retry on 429 (Rate Limit) and any 5xx (Server Error)
104
+ return status === 429 || (status >= 500 && status < 600);
105
+ }
106
+ return false;
107
+ }
108
+ /**
109
+ * Calculate exponential backoff delay with full jitter
110
+ */
111
+ calculateBackoff(attempt) {
112
+ const delay = this.options.retryInitialDelayMs * Math.pow(2, attempt - 1);
113
+ const cappedDelay = Math.min(this.options.retryMaxDelayMs, delay);
114
+ // Apply jitter: randomize between 50% and 100% of the calculated delay
115
+ const jitter = 0.5 + Math.random() * 0.5;
116
+ return Math.floor(cappedDelay * jitter);
117
+ }
118
+ sleep(ms) {
119
+ return new Promise((resolve) => setTimeout(resolve, ms));
120
+ }
121
+ /**
122
+ * Performs the HTTP/HTTPS POST request.
123
+ */
124
+ post(events) {
125
+ return new Promise((resolve, reject) => {
126
+ const payloadString = JSON.stringify(events);
127
+ const headers = {
128
+ 'Content-Type': 'application/json',
129
+ 'Content-Length': Buffer.byteLength(payloadString),
130
+ 'User-Agent': 'growlytics-node-sdk/1.0.0',
131
+ };
132
+ if (this.options.apiKey) {
133
+ headers['Authorization'] = `Bearer ${this.options.apiKey}`;
134
+ headers['X-Growlytics-Key'] = this.options.apiKey; // Alternate standard tracking header
135
+ }
136
+ const requestOptions = {
137
+ hostname: this.url.hostname,
138
+ port: this.url.port || (this.isHttps ? 443 : 80),
139
+ path: this.url.pathname + this.url.search,
140
+ method: 'POST',
141
+ headers: headers,
142
+ timeout: 10000, // 10 second timeout
143
+ };
144
+ const requestModule = this.isHttps ? https : http;
145
+ const req = requestModule.request(requestOptions, (res) => {
146
+ let responseBody = '';
147
+ res.on('data', (chunk) => {
148
+ responseBody += chunk;
149
+ });
150
+ res.on('end', () => {
151
+ const status = res.statusCode || 0;
152
+ if (status >= 200 && status < 300) {
153
+ resolve();
154
+ }
155
+ else {
156
+ const error = new Error(`HTTP Error Status ${status}: ${responseBody || res.statusMessage}`);
157
+ error.statusCode = status;
158
+ reject(error);
159
+ }
160
+ });
161
+ });
162
+ req.on('error', (err) => {
163
+ reject(err);
164
+ });
165
+ req.on('timeout', () => {
166
+ req.destroy();
167
+ const err = new Error('Request timed out');
168
+ err.code = 'ETIMEDOUT';
169
+ reject(err);
170
+ });
171
+ req.write(payloadString);
172
+ req.end();
173
+ });
174
+ }
175
+ }
176
+ exports.HttpClient = HttpClient;
@@ -0,0 +1,2 @@
1
+ export * from "./types";
2
+ export { Growlytic } from "./growlytics";
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.Growlytic = void 0;
18
+ __exportStar(require("./types"), exports);
19
+ var growlytics_1 = require("./growlytics");
20
+ Object.defineProperty(exports, "Growlytic", { enumerable: true, get: function () { return growlytics_1.Growlytic; } });
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
@@ -0,0 +1,45 @@
1
+ import { TrackingEvent } from './types';
2
+ import { HttpClient } from './http';
3
+ export interface QueueConfig {
4
+ batchSize: number;
5
+ flushIntervalMs: number;
6
+ maxQueueSize: number;
7
+ debug?: boolean;
8
+ onError?: (error: Error, events: TrackingEvent[]) => void;
9
+ }
10
+ export declare class EventQueue {
11
+ private client;
12
+ private config;
13
+ private queue;
14
+ private timer;
15
+ private isFlushing;
16
+ private activeFlushPromise;
17
+ constructor(client: HttpClient, config: QueueConfig);
18
+ private log;
19
+ /**
20
+ * Add a tracking event to the queue. If the queue is full, the oldest event is discarded.
21
+ */
22
+ add(event: TrackingEvent): void;
23
+ /**
24
+ * Manually trigger a flush of all currently queued events.
25
+ * Returns a promise that resolves when the flush is complete.
26
+ */
27
+ flush(): Promise<void>;
28
+ /**
29
+ * Performs the flush logic, calling the HttpClient to send batches of events.
30
+ */
31
+ private performFlush;
32
+ private startTimer;
33
+ /**
34
+ * Resets the background interval timer.
35
+ */
36
+ private resetTimer;
37
+ /**
38
+ * Stops the background timer.
39
+ */
40
+ stop(): void;
41
+ /**
42
+ * Get the current count of events in the queue.
43
+ */
44
+ get length(): number;
45
+ }
@@ -0,0 +1,121 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.EventQueue = void 0;
4
+ class EventQueue {
5
+ client;
6
+ config;
7
+ queue = [];
8
+ timer = null;
9
+ isFlushing = false;
10
+ activeFlushPromise = null;
11
+ constructor(client, config) {
12
+ this.client = client;
13
+ this.config = config;
14
+ this.startTimer();
15
+ }
16
+ log(message, ...args) {
17
+ if (this.config.debug) {
18
+ console.log(`[Growlytics-SDK][Queue] ${message}`, ...args);
19
+ }
20
+ }
21
+ /**
22
+ * Add a tracking event to the queue. If the queue is full, the oldest event is discarded.
23
+ */
24
+ add(event) {
25
+ if (this.queue.length >= this.config.maxQueueSize) {
26
+ const dropped = this.queue.shift();
27
+ this.log(`Queue full (${this.config.maxQueueSize}). Dropped oldest event to prevent OOM:`, dropped ? dropped.event_type : 'unknown');
28
+ }
29
+ this.queue.push(event);
30
+ this.log(`Event '${event.event_type}' added. Queue size: ${this.queue.length}`);
31
+ // If batch size is reached, trigger an asynchronous flush immediately
32
+ if (this.queue.length >= this.config.batchSize) {
33
+ this.flush().catch(() => { });
34
+ }
35
+ }
36
+ /**
37
+ * Manually trigger a flush of all currently queued events.
38
+ * Returns a promise that resolves when the flush is complete.
39
+ */
40
+ async flush() {
41
+ if (this.isFlushing) {
42
+ this.log('Flush already in progress, waiting for it to complete...');
43
+ return this.activeFlushPromise || Promise.resolve();
44
+ }
45
+ this.isFlushing = true;
46
+ this.activeFlushPromise = this.performFlush();
47
+ try {
48
+ await this.activeFlushPromise;
49
+ }
50
+ finally {
51
+ this.isFlushing = false;
52
+ this.activeFlushPromise = null;
53
+ }
54
+ }
55
+ /**
56
+ * Performs the flush logic, calling the HttpClient to send batches of events.
57
+ */
58
+ async performFlush() {
59
+ this.resetTimer();
60
+ while (this.queue.length > 0) {
61
+ // Dequeue a batch of events
62
+ const batch = this.queue.splice(0, this.config.batchSize);
63
+ if (batch.length === 0) {
64
+ break;
65
+ }
66
+ this.log(`Flushing batch of ${batch.length} events...`);
67
+ try {
68
+ await this.client.sendEvents(batch);
69
+ }
70
+ catch (error) {
71
+ this.log(`Error flushing batch of ${batch.length} events:`, error.message || error);
72
+ // Trigger error callback for custom handling (e.g. write to fallback log file, emit metric)
73
+ if (this.config.onError) {
74
+ try {
75
+ this.config.onError(error, batch);
76
+ }
77
+ catch (callbackErr) {
78
+ this.log('Error inside user-defined onError handler:', callbackErr);
79
+ }
80
+ }
81
+ }
82
+ }
83
+ }
84
+ startTimer() {
85
+ this.resetTimer();
86
+ }
87
+ /**
88
+ * Resets the background interval timer.
89
+ */
90
+ resetTimer() {
91
+ if (this.timer) {
92
+ clearInterval(this.timer);
93
+ }
94
+ this.timer = setInterval(() => {
95
+ if (this.queue.length > 0) {
96
+ this.log(`Flush interval of ${this.config.flushIntervalMs}ms reached. Flushing...`);
97
+ this.flush().catch(() => { });
98
+ }
99
+ }, this.config.flushIntervalMs);
100
+ // Unref the timer so it doesn't block process exit if there is no other work in Node's event loop
101
+ if (this.timer && typeof this.timer.unref === 'function') {
102
+ this.timer.unref();
103
+ }
104
+ }
105
+ /**
106
+ * Stops the background timer.
107
+ */
108
+ stop() {
109
+ if (this.timer) {
110
+ clearInterval(this.timer);
111
+ this.timer = null;
112
+ }
113
+ }
114
+ /**
115
+ * Get the current count of events in the queue.
116
+ */
117
+ get length() {
118
+ return this.queue.length;
119
+ }
120
+ }
121
+ exports.EventQueue = EventQueue;
@@ -0,0 +1,28 @@
1
+ import { GrowlyticsConfig, TrackingEventPayload } from './types';
2
+ export declare class GrowlyticsTracker {
3
+ private config;
4
+ private client;
5
+ private queue;
6
+ constructor(options?: GrowlyticsConfig);
7
+ private log;
8
+ /**
9
+ * Tracks an event by compiling client metadata and placing it in the buffer queue.
10
+ *
11
+ * @param eventType Name of the event, e.g. 'product_view' or 'add_to_cart'
12
+ * @param payload Custom event details and parameters
13
+ */
14
+ track(eventType: string, payload?: TrackingEventPayload): void;
15
+ /**
16
+ * Triggers a manual flush to send all currently buffered events.
17
+ * Useful for serverless functions (like AWS Lambda) before finishing execution.
18
+ */
19
+ flush(): Promise<void>;
20
+ /**
21
+ * Shuts down the tracker, flushing any remaining events and stopping the interval timers.
22
+ */
23
+ shutdown(): Promise<void>;
24
+ /**
25
+ * Set up hooks to flush the queue when the Node process is exiting.
26
+ */
27
+ private setupExitHandlers;
28
+ }
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.GrowlyticsTracker = void 0;
37
+ const os = __importStar(require("os"));
38
+ const http_1 = require("./http");
39
+ const queue_1 = require("./queue");
40
+ const utils_1 = require("./utils");
41
+ const SDK_NAME = 'growlytics-node-sdk';
42
+ const SDK_VERSION = '1.0.0';
43
+ class GrowlyticsTracker {
44
+ config;
45
+ client;
46
+ queue;
47
+ constructor(options = {}) {
48
+ // Standardize configurations with robust default values
49
+ this.config = {
50
+ clientId: options.clientId || 0,
51
+ workspaceId: options.workspaceId || 0,
52
+ applicationId: options.applicationId || 0,
53
+ apiKey: options.apiKey || '',
54
+ baseUrl: options.baseUrl || 'https://api.growlytics.co',
55
+ path: options.path || '/events',
56
+ batchSize: options.batchSize ?? 20,
57
+ flushIntervalMs: options.flushIntervalMs ?? 2000,
58
+ maxQueueSize: options.maxQueueSize ?? 1000,
59
+ debug: options.debug ?? false,
60
+ maxRetries: options.maxRetries ?? 3,
61
+ retryInitialDelayMs: options.retryInitialDelayMs ?? 1000,
62
+ retryMaxDelayMs: options.retryMaxDelayMs ?? 30000,
63
+ onError: options.onError || (() => { }),
64
+ disableAutoContext: options.disableAutoContext ?? false,
65
+ };
66
+ // Initialize the HTTP Client
67
+ this.client = new http_1.HttpClient({
68
+ baseUrl: this.config.baseUrl,
69
+ path: this.config.path,
70
+ apiKey: this.config.apiKey,
71
+ maxRetries: this.config.maxRetries,
72
+ retryInitialDelayMs: this.config.retryInitialDelayMs,
73
+ retryMaxDelayMs: this.config.retryMaxDelayMs,
74
+ debug: this.config.debug,
75
+ });
76
+ // Initialize the Event Queue
77
+ this.queue = new queue_1.EventQueue(this.client, {
78
+ batchSize: this.config.batchSize,
79
+ flushIntervalMs: this.config.flushIntervalMs,
80
+ maxQueueSize: this.config.maxQueueSize,
81
+ debug: this.config.debug,
82
+ onError: this.config.onError,
83
+ });
84
+ this.log('Tracker initialized successfully.');
85
+ this.setupExitHandlers();
86
+ }
87
+ log(message, ...args) {
88
+ if (this.config.debug) {
89
+ console.log(`[Growlytics-SDK] ${message}`, ...args);
90
+ }
91
+ }
92
+ /**
93
+ * Tracks an event by compiling client metadata and placing it in the buffer queue.
94
+ *
95
+ * @param eventType Name of the event, e.g. 'product_view' or 'add_to_cart'
96
+ * @param payload Custom event details and parameters
97
+ */
98
+ track(eventType, payload = {}) {
99
+ if (!eventType) {
100
+ throw new Error("Event tracking requires a valid 'event_type' / event name.");
101
+ }
102
+ this.log(`Track called for event: ${eventType}`);
103
+ // Auto-detect server device metadata if enabled
104
+ let autoDevice = {};
105
+ if (!this.config.disableAutoContext) {
106
+ try {
107
+ autoDevice = {
108
+ device_type: 'server',
109
+ os: os.platform(),
110
+ os_version: os.release(),
111
+ browser: 'node',
112
+ browser_version: process.version,
113
+ language: process.env.LANG || 'en-US',
114
+ user_agent: `${SDK_NAME}/${SDK_VERSION} (node ${process.version}; ${os.platform()} ${os.release()})`,
115
+ };
116
+ }
117
+ catch (err) {
118
+ this.log('Failed to auto-gather server context details:', err);
119
+ }
120
+ }
121
+ // Prepare SDK library details
122
+ const libraryMetadata = {
123
+ name: SDK_NAME,
124
+ version: SDK_VERSION,
125
+ };
126
+ // Construct the base tracking event with required system keys and auto-generated defaults
127
+ const defaultFields = {
128
+ event_type: eventType,
129
+ client_id: this.config.clientId,
130
+ workspace_id: this.config.workspaceId,
131
+ application_id: this.config.applicationId,
132
+ timestamp: new Date().toISOString(),
133
+ anonymous_id: (0, utils_1.generateUUID)(),
134
+ request_id: (0, utils_1.generateUUID)(),
135
+ library: libraryMetadata,
136
+ };
137
+ // Deep merge payload into defaults. User provided fields will take precedence.
138
+ const compiledEvent = (0, utils_1.mergeDeep)(defaultFields, payload);
139
+ // Explicitly override sub-objects if they need merged device context
140
+ if (!this.config.disableAutoContext) {
141
+ compiledEvent.device = (0, utils_1.mergeDeep)(autoDevice, payload.device || {});
142
+ }
143
+ // Add back the required event_type just in case payload modified it
144
+ compiledEvent.event_type = eventType;
145
+ // Enqueue the finalized event
146
+ this.queue.add(compiledEvent);
147
+ }
148
+ /**
149
+ * Triggers a manual flush to send all currently buffered events.
150
+ * Useful for serverless functions (like AWS Lambda) before finishing execution.
151
+ */
152
+ async flush() {
153
+ this.log('Manual flush triggered.');
154
+ await this.queue.flush();
155
+ }
156
+ /**
157
+ * Shuts down the tracker, flushing any remaining events and stopping the interval timers.
158
+ */
159
+ async shutdown() {
160
+ this.log('Shutdown initiated.');
161
+ await this.flush();
162
+ this.queue.stop();
163
+ this.log('Tracker stopped.');
164
+ }
165
+ /**
166
+ * Set up hooks to flush the queue when the Node process is exiting.
167
+ */
168
+ setupExitHandlers() {
169
+ process.once('beforeExit', () => {
170
+ this.log('Process beforeExit hook triggered. Flushing queue...');
171
+ this.flush().catch((err) => {
172
+ this.log('Failed to flush queue on beforeExit:', err);
173
+ });
174
+ });
175
+ }
176
+ }
177
+ exports.GrowlyticsTracker = GrowlyticsTracker;
@@ -0,0 +1,16 @@
1
+ export interface UserIdentifier {
2
+ customer_id?: string;
3
+ external_id?: string;
4
+ email?: string;
5
+ phone?: string;
6
+ }
7
+ export interface InitOptions {
8
+ client_id: number;
9
+ workspace_id: number;
10
+ app_id: number;
11
+ debug?: boolean;
12
+ }
13
+ export interface TrackPayload {
14
+ user_identifier?: UserIdentifier;
15
+ custom?: Record<string, any>;
16
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Generate a cryptographically secure random UUID (v4)
3
+ * Uses native crypto.randomUUID if available (Node 14.17.0+),
4
+ * falls back to a math-based generator for older Node environments.
5
+ */
6
+ export declare function generateUUID(): string;
7
+ /**
8
+ * Check if a value is a plain object
9
+ */
10
+ export declare function isObject(item: any): item is Record<string, any>;
11
+ /**
12
+ * Deep merges two objects. User-provided values (source) will overwrite target values,
13
+ * but nested structures will be recursively merged rather than replaced entirely.
14
+ */
15
+ export declare function mergeDeep<T extends Record<string, any>>(target: T, source: Record<string, any>): T;