@traqio/web 0.0.0-stage → 0.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/LICENSE +21 -0
- package/README.md +127 -2
- package/build/cookies.d.ts +13 -0
- package/build/index.cjs +1491 -0
- package/build/index.cjs.map +7 -0
- package/build/index.d.ts +83 -0
- package/build/index.js +1484 -0
- package/build/index.js.map +7 -0
- package/build/snippet.d.ts +6 -0
- package/build/storage.d.ts +46 -0
- package/build/test/fakeBrowser.d.ts +25 -0
- package/build/trackId.d.ts +35 -0
- package/build/traqio.min.js +2 -0
- package/build/traqio.min.js.map +7 -0
- package/package.json +49 -3
package/build/index.cjs
ADDED
|
@@ -0,0 +1,1491 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res, err) => function __init() {
|
|
9
|
+
if (err) throw err[0];
|
|
10
|
+
try {
|
|
11
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
12
|
+
} catch (e) {
|
|
13
|
+
throw err = [e], e;
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
17
|
+
try {
|
|
18
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
19
|
+
} catch (e) {
|
|
20
|
+
throw mod = 0, e;
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
var __export = (target, all) => {
|
|
24
|
+
for (var name in all)
|
|
25
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
26
|
+
};
|
|
27
|
+
var __copyProps = (to, from, except, desc) => {
|
|
28
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
29
|
+
for (let key of __getOwnPropNames(from))
|
|
30
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
31
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
32
|
+
}
|
|
33
|
+
return to;
|
|
34
|
+
};
|
|
35
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
36
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
37
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
38
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
39
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
40
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
41
|
+
mod
|
|
42
|
+
));
|
|
43
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
44
|
+
|
|
45
|
+
// ../sdk-core/build/skan.js
|
|
46
|
+
var require_skan = __commonJS({
|
|
47
|
+
"../sdk-core/build/skan.js"(exports) {
|
|
48
|
+
"use strict";
|
|
49
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
50
|
+
exports.Skan = exports.SKAN_STATE_KEY = exports.CONVERSION_WINDOWS = void 0;
|
|
51
|
+
exports.windowForAge = windowForAge;
|
|
52
|
+
exports.shouldLockWindow = shouldLockWindow;
|
|
53
|
+
exports.fineValueForRevenue = fineValueForRevenue;
|
|
54
|
+
exports.fineValueForEvents = fineValueForEvents;
|
|
55
|
+
exports.coarseValueForRevenue = coarseValueForRevenue;
|
|
56
|
+
exports.CONVERSION_WINDOWS = [
|
|
57
|
+
{ window: 0, startHours: 0, endHours: 48 },
|
|
58
|
+
{ window: 1, startHours: 48, endHours: 168 },
|
|
59
|
+
{ window: 2, startHours: 168, endHours: 840 }
|
|
60
|
+
];
|
|
61
|
+
function windowForAge(hoursSinceInstall) {
|
|
62
|
+
const found = exports.CONVERSION_WINDOWS.find((w) => hoursSinceInstall >= w.startHours && hoursSinceInstall < w.endHours);
|
|
63
|
+
return found ? found.window : null;
|
|
64
|
+
}
|
|
65
|
+
function shouldLockWindow(windows, hoursSinceInstall) {
|
|
66
|
+
const current = windowForAge(hoursSinceInstall);
|
|
67
|
+
if (current == null || !windows || !windows.length)
|
|
68
|
+
return false;
|
|
69
|
+
const rule = windows.find((w) => w.window === current);
|
|
70
|
+
if (!rule || !rule.lock)
|
|
71
|
+
return false;
|
|
72
|
+
if (rule.lockAfterHours == null)
|
|
73
|
+
return true;
|
|
74
|
+
return hoursSinceInstall >= rule.lockAfterHours;
|
|
75
|
+
}
|
|
76
|
+
var MAX_FINE_VALUE = 63;
|
|
77
|
+
var MAX_EVENT_BITS = 6;
|
|
78
|
+
function fineValueForRevenue(revenue, buckets) {
|
|
79
|
+
let value = 0;
|
|
80
|
+
for (let i = 0; i < Math.min(buckets.length, MAX_FINE_VALUE + 1); i++) {
|
|
81
|
+
if (revenue >= buckets[i])
|
|
82
|
+
value = i;
|
|
83
|
+
}
|
|
84
|
+
return value;
|
|
85
|
+
}
|
|
86
|
+
function fineValueForEvents(events, bits) {
|
|
87
|
+
const reached = new Set(events);
|
|
88
|
+
let value = 0;
|
|
89
|
+
bits.slice(0, MAX_EVENT_BITS).forEach((name, i) => {
|
|
90
|
+
if (reached.has(name))
|
|
91
|
+
value |= 1 << i;
|
|
92
|
+
});
|
|
93
|
+
return value;
|
|
94
|
+
}
|
|
95
|
+
function coarseValueForRevenue(revenue, tiers) {
|
|
96
|
+
if (!tiers)
|
|
97
|
+
return void 0;
|
|
98
|
+
let best;
|
|
99
|
+
let bestThreshold = -Infinity;
|
|
100
|
+
for (const tier of ["low", "medium", "high"]) {
|
|
101
|
+
const threshold = tiers[tier];
|
|
102
|
+
if (threshold != null && revenue >= threshold && threshold >= bestThreshold) {
|
|
103
|
+
best = tier;
|
|
104
|
+
bestThreshold = threshold;
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return best;
|
|
108
|
+
}
|
|
109
|
+
var EMPTY_STATE = { revenue: 0, events: [], lastFine: null };
|
|
110
|
+
exports.SKAN_STATE_KEY = "traq_skan_state";
|
|
111
|
+
var Skan = class {
|
|
112
|
+
constructor() {
|
|
113
|
+
this.mapping = null;
|
|
114
|
+
this.state = { ...EMPTY_STATE };
|
|
115
|
+
this.enabled = false;
|
|
116
|
+
}
|
|
117
|
+
async init(opts) {
|
|
118
|
+
this.opts = opts;
|
|
119
|
+
this.enabled = Boolean(opts.native);
|
|
120
|
+
if (!this.enabled)
|
|
121
|
+
return;
|
|
122
|
+
await this.restore();
|
|
123
|
+
if (this.state.firstSeenAt == null) {
|
|
124
|
+
this.state.firstSeenAt = this.now();
|
|
125
|
+
await this.persist();
|
|
126
|
+
}
|
|
127
|
+
this.mapping = await this.fetchMapping();
|
|
128
|
+
if (this.mapping)
|
|
129
|
+
this.push();
|
|
130
|
+
}
|
|
131
|
+
/**
|
|
132
|
+
* Add revenue this install produced. SKAN encodes a LIFETIME total, not one
|
|
133
|
+
* purchase, so amounts accumulate — passing a single sale twice double-counts
|
|
134
|
+
* it, same as anywhere else.
|
|
135
|
+
*/
|
|
136
|
+
addRevenue(amount) {
|
|
137
|
+
if (!this.enabled || !(amount > 0) || !Number.isFinite(amount))
|
|
138
|
+
return;
|
|
139
|
+
this.state.revenue += amount;
|
|
140
|
+
void this.persist();
|
|
141
|
+
this.push();
|
|
142
|
+
}
|
|
143
|
+
/** Mark a milestone reached (events mode). Repeats are idempotent. */
|
|
144
|
+
markEvent(name) {
|
|
145
|
+
if (!this.enabled || this.state.events.includes(name))
|
|
146
|
+
return;
|
|
147
|
+
this.state.events.push(name);
|
|
148
|
+
void this.persist();
|
|
149
|
+
this.push();
|
|
150
|
+
}
|
|
151
|
+
/** The mapping in force, for callers that want to show it. Null until fetched. */
|
|
152
|
+
get activeMapping() {
|
|
153
|
+
return this.mapping;
|
|
154
|
+
}
|
|
155
|
+
// ── internals ──────────────────────────────────────────
|
|
156
|
+
push() {
|
|
157
|
+
var _a, _b;
|
|
158
|
+
const m = this.mapping;
|
|
159
|
+
if (!m || !this.opts.native)
|
|
160
|
+
return;
|
|
161
|
+
let fine;
|
|
162
|
+
let coarse;
|
|
163
|
+
if (m.mode === "events") {
|
|
164
|
+
if (!((_a = m.eventBits) == null ? void 0 : _a.length))
|
|
165
|
+
return;
|
|
166
|
+
fine = fineValueForEvents(this.state.events, m.eventBits);
|
|
167
|
+
} else {
|
|
168
|
+
if (!((_b = m.revenueBuckets) == null ? void 0 : _b.length))
|
|
169
|
+
return;
|
|
170
|
+
fine = fineValueForRevenue(this.state.revenue, m.revenueBuckets);
|
|
171
|
+
coarse = coarseValueForRevenue(this.state.revenue, m.coarseRevenue);
|
|
172
|
+
}
|
|
173
|
+
if (this.state.lastFine == null && fine === 0)
|
|
174
|
+
return;
|
|
175
|
+
if (this.state.lastFine != null && fine <= this.state.lastFine)
|
|
176
|
+
return;
|
|
177
|
+
this.state.lastFine = fine;
|
|
178
|
+
void this.persist();
|
|
179
|
+
this.opts.native.updateConversionValue(fine, coarse, this.lockWindowNow());
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Whether this update closes the current conversion window, per the schedule the
|
|
183
|
+
* mapping published. Without a mapping, or with no rule for the window we are in,
|
|
184
|
+
* the answer is false — Apple's own timing, which gives nothing up.
|
|
185
|
+
*/
|
|
186
|
+
lockWindowNow() {
|
|
187
|
+
var _a;
|
|
188
|
+
const since = this.state.firstSeenAt;
|
|
189
|
+
if (since == null)
|
|
190
|
+
return false;
|
|
191
|
+
const hours = (this.now() - since) / 36e5;
|
|
192
|
+
return shouldLockWindow((_a = this.mapping) == null ? void 0 : _a.postbackWindows, hours);
|
|
193
|
+
}
|
|
194
|
+
now() {
|
|
195
|
+
return this.opts.nowFn ? this.opts.nowFn() : Date.now();
|
|
196
|
+
}
|
|
197
|
+
async fetchMapping() {
|
|
198
|
+
var _a;
|
|
199
|
+
const doFetch = (_a = this.opts.fetchFn) != null ? _a : typeof fetch === "function" ? fetch : void 0;
|
|
200
|
+
if (!doFetch)
|
|
201
|
+
return null;
|
|
202
|
+
try {
|
|
203
|
+
const res = await doFetch(`${this.opts.endpoint}/skan/mapping/${encodeURIComponent(this.opts.sdkKey)}`);
|
|
204
|
+
if (!res.ok)
|
|
205
|
+
return null;
|
|
206
|
+
const body = await res.json();
|
|
207
|
+
return body && typeof body === "object" ? body : null;
|
|
208
|
+
} catch {
|
|
209
|
+
return null;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
async restore() {
|
|
213
|
+
var _a;
|
|
214
|
+
try {
|
|
215
|
+
const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(exports.SKAN_STATE_KEY));
|
|
216
|
+
if (raw)
|
|
217
|
+
this.state = { ...EMPTY_STATE, ...JSON.parse(raw) };
|
|
218
|
+
} catch {
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
async persist() {
|
|
222
|
+
var _a;
|
|
223
|
+
try {
|
|
224
|
+
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(exports.SKAN_STATE_KEY, JSON.stringify(this.state)));
|
|
225
|
+
} catch {
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
};
|
|
229
|
+
exports.Skan = Skan;
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
|
|
233
|
+
// ../sdk-core/build/adservices.js
|
|
234
|
+
var require_adservices = __commonJS({
|
|
235
|
+
"../sdk-core/build/adservices.js"(exports) {
|
|
236
|
+
"use strict";
|
|
237
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
238
|
+
exports.ADSERVICES_ATTEMPTS_KEY = exports.ADSERVICES_SENT_KEY = void 0;
|
|
239
|
+
exports.reportAdServicesToken = reportAdServicesToken;
|
|
240
|
+
exports.ADSERVICES_SENT_KEY = "traq_adservices_sent";
|
|
241
|
+
exports.ADSERVICES_ATTEMPTS_KEY = "traq_adservices_attempts";
|
|
242
|
+
var MAX_ATTEMPTS = 5;
|
|
243
|
+
async function reportAdServicesToken(opts) {
|
|
244
|
+
var _a, _b;
|
|
245
|
+
if (!((_a = opts.native) == null ? void 0 : _a.getAttributionToken))
|
|
246
|
+
return "unsupported";
|
|
247
|
+
if (await read(opts, exports.ADSERVICES_SENT_KEY))
|
|
248
|
+
return "already-sent";
|
|
249
|
+
let token = null;
|
|
250
|
+
try {
|
|
251
|
+
token = await opts.native.getAttributionToken();
|
|
252
|
+
} catch {
|
|
253
|
+
}
|
|
254
|
+
if (!token || !token.trim()) {
|
|
255
|
+
const attempts = Number(await read(opts, exports.ADSERVICES_ATTEMPTS_KEY)) || 0;
|
|
256
|
+
await write(opts, exports.ADSERVICES_ATTEMPTS_KEY, String(attempts + 1));
|
|
257
|
+
if (attempts + 1 >= MAX_ATTEMPTS)
|
|
258
|
+
await write(opts, exports.ADSERVICES_SENT_KEY, "1");
|
|
259
|
+
return "no-token";
|
|
260
|
+
}
|
|
261
|
+
const doFetch = (_b = opts.fetchFn) != null ? _b : typeof fetch === "function" ? fetch : void 0;
|
|
262
|
+
if (!doFetch)
|
|
263
|
+
return "post-failed";
|
|
264
|
+
try {
|
|
265
|
+
const res = await doFetch(`${opts.endpoint}/ingest/adservices`, {
|
|
266
|
+
method: "POST",
|
|
267
|
+
headers: { "Content-Type": "application/json" },
|
|
268
|
+
body: JSON.stringify({
|
|
269
|
+
sdkKey: opts.sdkKey,
|
|
270
|
+
token: token.trim(),
|
|
271
|
+
deviceId: opts.deviceId,
|
|
272
|
+
appUserId: opts.userId
|
|
273
|
+
})
|
|
274
|
+
});
|
|
275
|
+
if (!res.ok)
|
|
276
|
+
return "post-failed";
|
|
277
|
+
} catch {
|
|
278
|
+
return "post-failed";
|
|
279
|
+
}
|
|
280
|
+
await write(opts, exports.ADSERVICES_SENT_KEY, "1");
|
|
281
|
+
return "sent";
|
|
282
|
+
}
|
|
283
|
+
async function read(opts, key) {
|
|
284
|
+
var _a, _b;
|
|
285
|
+
try {
|
|
286
|
+
return (_b = await ((_a = opts.storage) == null ? void 0 : _a.getItem(key))) != null ? _b : null;
|
|
287
|
+
} catch {
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async function write(opts, key, value) {
|
|
292
|
+
var _a;
|
|
293
|
+
try {
|
|
294
|
+
await ((_a = opts.storage) == null ? void 0 : _a.setItem(key, value));
|
|
295
|
+
} catch {
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
// ../sdk-core/build/deeplink.js
|
|
302
|
+
var require_deeplink = __commonJS({
|
|
303
|
+
"../sdk-core/build/deeplink.js"(exports) {
|
|
304
|
+
"use strict";
|
|
305
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
306
|
+
exports.isTrackingUrl = isTrackingUrl;
|
|
307
|
+
exports.toDeepLink = toDeepLink;
|
|
308
|
+
var TRACKING_PATH = /^\/c\/[A-Za-z0-9_-]{1,50}\/?$/;
|
|
309
|
+
function isTrackingUrl(url) {
|
|
310
|
+
var _a;
|
|
311
|
+
const m = /^https?:\/\/[^/?#]+(\/[^?#]*)?/i.exec(url);
|
|
312
|
+
return Boolean(m && TRACKING_PATH.test((_a = m[1]) != null ? _a : ""));
|
|
313
|
+
}
|
|
314
|
+
function toDeepLink(answer, deferred, url) {
|
|
315
|
+
if (!(answer == null ? void 0 : answer.matched) || !answer.via)
|
|
316
|
+
return null;
|
|
317
|
+
return { deepLink: answer.deepLink, code: answer.code, deferred, via: answer.via, ...url ? { url } : {} };
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
// src/shims/empty.ts
|
|
323
|
+
var empty_exports = {};
|
|
324
|
+
var init_empty = __esm({
|
|
325
|
+
"src/shims/empty.ts"() {
|
|
326
|
+
"use strict";
|
|
327
|
+
}
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
// ../sdk-core/build/index.js
|
|
331
|
+
var require_build = __commonJS({
|
|
332
|
+
"../sdk-core/build/index.js"(exports) {
|
|
333
|
+
"use strict";
|
|
334
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
335
|
+
exports.Traqio = exports.Client = exports.isTrackingUrl = exports.reportAdServicesToken = exports.Skan = exports.SDK_VERSION = void 0;
|
|
336
|
+
exports.normalizeAdvertisingId = normalizeAdvertisingId;
|
|
337
|
+
exports.fromMaxAd = fromMaxAd;
|
|
338
|
+
var skan_1 = require_skan();
|
|
339
|
+
var adservices_1 = require_adservices();
|
|
340
|
+
var deeplink_1 = require_deeplink();
|
|
341
|
+
exports.SDK_VERSION = "0.1.0";
|
|
342
|
+
var skan_2 = require_skan();
|
|
343
|
+
Object.defineProperty(exports, "Skan", { enumerable: true, get: function() {
|
|
344
|
+
return skan_2.Skan;
|
|
345
|
+
} });
|
|
346
|
+
var adservices_2 = require_adservices();
|
|
347
|
+
Object.defineProperty(exports, "reportAdServicesToken", { enumerable: true, get: function() {
|
|
348
|
+
return adservices_2.reportAdServicesToken;
|
|
349
|
+
} });
|
|
350
|
+
var deeplink_2 = require_deeplink();
|
|
351
|
+
Object.defineProperty(exports, "isTrackingUrl", { enumerable: true, get: function() {
|
|
352
|
+
return deeplink_2.isTrackingUrl;
|
|
353
|
+
} });
|
|
354
|
+
var INSTALL_SENT_KEY = "traq_install_sent";
|
|
355
|
+
var INSTALL_ATTEMPTS_KEY = "traq_install_attempts";
|
|
356
|
+
var REFERRER_KEY = "traq_referrer";
|
|
357
|
+
var QUEUE_KEY = "traq_queue";
|
|
358
|
+
var AD_QUEUE_KEY = "traq_ad_queue";
|
|
359
|
+
var DEVICE_ID_KEY2 = "traq_device_id";
|
|
360
|
+
var LAST_SESSION_KEY = "traq_last_session";
|
|
361
|
+
var ERASED_KEY = "traq_erased";
|
|
362
|
+
var DEFERRED_KEY = "traq_deferred_link";
|
|
363
|
+
var CONSENT_KEY = "traq_consent";
|
|
364
|
+
var MAX_BATCH = 20;
|
|
365
|
+
var MAX_QUEUE = 500;
|
|
366
|
+
var MAX_AD_BATCH = 100;
|
|
367
|
+
var MAX_AD_QUEUE = 1e3;
|
|
368
|
+
var BASE_RETRY_MS = 1e3;
|
|
369
|
+
var MAX_RETRY_MS = 5 * 60 * 1e3;
|
|
370
|
+
var FLUSH_DELAY_MS = 3e3;
|
|
371
|
+
var MAX_INSTALL_ATTEMPTS = 3;
|
|
372
|
+
var SESSION_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
373
|
+
var MAX_PRECISION = {
|
|
374
|
+
exact: "precise",
|
|
375
|
+
publisher_defined: "publisher_provided",
|
|
376
|
+
estimated: "estimated"
|
|
377
|
+
};
|
|
378
|
+
var MAX_FORMAT = {
|
|
379
|
+
BANNER: "banner",
|
|
380
|
+
LEADER: "banner",
|
|
381
|
+
MREC: "banner",
|
|
382
|
+
INTER: "interstitial",
|
|
383
|
+
INTERSTITIAL: "interstitial",
|
|
384
|
+
REWARDED: "rewarded",
|
|
385
|
+
REWARDED_INTER: "rewarded_interstitial",
|
|
386
|
+
NATIVE: "native",
|
|
387
|
+
APPOPEN: "app_open",
|
|
388
|
+
APP_OPEN: "app_open"
|
|
389
|
+
};
|
|
390
|
+
var ZERO_AD_ID = "00000000-0000-0000-0000-000000000000";
|
|
391
|
+
function normalizeAdvertisingId(raw) {
|
|
392
|
+
if (typeof raw !== "string")
|
|
393
|
+
return void 0;
|
|
394
|
+
const id = raw.trim();
|
|
395
|
+
if (!/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id))
|
|
396
|
+
return void 0;
|
|
397
|
+
return id === ZERO_AD_ID ? void 0 : id;
|
|
398
|
+
}
|
|
399
|
+
function fromMaxAd(ad) {
|
|
400
|
+
var _a, _b, _c;
|
|
401
|
+
if (!(typeof ad.revenue === "number" && Number.isFinite(ad.revenue) && ad.revenue >= 0))
|
|
402
|
+
return void 0;
|
|
403
|
+
return {
|
|
404
|
+
// Rounded to the micro, never earlier: a banner is worth ~0.00002 USD.
|
|
405
|
+
valueMicros: Math.round(ad.revenue * 1e6),
|
|
406
|
+
currency: "USD",
|
|
407
|
+
precision: (_b = MAX_PRECISION[(_a = ad.revenuePrecision) != null ? _a : ""]) != null ? _b : "unknown",
|
|
408
|
+
adUnitId: ad.adUnitId,
|
|
409
|
+
adFormat: MAX_FORMAT[((_c = ad.format) != null ? _c : "").toUpperCase()],
|
|
410
|
+
adSourceName: ad.networkName,
|
|
411
|
+
ts: ad.ts
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function uuid() {
|
|
415
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
|
416
|
+
const r = Math.random() * 16 | 0;
|
|
417
|
+
const v = c === "x" ? r : r & 3 | 8;
|
|
418
|
+
return v.toString(16);
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
function safeLocale() {
|
|
422
|
+
try {
|
|
423
|
+
return Intl.DateTimeFormat().resolvedOptions().locale;
|
|
424
|
+
} catch {
|
|
425
|
+
return void 0;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
function defaultStorage() {
|
|
429
|
+
var _a;
|
|
430
|
+
try {
|
|
431
|
+
const mod = (init_empty(), __toCommonJS(empty_exports));
|
|
432
|
+
const store = (_a = mod == null ? void 0 : mod.default) != null ? _a : mod;
|
|
433
|
+
if (typeof (store == null ? void 0 : store.getItem) === "function" && typeof (store == null ? void 0 : store.setItem) === "function") {
|
|
434
|
+
return {
|
|
435
|
+
getItem: (key) => store.getItem(key),
|
|
436
|
+
setItem: (key, value) => store.setItem(key, value)
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
}
|
|
441
|
+
return void 0;
|
|
442
|
+
}
|
|
443
|
+
var Client2 = class {
|
|
444
|
+
constructor() {
|
|
445
|
+
this.queue = [];
|
|
446
|
+
this.adQueue = [];
|
|
447
|
+
this.adBatchId = null;
|
|
448
|
+
this.context = { sdkVersion: exports.SDK_VERSION };
|
|
449
|
+
this.referrer = null;
|
|
450
|
+
this.started = false;
|
|
451
|
+
this.flushing = false;
|
|
452
|
+
this.flushTimer = null;
|
|
453
|
+
this.retryMs = BASE_RETRY_MS;
|
|
454
|
+
this.skan = new skan_1.Skan();
|
|
455
|
+
this.erased = false;
|
|
456
|
+
this.deepLinkListeners = /* @__PURE__ */ new Set();
|
|
457
|
+
this.undelivered = [];
|
|
458
|
+
this.deferred = null;
|
|
459
|
+
this.consent = null;
|
|
460
|
+
}
|
|
461
|
+
async init(opts) {
|
|
462
|
+
var _a;
|
|
463
|
+
if (this.started)
|
|
464
|
+
return;
|
|
465
|
+
this.started = true;
|
|
466
|
+
this.opts = { collectContext: true, ...opts, storage: (_a = opts.storage) != null ? _a : defaultStorage() };
|
|
467
|
+
if (!this.opts.storage) {
|
|
468
|
+
console.warn("[traqio] no storage available \u2014 pass `storage` to init() or install @react-native-async-storage/async-storage, otherwise the install is re-sent at every launch.");
|
|
469
|
+
}
|
|
470
|
+
await this.restoreConsent(opts.consent);
|
|
471
|
+
await this.restoreQueue();
|
|
472
|
+
await this.restoreAdQueue();
|
|
473
|
+
await this.buildContext();
|
|
474
|
+
if (await this.restoreErased())
|
|
475
|
+
return;
|
|
476
|
+
if (!this.isWeb) {
|
|
477
|
+
const freshInstall = Boolean(this.opts.storage) && !await this.opts.storage.getItem(INSTALL_SENT_KEY).catch(() => "1");
|
|
478
|
+
await this.sendInstallOnce();
|
|
479
|
+
if (this.opts.deepLinking !== false) {
|
|
480
|
+
this.deferred = this.resolveDeferredOnce(freshInstall);
|
|
481
|
+
this.wireDeepLinks();
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
await this.maybeStartSession(!this.isWeb);
|
|
485
|
+
await this.initSkan();
|
|
486
|
+
await this.initAppleAds();
|
|
487
|
+
this.wireLifecycle();
|
|
488
|
+
if (this.queue.length || this.adQueue.length)
|
|
489
|
+
this.scheduleFlush(0);
|
|
490
|
+
}
|
|
491
|
+
track(name, props) {
|
|
492
|
+
var _a, _b;
|
|
493
|
+
if (!this.started || this.erased)
|
|
494
|
+
return;
|
|
495
|
+
const transactionId = ((_a = props == null ? void 0 : props.transactionId) == null ? void 0 : _a.trim()) || void 0;
|
|
496
|
+
this.enqueue({
|
|
497
|
+
name,
|
|
498
|
+
eventId: uuid(),
|
|
499
|
+
value: props == null ? void 0 : props.value,
|
|
500
|
+
currency: props == null ? void 0 : props.currency,
|
|
501
|
+
...transactionId ? { transactionId, store: (_b = props == null ? void 0 : props.store) != null ? _b : this.defaultStore() } : {}
|
|
502
|
+
});
|
|
503
|
+
this.skan.markEvent(name);
|
|
504
|
+
if (props == null ? void 0 : props.value)
|
|
505
|
+
this.skan.addRevenue(props.value);
|
|
506
|
+
}
|
|
507
|
+
defaultStore() {
|
|
508
|
+
var _a;
|
|
509
|
+
const platform = (_a = this.opts.native) == null ? void 0 : _a.platform;
|
|
510
|
+
return platform === "ios" ? "app_store" : platform === "android" ? "play_store" : void 0;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* Report one AdMob impression's revenue. Call it from the paid-event callback:
|
|
514
|
+
*
|
|
515
|
+
* ad.setOnPaidEventListener(v => Traqio.trackAdRevenue({
|
|
516
|
+
* valueMicros: v.valueMicros, currency: v.currencyCode, precision: "estimated",
|
|
517
|
+
* adUnitId, adFormat: "rewarded", adSourceName,
|
|
518
|
+
* }));
|
|
519
|
+
*
|
|
520
|
+
* Impressions are batched and sent to /ingest/ad-revenue, where they are matched
|
|
521
|
+
* to this install and become the ad half of ROAS.
|
|
522
|
+
*/
|
|
523
|
+
trackAdRevenue(ad) {
|
|
524
|
+
this.queueAdRevenue(ad, "admob");
|
|
525
|
+
}
|
|
526
|
+
/**
|
|
527
|
+
* Report one AppLovin MAX impression's revenue. Call it from MAX's callback:
|
|
528
|
+
*
|
|
529
|
+
* onAdRevenuePaid(ad) { Traqio.trackMaxAdRevenue({
|
|
530
|
+
* revenue: ad.getRevenue(), revenuePrecision: ad.getRevenuePrecision(),
|
|
531
|
+
* adUnitId: ad.getAdUnitId(), format: ad.getFormat().getLabel(),
|
|
532
|
+
* networkName: ad.getNetworkName(),
|
|
533
|
+
* }); }
|
|
534
|
+
*
|
|
535
|
+
* Same batching, same endpoint and same ROAS numerator as AdMob, filed under
|
|
536
|
+
* the `applovin_max` source.
|
|
537
|
+
*/
|
|
538
|
+
trackMaxAdRevenue(ad) {
|
|
539
|
+
const converted = fromMaxAd(ad);
|
|
540
|
+
if (converted)
|
|
541
|
+
this.queueAdRevenue(converted, "applovin_max");
|
|
542
|
+
}
|
|
543
|
+
queueAdRevenue(ad, source) {
|
|
544
|
+
var _a;
|
|
545
|
+
if (!this.started || this.erased)
|
|
546
|
+
return;
|
|
547
|
+
if (!(ad.valueMicros >= 0) || !ad.currency)
|
|
548
|
+
return;
|
|
549
|
+
this.adQueue.push({ ...ad, source, impressionId: uuid(), ts: (_a = ad.ts) != null ? _a : Math.floor(Date.now() / 1e3) });
|
|
550
|
+
this.skan.addRevenue(ad.valueMicros / 1e6);
|
|
551
|
+
if (this.adQueue.length > MAX_AD_QUEUE)
|
|
552
|
+
this.adQueue.splice(0, this.adQueue.length - MAX_AD_QUEUE);
|
|
553
|
+
void this.persistAdQueue();
|
|
554
|
+
this.scheduleFlush();
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* The Play Install Referrer for this install — the raw string your tracking link
|
|
558
|
+
* put there, so a host app can use it for deferred deep linking on top of the
|
|
559
|
+
* attribution we already do server-side. Resolves from cache after the first read
|
|
560
|
+
* (Play only serves it reliably once). On iOS it reports
|
|
561
|
+
* `not_supported_platform`; attribution there is SKAN.
|
|
562
|
+
*/
|
|
563
|
+
getInstallReferrer() {
|
|
564
|
+
if (!this.started)
|
|
565
|
+
return Promise.resolve({ status: "unavailable", retryable: false });
|
|
566
|
+
return this.readReferrer();
|
|
567
|
+
}
|
|
568
|
+
/**
|
|
569
|
+
* Subscribe to deep links — direct opens AND the one deferred link of a fresh
|
|
570
|
+
* install. Links resolved before the first subscriber are delivered to it on
|
|
571
|
+
* subscription, so a cold start does not lose the link that opened the app.
|
|
572
|
+
*
|
|
573
|
+
* Traqio.onDeepLink(({ deepLink }) => { if (deepLink) router.push(deepLink); });
|
|
574
|
+
*
|
|
575
|
+
* Returns the unsubscribe function.
|
|
576
|
+
*/
|
|
577
|
+
onDeepLink(listener) {
|
|
578
|
+
this.deepLinkListeners.add(listener);
|
|
579
|
+
const pending = this.undelivered.splice(0);
|
|
580
|
+
for (const link of pending)
|
|
581
|
+
listener(link);
|
|
582
|
+
return () => {
|
|
583
|
+
this.deepLinkListeners.delete(listener);
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
/**
|
|
587
|
+
* A URL opened the app. React Native is wired automatically (`Linking`); every
|
|
588
|
+
* other host (Capacitor's `appUrlOpen`, a native shell) calls this.
|
|
589
|
+
*
|
|
590
|
+
* Only our tracking URLs (`https://<host>/c/<code>`) leave the device; the
|
|
591
|
+
* app's own URLs resolve to null without a request. Resolving also records
|
|
592
|
+
* the click, which the OS skipped by opening the app directly.
|
|
593
|
+
*/
|
|
594
|
+
async handleUrl(url) {
|
|
595
|
+
if (!this.started || this.erased || this.opts.deepLinking === false || !(0, deeplink_1.isTrackingUrl)(url))
|
|
596
|
+
return null;
|
|
597
|
+
const answer = await this.postJson({ url }, "/deeplink/open");
|
|
598
|
+
const link = (0, deeplink_1.toDeepLink)(answer, false, url);
|
|
599
|
+
if (link)
|
|
600
|
+
this.emitDeepLink(link);
|
|
601
|
+
return link;
|
|
602
|
+
}
|
|
603
|
+
/**
|
|
604
|
+
* The deferred deep link of this install, if it came from one — resolved once,
|
|
605
|
+
* on the first launch, and remembered. Null on every install that did not
|
|
606
|
+
* come from a link (and on iOS unless the IP match is on for this app).
|
|
607
|
+
*/
|
|
608
|
+
getDeferredDeepLink() {
|
|
609
|
+
var _a;
|
|
610
|
+
return (_a = this.deferred) != null ? _a : Promise.resolve(null);
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* GDPR Art. 17, from inside the app: delete everything the server holds about this
|
|
614
|
+
* device and this user, and stop sending.
|
|
615
|
+
*
|
|
616
|
+
* ⚠️ IRREVERSIBLE, on both sides. The server deletes the installs, events, clicks
|
|
617
|
+
* and delivery payloads that name this subject and tombstones their identifiers,
|
|
618
|
+
* so nothing this device sends afterwards is accepted. Locally the queue is
|
|
619
|
+
* dropped and the SDK goes quiet for good — persisted, so the next launch does not
|
|
620
|
+
* re-report the install. There is no way back on: an app that needs measurement
|
|
621
|
+
* again has to be reinstalled.
|
|
622
|
+
*
|
|
623
|
+
* Wire it to your own "delete my data" control. Returns false when the call did
|
|
624
|
+
* not reach the server, and in that case NOTHING has changed on either side — show
|
|
625
|
+
* the user an error and let them try again, rather than a confirmation of a
|
|
626
|
+
* deletion that did not happen.
|
|
627
|
+
*/
|
|
628
|
+
async forgetMe() {
|
|
629
|
+
if (!this.started)
|
|
630
|
+
return false;
|
|
631
|
+
if (this.erased)
|
|
632
|
+
return true;
|
|
633
|
+
const ok = await this.post({ deviceId: this.context.deviceId, appUserId: this.opts.userId }, "/privacy/forget");
|
|
634
|
+
if (!ok)
|
|
635
|
+
return false;
|
|
636
|
+
await this.markErased();
|
|
637
|
+
return true;
|
|
638
|
+
}
|
|
639
|
+
/**
|
|
640
|
+
* The user's consent to SHARING their data with ad networks, as collected by the
|
|
641
|
+
* app's own prompt — Traqio is not a CMP. Persisted, and sent with every install,
|
|
642
|
+
* event batch and session from now on, events already queued included.
|
|
643
|
+
*
|
|
644
|
+
* `false` keeps first-party measurement (installs, events, retention and ROAS in
|
|
645
|
+
* your dashboard), but the server forwards nothing about this device to Meta,
|
|
646
|
+
* TikTok or any outbound postback. Never calling it = not collected: the app's
|
|
647
|
+
* policy in the console decides (docs/PRIVACY.md §Consent).
|
|
648
|
+
*
|
|
649
|
+
* Traqio.setConsent(userAgreed);
|
|
650
|
+
*/
|
|
651
|
+
async setConsent(granted) {
|
|
652
|
+
var _a, _b;
|
|
653
|
+
this.consent = granted ? "granted" : "denied";
|
|
654
|
+
await ((_b = (_a = this.opts) == null ? void 0 : _a.storage) == null ? void 0 : _b.setItem(CONSENT_KEY, this.consent).catch(() => void 0));
|
|
655
|
+
}
|
|
656
|
+
/** True once `forgetMe()` has been honoured — this install sends nothing any more. */
|
|
657
|
+
get forgotten() {
|
|
658
|
+
return this.erased;
|
|
659
|
+
}
|
|
660
|
+
/** Set/override the user id (== RevenueCat app_user_id). Call after login. */
|
|
661
|
+
setUserId(id) {
|
|
662
|
+
if (this.opts)
|
|
663
|
+
this.opts.userId = id;
|
|
664
|
+
}
|
|
665
|
+
/** Force a flush now (e.g. on app background). RN wires this automatically. */
|
|
666
|
+
flush() {
|
|
667
|
+
if (this.erased)
|
|
668
|
+
return;
|
|
669
|
+
if (this.flushTimer) {
|
|
670
|
+
clearTimeout(this.flushTimer);
|
|
671
|
+
this.flushTimer = null;
|
|
672
|
+
}
|
|
673
|
+
void this.drain();
|
|
674
|
+
}
|
|
675
|
+
/**
|
|
676
|
+
* Tell the SDK the app came back to the foreground. React Native is wired
|
|
677
|
+
* automatically; every other host (a web view, a game loop, a custom shell) has
|
|
678
|
+
* to call this or its users look like they never came back.
|
|
679
|
+
*
|
|
680
|
+
* Safe to call on every resume: it is debounced by the session timeout.
|
|
681
|
+
*/
|
|
682
|
+
appOpened() {
|
|
683
|
+
if (!this.started || this.erased)
|
|
684
|
+
return;
|
|
685
|
+
void this.maybeStartSession();
|
|
686
|
+
}
|
|
687
|
+
/** The conversion-value mapping in force on this device, once fetched. */
|
|
688
|
+
get skanMapping() {
|
|
689
|
+
return this.skan.activeMapping;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Apple Ads self-attribution. Awaited rather than fired off, so a host that awaits
|
|
693
|
+
* `init()` can be sure the token left the device before the app does anything
|
|
694
|
+
* else — the window is 24 hours, but a user who installs from a Search Ads tap and
|
|
695
|
+
* never reopens the app still has to be attributed.
|
|
696
|
+
*/
|
|
697
|
+
async initAppleAds() {
|
|
698
|
+
if (this.opts.appleAds === false)
|
|
699
|
+
return;
|
|
700
|
+
const native = this.opts.native;
|
|
701
|
+
if ((native == null ? void 0 : native.platform) !== "ios" || !native.getAttributionToken)
|
|
702
|
+
return;
|
|
703
|
+
await (0, adservices_1.reportAdServicesToken)({
|
|
704
|
+
endpoint: this.opts.endpoint,
|
|
705
|
+
sdkKey: this.opts.sdkKey,
|
|
706
|
+
deviceId: this.context.deviceId,
|
|
707
|
+
userId: this.opts.userId,
|
|
708
|
+
storage: this.opts.storage,
|
|
709
|
+
native: { getAttributionToken: () => native.getAttributionToken() }
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
async initSkan() {
|
|
713
|
+
if (this.opts.skan === false)
|
|
714
|
+
return;
|
|
715
|
+
const native = this.opts.native;
|
|
716
|
+
if ((native == null ? void 0 : native.platform) !== "ios" || !native.updateConversionValue)
|
|
717
|
+
return;
|
|
718
|
+
await this.skan.init({
|
|
719
|
+
endpoint: this.opts.endpoint,
|
|
720
|
+
sdkKey: this.opts.sdkKey,
|
|
721
|
+
storage: this.opts.storage,
|
|
722
|
+
native: {
|
|
723
|
+
updateConversionValue: (fine, coarse, lockWindow) => {
|
|
724
|
+
var _a;
|
|
725
|
+
return (_a = native.updateConversionValue) == null ? void 0 : _a.call(native, fine, coarse, lockWindow);
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Asks `/deeplink/deferred` once per install. A settled answer — link or no
|
|
732
|
+
* link — is persisted; a failed request is not, so the next launch retries
|
|
733
|
+
* (still counted as fresh, since the flag is only written on an answer).
|
|
734
|
+
*/
|
|
735
|
+
async resolveDeferredOnce(freshInstall) {
|
|
736
|
+
var _a, _b;
|
|
737
|
+
const store = this.opts.storage;
|
|
738
|
+
try {
|
|
739
|
+
const cached = await (store == null ? void 0 : store.getItem(DEFERRED_KEY));
|
|
740
|
+
if (cached)
|
|
741
|
+
return JSON.parse(cached);
|
|
742
|
+
} catch {
|
|
743
|
+
}
|
|
744
|
+
if (!freshInstall && !await (store == null ? void 0 : store.getItem(`${DEFERRED_KEY}_pending`).catch(() => null)))
|
|
745
|
+
return null;
|
|
746
|
+
const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
|
|
747
|
+
const referrer = platform === "android" ? await this.readReferrer() : null;
|
|
748
|
+
await (store == null ? void 0 : store.setItem(`${DEFERRED_KEY}_pending`, "1").catch(() => void 0));
|
|
749
|
+
const answer = await this.postJson({ platform, installReferrer: referrer == null ? void 0 : referrer.referrer }, "/deeplink/deferred");
|
|
750
|
+
if (!answer)
|
|
751
|
+
return null;
|
|
752
|
+
const link = (0, deeplink_1.toDeepLink)(answer, true);
|
|
753
|
+
try {
|
|
754
|
+
await (store == null ? void 0 : store.setItem(DEFERRED_KEY, JSON.stringify(link)));
|
|
755
|
+
} catch {
|
|
756
|
+
}
|
|
757
|
+
if (link)
|
|
758
|
+
this.emitDeepLink(link);
|
|
759
|
+
return link;
|
|
760
|
+
}
|
|
761
|
+
emitDeepLink(link) {
|
|
762
|
+
if (!this.deepLinkListeners.size) {
|
|
763
|
+
this.undelivered.push(link);
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
for (const listener of this.deepLinkListeners) {
|
|
767
|
+
try {
|
|
768
|
+
listener(link);
|
|
769
|
+
} catch {
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
wireDeepLinks() {
|
|
774
|
+
try {
|
|
775
|
+
const { Linking } = (init_empty(), __toCommonJS(empty_exports));
|
|
776
|
+
if (!Linking)
|
|
777
|
+
return;
|
|
778
|
+
void Linking.getInitialURL().then((url) => url && this.handleUrl(url)).catch(() => void 0);
|
|
779
|
+
Linking.addEventListener("url", ({ url }) => void this.handleUrl(url));
|
|
780
|
+
} catch {
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
get isWeb() {
|
|
784
|
+
var _a;
|
|
785
|
+
return ((_a = this.opts) == null ? void 0 : _a.platform) === "web";
|
|
786
|
+
}
|
|
787
|
+
wireLifecycle() {
|
|
788
|
+
const events = {
|
|
789
|
+
background: () => this.flush(),
|
|
790
|
+
// Debounced by SESSION_TIMEOUT_MS inside, so a flick to another app/tab and
|
|
791
|
+
// straight back posts nothing.
|
|
792
|
+
foreground: () => this.appOpened()
|
|
793
|
+
};
|
|
794
|
+
if (this.opts.lifecycle) {
|
|
795
|
+
this.opts.lifecycle(events);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
try {
|
|
799
|
+
const { AppState } = (init_empty(), __toCommonJS(empty_exports));
|
|
800
|
+
AppState.addEventListener("change", (state) => {
|
|
801
|
+
if (state !== "active") {
|
|
802
|
+
this.scheduleFlush(0);
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
void this.maybeStartSession();
|
|
806
|
+
});
|
|
807
|
+
} catch {
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
// ── internals ──────────────────────────────────────────
|
|
811
|
+
/** Reads the persisted erasure flag. True ⇒ this install must stay silent. */
|
|
812
|
+
async restoreErased() {
|
|
813
|
+
var _a;
|
|
814
|
+
try {
|
|
815
|
+
this.erased = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(ERASED_KEY)) === "1";
|
|
816
|
+
} catch {
|
|
817
|
+
this.erased = false;
|
|
818
|
+
}
|
|
819
|
+
return this.erased;
|
|
820
|
+
}
|
|
821
|
+
/** Local half of forgetMe(): drop what is queued and never send again. */
|
|
822
|
+
async markErased() {
|
|
823
|
+
var _a;
|
|
824
|
+
this.erased = true;
|
|
825
|
+
if (this.flushTimer) {
|
|
826
|
+
clearTimeout(this.flushTimer);
|
|
827
|
+
this.flushTimer = null;
|
|
828
|
+
}
|
|
829
|
+
this.queue = [];
|
|
830
|
+
this.adQueue = [];
|
|
831
|
+
this.adBatchId = null;
|
|
832
|
+
await this.persistQueue();
|
|
833
|
+
await this.persistAdQueue();
|
|
834
|
+
try {
|
|
835
|
+
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(ERASED_KEY, "1"));
|
|
836
|
+
} catch {
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
enqueue(e) {
|
|
840
|
+
this.queue.push(e);
|
|
841
|
+
if (this.queue.length > MAX_QUEUE)
|
|
842
|
+
this.queue.splice(0, this.queue.length - MAX_QUEUE);
|
|
843
|
+
void this.persistQueue();
|
|
844
|
+
this.scheduleFlush();
|
|
845
|
+
}
|
|
846
|
+
async restoreQueue() {
|
|
847
|
+
var _a;
|
|
848
|
+
try {
|
|
849
|
+
const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(QUEUE_KEY));
|
|
850
|
+
if (raw)
|
|
851
|
+
this.queue = JSON.parse(raw);
|
|
852
|
+
} catch {
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
async persistQueue() {
|
|
856
|
+
var _a;
|
|
857
|
+
try {
|
|
858
|
+
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(QUEUE_KEY, JSON.stringify(this.queue)));
|
|
859
|
+
} catch {
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
async restoreAdQueue() {
|
|
863
|
+
var _a, _b, _c;
|
|
864
|
+
try {
|
|
865
|
+
const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(AD_QUEUE_KEY));
|
|
866
|
+
if (!raw)
|
|
867
|
+
return;
|
|
868
|
+
const parsed = JSON.parse(raw);
|
|
869
|
+
this.adQueue = (_b = parsed.items) != null ? _b : [];
|
|
870
|
+
this.adBatchId = (_c = parsed.batchId) != null ? _c : null;
|
|
871
|
+
} catch {
|
|
872
|
+
}
|
|
873
|
+
}
|
|
874
|
+
async persistAdQueue() {
|
|
875
|
+
var _a;
|
|
876
|
+
try {
|
|
877
|
+
const state = { batchId: this.adBatchId, items: this.adQueue };
|
|
878
|
+
await ((_a = this.opts.storage) == null ? void 0 : _a.setItem(AD_QUEUE_KEY, JSON.stringify(state)));
|
|
879
|
+
} catch {
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
/**
|
|
883
|
+
* Report one app open — the signal that makes "did the user come back on day n"
|
|
884
|
+
* answerable at all (docs/SESSIONS.md).
|
|
885
|
+
*
|
|
886
|
+
* Called on `init()` (the app was opened) and on returning to the foreground
|
|
887
|
+
* after `SESSION_TIMEOUT_MS`.
|
|
888
|
+
*
|
|
889
|
+
* NO QUEUE, deliberately. A failed post does NOT persist the marker, so the next
|
|
890
|
+
* foreground retries it. The signal is only ever read at DAY granularity, so a
|
|
891
|
+
* post lost at 09:00 is recovered by any open before midnight — a far smaller
|
|
892
|
+
* failure than a persisted queue that can replay yesterday's sessions into today,
|
|
893
|
+
* which would be a retention chart that invents its own history.
|
|
894
|
+
*/
|
|
895
|
+
async maybeStartSession(force = false) {
|
|
896
|
+
var _a, _b, _c;
|
|
897
|
+
if (this.erased)
|
|
898
|
+
return;
|
|
899
|
+
const now = Date.now();
|
|
900
|
+
if (!force) {
|
|
901
|
+
const last = Number(await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(LAST_SESSION_KEY).catch(() => null))) || 0;
|
|
902
|
+
if (last && now - last < SESSION_TIMEOUT_MS)
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
const deviceId = (_b = this.context.deviceId) != null ? _b : await this.getOrCreateDeviceId();
|
|
906
|
+
const ok = await this.post({
|
|
907
|
+
deviceId,
|
|
908
|
+
appUserId: this.opts.userId,
|
|
909
|
+
sessionId: uuid(),
|
|
910
|
+
ts: Math.floor(now / 1e3),
|
|
911
|
+
context: this.context
|
|
912
|
+
}, "/ingest/session");
|
|
913
|
+
if (ok) {
|
|
914
|
+
try {
|
|
915
|
+
await ((_c = this.opts.storage) == null ? void 0 : _c.setItem(LAST_SESSION_KEY, String(now)));
|
|
916
|
+
} catch {
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
async buildContext() {
|
|
921
|
+
var _a, _b, _c;
|
|
922
|
+
if (!this.opts.collectContext) {
|
|
923
|
+
this.context = { sdkVersion: exports.SDK_VERSION };
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
let native = {};
|
|
927
|
+
try {
|
|
928
|
+
native = (_c = await ((_b = (_a = this.opts.native) == null ? void 0 : _a.getContext) == null ? void 0 : _b.call(_a))) != null ? _c : {};
|
|
929
|
+
} catch {
|
|
930
|
+
}
|
|
931
|
+
this.context = {
|
|
932
|
+
deviceId: await this.getOrCreateDeviceId(),
|
|
933
|
+
deviceModel: native.deviceModel,
|
|
934
|
+
osVersion: native.osVersion,
|
|
935
|
+
appVersion: this.opts.appVersion,
|
|
936
|
+
locale: safeLocale(),
|
|
937
|
+
sdkVersion: exports.SDK_VERSION
|
|
938
|
+
};
|
|
939
|
+
}
|
|
940
|
+
async getOrCreateDeviceId() {
|
|
941
|
+
var _a, _b;
|
|
942
|
+
try {
|
|
943
|
+
const existing = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(DEVICE_ID_KEY2));
|
|
944
|
+
if (existing)
|
|
945
|
+
return existing;
|
|
946
|
+
} catch {
|
|
947
|
+
}
|
|
948
|
+
const id = uuid();
|
|
949
|
+
try {
|
|
950
|
+
await ((_b = this.opts.storage) == null ? void 0 : _b.setItem(DEVICE_ID_KEY2, id));
|
|
951
|
+
} catch {
|
|
952
|
+
}
|
|
953
|
+
return id;
|
|
954
|
+
}
|
|
955
|
+
/**
|
|
956
|
+
* Reads the Play Install Referrer, once per install, and caches a settled answer.
|
|
957
|
+
* A retryable failure is deliberately NOT cached — freezing it would make the
|
|
958
|
+
* install look organic for good.
|
|
959
|
+
*/
|
|
960
|
+
async readReferrer() {
|
|
961
|
+
var _a, _b;
|
|
962
|
+
if (this.referrer)
|
|
963
|
+
return this.referrer;
|
|
964
|
+
try {
|
|
965
|
+
const raw = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(REFERRER_KEY));
|
|
966
|
+
if (raw)
|
|
967
|
+
return this.referrer = JSON.parse(raw);
|
|
968
|
+
} catch {
|
|
969
|
+
}
|
|
970
|
+
const native = this.opts.native;
|
|
971
|
+
if ((native == null ? void 0 : native.platform) !== "android") {
|
|
972
|
+
return { status: native ? "not_supported_platform" : "unavailable", retryable: false };
|
|
973
|
+
}
|
|
974
|
+
const result = await native.getInstallReferrer().catch(() => ({ status: "error", retryable: true }));
|
|
975
|
+
if (!result.retryable) {
|
|
976
|
+
this.referrer = result;
|
|
977
|
+
try {
|
|
978
|
+
await ((_b = this.opts.storage) == null ? void 0 : _b.setItem(REFERRER_KEY, JSON.stringify(result)));
|
|
979
|
+
} catch {
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
return result;
|
|
983
|
+
}
|
|
984
|
+
/** Only with the host's opt-in; a zeroed or malformed id is never sent. */
|
|
985
|
+
async readAdvertisingId() {
|
|
986
|
+
var _a;
|
|
987
|
+
if (!this.opts.collectAdvertisingId || !((_a = this.opts.native) == null ? void 0 : _a.getAdvertisingId))
|
|
988
|
+
return void 0;
|
|
989
|
+
try {
|
|
990
|
+
return normalizeAdvertisingId(await this.opts.native.getAdvertisingId());
|
|
991
|
+
} catch {
|
|
992
|
+
return void 0;
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
async sendInstallOnce() {
|
|
996
|
+
var _a, _b;
|
|
997
|
+
const store = this.opts.storage;
|
|
998
|
+
if (store && await store.getItem(INSTALL_SENT_KEY))
|
|
999
|
+
return;
|
|
1000
|
+
const platform = (_b = (_a = this.opts.native) == null ? void 0 : _a.platform) != null ? _b : "android";
|
|
1001
|
+
const referrer = await this.readReferrer();
|
|
1002
|
+
if (referrer.retryable && store) {
|
|
1003
|
+
const attempts = Number(await store.getItem(INSTALL_ATTEMPTS_KEY)) || 0;
|
|
1004
|
+
if (attempts + 1 < MAX_INSTALL_ATTEMPTS) {
|
|
1005
|
+
await store.setItem(INSTALL_ATTEMPTS_KEY, String(attempts + 1));
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
}
|
|
1009
|
+
const ok = await this.post({
|
|
1010
|
+
install: {
|
|
1011
|
+
platform,
|
|
1012
|
+
installReferrer: referrer.referrer,
|
|
1013
|
+
appUserId: this.opts.userId,
|
|
1014
|
+
advertisingId: await this.readAdvertisingId(),
|
|
1015
|
+
context: this.context
|
|
1016
|
+
}
|
|
1017
|
+
});
|
|
1018
|
+
if (ok)
|
|
1019
|
+
await (store == null ? void 0 : store.setItem(INSTALL_SENT_KEY, "1"));
|
|
1020
|
+
}
|
|
1021
|
+
scheduleFlush(delay = FLUSH_DELAY_MS) {
|
|
1022
|
+
if (this.flushTimer)
|
|
1023
|
+
return;
|
|
1024
|
+
this.flushTimer = setTimeout(() => {
|
|
1025
|
+
this.flushTimer = null;
|
|
1026
|
+
void this.drain();
|
|
1027
|
+
}, delay);
|
|
1028
|
+
}
|
|
1029
|
+
async drain() {
|
|
1030
|
+
var _a;
|
|
1031
|
+
if (this.erased)
|
|
1032
|
+
return;
|
|
1033
|
+
if (this.flushing || !this.queue.length && !this.adQueue.length)
|
|
1034
|
+
return;
|
|
1035
|
+
this.flushing = true;
|
|
1036
|
+
try {
|
|
1037
|
+
while (this.queue.length) {
|
|
1038
|
+
const batch = this.queue.slice(0, MAX_BATCH);
|
|
1039
|
+
const ok = await this.post({
|
|
1040
|
+
events: batch,
|
|
1041
|
+
appUserId: this.opts.userId,
|
|
1042
|
+
deviceId: this.context.deviceId
|
|
1043
|
+
});
|
|
1044
|
+
if (!ok)
|
|
1045
|
+
return this.backOff();
|
|
1046
|
+
this.queue.splice(0, batch.length);
|
|
1047
|
+
await this.persistQueue();
|
|
1048
|
+
this.retryMs = BASE_RETRY_MS;
|
|
1049
|
+
}
|
|
1050
|
+
while (this.adQueue.length) {
|
|
1051
|
+
const source = (_a = this.adQueue[0].source) != null ? _a : "admob";
|
|
1052
|
+
const run = this.adQueue.findIndex((i) => {
|
|
1053
|
+
var _a2;
|
|
1054
|
+
return ((_a2 = i.source) != null ? _a2 : "admob") !== source;
|
|
1055
|
+
});
|
|
1056
|
+
const batch = this.adQueue.slice(0, Math.min(MAX_AD_BATCH, run === -1 ? this.adQueue.length : run));
|
|
1057
|
+
if (!this.adBatchId) {
|
|
1058
|
+
this.adBatchId = uuid();
|
|
1059
|
+
await this.persistAdQueue();
|
|
1060
|
+
}
|
|
1061
|
+
const ok = await this.post({
|
|
1062
|
+
batchId: this.adBatchId,
|
|
1063
|
+
source,
|
|
1064
|
+
environment: this.opts.testAds ? "TEST" : "PRODUCTION",
|
|
1065
|
+
deviceId: this.context.deviceId,
|
|
1066
|
+
appUserId: this.opts.userId,
|
|
1067
|
+
impressions: batch.map(({ source: _source, ...impression }) => impression)
|
|
1068
|
+
}, "/ingest/ad-revenue");
|
|
1069
|
+
if (!ok)
|
|
1070
|
+
return this.backOff();
|
|
1071
|
+
this.adQueue.splice(0, batch.length);
|
|
1072
|
+
this.adBatchId = null;
|
|
1073
|
+
await this.persistAdQueue();
|
|
1074
|
+
this.retryMs = BASE_RETRY_MS;
|
|
1075
|
+
}
|
|
1076
|
+
} finally {
|
|
1077
|
+
this.flushing = false;
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
// network/server failure → keep the queue, back off, retry later.
|
|
1081
|
+
backOff() {
|
|
1082
|
+
this.retryMs = Math.min(this.retryMs * 2, MAX_RETRY_MS);
|
|
1083
|
+
this.scheduleFlush(this.retryMs);
|
|
1084
|
+
}
|
|
1085
|
+
/** Like `post`, for the two calls whose ANSWER matters. Null on any failure. */
|
|
1086
|
+
async postJson(body, path) {
|
|
1087
|
+
try {
|
|
1088
|
+
const res = await fetch(`${this.opts.endpoint}${path}`, {
|
|
1089
|
+
method: "POST",
|
|
1090
|
+
headers: { "Content-Type": "application/json" },
|
|
1091
|
+
body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body }),
|
|
1092
|
+
...this.keepalive()
|
|
1093
|
+
});
|
|
1094
|
+
return res.ok ? await res.json() : null;
|
|
1095
|
+
} catch {
|
|
1096
|
+
return null;
|
|
1097
|
+
}
|
|
1098
|
+
}
|
|
1099
|
+
/**
|
|
1100
|
+
* The init option wins over what is stored (it is the app's current answer); a
|
|
1101
|
+
* `setConsent()` made before `init()` survives too — it is only kept in memory
|
|
1102
|
+
* until there is a storage to write it to.
|
|
1103
|
+
*/
|
|
1104
|
+
async restoreConsent(fromInit) {
|
|
1105
|
+
var _a;
|
|
1106
|
+
if (fromInit !== void 0)
|
|
1107
|
+
return this.setConsent(fromInit);
|
|
1108
|
+
if (this.consent)
|
|
1109
|
+
return this.setConsent(this.consent === "granted");
|
|
1110
|
+
const stored = await ((_a = this.opts.storage) == null ? void 0 : _a.getItem(CONSENT_KEY).catch(() => null));
|
|
1111
|
+
if (stored === "granted" || stored === "denied")
|
|
1112
|
+
this.consent = stored;
|
|
1113
|
+
}
|
|
1114
|
+
/**
|
|
1115
|
+
* Web only: a request started on `pagehide` is otherwise cancelled with the page.
|
|
1116
|
+
* Not set for apps — their fetch is not torn down, and the request stays as it was.
|
|
1117
|
+
*/
|
|
1118
|
+
keepalive() {
|
|
1119
|
+
return this.isWeb ? { keepalive: true } : {};
|
|
1120
|
+
}
|
|
1121
|
+
async post(body, path = "/ingest") {
|
|
1122
|
+
const consent = this.consent && (path === "/ingest" || path === "/ingest/session") ? { consent: this.consent } : {};
|
|
1123
|
+
try {
|
|
1124
|
+
const res = await fetch(`${this.opts.endpoint}${path}`, {
|
|
1125
|
+
method: "POST",
|
|
1126
|
+
headers: { "Content-Type": "application/json" },
|
|
1127
|
+
body: JSON.stringify({ sdkKey: this.opts.sdkKey, ...body, ...consent }),
|
|
1128
|
+
...this.keepalive()
|
|
1129
|
+
});
|
|
1130
|
+
return res.ok;
|
|
1131
|
+
} catch {
|
|
1132
|
+
return false;
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
};
|
|
1136
|
+
exports.Client = Client2;
|
|
1137
|
+
exports.Traqio = new Client2();
|
|
1138
|
+
}
|
|
1139
|
+
});
|
|
1140
|
+
|
|
1141
|
+
// src/index.ts
|
|
1142
|
+
var index_exports = {};
|
|
1143
|
+
__export(index_exports, {
|
|
1144
|
+
DEFAULT_ENDPOINT: () => DEFAULT_ENDPOINT,
|
|
1145
|
+
Traqio: () => Traqio,
|
|
1146
|
+
TraqioWeb: () => TraqioWeb
|
|
1147
|
+
});
|
|
1148
|
+
module.exports = __toCommonJS(index_exports);
|
|
1149
|
+
var import_core = __toESM(require_build(), 1);
|
|
1150
|
+
|
|
1151
|
+
// src/cookies.ts
|
|
1152
|
+
var COOKIE_PREFIX = "traq_";
|
|
1153
|
+
function doc() {
|
|
1154
|
+
return typeof document === "undefined" ? void 0 : document;
|
|
1155
|
+
}
|
|
1156
|
+
function readCookie(name) {
|
|
1157
|
+
const d = doc();
|
|
1158
|
+
if (!d) return null;
|
|
1159
|
+
for (const part of d.cookie ? d.cookie.split(";") : []) {
|
|
1160
|
+
const eq = part.indexOf("=");
|
|
1161
|
+
if (eq < 0) continue;
|
|
1162
|
+
if (part.slice(0, eq).trim() === name) {
|
|
1163
|
+
try {
|
|
1164
|
+
return decodeURIComponent(part.slice(eq + 1).trim());
|
|
1165
|
+
} catch {
|
|
1166
|
+
return null;
|
|
1167
|
+
}
|
|
1168
|
+
}
|
|
1169
|
+
}
|
|
1170
|
+
return null;
|
|
1171
|
+
}
|
|
1172
|
+
function serialize(name, value, maxAgeSeconds, domain) {
|
|
1173
|
+
const secure = typeof location !== "undefined" && location.protocol === "https:" ? "; Secure" : "";
|
|
1174
|
+
const scope = domain ? `; Domain=${domain}` : "";
|
|
1175
|
+
return `${name}=${encodeURIComponent(value)}; Max-Age=${Math.floor(maxAgeSeconds)}; Path=/${scope}; SameSite=Lax${secure}`;
|
|
1176
|
+
}
|
|
1177
|
+
function registrableDomain(hostname) {
|
|
1178
|
+
const d = doc();
|
|
1179
|
+
if (!d || !hostname.includes(".") || /^[\d.]+$/.test(hostname) || hostname.includes(":")) return null;
|
|
1180
|
+
const labels = hostname.split(".");
|
|
1181
|
+
const probe = `${COOKIE_PREFIX}probe`;
|
|
1182
|
+
for (let i = labels.length - 2; i >= 0; i--) {
|
|
1183
|
+
const candidate = labels.slice(i).join(".");
|
|
1184
|
+
d.cookie = serialize(probe, "1", 10, candidate);
|
|
1185
|
+
if (readCookie(probe) === "1") {
|
|
1186
|
+
d.cookie = serialize(probe, "", 0, candidate);
|
|
1187
|
+
return candidate;
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
return null;
|
|
1191
|
+
}
|
|
1192
|
+
function writeCookie(name, value, maxAgeSeconds, domain) {
|
|
1193
|
+
const d = doc();
|
|
1194
|
+
if (!d) return;
|
|
1195
|
+
try {
|
|
1196
|
+
d.cookie = serialize(name, value, maxAgeSeconds, domain);
|
|
1197
|
+
} catch {
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
function deleteCookie(name, domain) {
|
|
1201
|
+
writeCookie(name, "", 0, domain);
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
// src/storage.ts
|
|
1205
|
+
var DEVICE_ID_KEY = "traq_device_id";
|
|
1206
|
+
var MIRRORED = /* @__PURE__ */ new Set([DEVICE_ID_KEY]);
|
|
1207
|
+
var MIRROR_MAX_AGE_SECONDS = 395 * 24 * 60 * 60;
|
|
1208
|
+
function local() {
|
|
1209
|
+
try {
|
|
1210
|
+
return typeof localStorage === "undefined" ? void 0 : localStorage;
|
|
1211
|
+
} catch {
|
|
1212
|
+
return void 0;
|
|
1213
|
+
}
|
|
1214
|
+
}
|
|
1215
|
+
var BrowserStore = class {
|
|
1216
|
+
constructor(persistent, cookieDomain, cookies) {
|
|
1217
|
+
this.persistent = persistent;
|
|
1218
|
+
this.cookieDomain = cookieDomain;
|
|
1219
|
+
this.cookies = cookies;
|
|
1220
|
+
this.memory = /* @__PURE__ */ new Map();
|
|
1221
|
+
}
|
|
1222
|
+
get isPersistent() {
|
|
1223
|
+
return this.persistent;
|
|
1224
|
+
}
|
|
1225
|
+
async getItem(key) {
|
|
1226
|
+
return this.getSync(key);
|
|
1227
|
+
}
|
|
1228
|
+
async setItem(key, value) {
|
|
1229
|
+
this.setSync(key, value);
|
|
1230
|
+
}
|
|
1231
|
+
getSync(key) {
|
|
1232
|
+
var _a, _b, _c;
|
|
1233
|
+
if (this.memory.has(key)) return (_a = this.memory.get(key)) != null ? _a : null;
|
|
1234
|
+
if (!this.persistent) return null;
|
|
1235
|
+
let value = null;
|
|
1236
|
+
try {
|
|
1237
|
+
value = (_c = (_b = local()) == null ? void 0 : _b.getItem(key)) != null ? _c : null;
|
|
1238
|
+
} catch {
|
|
1239
|
+
}
|
|
1240
|
+
if (value === null && this.cookies && MIRRORED.has(key)) value = readCookie(key);
|
|
1241
|
+
return value;
|
|
1242
|
+
}
|
|
1243
|
+
setSync(key, value) {
|
|
1244
|
+
if (!this.persistent) {
|
|
1245
|
+
this.memory.set(key, value);
|
|
1246
|
+
return;
|
|
1247
|
+
}
|
|
1248
|
+
let stored = false;
|
|
1249
|
+
try {
|
|
1250
|
+
const ls = local();
|
|
1251
|
+
if (ls) {
|
|
1252
|
+
ls.setItem(key, value);
|
|
1253
|
+
stored = true;
|
|
1254
|
+
}
|
|
1255
|
+
} catch {
|
|
1256
|
+
}
|
|
1257
|
+
if (!stored) this.memory.set(key, value);
|
|
1258
|
+
if (this.cookies && MIRRORED.has(key)) writeCookie(key, value, MIRROR_MAX_AGE_SECONDS, this.cookieDomain());
|
|
1259
|
+
}
|
|
1260
|
+
removeSync(key) {
|
|
1261
|
+
var _a;
|
|
1262
|
+
this.memory.delete(key);
|
|
1263
|
+
try {
|
|
1264
|
+
(_a = local()) == null ? void 0 : _a.removeItem(key);
|
|
1265
|
+
} catch {
|
|
1266
|
+
}
|
|
1267
|
+
if (this.cookies) deleteCookie(key, this.cookieDomain());
|
|
1268
|
+
}
|
|
1269
|
+
/** Consent given: what this page kept in memory goes to the device. */
|
|
1270
|
+
enable() {
|
|
1271
|
+
if (this.persistent) return;
|
|
1272
|
+
this.persistent = true;
|
|
1273
|
+
const pending = [...this.memory];
|
|
1274
|
+
this.memory.clear();
|
|
1275
|
+
for (const [key, value] of pending) this.setSync(key, value);
|
|
1276
|
+
}
|
|
1277
|
+
/**
|
|
1278
|
+
* Consent withdrawn: every `traq_*` value leaves the device (localStorage and
|
|
1279
|
+
* cookies) and stays in memory for the rest of this page, so nothing breaks
|
|
1280
|
+
* mid-visit and nothing survives it.
|
|
1281
|
+
*/
|
|
1282
|
+
disable() {
|
|
1283
|
+
if (!this.persistent) return;
|
|
1284
|
+
const ls = local();
|
|
1285
|
+
const keys = [];
|
|
1286
|
+
try {
|
|
1287
|
+
for (let i = 0; ls && i < ls.length; i++) {
|
|
1288
|
+
const k = ls.key(i);
|
|
1289
|
+
if (k && k.startsWith(COOKIE_PREFIX)) keys.push(k);
|
|
1290
|
+
}
|
|
1291
|
+
} catch {
|
|
1292
|
+
}
|
|
1293
|
+
for (const k of MIRRORED) if (!keys.includes(k)) keys.push(k);
|
|
1294
|
+
for (const k of keys) {
|
|
1295
|
+
const value = this.getSync(k);
|
|
1296
|
+
if (value !== null) this.memory.set(k, value);
|
|
1297
|
+
}
|
|
1298
|
+
this.persistent = false;
|
|
1299
|
+
for (const k of keys) {
|
|
1300
|
+
try {
|
|
1301
|
+
ls == null ? void 0 : ls.removeItem(k);
|
|
1302
|
+
} catch {
|
|
1303
|
+
}
|
|
1304
|
+
if (this.cookies) deleteCookie(k, this.cookieDomain());
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
// src/trackId.ts
|
|
1310
|
+
var CLICK_PARAM = "traq_click";
|
|
1311
|
+
var STORE_KEY = "traq_click";
|
|
1312
|
+
var CLICK_ID = /^[A-Za-z0-9_-]{8,64}$/;
|
|
1313
|
+
function clickIdFromUrl(href) {
|
|
1314
|
+
try {
|
|
1315
|
+
const raw = new URL(href).searchParams.get(CLICK_PARAM);
|
|
1316
|
+
return raw && CLICK_ID.test(raw) ? raw : null;
|
|
1317
|
+
} catch {
|
|
1318
|
+
return null;
|
|
1319
|
+
}
|
|
1320
|
+
}
|
|
1321
|
+
var TrackIdKeeper = class {
|
|
1322
|
+
constructor(store, maxAgeMs, cookieDomain, cookies) {
|
|
1323
|
+
this.store = store;
|
|
1324
|
+
this.maxAgeMs = maxAgeMs;
|
|
1325
|
+
this.cookieDomain = cookieDomain;
|
|
1326
|
+
this.cookies = cookies;
|
|
1327
|
+
}
|
|
1328
|
+
/**
|
|
1329
|
+
* Reads the landing URL. A new click REPLACES the kept one: the last ad clicked is
|
|
1330
|
+
* the one that brought the visitor this time. A URL without a click id changes
|
|
1331
|
+
* nothing — an internal navigation must not wipe the id the landing brought.
|
|
1332
|
+
*/
|
|
1333
|
+
capture(href, now = Date.now()) {
|
|
1334
|
+
const id = clickIdFromUrl(href);
|
|
1335
|
+
if (id) this.write(id, now);
|
|
1336
|
+
return id;
|
|
1337
|
+
}
|
|
1338
|
+
/** The kept click id, or null once it has expired or was never there. */
|
|
1339
|
+
get(now = Date.now()) {
|
|
1340
|
+
const raw = this.store.getSync(STORE_KEY);
|
|
1341
|
+
if (raw) {
|
|
1342
|
+
try {
|
|
1343
|
+
const parsed = JSON.parse(raw);
|
|
1344
|
+
if (parsed && typeof parsed.id === "string" && parsed.exp > now) return parsed.id;
|
|
1345
|
+
} catch {
|
|
1346
|
+
}
|
|
1347
|
+
}
|
|
1348
|
+
if (this.cookies && this.store.isPersistent) {
|
|
1349
|
+
const fromCookie = readCookie(STORE_KEY);
|
|
1350
|
+
if (fromCookie && CLICK_ID.test(fromCookie)) return fromCookie;
|
|
1351
|
+
}
|
|
1352
|
+
return null;
|
|
1353
|
+
}
|
|
1354
|
+
/** Removes it everywhere — `forgetMe()`. */
|
|
1355
|
+
clear() {
|
|
1356
|
+
this.store.removeSync(STORE_KEY);
|
|
1357
|
+
if (this.cookies) deleteCookie(STORE_KEY, this.cookieDomain());
|
|
1358
|
+
}
|
|
1359
|
+
/** Writes the cookie half once storage becomes allowed (the localStorage half moves with the store). */
|
|
1360
|
+
persistCookie(now = Date.now()) {
|
|
1361
|
+
const raw = this.store.getSync(STORE_KEY);
|
|
1362
|
+
if (!raw || !this.cookies || !this.store.isPersistent) return;
|
|
1363
|
+
try {
|
|
1364
|
+
const parsed = JSON.parse(raw);
|
|
1365
|
+
if (parsed.exp > now) writeCookie(STORE_KEY, parsed.id, (parsed.exp - now) / 1e3, this.cookieDomain());
|
|
1366
|
+
} catch {
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
write(id, now) {
|
|
1370
|
+
const record = { id, exp: now + this.maxAgeMs };
|
|
1371
|
+
this.store.setSync(STORE_KEY, JSON.stringify(record));
|
|
1372
|
+
if (this.cookies && this.store.isPersistent) writeCookie(STORE_KEY, id, this.maxAgeMs / 1e3, this.cookieDomain());
|
|
1373
|
+
}
|
|
1374
|
+
};
|
|
1375
|
+
|
|
1376
|
+
// src/index.ts
|
|
1377
|
+
var DEFAULT_ENDPOINT = "https://api.traqio.app";
|
|
1378
|
+
var DEFAULT_TRACK_ID_DAYS = 30;
|
|
1379
|
+
var DAY_MS = 24 * 60 * 60 * 1e3;
|
|
1380
|
+
function inBrowser() {
|
|
1381
|
+
return typeof window !== "undefined" && typeof document !== "undefined";
|
|
1382
|
+
}
|
|
1383
|
+
function randomId() {
|
|
1384
|
+
try {
|
|
1385
|
+
return typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : null;
|
|
1386
|
+
} catch {
|
|
1387
|
+
return null;
|
|
1388
|
+
}
|
|
1389
|
+
}
|
|
1390
|
+
var TraqioWeb = class {
|
|
1391
|
+
constructor() {
|
|
1392
|
+
this.core = new import_core.Client();
|
|
1393
|
+
this.store = null;
|
|
1394
|
+
this.trackIds = null;
|
|
1395
|
+
this.waitForConsent = false;
|
|
1396
|
+
this.started = false;
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Call once, as early as possible on every page (or once in a single-page app).
|
|
1400
|
+
* Reads the trackID from the current URL first, synchronously, so even a visitor
|
|
1401
|
+
* who leaves before the network answers keeps it. Safe to call on a server: it
|
|
1402
|
+
* does nothing there.
|
|
1403
|
+
*/
|
|
1404
|
+
async init(opts) {
|
|
1405
|
+
var _a, _b, _c;
|
|
1406
|
+
if (this.started || !inBrowser()) return;
|
|
1407
|
+
this.started = true;
|
|
1408
|
+
this.waitForConsent = opts.waitForConsent === true;
|
|
1409
|
+
const cookies = opts.cookies !== false;
|
|
1410
|
+
let domain;
|
|
1411
|
+
const cookieDomain = () => domain === void 0 ? domain = registrableDomain(location.hostname) : domain;
|
|
1412
|
+
const consent = (_a = opts.consent) != null ? _a : this.earlyConsent;
|
|
1413
|
+
const persistent = !this.waitForConsent || consent === true;
|
|
1414
|
+
this.store = new BrowserStore(persistent, cookieDomain, cookies);
|
|
1415
|
+
this.trackIds = new TrackIdKeeper(this.store, ((_b = opts.trackIdDays) != null ? _b : DEFAULT_TRACK_ID_DAYS) * DAY_MS, cookieDomain, cookies);
|
|
1416
|
+
this.trackIds.capture(location.href);
|
|
1417
|
+
if (!this.store.getSync(DEVICE_ID_KEY)) {
|
|
1418
|
+
const id = randomId();
|
|
1419
|
+
if (id) this.store.setSync(DEVICE_ID_KEY, id);
|
|
1420
|
+
}
|
|
1421
|
+
await this.core.init({
|
|
1422
|
+
sdkKey: opts.sdkKey,
|
|
1423
|
+
endpoint: ((_c = opts.endpoint) != null ? _c : DEFAULT_ENDPOINT).replace(/\/+$/, ""),
|
|
1424
|
+
storage: this.store,
|
|
1425
|
+
platform: "web",
|
|
1426
|
+
userId: opts.userId,
|
|
1427
|
+
consent,
|
|
1428
|
+
lifecycle: ({ background, foreground }) => {
|
|
1429
|
+
document.addEventListener("visibilitychange", () => document.visibilityState === "hidden" ? background() : foreground());
|
|
1430
|
+
window.addEventListener("pagehide", background);
|
|
1431
|
+
}
|
|
1432
|
+
});
|
|
1433
|
+
}
|
|
1434
|
+
/** Record an event — `signup`, `purchase`, `add_to_cart`… Batched, retried, kept across page loads. */
|
|
1435
|
+
track(name, props) {
|
|
1436
|
+
this.core.track(name, props);
|
|
1437
|
+
}
|
|
1438
|
+
/** Set the user id once known (after sign-in). */
|
|
1439
|
+
setUserId(id) {
|
|
1440
|
+
this.core.setUserId(id);
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1443
|
+
* The visitor's consent answer. Governs sharing with ad networks, and — with
|
|
1444
|
+
* `waitForConsent` — whether anything may be stored: `true` writes out what the
|
|
1445
|
+
* page kept in memory (the trackID included), `false` removes everything this SDK
|
|
1446
|
+
* stored on the device.
|
|
1447
|
+
*/
|
|
1448
|
+
async setConsent(granted) {
|
|
1449
|
+
var _a;
|
|
1450
|
+
if (!this.started) this.earlyConsent = granted;
|
|
1451
|
+
if (this.store && this.waitForConsent) {
|
|
1452
|
+
if (granted) {
|
|
1453
|
+
this.store.enable();
|
|
1454
|
+
(_a = this.trackIds) == null ? void 0 : _a.persistCookie();
|
|
1455
|
+
} else {
|
|
1456
|
+
this.store.disable();
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
await this.core.setConsent(granted);
|
|
1460
|
+
}
|
|
1461
|
+
/**
|
|
1462
|
+
* The trackID kept for this visitor, or null (no ad click, or expired). Pass it to
|
|
1463
|
+
* your backend with the sign-up or checkout — a hidden form field, a header — if
|
|
1464
|
+
* your backend cannot read the `traq_click` cookie itself.
|
|
1465
|
+
*/
|
|
1466
|
+
getTrackId() {
|
|
1467
|
+
var _a, _b;
|
|
1468
|
+
return (_b = (_a = this.trackIds) == null ? void 0 : _a.get()) != null ? _b : null;
|
|
1469
|
+
}
|
|
1470
|
+
/**
|
|
1471
|
+
* GDPR erasure from the page: the server deletes what it holds about this browser
|
|
1472
|
+
* and user, and this SDK stops sending and forgets the trackID. Irreversible.
|
|
1473
|
+
* Resolves false when the request did not reach the server — then nothing changed.
|
|
1474
|
+
*/
|
|
1475
|
+
async forgetMe() {
|
|
1476
|
+
var _a;
|
|
1477
|
+
const ok = await this.core.forgetMe();
|
|
1478
|
+
if (ok) (_a = this.trackIds) == null ? void 0 : _a.clear();
|
|
1479
|
+
return ok;
|
|
1480
|
+
}
|
|
1481
|
+
/** Send what is queued now. Already wired to tab hide and page exit. */
|
|
1482
|
+
flush() {
|
|
1483
|
+
this.core.flush();
|
|
1484
|
+
}
|
|
1485
|
+
/** True once `forgetMe()` has been honoured: this browser sends nothing any more. */
|
|
1486
|
+
get forgotten() {
|
|
1487
|
+
return this.core.forgotten;
|
|
1488
|
+
}
|
|
1489
|
+
};
|
|
1490
|
+
var Traqio = new TraqioWeb();
|
|
1491
|
+
//# sourceMappingURL=index.cjs.map
|