@shotik/react-native 0.1.1 → 0.2.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/CHANGELOG.md +16 -0
- package/LICENSE +26 -0
- package/README.md +36 -1
- package/README.ru.md +37 -1
- package/dist/analytics/core.d.ts +96 -11
- package/dist/analytics/core.js +295 -22
- package/dist/analytics/privacy.d.ts +4 -0
- package/dist/analytics/privacy.js +46 -0
- package/dist/analytics/replay.d.ts +41 -0
- package/dist/analytics/replay.js +192 -0
- package/dist/analytics/rn.d.ts +52 -2
- package/dist/analytics/rn.js +669 -62
- package/dist/analytics/wire.d.ts +54 -2
- package/dist/analytics/wire.js +44 -4
- package/dist/client.d.ts +93 -0
- package/dist/client.js +247 -9
- package/dist/flow.d.ts +48 -0
- package/dist/flow.js +56 -0
- package/dist/index.d.ts +4 -4
- package/dist/index.js +2 -2
- package/dist/parts.d.ts +42 -1
- package/dist/parts.js +72 -14
- package/dist/react.d.ts +24 -3
- package/dist/react.js +42 -15
- package/dist/sheet.d.ts +2 -1
- package/dist/sheet.js +206 -15
- package/dist/support.js +2 -2
- package/dist/theme.d.ts +43 -0
- package/dist/theme.js +88 -2
- package/package.json +15 -2
- package/recipe.json +1 -1
- package/src/analytics/README.md +10 -6
- package/src/analytics/core.ts +314 -25
- package/src/analytics/privacy.ts +50 -0
- package/src/analytics/recipe.json +1 -1
- package/src/analytics/replay.ts +190 -0
- package/src/analytics/rn.tsx +620 -63
- package/src/analytics/wire.ts +99 -8
- package/src/client.ts +334 -9
- package/src/flow.ts +100 -0
- package/src/index.ts +4 -4
- package/src/parts.tsx +102 -14
- package/src/react.tsx +57 -16
- package/src/sheet.tsx +422 -19
- package/src/support.ts +2 -2
- package/src/theme.ts +88 -2
package/dist/analytics/wire.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export declare const WIRE_VERSION = 1;
|
|
2
|
-
export declare const TYPES: readonly ["session", "open", "close", "screen", "leave", "tap", "rage", "scroll", "error", "slow", "purchase", "custom", "identify", "snapshot"];
|
|
2
|
+
export declare const TYPES: readonly ["session", "open", "close", "screen", "leave", "tap", "rage", "scroll", "error", "slow", "purchase", "custom", "identify", "snapshot", "net", "field", "state", "gesture"];
|
|
3
3
|
export type EventType = (typeof TYPES)[number];
|
|
4
4
|
export interface DeviceContext {
|
|
5
5
|
platform?: string;
|
|
@@ -11,6 +11,12 @@ export interface DeviceContext {
|
|
|
11
11
|
tz?: string;
|
|
12
12
|
w?: number;
|
|
13
13
|
h?: number;
|
|
14
|
+
ota?: string;
|
|
15
|
+
ch?: string;
|
|
16
|
+
rt?: string;
|
|
17
|
+
sdk?: string;
|
|
18
|
+
tzo?: number;
|
|
19
|
+
dev?: 1;
|
|
14
20
|
}
|
|
15
21
|
export interface WireEvent {
|
|
16
22
|
seq: number;
|
|
@@ -20,6 +26,7 @@ export interface WireEvent {
|
|
|
20
26
|
name?: string;
|
|
21
27
|
screen?: string;
|
|
22
28
|
props?: Record<string, unknown>;
|
|
29
|
+
kind?: 'test';
|
|
23
30
|
}
|
|
24
31
|
export interface Batch {
|
|
25
32
|
anonymousId: string;
|
|
@@ -28,7 +35,7 @@ export interface Batch {
|
|
|
28
35
|
device?: DeviceContext;
|
|
29
36
|
events: WireEvent[];
|
|
30
37
|
}
|
|
31
|
-
export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0];
|
|
38
|
+
export type PackedEvent = [number, number, number, number, number, number, Record<string, unknown> | 0, 1?];
|
|
32
39
|
export interface PackedBatch {
|
|
33
40
|
v: 1;
|
|
34
41
|
a: string;
|
|
@@ -51,3 +58,48 @@ export interface Wireframe {
|
|
|
51
58
|
dark?: boolean;
|
|
52
59
|
nodes: WireNode[];
|
|
53
60
|
}
|
|
61
|
+
export type KeyedNode = [string, string, number, number, number, number, (string | null)?, (number | null)?, (string | null)?];
|
|
62
|
+
export interface ReplayScroll {
|
|
63
|
+
node: string;
|
|
64
|
+
y: number;
|
|
65
|
+
x?: number;
|
|
66
|
+
}
|
|
67
|
+
export interface ReplayRun {
|
|
68
|
+
after: string | null;
|
|
69
|
+
nodes: KeyedNode[];
|
|
70
|
+
}
|
|
71
|
+
export interface ReplayChunk {
|
|
72
|
+
sess: string;
|
|
73
|
+
seq: number;
|
|
74
|
+
t: number;
|
|
75
|
+
keyframe?: {
|
|
76
|
+
screen: string;
|
|
77
|
+
w: number;
|
|
78
|
+
h: number;
|
|
79
|
+
nodes: KeyedNode[];
|
|
80
|
+
};
|
|
81
|
+
diff?: {
|
|
82
|
+
add?: ReplayRun[];
|
|
83
|
+
rm?: string[];
|
|
84
|
+
mv?: [string, number, number][];
|
|
85
|
+
};
|
|
86
|
+
scroll?: ReplayScroll[];
|
|
87
|
+
}
|
|
88
|
+
export type ReplayWhy = 'sample' | 'rage' | 'dead' | 'unresponsive' | 'errtap' | 'error' | 'crash';
|
|
89
|
+
export interface ReplayUpload {
|
|
90
|
+
v: 1;
|
|
91
|
+
a: string;
|
|
92
|
+
why: ReplayWhy;
|
|
93
|
+
chunks: ReplayChunk[];
|
|
94
|
+
}
|
|
95
|
+
export interface ReplayPicture {
|
|
96
|
+
screen: string;
|
|
97
|
+
w: number;
|
|
98
|
+
h: number;
|
|
99
|
+
nodes: KeyedNode[];
|
|
100
|
+
scroll: Record<string, {
|
|
101
|
+
x: number;
|
|
102
|
+
y: number;
|
|
103
|
+
}>;
|
|
104
|
+
}
|
|
105
|
+
export declare function applyChunk(prev: ReplayPicture | null, c: ReplayChunk): ReplayPicture | null;
|
package/dist/analytics/wire.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
// native code, so this is the compression: about 6x smaller than plain JSON on tap-heavy batches.
|
|
5
5
|
export const WIRE_VERSION = 1;
|
|
6
6
|
// Event types. Codes are the array position, so append only.
|
|
7
|
-
export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot'];
|
|
7
|
+
export const TYPES = ['session', 'open', 'close', 'screen', 'leave', 'tap', 'rage', 'scroll', 'error', 'slow', 'purchase', 'custom', 'identify', 'snapshot', 'net', 'field', 'state', 'gesture'];
|
|
8
8
|
const PACKED_PROPS = ['el', 'label', 'from'];
|
|
9
9
|
export function pack(b) {
|
|
10
10
|
const d = [];
|
|
@@ -35,14 +35,17 @@ export function pack(b) {
|
|
|
35
35
|
p[k] = PACKED_PROPS.includes(k) && typeof v === 'string' ? s(v) : v;
|
|
36
36
|
}
|
|
37
37
|
}
|
|
38
|
-
|
|
38
|
+
const row = [dt, TYPES.indexOf(ev.type), ev.seq, s(ev.sessionId), s(ev.screen), s(ev.name), p];
|
|
39
|
+
if (ev.kind === 'test')
|
|
40
|
+
row.push(1);
|
|
41
|
+
return row;
|
|
39
42
|
});
|
|
40
43
|
return { v: 1, a: b.anonymousId, u: b.userId ?? null, f: b.firstSeen, c: b.device, t0, d, e };
|
|
41
44
|
}
|
|
42
45
|
export function unpack(p) {
|
|
43
46
|
const str = (i) => (i >= 0 && i < p.d.length ? p.d[i] : undefined);
|
|
44
47
|
let ts = p.t0;
|
|
45
|
-
const events = p.e.map(([dt, type, seq, sess, screen, name, props]) => {
|
|
48
|
+
const events = p.e.map(([dt, type, seq, sess, screen, name, props, test]) => {
|
|
46
49
|
ts += dt;
|
|
47
50
|
let pr;
|
|
48
51
|
if (props) {
|
|
@@ -50,7 +53,44 @@ export function unpack(p) {
|
|
|
50
53
|
for (const k in props)
|
|
51
54
|
pr[k] = PACKED_PROPS.includes(k) && typeof props[k] === 'number' ? str(props[k]) : props[k];
|
|
52
55
|
}
|
|
53
|
-
return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr };
|
|
56
|
+
return { seq, ts, type: TYPES[type] ?? 'custom', sessionId: str(sess) ?? '', screen: str(screen), name: str(name), props: pr, ...(test === 1 && { kind: 'test' }) };
|
|
54
57
|
});
|
|
55
58
|
return { anonymousId: p.a, userId: p.u ?? null, firstSeen: p.f, device: p.c, events };
|
|
56
59
|
}
|
|
60
|
+
export function applyChunk(prev, c) {
|
|
61
|
+
let pic;
|
|
62
|
+
if (c.keyframe)
|
|
63
|
+
pic = { screen: c.keyframe.screen, w: c.keyframe.w, h: c.keyframe.h, nodes: c.keyframe.nodes.slice(), scroll: {} };
|
|
64
|
+
else if (prev)
|
|
65
|
+
pic = { ...prev, nodes: prev.nodes.slice(), scroll: { ...prev.scroll } };
|
|
66
|
+
else
|
|
67
|
+
return null;
|
|
68
|
+
const d = c.diff;
|
|
69
|
+
if (d) {
|
|
70
|
+
const gone = new Set(d.rm ?? []);
|
|
71
|
+
for (const r of d.add ?? [])
|
|
72
|
+
for (const n of r.nodes)
|
|
73
|
+
gone.add(n[0]);
|
|
74
|
+
let nodes = pic.nodes.filter((n) => !gone.has(n[0]));
|
|
75
|
+
for (const r of d.add ?? []) {
|
|
76
|
+
const i = r.after === null ? 0 : nodes.findIndex((n) => n[0] === r.after) + 1;
|
|
77
|
+
nodes = nodes.slice(0, i).concat(r.nodes, nodes.slice(i));
|
|
78
|
+
}
|
|
79
|
+
if (d.mv?.length) {
|
|
80
|
+
const mv = new Map(d.mv.map((m) => [m[0], m]));
|
|
81
|
+
nodes = nodes.map((n) => {
|
|
82
|
+
const m = mv.get(n[0]);
|
|
83
|
+
if (!m)
|
|
84
|
+
return n;
|
|
85
|
+
const k = n.slice();
|
|
86
|
+
k[2] = m[1];
|
|
87
|
+
k[3] = m[2];
|
|
88
|
+
return k;
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
pic.nodes = nodes;
|
|
92
|
+
}
|
|
93
|
+
for (const s of c.scroll ?? [])
|
|
94
|
+
pic.scroll[s.node] = { x: s.x ?? 0, y: s.y };
|
|
95
|
+
return pic;
|
|
96
|
+
}
|
package/dist/client.d.ts
CHANGED
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
export interface ErasableAnalytics {
|
|
2
|
+
forget(): Promise<boolean>;
|
|
3
|
+
reset(): Promise<void> | void;
|
|
4
|
+
}
|
|
5
|
+
export declare function registerAnalytics(a: ErasableAnalytics | null): void;
|
|
1
6
|
export type Author = 'user' | 'ai' | 'founder' | 'system';
|
|
2
7
|
export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string;
|
|
3
8
|
export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error';
|
|
@@ -10,7 +15,60 @@ export interface Conversation {
|
|
|
10
15
|
lastAuthor: Author | null;
|
|
11
16
|
createdAt: number;
|
|
12
17
|
founderUnread?: number;
|
|
18
|
+
csat?: 1 | -1 | null;
|
|
19
|
+
}
|
|
20
|
+
export interface Subscription {
|
|
21
|
+
status: 'trial' | 'active' | 'grace' | 'billing_retry' | 'cancelled' | 'expired' | 'refunded' | 'none';
|
|
22
|
+
product?: string | null;
|
|
23
|
+
period?: 'P1W' | 'P1M' | 'P3M' | 'P6M' | 'P1Y' | 'lifetime' | null;
|
|
24
|
+
price?: string | null;
|
|
25
|
+
renewsAt?: number | null;
|
|
26
|
+
expiresAt?: number | null;
|
|
27
|
+
trialEndsAt?: number | null;
|
|
28
|
+
willRenew?: boolean | null;
|
|
29
|
+
store?: 'app_store' | 'play' | 'stripe' | null;
|
|
30
|
+
}
|
|
31
|
+
export type ActionKind = 'manage_subscription' | 'restore' | 'redeem_code' | 'change_plan' | 'request_refund' | 'open_url' | 'write_review' | 'custom';
|
|
32
|
+
export interface SupportAction {
|
|
33
|
+
id: string;
|
|
34
|
+
kind: ActionKind;
|
|
35
|
+
label: string;
|
|
36
|
+
value?: string | null;
|
|
37
|
+
}
|
|
38
|
+
export type ActionResult = 'done' | 'cancelled' | 'failed';
|
|
39
|
+
export declare const actionsOf: (m: Message) => SupportAction[];
|
|
40
|
+
export type CancelReason = 'too_expensive' | 'not_using' | 'bug' | 'mistake' | 'other';
|
|
41
|
+
export interface Offer {
|
|
42
|
+
kind: 'chat';
|
|
43
|
+
label: string;
|
|
44
|
+
}
|
|
45
|
+
export interface WidgetConfig {
|
|
46
|
+
offers: Partial<Record<CancelReason, Offer>>;
|
|
47
|
+
offerEligible: boolean;
|
|
48
|
+
review: {
|
|
49
|
+
moments: Record<string, number>;
|
|
50
|
+
minDaysSinceInstall: number;
|
|
51
|
+
maxPerYear: number;
|
|
52
|
+
quietDaysAfterFriction: number;
|
|
53
|
+
quietDaysAfterRefundOrCancel: number;
|
|
54
|
+
};
|
|
55
|
+
quietScreens: string[];
|
|
56
|
+
customActions: {
|
|
57
|
+
id: string;
|
|
58
|
+
label: string;
|
|
59
|
+
}[];
|
|
60
|
+
}
|
|
61
|
+
export interface Friction {
|
|
62
|
+
kind: 'purchase_fail' | 'rage' | 'error';
|
|
63
|
+
screen?: string | null;
|
|
64
|
+
element?: string | null;
|
|
13
65
|
}
|
|
66
|
+
export type Trigger = Friction | {
|
|
67
|
+
kind: 'offer';
|
|
68
|
+
screen?: null;
|
|
69
|
+
element: CancelReason;
|
|
70
|
+
};
|
|
71
|
+
export type SupportEventKind = 'action' | 'cancel_started' | 'cancel_reason' | 'offer_shown' | 'offer_accepted' | 'cancel_continued' | 'refund_help' | 'refund_requested' | 'review_prompt' | 'friction_shown' | 'friction_opened' | 'friction_dismissed';
|
|
14
72
|
export interface LocalAttachment {
|
|
15
73
|
uri: string;
|
|
16
74
|
type?: string;
|
|
@@ -64,6 +122,12 @@ export interface SupportConfig {
|
|
|
64
122
|
serverUrl: string;
|
|
65
123
|
storage?: KeyValueStorage;
|
|
66
124
|
device?: () => DeviceInfo | Promise<DeviceInfo>;
|
|
125
|
+
aiConsent?: boolean;
|
|
126
|
+
onAction?: (action: SupportAction) => ActionResult | void | Promise<ActionResult | void>;
|
|
127
|
+
openUrl?: (url: string) => unknown;
|
|
128
|
+
requestReview?: () => unknown;
|
|
129
|
+
appStoreId?: string;
|
|
130
|
+
analytics?: ErasableAnalytics | null;
|
|
67
131
|
}
|
|
68
132
|
export interface SupportState {
|
|
69
133
|
status: Status;
|
|
@@ -76,6 +140,10 @@ export interface SupportState {
|
|
|
76
140
|
activeConversationId: string | null;
|
|
77
141
|
error: string | null;
|
|
78
142
|
typing: Record<string, Typing>;
|
|
143
|
+
aiConsent: boolean | null;
|
|
144
|
+
subscription: Subscription | null;
|
|
145
|
+
widget: WidgetConfig | null;
|
|
146
|
+
friction: Friction | null;
|
|
79
147
|
}
|
|
80
148
|
export declare function receiptOf(m: Message, list: Message[], conv: Conversation | undefined, offline?: boolean): Receipt | null;
|
|
81
149
|
export declare const attachmentsOf: (m: Message) => (Partial<Attachment> & {
|
|
@@ -91,6 +159,13 @@ export declare class SupportClient {
|
|
|
91
159
|
private storage;
|
|
92
160
|
private listeners;
|
|
93
161
|
private state;
|
|
162
|
+
private subscriptionSet;
|
|
163
|
+
private ledger;
|
|
164
|
+
private session_;
|
|
165
|
+
private pendingTrigger;
|
|
166
|
+
private offerShown;
|
|
167
|
+
private eraseTimer;
|
|
168
|
+
private eraseStep;
|
|
94
169
|
private typingTimers;
|
|
95
170
|
private session;
|
|
96
171
|
private anonId;
|
|
@@ -118,6 +193,21 @@ export declare class SupportClient {
|
|
|
118
193
|
request<T>(method: 'GET' | 'POST', path: string, body?: unknown): Promise<T>;
|
|
119
194
|
identify(user?: UserInfo): Promise<void>;
|
|
120
195
|
ensureIdentified(): Promise<void>;
|
|
196
|
+
setAiConsent(allowed: boolean): Promise<void>;
|
|
197
|
+
setSubscription(sub: Subscription | null): Promise<void>;
|
|
198
|
+
private loadWidget;
|
|
199
|
+
track(kind: SupportEventKind, data?: Record<string, string | number | boolean>, conversationId?: string | null): void;
|
|
200
|
+
runAction(action: SupportAction, conversationId?: string | null): Promise<ActionResult>;
|
|
201
|
+
fallbackUrl(action: Pick<SupportAction, 'kind' | 'value'>): string | null;
|
|
202
|
+
private openFallback;
|
|
203
|
+
rate(conversationId: string, score: 1 | -1, comment?: string): Promise<void>;
|
|
204
|
+
reviewMoment(name: string): Promise<boolean>;
|
|
205
|
+
friction(f: Friction): void;
|
|
206
|
+
openFriction(): void;
|
|
207
|
+
askForOffer(reason: CancelReason): void;
|
|
208
|
+
dismissFriction(): void;
|
|
209
|
+
private ledgerSet;
|
|
210
|
+
private platform;
|
|
121
211
|
setPushToken(token: string | null, platform?: string): Promise<void>;
|
|
122
212
|
private sendPushToken;
|
|
123
213
|
open(conversationId?: string | null): void;
|
|
@@ -149,5 +239,8 @@ export declare class SupportClient {
|
|
|
149
239
|
get reconnectAttempts(): number;
|
|
150
240
|
disconnect(): void;
|
|
151
241
|
stop(): void;
|
|
242
|
+
deleteMyData(): Promise<'done' | 'pending'>;
|
|
243
|
+
private erasing;
|
|
244
|
+
private flushErase;
|
|
152
245
|
reset(): Promise<void>;
|
|
153
246
|
}
|
package/dist/client.js
CHANGED
|
@@ -2,6 +2,11 @@
|
|
|
2
2
|
// conversations and messages over HTTP, live replies over the /support/v1/stream WebSocket with reconnect and backoff,
|
|
3
3
|
// an offline send queue with optimistic messages, and a pull for anything missed. No React Native imports, so it runs
|
|
4
4
|
// (and is tested) under plain Node as well as in the app.
|
|
5
|
+
let installAnalytics = null;
|
|
6
|
+
export function registerAnalytics(a) {
|
|
7
|
+
installAnalytics = a;
|
|
8
|
+
}
|
|
9
|
+
export const actionsOf = (m) => (Array.isArray(m.meta?.['actions']) ? m.meta['actions'].filter((a) => a && typeof a.kind === 'string' && typeof a.label === 'string').slice(0, 3) : []);
|
|
5
10
|
// Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
|
|
6
11
|
// queued = waiting to send: offline, or the last attempt hit a network error, 5xx or 429 (it goes out on its own).
|
|
7
12
|
export function receiptOf(m, list, conv, offline = false) {
|
|
@@ -26,7 +31,10 @@ export class HttpError extends Error {
|
|
|
26
31
|
this.status = status;
|
|
27
32
|
}
|
|
28
33
|
}
|
|
29
|
-
const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' };
|
|
34
|
+
const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push', consent: 'shotik.support.aiConsent', review: 'shotik.support.review', erase: 'shotik.support.erase' };
|
|
35
|
+
const DAY = 86400000;
|
|
36
|
+
const FRICTION_N = 3;
|
|
37
|
+
const FRICTION_QUIET_MS = 7 * DAY;
|
|
30
38
|
const LOCAL_CONV = 'local_conv_';
|
|
31
39
|
export function memoryStorage() {
|
|
32
40
|
const m = new Map();
|
|
@@ -43,7 +51,14 @@ function localId(prefix) {
|
|
|
43
51
|
export class SupportClient {
|
|
44
52
|
constructor(config) {
|
|
45
53
|
this.listeners = new Set();
|
|
46
|
-
this.state = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} };
|
|
54
|
+
this.state = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {}, aiConsent: null, subscription: null, widget: null, friction: null };
|
|
55
|
+
this.subscriptionSet = false;
|
|
56
|
+
this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 };
|
|
57
|
+
this.session_ = { friction: false, chipShown: false, counts: new Map() };
|
|
58
|
+
this.pendingTrigger = null;
|
|
59
|
+
this.offerShown = null;
|
|
60
|
+
this.eraseTimer = null;
|
|
61
|
+
this.eraseStep = 0;
|
|
47
62
|
this.typingTimers = new Map();
|
|
48
63
|
this.session = null;
|
|
49
64
|
this.anonId = null;
|
|
@@ -66,6 +81,7 @@ export class SupportClient {
|
|
|
66
81
|
this.listeners.add(fn);
|
|
67
82
|
return () => void this.listeners.delete(fn);
|
|
68
83
|
};
|
|
84
|
+
this.platform = null;
|
|
69
85
|
this.config = { ...config, serverUrl: config.serverUrl.replace(/\/+$/, '') };
|
|
70
86
|
this.storage = config.storage ?? memoryStorage();
|
|
71
87
|
}
|
|
@@ -90,7 +106,14 @@ export class SupportClient {
|
|
|
90
106
|
}
|
|
91
107
|
load() {
|
|
92
108
|
this.loaded ?? (this.loaded = (async () => {
|
|
93
|
-
const [anon, session, queue, read, push] = await Promise.all([K.anon, K.session, K.queue, K.read, K.push].map((k) => this.storage.get(k).catch(() => null)));
|
|
109
|
+
const [anon, session, queue, read, push, consent, review] = await Promise.all([K.anon, K.session, K.queue, K.read, K.push, K.consent, K.review].map((k) => this.storage.get(k).catch(() => null)));
|
|
110
|
+
const aiConsent = consent === 'true' ? true : consent === 'false' ? false : (this.config.aiConsent ?? null);
|
|
111
|
+
if (aiConsent !== this.state.aiConsent)
|
|
112
|
+
this.set({ aiConsent });
|
|
113
|
+
if (review)
|
|
114
|
+
this.ledger = { ...this.ledger, ...JSON.parse(review) };
|
|
115
|
+
else
|
|
116
|
+
this.persist(K.review, this.ledger);
|
|
94
117
|
this.anonId = anon ?? localId('anon_');
|
|
95
118
|
if (!anon)
|
|
96
119
|
await this.storage.set(K.anon, this.anonId).catch(() => { });
|
|
@@ -104,6 +127,8 @@ export class SupportClient {
|
|
|
104
127
|
messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, q.attempts ? 'waiting' : 'sending')];
|
|
105
128
|
this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) });
|
|
106
129
|
}
|
|
130
|
+
if ((await this.erasing()).length)
|
|
131
|
+
void this.flushErase();
|
|
107
132
|
})());
|
|
108
133
|
return this.loaded;
|
|
109
134
|
}
|
|
@@ -148,6 +173,7 @@ export class SupportClient {
|
|
|
148
173
|
await this.load();
|
|
149
174
|
this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null });
|
|
150
175
|
const device = await Promise.resolve(this.config.device?.()).catch(() => undefined);
|
|
176
|
+
this.platform = device?.platform?.toLowerCase() ?? null;
|
|
151
177
|
const r = await this.request('POST', '/support/v1/identify', {
|
|
152
178
|
anonymousId: this.anonId,
|
|
153
179
|
userId: this.user.userId,
|
|
@@ -156,7 +182,9 @@ export class SupportClient {
|
|
|
156
182
|
attributes: this.user.attributes,
|
|
157
183
|
device: device ?? undefined,
|
|
158
184
|
appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
|
|
159
|
-
locale: device?.locale
|
|
185
|
+
locale: device?.locale,
|
|
186
|
+
aiConsent: this.state.aiConsent ?? undefined,
|
|
187
|
+
subscription: this.subscriptionSet ? this.state.subscription : undefined
|
|
160
188
|
});
|
|
161
189
|
const changed = this.session?.userId !== r.user.id;
|
|
162
190
|
this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null };
|
|
@@ -167,6 +195,7 @@ export class SupportClient {
|
|
|
167
195
|
if (changed || !this.ws)
|
|
168
196
|
this.connect(true);
|
|
169
197
|
this.scheduleFlush(0);
|
|
198
|
+
this.loadWidget().catch(() => { });
|
|
170
199
|
};
|
|
171
200
|
const p = (this.identifying ?? Promise.resolve()).then(run, run);
|
|
172
201
|
this.identifying = p.catch((e) => {
|
|
@@ -181,6 +210,154 @@ export class SupportClient {
|
|
|
181
210
|
ensureIdentified() {
|
|
182
211
|
return this.identifying ? this.identifying : this.identify();
|
|
183
212
|
}
|
|
213
|
+
// AI-drafted replies (Apple 5.1.2(i)): true lets the founder's AI draft answers, false keeps the chat person-only.
|
|
214
|
+
setAiConsent(allowed) {
|
|
215
|
+
this.storage.set(K.consent, String(allowed)).catch(() => { });
|
|
216
|
+
this.set({ aiConsent: allowed });
|
|
217
|
+
return this.session ? this.identify() : Promise.resolve();
|
|
218
|
+
}
|
|
219
|
+
// The subscription the founder sees next to the chat and the widget's Subscription screen shows (null: none).
|
|
220
|
+
setSubscription(sub) {
|
|
221
|
+
this.subscriptionSet = true;
|
|
222
|
+
this.set({ subscription: sub });
|
|
223
|
+
return this.session ? this.identify() : Promise.resolve();
|
|
224
|
+
}
|
|
225
|
+
async loadWidget() {
|
|
226
|
+
const w = await this.request('GET', '/support/v1/config');
|
|
227
|
+
this.set({ widget: w });
|
|
228
|
+
}
|
|
229
|
+
// Reports what the user did in the widget; with a conversation it shows in the founder's timeline. Best effort.
|
|
230
|
+
track(kind, data = {}, conversationId) {
|
|
231
|
+
if (kind === 'refund_requested' || kind === 'cancel_continued')
|
|
232
|
+
this.ledgerSet({ refundOrCancelAt: Date.now() });
|
|
233
|
+
if (kind === 'offer_shown')
|
|
234
|
+
this.offerShown = data['reason'];
|
|
235
|
+
if (kind === 'offer_shown' && this.state.widget)
|
|
236
|
+
this.set({ widget: { ...this.state.widget, offers: {}, offerEligible: false } });
|
|
237
|
+
this.ensureIdentified()
|
|
238
|
+
.then(() => this.request('POST', '/support/v1/events', { kind, data, conversationId: conversationId && !conversationId.startsWith(LOCAL_CONV) ? conversationId : undefined }))
|
|
239
|
+
.catch(() => { });
|
|
240
|
+
}
|
|
241
|
+
// Runs an action from a message: the host's onAction, else the store URL fallbacks. The founder sees the outcome.
|
|
242
|
+
async runAction(action, conversationId) {
|
|
243
|
+
let result = 'failed';
|
|
244
|
+
try {
|
|
245
|
+
const r = this.config.onAction ? await this.config.onAction(action) : undefined;
|
|
246
|
+
result = r ?? (this.config.onAction && action.kind === 'custom' ? 'done' : this.openFallback(action));
|
|
247
|
+
}
|
|
248
|
+
catch {
|
|
249
|
+
result = 'failed';
|
|
250
|
+
}
|
|
251
|
+
this.track('action', { actionId: action.id, action: action.kind, label: action.label, result }, conversationId);
|
|
252
|
+
return result;
|
|
253
|
+
}
|
|
254
|
+
// The store pages that do the job when the host has no handler (iOS first; Android goes to Play's subscriptions).
|
|
255
|
+
fallbackUrl(action) {
|
|
256
|
+
const android = this.platform === 'android';
|
|
257
|
+
const id = this.config.appStoreId;
|
|
258
|
+
switch (action.kind) {
|
|
259
|
+
case 'manage_subscription':
|
|
260
|
+
return android ? 'https://play.google.com/store/account/subscriptions' : 'https://apps.apple.com/account/subscriptions';
|
|
261
|
+
case 'request_refund':
|
|
262
|
+
return android ? null : 'https://reportaproblem.apple.com';
|
|
263
|
+
case 'redeem_code':
|
|
264
|
+
return !android && id && action.value ? 'https://apps.apple.com/redeem?ctx=offercodes&id=' + id + '&code=' + encodeURIComponent(action.value) : null;
|
|
265
|
+
case 'write_review':
|
|
266
|
+
return !android && id ? 'https://apps.apple.com/app/id' + id + '?action=write-review' : null;
|
|
267
|
+
case 'open_url':
|
|
268
|
+
return action.value && /^https:\/\//.test(action.value) ? action.value : null;
|
|
269
|
+
default:
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
openFallback(action) {
|
|
274
|
+
const url = this.fallbackUrl(action);
|
|
275
|
+
if (!url || !this.config.openUrl)
|
|
276
|
+
return 'failed';
|
|
277
|
+
this.config.openUrl(url);
|
|
278
|
+
return 'done';
|
|
279
|
+
}
|
|
280
|
+
// "Did this help?" on a resolved conversation (CSAT): 1 or -1 and an optional line.
|
|
281
|
+
async rate(conversationId, score, comment) {
|
|
282
|
+
this.set({ conversations: this.state.conversations.map((c) => (c.id === conversationId ? { ...c, csat: score } : c)) });
|
|
283
|
+
await this.request('POST', '/support/v1/conversations/' + conversationId + '/rating', { score, comment });
|
|
284
|
+
}
|
|
285
|
+
// A success moment in the app (a goal reached, a streak, a finished lesson). Asks the store's review prompt only when
|
|
286
|
+
// the founder's rules pass: enough of this moment, days since install, not yet in this version, under the yearly cap,
|
|
287
|
+
// and no friction in this session or the quiet days after friction, a refund or a cancel. Returns whether it asked.
|
|
288
|
+
async reviewMoment(name) {
|
|
289
|
+
await this.load();
|
|
290
|
+
const counts = { ...this.ledger.counts, [name]: (this.ledger.counts[name] ?? 0) + 1 };
|
|
291
|
+
this.ledgerSet({ counts });
|
|
292
|
+
const rules = this.state.widget?.review;
|
|
293
|
+
const need = rules?.moments[name];
|
|
294
|
+
if (!rules || !need || !this.config.requestReview)
|
|
295
|
+
return false;
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
const version = (await Promise.resolve(this.config.device?.()).catch(() => undefined))?.appVersion ?? '';
|
|
298
|
+
const ok = counts[name] >= need &&
|
|
299
|
+
now - this.ledger.installAt >= rules.minDaysSinceInstall * DAY &&
|
|
300
|
+
!this.ledger.versions.includes(version) &&
|
|
301
|
+
this.ledger.prompts.filter((t) => now - t < 365 * DAY).length < rules.maxPerYear &&
|
|
302
|
+
!this.session_.friction &&
|
|
303
|
+
now - this.ledger.frictionAt >= rules.quietDaysAfterFriction * DAY &&
|
|
304
|
+
now - this.ledger.refundOrCancelAt >= rules.quietDaysAfterRefundOrCancel * DAY;
|
|
305
|
+
if (!ok)
|
|
306
|
+
return false;
|
|
307
|
+
this.ledgerSet({ prompts: [...this.ledger.prompts, now].slice(-10), versions: [...this.ledger.versions, version].slice(-20) });
|
|
308
|
+
await Promise.resolve(this.config.requestReview()).catch(() => { });
|
|
309
|
+
this.track('review_prompt', { moment: name, version });
|
|
310
|
+
return true;
|
|
311
|
+
}
|
|
312
|
+
// Friction from the app (analytics onEvent, or the host directly): a failed purchase opens the help chip at once;
|
|
313
|
+
// rage taps on one element or the same error three times in a session do too. Once per session, never on quiet screens,
|
|
314
|
+
// and not for a week after the user tapped "Not now".
|
|
315
|
+
friction(f) {
|
|
316
|
+
const now = Date.now();
|
|
317
|
+
this.session_.friction = true;
|
|
318
|
+
this.ledgerSet({ frictionAt: now });
|
|
319
|
+
const key = f.kind + '|' + (f.element ?? '') + '|' + (f.kind === 'rage' ? '' : (f.screen ?? ''));
|
|
320
|
+
const n = (this.session_.counts.get(key) ?? 0) + 1;
|
|
321
|
+
this.session_.counts.set(key, n);
|
|
322
|
+
if (n < (f.kind === 'error' ? FRICTION_N : 1))
|
|
323
|
+
return;
|
|
324
|
+
if (this.session_.chipShown || now - this.ledger.frictionDismissedAt < FRICTION_QUIET_MS)
|
|
325
|
+
return;
|
|
326
|
+
if (f.screen && this.state.widget?.quietScreens.includes(f.screen))
|
|
327
|
+
return;
|
|
328
|
+
this.session_.chipShown = true;
|
|
329
|
+
this.set({ friction: f });
|
|
330
|
+
this.track('friction_shown', { friction: f.kind, screen: f.screen ?? '', element: f.element ?? '' });
|
|
331
|
+
}
|
|
332
|
+
// The user tapped the chip: the next message starts a conversation that carries what happened.
|
|
333
|
+
openFriction() {
|
|
334
|
+
const f = this.state.friction;
|
|
335
|
+
if (!f)
|
|
336
|
+
return;
|
|
337
|
+
this.pendingTrigger = f;
|
|
338
|
+
this.track('friction_opened', { friction: f.kind });
|
|
339
|
+
this.set({ friction: null, open: true, activeConversationId: null });
|
|
340
|
+
}
|
|
341
|
+
// The user took the save offer for this cancel reason: the widget opens on a new conversation that goes to the founder.
|
|
342
|
+
// Showing the offer empties widget.offers for the cooldown, so the reason shown on screen still counts.
|
|
343
|
+
askForOffer(reason) {
|
|
344
|
+
if (!this.state.widget?.offers[reason] && this.offerShown !== reason)
|
|
345
|
+
return;
|
|
346
|
+
this.pendingTrigger = { kind: 'offer', element: reason };
|
|
347
|
+
this.track('offer_accepted', { reason });
|
|
348
|
+
this.set({ open: true, activeConversationId: null });
|
|
349
|
+
}
|
|
350
|
+
dismissFriction() {
|
|
351
|
+
if (!this.state.friction)
|
|
352
|
+
return;
|
|
353
|
+
this.ledgerSet({ frictionDismissedAt: Date.now() });
|
|
354
|
+
this.track('friction_dismissed', { friction: this.state.friction.kind });
|
|
355
|
+
this.set({ friction: null });
|
|
356
|
+
}
|
|
357
|
+
ledgerSet(p) {
|
|
358
|
+
this.ledger = { ...this.ledger, ...p };
|
|
359
|
+
this.persist(K.review, this.ledger);
|
|
360
|
+
}
|
|
184
361
|
async setPushToken(token, platform = 'ios') {
|
|
185
362
|
await this.load();
|
|
186
363
|
this.pushToken = token ? { token, platform } : null;
|
|
@@ -234,7 +411,9 @@ export class SupportClient {
|
|
|
234
411
|
if (!text && !attachments.length)
|
|
235
412
|
return null;
|
|
236
413
|
const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('');
|
|
237
|
-
const
|
|
414
|
+
const trigger = convId.startsWith(LOCAL_CONV) && this.pendingTrigger ? this.pendingTrigger : null;
|
|
415
|
+
this.pendingTrigger = null;
|
|
416
|
+
const item = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}), ...(trigger ? { trigger } : {}) };
|
|
238
417
|
this.queue.push(item);
|
|
239
418
|
this.persist(K.queue, this.queue);
|
|
240
419
|
const msg = this.optimistic(item, 'sending');
|
|
@@ -373,6 +552,8 @@ export class SupportClient {
|
|
|
373
552
|
const meta = { localId: item.localId };
|
|
374
553
|
if (item.attachments?.length)
|
|
375
554
|
meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }));
|
|
555
|
+
if (item.trigger)
|
|
556
|
+
meta['trigger'] = item.trigger;
|
|
376
557
|
if (item.conversationId.startsWith(LOCAL_CONV)) {
|
|
377
558
|
const r = await this.request('POST', '/support/v1/conversations', { body: item.body, meta });
|
|
378
559
|
this.remapConversation(item.conversationId, r.conversation);
|
|
@@ -461,6 +642,8 @@ export class SupportClient {
|
|
|
461
642
|
else
|
|
462
643
|
this.pull().catch(() => { });
|
|
463
644
|
this.scheduleFlush(0);
|
|
645
|
+
if (this.eraseTimer)
|
|
646
|
+
void this.flushErase();
|
|
464
647
|
}
|
|
465
648
|
connect(resetBackoff = false) {
|
|
466
649
|
if (this.stopped || !this.session)
|
|
@@ -571,14 +754,68 @@ export class SupportClient {
|
|
|
571
754
|
}
|
|
572
755
|
stop() {
|
|
573
756
|
this.stopped = true;
|
|
574
|
-
for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()])
|
|
757
|
+
for (const t of [this.reconnectTimer, this.flushTimer, this.eraseTimer, ...this.typingTimers.values()])
|
|
575
758
|
if (t)
|
|
576
759
|
clearTimeout(t);
|
|
577
760
|
this.typingTimers.clear();
|
|
578
|
-
this.reconnectTimer = this.flushTimer = null;
|
|
761
|
+
this.reconnectTimer = this.flushTimer = this.eraseTimer = null;
|
|
579
762
|
this.disconnect();
|
|
580
763
|
this.set({ status: 'idle' });
|
|
581
764
|
}
|
|
765
|
+
// Delete my data (Apple 5.1.1(v), GDPR erase; PROTOCOL.md §3.13). The device forgets at once: conversations, queue,
|
|
766
|
+
// ids, the review ledger and the install's analytics (config.analytics, else ShotikAnalytics). Then the server erases
|
|
767
|
+
// what this install's support and analytics recorded. Offline, the request waits on the device and is retried with
|
|
768
|
+
// backoff, after an app restart too. Resolves 'done' once the server confirmed, 'pending' while it waits to retry.
|
|
769
|
+
async deleteMyData() {
|
|
770
|
+
await this.load();
|
|
771
|
+
const token = this.session?.userToken;
|
|
772
|
+
if (token) {
|
|
773
|
+
const list = await this.erasing();
|
|
774
|
+
if (!list.includes(token))
|
|
775
|
+
await this.storage.set(K.erase, JSON.stringify([...list, token])).catch(() => { });
|
|
776
|
+
}
|
|
777
|
+
await this.reset();
|
|
778
|
+
this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 };
|
|
779
|
+
this.pushToken = null;
|
|
780
|
+
await Promise.all([this.storage.remove(K.review), this.storage.remove(K.push)]).catch(() => { });
|
|
781
|
+
const a = this.config.analytics === undefined ? installAnalytics : this.config.analytics;
|
|
782
|
+
if (a && !(await a.forget().catch(() => false)))
|
|
783
|
+
await Promise.resolve(a.reset()).catch(() => { });
|
|
784
|
+
this.anonId = (await this.storage.get(K.anon).catch(() => null)) ?? this.anonId;
|
|
785
|
+
return this.flushErase();
|
|
786
|
+
}
|
|
787
|
+
async erasing() {
|
|
788
|
+
try {
|
|
789
|
+
return JSON.parse((await this.storage.get(K.erase)) ?? '[]');
|
|
790
|
+
}
|
|
791
|
+
catch {
|
|
792
|
+
return [];
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
async flushErase() {
|
|
796
|
+
if (this.eraseTimer)
|
|
797
|
+
clearTimeout(this.eraseTimer);
|
|
798
|
+
this.eraseTimer = null;
|
|
799
|
+
let left = await this.erasing();
|
|
800
|
+
for (const token of left) {
|
|
801
|
+
const status = await fetch(this.config.serverUrl + '/support/v1/erase', { method: 'POST', headers: { 'x-shotik-key': this.config.appKey, 'x-shotik-user': token, 'content-type': 'application/json' }, body: '{}' })
|
|
802
|
+
.then((r) => r.status)
|
|
803
|
+
.catch(() => 0);
|
|
804
|
+
if (status === 0 || status === 429 || status >= 500)
|
|
805
|
+
continue;
|
|
806
|
+
left = left.filter((t) => t !== token);
|
|
807
|
+
}
|
|
808
|
+
await (left.length ? this.storage.set(K.erase, JSON.stringify(left)) : this.storage.remove(K.erase)).catch(() => { });
|
|
809
|
+
if (!left.length) {
|
|
810
|
+
this.eraseStep = 0;
|
|
811
|
+
return 'done';
|
|
812
|
+
}
|
|
813
|
+
if (!this.stopped) {
|
|
814
|
+
this.eraseTimer = setTimeout(() => void this.flushErase(), Math.min(300000, 2000 * 2 ** this.eraseStep++));
|
|
815
|
+
this.eraseTimer.unref?.();
|
|
816
|
+
}
|
|
817
|
+
return 'pending';
|
|
818
|
+
}
|
|
582
819
|
// Sign-out: forget the identified user and start over as a new anonymous user.
|
|
583
820
|
async reset() {
|
|
584
821
|
await this.load();
|
|
@@ -589,7 +826,8 @@ export class SupportClient {
|
|
|
589
826
|
this.readAt = {};
|
|
590
827
|
this.full.clear();
|
|
591
828
|
this.anonId = localId('anon_');
|
|
592
|
-
|
|
593
|
-
this.set(
|
|
829
|
+
this.subscriptionSet = false;
|
|
830
|
+
await Promise.all([this.storage.set(K.anon, this.anonId), this.storage.remove(K.session), this.storage.remove(K.queue), this.storage.remove(K.read), this.storage.remove(K.consent)]).catch(() => { });
|
|
831
|
+
this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {}, aiConsent: this.config.aiConsent ?? null, subscription: null, friction: null });
|
|
594
832
|
}
|
|
595
833
|
}
|