kv-test-lib 1.0.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.
@@ -0,0 +1,436 @@
1
+ /*
2
+ Authored by Brett Barinaga on 11/17/21.
3
+ Copyright (c) Kochava, Inc. All rights reserved.
4
+ */
5
+ import { Log } from "./utils/log";
6
+ import JobQueue from "./jobqueue";
7
+ import * as Kvinit from "./payloads/kvinit";
8
+ import * as Install from "./payloads/install";
9
+ import { DEFAULTS, } from "./interfaces";
10
+ import { deleteAllPersisted, readAndUpdatePersistedValue, updatePersistedValue, PersistKey, checkDuplicateIdLink, addPersistedIdLinks, checkInstallIdChange, readAndUpdateSessionCount, readAndUpdateDeviceId, readAndUpdateUTM, } from "./browser/persist";
11
+ import * as utils from "./utils/utils";
12
+ import { getPageName } from "./browser/browser";
13
+ export class Kochava {
14
+ // ============================= PUBLIC =============================== //
15
+ constructor() {
16
+ this.resetInstance();
17
+ this.jobQueue = new JobQueue();
18
+ }
19
+ /*
20
+ Set if the SDK should also store persisted values in cookie storage.
21
+ - Not all values can be persisted in cookies, such as event/idlink queues
22
+ due to size constraints.
23
+ - true = yes use cookies
24
+ - no = no don't use cookies
25
+ - defaults to false
26
+ */
27
+ useCookies(condition = false) {
28
+ this.instance.useCookies = condition;
29
+ }
30
+ /*
31
+ - Set whether the sdk shouldn't automatically send a page or should.
32
+ - true = no auto page
33
+ - false = yes auto page
34
+ - defaults to false
35
+ */
36
+ disableAutoPage(condition = false) {
37
+ this.instance.disableAutoPage = condition;
38
+ }
39
+ /*
40
+ The primary means for starting the sdk.
41
+ Responsibilites:
42
+ - Checks for migrations.
43
+ - Creates the sdk instance.
44
+ - Checks for persisted state.
45
+ - Determines and sends kvinit.
46
+ - Determines and sends install.
47
+ - Optionally enqueues an auto_page.
48
+ - Starts the job queue.
49
+ */
50
+ startWithAppGuid(appGuid) {
51
+ if (!appGuid) {
52
+ Log.error(`Invalid appGuid ${appGuid}, start failed.`);
53
+ return;
54
+ }
55
+ if (!this.instance)
56
+ this.resetInstance();
57
+ if (this.instance.started) {
58
+ Log.warn("Kochava SDK already started.");
59
+ return;
60
+ }
61
+ Log.diagDebug(`Host called API: Start With App Guid ${appGuid}`);
62
+ this.instance.started = true;
63
+ this.checkFirstLaunchAndMigrate();
64
+ this.initInstance(appGuid);
65
+ if (!this.instance.disableAutoPage)
66
+ this.sendPageEvent();
67
+ this.checkPersistedState();
68
+ this.checkPersistedKvinit();
69
+ this.printStartupMsgs(appGuid);
70
+ this.beginStart();
71
+ }
72
+ /*
73
+ Primary means for stopping the sdk.
74
+ Will optionally delete all persisted data, and will shutdown the
75
+ sdk and job queue.
76
+ */
77
+ shutdown(deleteData) {
78
+ Log.diagDebug(`Host called API: Shutdown and ${deleteData ? "delete data" : "keep data"}`);
79
+ if (deleteData) {
80
+ Log.debug("Deleting persisted values");
81
+ deleteAllPersisted();
82
+ }
83
+ if (!this.instance.started) {
84
+ Log.warn("SDK already shutdown.");
85
+ }
86
+ Log.info("SDK shutting down.");
87
+ Kvinit.cancelRetries();
88
+ Install.cancelRetries();
89
+ this.jobQueue.stop();
90
+ // wipe whatever was previously in the queue
91
+ this.jobQueue = new JobQueue();
92
+ this.resetInstance();
93
+ }
94
+ /*
95
+ Changes the current logLevel.
96
+ Options include:
97
+ - Off :: No logging whatsoever
98
+ - Error :: Only critical errors
99
+ - Warn :: Only critical errors and non-critical warnings
100
+ - Info :: High-level sdk behavior logs (default)
101
+ - Debug :: More in-depth sdk behavior logs and payload logs
102
+ - Trace :: Everything, granular detail
103
+ */
104
+ setLogLevel(logLevel) {
105
+ Log.diagDebug(`Host called API: Set Log Level ${logLevel}`);
106
+ Log.setLogLevel(logLevel);
107
+ }
108
+ /*
109
+ Used internally, for special SDK behavior not utilized by a client.
110
+ Examples include:
111
+ - urls :: purposefully changing an endpoint for testing
112
+ - wrapper :: overwriting the version of a wrapper
113
+ several more ...
114
+ */
115
+ executeAdvancedInstruction(key, valueStr, callback) {
116
+ Log.diagDebug(`Host called API: Execute Advanced Instruction ${key}`);
117
+ switch (key) {
118
+ case "wrapper":
119
+ {
120
+ const wrapperVersion = JSON.parse(valueStr);
121
+ this.instance.version = `${this.instance.version} (${wrapperVersion.name} ${wrapperVersion.version})`;
122
+ }
123
+ break;
124
+ case "urls":
125
+ {
126
+ const overrideUrls = JSON.parse(valueStr);
127
+ if (overrideUrls.init)
128
+ this.instance.overrideUrls.init = overrideUrls.init;
129
+ if (overrideUrls.event)
130
+ this.instance.overrideUrls.event = overrideUrls.event;
131
+ if (overrideUrls.install)
132
+ this.instance.overrideUrls.install = overrideUrls.install;
133
+ if (overrideUrls.identityLink)
134
+ this.instance.overrideUrls.identityLink = overrideUrls.identityLink;
135
+ }
136
+ break;
137
+ case "urlsRestore":
138
+ {
139
+ const restoreUrls = JSON.parse(valueStr);
140
+ for (const url of restoreUrls) {
141
+ if (url === "init")
142
+ this.instance.overrideUrls.init = DEFAULTS.networking.urls.init;
143
+ if (url === "event")
144
+ this.instance.overrideUrls.event = DEFAULTS.networking.urls.event;
145
+ if (url === "install")
146
+ this.instance.overrideUrls.install =
147
+ DEFAULTS.networking.urls.install;
148
+ if (url === "identityLink")
149
+ this.instance.overrideUrls.identityLink =
150
+ DEFAULTS.networking.urls.identityLink;
151
+ }
152
+ }
153
+ break;
154
+ case "logFilter":
155
+ {
156
+ const disabled = JSON.parse(valueStr);
157
+ disabled.forEach((level) => Log.disableLogType(level));
158
+ }
159
+ break;
160
+ case "getInstance":
161
+ {
162
+ const currInstance = JSON.stringify(this.instance);
163
+ callback(currInstance);
164
+ Log.debug(`capturing instance: ${valueStr}`);
165
+ }
166
+ break;
167
+ case "logObjects":
168
+ Log.setLogObjects(JSON.parse(valueStr));
169
+ break;
170
+ default:
171
+ break;
172
+ }
173
+ }
174
+ /*
175
+ Builds and enqueues a kochava event. Must include an event_name string,
176
+ with optional event_data as either another string or object.
177
+ */
178
+ sendEvent(name, data) {
179
+ Log.diagDebug(`Host called API: Send Event`);
180
+ if (!name) {
181
+ Log.warn("Invalid event name, ignoring call.");
182
+ return;
183
+ }
184
+ this.jobQueue.enqueueEvent(this.instance, [name, data]);
185
+ }
186
+ /*
187
+ Wraps the sendEvent call with predefined data specific to page events.
188
+ */
189
+ sendPageEvent(pageName, additionalData) {
190
+ if (pageName)
191
+ this.sendEvent("page", Object.assign({ page_name: pageName }, additionalData));
192
+ else
193
+ this.sendEvent("page", Object.assign({ page_name: getPageName() }, additionalData));
194
+ }
195
+ /*
196
+ - Registers new identity links with the sdk, either to be sent out with
197
+ the install, or standalone.
198
+ - Will update an identity link if its key already exists in storage.
199
+ - A max of 10 identity links are currently allowed to be stored
200
+ at any one time.
201
+ */
202
+ registerIdentityLink(name, identifier) {
203
+ Log.diagDebug(`Host called API: Register Identity Link ${name}`);
204
+ if (!name || !identifier) {
205
+ Log.warn("Invalid identity link, ignoring call.");
206
+ return;
207
+ }
208
+ if (checkDuplicateIdLink(name, identifier)) {
209
+ Log.debug("Duplicate Identity Link found, ignoring.");
210
+ return;
211
+ }
212
+ const idLink = {};
213
+ idLink[name] = identifier;
214
+ addPersistedIdLinks(name, identifier, this.instance.useCookies);
215
+ if (this.instance.installStarted || this.instance.installDone) {
216
+ // it will be sent standalone
217
+ this.jobQueue.enqueueIdLink(this.instance, idLink);
218
+ }
219
+ // will be sent in install
220
+ }
221
+ // Allows the client to attach arbitrary data to certain payloads.
222
+ registerCustomValue(name, value) {
223
+ Log.diagDebug(`Host called API: Register Custom Value ${name}`);
224
+ if (!name || !value) {
225
+ Log.warn("Invalid custom value, ignoring call.");
226
+ return;
227
+ }
228
+ const dataToAdorn = {};
229
+ dataToAdorn[name] = value;
230
+ this.instance.customValues.push({ data: dataToAdorn, isDeviceId: false });
231
+ }
232
+ // Allows the client to attach arbitrary identifiers to go out in the install.
233
+ registerCustomDeviceIdentifier(name, value) {
234
+ Log.diagDebug(`Host called API: Register Custom Device Identifier ${name}`);
235
+ if (!name || !value) {
236
+ Log.warn("Invalid custom device identifier, ignoring call.");
237
+ return;
238
+ }
239
+ const dataToAdorn = {};
240
+ dataToAdorn[name] = value;
241
+ this.instance.customValues.push({ data: dataToAdorn, isDeviceId: true });
242
+ }
243
+ /*
244
+ Returns whether or not the sdk is in a "started" state.
245
+ This basically amounts to if start has been called,
246
+ not if kvinit is done or the queue is started.
247
+ Likewise, shutdown will set "started" to false;
248
+ */
249
+ getStarted() {
250
+ return this.instance.started;
251
+ }
252
+ /*
253
+ Returns the current kochavaDeviceId, or "" if called too early.
254
+ */
255
+ getDeviceId() {
256
+ Log.diagDebug(`Host called API: Get Kochava Device Id`);
257
+ if (this.instance.started)
258
+ return this.instance.kochavaDeviceId;
259
+ else
260
+ return "";
261
+ }
262
+ /*
263
+ Puts the sdk in a "sleep" state. This will stop the sdk from dequeuing
264
+ new jobs and retrying failed jobs. Different than shutdown, because the
265
+ current state is not destroyed.
266
+ */
267
+ setSleep(sleep) {
268
+ Log.diagDebug(`Host called API: Sleep ${sleep ? "Stop" : "Start"}`);
269
+ if (sleep && !this.instance.sleep) {
270
+ // only pause if it was running
271
+ this.instance.sleep = sleep;
272
+ this.jobQueue.pause();
273
+ }
274
+ else if (!sleep && this.instance.sleep) {
275
+ // only resume queueing if it was paused
276
+ this.instance.sleep = sleep;
277
+ this.beginStart();
278
+ }
279
+ }
280
+ // ============================= PRIVATE =============================== //
281
+ // Unintialized/invalid state.
282
+ // start must be called before these values will be correct.
283
+ resetInstance() {
284
+ this.instance = {
285
+ appGuid: "",
286
+ started: false,
287
+ installStarted: false,
288
+ kvinitDone: false,
289
+ installDone: false,
290
+ disableAutoPage: false,
291
+ useCookies: false,
292
+ sleep: false,
293
+ version: "Web 3.0.0",
294
+ buildDate: "",
295
+ overrideUrls: {
296
+ init: "",
297
+ install: "",
298
+ event: "",
299
+ identityLink: "",
300
+ },
301
+ customValues: [],
302
+ kochavaSession: "",
303
+ retryWaterfall: [],
304
+ startTimeMS: 0,
305
+ utm: "",
306
+ kochavaDeviceId: "",
307
+ kochavaInstallId: "",
308
+ kochavaSessionCount: -1,
309
+ kochavaInstallDate: -1,
310
+ kochavaConfig: undefined,
311
+ };
312
+ }
313
+ initInstance(appGuid) {
314
+ // init instance with defaults
315
+ this.instance.appGuid = appGuid;
316
+ this.instance.disableAutoPage = this.instance.disableAutoPage || false;
317
+ this.instance.useCookies = this.instance.useCookies || false;
318
+ this.instance.version = "Web 3.0.0";
319
+ this.instance.buildDate = "kbd: 3/29/2022, 9:27:29 AM";
320
+ this.instance.kochavaSession = utils.uuidv4().substring(0, 5);
321
+ this.instance.startTimeMS = utils.getCurrTimeMS();
322
+ this.instance.retryWaterfall = [7, 30, 300, 1800];
323
+ this.instance.kochavaConfig = JSON.parse(JSON.stringify(DEFAULTS));
324
+ }
325
+ checkFirstLaunchAndMigrate() {
326
+ // If this is our first launch ever, set it in persistence.
327
+ if (!readAndUpdatePersistedValue(PersistKey.FirstStartDate, this.instance.useCookies)) {
328
+ updatePersistedValue(PersistKey.FirstStartDate, String(utils.getCurrTimeSec()), this.instance.useCookies);
329
+ /*
330
+ On a first launch of the v3 sdk, we need to migrate old persisted kv_id
331
+ from v2.2, v2.3, and v2.5
332
+ */
333
+ // perform migration
334
+ const oldKvId = readAndUpdatePersistedValue(PersistKey.OldKvid, this.instance.useCookies);
335
+ if (oldKvId) {
336
+ updatePersistedValue(PersistKey.DeviceId, oldKvId, this.instance.useCookies);
337
+ updatePersistedValue(PersistKey.InstallSentDate, JSON.stringify(utils.getCurrTimeSec()), this.instance.useCookies);
338
+ }
339
+ }
340
+ }
341
+ checkPersistedKvinit() {
342
+ // check if persisted kvinit
343
+ let persistedKvinit = {};
344
+ const persistedKvinitStr = readAndUpdatePersistedValue(PersistKey.LastKvinit, this.instance.useCookies);
345
+ if (persistedKvinitStr) {
346
+ persistedKvinit = JSON.parse(persistedKvinitStr);
347
+ if (persistedKvinit) {
348
+ // if persisted kvinit, apply it
349
+ Log.trace("Found persisted kvinit.", persistedKvinit);
350
+ Kvinit.applyKvinitResp(this.instance, persistedKvinit);
351
+ Log.trace("KochavaConfig after persistedKvinit:", JSON.parse(JSON.stringify(this.instance.kochavaConfig)));
352
+ }
353
+ }
354
+ // check refresh minimum too
355
+ const persistedKvinitDateStr = readAndUpdatePersistedValue(PersistKey.KvinitSentDate, this.instance.useCookies);
356
+ if (persistedKvinitDateStr) {
357
+ const lastKvinitDate = JSON.parse(persistedKvinitDateStr);
358
+ if (lastKvinitDate) {
359
+ const refreshMin = this.instance.kochavaConfig.config.refresh_minimum;
360
+ if (utils.getCurrTimeSec() - lastKvinitDate < refreshMin)
361
+ this.instance.kvinitDone = true;
362
+ }
363
+ }
364
+ }
365
+ checkPersistedState() {
366
+ this.instance.installDone =
367
+ readAndUpdatePersistedValue(PersistKey.InstallSentDate, this.instance.useCookies).length > 0;
368
+ this.instance.kochavaInstallId = readAndUpdatePersistedValue(PersistKey.InstallId, this.instance.useCookies);
369
+ this.instance.kochavaDeviceId = readAndUpdateDeviceId(this.instance.useCookies);
370
+ this.instance.kochavaSessionCount = readAndUpdateSessionCount(this.instance.useCookies);
371
+ this.instance.utm = readAndUpdateUTM(this.instance.appGuid, this.instance.useCookies);
372
+ }
373
+ printStartupMsgs(appGuid) {
374
+ Log.diagInfo(`Started SDK ${this.instance.version}
375
+ published ${this.instance.buildDate}`);
376
+ Log.diagInfo(`The log level is set to ${Log.getLogLevel()}`);
377
+ Log.diagDebug(`This ${!this.instance.installDone ? "is" : "is not"} the first tracker SDK launch`);
378
+ Log.diagDebug(`The kochava device id is ${this.instance.kochavaDeviceId}`);
379
+ Log.diagDebug(`The kochava app GUID provided was ${appGuid}`);
380
+ }
381
+ async beginStart() {
382
+ // if we need to send a new kvinit, send it
383
+ if (!this.instance.kvinitDone) {
384
+ Log.diagDebug(`A new kvinit will be sent`);
385
+ await this.performNewKvinit();
386
+ }
387
+ else {
388
+ Log.diagDebug(`A new kvinit will not be sent`);
389
+ }
390
+ // if the install_id changed and thus a new install must go out
391
+ if (this.checkResendId())
392
+ this.instance.installDone = false;
393
+ Log.diagDebug(`The install ${this.instance.installDone ? "has already" : "has not yet"} been sent`);
394
+ if (this.instance.sleep)
395
+ return;
396
+ if (!this.instance.installDone) {
397
+ await this.performInstall();
398
+ }
399
+ if (this.instance.kvinitDone && this.instance.installDone) {
400
+ await this.jobQueue.start(this.instance);
401
+ }
402
+ }
403
+ async performNewKvinit() {
404
+ this.instance.kvinitDone = await Kvinit.send(this.instance, this.instance.retryWaterfall);
405
+ updatePersistedValue(PersistKey.KvinitSentDate, String(utils.getCurrTimeSec()), this.instance.useCookies);
406
+ // if new kvinit, apply it
407
+ let newKvinit = {};
408
+ const newKvinitStr = readAndUpdatePersistedValue(PersistKey.LastKvinit, this.instance.useCookies);
409
+ if (newKvinitStr) {
410
+ newKvinit = JSON.parse(newKvinitStr);
411
+ }
412
+ Kvinit.applyKvinitResp(this.instance, newKvinit);
413
+ Log.trace("KochavaConfig after new Kvinit:", JSON.parse(JSON.stringify(this.instance.kochavaConfig)));
414
+ }
415
+ checkResendId() {
416
+ let resendId = "";
417
+ if (this.instance.kochavaConfig.install) {
418
+ resendId = this.instance.kochavaConfig.install.resend_id;
419
+ }
420
+ const needsNewInstall = checkInstallIdChange(resendId, this.instance.useCookies);
421
+ if (needsNewInstall) {
422
+ Log.debug(`resend_id ${resendId} found, forcing new install`);
423
+ }
424
+ return needsNewInstall;
425
+ }
426
+ async performInstall() {
427
+ const request = Install.build(this.instance);
428
+ this.instance.installDone = await Install.send(this.instance, request);
429
+ if (!this.instance.installDone)
430
+ return;
431
+ // If the install succeeded, remove all idLink that were passed to it
432
+ Install.onSuccess(this.instance);
433
+ updatePersistedValue(PersistKey.IdLinkQueue, JSON.stringify(this.jobQueue.idLinkQueue), false);
434
+ }
435
+ }
436
+ window.kochava = new Kochava();
@@ -0,0 +1,6 @@
1
+ import { Json } from "../interfaces";
2
+ import { KochavaInstance } from "../kochava";
3
+ import { PreStartBody, PostStartBody } from "./payload";
4
+ export declare const constructPreStart: (instance: KochavaInstance, eventName: string, eventData?: Json | string) => PreStartBody;
5
+ export declare const constructPostStart: (instance: KochavaInstance, preStartBody: PreStartBody) => PostStartBody;
6
+ export declare const send: (instance: KochavaInstance, preStartBody: PreStartBody, postStartBody: PostStartBody) => Promise<boolean>;
@@ -0,0 +1,92 @@
1
+ /*
2
+ Authored by Brett Barinaga on 11/17/21.
3
+ Copyright (c) Kochava, Inc. All rights reserved.
4
+ */
5
+ import * as http from "../http";
6
+ import * as utils from "../utils/utils";
7
+ import * as browser from "../browser/browser";
8
+ import { Log } from "../utils/log";
9
+ import { constructCommonData } from "./payload";
10
+ export const constructPreStart = (instance, eventName, eventData) => {
11
+ const preStart = {
12
+ action: "event",
13
+ sdk_version: instance.version,
14
+ sdk_protocol: "17",
15
+ data: {
16
+ event_name: eventName,
17
+ event_data: eventData,
18
+ device_orientation: browser.getDeviceOrientation(),
19
+ disp_w: browser.getDeviceWidth(),
20
+ disp_h: browser.getDeviceHeight(),
21
+ },
22
+ };
23
+ if (instance.kochavaConfig)
24
+ preStart.init_token = (instance.kochavaConfig.config.init_token) || undefined;
25
+ return preStart;
26
+ };
27
+ export const constructPostStart = (instance, preStartBody) => {
28
+ const postStartBody = {
29
+ kochava_app_id: instance.appGuid,
30
+ kochava_device_id: instance.kochavaDeviceId,
31
+ nt_id: `${instance.kochavaSession}-${instance.kochavaSessionCount}-${utils.uuidv4()}`,
32
+ };
33
+ postStartBody.data = Object.assign(Object.assign({}, constructCommonData(instance)), preStartBody.data);
34
+ instance.customValues.forEach((custom) => {
35
+ if (!custom.isDeviceId) {
36
+ const customKey = Object.keys(custom.data)[0];
37
+ if (instance.kochavaConfig.privacy) {
38
+ let keyAllowed = false;
39
+ for (const allowed of instance.kochavaConfig.privacy.allow_custom_ids) {
40
+ if (customKey === allowed) {
41
+ keyAllowed = true;
42
+ }
43
+ }
44
+ if (keyAllowed)
45
+ postStartBody.data = Object.assign(Object.assign({}, custom.data), postStartBody.data);
46
+ }
47
+ }
48
+ });
49
+ return postStartBody;
50
+ };
51
+ const build = (instance, preStartBody, postStartBody) => {
52
+ const payload = Object.assign(Object.assign({}, preStartBody), postStartBody);
53
+ Log.debug("Event Payload", JSON.stringify(payload));
54
+ if (instance.kochavaConfig.privacy) {
55
+ instance.kochavaConfig.privacy.deny_datapoints.forEach(denyPoint => {
56
+ for (const point in payload.data) {
57
+ const key = point;
58
+ if (key === denyPoint)
59
+ delete payload.data[key];
60
+ }
61
+ for (const point in payload) {
62
+ const key = point;
63
+ if (key === denyPoint)
64
+ delete payload[key];
65
+ }
66
+ });
67
+ }
68
+ return payload;
69
+ };
70
+ export const send = async (instance, preStartBody, postStartBody) => {
71
+ const payload = build(instance, preStartBody, postStartBody);
72
+ const respStr = await http.sendRequest(payload, (instance.overrideUrls.event) ?
73
+ instance.overrideUrls.event : instance.kochavaConfig.networking.urls.event);
74
+ let resp;
75
+ let success = false;
76
+ try {
77
+ Log.trace("Event Response string:", respStr);
78
+ resp = JSON.parse(respStr);
79
+ Log.debug("Event Response:", respStr);
80
+ success = http.wasRespSuccess(resp.success);
81
+ }
82
+ catch (e) {
83
+ Log.error("Error parsing Event Response", e);
84
+ success = false;
85
+ }
86
+ if (success) {
87
+ Log.info("Event success!");
88
+ return true;
89
+ }
90
+ Log.error("Event failed!");
91
+ return false;
92
+ };
@@ -0,0 +1,7 @@
1
+ import { IdentityLink } from "../interfaces";
2
+ import { KochavaInstance } from "../kochava";
3
+ import { PostStartBody, PreStartBody } from "./payload";
4
+ import { IdLinkJob } from "../jobqueue";
5
+ export declare const constructPreStart: (instance: KochavaInstance, idLink: IdentityLink) => PreStartBody;
6
+ export declare const constructPostStart: (instance: KochavaInstance, preStartBody: PreStartBody) => PostStartBody;
7
+ export declare const send: (instance: KochavaInstance, job: IdLinkJob) => Promise<boolean>;
@@ -0,0 +1,73 @@
1
+ /*
2
+ Authored by Brett Barinaga on 11/18/21.
3
+ Copyright (c) Kochava, Inc. All rights reserved.
4
+ */
5
+ import * as http from "../http";
6
+ import * as utils from "../utils/utils";
7
+ import { Log } from "../utils/log";
8
+ import { constructCommonData } from "./payload";
9
+ export const constructPreStart = (instance, idLink) => {
10
+ const preStart = {
11
+ action: "identityLink",
12
+ sdk_version: instance.version,
13
+ sdk_protocol: "17",
14
+ data: {
15
+ identity_link: Object.assign({}, idLink),
16
+ },
17
+ };
18
+ if (instance.kochavaConfig)
19
+ preStart.init_token = (instance.kochavaConfig.config.init_token) || undefined;
20
+ return preStart;
21
+ };
22
+ export const constructPostStart = (instance, preStartBody) => {
23
+ const postStartBody = {
24
+ kochava_app_id: instance.appGuid,
25
+ kochava_device_id: instance.kochavaDeviceId,
26
+ nt_id: `${instance.kochavaSession}-${instance.kochavaSessionCount}-${utils.uuidv4()}`,
27
+ };
28
+ postStartBody.data = Object.assign(Object.assign({}, preStartBody.data), constructCommonData(instance));
29
+ return postStartBody;
30
+ };
31
+ const build = (instance, job) => {
32
+ const payload = Object.assign(Object.assign({}, job.preStartBody), job.postStartBody);
33
+ Log.debug("IdentityLink Payload", JSON.stringify(payload));
34
+ Log.diagDebug(`IdentityLink to be sent as stand alone`);
35
+ if (instance.kochavaConfig.privacy) {
36
+ instance.kochavaConfig.privacy.deny_datapoints.forEach(denyPoint => {
37
+ for (const point in payload.data) {
38
+ const key = point;
39
+ if (key === denyPoint)
40
+ delete payload.data[key];
41
+ }
42
+ for (const point in payload) {
43
+ const key = point;
44
+ if (key === denyPoint)
45
+ delete payload[key];
46
+ }
47
+ });
48
+ }
49
+ return payload;
50
+ };
51
+ export const send = async (instance, job) => {
52
+ const payload = build(instance, job);
53
+ const respStr = await http.sendRequest(payload, (instance.overrideUrls.identityLink) ?
54
+ instance.overrideUrls.identityLink : instance.kochavaConfig.networking.urls.identityLink);
55
+ let resp;
56
+ let success = false;
57
+ try {
58
+ Log.trace("IdentityLink Response string:", respStr);
59
+ resp = JSON.parse(respStr);
60
+ Log.debug("IdentityLink Response:", respStr);
61
+ success = http.wasRespSuccess(resp.success);
62
+ }
63
+ catch (e) {
64
+ Log.error("Error parsing IdentityLink Response", e);
65
+ success = false;
66
+ }
67
+ if (success) {
68
+ Log.info("IdentityLink success!");
69
+ return true;
70
+ }
71
+ Log.error("IdentityLink failed!");
72
+ return false;
73
+ };
@@ -0,0 +1,6 @@
1
+ import { KochavaInstance } from "../kochava";
2
+ import { Payload } from "./payload";
3
+ export declare const build: (instance: KochavaInstance) => Payload;
4
+ export declare const cancelRetries: () => void;
5
+ export declare const send: (instance: KochavaInstance, payload: Payload, retries?: number) => Promise<boolean>;
6
+ export declare const onSuccess: (instance: KochavaInstance) => void;