@lemuai/analytics 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +172 -2
- package/core/package.json +7 -0
- package/dist/chunk-2J55PE4P.js +656 -0
- package/dist/chunk-2J55PE4P.js.map +1 -0
- package/dist/core.cjs +667 -0
- package/dist/core.cjs.map +1 -0
- package/dist/core.d.cts +333 -0
- package/dist/core.d.ts +333 -0
- package/dist/core.js +3 -0
- package/dist/core.js.map +1 -0
- package/dist/index.cjs +838 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +50 -0
- package/dist/index.d.ts +50 -0
- package/dist/index.js +170 -0
- package/dist/index.js.map +1 -0
- package/dist/lemu.js +1 -0
- package/package.json +45 -4
package/dist/core.cjs
ADDED
|
@@ -0,0 +1,667 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/core/util.ts
|
|
4
|
+
function uuid() {
|
|
5
|
+
const c = typeof crypto !== "undefined" ? crypto : void 0;
|
|
6
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
7
|
+
const bytes = new Uint8Array(16);
|
|
8
|
+
if (c && typeof c.getRandomValues === "function") c.getRandomValues(bytes);
|
|
9
|
+
else for (let i = 0; i < 16; i++) bytes[i] = Math.random() * 256 | 0;
|
|
10
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
11
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
12
|
+
let hex = "";
|
|
13
|
+
for (let i = 0; i < 16; i++) hex += (bytes[i] + 256).toString(16).slice(1);
|
|
14
|
+
return hex.slice(0, 8) + "-" + hex.slice(8, 12) + "-" + hex.slice(12, 16) + "-" + hex.slice(16, 20) + "-" + hex.slice(20);
|
|
15
|
+
}
|
|
16
|
+
function isoNow() {
|
|
17
|
+
return (/* @__PURE__ */ new Date()).toISOString();
|
|
18
|
+
}
|
|
19
|
+
function isThenable(value) {
|
|
20
|
+
return !!value && typeof value.then === "function";
|
|
21
|
+
}
|
|
22
|
+
function settleAll(values, done) {
|
|
23
|
+
if (values.some(isThenable)) {
|
|
24
|
+
Promise.all(values.map((v) => Promise.resolve(v).catch(() => void 0))).then(done, () => done([]));
|
|
25
|
+
} else {
|
|
26
|
+
done(values);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
function cleanProps(value) {
|
|
30
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
|
|
31
|
+
const copy = JSON.parse(JSON.stringify(value));
|
|
32
|
+
return copy && typeof copy === "object" ? copy : {};
|
|
33
|
+
}
|
|
34
|
+
var CAMPAIGN_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "gclid", "fbclid", "lmclid"];
|
|
35
|
+
function parseCampaign(url) {
|
|
36
|
+
const out = {};
|
|
37
|
+
if (!url) return out;
|
|
38
|
+
const q = url.indexOf("?");
|
|
39
|
+
if (q < 0) return out;
|
|
40
|
+
const query = url.slice(q + 1).split("#")[0];
|
|
41
|
+
const parts = query.split("&");
|
|
42
|
+
for (let i = 0; i < parts.length; i++) {
|
|
43
|
+
const eq = parts[i].indexOf("=");
|
|
44
|
+
const key = decode(eq < 0 ? parts[i] : parts[i].slice(0, eq));
|
|
45
|
+
const value = eq < 0 ? "" : decode(parts[i].slice(eq + 1));
|
|
46
|
+
if (value && CAMPAIGN_KEYS.indexOf(key) >= 0 && !out[key.replace("utm_", "")]) {
|
|
47
|
+
out[key.replace("utm_", "")] = value;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
function decode(s) {
|
|
53
|
+
try {
|
|
54
|
+
return decodeURIComponent(s.replace(/\+/g, " "));
|
|
55
|
+
} catch (e) {
|
|
56
|
+
return s;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
function hasKeys(o) {
|
|
60
|
+
if (!o) return false;
|
|
61
|
+
for (const k in o) if (Object.prototype.hasOwnProperty.call(o, k)) return true;
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// src/core/client.ts
|
|
66
|
+
var DEFAULT_API_HOST = "https://app.lemuai.com";
|
|
67
|
+
var BATCH_PATH = "/api/v1/pixel/batch";
|
|
68
|
+
var KEYS = {
|
|
69
|
+
anonymousId: "_lemu_aid",
|
|
70
|
+
userId: "_lemu_uid",
|
|
71
|
+
optOut: "_lemu_optout",
|
|
72
|
+
queue: "_lemu_queue",
|
|
73
|
+
/** "1" once consent was granted; remembered like the other SDKs do. */
|
|
74
|
+
consent: "_lemu_consent"
|
|
75
|
+
};
|
|
76
|
+
var MAX_BATCH = 50;
|
|
77
|
+
var MAX_HELD = 50;
|
|
78
|
+
var MAX_PENDING_CALLS = 1e3;
|
|
79
|
+
var HOUR = 36e5;
|
|
80
|
+
var GIVE_UP_MS = 20 * HOUR;
|
|
81
|
+
var MAX_AGE_MS = 7 * 24 * HOUR;
|
|
82
|
+
var MAX_BACKOFF_MS = 3e5;
|
|
83
|
+
var LemuClient = class {
|
|
84
|
+
constructor(adapters) {
|
|
85
|
+
this.o = {};
|
|
86
|
+
this.writeKey = "";
|
|
87
|
+
this.host = DEFAULT_API_HOST;
|
|
88
|
+
this.campaign = {};
|
|
89
|
+
this.inited = false;
|
|
90
|
+
this.loaded = false;
|
|
91
|
+
this.calls = [];
|
|
92
|
+
this.values = {};
|
|
93
|
+
this.aid = null;
|
|
94
|
+
this.uid = null;
|
|
95
|
+
this.consent = true;
|
|
96
|
+
this.out = false;
|
|
97
|
+
this.queue = [];
|
|
98
|
+
this.flying = [];
|
|
99
|
+
/** Requests in flight, so `flush()` can wait for ones an earlier call started. */
|
|
100
|
+
this.posts = [];
|
|
101
|
+
this.held = [];
|
|
102
|
+
/** Storage writes waiting for consent. `null` once consent is given. */
|
|
103
|
+
this.writes = null;
|
|
104
|
+
this.timer = null;
|
|
105
|
+
this.retryAt = 0;
|
|
106
|
+
this.failures = 0;
|
|
107
|
+
this.seq = 0;
|
|
108
|
+
this.persisting = false;
|
|
109
|
+
this.unsubscribe = void 0;
|
|
110
|
+
this.closed = false;
|
|
111
|
+
this.a = adapters;
|
|
112
|
+
}
|
|
113
|
+
// --------------------------------------------------------------------------
|
|
114
|
+
// Public API
|
|
115
|
+
// --------------------------------------------------------------------------
|
|
116
|
+
/** Starts the client. Calls made before `init` are kept and run after it. */
|
|
117
|
+
init(writeKey, options) {
|
|
118
|
+
this.safe(() => {
|
|
119
|
+
if (this.inited) return this.log("init called again; ignored");
|
|
120
|
+
if (!writeKey || typeof writeKey !== "string") return this.log("init needs a write key; ignored");
|
|
121
|
+
const o = {};
|
|
122
|
+
assign(o, this.a.defaults);
|
|
123
|
+
assign(o, options);
|
|
124
|
+
this.o = o;
|
|
125
|
+
this.inited = true;
|
|
126
|
+
this.writeKey = writeKey;
|
|
127
|
+
if (o.apiHost) this.host = String(o.apiHost).replace(/\/+$/, "");
|
|
128
|
+
this.consent = !o.requireConsent;
|
|
129
|
+
if (!this.consent) this.writes = {};
|
|
130
|
+
this.log("init", writeKey, o);
|
|
131
|
+
this.load();
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
track(event, properties) {
|
|
135
|
+
this.when(() => {
|
|
136
|
+
if (typeof event !== "string" || !event.trim()) return this.log("track needs an event name; ignored");
|
|
137
|
+
this.send("track", { event, properties: this.props(properties) });
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
page(name, properties) {
|
|
141
|
+
this.when(() => {
|
|
142
|
+
if (name && typeof name === "object") {
|
|
143
|
+
properties = name;
|
|
144
|
+
name = void 0;
|
|
145
|
+
}
|
|
146
|
+
this.send("page", { name: name ? String(name) : void 0, properties: this.props(properties) });
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
screen(name, properties) {
|
|
150
|
+
this.when(() => {
|
|
151
|
+
if (typeof name !== "string" || !name.trim()) return this.log("screen needs a name; ignored");
|
|
152
|
+
this.send("screen", { name, properties: this.props(properties) });
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/** Sets the user's id (kept until `reset()`) and sends their traits. `identify(traits)` works too. */
|
|
156
|
+
identify(userId, traits) {
|
|
157
|
+
this.when(() => {
|
|
158
|
+
if (userId && typeof userId === "object") {
|
|
159
|
+
traits = userId;
|
|
160
|
+
userId = void 0;
|
|
161
|
+
}
|
|
162
|
+
if (userId !== void 0 && userId !== null && userId !== "") {
|
|
163
|
+
this.uid = String(userId);
|
|
164
|
+
this.store(KEYS.userId, this.uid);
|
|
165
|
+
}
|
|
166
|
+
this.send("identify", { traits: this.props(traits) });
|
|
167
|
+
this.sendNow(false);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
/** Sends a `Purchase` event at once. `value`, `currency` and `order_id` are required. */
|
|
171
|
+
purchase(purchase) {
|
|
172
|
+
this.when(() => {
|
|
173
|
+
if (!purchase || typeof purchase !== "object") return this.log("purchase needs {value, currency, order_id}; ignored");
|
|
174
|
+
const p = this.props(purchase);
|
|
175
|
+
if (p.order_id == null && p.orderId != null) p.order_id = p.orderId;
|
|
176
|
+
delete p.orderId;
|
|
177
|
+
if (typeof p.value === "string" && p.value.trim() && !isNaN(Number(p.value))) p.value = Number(p.value);
|
|
178
|
+
if (typeof p.order_id === "number") p.order_id = String(p.order_id);
|
|
179
|
+
if (typeof p.value !== "number" || !isFinite(p.value)) this.log("purchase: value should be a number");
|
|
180
|
+
if (typeof p.currency !== "string" || !p.currency) this.log("purchase: currency is missing");
|
|
181
|
+
if (typeof p.order_id !== "string" || !p.order_id) this.log("purchase: order_id is missing; Lemu can't de-duplicate this order");
|
|
182
|
+
this.send("track", { event: "Purchase", properties: p });
|
|
183
|
+
this.sendNow(false);
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/** On logout: a new anonymous id, and the user id is cleared. */
|
|
187
|
+
reset() {
|
|
188
|
+
this.when(() => {
|
|
189
|
+
this.uid = null;
|
|
190
|
+
this.aid = uuid();
|
|
191
|
+
this.store(KEYS.userId, null);
|
|
192
|
+
this.store(KEYS.anonymousId, this.aid);
|
|
193
|
+
this.log("reset", this.aid);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
/** Sends everything queued now. Resolves when the requests have finished. */
|
|
197
|
+
flush() {
|
|
198
|
+
return new Promise((resolve) => {
|
|
199
|
+
this.when(() => {
|
|
200
|
+
this.sendNow(false).then(resolve, resolve);
|
|
201
|
+
}, resolve);
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
/** With `requireConsent`, starts sending (true) or discards held events and stops (false). */
|
|
205
|
+
setConsent(granted) {
|
|
206
|
+
this.when(() => {
|
|
207
|
+
const held = this.held;
|
|
208
|
+
this.held = [];
|
|
209
|
+
this.consent = !!granted;
|
|
210
|
+
this.log("consent", this.consent);
|
|
211
|
+
if (!this.consent) {
|
|
212
|
+
this.writes = {};
|
|
213
|
+
this.queue = [];
|
|
214
|
+
this.write(KEYS.consent, null);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const writes = this.writes;
|
|
218
|
+
this.writes = null;
|
|
219
|
+
if (writes) for (const key in writes) this.store(key, writes[key]);
|
|
220
|
+
this.write(KEYS.consent, "1");
|
|
221
|
+
const aid = this.ensureId();
|
|
222
|
+
for (let i = 0; i < held.length; i++) {
|
|
223
|
+
held[i].anonymousId = aid;
|
|
224
|
+
this.push(held[i]);
|
|
225
|
+
}
|
|
226
|
+
this.schedule();
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/** Stops all tracking and clears the queue. Remembered across launches. */
|
|
230
|
+
optOut() {
|
|
231
|
+
this.when(() => {
|
|
232
|
+
this.out = true;
|
|
233
|
+
this.queue = [];
|
|
234
|
+
this.held = [];
|
|
235
|
+
this.write(KEYS.optOut, "1");
|
|
236
|
+
if (this.a.persistQueue) this.write(KEYS.queue, null);
|
|
237
|
+
this.log("opted out");
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
optIn() {
|
|
241
|
+
this.when(() => {
|
|
242
|
+
this.out = false;
|
|
243
|
+
this.write(KEYS.optOut, null);
|
|
244
|
+
this.log("opted in");
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
/** The visitor's anonymous id, or null before consent, after opt-out, or before the client has loaded. */
|
|
248
|
+
anonymousId() {
|
|
249
|
+
return this.safe(() => this.loaded && this.consent && !this.out ? this.ensureId() : null) || null;
|
|
250
|
+
}
|
|
251
|
+
userId() {
|
|
252
|
+
return this.uid;
|
|
253
|
+
}
|
|
254
|
+
/** Resolves once storage has loaded and calls made before that have run. */
|
|
255
|
+
ready() {
|
|
256
|
+
return new Promise((resolve) => this.when(resolve, resolve));
|
|
257
|
+
}
|
|
258
|
+
/** Stops timers and listeners. Queued messages stay in storage (apps). */
|
|
259
|
+
shutdown() {
|
|
260
|
+
this.safe(() => {
|
|
261
|
+
this.closed = true;
|
|
262
|
+
if (this.timer) clearTimeout(this.timer);
|
|
263
|
+
this.timer = null;
|
|
264
|
+
if (this.unsubscribe) this.unsubscribe();
|
|
265
|
+
this.unsubscribe = void 0;
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
// --------------------------------------------------------------------------
|
|
269
|
+
// For platform packages
|
|
270
|
+
// --------------------------------------------------------------------------
|
|
271
|
+
/** Called once storage has loaded, before calls made earlier run. */
|
|
272
|
+
started() {
|
|
273
|
+
}
|
|
274
|
+
onForeground() {
|
|
275
|
+
}
|
|
276
|
+
onBackground() {
|
|
277
|
+
this.sendNow(true);
|
|
278
|
+
}
|
|
279
|
+
/** A value read from storage at start (keys from `adapters.extraKeys`). */
|
|
280
|
+
stored(key) {
|
|
281
|
+
return this.values[key];
|
|
282
|
+
}
|
|
283
|
+
/** Writes to storage, or holds the write until consent. */
|
|
284
|
+
store(key, value) {
|
|
285
|
+
if (this.writes) this.writes[key] = value;
|
|
286
|
+
else this.write(key, value);
|
|
287
|
+
}
|
|
288
|
+
setCampaign(campaign) {
|
|
289
|
+
this.campaign = campaign;
|
|
290
|
+
}
|
|
291
|
+
options() {
|
|
292
|
+
return this.o;
|
|
293
|
+
}
|
|
294
|
+
/** Runs `fn` now if the client has started, otherwise after it does. Never throws. */
|
|
295
|
+
when(fn, otherwise) {
|
|
296
|
+
if (this.inited && this.loaded) {
|
|
297
|
+
this.safe(fn);
|
|
298
|
+
} else if (this.calls.length < MAX_PENDING_CALLS) {
|
|
299
|
+
this.calls.push(fn);
|
|
300
|
+
} else if (otherwise) {
|
|
301
|
+
otherwise();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
safe(fn) {
|
|
305
|
+
try {
|
|
306
|
+
return fn();
|
|
307
|
+
} catch (e) {
|
|
308
|
+
this.log("error", e);
|
|
309
|
+
return void 0;
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
log(...args) {
|
|
313
|
+
if (this.o.debug && typeof console !== "undefined") console.log("[lemu]", ...args);
|
|
314
|
+
}
|
|
315
|
+
/** Sends what is queued. `beacon` uses the transport's fire-and-forget path when it has one. */
|
|
316
|
+
sendNow(beacon) {
|
|
317
|
+
if (this.timer) clearTimeout(this.timer);
|
|
318
|
+
this.timer = null;
|
|
319
|
+
if (!this.writeKey || !this.consent || this.out || this.closed) return Promise.resolve();
|
|
320
|
+
const now = Date.now();
|
|
321
|
+
this.queue = this.queue.filter((i) => now - i.q < MAX_AGE_MS);
|
|
322
|
+
const jobs = [];
|
|
323
|
+
while (this.queue.length) {
|
|
324
|
+
const items = this.queue.splice(0, MAX_BATCH);
|
|
325
|
+
if (beacon && this.a.transport.beacon) {
|
|
326
|
+
const ok = this.safe(() => this.a.transport.beacon({ url: this.url(), body: this.body(items) }));
|
|
327
|
+
if (ok) {
|
|
328
|
+
this.log("beacon", items.length);
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
jobs.push(this.post(items));
|
|
333
|
+
}
|
|
334
|
+
this.persist();
|
|
335
|
+
return Promise.all(jobs.concat(this.posts)).then(() => void 0);
|
|
336
|
+
}
|
|
337
|
+
// --------------------------------------------------------------------------
|
|
338
|
+
// Internals
|
|
339
|
+
// --------------------------------------------------------------------------
|
|
340
|
+
load() {
|
|
341
|
+
const keys = [KEYS.anonymousId, KEYS.userId, KEYS.optOut];
|
|
342
|
+
if (this.a.persistQueue) keys.push(KEYS.queue);
|
|
343
|
+
keys.push(KEYS.consent);
|
|
344
|
+
const extra = this.a.extraKeys || [];
|
|
345
|
+
for (let i = 0; i < extra.length; i++) keys.push(extra[i]);
|
|
346
|
+
const reads = keys.map((k) => {
|
|
347
|
+
try {
|
|
348
|
+
return this.a.storage.get(k);
|
|
349
|
+
} catch (e) {
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
});
|
|
353
|
+
settleAll(reads, (values) => {
|
|
354
|
+
this.safe(() => {
|
|
355
|
+
for (let i = 0; i < keys.length; i++) this.values[keys[i]] = values[i];
|
|
356
|
+
this.out = values[2] === "1";
|
|
357
|
+
this.aid = values[0] || null;
|
|
358
|
+
this.uid = values[1] || null;
|
|
359
|
+
if (this.a.persistQueue && values[3]) this.restore(values[3]);
|
|
360
|
+
if (!this.consent && this.values[KEYS.consent] === "1") {
|
|
361
|
+
this.consent = true;
|
|
362
|
+
this.writes = null;
|
|
363
|
+
}
|
|
364
|
+
});
|
|
365
|
+
this.loaded = true;
|
|
366
|
+
this.safe(() => {
|
|
367
|
+
if (this.consent && !this.out) this.store(KEYS.anonymousId, this.ensureId());
|
|
368
|
+
if (this.a.lifecycle) {
|
|
369
|
+
this.unsubscribe = this.a.lifecycle.subscribe({
|
|
370
|
+
foreground: () => this.safe(() => this.onForeground()),
|
|
371
|
+
background: () => this.safe(() => this.onBackground())
|
|
372
|
+
});
|
|
373
|
+
}
|
|
374
|
+
this.started();
|
|
375
|
+
});
|
|
376
|
+
const calls = this.calls;
|
|
377
|
+
this.calls = [];
|
|
378
|
+
for (let i = 0; i < calls.length; i++) this.safe(calls[i]);
|
|
379
|
+
this.safe(() => this.schedule());
|
|
380
|
+
});
|
|
381
|
+
}
|
|
382
|
+
restore(raw) {
|
|
383
|
+
const items = JSON.parse(raw);
|
|
384
|
+
if (!Array.isArray(items)) return;
|
|
385
|
+
const restored = [];
|
|
386
|
+
for (let i = 0; i < items.length; i++) {
|
|
387
|
+
const it = items[i];
|
|
388
|
+
if (it && it.m && typeof it.m === "object" && typeof it.q === "number") restored.push({ m: it.m, q: it.q, n: 0, f: it.f });
|
|
389
|
+
}
|
|
390
|
+
for (let i = 0; i < this.queue.length; i++) restored.push(this.queue[i]);
|
|
391
|
+
for (let i = 0; i < restored.length; i++) restored[i].n = ++this.seq;
|
|
392
|
+
this.queue = restored;
|
|
393
|
+
this.trim();
|
|
394
|
+
}
|
|
395
|
+
ensureId() {
|
|
396
|
+
if (!this.aid) {
|
|
397
|
+
this.aid = uuid();
|
|
398
|
+
this.store(KEYS.anonymousId, this.aid);
|
|
399
|
+
}
|
|
400
|
+
return this.aid;
|
|
401
|
+
}
|
|
402
|
+
props(value) {
|
|
403
|
+
try {
|
|
404
|
+
return cleanProps(value);
|
|
405
|
+
} catch (e) {
|
|
406
|
+
this.log("properties could not be serialised; sent as {}", e);
|
|
407
|
+
return {};
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
context() {
|
|
411
|
+
const ctx = this.a.context() || {};
|
|
412
|
+
ctx.platform = this.a.platform;
|
|
413
|
+
ctx.library = this.a.library;
|
|
414
|
+
if (!ctx.campaign && hasKeys(this.campaign)) ctx.campaign = assign({}, this.campaign);
|
|
415
|
+
return ctx;
|
|
416
|
+
}
|
|
417
|
+
send(type, fields) {
|
|
418
|
+
if (this.out) return this.log("opted out; dropped", type);
|
|
419
|
+
const m = { type, messageId: uuid(), timestamp: isoNow(), context: this.context() };
|
|
420
|
+
for (const k in fields) {
|
|
421
|
+
const v = fields[k];
|
|
422
|
+
if (v !== void 0) m[k] = v;
|
|
423
|
+
}
|
|
424
|
+
if (this.uid) m.userId = this.uid;
|
|
425
|
+
this.log(type, m);
|
|
426
|
+
if (!this.consent) {
|
|
427
|
+
if (this.held.length < MAX_HELD) this.held.push(m);
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
m.anonymousId = this.ensureId();
|
|
431
|
+
this.push(m);
|
|
432
|
+
this.schedule();
|
|
433
|
+
}
|
|
434
|
+
push(m) {
|
|
435
|
+
this.queue.push({ m, q: Date.now(), n: ++this.seq });
|
|
436
|
+
this.trim();
|
|
437
|
+
this.persist();
|
|
438
|
+
}
|
|
439
|
+
/** Over the limit: drop the oldest message that isn't a Purchase. */
|
|
440
|
+
trim() {
|
|
441
|
+
const max = this.o.maxQueueSize || 1e3;
|
|
442
|
+
while (this.queue.length > max) {
|
|
443
|
+
let idx = 0;
|
|
444
|
+
for (let i = 0; i < this.queue.length; i++) {
|
|
445
|
+
if (this.queue[i].m.event !== "Purchase") {
|
|
446
|
+
idx = i;
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
this.queue.splice(idx, 1);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
schedule() {
|
|
454
|
+
if (!this.queue.length || !this.consent || this.out || this.closed || !this.writeKey) return;
|
|
455
|
+
const now = Date.now();
|
|
456
|
+
if (this.queue.length >= (this.o.flushAt || 20) && now >= this.retryAt) {
|
|
457
|
+
this.sendNow(false);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (!this.timer) {
|
|
461
|
+
const delay = Math.max(this.o.flushInterval || 3e4, this.retryAt - now);
|
|
462
|
+
const t = setTimeout(() => {
|
|
463
|
+
if (this.timer === t) this.timer = null;
|
|
464
|
+
this.sendNow(false);
|
|
465
|
+
}, delay);
|
|
466
|
+
this.timer = t;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
url() {
|
|
470
|
+
return this.host + BATCH_PATH;
|
|
471
|
+
}
|
|
472
|
+
body(items) {
|
|
473
|
+
const body = { writeKey: this.writeKey, sentAt: isoNow(), batch: items.map((i) => i.m) };
|
|
474
|
+
return JSON.stringify(body);
|
|
475
|
+
}
|
|
476
|
+
post(items) {
|
|
477
|
+
this.flying = this.flying.concat(items);
|
|
478
|
+
const body = this.body(items);
|
|
479
|
+
this.log("request", body);
|
|
480
|
+
let sent;
|
|
481
|
+
try {
|
|
482
|
+
sent = this.a.transport.send({ url: this.url(), body });
|
|
483
|
+
} catch (e) {
|
|
484
|
+
sent = Promise.reject(e);
|
|
485
|
+
}
|
|
486
|
+
const done = sent.then(
|
|
487
|
+
(status) => this.settle(items, typeof status === "number" && status > 0 ? status : 204),
|
|
488
|
+
(err) => this.settle(items, err && err.timeout ? "timeout" : "network")
|
|
489
|
+
).then(() => {
|
|
490
|
+
this.posts = this.posts.filter((p) => p !== done);
|
|
491
|
+
});
|
|
492
|
+
this.posts.push(done);
|
|
493
|
+
return done;
|
|
494
|
+
}
|
|
495
|
+
settle(items, outcome) {
|
|
496
|
+
return this.safe(() => {
|
|
497
|
+
this.flying = this.flying.filter((i) => items.indexOf(i) < 0);
|
|
498
|
+
this.log("response", outcome, items.length + " messages");
|
|
499
|
+
if (typeof outcome === "number" && outcome >= 200 && outcome < 300) {
|
|
500
|
+
this.failures = 0;
|
|
501
|
+
this.retryAt = 0;
|
|
502
|
+
this.persist();
|
|
503
|
+
this.schedule();
|
|
504
|
+
return void 0;
|
|
505
|
+
}
|
|
506
|
+
if (outcome === 413) {
|
|
507
|
+
if (items.length === 1) {
|
|
508
|
+
this.log("message too large; dropped");
|
|
509
|
+
this.persist();
|
|
510
|
+
return void 0;
|
|
511
|
+
}
|
|
512
|
+
const half = Math.ceil(items.length / 2);
|
|
513
|
+
return this.post(items.slice(0, half)).then(() => this.post(items.slice(half)));
|
|
514
|
+
}
|
|
515
|
+
if (outcome === "network" || outcome === "timeout" || outcome === 408 || outcome === 429 || outcome >= 500) {
|
|
516
|
+
this.retry(items, outcome !== "network");
|
|
517
|
+
return void 0;
|
|
518
|
+
}
|
|
519
|
+
this.log("batch dropped", outcome);
|
|
520
|
+
this.persist();
|
|
521
|
+
return void 0;
|
|
522
|
+
}) || Promise.resolve();
|
|
523
|
+
}
|
|
524
|
+
retry(items, reachedServer) {
|
|
525
|
+
const now = Date.now();
|
|
526
|
+
const keep = items.filter((i) => {
|
|
527
|
+
if (reachedServer && i.f === void 0) i.f = now;
|
|
528
|
+
return i.f === void 0 || now - i.f < GIVE_UP_MS;
|
|
529
|
+
});
|
|
530
|
+
this.queue = keep.concat(this.queue).sort((x, y) => x.n - y.n);
|
|
531
|
+
this.trim();
|
|
532
|
+
this.persist();
|
|
533
|
+
if (now >= this.retryAt) {
|
|
534
|
+
this.failures++;
|
|
535
|
+
const base = Math.min(1e3 * Math.pow(2, this.failures - 1), MAX_BACKOFF_MS);
|
|
536
|
+
this.retryAt = now + base * (0.8 + Math.random() * 0.4);
|
|
537
|
+
}
|
|
538
|
+
if (this.timer) clearTimeout(this.timer);
|
|
539
|
+
this.timer = null;
|
|
540
|
+
if (this.closed) return;
|
|
541
|
+
const t = setTimeout(() => {
|
|
542
|
+
if (this.timer === t) this.timer = null;
|
|
543
|
+
this.sendNow(false);
|
|
544
|
+
}, this.retryAt - now);
|
|
545
|
+
this.timer = t;
|
|
546
|
+
this.log("retry in", Math.round(this.retryAt - now), "ms");
|
|
547
|
+
}
|
|
548
|
+
/** Apps: write the queue (including requests in flight) to storage, at most once per tick. */
|
|
549
|
+
persist() {
|
|
550
|
+
if (!this.a.persistQueue || this.persisting || this.writes || this.out) return;
|
|
551
|
+
this.persisting = true;
|
|
552
|
+
Promise.resolve().then(() => {
|
|
553
|
+
this.persisting = false;
|
|
554
|
+
if (this.writes || this.out) return;
|
|
555
|
+
const all = this.flying.concat(this.queue).sort((x, y) => x.n - y.n);
|
|
556
|
+
this.write(KEYS.queue, all.length ? JSON.stringify(all) : null);
|
|
557
|
+
});
|
|
558
|
+
}
|
|
559
|
+
write(key, value) {
|
|
560
|
+
try {
|
|
561
|
+
const r = value === null ? this.a.storage.remove(key) : this.a.storage.set(key, value);
|
|
562
|
+
if (r && typeof r.catch === "function") r.catch(() => void 0);
|
|
563
|
+
} catch (e) {
|
|
564
|
+
this.log("storage error", e);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
};
|
|
568
|
+
function assign(target, source) {
|
|
569
|
+
if (source) {
|
|
570
|
+
for (const k in source) if (source[k] !== void 0) target[k] = source[k];
|
|
571
|
+
}
|
|
572
|
+
return target;
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
// src/core/events.ts
|
|
576
|
+
var LemuEvent = {
|
|
577
|
+
// Meta standard events
|
|
578
|
+
PageView: "PageView",
|
|
579
|
+
ViewContent: "ViewContent",
|
|
580
|
+
Search: "Search",
|
|
581
|
+
AddToCart: "AddToCart",
|
|
582
|
+
AddToWishlist: "AddToWishlist",
|
|
583
|
+
InitiateCheckout: "InitiateCheckout",
|
|
584
|
+
AddPaymentInfo: "AddPaymentInfo",
|
|
585
|
+
Purchase: "Purchase",
|
|
586
|
+
Lead: "Lead",
|
|
587
|
+
CompleteRegistration: "CompleteRegistration",
|
|
588
|
+
Subscribe: "Subscribe",
|
|
589
|
+
StartTrial: "StartTrial",
|
|
590
|
+
Schedule: "Schedule",
|
|
591
|
+
SubmitApplication: "SubmitApplication",
|
|
592
|
+
Contact: "Contact",
|
|
593
|
+
CustomizeProduct: "CustomizeProduct",
|
|
594
|
+
Donate: "Donate",
|
|
595
|
+
FindLocation: "FindLocation",
|
|
596
|
+
// App lifecycle events
|
|
597
|
+
AppInstalled: "app_installed",
|
|
598
|
+
AppUpdated: "app_updated",
|
|
599
|
+
AppOpened: "app_opened",
|
|
600
|
+
AppBackgrounded: "app_backgrounded",
|
|
601
|
+
DeepLinkOpened: "deep_link_opened",
|
|
602
|
+
ScreenViewed: "screen_viewed"
|
|
603
|
+
};
|
|
604
|
+
|
|
605
|
+
// src/core/fetch-transport.ts
|
|
606
|
+
function fetchTransport(options = {}) {
|
|
607
|
+
return {
|
|
608
|
+
send(request) {
|
|
609
|
+
const f = options.fetch || (typeof fetch !== "undefined" ? fetch : void 0);
|
|
610
|
+
if (!f) return Promise.reject(new Error("fetch is not available"));
|
|
611
|
+
const init = { method: "POST", body: request.body, headers: options.headers || {} };
|
|
612
|
+
if (options.init) for (const k in options.init) init[k] = options.init[k];
|
|
613
|
+
let timer;
|
|
614
|
+
let timedOut = false;
|
|
615
|
+
if (typeof AbortController !== "undefined") {
|
|
616
|
+
const controller = new AbortController();
|
|
617
|
+
init.signal = controller.signal;
|
|
618
|
+
timer = setTimeout(() => {
|
|
619
|
+
timedOut = true;
|
|
620
|
+
controller.abort();
|
|
621
|
+
}, options.timeout || 1e4);
|
|
622
|
+
}
|
|
623
|
+
return f(request.url, init).then(
|
|
624
|
+
(res) => {
|
|
625
|
+
if (timer) clearTimeout(timer);
|
|
626
|
+
return res ? res.status : void 0;
|
|
627
|
+
},
|
|
628
|
+
(err) => {
|
|
629
|
+
if (timer) clearTimeout(timer);
|
|
630
|
+
throw timedOut ? { timeout: true } : err;
|
|
631
|
+
}
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
};
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// src/core/memory-storage.ts
|
|
638
|
+
function memoryStorage(initial) {
|
|
639
|
+
const data = {};
|
|
640
|
+
if (initial) for (const k in initial) data[k] = initial[k];
|
|
641
|
+
return {
|
|
642
|
+
data,
|
|
643
|
+
get: (key) => Object.prototype.hasOwnProperty.call(data, key) ? data[key] : null,
|
|
644
|
+
set: (key, value) => {
|
|
645
|
+
data[key] = value;
|
|
646
|
+
},
|
|
647
|
+
remove: (key) => {
|
|
648
|
+
delete data[key];
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
// src/version.ts
|
|
654
|
+
var VERSION = "1.1.0";
|
|
655
|
+
|
|
656
|
+
exports.BATCH_PATH = BATCH_PATH;
|
|
657
|
+
exports.DEFAULT_API_HOST = DEFAULT_API_HOST;
|
|
658
|
+
exports.KEYS = KEYS;
|
|
659
|
+
exports.LemuClient = LemuClient;
|
|
660
|
+
exports.LemuEvent = LemuEvent;
|
|
661
|
+
exports.VERSION = VERSION;
|
|
662
|
+
exports.fetchTransport = fetchTransport;
|
|
663
|
+
exports.memoryStorage = memoryStorage;
|
|
664
|
+
exports.parseCampaign = parseCampaign;
|
|
665
|
+
exports.uuid = uuid;
|
|
666
|
+
//# sourceMappingURL=core.cjs.map
|
|
667
|
+
//# sourceMappingURL=core.cjs.map
|