@leisuresaas/react-native 0.6.7 → 0.6.8-dev.2
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/package.json +1 -1
- package/src/analytics.ts +223 -0
- package/src/errors.ts +1 -0
- package/src/index.ts +12 -0
- package/src/public-auth.ts +4 -2
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@leisuresaas/react-native",
|
|
3
|
-
"version": "0.6.
|
|
3
|
+
"version": "0.6.8-dev.2",
|
|
4
4
|
"description": "React Native SDK for LeisureSaas: OAuth, Public Ads/App Config, Drive User Plane (publishable keys). Frontend-only — no Integration Key.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
package/src/analytics.ts
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
import { AppState, Platform, type AppStateStatus } from "react-native";
|
|
2
|
+
|
|
3
|
+
import { authGetItem, authSetItem } from "./auth-storage";
|
|
4
|
+
import { ErrorReason, isReason, PlatformError } from "./errors";
|
|
5
|
+
import { authHeaders, deviceHeaders, type PublicAuthContext } from "./public-auth";
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Product analytics for apps: app_open, foreground / background (automatic), screen views and
|
|
9
|
+
* custom events. Events are queued in memory and sent in batches to
|
|
10
|
+
* `/v1/public/analytics/events` (Publishable Key with the `analytics` capability). On by default
|
|
11
|
+
* once started; `setAnalyticsEnabled(false)` opts the device out and is remembered.
|
|
12
|
+
*/
|
|
13
|
+
export type AnalyticsOptions = PublicAuthContext & {
|
|
14
|
+
/** Signed-in user's access token, so events are attributed to the user. */
|
|
15
|
+
getAccessToken?: () => string | undefined | Promise<string | undefined>;
|
|
16
|
+
/** Record app_open, app_foreground and app_background. Default true. */
|
|
17
|
+
autoAppEvents?: boolean;
|
|
18
|
+
/** Send queued events this often while the app is active. Default 10 s. */
|
|
19
|
+
flushIntervalMs?: number;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
export type AnalyticsProps = Record<string, string | number | boolean | null | undefined>;
|
|
23
|
+
|
|
24
|
+
type QueuedEvent = {
|
|
25
|
+
event_id: string;
|
|
26
|
+
name: string;
|
|
27
|
+
occurred_at: number;
|
|
28
|
+
session_id: string;
|
|
29
|
+
screen?: string;
|
|
30
|
+
props?: Record<string, string>;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
const maxBatch = 50;
|
|
34
|
+
const flushAt = 20;
|
|
35
|
+
const maxQueue = 500;
|
|
36
|
+
const sessionIdleMs = 30 * 60 * 1000;
|
|
37
|
+
const disabledKey = "leisuresaas.analytics_disabled";
|
|
38
|
+
|
|
39
|
+
let opts: AnalyticsOptions | undefined;
|
|
40
|
+
let queue: QueuedEvent[] = [];
|
|
41
|
+
let timer: ReturnType<typeof setInterval> | undefined;
|
|
42
|
+
let appStateSub: { remove: () => void } | undefined;
|
|
43
|
+
let sending = false;
|
|
44
|
+
let session = { id: "", lastActive: 0 };
|
|
45
|
+
let optedOut = false;
|
|
46
|
+
let productDisabled = false;
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Starts collection: app_open now, app_foreground / app_background on AppState changes (unless
|
|
50
|
+
* `autoAppEvents: false`), and a flush every 10 s while active and when the app goes to the
|
|
51
|
+
* background. Returns a function that stops it.
|
|
52
|
+
*/
|
|
53
|
+
export function startAnalytics(options: AnalyticsOptions): () => void {
|
|
54
|
+
stopAnalytics();
|
|
55
|
+
opts = options;
|
|
56
|
+
productDisabled = false;
|
|
57
|
+
void authGetItem(disabledKey).then((v) => {
|
|
58
|
+
optedOut = v === "1";
|
|
59
|
+
if (optedOut) {
|
|
60
|
+
queue = [];
|
|
61
|
+
}
|
|
62
|
+
}).catch(() => undefined);
|
|
63
|
+
|
|
64
|
+
timer = setInterval(() => {
|
|
65
|
+
if (AppState.currentState === "active") {
|
|
66
|
+
void flushAnalytics();
|
|
67
|
+
}
|
|
68
|
+
}, options.flushIntervalMs ?? 10_000);
|
|
69
|
+
|
|
70
|
+
let last = (AppState.currentState ?? "unknown") as AppStateStatus;
|
|
71
|
+
appStateSub = AppState.addEventListener("change", (next) => {
|
|
72
|
+
if (options.autoAppEvents !== false) {
|
|
73
|
+
if (next === "active" && last !== "active") {
|
|
74
|
+
track("app_foreground");
|
|
75
|
+
} else if (next === "background" && last !== "background") {
|
|
76
|
+
track("app_background");
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
if (next === "background") {
|
|
80
|
+
void flushAnalytics();
|
|
81
|
+
}
|
|
82
|
+
last = next;
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
if (options.autoAppEvents !== false) {
|
|
86
|
+
track("app_open");
|
|
87
|
+
}
|
|
88
|
+
return stopAnalytics;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Stops automatic collection and the flush timer. Queued events stay until the next start. */
|
|
92
|
+
export function stopAnalytics(): void {
|
|
93
|
+
if (timer !== undefined) {
|
|
94
|
+
clearInterval(timer);
|
|
95
|
+
timer = undefined;
|
|
96
|
+
}
|
|
97
|
+
appStateSub?.remove();
|
|
98
|
+
appStateSub = undefined;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Records a screen view; call it from your navigation container's state change. */
|
|
102
|
+
export function screen(name: string, props?: AnalyticsProps): void {
|
|
103
|
+
if (!collecting()) {
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
enqueue({ ...baseEvent("screen_view"), screen: name, props: stringProps(props) });
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Records a custom event, e.g. `track("checkout_started", { plan: "premium" })`. */
|
|
110
|
+
export function track(name: string, props?: AnalyticsProps): void {
|
|
111
|
+
if (!collecting()) {
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
enqueue({ ...baseEvent(name), props: stringProps(props) });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Call right after sign-in: sends an `identify` event with the user's token now, so this device's
|
|
119
|
+
* earlier anonymous events count as the user's (the first user seen on a device keeps it).
|
|
120
|
+
* Needs `getAccessToken` in the options; the user comes from the token.
|
|
121
|
+
*/
|
|
122
|
+
export function identify(): Promise<void> {
|
|
123
|
+
if (!collecting() || !opts) {
|
|
124
|
+
return Promise.resolve();
|
|
125
|
+
}
|
|
126
|
+
enqueue(baseEvent("identify"));
|
|
127
|
+
return flushAnalytics();
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Opts this device in or out. Opting out drops queued events; the choice is kept in secure storage. */
|
|
131
|
+
export async function setAnalyticsEnabled(enabled: boolean): Promise<void> {
|
|
132
|
+
optedOut = !enabled;
|
|
133
|
+
if (!enabled) {
|
|
134
|
+
queue = [];
|
|
135
|
+
}
|
|
136
|
+
try {
|
|
137
|
+
await authSetItem(disabledKey, enabled ? "" : "1");
|
|
138
|
+
} catch {
|
|
139
|
+
// storage unavailable: the choice lasts for this run
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Whether this device collects analytics (default true). */
|
|
144
|
+
export function analyticsEnabled(): boolean {
|
|
145
|
+
return !optedOut;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** Sends queued events now. Failed sends stay queued; ANALYTICS_DISABLED stops collection. */
|
|
149
|
+
export async function flushAnalytics(): Promise<void> {
|
|
150
|
+
if (!opts || sending || queue.length === 0) {
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
sending = true;
|
|
154
|
+
const batch = queue.slice(0, maxBatch);
|
|
155
|
+
try {
|
|
156
|
+
await sendBatch(opts, batch);
|
|
157
|
+
queue = queue.slice(batch.length);
|
|
158
|
+
} catch (err) {
|
|
159
|
+
if (isReason(err, ErrorReason.AnalyticsDisabled)) {
|
|
160
|
+
productDisabled = true;
|
|
161
|
+
queue = [];
|
|
162
|
+
stopAnalytics();
|
|
163
|
+
} else if (err instanceof PlatformError && err.statusCode >= 400 && err.statusCode < 500 && err.statusCode !== 429) {
|
|
164
|
+
// The batch itself is unacceptable (bad key, too large); retrying would fail again.
|
|
165
|
+
queue = queue.slice(batch.length);
|
|
166
|
+
}
|
|
167
|
+
} finally {
|
|
168
|
+
sending = false;
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function collecting(): boolean {
|
|
173
|
+
return !optedOut && !productDisabled;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function enqueue(ev: QueuedEvent): void {
|
|
177
|
+
queue.push(ev);
|
|
178
|
+
if (queue.length > maxQueue) {
|
|
179
|
+
queue = queue.slice(queue.length - maxQueue);
|
|
180
|
+
}
|
|
181
|
+
if (queue.length >= flushAt) {
|
|
182
|
+
void flushAnalytics();
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function baseEvent(name: string): QueuedEvent {
|
|
187
|
+
const now = Date.now();
|
|
188
|
+
if (!session.id || now - session.lastActive > sessionIdleMs) {
|
|
189
|
+
session = { id: newId(), lastActive: now };
|
|
190
|
+
}
|
|
191
|
+
session.lastActive = now;
|
|
192
|
+
return { event_id: newId(), name, occurred_at: now, session_id: session.id };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function stringProps(props?: AnalyticsProps): Record<string, string> | undefined {
|
|
196
|
+
if (!props) {
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
const out: Record<string, string> = {};
|
|
200
|
+
for (const [k, v] of Object.entries(props)) {
|
|
201
|
+
if (v !== undefined && v !== null) {
|
|
202
|
+
out[k] = String(v);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
return out;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async function sendBatch(options: AnalyticsOptions, events: QueuedEvent[]): Promise<void> {
|
|
209
|
+
const token = await options.getAccessToken?.();
|
|
210
|
+
const headers = { ...authHeaders(options, token), ...(await deviceHeaders(options)) };
|
|
211
|
+
const res = await fetch(`${options.gatewayUrl.replace(/\/+$/, "")}/v1/public/analytics/events`, {
|
|
212
|
+
method: "POST",
|
|
213
|
+
headers,
|
|
214
|
+
body: JSON.stringify({ os: `${Platform.OS} ${String(Platform.Version)}`, events }),
|
|
215
|
+
});
|
|
216
|
+
if (!res.ok) {
|
|
217
|
+
throw PlatformError.fromHttp(res.status, (await res.text()).trim());
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function newId(): string {
|
|
222
|
+
return globalThis.crypto?.randomUUID?.() ?? `rn-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
223
|
+
}
|
package/src/errors.ts
CHANGED
|
@@ -33,6 +33,7 @@ export const ErrorReason = {
|
|
|
33
33
|
// the product allows fewer devices / signed out from another device or by an operator.
|
|
34
34
|
SessionReplaced: "SESSION_REPLACED",
|
|
35
35
|
SessionLimitReached: "SESSION_LIMIT_REACHED",
|
|
36
|
+
AnalyticsDisabled: "ANALYTICS_DISABLED",
|
|
36
37
|
SessionRevoked: "SESSION_REVOKED",
|
|
37
38
|
// Drive uploads: the user's plan storage is used up / the product's storage is full / the file is
|
|
38
39
|
// over the product's single-file limit.
|
package/src/index.ts
CHANGED
|
@@ -201,3 +201,15 @@ export type {
|
|
|
201
201
|
RegisterDeviceTokenInput,
|
|
202
202
|
SubscriptionStatus,
|
|
203
203
|
} from "./types";
|
|
204
|
+
|
|
205
|
+
export {
|
|
206
|
+
analyticsEnabled,
|
|
207
|
+
flushAnalytics,
|
|
208
|
+
identify,
|
|
209
|
+
screen,
|
|
210
|
+
setAnalyticsEnabled,
|
|
211
|
+
startAnalytics,
|
|
212
|
+
stopAnalytics,
|
|
213
|
+
track,
|
|
214
|
+
} from "./analytics";
|
|
215
|
+
export type { AnalyticsOptions, AnalyticsProps } from "./analytics";
|
package/src/public-auth.ts
CHANGED
|
@@ -48,7 +48,8 @@ function resolvePlatform(ctx: PublicAuthContext): MobilePlatform | "web" {
|
|
|
48
48
|
return ctx.platform ?? mobilePlatform();
|
|
49
49
|
}
|
|
50
50
|
|
|
51
|
-
|
|
51
|
+
/** @internal Shared with analytics. */
|
|
52
|
+
export function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<string, string> {
|
|
52
53
|
const platform = resolvePlatform(ctx);
|
|
53
54
|
const headers: Record<string, string> = {
|
|
54
55
|
Accept: "application/json",
|
|
@@ -67,7 +68,8 @@ function authHeaders(ctx: PublicAuthContext, accessToken?: string): Record<strin
|
|
|
67
68
|
return headers;
|
|
68
69
|
}
|
|
69
70
|
|
|
70
|
-
|
|
71
|
+
/** @internal Shared with analytics. */
|
|
72
|
+
export async function deviceHeaders(ctx: PublicAuthContext): Promise<Record<string, string>> {
|
|
71
73
|
const headers: Record<string, string> = { "X-Device-Id": await appDeviceId() };
|
|
72
74
|
if (ctx.appVersion?.trim()) headers["X-App-Version"] = ctx.appVersion.trim();
|
|
73
75
|
if (ctx.deviceModel?.trim()) headers["X-Device-Model"] = ctx.deviceModel.trim();
|