@doow/track-react-native 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 +21 -0
- package/README.md +171 -0
- package/dist/index.d.mts +62 -0
- package/dist/index.d.ts +62 -0
- package/dist/index.js +273 -0
- package/dist/index.mjs +231 -0
- package/package.json +53 -0
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,171 @@
|
|
|
1
|
+
# Doow Track React Native SDK
|
|
2
|
+
|
|
3
|
+
[](https://reactnative.dev/)
|
|
4
|
+
[](https://expo.dev/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
Official React Native SDK for [Doow](https://doow.co) usage telemetry. Works with React Native CLI and Expo.
|
|
8
|
+
|
|
9
|
+
## Features
|
|
10
|
+
|
|
11
|
+
| Feature | Description |
|
|
12
|
+
|---------|-------------|
|
|
13
|
+
| **React Native 0.70+** | Hooks and Context API |
|
|
14
|
+
| **Expo** | Works with Expo managed and bare workflows |
|
|
15
|
+
| **Batching** | Events queued and sent in configurable batches |
|
|
16
|
+
| **Persistence** | Queue survives app restarts via AsyncStorage |
|
|
17
|
+
| **AppState** | Auto-flush on background/inactive |
|
|
18
|
+
| **Navigation** | `useTrackOnFocus` hook for screen tracking |
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
npm install @doow/track-react-native @react-native-async-storage/async-storage
|
|
26
|
+
# or
|
|
27
|
+
yarn add @doow/track-react-native @react-native-async-storage/async-storage
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Expo
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
npx expo install @doow/track-react-native @react-native-async-storage/async-storage
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
---
|
|
37
|
+
|
|
38
|
+
## Quick Start
|
|
39
|
+
|
|
40
|
+
### Provider Setup
|
|
41
|
+
|
|
42
|
+
```tsx
|
|
43
|
+
import { DoowProvider } from '@doow/track-react-native';
|
|
44
|
+
|
|
45
|
+
export default function App() {
|
|
46
|
+
return (
|
|
47
|
+
<DoowProvider apiKey="dk_your_api_key">
|
|
48
|
+
<Navigation />
|
|
49
|
+
</DoowProvider>
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### Track Events
|
|
55
|
+
|
|
56
|
+
```tsx
|
|
57
|
+
import { useTrackEvent } from '@doow/track-react-native';
|
|
58
|
+
|
|
59
|
+
function FeatureButton() {
|
|
60
|
+
const track = useTrackEvent();
|
|
61
|
+
|
|
62
|
+
const handlePress = () => {
|
|
63
|
+
track({
|
|
64
|
+
metric: 'feature_usage',
|
|
65
|
+
quantity: 1,
|
|
66
|
+
licenseId: 'lic_abc123',
|
|
67
|
+
attribution: { feature: 'export' },
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
return <Button onPress={handlePress} title="Export" />;
|
|
72
|
+
}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Track Screen Views
|
|
76
|
+
|
|
77
|
+
```tsx
|
|
78
|
+
import { useTrackOnFocus } from '@doow/track-react-native';
|
|
79
|
+
import { useNavigation } from '@react-navigation/native';
|
|
80
|
+
|
|
81
|
+
function DashboardScreen() {
|
|
82
|
+
const navigation = useNavigation();
|
|
83
|
+
|
|
84
|
+
useTrackOnFocus(navigation, {
|
|
85
|
+
metric: 'screen_view',
|
|
86
|
+
quantity: 1,
|
|
87
|
+
licenseId: 'lic_abc123',
|
|
88
|
+
attribution: { screen: 'dashboard' },
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
return <View>...</View>;
|
|
92
|
+
}
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Track on Mount
|
|
96
|
+
|
|
97
|
+
```tsx
|
|
98
|
+
import { useTrackOnMount } from '@doow/track-react-native';
|
|
99
|
+
|
|
100
|
+
function OnboardingComplete() {
|
|
101
|
+
useTrackOnMount({
|
|
102
|
+
metric: 'onboarding_complete',
|
|
103
|
+
quantity: 1,
|
|
104
|
+
licenseId: 'lic_abc123',
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return <Text>Welcome!</Text>;
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
---
|
|
112
|
+
|
|
113
|
+
## Configuration
|
|
114
|
+
|
|
115
|
+
```tsx
|
|
116
|
+
<DoowProvider
|
|
117
|
+
apiKey="dk_your_api_key"
|
|
118
|
+
options={{
|
|
119
|
+
endpoint: 'https://api.doow.co',
|
|
120
|
+
enabled: true,
|
|
121
|
+
debug: __DEV__,
|
|
122
|
+
flushAt: 20,
|
|
123
|
+
flushIntervalMs: 10000,
|
|
124
|
+
maxQueueSize: 10000,
|
|
125
|
+
timeoutMs: 10000,
|
|
126
|
+
retryCount: 3,
|
|
127
|
+
persistQueue: true,
|
|
128
|
+
attribution: { app: 'my-mobile-app', platform: Platform.OS },
|
|
129
|
+
onError: (e) => console.error('Doow error:', e),
|
|
130
|
+
}}
|
|
131
|
+
>
|
|
132
|
+
<App />
|
|
133
|
+
</DoowProvider>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
---
|
|
137
|
+
|
|
138
|
+
## Hooks
|
|
139
|
+
|
|
140
|
+
| Hook | Description |
|
|
141
|
+
|------|-------------|
|
|
142
|
+
| `useDoow()` | Full context: `{ track, flush, isEnabled }` |
|
|
143
|
+
| `useTrackEvent()` | Just the `track` function |
|
|
144
|
+
| `useTrackOnMount(event)` | Track once on component mount |
|
|
145
|
+
| `useTrackOnFocus(navigation, event)` | Track on React Navigation focus |
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
## Manual Tracker (No Provider)
|
|
150
|
+
|
|
151
|
+
```tsx
|
|
152
|
+
import { Tracker } from '@doow/track-react-native';
|
|
153
|
+
|
|
154
|
+
const tracker = new Tracker('dk_your_api_key', { debug: true });
|
|
155
|
+
await tracker.init();
|
|
156
|
+
|
|
157
|
+
tracker.track({
|
|
158
|
+
metric: 'api_calls',
|
|
159
|
+
quantity: 1,
|
|
160
|
+
licenseId: 'lic_abc123',
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
// On app shutdown
|
|
164
|
+
await tracker.destroy();
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
## License
|
|
170
|
+
|
|
171
|
+
MIT
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
interface TrackEvent {
|
|
2
|
+
metric: string;
|
|
3
|
+
quantity: number;
|
|
4
|
+
licenseId: string;
|
|
5
|
+
unit?: string;
|
|
6
|
+
attribution?: Record<string, unknown>;
|
|
7
|
+
timestamp?: string;
|
|
8
|
+
}
|
|
9
|
+
interface TrackerOptions {
|
|
10
|
+
endpoint?: string;
|
|
11
|
+
enabled?: boolean;
|
|
12
|
+
debug?: boolean;
|
|
13
|
+
flushAt?: number;
|
|
14
|
+
flushIntervalMs?: number;
|
|
15
|
+
maxQueueSize?: number;
|
|
16
|
+
timeoutMs?: number;
|
|
17
|
+
retryCount?: number;
|
|
18
|
+
persistQueue?: boolean;
|
|
19
|
+
attribution?: Record<string, unknown>;
|
|
20
|
+
onError?: (error: Error) => void;
|
|
21
|
+
}
|
|
22
|
+
interface DoowContextValue {
|
|
23
|
+
track: (event: TrackEvent) => void;
|
|
24
|
+
flush: () => Promise<void>;
|
|
25
|
+
isEnabled: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface DoowProviderProps {
|
|
28
|
+
apiKey: string;
|
|
29
|
+
options?: TrackerOptions;
|
|
30
|
+
children: React.ReactNode;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
declare class Tracker {
|
|
34
|
+
private apiKey;
|
|
35
|
+
private options;
|
|
36
|
+
private queue;
|
|
37
|
+
private flushTimer;
|
|
38
|
+
private shutdown;
|
|
39
|
+
private appStateSubscription;
|
|
40
|
+
constructor(apiKey: string, options?: TrackerOptions);
|
|
41
|
+
init(): Promise<void>;
|
|
42
|
+
private loadQueue;
|
|
43
|
+
private persistQueue;
|
|
44
|
+
private startFlushTimer;
|
|
45
|
+
private setupAppStateListener;
|
|
46
|
+
private log;
|
|
47
|
+
track(event: TrackEvent): void;
|
|
48
|
+
flush(): Promise<void>;
|
|
49
|
+
private sendWithRetry;
|
|
50
|
+
private sleep;
|
|
51
|
+
destroy(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare function DoowProvider({ apiKey, options, children }: DoowProviderProps): JSX.Element;
|
|
55
|
+
declare function useDoow(): DoowContextValue;
|
|
56
|
+
declare function useTrackEvent(): (event: TrackEvent) => void;
|
|
57
|
+
declare function useTrackOnMount(event: TrackEvent): void;
|
|
58
|
+
declare function useTrackOnFocus(navigation: {
|
|
59
|
+
addListener: (event: string, callback: () => void) => () => void;
|
|
60
|
+
}, event: TrackEvent): void;
|
|
61
|
+
|
|
62
|
+
export { type DoowContextValue, DoowProvider, type DoowProviderProps, type TrackEvent, Tracker, type TrackerOptions, useDoow, useTrackEvent, useTrackOnFocus, useTrackOnMount };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
interface TrackEvent {
|
|
2
|
+
metric: string;
|
|
3
|
+
quantity: number;
|
|
4
|
+
licenseId: string;
|
|
5
|
+
unit?: string;
|
|
6
|
+
attribution?: Record<string, unknown>;
|
|
7
|
+
timestamp?: string;
|
|
8
|
+
}
|
|
9
|
+
interface TrackerOptions {
|
|
10
|
+
endpoint?: string;
|
|
11
|
+
enabled?: boolean;
|
|
12
|
+
debug?: boolean;
|
|
13
|
+
flushAt?: number;
|
|
14
|
+
flushIntervalMs?: number;
|
|
15
|
+
maxQueueSize?: number;
|
|
16
|
+
timeoutMs?: number;
|
|
17
|
+
retryCount?: number;
|
|
18
|
+
persistQueue?: boolean;
|
|
19
|
+
attribution?: Record<string, unknown>;
|
|
20
|
+
onError?: (error: Error) => void;
|
|
21
|
+
}
|
|
22
|
+
interface DoowContextValue {
|
|
23
|
+
track: (event: TrackEvent) => void;
|
|
24
|
+
flush: () => Promise<void>;
|
|
25
|
+
isEnabled: boolean;
|
|
26
|
+
}
|
|
27
|
+
interface DoowProviderProps {
|
|
28
|
+
apiKey: string;
|
|
29
|
+
options?: TrackerOptions;
|
|
30
|
+
children: React.ReactNode;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
declare class Tracker {
|
|
34
|
+
private apiKey;
|
|
35
|
+
private options;
|
|
36
|
+
private queue;
|
|
37
|
+
private flushTimer;
|
|
38
|
+
private shutdown;
|
|
39
|
+
private appStateSubscription;
|
|
40
|
+
constructor(apiKey: string, options?: TrackerOptions);
|
|
41
|
+
init(): Promise<void>;
|
|
42
|
+
private loadQueue;
|
|
43
|
+
private persistQueue;
|
|
44
|
+
private startFlushTimer;
|
|
45
|
+
private setupAppStateListener;
|
|
46
|
+
private log;
|
|
47
|
+
track(event: TrackEvent): void;
|
|
48
|
+
flush(): Promise<void>;
|
|
49
|
+
private sendWithRetry;
|
|
50
|
+
private sleep;
|
|
51
|
+
destroy(): Promise<void>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
declare function DoowProvider({ apiKey, options, children }: DoowProviderProps): JSX.Element;
|
|
55
|
+
declare function useDoow(): DoowContextValue;
|
|
56
|
+
declare function useTrackEvent(): (event: TrackEvent) => void;
|
|
57
|
+
declare function useTrackOnMount(event: TrackEvent): void;
|
|
58
|
+
declare function useTrackOnFocus(navigation: {
|
|
59
|
+
addListener: (event: string, callback: () => void) => () => void;
|
|
60
|
+
}, event: TrackEvent): void;
|
|
61
|
+
|
|
62
|
+
export { type DoowContextValue, DoowProvider, type DoowProviderProps, type TrackEvent, Tracker, type TrackerOptions, useDoow, useTrackEvent, useTrackOnFocus, useTrackOnMount };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __export = (target, all) => {
|
|
9
|
+
for (var name in all)
|
|
10
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
29
|
+
|
|
30
|
+
// src/index.ts
|
|
31
|
+
var index_exports = {};
|
|
32
|
+
__export(index_exports, {
|
|
33
|
+
DoowProvider: () => DoowProvider,
|
|
34
|
+
Tracker: () => Tracker,
|
|
35
|
+
useDoow: () => useDoow,
|
|
36
|
+
useTrackEvent: () => useTrackEvent,
|
|
37
|
+
useTrackOnFocus: () => useTrackOnFocus,
|
|
38
|
+
useTrackOnMount: () => useTrackOnMount
|
|
39
|
+
});
|
|
40
|
+
module.exports = __toCommonJS(index_exports);
|
|
41
|
+
|
|
42
|
+
// src/tracker.ts
|
|
43
|
+
var import_react_native = require("react-native");
|
|
44
|
+
var import_async_storage = __toESM(require("@react-native-async-storage/async-storage"));
|
|
45
|
+
function generateUUID() {
|
|
46
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
47
|
+
const r = Math.random() * 16 | 0;
|
|
48
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
49
|
+
return v.toString(16);
|
|
50
|
+
});
|
|
51
|
+
}
|
|
52
|
+
var STORAGE_KEY = "@doow/track/queue";
|
|
53
|
+
var DEFAULT_OPTIONS = {
|
|
54
|
+
endpoint: "https://api.doow.co",
|
|
55
|
+
enabled: true,
|
|
56
|
+
debug: false,
|
|
57
|
+
flushAt: 20,
|
|
58
|
+
flushIntervalMs: 1e4,
|
|
59
|
+
maxQueueSize: 1e4,
|
|
60
|
+
timeoutMs: 1e4,
|
|
61
|
+
retryCount: 3,
|
|
62
|
+
persistQueue: true
|
|
63
|
+
};
|
|
64
|
+
var Tracker = class {
|
|
65
|
+
constructor(apiKey, options = {}) {
|
|
66
|
+
this.queue = [];
|
|
67
|
+
this.flushTimer = null;
|
|
68
|
+
this.shutdown = false;
|
|
69
|
+
this.appStateSubscription = null;
|
|
70
|
+
if (!apiKey.startsWith("dk_")) {
|
|
71
|
+
throw new Error("API key must start with dk_");
|
|
72
|
+
}
|
|
73
|
+
this.apiKey = apiKey;
|
|
74
|
+
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
75
|
+
}
|
|
76
|
+
async init() {
|
|
77
|
+
if (this.options.persistQueue) {
|
|
78
|
+
await this.loadQueue();
|
|
79
|
+
}
|
|
80
|
+
this.startFlushTimer();
|
|
81
|
+
this.setupAppStateListener();
|
|
82
|
+
}
|
|
83
|
+
async loadQueue() {
|
|
84
|
+
try {
|
|
85
|
+
const stored = await import_async_storage.default.getItem(STORAGE_KEY);
|
|
86
|
+
if (stored) {
|
|
87
|
+
this.queue = JSON.parse(stored);
|
|
88
|
+
this.log(`Loaded ${this.queue.length} events from storage`);
|
|
89
|
+
}
|
|
90
|
+
} catch (error) {
|
|
91
|
+
this.log(`Failed to load queue: ${error}`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async persistQueue() {
|
|
95
|
+
if (!this.options.persistQueue) return;
|
|
96
|
+
try {
|
|
97
|
+
await import_async_storage.default.setItem(STORAGE_KEY, JSON.stringify(this.queue));
|
|
98
|
+
} catch (error) {
|
|
99
|
+
this.log(`Failed to persist queue: ${error}`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
startFlushTimer() {
|
|
103
|
+
if (this.flushTimer) clearInterval(this.flushTimer);
|
|
104
|
+
this.flushTimer = setInterval(() => this.flush(), this.options.flushIntervalMs);
|
|
105
|
+
}
|
|
106
|
+
setupAppStateListener() {
|
|
107
|
+
this.appStateSubscription = import_react_native.AppState.addEventListener("change", (state) => {
|
|
108
|
+
if (state === "background" || state === "inactive") {
|
|
109
|
+
this.flush();
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
log(message) {
|
|
114
|
+
if (this.options.debug) {
|
|
115
|
+
console.log(`[DoowTrack] ${message}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
track(event) {
|
|
119
|
+
if (!this.options.enabled || this.shutdown) return;
|
|
120
|
+
if (this.queue.length >= this.options.maxQueueSize) {
|
|
121
|
+
this.log("Queue full, dropping event");
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const enrichedEvent = {
|
|
125
|
+
...event,
|
|
126
|
+
timestamp: event.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
|
|
127
|
+
attribution: { ...event.attribution, ...this.options.attribution }
|
|
128
|
+
};
|
|
129
|
+
this.queue.push(enrichedEvent);
|
|
130
|
+
this.persistQueue();
|
|
131
|
+
this.log(`Queued event: ${event.metric}`);
|
|
132
|
+
if (this.queue.length >= this.options.flushAt) {
|
|
133
|
+
this.flush();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
async flush() {
|
|
137
|
+
if (this.queue.length === 0 || this.shutdown) return;
|
|
138
|
+
const batch = [...this.queue];
|
|
139
|
+
this.queue = [];
|
|
140
|
+
await this.persistQueue();
|
|
141
|
+
this.log(`Flushing ${batch.length} events`);
|
|
142
|
+
try {
|
|
143
|
+
await this.sendWithRetry(batch);
|
|
144
|
+
} catch (error) {
|
|
145
|
+
this.queue = [...batch, ...this.queue];
|
|
146
|
+
await this.persistQueue();
|
|
147
|
+
this.options.onError?.(error);
|
|
148
|
+
this.log(`Flush failed: ${error}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
async sendWithRetry(batch) {
|
|
152
|
+
const payload = JSON.stringify({
|
|
153
|
+
events: batch.map((e) => ({
|
|
154
|
+
event_id: generateUUID(),
|
|
155
|
+
metric: e.metric,
|
|
156
|
+
quantity: e.quantity,
|
|
157
|
+
license_id: e.licenseId,
|
|
158
|
+
unit: e.unit,
|
|
159
|
+
attribution: e.attribution,
|
|
160
|
+
timestamp: e.timestamp
|
|
161
|
+
}))
|
|
162
|
+
});
|
|
163
|
+
for (let attempt = 0; attempt <= this.options.retryCount; attempt++) {
|
|
164
|
+
try {
|
|
165
|
+
const controller = new AbortController();
|
|
166
|
+
const timeout = setTimeout(() => controller.abort(), this.options.timeoutMs);
|
|
167
|
+
const response = await fetch(`${this.options.endpoint}/telemetry/events`, {
|
|
168
|
+
method: "POST",
|
|
169
|
+
headers: {
|
|
170
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
171
|
+
"Content-Type": "application/json"
|
|
172
|
+
},
|
|
173
|
+
body: payload,
|
|
174
|
+
signal: controller.signal
|
|
175
|
+
});
|
|
176
|
+
clearTimeout(timeout);
|
|
177
|
+
if (response.ok) {
|
|
178
|
+
this.log("Batch sent successfully");
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
if (response.status === 429) {
|
|
182
|
+
const retryAfter = response.headers.get("Retry-After");
|
|
183
|
+
const delay = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 100 * Math.pow(2, attempt);
|
|
184
|
+
await this.sleep(delay);
|
|
185
|
+
continue;
|
|
186
|
+
}
|
|
187
|
+
if (response.status >= 500) {
|
|
188
|
+
await this.sleep(100 * Math.pow(2, attempt));
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
|
|
192
|
+
} catch (error) {
|
|
193
|
+
if (attempt === this.options.retryCount) throw error;
|
|
194
|
+
await this.sleep(100 * Math.pow(2, attempt));
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
sleep(ms) {
|
|
199
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
200
|
+
}
|
|
201
|
+
async destroy() {
|
|
202
|
+
this.shutdown = true;
|
|
203
|
+
if (this.flushTimer) clearInterval(this.flushTimer);
|
|
204
|
+
this.appStateSubscription?.remove();
|
|
205
|
+
await this.flush();
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
// src/context.tsx
|
|
210
|
+
var import_react = require("react");
|
|
211
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
212
|
+
var DoowContext = (0, import_react.createContext)(null);
|
|
213
|
+
function DoowProvider({ apiKey, options, children }) {
|
|
214
|
+
const trackerRef = (0, import_react.useRef)(null);
|
|
215
|
+
const [ready, setReady] = (0, import_react.useState)(false);
|
|
216
|
+
(0, import_react.useEffect)(() => {
|
|
217
|
+
const tracker = new Tracker(apiKey, options);
|
|
218
|
+
trackerRef.current = tracker;
|
|
219
|
+
tracker.init().then(() => setReady(true));
|
|
220
|
+
return () => {
|
|
221
|
+
tracker.destroy();
|
|
222
|
+
};
|
|
223
|
+
}, [apiKey]);
|
|
224
|
+
const value = (0, import_react.useMemo)(
|
|
225
|
+
() => ({
|
|
226
|
+
track: (event) => trackerRef.current?.track(event),
|
|
227
|
+
flush: () => trackerRef.current?.flush() ?? Promise.resolve(),
|
|
228
|
+
isEnabled: options?.enabled !== false
|
|
229
|
+
}),
|
|
230
|
+
[options?.enabled]
|
|
231
|
+
);
|
|
232
|
+
if (!ready) return null;
|
|
233
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DoowContext.Provider, { value, children });
|
|
234
|
+
}
|
|
235
|
+
function useDoow() {
|
|
236
|
+
const context = (0, import_react.useContext)(DoowContext);
|
|
237
|
+
if (!context) {
|
|
238
|
+
throw new Error("useDoow must be used within a DoowProvider");
|
|
239
|
+
}
|
|
240
|
+
return context;
|
|
241
|
+
}
|
|
242
|
+
function useTrackEvent() {
|
|
243
|
+
const { track } = useDoow();
|
|
244
|
+
return track;
|
|
245
|
+
}
|
|
246
|
+
function useTrackOnMount(event) {
|
|
247
|
+
const { track } = useDoow();
|
|
248
|
+
const tracked = (0, import_react.useRef)(false);
|
|
249
|
+
(0, import_react.useEffect)(() => {
|
|
250
|
+
if (!tracked.current) {
|
|
251
|
+
track(event);
|
|
252
|
+
tracked.current = true;
|
|
253
|
+
}
|
|
254
|
+
}, []);
|
|
255
|
+
}
|
|
256
|
+
function useTrackOnFocus(navigation, event) {
|
|
257
|
+
const { track } = useDoow();
|
|
258
|
+
(0, import_react.useEffect)(() => {
|
|
259
|
+
const unsubscribe = navigation.addListener("focus", () => {
|
|
260
|
+
track(event);
|
|
261
|
+
});
|
|
262
|
+
return unsubscribe;
|
|
263
|
+
}, [navigation, event, track]);
|
|
264
|
+
}
|
|
265
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
266
|
+
0 && (module.exports = {
|
|
267
|
+
DoowProvider,
|
|
268
|
+
Tracker,
|
|
269
|
+
useDoow,
|
|
270
|
+
useTrackEvent,
|
|
271
|
+
useTrackOnFocus,
|
|
272
|
+
useTrackOnMount
|
|
273
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// src/tracker.ts
|
|
2
|
+
import { AppState } from "react-native";
|
|
3
|
+
import AsyncStorage from "@react-native-async-storage/async-storage";
|
|
4
|
+
function generateUUID() {
|
|
5
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
6
|
+
const r = Math.random() * 16 | 0;
|
|
7
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
8
|
+
return v.toString(16);
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
var STORAGE_KEY = "@doow/track/queue";
|
|
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
|
+
persistQueue: true
|
|
22
|
+
};
|
|
23
|
+
var Tracker = class {
|
|
24
|
+
constructor(apiKey, options = {}) {
|
|
25
|
+
this.queue = [];
|
|
26
|
+
this.flushTimer = null;
|
|
27
|
+
this.shutdown = false;
|
|
28
|
+
this.appStateSubscription = null;
|
|
29
|
+
if (!apiKey.startsWith("dk_")) {
|
|
30
|
+
throw new Error("API key must start with dk_");
|
|
31
|
+
}
|
|
32
|
+
this.apiKey = apiKey;
|
|
33
|
+
this.options = { ...DEFAULT_OPTIONS, ...options };
|
|
34
|
+
}
|
|
35
|
+
async init() {
|
|
36
|
+
if (this.options.persistQueue) {
|
|
37
|
+
await this.loadQueue();
|
|
38
|
+
}
|
|
39
|
+
this.startFlushTimer();
|
|
40
|
+
this.setupAppStateListener();
|
|
41
|
+
}
|
|
42
|
+
async loadQueue() {
|
|
43
|
+
try {
|
|
44
|
+
const stored = await AsyncStorage.getItem(STORAGE_KEY);
|
|
45
|
+
if (stored) {
|
|
46
|
+
this.queue = JSON.parse(stored);
|
|
47
|
+
this.log(`Loaded ${this.queue.length} events from storage`);
|
|
48
|
+
}
|
|
49
|
+
} catch (error) {
|
|
50
|
+
this.log(`Failed to load queue: ${error}`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
async persistQueue() {
|
|
54
|
+
if (!this.options.persistQueue) return;
|
|
55
|
+
try {
|
|
56
|
+
await AsyncStorage.setItem(STORAGE_KEY, JSON.stringify(this.queue));
|
|
57
|
+
} catch (error) {
|
|
58
|
+
this.log(`Failed to persist queue: ${error}`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
startFlushTimer() {
|
|
62
|
+
if (this.flushTimer) clearInterval(this.flushTimer);
|
|
63
|
+
this.flushTimer = setInterval(() => this.flush(), this.options.flushIntervalMs);
|
|
64
|
+
}
|
|
65
|
+
setupAppStateListener() {
|
|
66
|
+
this.appStateSubscription = AppState.addEventListener("change", (state) => {
|
|
67
|
+
if (state === "background" || state === "inactive") {
|
|
68
|
+
this.flush();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
log(message) {
|
|
73
|
+
if (this.options.debug) {
|
|
74
|
+
console.log(`[DoowTrack] ${message}`);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
track(event) {
|
|
78
|
+
if (!this.options.enabled || this.shutdown) return;
|
|
79
|
+
if (this.queue.length >= this.options.maxQueueSize) {
|
|
80
|
+
this.log("Queue full, dropping event");
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
const enrichedEvent = {
|
|
84
|
+
...event,
|
|
85
|
+
timestamp: event.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
|
|
86
|
+
attribution: { ...event.attribution, ...this.options.attribution }
|
|
87
|
+
};
|
|
88
|
+
this.queue.push(enrichedEvent);
|
|
89
|
+
this.persistQueue();
|
|
90
|
+
this.log(`Queued event: ${event.metric}`);
|
|
91
|
+
if (this.queue.length >= this.options.flushAt) {
|
|
92
|
+
this.flush();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
async flush() {
|
|
96
|
+
if (this.queue.length === 0 || this.shutdown) return;
|
|
97
|
+
const batch = [...this.queue];
|
|
98
|
+
this.queue = [];
|
|
99
|
+
await this.persistQueue();
|
|
100
|
+
this.log(`Flushing ${batch.length} events`);
|
|
101
|
+
try {
|
|
102
|
+
await this.sendWithRetry(batch);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
this.queue = [...batch, ...this.queue];
|
|
105
|
+
await this.persistQueue();
|
|
106
|
+
this.options.onError?.(error);
|
|
107
|
+
this.log(`Flush failed: ${error}`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async sendWithRetry(batch) {
|
|
111
|
+
const payload = JSON.stringify({
|
|
112
|
+
events: batch.map((e) => ({
|
|
113
|
+
event_id: generateUUID(),
|
|
114
|
+
metric: e.metric,
|
|
115
|
+
quantity: e.quantity,
|
|
116
|
+
license_id: e.licenseId,
|
|
117
|
+
unit: e.unit,
|
|
118
|
+
attribution: e.attribution,
|
|
119
|
+
timestamp: e.timestamp
|
|
120
|
+
}))
|
|
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
|
+
"Authorization": `Bearer ${this.apiKey}`,
|
|
130
|
+
"Content-Type": "application/json"
|
|
131
|
+
},
|
|
132
|
+
body: payload,
|
|
133
|
+
signal: controller.signal
|
|
134
|
+
});
|
|
135
|
+
clearTimeout(timeout);
|
|
136
|
+
if (response.ok) {
|
|
137
|
+
this.log("Batch sent successfully");
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (response.status === 429) {
|
|
141
|
+
const retryAfter = response.headers.get("Retry-After");
|
|
142
|
+
const delay = retryAfter ? parseInt(retryAfter, 10) * 1e3 : 100 * Math.pow(2, attempt);
|
|
143
|
+
await this.sleep(delay);
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (response.status >= 500) {
|
|
147
|
+
await this.sleep(100 * Math.pow(2, attempt));
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
throw new Error(`HTTP ${response.status}: ${await response.text()}`);
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (attempt === this.options.retryCount) throw error;
|
|
153
|
+
await this.sleep(100 * Math.pow(2, attempt));
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
sleep(ms) {
|
|
158
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
159
|
+
}
|
|
160
|
+
async destroy() {
|
|
161
|
+
this.shutdown = true;
|
|
162
|
+
if (this.flushTimer) clearInterval(this.flushTimer);
|
|
163
|
+
this.appStateSubscription?.remove();
|
|
164
|
+
await this.flush();
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
// src/context.tsx
|
|
169
|
+
import { createContext, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
170
|
+
import { jsx } from "react/jsx-runtime";
|
|
171
|
+
var DoowContext = createContext(null);
|
|
172
|
+
function DoowProvider({ apiKey, options, children }) {
|
|
173
|
+
const trackerRef = useRef(null);
|
|
174
|
+
const [ready, setReady] = useState(false);
|
|
175
|
+
useEffect(() => {
|
|
176
|
+
const tracker = new Tracker(apiKey, options);
|
|
177
|
+
trackerRef.current = tracker;
|
|
178
|
+
tracker.init().then(() => setReady(true));
|
|
179
|
+
return () => {
|
|
180
|
+
tracker.destroy();
|
|
181
|
+
};
|
|
182
|
+
}, [apiKey]);
|
|
183
|
+
const value = useMemo(
|
|
184
|
+
() => ({
|
|
185
|
+
track: (event) => trackerRef.current?.track(event),
|
|
186
|
+
flush: () => trackerRef.current?.flush() ?? Promise.resolve(),
|
|
187
|
+
isEnabled: options?.enabled !== false
|
|
188
|
+
}),
|
|
189
|
+
[options?.enabled]
|
|
190
|
+
);
|
|
191
|
+
if (!ready) return null;
|
|
192
|
+
return /* @__PURE__ */ jsx(DoowContext.Provider, { value, children });
|
|
193
|
+
}
|
|
194
|
+
function useDoow() {
|
|
195
|
+
const context = useContext(DoowContext);
|
|
196
|
+
if (!context) {
|
|
197
|
+
throw new Error("useDoow must be used within a DoowProvider");
|
|
198
|
+
}
|
|
199
|
+
return context;
|
|
200
|
+
}
|
|
201
|
+
function useTrackEvent() {
|
|
202
|
+
const { track } = useDoow();
|
|
203
|
+
return track;
|
|
204
|
+
}
|
|
205
|
+
function useTrackOnMount(event) {
|
|
206
|
+
const { track } = useDoow();
|
|
207
|
+
const tracked = useRef(false);
|
|
208
|
+
useEffect(() => {
|
|
209
|
+
if (!tracked.current) {
|
|
210
|
+
track(event);
|
|
211
|
+
tracked.current = true;
|
|
212
|
+
}
|
|
213
|
+
}, []);
|
|
214
|
+
}
|
|
215
|
+
function useTrackOnFocus(navigation, event) {
|
|
216
|
+
const { track } = useDoow();
|
|
217
|
+
useEffect(() => {
|
|
218
|
+
const unsubscribe = navigation.addListener("focus", () => {
|
|
219
|
+
track(event);
|
|
220
|
+
});
|
|
221
|
+
return unsubscribe;
|
|
222
|
+
}, [navigation, event, track]);
|
|
223
|
+
}
|
|
224
|
+
export {
|
|
225
|
+
DoowProvider,
|
|
226
|
+
Tracker,
|
|
227
|
+
useDoow,
|
|
228
|
+
useTrackEvent,
|
|
229
|
+
useTrackOnFocus,
|
|
230
|
+
useTrackOnMount
|
|
231
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@doow/track-react-native",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Official React Native 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": "jest"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"@react-native-async-storage/async-storage": ">=1.0.0",
|
|
26
|
+
"react": ">=17.0.0",
|
|
27
|
+
"react-native": ">=0.70.0"
|
|
28
|
+
},
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"@react-native-async-storage/async-storage": "^1.21.0",
|
|
31
|
+
"@types/react": "^18.2.0",
|
|
32
|
+
"@types/react-native": "^0.72.0",
|
|
33
|
+
"react": "^18.2.0",
|
|
34
|
+
"react-native": "^0.73.0",
|
|
35
|
+
"tsup": "^8.0.0",
|
|
36
|
+
"typescript": "^5.3.0"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"doow",
|
|
40
|
+
"telemetry",
|
|
41
|
+
"usage",
|
|
42
|
+
"billing",
|
|
43
|
+
"react-native",
|
|
44
|
+
"expo",
|
|
45
|
+
"mobile"
|
|
46
|
+
],
|
|
47
|
+
"author": "Doow",
|
|
48
|
+
"license": "MIT",
|
|
49
|
+
"repository": {
|
|
50
|
+
"type": "git",
|
|
51
|
+
"url": "https://github.com/Doow-Dev/doow-track-react-native.git"
|
|
52
|
+
}
|
|
53
|
+
}
|