@doow/track-react 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Doow
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,182 @@
1
+ # Doow Track React SDK
2
+
3
+ [![React](https://img.shields.io/badge/React-17+-blue)](https://react.dev/)
4
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-blue)](https://www.typescriptlang.org/)
5
+ [![License](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
+
7
+ Official React SDK for [Doow](https://doow.co) usage telemetry.
8
+
9
+ ## Features
10
+
11
+ | Feature | Description |
12
+ |---------|-------------|
13
+ | **React 17+** | Hooks and Context API |
14
+ | **TypeScript** | Full type safety |
15
+ | **Batching** | Events queued and sent in configurable batches |
16
+ | **Compression** | Automatic gzip via CompressionStream |
17
+ | **Lifecycle** | Auto-flush on beforeunload/visibilitychange |
18
+ | **Beacon** | Reliable delivery with sendBeacon fallback |
19
+
20
+ ---
21
+
22
+ ## Installation
23
+
24
+ ```bash
25
+ npm install @doow/track-react
26
+ # or
27
+ yarn add @doow/track-react
28
+ # or
29
+ pnpm add @doow/track-react
30
+ ```
31
+
32
+ ---
33
+
34
+ ## Quick Start
35
+
36
+ ### Provider Setup
37
+
38
+ ```tsx
39
+ import { DoowProvider } from '@doow/track-react';
40
+
41
+ function App() {
42
+ return (
43
+ <DoowProvider apiKey="dk_your_api_key">
44
+ <YourApp />
45
+ </DoowProvider>
46
+ );
47
+ }
48
+ ```
49
+
50
+ ### Track Events
51
+
52
+ ```tsx
53
+ import { useTrackEvent } from '@doow/track-react';
54
+
55
+ function FeatureButton() {
56
+ const track = useTrackEvent();
57
+
58
+ const handleClick = () => {
59
+ track({
60
+ metric: 'feature_usage',
61
+ quantity: 1,
62
+ licenseId: 'lic_abc123',
63
+ attribution: { feature: 'export' },
64
+ });
65
+ };
66
+
67
+ return <button onClick={handleClick}>Export</button>;
68
+ }
69
+ ```
70
+
71
+ ### Track on Mount
72
+
73
+ ```tsx
74
+ import { useTrackOnMount } from '@doow/track-react';
75
+
76
+ function Dashboard() {
77
+ useTrackOnMount({
78
+ metric: 'page_view',
79
+ quantity: 1,
80
+ licenseId: 'lic_abc123',
81
+ attribution: { page: 'dashboard' },
82
+ });
83
+
84
+ return <div>Dashboard</div>;
85
+ }
86
+ ```
87
+
88
+ ### Track on Change
89
+
90
+ ```tsx
91
+ import { useTrackOnChange } from '@doow/track-react';
92
+
93
+ function TokenCounter({ tokens }: { tokens: number }) {
94
+ useTrackOnChange(tokens, (value) => ({
95
+ metric: 'tokens_used',
96
+ quantity: value,
97
+ licenseId: 'lic_abc123',
98
+ }));
99
+
100
+ return <span>{tokens} tokens</span>;
101
+ }
102
+ ```
103
+
104
+ ---
105
+
106
+ ## Configuration
107
+
108
+ ```tsx
109
+ <DoowProvider
110
+ apiKey="dk_your_api_key"
111
+ options={{
112
+ endpoint: 'https://api.doow.co',
113
+ enabled: true,
114
+ debug: process.env.NODE_ENV === 'development',
115
+ flushAt: 20,
116
+ flushIntervalMs: 10000,
117
+ maxQueueSize: 10000,
118
+ timeoutMs: 10000,
119
+ retryCount: 3,
120
+ disableCompression: false,
121
+ attribution: { app: 'my-saas' },
122
+ onError: (e) => console.error('Doow error:', e),
123
+ }}
124
+ >
125
+ <App />
126
+ </DoowProvider>
127
+ ```
128
+
129
+ ---
130
+
131
+ ## Hooks
132
+
133
+ | Hook | Description |
134
+ |------|-------------|
135
+ | `useDoow()` | Full context: `{ track, flush, isEnabled }` |
136
+ | `useTrackEvent()` | Just the `track` function |
137
+ | `useTrackOnMount(event)` | Track once on component mount |
138
+ | `useTrackOnChange(value, getEvent)` | Track when value changes |
139
+
140
+ ---
141
+
142
+ ## Manual Flush
143
+
144
+ ```tsx
145
+ import { useDoow } from '@doow/track-react';
146
+
147
+ function LogoutButton() {
148
+ const { flush } = useDoow();
149
+
150
+ const handleLogout = async () => {
151
+ await flush();
152
+ logout();
153
+ };
154
+
155
+ return <button onClick={handleLogout}>Logout</button>;
156
+ }
157
+ ```
158
+
159
+ ---
160
+
161
+ ## Without Provider
162
+
163
+ ```tsx
164
+ import { Tracker } from '@doow/track-react';
165
+
166
+ const tracker = new Tracker('dk_your_api_key', { debug: true });
167
+
168
+ tracker.track({
169
+ metric: 'api_calls',
170
+ quantity: 1,
171
+ licenseId: 'lic_abc123',
172
+ });
173
+
174
+ // On app shutdown
175
+ tracker.destroy();
176
+ ```
177
+
178
+ ---
179
+
180
+ ## License
181
+
182
+ MIT
@@ -0,0 +1,64 @@
1
+ import React$1 from 'react';
2
+
3
+ interface TrackEvent {
4
+ metric: string;
5
+ quantity: number;
6
+ licenseId: string;
7
+ unit?: string;
8
+ attribution?: Record<string, unknown>;
9
+ timestamp?: string;
10
+ }
11
+ interface TrackerOptions {
12
+ endpoint?: string;
13
+ enabled?: boolean;
14
+ debug?: boolean;
15
+ flushAt?: number;
16
+ flushIntervalMs?: number;
17
+ maxQueueSize?: number;
18
+ timeoutMs?: number;
19
+ retryCount?: number;
20
+ disableCompression?: boolean;
21
+ attribution?: Record<string, unknown>;
22
+ onError?: (error: Error) => void;
23
+ }
24
+ interface DoowContextValue {
25
+ track: (event: TrackEvent) => void;
26
+ flush: () => Promise<void>;
27
+ isEnabled: boolean;
28
+ }
29
+ interface DoowProviderProps$1 {
30
+ apiKey: string;
31
+ options?: TrackerOptions;
32
+ children: React.ReactNode;
33
+ }
34
+
35
+ declare class Tracker {
36
+ private apiKey;
37
+ private options;
38
+ private queue;
39
+ private flushTimer;
40
+ private shutdown;
41
+ constructor(apiKey: string, options?: TrackerOptions);
42
+ private startFlushTimer;
43
+ private setupLifecycleHooks;
44
+ private log;
45
+ track(event: TrackEvent): void;
46
+ flush(): Promise<void>;
47
+ private flushSync;
48
+ private sendWithRetry;
49
+ private sleep;
50
+ destroy(): void;
51
+ }
52
+
53
+ interface DoowProviderProps {
54
+ apiKey: string;
55
+ options?: TrackerOptions;
56
+ children: React$1.ReactNode;
57
+ }
58
+ declare function DoowProvider({ apiKey, options, children }: DoowProviderProps): JSX.Element;
59
+ declare function useDoow(): DoowContextValue;
60
+ declare function useTrackEvent(): (event: TrackEvent) => void;
61
+ declare function useTrackOnMount(event: TrackEvent): void;
62
+ declare function useTrackOnChange<T>(value: T, getEvent: (value: T) => TrackEvent | null): void;
63
+
64
+ export { type DoowContextValue, DoowProvider, type DoowProviderProps$1 as DoowProviderProps, type TrackEvent, Tracker, type TrackerOptions, useDoow, useTrackEvent, useTrackOnChange, useTrackOnMount };
@@ -0,0 +1,64 @@
1
+ import React$1 from 'react';
2
+
3
+ interface TrackEvent {
4
+ metric: string;
5
+ quantity: number;
6
+ licenseId: string;
7
+ unit?: string;
8
+ attribution?: Record<string, unknown>;
9
+ timestamp?: string;
10
+ }
11
+ interface TrackerOptions {
12
+ endpoint?: string;
13
+ enabled?: boolean;
14
+ debug?: boolean;
15
+ flushAt?: number;
16
+ flushIntervalMs?: number;
17
+ maxQueueSize?: number;
18
+ timeoutMs?: number;
19
+ retryCount?: number;
20
+ disableCompression?: boolean;
21
+ attribution?: Record<string, unknown>;
22
+ onError?: (error: Error) => void;
23
+ }
24
+ interface DoowContextValue {
25
+ track: (event: TrackEvent) => void;
26
+ flush: () => Promise<void>;
27
+ isEnabled: boolean;
28
+ }
29
+ interface DoowProviderProps$1 {
30
+ apiKey: string;
31
+ options?: TrackerOptions;
32
+ children: React.ReactNode;
33
+ }
34
+
35
+ declare class Tracker {
36
+ private apiKey;
37
+ private options;
38
+ private queue;
39
+ private flushTimer;
40
+ private shutdown;
41
+ constructor(apiKey: string, options?: TrackerOptions);
42
+ private startFlushTimer;
43
+ private setupLifecycleHooks;
44
+ private log;
45
+ track(event: TrackEvent): void;
46
+ flush(): Promise<void>;
47
+ private flushSync;
48
+ private sendWithRetry;
49
+ private sleep;
50
+ destroy(): void;
51
+ }
52
+
53
+ interface DoowProviderProps {
54
+ apiKey: string;
55
+ options?: TrackerOptions;
56
+ children: React$1.ReactNode;
57
+ }
58
+ declare function DoowProvider({ apiKey, options, children }: DoowProviderProps): JSX.Element;
59
+ declare function useDoow(): DoowContextValue;
60
+ declare function useTrackEvent(): (event: TrackEvent) => void;
61
+ declare function useTrackOnMount(event: TrackEvent): void;
62
+ declare function useTrackOnChange<T>(value: T, getEvent: (value: T) => TrackEvent | null): void;
63
+
64
+ export { type DoowContextValue, DoowProvider, type DoowProviderProps$1 as DoowProviderProps, type TrackEvent, Tracker, type TrackerOptions, useDoow, useTrackEvent, useTrackOnChange, useTrackOnMount };
package/dist/index.js ADDED
@@ -0,0 +1,259 @@
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/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ DoowProvider: () => DoowProvider,
24
+ Tracker: () => Tracker,
25
+ useDoow: () => useDoow,
26
+ useTrackEvent: () => useTrackEvent,
27
+ useTrackOnChange: () => useTrackOnChange,
28
+ useTrackOnMount: () => useTrackOnMount
29
+ });
30
+ module.exports = __toCommonJS(index_exports);
31
+
32
+ // src/tracker.ts
33
+ function generateUUID() {
34
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
35
+ return crypto.randomUUID();
36
+ }
37
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
38
+ const r = Math.random() * 16 | 0;
39
+ const v = c === "x" ? r : r & 3 | 8;
40
+ return v.toString(16);
41
+ });
42
+ }
43
+ var DEFAULT_OPTIONS = {
44
+ endpoint: "https://api.doow.co",
45
+ enabled: true,
46
+ debug: false,
47
+ flushAt: 20,
48
+ flushIntervalMs: 1e4,
49
+ maxQueueSize: 1e4,
50
+ timeoutMs: 1e4,
51
+ retryCount: 3,
52
+ disableCompression: false
53
+ };
54
+ var Tracker = class {
55
+ constructor(apiKey, options = {}) {
56
+ this.queue = [];
57
+ this.flushTimer = null;
58
+ this.shutdown = false;
59
+ if (!apiKey.startsWith("dk_")) {
60
+ throw new Error("API key must start with dk_");
61
+ }
62
+ this.apiKey = apiKey;
63
+ this.options = { ...DEFAULT_OPTIONS, ...options };
64
+ this.startFlushTimer();
65
+ this.setupLifecycleHooks();
66
+ }
67
+ startFlushTimer() {
68
+ if (this.flushTimer) clearInterval(this.flushTimer);
69
+ this.flushTimer = setInterval(() => this.flush(), this.options.flushIntervalMs);
70
+ }
71
+ setupLifecycleHooks() {
72
+ if (typeof window === "undefined") return;
73
+ window.addEventListener("beforeunload", () => this.flushSync());
74
+ document.addEventListener("visibilitychange", () => {
75
+ if (document.visibilityState === "hidden") {
76
+ this.flushSync();
77
+ }
78
+ });
79
+ }
80
+ log(message) {
81
+ if (this.options.debug) {
82
+ console.log(`[DoowTrack] ${message}`);
83
+ }
84
+ }
85
+ track(event) {
86
+ if (!this.options.enabled || this.shutdown) return;
87
+ if (this.queue.length >= this.options.maxQueueSize) {
88
+ this.log("Queue full, dropping event");
89
+ return;
90
+ }
91
+ const enrichedEvent = {
92
+ ...event,
93
+ timestamp: event.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
94
+ attribution: { ...event.attribution, ...this.options.attribution }
95
+ };
96
+ this.queue.push(enrichedEvent);
97
+ this.log(`Queued event: ${event.metric}`);
98
+ if (this.queue.length >= this.options.flushAt) {
99
+ this.flush();
100
+ }
101
+ }
102
+ async flush() {
103
+ if (this.queue.length === 0 || this.shutdown) return;
104
+ const batch = [...this.queue];
105
+ this.queue = [];
106
+ this.log(`Flushing ${batch.length} events`);
107
+ try {
108
+ await this.sendWithRetry(batch);
109
+ } catch (error) {
110
+ this.options.onError?.(error);
111
+ this.log(`Flush failed: ${error}`);
112
+ }
113
+ }
114
+ flushSync() {
115
+ if (this.queue.length === 0 || typeof navigator === "undefined") return;
116
+ const payload = JSON.stringify({
117
+ events: this.queue.map((e) => ({
118
+ event_id: generateUUID(),
119
+ metric: e.metric,
120
+ quantity: e.quantity,
121
+ license_id: e.licenseId,
122
+ unit: e.unit,
123
+ attribution: e.attribution,
124
+ timestamp: e.timestamp
125
+ }))
126
+ });
127
+ const blob = new Blob([payload], { type: "application/json" });
128
+ navigator.sendBeacon(`${this.options.endpoint}/telemetry/events`, blob);
129
+ this.queue = [];
130
+ }
131
+ async sendWithRetry(batch) {
132
+ const payload = JSON.stringify({
133
+ events: batch.map((e) => ({
134
+ event_id: generateUUID(),
135
+ metric: e.metric,
136
+ quantity: e.quantity,
137
+ license_id: e.licenseId,
138
+ unit: e.unit,
139
+ attribution: e.attribution,
140
+ timestamp: e.timestamp
141
+ }))
142
+ });
143
+ const headers = {
144
+ "Authorization": `Bearer ${this.apiKey}`,
145
+ "Content-Type": "application/json"
146
+ };
147
+ let body = payload;
148
+ if (!this.options.disableCompression && payload.length > 1024 && typeof CompressionStream !== "undefined") {
149
+ const stream = new Blob([payload]).stream().pipeThrough(new CompressionStream("gzip"));
150
+ body = await new Response(stream).blob();
151
+ headers["Content-Encoding"] = "gzip";
152
+ }
153
+ for (let attempt = 0; attempt <= this.options.retryCount; attempt++) {
154
+ try {
155
+ const controller = new AbortController();
156
+ const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
157
+ const response = await fetch(`${this.options.endpoint}/telemetry/events`, {
158
+ method: "POST",
159
+ headers,
160
+ body,
161
+ signal: controller.signal
162
+ });
163
+ clearTimeout(timeout);
164
+ if (response.ok) {
165
+ this.log("Batch sent successfully");
166
+ return;
167
+ }
168
+ if (response.status === 429) {
169
+ const retryAfter = response.headers.get("Retry-After");
170
+ const delay = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 100 * Math.pow(2, attempt);
171
+ await this.sleep(delay);
172
+ continue;
173
+ }
174
+ if (response.status >= 500) {
175
+ await this.sleep(100 * Math.pow(2, attempt));
176
+ continue;
177
+ }
178
+ throw new Error(`HTTP ${response.status}: ${await response.text()}`);
179
+ } catch (error) {
180
+ if (attempt === this.options.retryCount) throw error;
181
+ await this.sleep(100 * Math.pow(2, attempt));
182
+ }
183
+ }
184
+ }
185
+ sleep(ms) {
186
+ return new Promise((resolve) => setTimeout(resolve, ms));
187
+ }
188
+ destroy() {
189
+ this.shutdown = true;
190
+ if (this.flushTimer) clearInterval(this.flushTimer);
191
+ this.flushSync();
192
+ }
193
+ };
194
+
195
+ // src/context.tsx
196
+ var import_react = require("react");
197
+ var import_jsx_runtime = require("react/jsx-runtime");
198
+ var DoowContext = (0, import_react.createContext)(null);
199
+ function DoowProvider({ apiKey, options, children }) {
200
+ const trackerRef = (0, import_react.useRef)(null);
201
+ if (!trackerRef.current) {
202
+ trackerRef.current = new Tracker(apiKey, options);
203
+ }
204
+ (0, import_react.useEffect)(() => {
205
+ return () => {
206
+ trackerRef.current?.destroy();
207
+ };
208
+ }, []);
209
+ const value = (0, import_react.useMemo)(
210
+ () => ({
211
+ track: (event) => trackerRef.current?.track(event),
212
+ flush: () => trackerRef.current?.flush() ?? Promise.resolve(),
213
+ isEnabled: options?.enabled !== false
214
+ }),
215
+ [options?.enabled]
216
+ );
217
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DoowContext.Provider, { value, children });
218
+ }
219
+ function useDoow() {
220
+ const context = (0, import_react.useContext)(DoowContext);
221
+ if (!context) {
222
+ throw new Error("useDoow must be used within a DoowProvider");
223
+ }
224
+ return context;
225
+ }
226
+ function useTrackEvent() {
227
+ const { track } = useDoow();
228
+ return track;
229
+ }
230
+ function useTrackOnMount(event) {
231
+ const { track } = useDoow();
232
+ const tracked = (0, import_react.useRef)(false);
233
+ (0, import_react.useEffect)(() => {
234
+ if (!tracked.current) {
235
+ track(event);
236
+ tracked.current = true;
237
+ }
238
+ }, []);
239
+ }
240
+ function useTrackOnChange(value, getEvent) {
241
+ const { track } = useDoow();
242
+ const prevValue = (0, import_react.useRef)(value);
243
+ (0, import_react.useEffect)(() => {
244
+ if (value !== prevValue.current) {
245
+ const event = getEvent(value);
246
+ if (event) track(event);
247
+ prevValue.current = value;
248
+ }
249
+ }, [value, getEvent, track]);
250
+ }
251
+ // Annotate the CommonJS export names for ESM import in node:
252
+ 0 && (module.exports = {
253
+ DoowProvider,
254
+ Tracker,
255
+ useDoow,
256
+ useTrackEvent,
257
+ useTrackOnChange,
258
+ useTrackOnMount
259
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,227 @@
1
+ // src/tracker.ts
2
+ function generateUUID() {
3
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
4
+ return crypto.randomUUID();
5
+ }
6
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
7
+ const r = Math.random() * 16 | 0;
8
+ const v = c === "x" ? r : r & 3 | 8;
9
+ return v.toString(16);
10
+ });
11
+ }
12
+ var DEFAULT_OPTIONS = {
13
+ endpoint: "https://api.doow.co",
14
+ enabled: true,
15
+ debug: false,
16
+ flushAt: 20,
17
+ flushIntervalMs: 1e4,
18
+ maxQueueSize: 1e4,
19
+ timeoutMs: 1e4,
20
+ retryCount: 3,
21
+ disableCompression: false
22
+ };
23
+ var Tracker = class {
24
+ constructor(apiKey, options = {}) {
25
+ this.queue = [];
26
+ this.flushTimer = null;
27
+ this.shutdown = false;
28
+ if (!apiKey.startsWith("dk_")) {
29
+ throw new Error("API key must start with dk_");
30
+ }
31
+ this.apiKey = apiKey;
32
+ this.options = { ...DEFAULT_OPTIONS, ...options };
33
+ this.startFlushTimer();
34
+ this.setupLifecycleHooks();
35
+ }
36
+ startFlushTimer() {
37
+ if (this.flushTimer) clearInterval(this.flushTimer);
38
+ this.flushTimer = setInterval(() => this.flush(), this.options.flushIntervalMs);
39
+ }
40
+ setupLifecycleHooks() {
41
+ if (typeof window === "undefined") return;
42
+ window.addEventListener("beforeunload", () => this.flushSync());
43
+ document.addEventListener("visibilitychange", () => {
44
+ if (document.visibilityState === "hidden") {
45
+ this.flushSync();
46
+ }
47
+ });
48
+ }
49
+ log(message) {
50
+ if (this.options.debug) {
51
+ console.log(`[DoowTrack] ${message}`);
52
+ }
53
+ }
54
+ track(event) {
55
+ if (!this.options.enabled || this.shutdown) return;
56
+ if (this.queue.length >= this.options.maxQueueSize) {
57
+ this.log("Queue full, dropping event");
58
+ return;
59
+ }
60
+ const enrichedEvent = {
61
+ ...event,
62
+ timestamp: event.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
63
+ attribution: { ...event.attribution, ...this.options.attribution }
64
+ };
65
+ this.queue.push(enrichedEvent);
66
+ this.log(`Queued event: ${event.metric}`);
67
+ if (this.queue.length >= this.options.flushAt) {
68
+ this.flush();
69
+ }
70
+ }
71
+ async flush() {
72
+ if (this.queue.length === 0 || this.shutdown) return;
73
+ const batch = [...this.queue];
74
+ this.queue = [];
75
+ this.log(`Flushing ${batch.length} events`);
76
+ try {
77
+ await this.sendWithRetry(batch);
78
+ } catch (error) {
79
+ this.options.onError?.(error);
80
+ this.log(`Flush failed: ${error}`);
81
+ }
82
+ }
83
+ flushSync() {
84
+ if (this.queue.length === 0 || typeof navigator === "undefined") return;
85
+ const payload = JSON.stringify({
86
+ events: this.queue.map((e) => ({
87
+ event_id: generateUUID(),
88
+ metric: e.metric,
89
+ quantity: e.quantity,
90
+ license_id: e.licenseId,
91
+ unit: e.unit,
92
+ attribution: e.attribution,
93
+ timestamp: e.timestamp
94
+ }))
95
+ });
96
+ const blob = new Blob([payload], { type: "application/json" });
97
+ navigator.sendBeacon(`${this.options.endpoint}/telemetry/events`, blob);
98
+ this.queue = [];
99
+ }
100
+ async sendWithRetry(batch) {
101
+ const payload = JSON.stringify({
102
+ events: batch.map((e) => ({
103
+ event_id: generateUUID(),
104
+ metric: e.metric,
105
+ quantity: e.quantity,
106
+ license_id: e.licenseId,
107
+ unit: e.unit,
108
+ attribution: e.attribution,
109
+ timestamp: e.timestamp
110
+ }))
111
+ });
112
+ const headers = {
113
+ "Authorization": `Bearer ${this.apiKey}`,
114
+ "Content-Type": "application/json"
115
+ };
116
+ let body = payload;
117
+ if (!this.options.disableCompression && payload.length > 1024 && typeof CompressionStream !== "undefined") {
118
+ const stream = new Blob([payload]).stream().pipeThrough(new CompressionStream("gzip"));
119
+ body = await new Response(stream).blob();
120
+ headers["Content-Encoding"] = "gzip";
121
+ }
122
+ for (let attempt = 0; attempt <= this.options.retryCount; attempt++) {
123
+ try {
124
+ const controller = new AbortController();
125
+ const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
126
+ const response = await fetch(`${this.options.endpoint}/telemetry/events`, {
127
+ method: "POST",
128
+ headers,
129
+ body,
130
+ signal: controller.signal
131
+ });
132
+ clearTimeout(timeout);
133
+ if (response.ok) {
134
+ this.log("Batch sent successfully");
135
+ return;
136
+ }
137
+ if (response.status === 429) {
138
+ const retryAfter = response.headers.get("Retry-After");
139
+ const delay = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 100 * Math.pow(2, attempt);
140
+ await this.sleep(delay);
141
+ continue;
142
+ }
143
+ if (response.status >= 500) {
144
+ await this.sleep(100 * Math.pow(2, attempt));
145
+ continue;
146
+ }
147
+ throw new Error(`HTTP ${response.status}: ${await response.text()}`);
148
+ } catch (error) {
149
+ if (attempt === this.options.retryCount) throw error;
150
+ await this.sleep(100 * Math.pow(2, attempt));
151
+ }
152
+ }
153
+ }
154
+ sleep(ms) {
155
+ return new Promise((resolve) => setTimeout(resolve, ms));
156
+ }
157
+ destroy() {
158
+ this.shutdown = true;
159
+ if (this.flushTimer) clearInterval(this.flushTimer);
160
+ this.flushSync();
161
+ }
162
+ };
163
+
164
+ // src/context.tsx
165
+ import { createContext, useContext, useEffect, useMemo, useRef } from "react";
166
+ import { jsx } from "react/jsx-runtime";
167
+ var DoowContext = createContext(null);
168
+ function DoowProvider({ apiKey, options, children }) {
169
+ const trackerRef = useRef(null);
170
+ if (!trackerRef.current) {
171
+ trackerRef.current = new Tracker(apiKey, options);
172
+ }
173
+ useEffect(() => {
174
+ return () => {
175
+ trackerRef.current?.destroy();
176
+ };
177
+ }, []);
178
+ const value = useMemo(
179
+ () => ({
180
+ track: (event) => trackerRef.current?.track(event),
181
+ flush: () => trackerRef.current?.flush() ?? Promise.resolve(),
182
+ isEnabled: options?.enabled !== false
183
+ }),
184
+ [options?.enabled]
185
+ );
186
+ return /* @__PURE__ */ jsx(DoowContext.Provider, { value, children });
187
+ }
188
+ function useDoow() {
189
+ const context = useContext(DoowContext);
190
+ if (!context) {
191
+ throw new Error("useDoow must be used within a DoowProvider");
192
+ }
193
+ return context;
194
+ }
195
+ function useTrackEvent() {
196
+ const { track } = useDoow();
197
+ return track;
198
+ }
199
+ function useTrackOnMount(event) {
200
+ const { track } = useDoow();
201
+ const tracked = useRef(false);
202
+ useEffect(() => {
203
+ if (!tracked.current) {
204
+ track(event);
205
+ tracked.current = true;
206
+ }
207
+ }, []);
208
+ }
209
+ function useTrackOnChange(value, getEvent) {
210
+ const { track } = useDoow();
211
+ const prevValue = useRef(value);
212
+ useEffect(() => {
213
+ if (value !== prevValue.current) {
214
+ const event = getEvent(value);
215
+ if (event) track(event);
216
+ prevValue.current = value;
217
+ }
218
+ }, [value, getEvent, track]);
219
+ }
220
+ export {
221
+ DoowProvider,
222
+ Tracker,
223
+ useDoow,
224
+ useTrackEvent,
225
+ useTrackOnChange,
226
+ useTrackOnMount
227
+ };
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@doow/track-react",
3
+ "version": "0.1.0",
4
+ "description": "Official React SDK for Doow usage telemetry",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": "./dist/index.mjs",
11
+ "require": "./dist/index.js",
12
+ "types": "./dist/index.d.ts"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist"
17
+ ],
18
+ "scripts": {
19
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean",
20
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
21
+ "lint": "eslint src",
22
+ "test": "vitest"
23
+ },
24
+ "peerDependencies": {
25
+ "react": ">=17.0.0"
26
+ },
27
+ "devDependencies": {
28
+ "@types/react": "^18.2.0",
29
+ "react": "^18.2.0",
30
+ "tsup": "^8.0.0",
31
+ "typescript": "^5.3.0",
32
+ "vitest": "^1.0.0"
33
+ },
34
+ "keywords": [
35
+ "doow",
36
+ "telemetry",
37
+ "usage",
38
+ "billing",
39
+ "react",
40
+ "hooks"
41
+ ],
42
+ "author": "Doow",
43
+ "license": "MIT",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/Doow-Dev/doow-track-react.git"
47
+ }
48
+ }