@kissmyappss/react-native 1.0.0 → 1.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/CHANGELOG.md +43 -0
- package/KissMyAppsReactNative.podspec +29 -0
- package/README.md +187 -30
- package/android/build.gradle +65 -0
- package/android/src/main/AndroidManifest.xml +2 -0
- package/android/src/main/AndroidManifestNew.xml +1 -0
- package/android/src/main/java/com/kissmyapps/reactnative/KissMyAppsAttributionModule.kt +138 -0
- package/android/src/main/java/com/kissmyapps/reactnative/KissMyAppsAttributionPackage.kt +15 -0
- package/ios/KissMyAppsAttribution.m +10 -0
- package/ios/KissMyAppsAttribution.swift +75 -0
- package/ios/PrivacyInfo.xcprivacy +40 -0
- package/lib/attribution.d.ts +78 -0
- package/lib/attribution.js +153 -0
- package/lib/client.d.ts +81 -1
- package/lib/client.js +434 -5
- package/lib/index.d.ts +26 -2
- package/lib/index.js +67 -2
- package/package.json +12 -3
- package/react-native.config.js +13 -0
- package/src/attribution.ts +207 -0
- package/src/client.ts +494 -5
- package/src/index.ts +79 -4
package/src/client.ts
CHANGED
|
@@ -2,7 +2,20 @@
|
|
|
2
2
|
// network come in through `Environment`, so the same code runs in tests and in Node.
|
|
3
3
|
// The Android and iOS SDKs follow the same rules; see integrations/analytics-mobile.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
import {
|
|
6
|
+
INSTALL_PATH,
|
|
7
|
+
OPEN_PATH,
|
|
8
|
+
deepLinkFrom,
|
|
9
|
+
deviceKey,
|
|
10
|
+
httpsLink,
|
|
11
|
+
installBody,
|
|
12
|
+
openBody,
|
|
13
|
+
parseAnswer,
|
|
14
|
+
within,
|
|
15
|
+
} from './attribution'
|
|
16
|
+
import type { AttributionInfo, AttributionRequest, DeepLink } from './attribution'
|
|
17
|
+
|
|
18
|
+
export const SDK_VERSION = '1.1.0'
|
|
6
19
|
export const DEFAULT_ENDPOINT = 'https://events.kissmyapps.dev'
|
|
7
20
|
|
|
8
21
|
export type Properties = Record<string, unknown>
|
|
@@ -40,9 +53,35 @@ export interface ClientOptions {
|
|
|
40
53
|
maxQueue?: number
|
|
41
54
|
/** Record installs, updates, opens and backgrounding. Default true. */
|
|
42
55
|
trackLifecycle?: boolean
|
|
56
|
+
/**
|
|
57
|
+
* Match the install to the link that brought it on the first launch, and report links that
|
|
58
|
+
* open the app. Default true. Nothing is matched until attribution is on for the project.
|
|
59
|
+
*/
|
|
60
|
+
attribution?: boolean
|
|
61
|
+
/**
|
|
62
|
+
* iPhone only: on the first launch, read a `kma:` click ID that the smart link's page put on
|
|
63
|
+
* the clipboard. Turn it on only with "Clipboard handoff for iPhone" on in the console:
|
|
64
|
+
* iOS asks the person before an app reads what another app copied. Default false.
|
|
65
|
+
*/
|
|
66
|
+
clipboardHandoff?: boolean
|
|
43
67
|
debug?: boolean
|
|
44
68
|
}
|
|
45
69
|
|
|
70
|
+
export interface RevenueOptions {
|
|
71
|
+
/** Your product or plan, such as annual_plan. */
|
|
72
|
+
productId?: string
|
|
73
|
+
/**
|
|
74
|
+
* The payment's ID at the store, such as StoreKit's transaction ID or Google Play's order
|
|
75
|
+
* ID. The same payment reported by the app and by a RevenueCat or Adapty webhook with the
|
|
76
|
+
* same ID counts once.
|
|
77
|
+
*/
|
|
78
|
+
transactionId?: string
|
|
79
|
+
/** The event's name. Default purchase, or refund for a negative amount. */
|
|
80
|
+
event?: string
|
|
81
|
+
/** More properties for the event. The kma_ revenue properties always win. */
|
|
82
|
+
properties?: Properties
|
|
83
|
+
}
|
|
84
|
+
|
|
46
85
|
export interface Environment {
|
|
47
86
|
storage: Storage | null
|
|
48
87
|
device(): DeviceInfo
|
|
@@ -50,8 +89,31 @@ export interface Environment {
|
|
|
50
89
|
sdk: string
|
|
51
90
|
now?: () => number
|
|
52
91
|
log?: (message: string) => void
|
|
92
|
+
/** The link that opened the app, such as Linking.getInitialURL(). */
|
|
93
|
+
initialLink?: () => Promise<string | null>
|
|
94
|
+
/** What the optional native module reads: device key, install referrer, Apple Ads token, if any. */
|
|
95
|
+
attributionInfo?: (request: AttributionRequest) => Promise<AttributionInfo | null>
|
|
53
96
|
}
|
|
54
97
|
|
|
98
|
+
/** The first launch's install call, kept until it gets an answer and resent as it was. */
|
|
99
|
+
interface PendingInstall {
|
|
100
|
+
/** When app_installed was queued. */
|
|
101
|
+
at: number
|
|
102
|
+
anonymousId: string
|
|
103
|
+
sessionId: string
|
|
104
|
+
/** The first link that opened the app on the first launch, before the call went out. */
|
|
105
|
+
link?: string
|
|
106
|
+
/** Calls made so far, one per launch. */
|
|
107
|
+
tries: number
|
|
108
|
+
/** What the device gave on the first try, without the Apple Ads token, which expires. */
|
|
109
|
+
info?: AttributionInfo
|
|
110
|
+
/** False when reading the install referrer timed out: the next try reads it again. */
|
|
111
|
+
infoComplete?: boolean
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** This launch's install call: links wait for its answer before they go to the open call. */
|
|
115
|
+
type InstallPhase = 'none' | 'waiting' | 'answered' | 'failed'
|
|
116
|
+
|
|
55
117
|
interface Session {
|
|
56
118
|
id: string
|
|
57
119
|
started: number
|
|
@@ -67,6 +129,7 @@ interface State {
|
|
|
67
129
|
optedOut: boolean
|
|
68
130
|
version?: string
|
|
69
131
|
build?: string
|
|
132
|
+
install?: PendingInstall | null
|
|
70
133
|
}
|
|
71
134
|
|
|
72
135
|
export interface QueuedEvent {
|
|
@@ -87,6 +150,25 @@ const BATCH_SIZE = 50
|
|
|
87
150
|
const FLUSH_AT = 30
|
|
88
151
|
const HEARTBEAT_MS = 60_000
|
|
89
152
|
const MAX_PROPERTIES_BYTES = 32_000
|
|
153
|
+
// The first launch's call, then at most three more launches.
|
|
154
|
+
const INSTALL_TRIES = 4
|
|
155
|
+
// A link handed over twice this close together, by Linking and by the app, counts once.
|
|
156
|
+
const SAME_LINK_MS = 3000
|
|
157
|
+
// As the iOS SDK: the opening link has 1.5 seconds to arrive before the install call goes.
|
|
158
|
+
const INITIAL_LINK_WAIT_MS = 1500
|
|
159
|
+
// The native module waits up to 10 seconds for Google Play's install referrer.
|
|
160
|
+
const NATIVE_WAIT_MS = 12_000
|
|
161
|
+
const FLUSH_WAIT_MS = 5000
|
|
162
|
+
// The properties a payment event carries; reports read revenue from them.
|
|
163
|
+
const REVENUE_KEYS = ['kma_revenue', 'kma_currency', 'kma_product_id', 'kma_transaction_id']
|
|
164
|
+
const MAX_REVENUE = 1e9
|
|
165
|
+
const CURRENCY = /^[A-Za-z]{3}$/
|
|
166
|
+
|
|
167
|
+
/** A product or transaction ID as reports keep it: text of 1 to 200 characters. */
|
|
168
|
+
function revenueId(value: unknown): string | undefined {
|
|
169
|
+
const id = typeof value === 'string' ? value.trim() : ''
|
|
170
|
+
return id && id.length <= 200 ? id : undefined
|
|
171
|
+
}
|
|
90
172
|
|
|
91
173
|
export function uuid(): string {
|
|
92
174
|
// Hermes has no crypto.randomUUID; a polyfill may add it.
|
|
@@ -118,6 +200,20 @@ export class KmaClient {
|
|
|
118
200
|
private inForeground = false
|
|
119
201
|
private firstLaunch = false
|
|
120
202
|
private stopped = false
|
|
203
|
+
private launched = false
|
|
204
|
+
// This launch is the first launch: its first link goes with the install call.
|
|
205
|
+
private firstLaunchNow = false
|
|
206
|
+
private installRunning = false
|
|
207
|
+
// This launch's try is on its way (one try per launch).
|
|
208
|
+
private installSent = false
|
|
209
|
+
private installPhase: InstallPhase = 'none'
|
|
210
|
+
private linksBeforeLaunch: { url: string; at: number }[] = []
|
|
211
|
+
private waitingLinks: { url: string; at: number }[] = []
|
|
212
|
+
private readonly recentLinks = new Map<string, number>()
|
|
213
|
+
private deviceKeyRead: string | null | undefined
|
|
214
|
+
private deepLinkHandler: ((link: DeepLink) => void) | null = null
|
|
215
|
+
private heldDeepLink: DeepLink | null = null
|
|
216
|
+
private readonly initialLink: Promise<string | null>
|
|
121
217
|
/** Settles once saved state is read and the launch is recorded. */
|
|
122
218
|
readonly ready: Promise<void>
|
|
123
219
|
|
|
@@ -139,6 +235,19 @@ export class KmaClient {
|
|
|
139
235
|
optedOut: false,
|
|
140
236
|
}
|
|
141
237
|
this.ready = this.load()
|
|
238
|
+
const opening =
|
|
239
|
+
env.initialLink && options.attribution !== false
|
|
240
|
+
? within(
|
|
241
|
+
Promise.resolve().then(() => env.initialLink?.() ?? null),
|
|
242
|
+
INITIAL_LINK_WAIT_MS,
|
|
243
|
+
null,
|
|
244
|
+
)
|
|
245
|
+
: Promise.resolve(null)
|
|
246
|
+
// Routed before the install call reads it, so the opening link goes with the install.
|
|
247
|
+
this.initialLink = opening.then((url) => {
|
|
248
|
+
if (url) this.handleDeepLink(url)
|
|
249
|
+
return url
|
|
250
|
+
})
|
|
142
251
|
}
|
|
143
252
|
|
|
144
253
|
// Public API ---------------------------------------------------------------------------
|
|
@@ -157,6 +266,46 @@ export class KmaClient {
|
|
|
157
266
|
})
|
|
158
267
|
}
|
|
159
268
|
|
|
269
|
+
/**
|
|
270
|
+
* Records a payment: the amount in major units (9.99, not 999), negative for a refund, and
|
|
271
|
+
* its ISO 4217 currency code. Sent as a purchase (or refund) event with kma_revenue and
|
|
272
|
+
* kma_currency. An amount or currency that is not valid sends nothing (a warning in debug).
|
|
273
|
+
*/
|
|
274
|
+
revenue(amount: number, currency: string, options: RevenueOptions = {}): void {
|
|
275
|
+
if (
|
|
276
|
+
typeof amount !== 'number' ||
|
|
277
|
+
!Number.isFinite(amount) ||
|
|
278
|
+
amount === 0 ||
|
|
279
|
+
Math.abs(amount) > MAX_REVENUE
|
|
280
|
+
) {
|
|
281
|
+
return this.warn(
|
|
282
|
+
'revenue needs an amount that is not 0 and at most 1,000,000,000 either way (negative for a refund).',
|
|
283
|
+
)
|
|
284
|
+
}
|
|
285
|
+
const code = typeof currency === 'string' ? currency.trim() : ''
|
|
286
|
+
if (!CURRENCY.test(code)) {
|
|
287
|
+
return this.warn(
|
|
288
|
+
`revenue needs a three-letter currency code such as USD, not "${String(currency)}".`,
|
|
289
|
+
)
|
|
290
|
+
}
|
|
291
|
+
const { productId, transactionId, event, properties } = options ?? {}
|
|
292
|
+
const values: Properties =
|
|
293
|
+
properties && typeof properties === 'object' && !Array.isArray(properties)
|
|
294
|
+
? { ...properties }
|
|
295
|
+
: {}
|
|
296
|
+
for (const field of REVENUE_KEYS) delete values[field]
|
|
297
|
+
values.kma_revenue = amount
|
|
298
|
+
values.kma_currency = code.toUpperCase()
|
|
299
|
+
const product = revenueId(productId)
|
|
300
|
+
const transaction = revenueId(transactionId)
|
|
301
|
+
if (product) values.kma_product_id = product
|
|
302
|
+
else if (productId != null) this.warn('productId must be 1 to 200 characters; it was left out.')
|
|
303
|
+
if (transaction) values.kma_transaction_id = transaction
|
|
304
|
+
else if (transactionId != null)
|
|
305
|
+
this.warn('transactionId must be 1 to 200 characters; it was left out.')
|
|
306
|
+
this.track(event || (amount > 0 ? 'purchase' : 'refund'), values)
|
|
307
|
+
}
|
|
308
|
+
|
|
160
309
|
/** Records a screen view; later events carry the screen's name. */
|
|
161
310
|
screen(name: string, properties: Properties = {}): void {
|
|
162
311
|
const screen = String(name ?? '')
|
|
@@ -185,6 +334,7 @@ export class KmaClient {
|
|
|
185
334
|
const id = String(userId ?? '').trim()
|
|
186
335
|
if (!id || id.length > 200) return this.warn('identify needs a user ID of 1 to 200 characters.')
|
|
187
336
|
this.whenLoaded(() => {
|
|
337
|
+
if (this.stopped || this.state.optedOut) return
|
|
188
338
|
this.state.userId = id
|
|
189
339
|
if (traits) this.state.traits = { ...(this.state.traits ?? {}), ...this.clean(traits) }
|
|
190
340
|
this.identityPending = true
|
|
@@ -196,6 +346,7 @@ export class KmaClient {
|
|
|
196
346
|
/** Updates traits for the current person without changing who they are. */
|
|
197
347
|
setTraits(traits: Properties): void {
|
|
198
348
|
this.whenLoaded(() => {
|
|
349
|
+
if (this.stopped || this.state.optedOut) return
|
|
199
350
|
this.state.traits = { ...(this.state.traits ?? {}), ...this.clean(traits) }
|
|
200
351
|
this.identityPending = true
|
|
201
352
|
this.save()
|
|
@@ -206,6 +357,7 @@ export class KmaClient {
|
|
|
206
357
|
/** Forgets the user, for example on sign out: what follows is a new person and session. */
|
|
207
358
|
reset(): void {
|
|
208
359
|
this.whenLoaded(() => {
|
|
360
|
+
if (this.stopped || this.state.optedOut) return
|
|
209
361
|
void this.flush()
|
|
210
362
|
this.state.userId = null
|
|
211
363
|
this.state.traits = null
|
|
@@ -221,18 +373,67 @@ export class KmaClient {
|
|
|
221
373
|
optOut(): void {
|
|
222
374
|
this.whenLoaded(() => {
|
|
223
375
|
this.state.optedOut = true
|
|
224
|
-
this.
|
|
225
|
-
this.save()
|
|
376
|
+
this.clearConsentData()
|
|
226
377
|
})
|
|
227
378
|
}
|
|
228
379
|
|
|
380
|
+
private clearConsentData(): void {
|
|
381
|
+
this.queue = []
|
|
382
|
+
this.state.userId = null
|
|
383
|
+
this.state.traits = null
|
|
384
|
+
this.identityPending = false
|
|
385
|
+
this.state.session = null
|
|
386
|
+
this.screenName = null
|
|
387
|
+
this.state.install = null
|
|
388
|
+
this.firstLaunch = false
|
|
389
|
+
this.linksBeforeLaunch = []
|
|
390
|
+
this.waitingLinks = []
|
|
391
|
+
this.recentLinks.clear()
|
|
392
|
+
this.heldDeepLink = null
|
|
393
|
+
this.installPhase = 'answered'
|
|
394
|
+
void this.writeNow()
|
|
395
|
+
}
|
|
396
|
+
|
|
229
397
|
optIn(): void {
|
|
230
398
|
this.whenLoaded(() => {
|
|
399
|
+
if (!this.state.optedOut) return
|
|
400
|
+
this.state.anonymousId = uuid()
|
|
231
401
|
this.state.optedOut = false
|
|
232
402
|
this.save()
|
|
233
403
|
})
|
|
234
404
|
}
|
|
235
405
|
|
|
406
|
+
/**
|
|
407
|
+
* Reports a link that opened the app, such as a Universal Link or App Link. Any https link
|
|
408
|
+
* is sent and KissMyApps decides whether it is one of the project's links; its deep link then
|
|
409
|
+
* goes to `onDeepLink`. Returns false when nothing is sent (not https, longer than 2,048
|
|
410
|
+
* characters, attribution off, opted out). The same link handed over twice within 3 seconds
|
|
411
|
+
* counts once, so Linking and the app may both report it.
|
|
412
|
+
*/
|
|
413
|
+
handleDeepLink(url: string): boolean {
|
|
414
|
+
if (this.options.attribution === false || this.stopped) return false
|
|
415
|
+
const link = httpsLink(url)
|
|
416
|
+
if (!link) return false
|
|
417
|
+
if (this.loaded && this.state.optedOut) return false
|
|
418
|
+
const at = this.now()
|
|
419
|
+
this.whenLoaded(() => this.routeLink(link, at))
|
|
420
|
+
return true
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
/**
|
|
424
|
+
* Where deep links go: the deferred one after an install, and one each time a link opens the
|
|
425
|
+
* app. Each deep link is handed over once; one that arrives before a handler is set is held
|
|
426
|
+
* and handed to the next handler set. Pass null to stop.
|
|
427
|
+
*/
|
|
428
|
+
onDeepLink(handler: ((link: DeepLink) => void) | null): void {
|
|
429
|
+
this.deepLinkHandler = handler
|
|
430
|
+
const held = this.heldDeepLink
|
|
431
|
+
if (handler && held) {
|
|
432
|
+
this.heldDeepLink = null
|
|
433
|
+
this.deliver(held)
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
236
437
|
getAnonymousId(): string {
|
|
237
438
|
return this.state.anonymousId
|
|
238
439
|
}
|
|
@@ -274,14 +475,17 @@ export class KmaClient {
|
|
|
274
475
|
this.whenLoaded(() => {
|
|
275
476
|
if (this.stopped || this.inForeground) return
|
|
276
477
|
const launch = this.foregroundAt === 0
|
|
478
|
+
this.launched = true
|
|
277
479
|
this.inForeground = true
|
|
278
480
|
this.foregroundAt = this.now()
|
|
279
481
|
if (this.state.optedOut) return
|
|
280
482
|
const session = this.ensureSession()
|
|
483
|
+
const firstLaunch = launch && this.firstLaunch
|
|
281
484
|
if (this.options.trackLifecycle !== false) {
|
|
282
485
|
if (launch) this.recordInstallOrUpdate(session)
|
|
283
486
|
this.enqueue('app_opened', { from_background: !launch }, session)
|
|
284
487
|
}
|
|
488
|
+
if (launch) this.attributeLaunch(session, firstLaunch)
|
|
285
489
|
this.heartbeatTimer ??= setInterval(() => this.heartbeat(), HEARTBEAT_MS)
|
|
286
490
|
})
|
|
287
491
|
}
|
|
@@ -329,12 +533,14 @@ export class KmaClient {
|
|
|
329
533
|
optedOut: saved.optedOut === true,
|
|
330
534
|
version: saved.version,
|
|
331
535
|
build: saved.build,
|
|
536
|
+
install: pendingInstall(saved.install),
|
|
332
537
|
}
|
|
333
538
|
}
|
|
334
539
|
// Nothing saved means a first launch, or the app's data was cleared.
|
|
335
540
|
this.firstLaunch = !saved?.anonymousId
|
|
336
541
|
this.queue = Array.isArray(queue) ? queue : []
|
|
337
542
|
this.identityPending = Boolean(this.state.traits)
|
|
543
|
+
if (this.state.optedOut) this.clearConsentData()
|
|
338
544
|
this.loaded = true
|
|
339
545
|
// What an earlier launch could not send goes now.
|
|
340
546
|
if (this.queue.length) this.scheduleFlush(0)
|
|
@@ -512,8 +718,8 @@ export class KmaClient {
|
|
|
512
718
|
return batch
|
|
513
719
|
}
|
|
514
720
|
|
|
515
|
-
private async post(body: Properties) {
|
|
516
|
-
return this.env.fetch(`${this.options.endpoint}
|
|
721
|
+
private async post(body: Properties, path = '/v1/events') {
|
|
722
|
+
return this.env.fetch(`${this.options.endpoint}${path}`, {
|
|
517
723
|
method: 'POST',
|
|
518
724
|
headers: { 'content-type': 'application/json', authorization: `Bearer ${this.options.key}` },
|
|
519
725
|
body: JSON.stringify(body),
|
|
@@ -592,7 +798,290 @@ export class KmaClient {
|
|
|
592
798
|
.catch(() => undefined)
|
|
593
799
|
}
|
|
594
800
|
|
|
801
|
+
// Attribution ---------------------------------------------------------------------------
|
|
802
|
+
|
|
803
|
+
/** The launch: the first one queues the install call; links that came before it are routed. */
|
|
804
|
+
private attributeLaunch(session: Session, firstLaunch: boolean): void {
|
|
805
|
+
this.firstLaunch = false
|
|
806
|
+
const early = this.linksBeforeLaunch.splice(0)
|
|
807
|
+
if (this.options.attribution === false) return
|
|
808
|
+
// Without storage every launch looks like the first, so there is no install to match.
|
|
809
|
+
if (firstLaunch && this.env.storage) {
|
|
810
|
+
this.state.install = {
|
|
811
|
+
at: this.now(),
|
|
812
|
+
anonymousId: this.state.anonymousId,
|
|
813
|
+
sessionId: session.id,
|
|
814
|
+
tries: 0,
|
|
815
|
+
}
|
|
816
|
+
this.firstLaunchNow = true
|
|
817
|
+
this.save()
|
|
818
|
+
}
|
|
819
|
+
if (this.state.install) {
|
|
820
|
+
this.installPhase = 'waiting'
|
|
821
|
+
for (const link of early) this.routeLaunched(link.url, link.at)
|
|
822
|
+
void this.sendInstall()
|
|
823
|
+
} else {
|
|
824
|
+
for (const link of early) void this.sendOpen(link.url, link.at)
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
private routeLink(url: string, at: number): void {
|
|
829
|
+
if (this.stopped || this.state.optedOut) return
|
|
830
|
+
for (const [seen, when] of this.recentLinks) {
|
|
831
|
+
if (at - when >= SAME_LINK_MS) this.recentLinks.delete(seen)
|
|
832
|
+
}
|
|
833
|
+
if (this.recentLinks.has(url)) return
|
|
834
|
+
this.recentLinks.set(url, at)
|
|
835
|
+
if (!this.launched) {
|
|
836
|
+
if (this.linksBeforeLaunch.length < 10) this.linksBeforeLaunch.push({ url, at })
|
|
837
|
+
return
|
|
838
|
+
}
|
|
839
|
+
this.routeLaunched(url, at)
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
private routeLaunched(url: string, at: number): void {
|
|
843
|
+
const pending = this.state.install
|
|
844
|
+
if (pending && this.installPhase === 'waiting') {
|
|
845
|
+
// Only the first link of the first launch goes with the install call.
|
|
846
|
+
if (this.firstLaunchNow && !this.installSent && !pending.tries && !pending.link) {
|
|
847
|
+
pending.link = url
|
|
848
|
+
this.save()
|
|
849
|
+
} else if (this.waitingLinks.length < 10) {
|
|
850
|
+
// Sent once the install is matched; an open first would record an install of its own.
|
|
851
|
+
this.waitingLinks.push({ url, at })
|
|
852
|
+
}
|
|
853
|
+
return
|
|
854
|
+
}
|
|
855
|
+
if (pending && this.installPhase === 'failed') {
|
|
856
|
+
this.warn('The link was not sent: the install is matched first, on the next launch.')
|
|
857
|
+
return
|
|
858
|
+
}
|
|
859
|
+
void this.sendOpen(url, at)
|
|
860
|
+
}
|
|
861
|
+
|
|
862
|
+
/** The device's details; `complete` is false when the install referrer could not be read in time. */
|
|
863
|
+
private async readNative(
|
|
864
|
+
install: boolean,
|
|
865
|
+
clipboard: boolean,
|
|
866
|
+
): Promise<{ info: AttributionInfo; complete: boolean }> {
|
|
867
|
+
const read = this.env.attributionInfo
|
|
868
|
+
if (!read) return { info: {}, complete: true }
|
|
869
|
+
const request = {
|
|
870
|
+
install,
|
|
871
|
+
clipboard: install && clipboard && this.options.clipboardHandoff === true,
|
|
872
|
+
}
|
|
873
|
+
const info = await within<AttributionInfo | null>(
|
|
874
|
+
Promise.resolve()
|
|
875
|
+
.then(() => read(request))
|
|
876
|
+
.then(
|
|
877
|
+
(answer) => (answer && typeof answer === 'object' ? answer : {}),
|
|
878
|
+
() => ({}),
|
|
879
|
+
),
|
|
880
|
+
NATIVE_WAIT_MS,
|
|
881
|
+
null,
|
|
882
|
+
)
|
|
883
|
+
if (!info) return { info: {}, complete: false }
|
|
884
|
+
const key = deviceKey(info.deviceKey)
|
|
885
|
+
if (key) this.deviceKeyRead = key
|
|
886
|
+
return { info, complete: info.retryReferrer !== true }
|
|
887
|
+
}
|
|
888
|
+
|
|
889
|
+
/** The first try's details again; the Apple Ads token, and a referrer that timed out, are read anew. */
|
|
890
|
+
private async installInfo(
|
|
891
|
+
pending: PendingInstall,
|
|
892
|
+
): Promise<{ info: AttributionInfo; complete: boolean }> {
|
|
893
|
+
const saved = pending.info
|
|
894
|
+
if (saved && pending.infoComplete && this.env.device().platform === 'android') {
|
|
895
|
+
return { info: saved, complete: true }
|
|
896
|
+
}
|
|
897
|
+
// The clipboard is read on the first try only.
|
|
898
|
+
const read = await this.readNative(true, !saved)
|
|
899
|
+
if (!saved) return read
|
|
900
|
+
return {
|
|
901
|
+
info: { ...read.info, ...definedOnly(saved), appleAdsToken: read.info.appleAdsToken },
|
|
902
|
+
complete: pending.infoComplete === true || read.complete,
|
|
903
|
+
}
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/** The install call: once, on the first launch; again on the next launches if it failed. */
|
|
907
|
+
private async sendInstall(): Promise<void> {
|
|
908
|
+
if (this.installRunning) return
|
|
909
|
+
this.installRunning = true
|
|
910
|
+
try {
|
|
911
|
+
await this.initialLink
|
|
912
|
+
const first = this.state.install
|
|
913
|
+
if (!first) return this.installAnswered()
|
|
914
|
+
const { info, complete } = await this.installInfo(first)
|
|
915
|
+
// app_installed and its session reach the server first.
|
|
916
|
+
await within(this.flush(), FLUSH_WAIT_MS, undefined)
|
|
917
|
+
const pending = this.state.install
|
|
918
|
+
if (!pending) return this.installAnswered()
|
|
919
|
+
if (this.stopped || this.state.optedOut || this.installSent) return
|
|
920
|
+
this.installSent = true
|
|
921
|
+
pending.tries += 1
|
|
922
|
+
if (!pending.info || !pending.infoComplete) {
|
|
923
|
+
pending.info = savedInfo(info)
|
|
924
|
+
pending.infoComplete = complete
|
|
925
|
+
}
|
|
926
|
+
const device = this.env.device()
|
|
927
|
+
const body = installBody({
|
|
928
|
+
anonymousId: pending.anonymousId,
|
|
929
|
+
sessionId: pending.sessionId,
|
|
930
|
+
platform: device.platform,
|
|
931
|
+
installedAt: pending.at,
|
|
932
|
+
sdk: this.env.sdk,
|
|
933
|
+
// Not after a reset: the install belongs to the person who installed.
|
|
934
|
+
userId: pending.anonymousId === this.state.anonymousId ? this.state.userId : null,
|
|
935
|
+
appVersion: this.options.appVersion,
|
|
936
|
+
link: pending.link,
|
|
937
|
+
info,
|
|
938
|
+
clipboard: this.options.clipboardHandoff === true,
|
|
939
|
+
})
|
|
940
|
+
await this.writeNow()
|
|
941
|
+
let response: Awaited<ReturnType<Environment['fetch']>>
|
|
942
|
+
try {
|
|
943
|
+
if (this.state.install !== pending || this.state.optedOut) return
|
|
944
|
+
response = await this.post(body, INSTALL_PATH)
|
|
945
|
+
} catch {
|
|
946
|
+
if (this.state.install === pending) this.installFailed(pending, 'no connection')
|
|
947
|
+
return
|
|
948
|
+
}
|
|
949
|
+
if (this.state.install !== pending || this.state.optedOut) return
|
|
950
|
+
if (!response.ok && retryable(response.status)) {
|
|
951
|
+
return this.installFailed(pending, `status ${response.status}`)
|
|
952
|
+
}
|
|
953
|
+
// Answered: a refused body would be refused again, and an unreadable answer is still one.
|
|
954
|
+
this.state.install = null
|
|
955
|
+
void this.writeNow()
|
|
956
|
+
const answer = await response.text().catch(() => '')
|
|
957
|
+
if (response.ok) {
|
|
958
|
+
this.deliver(deepLinkFrom(parseAnswer(answer), httpsLink(pending.link)))
|
|
959
|
+
} else {
|
|
960
|
+
this.warn(`The install was refused (${response.status}): ${answer}`)
|
|
961
|
+
}
|
|
962
|
+
this.installAnswered()
|
|
963
|
+
} finally {
|
|
964
|
+
this.installRunning = false
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** Links that waited for the install's answer go to the open call now. */
|
|
969
|
+
private installAnswered(): void {
|
|
970
|
+
this.installPhase = 'answered'
|
|
971
|
+
for (const link of this.waitingLinks.splice(0)) void this.sendOpen(link.url, link.at)
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
private installFailed(pending: PendingInstall, reason: string): void {
|
|
975
|
+
if (pending.tries >= INSTALL_TRIES) {
|
|
976
|
+
this.state.install = null
|
|
977
|
+
this.warn(`The install could not be matched (${reason}); giving up.`)
|
|
978
|
+
this.installAnswered()
|
|
979
|
+
} else {
|
|
980
|
+
this.warn(`The install could not be matched yet (${reason}); trying again next launch.`)
|
|
981
|
+
this.installPhase = 'failed'
|
|
982
|
+
if (this.waitingLinks.splice(0).length) {
|
|
983
|
+
this.warn('Links that opened the app were not sent: the install is matched first.')
|
|
984
|
+
}
|
|
985
|
+
}
|
|
986
|
+
void this.writeNow()
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/** The open call, for a link that opened the app after the install was matched. Not retried. */
|
|
990
|
+
private async sendOpen(url: string, at: number): Promise<void> {
|
|
991
|
+
if (this.stopped || this.state.optedOut) return
|
|
992
|
+
const session = this.ensureSession()
|
|
993
|
+
const anonymousId = this.state.anonymousId
|
|
994
|
+
const userId = this.state.userId
|
|
995
|
+
const key =
|
|
996
|
+
this.deviceKeyRead ?? deviceKey((await this.readNative(false, false)).info.deviceKey)
|
|
997
|
+
if (this.stopped || this.state.optedOut || anonymousId !== this.state.anonymousId) return
|
|
998
|
+
const body = openBody({
|
|
999
|
+
anonymousId,
|
|
1000
|
+
sessionId: session.id,
|
|
1001
|
+
platform: this.env.device().platform,
|
|
1002
|
+
url,
|
|
1003
|
+
openedAt: at,
|
|
1004
|
+
sdk: this.env.sdk,
|
|
1005
|
+
userId,
|
|
1006
|
+
appVersion: this.options.appVersion,
|
|
1007
|
+
deviceKey: key,
|
|
1008
|
+
})
|
|
1009
|
+
try {
|
|
1010
|
+
const response = await this.post(body, OPEN_PATH)
|
|
1011
|
+
const answer = await response.text().catch(() => '')
|
|
1012
|
+
if (this.state.optedOut || anonymousId !== this.state.anonymousId) return
|
|
1013
|
+
if (!response.ok) {
|
|
1014
|
+
this.warn(`The link was refused (${response.status}): ${answer}`)
|
|
1015
|
+
return
|
|
1016
|
+
}
|
|
1017
|
+
this.deliver(deepLinkFrom(parseAnswer(answer), url))
|
|
1018
|
+
} catch {
|
|
1019
|
+
this.warn('The link could not be sent: no connection.')
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
/** Hands a deep link to the handler; without one, the newest is held for the next handler. */
|
|
1024
|
+
private deliver(link: DeepLink | null): void {
|
|
1025
|
+
if (!link || this.stopped || this.state.optedOut) return
|
|
1026
|
+
const anonymousId = this.state.anonymousId
|
|
1027
|
+
const handler = this.deepLinkHandler
|
|
1028
|
+
if (!handler) {
|
|
1029
|
+
this.heldDeepLink = link
|
|
1030
|
+
return
|
|
1031
|
+
}
|
|
1032
|
+
// Later, so a handler set during a render or an effect runs after it.
|
|
1033
|
+
setTimeout(() => {
|
|
1034
|
+
try {
|
|
1035
|
+
if (!this.state.optedOut && anonymousId === this.state.anonymousId) handler(link)
|
|
1036
|
+
} catch (error) {
|
|
1037
|
+
this.warn(`onDeepLink threw: ${String(error)}`)
|
|
1038
|
+
}
|
|
1039
|
+
}, 0)
|
|
1040
|
+
}
|
|
1041
|
+
|
|
595
1042
|
private warn(message: string): void {
|
|
596
1043
|
if (this.options.debug) (this.env.log ?? console.warn)(`KissMyApps: ${message}`)
|
|
597
1044
|
}
|
|
598
1045
|
}
|
|
1046
|
+
|
|
1047
|
+
function retryable(status: number): boolean {
|
|
1048
|
+
return status >= 500 || status === 408 || status === 429 || status < 400
|
|
1049
|
+
}
|
|
1050
|
+
|
|
1051
|
+
function pendingInstall(value: unknown): PendingInstall | null {
|
|
1052
|
+
if (!value || typeof value !== 'object') return null
|
|
1053
|
+
const saved = value as Partial<PendingInstall>
|
|
1054
|
+
if (
|
|
1055
|
+
typeof saved.at !== 'number' ||
|
|
1056
|
+
typeof saved.anonymousId !== 'string' ||
|
|
1057
|
+
typeof saved.sessionId !== 'string'
|
|
1058
|
+
)
|
|
1059
|
+
return null
|
|
1060
|
+
const info = saved.info && typeof saved.info === 'object' ? savedInfo(saved.info) : undefined
|
|
1061
|
+
return {
|
|
1062
|
+
at: saved.at,
|
|
1063
|
+
anonymousId: saved.anonymousId,
|
|
1064
|
+
sessionId: saved.sessionId,
|
|
1065
|
+
link: typeof saved.link === 'string' ? saved.link : undefined,
|
|
1066
|
+
tries: typeof saved.tries === 'number' ? saved.tries : 0,
|
|
1067
|
+
info,
|
|
1068
|
+
infoComplete: info ? saved.infoComplete === true : undefined,
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
/** What is kept for the next tries: everything but the Apple Ads token, which expires. */
|
|
1073
|
+
function savedInfo(info: AttributionInfo): AttributionInfo {
|
|
1074
|
+
const kept: AttributionInfo = {}
|
|
1075
|
+
if (typeof info.deviceKey === 'string') kept.deviceKey = info.deviceKey
|
|
1076
|
+
if (typeof info.referrer === 'string') kept.referrer = info.referrer
|
|
1077
|
+
if (typeof info.referrerClickTs === 'number') kept.referrerClickTs = info.referrerClickTs
|
|
1078
|
+
if (typeof info.installBeginTs === 'number') kept.installBeginTs = info.installBeginTs
|
|
1079
|
+
if (typeof info.clipboardClick === 'string') kept.clipboardClick = info.clipboardClick
|
|
1080
|
+
return kept
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
function definedOnly(info: AttributionInfo): AttributionInfo {
|
|
1084
|
+
return Object.fromEntries(
|
|
1085
|
+
Object.entries(info).filter(([, value]) => value !== undefined && value !== null),
|
|
1086
|
+
) as AttributionInfo
|
|
1087
|
+
}
|