@shotik/react-native 0.1.0 → 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.
Files changed (46) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/LICENSE +26 -0
  3. package/README.md +39 -3
  4. package/README.ru.md +40 -3
  5. package/dist/analytics/core.d.ts +96 -11
  6. package/dist/analytics/core.js +295 -22
  7. package/dist/analytics/privacy.d.ts +4 -0
  8. package/dist/analytics/privacy.js +46 -0
  9. package/dist/analytics/replay.d.ts +41 -0
  10. package/dist/analytics/replay.js +192 -0
  11. package/dist/analytics/rn.d.ts +52 -2
  12. package/dist/analytics/rn.js +669 -62
  13. package/dist/analytics/wire.d.ts +54 -2
  14. package/dist/analytics/wire.js +44 -4
  15. package/dist/client.d.ts +94 -1
  16. package/dist/client.js +254 -17
  17. package/dist/flow.d.ts +48 -0
  18. package/dist/flow.js +56 -0
  19. package/dist/index.d.ts +4 -4
  20. package/dist/index.js +2 -2
  21. package/dist/parts.d.ts +42 -1
  22. package/dist/parts.js +72 -14
  23. package/dist/react.d.ts +24 -3
  24. package/dist/react.js +42 -15
  25. package/dist/sheet.d.ts +2 -1
  26. package/dist/sheet.js +207 -16
  27. package/dist/support.js +2 -2
  28. package/dist/theme.d.ts +43 -0
  29. package/dist/theme.js +90 -4
  30. package/package.json +15 -2
  31. package/recipe.json +1 -1
  32. package/src/analytics/README.md +10 -6
  33. package/src/analytics/core.ts +314 -25
  34. package/src/analytics/privacy.ts +50 -0
  35. package/src/analytics/recipe.json +1 -1
  36. package/src/analytics/replay.ts +190 -0
  37. package/src/analytics/rn.tsx +620 -63
  38. package/src/analytics/wire.ts +99 -8
  39. package/src/client.ts +344 -19
  40. package/src/flow.ts +100 -0
  41. package/src/index.ts +4 -4
  42. package/src/parts.tsx +102 -14
  43. package/src/react.tsx +57 -16
  44. package/src/sheet.tsx +423 -20
  45. package/src/support.ts +2 -2
  46. package/src/theme.ts +90 -4
package/src/client.ts CHANGED
@@ -3,6 +3,17 @@
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
5
 
6
+ // What one install shares between Support and Analytics: Delete my data erases both. ShotikAnalytics.init registers
7
+ // itself here, so the widget's row reaches it without the host wiring anything.
8
+ export interface ErasableAnalytics {
9
+ forget(): Promise<boolean>
10
+ reset(): Promise<void> | void
11
+ }
12
+ let installAnalytics: ErasableAnalytics | null = null
13
+ export function registerAnalytics(a: ErasableAnalytics | null): void {
14
+ installAnalytics = a
15
+ }
16
+
6
17
  export type Author = 'user' | 'ai' | 'founder' | 'system'
7
18
  export type ConversationStatus = 'open' | 'needs_human' | 'resolved' | 'closed' | string
8
19
  export type Status = 'idle' | 'identifying' | 'connecting' | 'live' | 'offline' | 'error'
@@ -17,7 +28,63 @@ export interface Conversation {
17
28
  createdAt: number
18
29
  // User messages the founder has not read yet; 0 means everything you sent was seen.
19
30
  founderUnread?: number
31
+ // "Did this help?" answer once the conversation was resolved: 1, -1, or null (not asked or not answered yet).
32
+ csat?: 1 | -1 | null
33
+ }
34
+
35
+ // The user's subscription as the host app knows it (StoreKit 2, RevenueCat, Play Billing), PROTOCOL.md §3.8.
36
+ export interface Subscription {
37
+ status: 'trial' | 'active' | 'grace' | 'billing_retry' | 'cancelled' | 'expired' | 'refunded' | 'none'
38
+ product?: string | null
39
+ period?: 'P1W' | 'P1M' | 'P3M' | 'P6M' | 'P1Y' | 'lifetime' | null
40
+ price?: string | null
41
+ renewsAt?: number | null
42
+ expiresAt?: number | null
43
+ trialEndsAt?: number | null
44
+ willRenew?: boolean | null
45
+ store?: 'app_store' | 'play' | 'stripe' | null
46
+ }
47
+
48
+ // A native button under a founder or AI message (PROTOCOL.md §3.9).
49
+ export type ActionKind = 'manage_subscription' | 'restore' | 'redeem_code' | 'change_plan' | 'request_refund' | 'open_url' | 'write_review' | 'custom'
50
+ export interface SupportAction {
51
+ id: string
52
+ kind: ActionKind
53
+ label: string
54
+ value?: string | null
55
+ }
56
+ export type ActionResult = 'done' | 'cancelled' | 'failed'
57
+ export const actionsOf = (m: Message): SupportAction[] => (Array.isArray(m.meta?.['actions']) ? (m.meta['actions'] as SupportAction[]).filter((a) => a && typeof a.kind === 'string' && typeof a.label === 'string').slice(0, 3) : [])
58
+
59
+ export type CancelReason = 'too_expensive' | 'not_using' | 'bug' | 'mistake' | 'other'
60
+ // A save offer as the device sees it: the founder's words only. askForOffer() asks the founder, whose click sends the
61
+ // code or the plan change (nothing that touches money reaches the user without it).
62
+ export interface Offer {
63
+ kind: 'chat'
64
+ label: string
65
+ }
66
+ // The founder's widget settings for this user (GET /support/v1/config): one save offer per cancel reason (empty while
67
+ // this user is inside the offer cooldown), review rules, screens where the friction chip stays quiet, custom actions.
68
+ export interface WidgetConfig {
69
+ offers: Partial<Record<CancelReason, Offer>>
70
+ offerEligible: boolean
71
+ review: { moments: Record<string, number>; minDaysSinceInstall: number; maxPerYear: number; quietDaysAfterFriction: number; quietDaysAfterRefundOrCancel: number }
72
+ quietScreens: string[]
73
+ customActions: { id: string; label: string }[]
74
+ }
75
+
76
+ // What the friction chip offers help for (PROTOCOL.md §3.12).
77
+ export interface Friction {
78
+ kind: 'purchase_fail' | 'rage' | 'error'
79
+ screen?: string | null
80
+ element?: string | null
20
81
  }
82
+ // Why a conversation started: the friction chip, or a save offer the user asked for (element = the cancel reason).
83
+ export type Trigger = Friction | { kind: 'offer'; screen?: null; element: CancelReason }
84
+
85
+ export type SupportEventKind =
86
+ | 'action' | 'cancel_started' | 'cancel_reason' | 'offer_shown' | 'offer_accepted' | 'cancel_continued' | 'refund_help' | 'refund_requested'
87
+ | 'review_prompt' | 'friction_shown' | 'friction_opened' | 'friction_dismissed'
21
88
 
22
89
  // A picked photo or screenshot before upload (uri: file:// or data:), and the uploaded form in message meta.
23
90
  export interface LocalAttachment {
@@ -50,7 +117,7 @@ export interface Message {
50
117
  // When the message reached the other side (Shotik for yours, the device for replies).
51
118
  deliveredAt?: number | null
52
119
  localId?: string
53
- pending?: 'sending' | 'failed'
120
+ pending?: 'sending' | 'waiting' | 'failed'
54
121
  }
55
122
 
56
123
  export interface UserInfo {
@@ -81,6 +148,18 @@ export interface SupportConfig {
81
148
  serverUrl: string
82
149
  storage?: KeyValueStorage
83
150
  device?: () => DeviceInfo | Promise<DeviceInfo>
151
+ // Consent the host app already collected for AI-drafted replies (Apple 5.1.2(i)); the widget asks when it's unset.
152
+ aiConsent?: boolean
153
+ // Runs an action tapped under a message (StoreKit, RevenueCat or the app's own code). Return the outcome; without a
154
+ // handler the URL fallbacks open through openUrl (Manage subscription, refund, redeem code, review, links).
155
+ onAction?: (action: SupportAction) => ActionResult | void | Promise<ActionResult | void>
156
+ openUrl?: (url: string) => unknown
157
+ // The native review prompt (StoreKit requestReview / Play In-App Review). Called only by reviewMoment() when every rule passes.
158
+ requestReview?: () => unknown
159
+ // The App Store id (numbers only), for the write-review and redeem-code links.
160
+ appStoreId?: string
161
+ // The install's analytics, erased with Delete my data. Defaults to ShotikAnalytics once it is initialized.
162
+ analytics?: ErasableAnalytics | null
84
163
  }
85
164
 
86
165
  export interface SupportState {
@@ -95,6 +174,12 @@ export interface SupportState {
95
174
  error: string | null
96
175
  // Who is typing in each conversation right now (the AI drafting or the founder in Shotik).
97
176
  typing: Record<string, Typing>
177
+ // AI-drafted replies: allowed, refused ("only a person"), or not asked yet (null).
178
+ aiConsent: boolean | null
179
+ subscription: Subscription | null
180
+ widget: WidgetConfig | null
181
+ // The friction chip to show now, or null.
182
+ friction: Friction | null
98
183
  }
99
184
 
100
185
  interface QueueItem {
@@ -104,14 +189,15 @@ interface QueueItem {
104
189
  createdAt: number
105
190
  attempts: number
106
191
  attachments?: (LocalAttachment & { remote?: Attachment })[]
192
+ trigger?: Trigger
107
193
  }
108
194
 
109
195
  // Receipt for one of your messages: sending -> sent -> delivered (reached Shotik) -> seen (the founder read it).
110
- // queued = waiting for the network.
196
+ // queued = waiting to send: offline, or the last attempt hit a network error, 5xx or 429 (it goes out on its own).
111
197
  export function receiptOf(m: Message, list: Message[], conv: Conversation | undefined, offline = false): Receipt | null {
112
198
  if (m.author !== 'user') return null
113
199
  if (m.pending === 'failed') return 'failed'
114
- if (m.pending) return offline ? 'queued' : 'sending'
200
+ if (m.pending) return offline || m.pending === 'waiting' ? 'queued' : 'sending'
115
201
  const unseen = conv?.founderUnread ?? null
116
202
  if (unseen !== null) {
117
203
  const mine = list.filter((x) => x.author === 'user' && !x.pending)
@@ -136,9 +222,22 @@ export class HttpError extends Error {
136
222
  }
137
223
  }
138
224
 
139
- const K = { anon: 'shotik.support.anon', session: 'shotik.support.session', queue: 'shotik.support.queue', read: 'shotik.support.read', push: 'shotik.support.push' }
225
+ 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' }
226
+ const DAY = 86_400_000
227
+ const FRICTION_N = 3
228
+ const FRICTION_QUIET_MS = 7 * DAY
229
+
230
+ // Review prompt ledger, kept on the device (PROTOCOL.md §3.11).
231
+ interface ReviewLedger {
232
+ installAt: number
233
+ counts: Record<string, number>
234
+ prompts: number[]
235
+ versions: string[]
236
+ frictionAt: number
237
+ refundOrCancelAt: number
238
+ frictionDismissedAt: number
239
+ }
140
240
  const LOCAL_CONV = 'local_conv_'
141
- const AUTO_RETRIES = 3
142
241
 
143
242
  export function memoryStorage(): KeyValueStorage {
144
243
  const m = new Map<string, string>()
@@ -159,7 +258,14 @@ export class SupportClient {
159
258
  readonly config: SupportConfig
160
259
  private storage: KeyValueStorage
161
260
  private listeners = new Set<(s: SupportState) => void>()
162
- private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {} }
261
+ private state: SupportState = { status: 'idle', userId: null, conversations: [], messages: {}, unread: 0, unreadBy: {}, open: false, activeConversationId: null, error: null, typing: {}, aiConsent: null, subscription: null, widget: null, friction: null }
262
+ private subscriptionSet = false
263
+ private ledger: ReviewLedger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 }
264
+ private session_ = { friction: false, chipShown: false, counts: new Map<string, number>() }
265
+ private pendingTrigger: Trigger | null = null
266
+ private offerShown: CancelReason | null = null
267
+ private eraseTimer: ReturnType<typeof setTimeout> | null = null
268
+ private eraseStep = 0
163
269
  private typingTimers = new Map<string, ReturnType<typeof setTimeout>>()
164
270
  private session: Session | null = null
165
271
  private anonId: string | null = null
@@ -211,7 +317,11 @@ export class SupportClient {
211
317
 
212
318
  private load(): Promise<void> {
213
319
  this.loaded ??= (async () => {
214
- 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)))
320
+ 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)))
321
+ const aiConsent = consent === 'true' ? true : consent === 'false' ? false : (this.config.aiConsent ?? null)
322
+ if (aiConsent !== this.state.aiConsent) this.set({ aiConsent })
323
+ if (review) this.ledger = { ...this.ledger, ...(JSON.parse(review) as Partial<ReviewLedger>) }
324
+ else this.persist(K.review, this.ledger)
215
325
  this.anonId = anon ?? localId('anon_')
216
326
  if (!anon) await this.storage.set(K.anon, this.anonId).catch(() => {})
217
327
  this.session = session ? (JSON.parse(session) as Session) : null
@@ -220,9 +330,10 @@ export class SupportClient {
220
330
  this.pushToken = push ? (JSON.parse(push) as { token: string; platform: string }) : null
221
331
  if (this.queue.length) {
222
332
  const messages = { ...this.state.messages }
223
- for (const q of this.queue) messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, 'sending')]
333
+ for (const q of this.queue) messages[q.conversationId] = [...(messages[q.conversationId] ?? []), this.optimistic(q, q.attempts ? 'waiting' : 'sending')]
224
334
  this.set({ messages, conversations: this.withLocalConversations(this.state.conversations, messages) })
225
335
  }
336
+ if ((await this.erasing()).length) void this.flushErase()
226
337
  })()
227
338
  return this.loaded
228
339
  }
@@ -266,6 +377,7 @@ export class SupportClient {
266
377
  await this.load()
267
378
  this.set({ status: this.state.status === 'live' ? 'live' : 'identifying', error: null })
268
379
  const device = await Promise.resolve(this.config.device?.()).catch(() => undefined)
380
+ this.platform = device?.platform?.toLowerCase() ?? null
269
381
  const r = await this.request<{ user: { id: string }; userToken: string; conversations: Conversation[] }>('POST', '/support/v1/identify', {
270
382
  anonymousId: this.anonId,
271
383
  userId: this.user.userId,
@@ -274,7 +386,9 @@ export class SupportClient {
274
386
  attributes: this.user.attributes,
275
387
  device: device ?? undefined,
276
388
  appVersion: device?.appVersion ? device.appVersion + (device.build ? ' (' + device.build + ')' : '') : undefined,
277
- locale: device?.locale
389
+ locale: device?.locale,
390
+ aiConsent: this.state.aiConsent ?? undefined,
391
+ subscription: this.subscriptionSet ? this.state.subscription : undefined
278
392
  })
279
393
  const changed = this.session?.userId !== r.user.id
280
394
  this.session = { userToken: r.userToken, userId: r.user.id, externalId: this.user.userId ?? null }
@@ -283,6 +397,7 @@ export class SupportClient {
283
397
  if (this.pushToken) await this.sendPushToken().catch(() => {})
284
398
  if (changed || !this.ws) this.connect(true)
285
399
  this.scheduleFlush(0)
400
+ this.loadWidget().catch(() => {})
286
401
  }
287
402
  const p = (this.identifying ?? Promise.resolve()).then(run, run)
288
403
  this.identifying = p.catch((e: Error) => {
@@ -298,6 +413,158 @@ export class SupportClient {
298
413
  return this.identifying ? this.identifying : this.identify()
299
414
  }
300
415
 
416
+ // AI-drafted replies (Apple 5.1.2(i)): true lets the founder's AI draft answers, false keeps the chat person-only.
417
+ setAiConsent(allowed: boolean): Promise<void> {
418
+ this.storage.set(K.consent, String(allowed)).catch(() => {})
419
+ this.set({ aiConsent: allowed })
420
+ return this.session ? this.identify() : Promise.resolve()
421
+ }
422
+
423
+ // The subscription the founder sees next to the chat and the widget's Subscription screen shows (null: none).
424
+ setSubscription(sub: Subscription | null): Promise<void> {
425
+ this.subscriptionSet = true
426
+ this.set({ subscription: sub })
427
+ return this.session ? this.identify() : Promise.resolve()
428
+ }
429
+
430
+ private async loadWidget(): Promise<void> {
431
+ const w = await this.request<WidgetConfig>('GET', '/support/v1/config')
432
+ this.set({ widget: w })
433
+ }
434
+
435
+ // Reports what the user did in the widget; with a conversation it shows in the founder's timeline. Best effort.
436
+ track(kind: SupportEventKind, data: Record<string, string | number | boolean> = {}, conversationId?: string | null): void {
437
+ if (kind === 'refund_requested' || kind === 'cancel_continued') this.ledgerSet({ refundOrCancelAt: Date.now() })
438
+ if (kind === 'offer_shown') this.offerShown = data['reason'] as CancelReason
439
+ if (kind === 'offer_shown' && this.state.widget) this.set({ widget: { ...this.state.widget, offers: {}, offerEligible: false } })
440
+ this.ensureIdentified()
441
+ .then(() => this.request('POST', '/support/v1/events', { kind, data, conversationId: conversationId && !conversationId.startsWith(LOCAL_CONV) ? conversationId : undefined }))
442
+ .catch(() => {})
443
+ }
444
+
445
+ // Runs an action from a message: the host's onAction, else the store URL fallbacks. The founder sees the outcome.
446
+ async runAction(action: SupportAction, conversationId?: string | null): Promise<ActionResult> {
447
+ let result: ActionResult = 'failed'
448
+ try {
449
+ const r = this.config.onAction ? await this.config.onAction(action) : undefined
450
+ result = r ?? (this.config.onAction && action.kind === 'custom' ? 'done' : this.openFallback(action))
451
+ } catch {
452
+ result = 'failed'
453
+ }
454
+ this.track('action', { actionId: action.id, action: action.kind, label: action.label, result }, conversationId)
455
+ return result
456
+ }
457
+
458
+ // The store pages that do the job when the host has no handler (iOS first; Android goes to Play's subscriptions).
459
+ fallbackUrl(action: Pick<SupportAction, 'kind' | 'value'>): string | null {
460
+ const android = this.platform === 'android'
461
+ const id = this.config.appStoreId
462
+ switch (action.kind) {
463
+ case 'manage_subscription':
464
+ return android ? 'https://play.google.com/store/account/subscriptions' : 'https://apps.apple.com/account/subscriptions'
465
+ case 'request_refund':
466
+ return android ? null : 'https://reportaproblem.apple.com'
467
+ case 'redeem_code':
468
+ return !android && id && action.value ? 'https://apps.apple.com/redeem?ctx=offercodes&id=' + id + '&code=' + encodeURIComponent(action.value) : null
469
+ case 'write_review':
470
+ return !android && id ? 'https://apps.apple.com/app/id' + id + '?action=write-review' : null
471
+ case 'open_url':
472
+ return action.value && /^https:\/\//.test(action.value) ? action.value : null
473
+ default:
474
+ return null
475
+ }
476
+ }
477
+
478
+ private openFallback(action: SupportAction): ActionResult {
479
+ const url = this.fallbackUrl(action)
480
+ if (!url || !this.config.openUrl) return 'failed'
481
+ this.config.openUrl(url)
482
+ return 'done'
483
+ }
484
+
485
+ // "Did this help?" on a resolved conversation (CSAT): 1 or -1 and an optional line.
486
+ async rate(conversationId: string, score: 1 | -1, comment?: string): Promise<void> {
487
+ this.set({ conversations: this.state.conversations.map((c) => (c.id === conversationId ? { ...c, csat: score } : c)) })
488
+ await this.request('POST', '/support/v1/conversations/' + conversationId + '/rating', { score, comment })
489
+ }
490
+
491
+ // A success moment in the app (a goal reached, a streak, a finished lesson). Asks the store's review prompt only when
492
+ // the founder's rules pass: enough of this moment, days since install, not yet in this version, under the yearly cap,
493
+ // and no friction in this session or the quiet days after friction, a refund or a cancel. Returns whether it asked.
494
+ async reviewMoment(name: string): Promise<boolean> {
495
+ await this.load()
496
+ const counts = { ...this.ledger.counts, [name]: (this.ledger.counts[name] ?? 0) + 1 }
497
+ this.ledgerSet({ counts })
498
+ const rules = this.state.widget?.review
499
+ const need = rules?.moments[name]
500
+ if (!rules || !need || !this.config.requestReview) return false
501
+ const now = Date.now()
502
+ const version = (await Promise.resolve(this.config.device?.()).catch(() => undefined))?.appVersion ?? ''
503
+ const ok =
504
+ counts[name]! >= need &&
505
+ now - this.ledger.installAt >= rules.minDaysSinceInstall * DAY &&
506
+ !this.ledger.versions.includes(version) &&
507
+ this.ledger.prompts.filter((t) => now - t < 365 * DAY).length < rules.maxPerYear &&
508
+ !this.session_.friction &&
509
+ now - this.ledger.frictionAt >= rules.quietDaysAfterFriction * DAY &&
510
+ now - this.ledger.refundOrCancelAt >= rules.quietDaysAfterRefundOrCancel * DAY
511
+ if (!ok) return false
512
+ this.ledgerSet({ prompts: [...this.ledger.prompts, now].slice(-10), versions: [...this.ledger.versions, version].slice(-20) })
513
+ await Promise.resolve(this.config.requestReview()).catch(() => {})
514
+ this.track('review_prompt', { moment: name, version })
515
+ return true
516
+ }
517
+
518
+ // Friction from the app (analytics onEvent, or the host directly): a failed purchase opens the help chip at once;
519
+ // rage taps on one element or the same error three times in a session do too. Once per session, never on quiet screens,
520
+ // and not for a week after the user tapped "Not now".
521
+ friction(f: Friction): void {
522
+ const now = Date.now()
523
+ this.session_.friction = true
524
+ this.ledgerSet({ frictionAt: now })
525
+ const key = f.kind + '|' + (f.element ?? '') + '|' + (f.kind === 'rage' ? '' : (f.screen ?? ''))
526
+ const n = (this.session_.counts.get(key) ?? 0) + 1
527
+ this.session_.counts.set(key, n)
528
+ if (n < (f.kind === 'error' ? FRICTION_N : 1)) return
529
+ if (this.session_.chipShown || now - this.ledger.frictionDismissedAt < FRICTION_QUIET_MS) return
530
+ if (f.screen && this.state.widget?.quietScreens.includes(f.screen)) return
531
+ this.session_.chipShown = true
532
+ this.set({ friction: f })
533
+ this.track('friction_shown', { friction: f.kind, screen: f.screen ?? '', element: f.element ?? '' })
534
+ }
535
+
536
+ // The user tapped the chip: the next message starts a conversation that carries what happened.
537
+ openFriction(): void {
538
+ const f = this.state.friction
539
+ if (!f) return
540
+ this.pendingTrigger = f
541
+ this.track('friction_opened', { friction: f.kind })
542
+ this.set({ friction: null, open: true, activeConversationId: null })
543
+ }
544
+
545
+ // The user took the save offer for this cancel reason: the widget opens on a new conversation that goes to the founder.
546
+ // Showing the offer empties widget.offers for the cooldown, so the reason shown on screen still counts.
547
+ askForOffer(reason: CancelReason): void {
548
+ if (!this.state.widget?.offers[reason] && this.offerShown !== reason) return
549
+ this.pendingTrigger = { kind: 'offer', element: reason }
550
+ this.track('offer_accepted', { reason })
551
+ this.set({ open: true, activeConversationId: null })
552
+ }
553
+
554
+ dismissFriction(): void {
555
+ if (!this.state.friction) return
556
+ this.ledgerSet({ frictionDismissedAt: Date.now() })
557
+ this.track('friction_dismissed', { friction: this.state.friction.kind })
558
+ this.set({ friction: null })
559
+ }
560
+
561
+ private ledgerSet(p: Partial<ReviewLedger>): void {
562
+ this.ledger = { ...this.ledger, ...p }
563
+ this.persist(K.review, this.ledger)
564
+ }
565
+
566
+ private platform: string | null = null
567
+
301
568
  async setPushToken(token: string | null, platform = 'ios'): Promise<void> {
302
569
  await this.load()
303
570
  this.pushToken = token ? { token, platform } : null
@@ -351,7 +618,9 @@ export class SupportClient {
351
618
  const text = body.trim()
352
619
  if (!text && !attachments.length) return null
353
620
  const convId = conversationId || this.state.activeConversationId || LOCAL_CONV + localId('')
354
- const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}) }
621
+ const trigger = convId.startsWith(LOCAL_CONV) && this.pendingTrigger ? this.pendingTrigger : null
622
+ this.pendingTrigger = null
623
+ const item: QueueItem = { localId: localId('local_'), conversationId: convId, body: text, createdAt: Date.now(), attempts: 0, ...(attachments.length ? { attachments: attachments.slice(0, 4) } : {}), ...(trigger ? { trigger } : {}) }
355
624
  this.queue.push(item)
356
625
  this.persist(K.queue, this.queue)
357
626
  const msg = this.optimistic(item, 'sending')
@@ -385,7 +654,8 @@ export class SupportClient {
385
654
  return this.queue.length
386
655
  }
387
656
 
388
- // Deliver queued messages in order. Network errors and 5xx keep them queued with backoff; a 4xx fails the message.
657
+ // Deliver queued messages in order. Network errors, 5xx and 429 keep them queued as 'waiting' with backoff; another 4xx
658
+ // fails the message.
389
659
  flush(): Promise<void> {
390
660
  this.flushing ??= (async () => {
391
661
  try {
@@ -404,7 +674,7 @@ export class SupportClient {
404
674
  this.identify().catch(() => {})
405
675
  return
406
676
  }
407
- if (status >= 400 && status < 500) {
677
+ if (status >= 400 && status < 500 && status !== 429) {
408
678
  this.queue.shift()
409
679
  this.persist(K.queue, this.queue)
410
680
  this.markPending(item, 'failed')
@@ -412,7 +682,7 @@ export class SupportClient {
412
682
  }
413
683
  item.attempts++
414
684
  this.persist(K.queue, this.queue)
415
- if (item.attempts >= AUTO_RETRIES) this.markPending(item, 'failed')
685
+ this.markPending(item, 'waiting')
416
686
  this.set({ status: this.ws ? this.state.status : 'offline', error: (e as Error).message })
417
687
  this.scheduleFlush(Math.min(30_000, 500 * 2 ** item.attempts))
418
688
  return
@@ -484,6 +754,7 @@ export class SupportClient {
484
754
  private async deliver(item: QueueItem): Promise<void> {
485
755
  const meta: Record<string, unknown> = { localId: item.localId }
486
756
  if (item.attachments?.length) meta['attachments'] = (await this.upload(item)).map((a) => ({ id: a.id }))
757
+ if (item.trigger) meta['trigger'] = item.trigger
487
758
  if (item.conversationId.startsWith(LOCAL_CONV)) {
488
759
  const r = await this.request<{ conversation: Conversation; message: Message }>('POST', '/support/v1/conversations', { body: item.body, meta })
489
760
  this.remapConversation(item.conversationId, r.conversation)
@@ -506,12 +777,12 @@ export class SupportClient {
506
777
  this.set({ messages, conversations: this.sortConvs([conv, ...conversations]), activeConversationId: this.state.activeConversationId === from ? conv.id : this.state.activeConversationId })
507
778
  }
508
779
 
509
- private optimistic(q: QueueItem, pending: 'sending' | 'failed'): Message {
780
+ private optimistic(q: QueueItem, pending: NonNullable<Message['pending']>): Message {
510
781
  const meta = q.attachments?.length ? { attachments: q.attachments.map((a) => ({ uri: a.uri, width: a.width ?? null, height: a.height ?? null, type: a.type ?? 'image/jpeg' })) } : null
511
782
  return { id: q.localId, localId: q.localId, conversationId: q.conversationId, author: 'user', body: q.body, createdAt: q.createdAt, pending, meta }
512
783
  }
513
784
 
514
- private markPending(item: QueueItem, pending: 'sending' | 'failed'): void {
785
+ private markPending(item: QueueItem, pending: NonNullable<Message['pending']>): void {
515
786
  const list = this.state.messages[item.conversationId] ?? []
516
787
  this.set({ messages: { ...this.state.messages, [item.conversationId]: list.map((m) => (m.localId === item.localId ? { ...m, pending } : m)) } })
517
788
  }
@@ -570,6 +841,7 @@ export class SupportClient {
570
841
  if (!this.ws) this.connect(true)
571
842
  else this.pull().catch(() => {})
572
843
  this.scheduleFlush(0)
844
+ if (this.eraseTimer) void this.flushErase()
573
845
  }
574
846
 
575
847
  private connect(resetBackoff = false): void {
@@ -662,13 +934,65 @@ export class SupportClient {
662
934
 
663
935
  stop(): void {
664
936
  this.stopped = true
665
- for (const t of [this.reconnectTimer, this.flushTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
937
+ for (const t of [this.reconnectTimer, this.flushTimer, this.eraseTimer, ...this.typingTimers.values()]) if (t) clearTimeout(t)
666
938
  this.typingTimers.clear()
667
- this.reconnectTimer = this.flushTimer = null
939
+ this.reconnectTimer = this.flushTimer = this.eraseTimer = null
668
940
  this.disconnect()
669
941
  this.set({ status: 'idle' })
670
942
  }
671
943
 
944
+ // Delete my data (Apple 5.1.1(v), GDPR erase; PROTOCOL.md §3.13). The device forgets at once: conversations, queue,
945
+ // ids, the review ledger and the install's analytics (config.analytics, else ShotikAnalytics). Then the server erases
946
+ // what this install's support and analytics recorded. Offline, the request waits on the device and is retried with
947
+ // backoff, after an app restart too. Resolves 'done' once the server confirmed, 'pending' while it waits to retry.
948
+ async deleteMyData(): Promise<'done' | 'pending'> {
949
+ await this.load()
950
+ const token = this.session?.userToken
951
+ if (token) {
952
+ const list = await this.erasing()
953
+ if (!list.includes(token)) await this.storage.set(K.erase, JSON.stringify([...list, token])).catch(() => {})
954
+ }
955
+ await this.reset()
956
+ this.ledger = { installAt: Date.now(), counts: {}, prompts: [], versions: [], frictionAt: 0, refundOrCancelAt: 0, frictionDismissedAt: 0 }
957
+ this.pushToken = null
958
+ await Promise.all([this.storage.remove(K.review), this.storage.remove(K.push)]).catch(() => {})
959
+ const a = this.config.analytics === undefined ? installAnalytics : this.config.analytics
960
+ if (a && !(await a.forget().catch(() => false))) await Promise.resolve(a.reset()).catch(() => {})
961
+ this.anonId = (await this.storage.get(K.anon).catch(() => null)) ?? this.anonId
962
+ return this.flushErase()
963
+ }
964
+
965
+ private async erasing(): Promise<string[]> {
966
+ try {
967
+ return JSON.parse((await this.storage.get(K.erase)) ?? '[]') as string[]
968
+ } catch {
969
+ return []
970
+ }
971
+ }
972
+
973
+ private async flushErase(): Promise<'done' | 'pending'> {
974
+ if (this.eraseTimer) clearTimeout(this.eraseTimer)
975
+ this.eraseTimer = null
976
+ let left = await this.erasing()
977
+ for (const token of left) {
978
+ 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: '{}' })
979
+ .then((r) => r.status)
980
+ .catch(() => 0)
981
+ if (status === 0 || status === 429 || status >= 500) continue
982
+ left = left.filter((t) => t !== token)
983
+ }
984
+ await (left.length ? this.storage.set(K.erase, JSON.stringify(left)) : this.storage.remove(K.erase)).catch(() => {})
985
+ if (!left.length) {
986
+ this.eraseStep = 0
987
+ return 'done'
988
+ }
989
+ if (!this.stopped) {
990
+ this.eraseTimer = setTimeout(() => void this.flushErase(), Math.min(300_000, 2_000 * 2 ** this.eraseStep++))
991
+ ;(this.eraseTimer as { unref?: () => void }).unref?.()
992
+ }
993
+ return 'pending'
994
+ }
995
+
672
996
  // Sign-out: forget the identified user and start over as a new anonymous user.
673
997
  async reset(): Promise<void> {
674
998
  await this.load()
@@ -679,7 +1003,8 @@ export class SupportClient {
679
1003
  this.readAt = {}
680
1004
  this.full.clear()
681
1005
  this.anonId = localId('anon_')
682
- 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)]).catch(() => {})
683
- this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {} })
1006
+ this.subscriptionSet = false
1007
+ 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(() => {})
1008
+ this.set({ userId: null, conversations: [], messages: {}, activeConversationId: null, status: 'idle', error: null, typing: {}, aiConsent: this.config.aiConsent ?? null, subscription: null, friction: null })
684
1009
  }
685
1010
  }
package/src/flow.ts ADDED
@@ -0,0 +1,100 @@
1
+ // The widget's v1.1 logic without React Native imports, so server/test runs it under plain Node: the honest cancel flow
2
+ // (PROTOCOL.md §3.10), the subscription summary, the CSAT prompt (§3.12) and action button states (§3.9).
3
+
4
+ import type { ActionResult, CancelReason, Conversation, Offer, Subscription, SupportEventKind } from './client'
5
+ import type { Copy } from './theme'
6
+ import { fill } from './theme'
7
+
8
+ export type Screen = 'sub' | 'reason' | 'offer' | 'refund'
9
+
10
+ export interface CancelFlow {
11
+ screen: Screen | null
12
+ reason: CancelReason | null
13
+ // The one alternative shown in this flow (kept here: showing it empties widget.offers for the cooldown).
14
+ offer: Offer | null
15
+ offered: boolean
16
+ // Where the refund screen goes back to: the subscription screen, or the reasons after "Subscribed by mistake".
17
+ from: Screen | null
18
+ }
19
+
20
+ export const startFlow: CancelFlow = { screen: null, reason: null, offer: null, offered: false, from: null }
21
+
22
+ export const cancelReasons: CancelReason[] = ['too_expensive', 'not_using', 'bug', 'mistake', 'other']
23
+
24
+ export type FlowEvent =
25
+ | { type: 'open' }
26
+ | { type: 'cancel' }
27
+ | { type: 'refund' }
28
+ // A reason, or null for Skip.
29
+ | { type: 'pick'; reason: CancelReason | null }
30
+ | { type: 'store' }
31
+ | { type: 'accept' }
32
+ | { type: 'continue' }
33
+ | { type: 'requestRefund' }
34
+ | { type: 'back' }
35
+
36
+ // What the widget runs after a step: a store action, or askForOffer (which posts offer_accepted itself).
37
+ export type FlowRun = 'manage_subscription' | 'request_refund' | 'offer' | null
38
+
39
+ export interface FlowStep {
40
+ flow: CancelFlow
41
+ track: [SupportEventKind, Record<string, string>][]
42
+ run: FlowRun
43
+ }
44
+
45
+ export function stepFlow(f: CancelFlow, e: FlowEvent, offers: Partial<Record<CancelReason, Offer>>): FlowStep {
46
+ const to = (p: Partial<CancelFlow>, track: FlowStep['track'] = [], run: FlowRun = null): FlowStep => ({ flow: { ...f, ...p }, track, run })
47
+ const toStore: FlowStep['track'] = [['cancel_continued', {}]]
48
+ switch (e.type) {
49
+ case 'open':
50
+ return to({ screen: 'sub', from: null })
51
+ case 'cancel':
52
+ return to({ screen: 'reason', reason: null }, [['cancel_started', {}]])
53
+ case 'refund':
54
+ return to({ screen: 'refund', from: f.screen ?? 'sub' }, [['refund_help', {}]])
55
+ case 'pick': {
56
+ const r = e.reason
57
+ const said: FlowStep['track'] = r ? [['cancel_reason', { reason: r }]] : []
58
+ if (r === 'mistake') return to({ reason: r, screen: 'refund', from: 'reason' }, [...said, ['refund_help', {}]])
59
+ const offer = r && !f.offered ? offers[r] : undefined
60
+ if (r && offer) return to({ reason: r, screen: 'offer', offer, offered: true }, [...said, ['offer_shown', { reason: r }]])
61
+ return to({ reason: r, screen: 'sub' }, [...said, ...toStore], 'manage_subscription')
62
+ }
63
+ case 'store':
64
+ case 'continue':
65
+ return to({ screen: 'sub' }, toStore, 'manage_subscription')
66
+ case 'accept':
67
+ return to({ screen: null }, [], f.offer && f.reason ? 'offer' : null)
68
+ case 'requestRefund':
69
+ return to({ screen: 'sub' }, [['refund_requested', {}]], 'request_refund')
70
+ case 'back':
71
+ return to({ screen: f.screen === 'offer' ? 'reason' : f.screen === 'reason' ? 'sub' : f.screen === 'refund' ? f.from : null })
72
+ }
73
+ }
74
+
75
+ // Only a renewing plan can be cancelled; lifetime purchases and ended plans can't.
76
+ export const canCancel = (sub: Subscription): boolean =>
77
+ (sub.status === 'trial' || sub.status === 'active' || sub.status === 'grace' || sub.status === 'billing_retry') && sub.willRenew !== false && sub.period !== 'lifetime'
78
+
79
+ export const storeName = (sub: Subscription | null, android: boolean): string => (sub?.store === 'play' || (!sub?.store && android) ? 'Google Play' : 'App Store')
80
+
81
+ // The Subscription row: plan, then price and the next date that matters.
82
+ export function subscriptionSummary(sub: Subscription, t: Copy, date: (ms: number) => string): { plan: string; detail: string } {
83
+ const when =
84
+ sub.status === 'expired' || sub.status === 'refunded' ? t.ended
85
+ : sub.status === 'trial' && sub.trialEndsAt ? fill(t.trialEnds, { date: date(sub.trialEndsAt) })
86
+ : sub.status === 'cancelled' || sub.willRenew === false ? (sub.expiresAt ? fill(t.ends, { date: date(sub.expiresAt) }) : '')
87
+ : sub.renewsAt ? fill(t.renews, { date: date(sub.renewsAt) })
88
+ : ''
89
+ return { plan: sub.product || t.subscription, detail: [sub.price, when].filter(Boolean).join(' · ') }
90
+ }
91
+
92
+ // "Did this help?" once a conversation is resolved and not rated yet; "Thanks" right after the user rated it.
93
+ export function csatPrompt(conv: Conversation | null | undefined, ratedHere: boolean): 'ask' | 'thanks' | null {
94
+ if (ratedHere) return 'thanks'
95
+ return conv?.status === 'resolved' && (conv.csat ?? null) === null ? 'ask' : null
96
+ }
97
+
98
+ export type RunState = 'pending' | 'done' | 'failed'
99
+ // A cancelled action (the user closed the store sheet) goes back to its idle look.
100
+ export const runState = (r: ActionResult): RunState | null => (r === 'cancelled' ? null : r)
package/src/index.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  // @shotik/react-native: in-app support chat for React Native and Expo, backed by a Shotik workspace.
2
2
 
3
3
  export { ShotikSupport } from './support'
4
- export { ShotikSupportProvider, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react'
5
- export type { ProviderProps, SheetViewProps, SupportApi, WidgetProps } from './react'
6
- export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf } from './client'
7
- export type { Attachment, Author, Conversation, ConversationStatus, DeviceInfo, KeyValueStorage, LocalAttachment, Message, Receipt, Status, SupportConfig, SupportState, Typing, UserInfo } from './client'
4
+ export { ShotikSupportProvider, SupportFrictionChip, SupportRoute, SupportSheet, SupportWidget, useSupport } from './react'
5
+ export type { FrictionChipProps, ProviderProps, SheetViewProps, SupportApi, WidgetProps } from './react'
6
+ export { SupportClient, HttpError, memoryStorage, receiptOf, attachmentsOf, actionsOf } from './client'
7
+ export type { ActionKind, ActionResult, Attachment, Author, CancelReason, Conversation, ConversationStatus, DeviceInfo, Friction, KeyValueStorage, LocalAttachment, Message, Offer, Receipt, Status, Subscription, SupportAction, SupportConfig, SupportEventKind, SupportState, Trigger, Typing, UserInfo, WidgetConfig } from './client'
8
8
  export type { Colors, Copy, SupportTheme } from './theme'
9
9
  export { catalogs } from './theme'
10
10
  export { nativeDevice, nativeStorage } from './native'