@stillkinetic/rn-sdk 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/README.md +72 -0
- package/dist/index.d.mts +64 -0
- package/dist/index.d.ts +64 -0
- package/dist/index.js +413 -0
- package/dist/index.mjs +376 -0
- package/package.json +36 -0
package/README.md
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# @stillkinetic/rn-sdk
|
|
2
|
+
|
|
3
|
+
Behavioral tracking + threshold-triggered Stripe billing for React Native apps.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @stillkinetic/rn-sdk @stripe/stripe-react-native
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
`@stripe/stripe-react-native` is a peer dependency. Follow its own native linking / pod install steps for iOS.
|
|
12
|
+
|
|
13
|
+
Wrap your app root in Stripe's provider (required by `@stripe/stripe-react-native`):
|
|
14
|
+
|
|
15
|
+
```tsx
|
|
16
|
+
import { StripeProvider } from '@stripe/stripe-react-native';
|
|
17
|
+
|
|
18
|
+
<StripeProvider publishableKey="pk_live_...">
|
|
19
|
+
<App />
|
|
20
|
+
</StripeProvider>
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Usage
|
|
24
|
+
|
|
25
|
+
```tsx
|
|
26
|
+
import { useStillKinetic, CardBindScreen } from '@stillkinetic/rn-sdk';
|
|
27
|
+
import { ScrollView, TextInput, Pressable, Text } from 'react-native';
|
|
28
|
+
|
|
29
|
+
const config = {
|
|
30
|
+
appId: 'app_123',
|
|
31
|
+
apiKey: 'pk_app_abc',
|
|
32
|
+
apiBaseUrl: 'https://api.yourplatform.com',
|
|
33
|
+
stripePublishableKey: 'pk_live_...',
|
|
34
|
+
endUserId: currentUser.id,
|
|
35
|
+
trackedMetrics: ['stay_duration', 'type_speed'] as const,
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
function HomeScreen() {
|
|
39
|
+
const { onScroll, onChangeText, onPressIn } = useTrackPay(config, 'HomeScreen');
|
|
40
|
+
|
|
41
|
+
return (
|
|
42
|
+
<ScrollView onScroll={onScroll} scrollEventThrottle={16}>
|
|
43
|
+
<TextInput onChangeText={onChangeText} placeholder="Type here" />
|
|
44
|
+
<Pressable onPressIn={onPressIn}>
|
|
45
|
+
<Text>Tap me</Text>
|
|
46
|
+
</Pressable>
|
|
47
|
+
</ScrollView>
|
|
48
|
+
);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// One-time screen, shown once per end user before any charge can fire:
|
|
52
|
+
function BillingSetupScreen({ navigation }) {
|
|
53
|
+
return (
|
|
54
|
+
<CardBindScreen
|
|
55
|
+
config={config}
|
|
56
|
+
defaultCap={{ amountCents: 5000, period: 'monthly' }}
|
|
57
|
+
onComplete={(result) => {
|
|
58
|
+
if (result.success) navigation.goBack();
|
|
59
|
+
else console.error(result.error);
|
|
60
|
+
}}
|
|
61
|
+
/>
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
## Screen focus vs mount/unmount
|
|
67
|
+
|
|
68
|
+
`useStayTracker` (used internally by `useTrackPay`) starts/stops its timer on component mount/unmount and pauses on app background. If you use React Navigation and want stay-duration to reset per screen *focus* (not just mount), call `useTrackPay` inside a screen component that React Navigation actually unmounts on blur (e.g. within a stack navigator with `unmountOnBlur`), or wrap it in your own `useFocusEffect` that calls `tp.start()`/`stop()`-equivalent logic — the hook is intentionally simple so it composes with whatever navigation library you use.
|
|
69
|
+
|
|
70
|
+
## Notes
|
|
71
|
+
|
|
72
|
+
Same architecture as the web SDK: this package only reports metrics and handles the one-time card bind. All threshold evaluation and Stripe charges happen server-side.
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as react_native from 'react-native';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
|
|
4
|
+
type Metric = 'press_count' | 'scroll_length' | 'scroll_speed' | 'type_speed' | 'stay_duration' | 'swipe_count' | 'pinch_zoom_count' | 'long_press_count' | 'form_submit_count' | 'tab_switch_count' | 'search_count' | 'video_play_count' | 'video_watch_duration' | 'file_download_count' | 'share_count' | 'mouse_distance';
|
|
5
|
+
declare const ALL_METRICS: Metric[];
|
|
6
|
+
interface TrackEvent {
|
|
7
|
+
appId: string;
|
|
8
|
+
endUserId: string;
|
|
9
|
+
pageId: string;
|
|
10
|
+
metric: Metric;
|
|
11
|
+
value: number;
|
|
12
|
+
timestamp: number;
|
|
13
|
+
}
|
|
14
|
+
interface StillKineticConfig {
|
|
15
|
+
appId: string;
|
|
16
|
+
apiKey: string;
|
|
17
|
+
apiBaseUrl: string;
|
|
18
|
+
stripePublishableKey: string;
|
|
19
|
+
endUserId: string;
|
|
20
|
+
trackedMetrics: Metric[];
|
|
21
|
+
batchIntervalMs?: number;
|
|
22
|
+
}
|
|
23
|
+
interface SpendingCapInput {
|
|
24
|
+
amountCents: number;
|
|
25
|
+
period: 'weekly' | 'monthly';
|
|
26
|
+
}
|
|
27
|
+
interface CardBindResult {
|
|
28
|
+
success: boolean;
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface Props {
|
|
33
|
+
config: StillKineticConfig;
|
|
34
|
+
defaultCap: SpendingCapInput;
|
|
35
|
+
onComplete: (result: CardBindResult) => void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Drop-in screen/component for the ONE-TIME card bind + spending cap flow.
|
|
39
|
+
* Render this once (e.g. on signup, or the first time a threshold is
|
|
40
|
+
* approached) — never per-transaction. After this succeeds, all future
|
|
41
|
+
* threshold charges fire server-side with no further screen.
|
|
42
|
+
*/
|
|
43
|
+
declare function CardBindScreen({ config, defaultCap, onComplete }: Props): React.JSX.Element;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Primary hook for React Native screens. Give it the config, the current
|
|
47
|
+
* screen's pageId, and which metrics this app selected to track — it wires
|
|
48
|
+
* up whichever handlers are relevant and returns them for you to spread
|
|
49
|
+
* onto your components.
|
|
50
|
+
*
|
|
51
|
+
* const { onScroll, onChangeText, onPressIn } = useStillKinetic(config, 'HomeScreen');
|
|
52
|
+
*
|
|
53
|
+
* <ScrollView onScroll={onScroll} scrollEventThrottle={16}>
|
|
54
|
+
* <TextInput onChangeText={onChangeText} />
|
|
55
|
+
* <Pressable onPressIn={onPressIn} />
|
|
56
|
+
* </ScrollView>
|
|
57
|
+
*/
|
|
58
|
+
declare function useStillKinetic(config: StillKineticConfig, pageId: string): {
|
|
59
|
+
onPressIn: (() => void) | undefined;
|
|
60
|
+
onScroll: ((e: react_native.NativeSyntheticEvent<react_native.NativeScrollEvent>) => void) | undefined;
|
|
61
|
+
onChangeText: ((text: string) => void) | undefined;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export { ALL_METRICS, type CardBindResult, CardBindScreen, type Metric, type SpendingCapInput, type StillKineticConfig, type TrackEvent, useStillKinetic };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import * as react_native from 'react-native';
|
|
2
|
+
import React from 'react';
|
|
3
|
+
|
|
4
|
+
type Metric = 'press_count' | 'scroll_length' | 'scroll_speed' | 'type_speed' | 'stay_duration' | 'swipe_count' | 'pinch_zoom_count' | 'long_press_count' | 'form_submit_count' | 'tab_switch_count' | 'search_count' | 'video_play_count' | 'video_watch_duration' | 'file_download_count' | 'share_count' | 'mouse_distance';
|
|
5
|
+
declare const ALL_METRICS: Metric[];
|
|
6
|
+
interface TrackEvent {
|
|
7
|
+
appId: string;
|
|
8
|
+
endUserId: string;
|
|
9
|
+
pageId: string;
|
|
10
|
+
metric: Metric;
|
|
11
|
+
value: number;
|
|
12
|
+
timestamp: number;
|
|
13
|
+
}
|
|
14
|
+
interface StillKineticConfig {
|
|
15
|
+
appId: string;
|
|
16
|
+
apiKey: string;
|
|
17
|
+
apiBaseUrl: string;
|
|
18
|
+
stripePublishableKey: string;
|
|
19
|
+
endUserId: string;
|
|
20
|
+
trackedMetrics: Metric[];
|
|
21
|
+
batchIntervalMs?: number;
|
|
22
|
+
}
|
|
23
|
+
interface SpendingCapInput {
|
|
24
|
+
amountCents: number;
|
|
25
|
+
period: 'weekly' | 'monthly';
|
|
26
|
+
}
|
|
27
|
+
interface CardBindResult {
|
|
28
|
+
success: boolean;
|
|
29
|
+
error?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
interface Props {
|
|
33
|
+
config: StillKineticConfig;
|
|
34
|
+
defaultCap: SpendingCapInput;
|
|
35
|
+
onComplete: (result: CardBindResult) => void;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Drop-in screen/component for the ONE-TIME card bind + spending cap flow.
|
|
39
|
+
* Render this once (e.g. on signup, or the first time a threshold is
|
|
40
|
+
* approached) — never per-transaction. After this succeeds, all future
|
|
41
|
+
* threshold charges fire server-side with no further screen.
|
|
42
|
+
*/
|
|
43
|
+
declare function CardBindScreen({ config, defaultCap, onComplete }: Props): React.JSX.Element;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Primary hook for React Native screens. Give it the config, the current
|
|
47
|
+
* screen's pageId, and which metrics this app selected to track — it wires
|
|
48
|
+
* up whichever handlers are relevant and returns them for you to spread
|
|
49
|
+
* onto your components.
|
|
50
|
+
*
|
|
51
|
+
* const { onScroll, onChangeText, onPressIn } = useStillKinetic(config, 'HomeScreen');
|
|
52
|
+
*
|
|
53
|
+
* <ScrollView onScroll={onScroll} scrollEventThrottle={16}>
|
|
54
|
+
* <TextInput onChangeText={onChangeText} />
|
|
55
|
+
* <Pressable onPressIn={onPressIn} />
|
|
56
|
+
* </ScrollView>
|
|
57
|
+
*/
|
|
58
|
+
declare function useStillKinetic(config: StillKineticConfig, pageId: string): {
|
|
59
|
+
onPressIn: (() => void) | undefined;
|
|
60
|
+
onScroll: ((e: react_native.NativeSyntheticEvent<react_native.NativeScrollEvent>) => void) | undefined;
|
|
61
|
+
onChangeText: ((text: string) => void) | undefined;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
export { ALL_METRICS, type CardBindResult, CardBindScreen, type Metric, type SpendingCapInput, type StillKineticConfig, type TrackEvent, useStillKinetic };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
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
|
+
ALL_METRICS: () => ALL_METRICS,
|
|
34
|
+
CardBindScreen: () => CardBindScreen,
|
|
35
|
+
useStillKinetic: () => useStillKinetic
|
|
36
|
+
});
|
|
37
|
+
module.exports = __toCommonJS(index_exports);
|
|
38
|
+
var import_react6 = require("react");
|
|
39
|
+
|
|
40
|
+
// src/transport/batchSender.ts
|
|
41
|
+
var import_react_native = require("react-native");
|
|
42
|
+
var BatchSender = class {
|
|
43
|
+
constructor(config) {
|
|
44
|
+
this.config = config;
|
|
45
|
+
this.buffer = [];
|
|
46
|
+
this.timer = null;
|
|
47
|
+
this.maxBufferSize = 200;
|
|
48
|
+
this.appStateSub = null;
|
|
49
|
+
this.endpoint = `${config.apiBaseUrl.replace(/\/$/, "")}/api/events`;
|
|
50
|
+
}
|
|
51
|
+
start() {
|
|
52
|
+
const intervalMs = this.config.batchIntervalMs ?? 5e3;
|
|
53
|
+
this.timer = setInterval(() => this.flush(), intervalMs);
|
|
54
|
+
const handleAppStateChange = (state) => {
|
|
55
|
+
if (state === "background" || state === "inactive") this.flush();
|
|
56
|
+
};
|
|
57
|
+
this.appStateSub = import_react_native.AppState.addEventListener("change", handleAppStateChange);
|
|
58
|
+
}
|
|
59
|
+
stop() {
|
|
60
|
+
if (this.timer) clearInterval(this.timer);
|
|
61
|
+
this.appStateSub?.remove();
|
|
62
|
+
this.flush();
|
|
63
|
+
}
|
|
64
|
+
enqueue(event) {
|
|
65
|
+
this.buffer.push(event);
|
|
66
|
+
if (this.buffer.length >= this.maxBufferSize) this.flush();
|
|
67
|
+
}
|
|
68
|
+
flush() {
|
|
69
|
+
if (this.buffer.length === 0) return;
|
|
70
|
+
const events = this.buffer;
|
|
71
|
+
this.buffer = [];
|
|
72
|
+
this.sendWithRetry(events, 3);
|
|
73
|
+
}
|
|
74
|
+
sendWithRetry(events, retriesLeft) {
|
|
75
|
+
fetch(this.endpoint, {
|
|
76
|
+
method: "POST",
|
|
77
|
+
headers: {
|
|
78
|
+
"Content-Type": "application/json",
|
|
79
|
+
"X-Api-Key": this.config.apiKey
|
|
80
|
+
},
|
|
81
|
+
body: JSON.stringify({ appId: this.config.appId, events })
|
|
82
|
+
}).catch(() => {
|
|
83
|
+
if (retriesLeft > 0) {
|
|
84
|
+
const delay = Math.pow(2, 3 - retriesLeft) * 1e3;
|
|
85
|
+
setTimeout(() => this.sendWithRetry(events, retriesLeft - 1), delay);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
// src/trackers/pressTracker.ts
|
|
92
|
+
var import_react = require("react");
|
|
93
|
+
function usePressTracker(config, sender, pageId) {
|
|
94
|
+
const onPressIn = (0, import_react.useCallback)(() => {
|
|
95
|
+
sender.enqueue({
|
|
96
|
+
appId: config.appId,
|
|
97
|
+
endUserId: config.endUserId,
|
|
98
|
+
pageId,
|
|
99
|
+
metric: "press_count",
|
|
100
|
+
value: 1,
|
|
101
|
+
timestamp: Date.now()
|
|
102
|
+
});
|
|
103
|
+
}, [config, sender, pageId]);
|
|
104
|
+
return { onPressIn };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// src/trackers/scrollTracker.ts
|
|
108
|
+
var import_react2 = require("react");
|
|
109
|
+
function useScrollTracker(config, sender, pageId, enabledMetrics) {
|
|
110
|
+
const lastY = (0, import_react2.useRef)(null);
|
|
111
|
+
const lastTimestamp = (0, import_react2.useRef)(Date.now());
|
|
112
|
+
const wantsLength = enabledMetrics.includes("scroll_length");
|
|
113
|
+
const wantsSpeed = enabledMetrics.includes("scroll_speed");
|
|
114
|
+
const onScroll = (0, import_react2.useCallback)(
|
|
115
|
+
(e) => {
|
|
116
|
+
if (!wantsLength && !wantsSpeed) return;
|
|
117
|
+
const currentY = e.nativeEvent.contentOffset.y;
|
|
118
|
+
const now = Date.now();
|
|
119
|
+
if (lastY.current === null) {
|
|
120
|
+
lastY.current = currentY;
|
|
121
|
+
lastTimestamp.current = now;
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const deltaY = Math.abs(currentY - lastY.current);
|
|
125
|
+
const deltaT = Math.max(now - lastTimestamp.current, 1);
|
|
126
|
+
if (deltaY > 0) {
|
|
127
|
+
if (wantsLength) {
|
|
128
|
+
sender.enqueue({
|
|
129
|
+
appId: config.appId,
|
|
130
|
+
endUserId: config.endUserId,
|
|
131
|
+
pageId,
|
|
132
|
+
metric: "scroll_length",
|
|
133
|
+
value: deltaY,
|
|
134
|
+
timestamp: now
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (wantsSpeed) {
|
|
138
|
+
sender.enqueue({
|
|
139
|
+
appId: config.appId,
|
|
140
|
+
endUserId: config.endUserId,
|
|
141
|
+
pageId,
|
|
142
|
+
metric: "scroll_speed",
|
|
143
|
+
value: deltaY / deltaT,
|
|
144
|
+
timestamp: now
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
lastY.current = currentY;
|
|
149
|
+
lastTimestamp.current = now;
|
|
150
|
+
},
|
|
151
|
+
[config, sender, pageId, wantsLength, wantsSpeed]
|
|
152
|
+
);
|
|
153
|
+
return { onScroll };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// src/trackers/typeTracker.ts
|
|
157
|
+
var import_react3 = require("react");
|
|
158
|
+
function useTypeTracker(config, sender, pageId) {
|
|
159
|
+
const timestamps = (0, import_react3.useRef)([]);
|
|
160
|
+
const lastLength = (0, import_react3.useRef)(0);
|
|
161
|
+
const windowMs = 1e4;
|
|
162
|
+
const onChangeText = (0, import_react3.useCallback)(
|
|
163
|
+
(text) => {
|
|
164
|
+
const now = Date.now();
|
|
165
|
+
const lengthDelta = text.length - lastLength.current;
|
|
166
|
+
lastLength.current = text.length;
|
|
167
|
+
if (lengthDelta === 0) return;
|
|
168
|
+
timestamps.current.push(now);
|
|
169
|
+
while (timestamps.current.length > 0 && now - timestamps.current[0] > windowMs) {
|
|
170
|
+
timestamps.current.shift();
|
|
171
|
+
}
|
|
172
|
+
if (timestamps.current.length < 2) return;
|
|
173
|
+
const elapsedMinutes = (now - timestamps.current[0]) / 6e4;
|
|
174
|
+
const charsPerMinute = elapsedMinutes > 0 ? timestamps.current.length / elapsedMinutes : 0;
|
|
175
|
+
sender.enqueue({
|
|
176
|
+
appId: config.appId,
|
|
177
|
+
endUserId: config.endUserId,
|
|
178
|
+
pageId,
|
|
179
|
+
metric: "type_speed",
|
|
180
|
+
value: Math.round(charsPerMinute),
|
|
181
|
+
timestamp: now
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
[config, sender, pageId]
|
|
185
|
+
);
|
|
186
|
+
return { onChangeText };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// src/trackers/stayTracker.ts
|
|
190
|
+
var import_react4 = require("react");
|
|
191
|
+
var import_react_native2 = require("react-native");
|
|
192
|
+
function useStayTracker(config, sender, pageId) {
|
|
193
|
+
const activeMsRef = (0, import_react4.useRef)(0);
|
|
194
|
+
const segmentStart = (0, import_react4.useRef)(Date.now());
|
|
195
|
+
const intervalRef = (0, import_react4.useRef)(null);
|
|
196
|
+
(0, import_react4.useEffect)(() => {
|
|
197
|
+
const closeSegment = () => {
|
|
198
|
+
if (segmentStart.current !== null) {
|
|
199
|
+
activeMsRef.current += Date.now() - segmentStart.current;
|
|
200
|
+
segmentStart.current = null;
|
|
201
|
+
}
|
|
202
|
+
};
|
|
203
|
+
const openSegment = () => {
|
|
204
|
+
if (segmentStart.current === null) segmentStart.current = Date.now();
|
|
205
|
+
};
|
|
206
|
+
const report = () => {
|
|
207
|
+
closeSegment();
|
|
208
|
+
const elapsed = activeMsRef.current;
|
|
209
|
+
activeMsRef.current = 0;
|
|
210
|
+
if (elapsed > 0) {
|
|
211
|
+
sender.enqueue({
|
|
212
|
+
appId: config.appId,
|
|
213
|
+
endUserId: config.endUserId,
|
|
214
|
+
pageId,
|
|
215
|
+
metric: "stay_duration",
|
|
216
|
+
value: elapsed,
|
|
217
|
+
timestamp: Date.now()
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
openSegment();
|
|
221
|
+
};
|
|
222
|
+
const handleAppStateChange = (state) => {
|
|
223
|
+
if (state === "active") openSegment();
|
|
224
|
+
else closeSegment();
|
|
225
|
+
};
|
|
226
|
+
const sub = import_react_native2.AppState.addEventListener("change", handleAppStateChange);
|
|
227
|
+
intervalRef.current = setInterval(report, 5e3);
|
|
228
|
+
return () => {
|
|
229
|
+
closeSegment();
|
|
230
|
+
const remaining = activeMsRef.current;
|
|
231
|
+
if (remaining > 0) {
|
|
232
|
+
sender.enqueue({
|
|
233
|
+
appId: config.appId,
|
|
234
|
+
endUserId: config.endUserId,
|
|
235
|
+
pageId,
|
|
236
|
+
metric: "stay_duration",
|
|
237
|
+
value: remaining,
|
|
238
|
+
timestamp: Date.now()
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
sub.remove();
|
|
242
|
+
if (intervalRef.current) clearInterval(intervalRef.current);
|
|
243
|
+
};
|
|
244
|
+
}, [config, sender, pageId]);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// src/core/types.ts
|
|
248
|
+
var ALL_METRICS = [
|
|
249
|
+
"press_count",
|
|
250
|
+
"scroll_length",
|
|
251
|
+
"scroll_speed",
|
|
252
|
+
"type_speed",
|
|
253
|
+
"stay_duration",
|
|
254
|
+
"swipe_count",
|
|
255
|
+
"pinch_zoom_count",
|
|
256
|
+
"long_press_count",
|
|
257
|
+
"form_submit_count",
|
|
258
|
+
"tab_switch_count",
|
|
259
|
+
"search_count",
|
|
260
|
+
"video_play_count",
|
|
261
|
+
"video_watch_duration",
|
|
262
|
+
"file_download_count",
|
|
263
|
+
"share_count",
|
|
264
|
+
"mouse_distance"
|
|
265
|
+
];
|
|
266
|
+
|
|
267
|
+
// src/billing/CardBindScreen.tsx
|
|
268
|
+
var import_react5 = __toESM(require("react"));
|
|
269
|
+
var import_react_native3 = require("react-native");
|
|
270
|
+
var import_stripe_react_native = require("@stripe/stripe-react-native");
|
|
271
|
+
function CardBindScreen({ config, defaultCap, onComplete }) {
|
|
272
|
+
const { confirmSetupIntent } = (0, import_stripe_react_native.useStripe)();
|
|
273
|
+
const [capAmount, setCapAmount] = (0, import_react5.useState)(String(defaultCap.amountCents / 100));
|
|
274
|
+
const [period, setPeriod] = (0, import_react5.useState)(defaultCap.period);
|
|
275
|
+
const [submitting, setSubmitting] = (0, import_react5.useState)(false);
|
|
276
|
+
const [errorMsg, setErrorMsg] = (0, import_react5.useState)(null);
|
|
277
|
+
const handleSubmit = async () => {
|
|
278
|
+
setSubmitting(true);
|
|
279
|
+
setErrorMsg(null);
|
|
280
|
+
try {
|
|
281
|
+
const setupResp = await fetch(
|
|
282
|
+
`${config.apiBaseUrl.replace(/\/$/, "")}/api/billing/setup-intent`,
|
|
283
|
+
{
|
|
284
|
+
method: "POST",
|
|
285
|
+
headers: { "Content-Type": "application/json", "X-Api-Key": config.apiKey },
|
|
286
|
+
body: JSON.stringify({ appId: config.appId, endUserId: config.endUserId })
|
|
287
|
+
}
|
|
288
|
+
);
|
|
289
|
+
if (!setupResp.ok) throw new Error(`Setup failed (${setupResp.status})`);
|
|
290
|
+
const { clientSecret } = await setupResp.json();
|
|
291
|
+
const { error, setupIntent } = await confirmSetupIntent(clientSecret, {
|
|
292
|
+
paymentMethodType: "Card"
|
|
293
|
+
});
|
|
294
|
+
if (error) throw new Error(error.message);
|
|
295
|
+
const paymentMethodId = setupIntent?.paymentMethodId;
|
|
296
|
+
if (!paymentMethodId) throw new Error("No payment method returned.");
|
|
297
|
+
const amountCents = Math.round(parseFloat(capAmount) * 100);
|
|
298
|
+
if (!Number.isFinite(amountCents) || amountCents <= 0) {
|
|
299
|
+
throw new Error("Enter a valid spending cap amount.");
|
|
300
|
+
}
|
|
301
|
+
const capResp = await fetch(
|
|
302
|
+
`${config.apiBaseUrl.replace(/\/$/, "")}/api/billing/end-user-config`,
|
|
303
|
+
{
|
|
304
|
+
method: "POST",
|
|
305
|
+
headers: { "Content-Type": "application/json", "X-Api-Key": config.apiKey },
|
|
306
|
+
body: JSON.stringify({
|
|
307
|
+
appId: config.appId,
|
|
308
|
+
endUserId: config.endUserId,
|
|
309
|
+
paymentMethodId,
|
|
310
|
+
spendingCapCents: amountCents,
|
|
311
|
+
spendingCapPeriod: period
|
|
312
|
+
})
|
|
313
|
+
}
|
|
314
|
+
);
|
|
315
|
+
if (!capResp.ok) throw new Error(`Spending cap could not be saved (${capResp.status})`);
|
|
316
|
+
onComplete({ success: true });
|
|
317
|
+
} catch (err) {
|
|
318
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
319
|
+
setErrorMsg(message);
|
|
320
|
+
onComplete({ success: false, error: message });
|
|
321
|
+
} finally {
|
|
322
|
+
setSubmitting(false);
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
return /* @__PURE__ */ import_react5.default.createElement(import_react_native3.View, { style: styles.container }, /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.title }, "Add a payment method"), /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.subtitle }, "You'll be charged automatically based on usage in this app, up to the limit you set below. You can change or remove this at any time."), /* @__PURE__ */ import_react5.default.createElement(
|
|
326
|
+
import_stripe_react_native.CardField,
|
|
327
|
+
{
|
|
328
|
+
postalCodeEnabled: true,
|
|
329
|
+
style: styles.cardField,
|
|
330
|
+
placeholders: { number: "4242 4242 4242 4242" }
|
|
331
|
+
}
|
|
332
|
+
), /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.label }, "Spending cap ($)"), /* @__PURE__ */ import_react5.default.createElement(
|
|
333
|
+
import_react_native3.TextInput,
|
|
334
|
+
{
|
|
335
|
+
style: styles.input,
|
|
336
|
+
keyboardType: "decimal-pad",
|
|
337
|
+
value: capAmount,
|
|
338
|
+
onChangeText: setCapAmount
|
|
339
|
+
}
|
|
340
|
+
), /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.label }, "Cap period"), /* @__PURE__ */ import_react5.default.createElement(import_react_native3.View, { style: styles.periodRow }, ["weekly", "monthly"].map((p) => /* @__PURE__ */ import_react5.default.createElement(
|
|
341
|
+
import_react_native3.Pressable,
|
|
342
|
+
{
|
|
343
|
+
key: p,
|
|
344
|
+
style: [styles.periodButton, period === p && styles.periodButtonActive],
|
|
345
|
+
onPress: () => setPeriod(p)
|
|
346
|
+
},
|
|
347
|
+
/* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: period === p ? styles.periodTextActive : styles.periodText }, p === "weekly" ? "Weekly" : "Monthly")
|
|
348
|
+
))), errorMsg && /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.error }, errorMsg), /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Pressable, { style: styles.submitButton, onPress: handleSubmit, disabled: submitting }, /* @__PURE__ */ import_react5.default.createElement(import_react_native3.Text, { style: styles.submitText }, submitting ? "Saving\u2026" : "Confirm")));
|
|
349
|
+
}
|
|
350
|
+
var styles = import_react_native3.StyleSheet.create({
|
|
351
|
+
container: { padding: 20 },
|
|
352
|
+
title: { fontSize: 18, fontWeight: "600", marginBottom: 8 },
|
|
353
|
+
subtitle: { fontSize: 13, color: "#555", marginBottom: 20 },
|
|
354
|
+
cardField: { height: 50, marginVertical: 12 },
|
|
355
|
+
label: { fontSize: 13, fontWeight: "500", marginTop: 12, marginBottom: 4 },
|
|
356
|
+
input: {
|
|
357
|
+
borderWidth: 1,
|
|
358
|
+
borderColor: "#ccc",
|
|
359
|
+
borderRadius: 8,
|
|
360
|
+
padding: 10,
|
|
361
|
+
fontSize: 16
|
|
362
|
+
},
|
|
363
|
+
periodRow: { flexDirection: "row", gap: 8, marginTop: 4 },
|
|
364
|
+
periodButton: {
|
|
365
|
+
flex: 1,
|
|
366
|
+
padding: 10,
|
|
367
|
+
borderWidth: 1,
|
|
368
|
+
borderColor: "#ccc",
|
|
369
|
+
borderRadius: 8,
|
|
370
|
+
alignItems: "center"
|
|
371
|
+
},
|
|
372
|
+
periodButtonActive: { backgroundColor: "#111", borderColor: "#111" },
|
|
373
|
+
periodText: { color: "#111" },
|
|
374
|
+
periodTextActive: { color: "#fff" },
|
|
375
|
+
error: { color: "#c00", marginTop: 12 },
|
|
376
|
+
submitButton: {
|
|
377
|
+
marginTop: 24,
|
|
378
|
+
backgroundColor: "#111",
|
|
379
|
+
padding: 14,
|
|
380
|
+
borderRadius: 8,
|
|
381
|
+
alignItems: "center"
|
|
382
|
+
},
|
|
383
|
+
submitText: { color: "#fff", fontWeight: "600" }
|
|
384
|
+
});
|
|
385
|
+
|
|
386
|
+
// src/index.ts
|
|
387
|
+
function useStillKinetic(config, pageId) {
|
|
388
|
+
const senderRef = (0, import_react6.useRef)(null);
|
|
389
|
+
if (senderRef.current === null) {
|
|
390
|
+
senderRef.current = new BatchSender(config);
|
|
391
|
+
senderRef.current.start();
|
|
392
|
+
}
|
|
393
|
+
const sender = senderRef.current;
|
|
394
|
+
const metrics = config.trackedMetrics;
|
|
395
|
+
const { onPressIn } = usePressTracker(config, sender, pageId);
|
|
396
|
+
const { onScroll } = useScrollTracker(config, sender, pageId, metrics);
|
|
397
|
+
const { onChangeText } = useTypeTracker(config, sender, pageId);
|
|
398
|
+
useStayTracker(config, sender, pageId);
|
|
399
|
+
return (0, import_react6.useMemo)(
|
|
400
|
+
() => ({
|
|
401
|
+
onPressIn: metrics.includes("press_count") ? onPressIn : void 0,
|
|
402
|
+
onScroll: metrics.includes("scroll_length") || metrics.includes("scroll_speed") ? onScroll : void 0,
|
|
403
|
+
onChangeText: metrics.includes("type_speed") ? onChangeText : void 0
|
|
404
|
+
}),
|
|
405
|
+
[metrics, onPressIn, onScroll, onChangeText]
|
|
406
|
+
);
|
|
407
|
+
}
|
|
408
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
409
|
+
0 && (module.exports = {
|
|
410
|
+
ALL_METRICS,
|
|
411
|
+
CardBindScreen,
|
|
412
|
+
useStillKinetic
|
|
413
|
+
});
|
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { useMemo, useRef as useRef4 } from "react";
|
|
3
|
+
|
|
4
|
+
// src/transport/batchSender.ts
|
|
5
|
+
import { AppState } from "react-native";
|
|
6
|
+
var BatchSender = class {
|
|
7
|
+
constructor(config) {
|
|
8
|
+
this.config = config;
|
|
9
|
+
this.buffer = [];
|
|
10
|
+
this.timer = null;
|
|
11
|
+
this.maxBufferSize = 200;
|
|
12
|
+
this.appStateSub = null;
|
|
13
|
+
this.endpoint = `${config.apiBaseUrl.replace(/\/$/, "")}/api/events`;
|
|
14
|
+
}
|
|
15
|
+
start() {
|
|
16
|
+
const intervalMs = this.config.batchIntervalMs ?? 5e3;
|
|
17
|
+
this.timer = setInterval(() => this.flush(), intervalMs);
|
|
18
|
+
const handleAppStateChange = (state) => {
|
|
19
|
+
if (state === "background" || state === "inactive") this.flush();
|
|
20
|
+
};
|
|
21
|
+
this.appStateSub = AppState.addEventListener("change", handleAppStateChange);
|
|
22
|
+
}
|
|
23
|
+
stop() {
|
|
24
|
+
if (this.timer) clearInterval(this.timer);
|
|
25
|
+
this.appStateSub?.remove();
|
|
26
|
+
this.flush();
|
|
27
|
+
}
|
|
28
|
+
enqueue(event) {
|
|
29
|
+
this.buffer.push(event);
|
|
30
|
+
if (this.buffer.length >= this.maxBufferSize) this.flush();
|
|
31
|
+
}
|
|
32
|
+
flush() {
|
|
33
|
+
if (this.buffer.length === 0) return;
|
|
34
|
+
const events = this.buffer;
|
|
35
|
+
this.buffer = [];
|
|
36
|
+
this.sendWithRetry(events, 3);
|
|
37
|
+
}
|
|
38
|
+
sendWithRetry(events, retriesLeft) {
|
|
39
|
+
fetch(this.endpoint, {
|
|
40
|
+
method: "POST",
|
|
41
|
+
headers: {
|
|
42
|
+
"Content-Type": "application/json",
|
|
43
|
+
"X-Api-Key": this.config.apiKey
|
|
44
|
+
},
|
|
45
|
+
body: JSON.stringify({ appId: this.config.appId, events })
|
|
46
|
+
}).catch(() => {
|
|
47
|
+
if (retriesLeft > 0) {
|
|
48
|
+
const delay = Math.pow(2, 3 - retriesLeft) * 1e3;
|
|
49
|
+
setTimeout(() => this.sendWithRetry(events, retriesLeft - 1), delay);
|
|
50
|
+
}
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// src/trackers/pressTracker.ts
|
|
56
|
+
import { useCallback } from "react";
|
|
57
|
+
function usePressTracker(config, sender, pageId) {
|
|
58
|
+
const onPressIn = useCallback(() => {
|
|
59
|
+
sender.enqueue({
|
|
60
|
+
appId: config.appId,
|
|
61
|
+
endUserId: config.endUserId,
|
|
62
|
+
pageId,
|
|
63
|
+
metric: "press_count",
|
|
64
|
+
value: 1,
|
|
65
|
+
timestamp: Date.now()
|
|
66
|
+
});
|
|
67
|
+
}, [config, sender, pageId]);
|
|
68
|
+
return { onPressIn };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// src/trackers/scrollTracker.ts
|
|
72
|
+
import { useCallback as useCallback2, useRef } from "react";
|
|
73
|
+
function useScrollTracker(config, sender, pageId, enabledMetrics) {
|
|
74
|
+
const lastY = useRef(null);
|
|
75
|
+
const lastTimestamp = useRef(Date.now());
|
|
76
|
+
const wantsLength = enabledMetrics.includes("scroll_length");
|
|
77
|
+
const wantsSpeed = enabledMetrics.includes("scroll_speed");
|
|
78
|
+
const onScroll = useCallback2(
|
|
79
|
+
(e) => {
|
|
80
|
+
if (!wantsLength && !wantsSpeed) return;
|
|
81
|
+
const currentY = e.nativeEvent.contentOffset.y;
|
|
82
|
+
const now = Date.now();
|
|
83
|
+
if (lastY.current === null) {
|
|
84
|
+
lastY.current = currentY;
|
|
85
|
+
lastTimestamp.current = now;
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const deltaY = Math.abs(currentY - lastY.current);
|
|
89
|
+
const deltaT = Math.max(now - lastTimestamp.current, 1);
|
|
90
|
+
if (deltaY > 0) {
|
|
91
|
+
if (wantsLength) {
|
|
92
|
+
sender.enqueue({
|
|
93
|
+
appId: config.appId,
|
|
94
|
+
endUserId: config.endUserId,
|
|
95
|
+
pageId,
|
|
96
|
+
metric: "scroll_length",
|
|
97
|
+
value: deltaY,
|
|
98
|
+
timestamp: now
|
|
99
|
+
});
|
|
100
|
+
}
|
|
101
|
+
if (wantsSpeed) {
|
|
102
|
+
sender.enqueue({
|
|
103
|
+
appId: config.appId,
|
|
104
|
+
endUserId: config.endUserId,
|
|
105
|
+
pageId,
|
|
106
|
+
metric: "scroll_speed",
|
|
107
|
+
value: deltaY / deltaT,
|
|
108
|
+
timestamp: now
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
lastY.current = currentY;
|
|
113
|
+
lastTimestamp.current = now;
|
|
114
|
+
},
|
|
115
|
+
[config, sender, pageId, wantsLength, wantsSpeed]
|
|
116
|
+
);
|
|
117
|
+
return { onScroll };
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// src/trackers/typeTracker.ts
|
|
121
|
+
import { useCallback as useCallback3, useRef as useRef2 } from "react";
|
|
122
|
+
function useTypeTracker(config, sender, pageId) {
|
|
123
|
+
const timestamps = useRef2([]);
|
|
124
|
+
const lastLength = useRef2(0);
|
|
125
|
+
const windowMs = 1e4;
|
|
126
|
+
const onChangeText = useCallback3(
|
|
127
|
+
(text) => {
|
|
128
|
+
const now = Date.now();
|
|
129
|
+
const lengthDelta = text.length - lastLength.current;
|
|
130
|
+
lastLength.current = text.length;
|
|
131
|
+
if (lengthDelta === 0) return;
|
|
132
|
+
timestamps.current.push(now);
|
|
133
|
+
while (timestamps.current.length > 0 && now - timestamps.current[0] > windowMs) {
|
|
134
|
+
timestamps.current.shift();
|
|
135
|
+
}
|
|
136
|
+
if (timestamps.current.length < 2) return;
|
|
137
|
+
const elapsedMinutes = (now - timestamps.current[0]) / 6e4;
|
|
138
|
+
const charsPerMinute = elapsedMinutes > 0 ? timestamps.current.length / elapsedMinutes : 0;
|
|
139
|
+
sender.enqueue({
|
|
140
|
+
appId: config.appId,
|
|
141
|
+
endUserId: config.endUserId,
|
|
142
|
+
pageId,
|
|
143
|
+
metric: "type_speed",
|
|
144
|
+
value: Math.round(charsPerMinute),
|
|
145
|
+
timestamp: now
|
|
146
|
+
});
|
|
147
|
+
},
|
|
148
|
+
[config, sender, pageId]
|
|
149
|
+
);
|
|
150
|
+
return { onChangeText };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/trackers/stayTracker.ts
|
|
154
|
+
import { useEffect, useRef as useRef3 } from "react";
|
|
155
|
+
import { AppState as AppState2 } from "react-native";
|
|
156
|
+
function useStayTracker(config, sender, pageId) {
|
|
157
|
+
const activeMsRef = useRef3(0);
|
|
158
|
+
const segmentStart = useRef3(Date.now());
|
|
159
|
+
const intervalRef = useRef3(null);
|
|
160
|
+
useEffect(() => {
|
|
161
|
+
const closeSegment = () => {
|
|
162
|
+
if (segmentStart.current !== null) {
|
|
163
|
+
activeMsRef.current += Date.now() - segmentStart.current;
|
|
164
|
+
segmentStart.current = null;
|
|
165
|
+
}
|
|
166
|
+
};
|
|
167
|
+
const openSegment = () => {
|
|
168
|
+
if (segmentStart.current === null) segmentStart.current = Date.now();
|
|
169
|
+
};
|
|
170
|
+
const report = () => {
|
|
171
|
+
closeSegment();
|
|
172
|
+
const elapsed = activeMsRef.current;
|
|
173
|
+
activeMsRef.current = 0;
|
|
174
|
+
if (elapsed > 0) {
|
|
175
|
+
sender.enqueue({
|
|
176
|
+
appId: config.appId,
|
|
177
|
+
endUserId: config.endUserId,
|
|
178
|
+
pageId,
|
|
179
|
+
metric: "stay_duration",
|
|
180
|
+
value: elapsed,
|
|
181
|
+
timestamp: Date.now()
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
openSegment();
|
|
185
|
+
};
|
|
186
|
+
const handleAppStateChange = (state) => {
|
|
187
|
+
if (state === "active") openSegment();
|
|
188
|
+
else closeSegment();
|
|
189
|
+
};
|
|
190
|
+
const sub = AppState2.addEventListener("change", handleAppStateChange);
|
|
191
|
+
intervalRef.current = setInterval(report, 5e3);
|
|
192
|
+
return () => {
|
|
193
|
+
closeSegment();
|
|
194
|
+
const remaining = activeMsRef.current;
|
|
195
|
+
if (remaining > 0) {
|
|
196
|
+
sender.enqueue({
|
|
197
|
+
appId: config.appId,
|
|
198
|
+
endUserId: config.endUserId,
|
|
199
|
+
pageId,
|
|
200
|
+
metric: "stay_duration",
|
|
201
|
+
value: remaining,
|
|
202
|
+
timestamp: Date.now()
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
sub.remove();
|
|
206
|
+
if (intervalRef.current) clearInterval(intervalRef.current);
|
|
207
|
+
};
|
|
208
|
+
}, [config, sender, pageId]);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// src/core/types.ts
|
|
212
|
+
var ALL_METRICS = [
|
|
213
|
+
"press_count",
|
|
214
|
+
"scroll_length",
|
|
215
|
+
"scroll_speed",
|
|
216
|
+
"type_speed",
|
|
217
|
+
"stay_duration",
|
|
218
|
+
"swipe_count",
|
|
219
|
+
"pinch_zoom_count",
|
|
220
|
+
"long_press_count",
|
|
221
|
+
"form_submit_count",
|
|
222
|
+
"tab_switch_count",
|
|
223
|
+
"search_count",
|
|
224
|
+
"video_play_count",
|
|
225
|
+
"video_watch_duration",
|
|
226
|
+
"file_download_count",
|
|
227
|
+
"share_count",
|
|
228
|
+
"mouse_distance"
|
|
229
|
+
];
|
|
230
|
+
|
|
231
|
+
// src/billing/CardBindScreen.tsx
|
|
232
|
+
import React, { useState } from "react";
|
|
233
|
+
import { View, Text, TextInput, Pressable, StyleSheet } from "react-native";
|
|
234
|
+
import { CardField, useStripe } from "@stripe/stripe-react-native";
|
|
235
|
+
function CardBindScreen({ config, defaultCap, onComplete }) {
|
|
236
|
+
const { confirmSetupIntent } = useStripe();
|
|
237
|
+
const [capAmount, setCapAmount] = useState(String(defaultCap.amountCents / 100));
|
|
238
|
+
const [period, setPeriod] = useState(defaultCap.period);
|
|
239
|
+
const [submitting, setSubmitting] = useState(false);
|
|
240
|
+
const [errorMsg, setErrorMsg] = useState(null);
|
|
241
|
+
const handleSubmit = async () => {
|
|
242
|
+
setSubmitting(true);
|
|
243
|
+
setErrorMsg(null);
|
|
244
|
+
try {
|
|
245
|
+
const setupResp = await fetch(
|
|
246
|
+
`${config.apiBaseUrl.replace(/\/$/, "")}/api/billing/setup-intent`,
|
|
247
|
+
{
|
|
248
|
+
method: "POST",
|
|
249
|
+
headers: { "Content-Type": "application/json", "X-Api-Key": config.apiKey },
|
|
250
|
+
body: JSON.stringify({ appId: config.appId, endUserId: config.endUserId })
|
|
251
|
+
}
|
|
252
|
+
);
|
|
253
|
+
if (!setupResp.ok) throw new Error(`Setup failed (${setupResp.status})`);
|
|
254
|
+
const { clientSecret } = await setupResp.json();
|
|
255
|
+
const { error, setupIntent } = await confirmSetupIntent(clientSecret, {
|
|
256
|
+
paymentMethodType: "Card"
|
|
257
|
+
});
|
|
258
|
+
if (error) throw new Error(error.message);
|
|
259
|
+
const paymentMethodId = setupIntent?.paymentMethodId;
|
|
260
|
+
if (!paymentMethodId) throw new Error("No payment method returned.");
|
|
261
|
+
const amountCents = Math.round(parseFloat(capAmount) * 100);
|
|
262
|
+
if (!Number.isFinite(amountCents) || amountCents <= 0) {
|
|
263
|
+
throw new Error("Enter a valid spending cap amount.");
|
|
264
|
+
}
|
|
265
|
+
const capResp = await fetch(
|
|
266
|
+
`${config.apiBaseUrl.replace(/\/$/, "")}/api/billing/end-user-config`,
|
|
267
|
+
{
|
|
268
|
+
method: "POST",
|
|
269
|
+
headers: { "Content-Type": "application/json", "X-Api-Key": config.apiKey },
|
|
270
|
+
body: JSON.stringify({
|
|
271
|
+
appId: config.appId,
|
|
272
|
+
endUserId: config.endUserId,
|
|
273
|
+
paymentMethodId,
|
|
274
|
+
spendingCapCents: amountCents,
|
|
275
|
+
spendingCapPeriod: period
|
|
276
|
+
})
|
|
277
|
+
}
|
|
278
|
+
);
|
|
279
|
+
if (!capResp.ok) throw new Error(`Spending cap could not be saved (${capResp.status})`);
|
|
280
|
+
onComplete({ success: true });
|
|
281
|
+
} catch (err) {
|
|
282
|
+
const message = err instanceof Error ? err.message : "Unknown error";
|
|
283
|
+
setErrorMsg(message);
|
|
284
|
+
onComplete({ success: false, error: message });
|
|
285
|
+
} finally {
|
|
286
|
+
setSubmitting(false);
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
return /* @__PURE__ */ React.createElement(View, { style: styles.container }, /* @__PURE__ */ React.createElement(Text, { style: styles.title }, "Add a payment method"), /* @__PURE__ */ React.createElement(Text, { style: styles.subtitle }, "You'll be charged automatically based on usage in this app, up to the limit you set below. You can change or remove this at any time."), /* @__PURE__ */ React.createElement(
|
|
290
|
+
CardField,
|
|
291
|
+
{
|
|
292
|
+
postalCodeEnabled: true,
|
|
293
|
+
style: styles.cardField,
|
|
294
|
+
placeholders: { number: "4242 4242 4242 4242" }
|
|
295
|
+
}
|
|
296
|
+
), /* @__PURE__ */ React.createElement(Text, { style: styles.label }, "Spending cap ($)"), /* @__PURE__ */ React.createElement(
|
|
297
|
+
TextInput,
|
|
298
|
+
{
|
|
299
|
+
style: styles.input,
|
|
300
|
+
keyboardType: "decimal-pad",
|
|
301
|
+
value: capAmount,
|
|
302
|
+
onChangeText: setCapAmount
|
|
303
|
+
}
|
|
304
|
+
), /* @__PURE__ */ React.createElement(Text, { style: styles.label }, "Cap period"), /* @__PURE__ */ React.createElement(View, { style: styles.periodRow }, ["weekly", "monthly"].map((p) => /* @__PURE__ */ React.createElement(
|
|
305
|
+
Pressable,
|
|
306
|
+
{
|
|
307
|
+
key: p,
|
|
308
|
+
style: [styles.periodButton, period === p && styles.periodButtonActive],
|
|
309
|
+
onPress: () => setPeriod(p)
|
|
310
|
+
},
|
|
311
|
+
/* @__PURE__ */ React.createElement(Text, { style: period === p ? styles.periodTextActive : styles.periodText }, p === "weekly" ? "Weekly" : "Monthly")
|
|
312
|
+
))), errorMsg && /* @__PURE__ */ React.createElement(Text, { style: styles.error }, errorMsg), /* @__PURE__ */ React.createElement(Pressable, { style: styles.submitButton, onPress: handleSubmit, disabled: submitting }, /* @__PURE__ */ React.createElement(Text, { style: styles.submitText }, submitting ? "Saving\u2026" : "Confirm")));
|
|
313
|
+
}
|
|
314
|
+
var styles = StyleSheet.create({
|
|
315
|
+
container: { padding: 20 },
|
|
316
|
+
title: { fontSize: 18, fontWeight: "600", marginBottom: 8 },
|
|
317
|
+
subtitle: { fontSize: 13, color: "#555", marginBottom: 20 },
|
|
318
|
+
cardField: { height: 50, marginVertical: 12 },
|
|
319
|
+
label: { fontSize: 13, fontWeight: "500", marginTop: 12, marginBottom: 4 },
|
|
320
|
+
input: {
|
|
321
|
+
borderWidth: 1,
|
|
322
|
+
borderColor: "#ccc",
|
|
323
|
+
borderRadius: 8,
|
|
324
|
+
padding: 10,
|
|
325
|
+
fontSize: 16
|
|
326
|
+
},
|
|
327
|
+
periodRow: { flexDirection: "row", gap: 8, marginTop: 4 },
|
|
328
|
+
periodButton: {
|
|
329
|
+
flex: 1,
|
|
330
|
+
padding: 10,
|
|
331
|
+
borderWidth: 1,
|
|
332
|
+
borderColor: "#ccc",
|
|
333
|
+
borderRadius: 8,
|
|
334
|
+
alignItems: "center"
|
|
335
|
+
},
|
|
336
|
+
periodButtonActive: { backgroundColor: "#111", borderColor: "#111" },
|
|
337
|
+
periodText: { color: "#111" },
|
|
338
|
+
periodTextActive: { color: "#fff" },
|
|
339
|
+
error: { color: "#c00", marginTop: 12 },
|
|
340
|
+
submitButton: {
|
|
341
|
+
marginTop: 24,
|
|
342
|
+
backgroundColor: "#111",
|
|
343
|
+
padding: 14,
|
|
344
|
+
borderRadius: 8,
|
|
345
|
+
alignItems: "center"
|
|
346
|
+
},
|
|
347
|
+
submitText: { color: "#fff", fontWeight: "600" }
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
// src/index.ts
|
|
351
|
+
function useStillKinetic(config, pageId) {
|
|
352
|
+
const senderRef = useRef4(null);
|
|
353
|
+
if (senderRef.current === null) {
|
|
354
|
+
senderRef.current = new BatchSender(config);
|
|
355
|
+
senderRef.current.start();
|
|
356
|
+
}
|
|
357
|
+
const sender = senderRef.current;
|
|
358
|
+
const metrics = config.trackedMetrics;
|
|
359
|
+
const { onPressIn } = usePressTracker(config, sender, pageId);
|
|
360
|
+
const { onScroll } = useScrollTracker(config, sender, pageId, metrics);
|
|
361
|
+
const { onChangeText } = useTypeTracker(config, sender, pageId);
|
|
362
|
+
useStayTracker(config, sender, pageId);
|
|
363
|
+
return useMemo(
|
|
364
|
+
() => ({
|
|
365
|
+
onPressIn: metrics.includes("press_count") ? onPressIn : void 0,
|
|
366
|
+
onScroll: metrics.includes("scroll_length") || metrics.includes("scroll_speed") ? onScroll : void 0,
|
|
367
|
+
onChangeText: metrics.includes("type_speed") ? onChangeText : void 0
|
|
368
|
+
}),
|
|
369
|
+
[metrics, onPressIn, onScroll, onChangeText]
|
|
370
|
+
);
|
|
371
|
+
}
|
|
372
|
+
export {
|
|
373
|
+
ALL_METRICS,
|
|
374
|
+
CardBindScreen,
|
|
375
|
+
useStillKinetic
|
|
376
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@stillkinetic/rn-sdk",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Selectable-metric behavioral tracking with threshold-triggered Stripe billing, for React Native apps.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"main": "dist/index.cjs.js",
|
|
7
|
+
"module": "dist/index.esm.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"files": [
|
|
10
|
+
"dist"
|
|
11
|
+
],
|
|
12
|
+
"scripts": {
|
|
13
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --out-dir dist --clean --external react-native,react",
|
|
14
|
+
"dev": "tsup src/index.ts --format esm,cjs --dts --out-dir dist --watch --external react-native,react",
|
|
15
|
+
"typecheck": "tsc --noEmit"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"@stripe/stripe-react-native": "^0.37.0",
|
|
19
|
+
"react": ">=18.0.0",
|
|
20
|
+
"react-native": ">=0.72.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@stripe/stripe-react-native": "^0.37.3",
|
|
24
|
+
"@types/react": "^18.3.31",
|
|
25
|
+
"react": "^18.3.1",
|
|
26
|
+
"react-native": "^0.74.7",
|
|
27
|
+
"tsup": "^8.0.2",
|
|
28
|
+
"typescript": "^5.9.3"
|
|
29
|
+
},
|
|
30
|
+
"engines": {
|
|
31
|
+
"node": ">=18"
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
}
|
|
36
|
+
}
|