@fire-spark/analytics 0.17.3 → 0.19.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/README.md +34 -0
- package/dist/index.d.ts +119 -6
- package/dist/index.js +1759 -574
- package/package.json +3 -2
package/dist/index.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import { StorefrontHttpError, logError, storefrontJson } from "@fire-spark/core";
|
|
2
|
-
|
|
3
|
-
|
|
2
|
+
import { Big } from "big.js";
|
|
3
|
+
//#region src/version.ts
|
|
4
|
+
/** Kept equal to package.json by `pnpm sdk:release` (see version.test.ts). */
|
|
5
|
+
const SDK_VERSION = "0.19.0";
|
|
4
6
|
const intlContext = () => {
|
|
5
7
|
try {
|
|
6
8
|
const options = Intl.DateTimeFormat().resolvedOptions();
|
|
@@ -12,7 +14,7 @@ const intlContext = () => {
|
|
|
12
14
|
return {};
|
|
13
15
|
}
|
|
14
16
|
};
|
|
15
|
-
const compact = (context) => {
|
|
17
|
+
const compact$1 = (context) => {
|
|
16
18
|
const next = {};
|
|
17
19
|
for (const [key, raw] of Object.entries(context)) {
|
|
18
20
|
if (typeof raw !== "string") continue;
|
|
@@ -27,11 +29,164 @@ const buildEventContext = (context) => {
|
|
|
27
29
|
...context
|
|
28
30
|
};
|
|
29
31
|
return {
|
|
30
|
-
...compact(merged),
|
|
32
|
+
...compact$1(merged),
|
|
31
33
|
sdk_version: SDK_VERSION
|
|
32
34
|
};
|
|
33
35
|
};
|
|
34
36
|
//#endregion
|
|
37
|
+
//#region src/sha256.ts
|
|
38
|
+
const K = [
|
|
39
|
+
1116352408,
|
|
40
|
+
1899447441,
|
|
41
|
+
3049323471,
|
|
42
|
+
3921009573,
|
|
43
|
+
961987163,
|
|
44
|
+
1508970993,
|
|
45
|
+
2453635748,
|
|
46
|
+
2870763221,
|
|
47
|
+
3624381080,
|
|
48
|
+
310598401,
|
|
49
|
+
607225278,
|
|
50
|
+
1426881987,
|
|
51
|
+
1925078388,
|
|
52
|
+
2162078206,
|
|
53
|
+
2614888103,
|
|
54
|
+
3248222580,
|
|
55
|
+
3835390401,
|
|
56
|
+
4022224774,
|
|
57
|
+
264347078,
|
|
58
|
+
604807628,
|
|
59
|
+
770255983,
|
|
60
|
+
1249150122,
|
|
61
|
+
1555081692,
|
|
62
|
+
1996064986,
|
|
63
|
+
2554220882,
|
|
64
|
+
2821834349,
|
|
65
|
+
2952996808,
|
|
66
|
+
3210313671,
|
|
67
|
+
3336571891,
|
|
68
|
+
3584528711,
|
|
69
|
+
113926993,
|
|
70
|
+
338241895,
|
|
71
|
+
666307205,
|
|
72
|
+
773529912,
|
|
73
|
+
1294757372,
|
|
74
|
+
1396182291,
|
|
75
|
+
1695183700,
|
|
76
|
+
1986661051,
|
|
77
|
+
2177026350,
|
|
78
|
+
2456956037,
|
|
79
|
+
2730485921,
|
|
80
|
+
2820302411,
|
|
81
|
+
3259730800,
|
|
82
|
+
3345764771,
|
|
83
|
+
3516065817,
|
|
84
|
+
3600352804,
|
|
85
|
+
4094571909,
|
|
86
|
+
275423344,
|
|
87
|
+
430227734,
|
|
88
|
+
506948616,
|
|
89
|
+
659060556,
|
|
90
|
+
883997877,
|
|
91
|
+
958139571,
|
|
92
|
+
1322822218,
|
|
93
|
+
1537002063,
|
|
94
|
+
1747873779,
|
|
95
|
+
1955562222,
|
|
96
|
+
2024104815,
|
|
97
|
+
2227730452,
|
|
98
|
+
2361852424,
|
|
99
|
+
2428436474,
|
|
100
|
+
2756734187,
|
|
101
|
+
3204031479,
|
|
102
|
+
3329325298
|
|
103
|
+
];
|
|
104
|
+
const H0 = [
|
|
105
|
+
1779033703,
|
|
106
|
+
3144134277,
|
|
107
|
+
1013904242,
|
|
108
|
+
2773480762,
|
|
109
|
+
1359893119,
|
|
110
|
+
2600822924,
|
|
111
|
+
528734635,
|
|
112
|
+
1541459225
|
|
113
|
+
];
|
|
114
|
+
const rotr = (value, bits) => {
|
|
115
|
+
return value >>> bits | value << 32 - bits;
|
|
116
|
+
};
|
|
117
|
+
/** UTF-8 bytes without `TextEncoder`, which older Hermes builds lack. */
|
|
118
|
+
const utf8 = (value) => {
|
|
119
|
+
const bytes = [];
|
|
120
|
+
for (const char of value) {
|
|
121
|
+
const code = char.codePointAt(0);
|
|
122
|
+
if (code < 128) bytes.push(code);
|
|
123
|
+
else if (code < 2048) bytes.push(192 | code >> 6, 128 | code & 63);
|
|
124
|
+
else if (code < 65536) {
|
|
125
|
+
const b1 = 224 | code >> 12;
|
|
126
|
+
bytes.push(b1, 128 | code >> 6 & 63, 128 | code & 63);
|
|
127
|
+
} else {
|
|
128
|
+
bytes.push(240 | code >> 18, 128 | code >> 12 & 63);
|
|
129
|
+
bytes.push(128 | code >> 6 & 63, 128 | code & 63);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return Uint8Array.from(bytes);
|
|
133
|
+
};
|
|
134
|
+
const padded = (bytes) => {
|
|
135
|
+
const bitLength = bytes.length * 8;
|
|
136
|
+
const total = Math.ceil((bytes.length + 9) / 64) * 64;
|
|
137
|
+
const out = new Uint8Array(total);
|
|
138
|
+
out.set(bytes);
|
|
139
|
+
out[bytes.length] = 128;
|
|
140
|
+
const view = new DataView(out.buffer);
|
|
141
|
+
view.setUint32(total - 8, Math.floor(bitLength / 4294967296));
|
|
142
|
+
view.setUint32(total - 4, bitLength >>> 0);
|
|
143
|
+
return view;
|
|
144
|
+
};
|
|
145
|
+
const compress = (view, offset, h) => {
|
|
146
|
+
const w = new Array(64);
|
|
147
|
+
for (let i = 0; i < 16; i += 1) w[i] = view.getUint32(offset + i * 4);
|
|
148
|
+
for (let i = 16; i < 64; i += 1) {
|
|
149
|
+
const a = w[i - 15];
|
|
150
|
+
const b = w[i - 2];
|
|
151
|
+
const s0 = rotr(a, 7) ^ rotr(a, 18) ^ a >>> 3;
|
|
152
|
+
const s1 = rotr(b, 17) ^ rotr(b, 19) ^ b >>> 10;
|
|
153
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 | 0;
|
|
154
|
+
}
|
|
155
|
+
let [a, b, c, d, e, f, g, hh] = h;
|
|
156
|
+
for (let i = 0; i < 64; i += 1) {
|
|
157
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
158
|
+
const ch = e & f ^ ~e & g;
|
|
159
|
+
const t1 = hh + s1 + ch + K[i] + w[i] | 0;
|
|
160
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) | 0;
|
|
161
|
+
hh = g;
|
|
162
|
+
g = f;
|
|
163
|
+
f = e;
|
|
164
|
+
e = d + t1 | 0;
|
|
165
|
+
d = c;
|
|
166
|
+
c = b;
|
|
167
|
+
b = a;
|
|
168
|
+
a = t1 + t2 | 0;
|
|
169
|
+
}
|
|
170
|
+
const next = [
|
|
171
|
+
a,
|
|
172
|
+
b,
|
|
173
|
+
c,
|
|
174
|
+
d,
|
|
175
|
+
e,
|
|
176
|
+
f,
|
|
177
|
+
g,
|
|
178
|
+
hh
|
|
179
|
+
];
|
|
180
|
+
for (let i = 0; i < 8; i += 1) h[i] = h[i] + next[i] | 0;
|
|
181
|
+
};
|
|
182
|
+
/** Pure-JS SHA-256 (hex) for runtimes without `crypto.subtle`. */
|
|
183
|
+
const sha256Hex = (value) => {
|
|
184
|
+
const view = padded(utf8(value));
|
|
185
|
+
const h = [...H0];
|
|
186
|
+
for (let offset = 0; offset < view.byteLength; offset += 64) compress(view, offset, h);
|
|
187
|
+
return h.map((word) => (word >>> 0).toString(16).padStart(8, "0")).join("");
|
|
188
|
+
};
|
|
189
|
+
//#endregion
|
|
35
190
|
//#region src/pii.ts
|
|
36
191
|
const PII_KEYS = /* @__PURE__ */ new Set([
|
|
37
192
|
"phone",
|
|
@@ -45,22 +200,26 @@ const toHex = (bytes) => {
|
|
|
45
200
|
const isPiiParam = (name) => {
|
|
46
201
|
return PII_KEYS.has(name);
|
|
47
202
|
};
|
|
48
|
-
|
|
203
|
+
/** `crypto.subtle` when available, else the built-in implementation. */
|
|
204
|
+
const defaultHash = async (value) => {
|
|
49
205
|
const subtle = globalThis.crypto?.subtle;
|
|
50
|
-
if (!subtle)
|
|
51
|
-
const
|
|
52
|
-
const data = new TextEncoder().encode(normalized);
|
|
206
|
+
if (!subtle) return sha256Hex(value);
|
|
207
|
+
const data = new TextEncoder().encode(value);
|
|
53
208
|
const digest = await subtle.digest("SHA-256", data);
|
|
54
209
|
return toHex(new Uint8Array(digest));
|
|
55
210
|
};
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
211
|
+
const hashPiiValue = async (value, hash) => {
|
|
212
|
+
return hash(value.trim().toLowerCase());
|
|
213
|
+
};
|
|
214
|
+
const hashDeep = async (value, hash) => {
|
|
215
|
+
if (typeof value === "string") return hashPiiValue(value, hash);
|
|
216
|
+
if (typeof value === "number" || typeof value === "boolean") return hashPiiValue(String(value), hash);
|
|
217
|
+
if (Array.isArray(value)) return Promise.all(value.map((item) => hashDeep(item, hash)));
|
|
60
218
|
if (!value || typeof value !== "object") return value;
|
|
61
|
-
return hashPiiParams(value);
|
|
219
|
+
return hashPiiParams(value, hash);
|
|
62
220
|
};
|
|
63
|
-
|
|
221
|
+
/** Hashes PII params. A param whose hash fails is omitted, never sent raw. */
|
|
222
|
+
const hashPiiParams = async (params, hash = defaultHash, onFailure) => {
|
|
64
223
|
const next = {};
|
|
65
224
|
for (const [key, value] of Object.entries(params)) {
|
|
66
225
|
if (!isPiiParam(key)) {
|
|
@@ -68,183 +227,61 @@ const hashPiiParams = async (params) => {
|
|
|
68
227
|
continue;
|
|
69
228
|
}
|
|
70
229
|
try {
|
|
71
|
-
next[key] = await hashDeep(value);
|
|
72
|
-
} catch {
|
|
230
|
+
next[key] = await hashDeep(value, hash);
|
|
231
|
+
} catch (error) {
|
|
232
|
+
onFailure?.(key, error);
|
|
233
|
+
}
|
|
73
234
|
}
|
|
74
235
|
return next;
|
|
75
236
|
};
|
|
76
237
|
//#endregion
|
|
77
|
-
//#region src/
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
"product_viewed",
|
|
81
|
-
"add_to_cart",
|
|
82
|
-
"purchase"
|
|
83
|
-
];
|
|
84
|
-
const INTERACTION_EVENTS = ["product_visited", "category_visited"];
|
|
85
|
-
const isFunnelEventName = (name) => {
|
|
86
|
-
return FUNNEL_EVENTS.includes(name);
|
|
87
|
-
};
|
|
88
|
-
const isInteractionEventName = (name) => {
|
|
89
|
-
return INTERACTION_EVENTS.includes(name);
|
|
90
|
-
};
|
|
91
|
-
//#endregion
|
|
92
|
-
//#region src/interactions.ts
|
|
93
|
-
const INTERACTIONS_KEY = "firespark:analytics:interactions";
|
|
94
|
-
const interactionKey = (name, entityId) => {
|
|
95
|
-
return `${name}:${entityId}`;
|
|
96
|
-
};
|
|
97
|
-
const parseInteractions = (raw) => {
|
|
98
|
-
if (!raw) return null;
|
|
238
|
+
//#region src/report.ts
|
|
239
|
+
const PREFIX = "[@fire-spark/analytics]";
|
|
240
|
+
const logMasivo = (issue) => {
|
|
99
241
|
try {
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
242
|
+
const opts = {
|
|
243
|
+
alias: "masivo.destination",
|
|
244
|
+
detail: issue.event
|
|
245
|
+
};
|
|
246
|
+
const logged = logError(issue.error ?? issue.message, opts);
|
|
247
|
+
Promise.resolve(logged).catch((failure) => {
|
|
248
|
+
console.error(`${PREFIX} Masivo error was not logged`, failure);
|
|
249
|
+
});
|
|
250
|
+
} catch (failure) {
|
|
251
|
+
console.error(`${PREFIX} Masivo error was not logged`, failure);
|
|
105
252
|
}
|
|
106
253
|
};
|
|
107
|
-
const
|
|
108
|
-
if (!state || state.session_id !== sessionId) return {
|
|
109
|
-
session_id: sessionId,
|
|
110
|
-
keys: []
|
|
111
|
-
};
|
|
112
|
-
return state;
|
|
113
|
-
};
|
|
114
|
-
const shouldSkipInteraction = (state, name, entityId) => {
|
|
115
|
-
if (!isInteractionEventName(name) || !entityId) return false;
|
|
116
|
-
return state.keys.includes(interactionKey(name, entityId));
|
|
117
|
-
};
|
|
118
|
-
const markInteraction = (state, name, entityId) => {
|
|
119
|
-
if (!isInteractionEventName(name) || !entityId) return state;
|
|
120
|
-
const key = interactionKey(name, entityId);
|
|
121
|
-
if (state.keys.includes(key)) return state;
|
|
122
|
-
const keys = [...state.keys, key].slice(-500);
|
|
123
|
-
return {
|
|
124
|
-
...state,
|
|
125
|
-
keys
|
|
126
|
-
};
|
|
127
|
-
};
|
|
128
|
-
//#endregion
|
|
129
|
-
//#region src/queue.ts
|
|
130
|
-
const QUEUE_KEY = "firespark:analytics:queue";
|
|
131
|
-
const parseQueue = (raw) => {
|
|
132
|
-
if (!raw) return [];
|
|
254
|
+
const callHook = (hook, issue) => {
|
|
133
255
|
try {
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
} catch {
|
|
138
|
-
return [];
|
|
139
|
-
}
|
|
140
|
-
};
|
|
141
|
-
const eventAgeMs = (event, now) => {
|
|
142
|
-
const at = Date.parse(event.timestamp);
|
|
143
|
-
if (!Number.isFinite(at)) return Number.POSITIVE_INFINITY;
|
|
144
|
-
return now - at;
|
|
145
|
-
};
|
|
146
|
-
const pruneQueue = (events, now, limits) => {
|
|
147
|
-
let next = events.filter((event) => eventAgeMs(event, now) <= limits.maxAgeMs);
|
|
148
|
-
if (next.length > limits.maxEvents) next = next.slice(next.length - limits.maxEvents);
|
|
149
|
-
while (next.length > 0 && JSON.stringify(next).length > limits.maxBytes) next = next.slice(1);
|
|
150
|
-
return next;
|
|
151
|
-
};
|
|
152
|
-
const enqueueEvent = (events, event, now, limits) => {
|
|
153
|
-
return pruneQueue([...events, event], now, limits);
|
|
154
|
-
};
|
|
155
|
-
//#endregion
|
|
156
|
-
//#region src/runtime.ts
|
|
157
|
-
const CONFIG_KEY = "firespark:analytics:config";
|
|
158
|
-
const DEFAULT_SESSION_MS = 1800 * 1e3;
|
|
159
|
-
const RETRY_MS = 6e4;
|
|
160
|
-
const r1 = {
|
|
161
|
-
options: null,
|
|
162
|
-
context: null
|
|
163
|
-
};
|
|
164
|
-
const r2 = {
|
|
165
|
-
sessionMs: DEFAULT_SESSION_MS,
|
|
166
|
-
session: null
|
|
167
|
-
};
|
|
168
|
-
const r3 = {
|
|
169
|
-
interactions: null,
|
|
170
|
-
queue: []
|
|
171
|
-
};
|
|
172
|
-
const r4 = {
|
|
173
|
-
hydrated: false,
|
|
174
|
-
sessionTimer: null,
|
|
175
|
-
retryTimer: null
|
|
176
|
-
};
|
|
177
|
-
const r5 = { sampleSeen: null };
|
|
178
|
-
const runtime = {
|
|
179
|
-
...r1,
|
|
180
|
-
...r2,
|
|
181
|
-
...r3,
|
|
182
|
-
...r4,
|
|
183
|
-
...r5
|
|
184
|
-
};
|
|
185
|
-
const getLimits = () => {
|
|
186
|
-
const limits = runtime.options?.limits;
|
|
187
|
-
return {
|
|
188
|
-
maxEvents: limits?.maxEvents ?? 500,
|
|
189
|
-
maxAgeMs: limits?.maxAgeMs ?? 6048e5,
|
|
190
|
-
maxBytes: limits?.maxBytes ?? 1e6
|
|
191
|
-
};
|
|
192
|
-
};
|
|
193
|
-
const readStorage = async (key) => {
|
|
194
|
-
const storage = runtime.options?.storage;
|
|
195
|
-
if (!storage) return null;
|
|
196
|
-
return storage.getItem(key);
|
|
197
|
-
};
|
|
198
|
-
const writeStorage = async (key, value) => {
|
|
199
|
-
const storage = runtime.options?.storage;
|
|
200
|
-
if (!storage) return;
|
|
201
|
-
await storage.setItem(key, value);
|
|
202
|
-
};
|
|
203
|
-
const clearStorage = async (key) => {
|
|
204
|
-
const storage = runtime.options?.storage;
|
|
205
|
-
if (!storage) return;
|
|
206
|
-
await storage.removeItem(key);
|
|
207
|
-
};
|
|
208
|
-
const persistSession = async () => {
|
|
209
|
-
const key = "firespark:analytics:session";
|
|
210
|
-
if (!runtime.session) {
|
|
211
|
-
await clearStorage(key);
|
|
212
|
-
return;
|
|
256
|
+
hook(issue);
|
|
257
|
+
} catch (failure) {
|
|
258
|
+
console.error(`${PREFIX} onError/onWarning threw`, failure);
|
|
213
259
|
}
|
|
214
|
-
const p1 = [key, JSON.stringify(runtime.session)];
|
|
215
|
-
await writeStorage(...p1);
|
|
216
|
-
};
|
|
217
|
-
const persistQueue = async () => {
|
|
218
|
-
const p1 = ["firespark:analytics:queue", JSON.stringify(runtime.queue)];
|
|
219
|
-
await writeStorage(...p1);
|
|
220
|
-
};
|
|
221
|
-
const persistConfig = async (sessionMs) => {
|
|
222
|
-
await writeStorage(CONFIG_KEY, JSON.stringify({ session_ms: sessionMs }));
|
|
223
260
|
};
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
261
|
+
/** Never throws: a failing reporter must not break tracking. */
|
|
262
|
+
const report = (rt, issue) => {
|
|
263
|
+
const error = issue.level === "error";
|
|
264
|
+
if (error && issue.provider === "masivo") logMasivo(issue);
|
|
265
|
+
const hook = error ? rt.options?.onError : rt.options?.onWarning;
|
|
266
|
+
if (hook) {
|
|
267
|
+
callHook(hook, issue);
|
|
227
268
|
return;
|
|
228
269
|
}
|
|
229
|
-
const
|
|
230
|
-
|
|
270
|
+
const detail = {
|
|
271
|
+
provider: issue.provider,
|
|
272
|
+
event: issue.event
|
|
273
|
+
};
|
|
274
|
+
const args = [
|
|
275
|
+
`${PREFIX} ${issue.message}`,
|
|
276
|
+
detail,
|
|
277
|
+
issue.error
|
|
278
|
+
];
|
|
279
|
+
if (error) console.error(...args);
|
|
280
|
+
else console.warn(...args);
|
|
231
281
|
};
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
runtime[key] = null;
|
|
236
|
-
};
|
|
237
|
-
const resetRuntime = () => {
|
|
238
|
-
clearTimer("sessionTimer");
|
|
239
|
-
clearTimer("retryTimer");
|
|
240
|
-
runtime.options = null;
|
|
241
|
-
runtime.context = null;
|
|
242
|
-
runtime.sessionMs = DEFAULT_SESSION_MS;
|
|
243
|
-
runtime.session = null;
|
|
244
|
-
runtime.interactions = null;
|
|
245
|
-
runtime.queue = [];
|
|
246
|
-
runtime.hydrated = false;
|
|
247
|
-
runtime.sampleSeen = null;
|
|
282
|
+
const errorMessage = (error) => {
|
|
283
|
+
if (error instanceof Error) return error.message;
|
|
284
|
+
return String(error);
|
|
248
285
|
};
|
|
249
286
|
//#endregion
|
|
250
287
|
//#region ../../packages/constants/src/tracking-plan-catalog/currency.ts
|
|
@@ -256,6 +293,7 @@ const isUsdAmountParam = (name) => {
|
|
|
256
293
|
const dropUsdDeep = (value) => {
|
|
257
294
|
if (Array.isArray(value)) return value.map(dropUsdDeep);
|
|
258
295
|
if (!value || typeof value !== "object") return value;
|
|
296
|
+
if (value instanceof Date) return value;
|
|
259
297
|
const next = {};
|
|
260
298
|
for (const [key, nested] of Object.entries(value)) {
|
|
261
299
|
if (isUsdAmountParam(key)) continue;
|
|
@@ -266,10 +304,11 @@ const dropUsdDeep = (value) => {
|
|
|
266
304
|
const dropUsdAmountParams = (params) => {
|
|
267
305
|
return dropUsdDeep(params);
|
|
268
306
|
};
|
|
269
|
-
/** ISO 4217
|
|
270
|
-
const
|
|
307
|
+
/** Upper-case ISO 4217 code, or `undefined` when `code` is not one. */
|
|
308
|
+
const isoCurrencyCode = (code) => {
|
|
309
|
+
if (typeof code !== "string") return void 0;
|
|
271
310
|
const normalized = code.trim().toUpperCase();
|
|
272
|
-
if (!ISO_4217_CODE.test(normalized))
|
|
311
|
+
if (!ISO_4217_CODE.test(normalized)) return void 0;
|
|
273
312
|
return normalized;
|
|
274
313
|
};
|
|
275
314
|
//#endregion
|
|
@@ -334,6 +373,18 @@ const meta = (web, reactNative) => {
|
|
|
334
373
|
reactNative
|
|
335
374
|
};
|
|
336
375
|
};
|
|
376
|
+
const webOnly = (name) => {
|
|
377
|
+
return {
|
|
378
|
+
web: name,
|
|
379
|
+
reactNative: null
|
|
380
|
+
};
|
|
381
|
+
};
|
|
382
|
+
const nativeOnly = (name) => {
|
|
383
|
+
return {
|
|
384
|
+
web: null,
|
|
385
|
+
reactNative: name
|
|
386
|
+
};
|
|
387
|
+
};
|
|
337
388
|
const ecommerceParams = (valueRequired = true) => {
|
|
338
389
|
return [
|
|
339
390
|
valueParam(valueRequired),
|
|
@@ -473,8 +524,8 @@ const CATALOG_EVENTS = [
|
|
|
473
524
|
runtimes: ["web"],
|
|
474
525
|
recommendedParams: [],
|
|
475
526
|
destinations: {
|
|
476
|
-
"fire-spark":
|
|
477
|
-
ga4:
|
|
527
|
+
"fire-spark": webOnly("page_view"),
|
|
528
|
+
ga4: webOnly("page_view"),
|
|
478
529
|
meta: none(),
|
|
479
530
|
tiktok: none(),
|
|
480
531
|
masivo: none()
|
|
@@ -488,8 +539,8 @@ const CATALOG_EVENTS = [
|
|
|
488
539
|
runtimes: ["react-native"],
|
|
489
540
|
recommendedParams: [],
|
|
490
541
|
destinations: {
|
|
491
|
-
"fire-spark":
|
|
492
|
-
ga4:
|
|
542
|
+
"fire-spark": nativeOnly("screen_view"),
|
|
543
|
+
ga4: nativeOnly("screen_view"),
|
|
493
544
|
meta: none(),
|
|
494
545
|
tiktok: none(),
|
|
495
546
|
masivo: none()
|
|
@@ -595,44 +646,206 @@ const eventsByName = new Map(CATALOG_EVENTS.map((event) => [event.name, event]))
|
|
|
595
646
|
const catalogEventByName = (name) => {
|
|
596
647
|
return eventsByName.get(name);
|
|
597
648
|
};
|
|
649
|
+
/** Catalog ecommerce events carry `value`, `currency` and `items`. */
|
|
650
|
+
const isCatalogEcommerceEvent = (name) => {
|
|
651
|
+
return catalogEventByName(name)?.category === "E-commerce";
|
|
652
|
+
};
|
|
653
|
+
/**
|
|
654
|
+
* Destination name for one runtime, or `null` when the event is not sent
|
|
655
|
+
* there: a `null` binding, or a runtime the catalog does not declare.
|
|
656
|
+
*/
|
|
598
657
|
const destinationEventName = (developerName, provider, runtime) => {
|
|
599
658
|
const event = catalogEventByName(developerName);
|
|
600
659
|
if (!event) return developerName;
|
|
660
|
+
if (!event.runtimes.includes(runtime)) return null;
|
|
601
661
|
const binding = event.destinations[provider];
|
|
602
662
|
if (!binding) return developerName;
|
|
603
663
|
if (runtime === "react-native") return binding.reactNative;
|
|
604
664
|
return binding.web;
|
|
605
665
|
};
|
|
606
666
|
//#endregion
|
|
667
|
+
//#region ../../packages/constants/src/tracking-plan-catalog/masivo.ts
|
|
668
|
+
const MASIVO_ATTRIBUTION_FIELDS = [
|
|
669
|
+
"tracking_id",
|
|
670
|
+
"utm_source",
|
|
671
|
+
"utm_medium",
|
|
672
|
+
"utm_campaign",
|
|
673
|
+
"utm_term",
|
|
674
|
+
"utm_content",
|
|
675
|
+
"utm_referral",
|
|
676
|
+
"gclid",
|
|
677
|
+
"gbraid",
|
|
678
|
+
"wbraid",
|
|
679
|
+
"fbclid",
|
|
680
|
+
"ttclid",
|
|
681
|
+
"fbc",
|
|
682
|
+
"fbp",
|
|
683
|
+
"ttp",
|
|
684
|
+
"event_source_url"
|
|
685
|
+
];
|
|
686
|
+
const MASIVO_PAYMENT_METHODS = [
|
|
687
|
+
"CREDIT",
|
|
688
|
+
"DEBIT",
|
|
689
|
+
"CASH",
|
|
690
|
+
"BANK_TRANSFER",
|
|
691
|
+
"OTHER"
|
|
692
|
+
];
|
|
693
|
+
const PAYMENT_ALIASES = {
|
|
694
|
+
CASH: "CASH",
|
|
695
|
+
BANK_TRANSFER: "BANK_TRANSFER",
|
|
696
|
+
CARD: "OTHER",
|
|
697
|
+
PIN_PAD: "OTHER",
|
|
698
|
+
WALLET: "OTHER",
|
|
699
|
+
FINANCING: "OTHER"
|
|
700
|
+
};
|
|
701
|
+
/** Spark tender method (or a Masivo value) → Masivo `payment_method`. */
|
|
702
|
+
const masivoPaymentMethod = (method) => {
|
|
703
|
+
if (typeof method !== "string") return "OTHER";
|
|
704
|
+
const upper = method.trim().toUpperCase();
|
|
705
|
+
const alias = PAYMENT_ALIASES[upper];
|
|
706
|
+
if (alias) return alias;
|
|
707
|
+
if (MASIVO_PAYMENT_METHODS.includes(upper)) return upper;
|
|
708
|
+
return "OTHER";
|
|
709
|
+
};
|
|
710
|
+
new Set(MASIVO_ATTRIBUTION_FIELDS);
|
|
711
|
+
/** Masivo `type` that carries an order or a single product. */
|
|
712
|
+
const MASIVO_ORDER_TYPES = /* @__PURE__ */ new Set(["PURCHASE"]);
|
|
713
|
+
const MASIVO_PRODUCT_TYPES = /* @__PURE__ */ new Set(["ADD_TO_CART"]);
|
|
714
|
+
//#endregion
|
|
607
715
|
//#region ../../packages/constants/src/tracking-plan-catalog/transforms.ts
|
|
716
|
+
/** Params the SDK hashes for ads and never forwards raw to a destination. */
|
|
717
|
+
const PII_PARAM_NAMES = [
|
|
718
|
+
"phone",
|
|
719
|
+
"device_ip",
|
|
720
|
+
"email",
|
|
721
|
+
"ttclid"
|
|
722
|
+
];
|
|
723
|
+
const PII = new Set(PII_PARAM_NAMES);
|
|
724
|
+
const DECIMAL = /^-?\d+(\.\d+)?$/;
|
|
725
|
+
const isRecord = (value) => {
|
|
726
|
+
return !!value && typeof value === "object" && !Array.isArray(value);
|
|
727
|
+
};
|
|
608
728
|
const stringVal = (value) => {
|
|
609
|
-
|
|
729
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
730
|
+
if (typeof value !== "string") return void 0;
|
|
731
|
+
const trimmed = value.trim();
|
|
732
|
+
return trimmed.length > 0 ? trimmed : void 0;
|
|
733
|
+
};
|
|
734
|
+
const toBig = (value) => {
|
|
735
|
+
if (typeof value === "number" && Number.isFinite(value)) return new Big(value);
|
|
736
|
+
if (typeof value !== "string") return void 0;
|
|
737
|
+
const trimmed = value.trim();
|
|
738
|
+
return DECIMAL.test(trimmed) ? new Big(trimmed) : void 0;
|
|
739
|
+
};
|
|
740
|
+
/** Amounts pass through unrounded; decimal strings become numbers. */
|
|
741
|
+
const amountOf = (value) => {
|
|
742
|
+
return toBig(value)?.toNumber();
|
|
743
|
+
};
|
|
744
|
+
const quantityOf = (value) => {
|
|
745
|
+
const amount = amountOf(value);
|
|
746
|
+
if (amount === void 0 || amount <= 0) return void 0;
|
|
747
|
+
return amount;
|
|
748
|
+
};
|
|
749
|
+
/** Drops `undefined`, `null`, non-finite numbers and functions, deeply. */
|
|
750
|
+
const compact = (value) => {
|
|
751
|
+
if (value === void 0 || value === null) return void 0;
|
|
752
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
753
|
+
if (typeof value === "function" || typeof value === "symbol") return;
|
|
754
|
+
if (Array.isArray(value)) return value.map(compact).filter((item) => item !== void 0);
|
|
755
|
+
if (value instanceof Date) return value.toISOString();
|
|
756
|
+
if (typeof value !== "object") return value;
|
|
757
|
+
const next = {};
|
|
758
|
+
for (const [key, nested] of Object.entries(value)) {
|
|
759
|
+
const kept = compact(nested);
|
|
760
|
+
if (kept !== void 0) next[key] = kept;
|
|
761
|
+
}
|
|
762
|
+
return next;
|
|
610
763
|
};
|
|
611
|
-
const
|
|
612
|
-
|
|
613
|
-
return value;
|
|
764
|
+
const compactPayload$1 = (value) => {
|
|
765
|
+
return compact(value);
|
|
614
766
|
};
|
|
615
|
-
const
|
|
616
|
-
|
|
767
|
+
const nonEmpty = (record) => {
|
|
768
|
+
const kept = compactPayload$1(record);
|
|
769
|
+
return Object.keys(kept).length > 0 ? kept : void 0;
|
|
617
770
|
};
|
|
618
|
-
const
|
|
619
|
-
|
|
771
|
+
const omit = (record, keys) => {
|
|
772
|
+
const drop = new Set(keys);
|
|
773
|
+
const next = {};
|
|
774
|
+
for (const [key, value] of Object.entries(record)) if (!drop.has(key)) next[key] = value;
|
|
775
|
+
return next;
|
|
620
776
|
};
|
|
621
|
-
const
|
|
622
|
-
return
|
|
777
|
+
const itemIdOf = (item) => {
|
|
778
|
+
return stringVal(item.item_id) ?? stringVal(item.content_id) ?? stringVal(item.product_id) ?? stringVal(item.sku);
|
|
623
779
|
};
|
|
624
|
-
const
|
|
780
|
+
const sourceItems = (input) => {
|
|
625
781
|
if (input.items && input.items.length > 0) return input.items;
|
|
626
782
|
const fromParams = input.params.items;
|
|
627
783
|
if (!Array.isArray(fromParams)) return [];
|
|
628
|
-
return fromParams.filter(
|
|
629
|
-
|
|
784
|
+
return fromParams.filter(isRecord);
|
|
785
|
+
};
|
|
786
|
+
/** `product_id` + `quantity` (+ `price`) become one item. */
|
|
787
|
+
const productItem = (params) => {
|
|
788
|
+
const item_id = stringVal(params.product_id);
|
|
789
|
+
if (!item_id) return [];
|
|
790
|
+
return [{
|
|
791
|
+
item_id,
|
|
792
|
+
item_name: params.item_name,
|
|
793
|
+
quantity: params.quantity,
|
|
794
|
+
price: params.price
|
|
795
|
+
}];
|
|
796
|
+
};
|
|
797
|
+
const canonicalItem = (item) => {
|
|
798
|
+
const price = amountOf(item.price ?? item.item_price);
|
|
799
|
+
const quantity = quantityOf(item.quantity);
|
|
800
|
+
const rest = omit(item, ["item_price"]);
|
|
801
|
+
const b1 = {
|
|
802
|
+
item_id: itemIdOf(item),
|
|
803
|
+
price,
|
|
804
|
+
quantity
|
|
805
|
+
};
|
|
806
|
+
return compactPayload$1({
|
|
807
|
+
...rest,
|
|
808
|
+
...b1
|
|
630
809
|
});
|
|
631
810
|
};
|
|
632
|
-
const
|
|
633
|
-
const explicit =
|
|
811
|
+
const ecommerceValue = (params, items) => {
|
|
812
|
+
const explicit = amountOf(params.value);
|
|
634
813
|
if (explicit !== void 0) return explicit;
|
|
635
|
-
|
|
814
|
+
if (items.length === 0) return void 0;
|
|
815
|
+
let total = new Big(0);
|
|
816
|
+
for (const item of items) {
|
|
817
|
+
const price = toBig(item.price);
|
|
818
|
+
if (!price) return void 0;
|
|
819
|
+
const quantity = quantityOf(item.quantity) ?? 1;
|
|
820
|
+
total = total.plus(price.times(quantity));
|
|
821
|
+
}
|
|
822
|
+
return total.toNumber();
|
|
823
|
+
};
|
|
824
|
+
const shapeOf = (input) => {
|
|
825
|
+
const params = input.params;
|
|
826
|
+
const explicitItems = sourceItems(input);
|
|
827
|
+
const hasValue = amountOf(params.value) !== void 0;
|
|
828
|
+
const ecommerce = isCatalogEcommerceEvent(input.name) || explicitItems.length > 0 || hasValue;
|
|
829
|
+
if (!ecommerce) return {
|
|
830
|
+
ecommerce,
|
|
831
|
+
items: []
|
|
832
|
+
};
|
|
833
|
+
const items = (explicitItems.length > 0 ? explicitItems : productItem(params)).map(canonicalItem).filter((item) => {
|
|
834
|
+
return item.item_id !== void 0 || item.item_name !== void 0;
|
|
835
|
+
});
|
|
836
|
+
return {
|
|
837
|
+
ecommerce,
|
|
838
|
+
items,
|
|
839
|
+
value: ecommerceValue(params, items),
|
|
840
|
+
currency: isoCurrencyCode(params.currency) ?? isoCurrencyCode(input.currency)
|
|
841
|
+
};
|
|
842
|
+
};
|
|
843
|
+
const hasMoney = (shape) => {
|
|
844
|
+
if (shape.value !== void 0) return true;
|
|
845
|
+
return shape.items.some((item) => item.price !== void 0);
|
|
846
|
+
};
|
|
847
|
+
const orderIdOf = (params) => {
|
|
848
|
+
return stringVal(params.transaction_id) ?? stringVal(params.order_id);
|
|
636
849
|
};
|
|
637
850
|
/**
|
|
638
851
|
* Delivery-only TikTok names for storefronts already emitting these events.
|
|
@@ -647,123 +860,367 @@ const LEGACY_TIKTOK_ALIASES = {
|
|
|
647
860
|
const resolvedName = (input, provider) => {
|
|
648
861
|
const alias = LEGACY_TIKTOK_ALIASES[input.name];
|
|
649
862
|
if (provider === "tiktok" && alias) return alias;
|
|
650
|
-
return destinationEventName(input.name, provider, input.runtime)
|
|
863
|
+
return destinationEventName(input.name, provider, input.runtime);
|
|
651
864
|
};
|
|
652
|
-
const
|
|
653
|
-
|
|
654
|
-
|
|
865
|
+
const ECOMMERCE_KEYS = [
|
|
866
|
+
"items",
|
|
867
|
+
"value",
|
|
868
|
+
"currency"
|
|
869
|
+
];
|
|
870
|
+
const baseParams = (input, shape) => {
|
|
871
|
+
const drop = [...PII];
|
|
872
|
+
if (shape.ecommerce) drop.push(...ECOMMERCE_KEYS);
|
|
873
|
+
return omit(input.params, drop);
|
|
874
|
+
};
|
|
875
|
+
const ga4Payload = (input, shape) => {
|
|
876
|
+
const base = baseParams(input, shape);
|
|
877
|
+
if (!shape.ecommerce) return compactPayload$1(base);
|
|
878
|
+
const currency = hasMoney(shape) ? shape.currency : void 0;
|
|
879
|
+
const items = shape.items.length > 0 ? shape.items : void 0;
|
|
880
|
+
const transaction_id = orderIdOf(input.params);
|
|
655
881
|
const b1 = {
|
|
656
|
-
items
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
price: itemPrice(item),
|
|
661
|
-
quantity: itemQty(item)
|
|
662
|
-
};
|
|
663
|
-
}),
|
|
664
|
-
value,
|
|
665
|
-
currency
|
|
882
|
+
items,
|
|
883
|
+
value: shape.value,
|
|
884
|
+
currency,
|
|
885
|
+
transaction_id
|
|
666
886
|
};
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
887
|
+
return compactPayload$1({
|
|
888
|
+
...base,
|
|
889
|
+
...b1
|
|
890
|
+
});
|
|
891
|
+
};
|
|
892
|
+
const userDataOf = (input, keys) => {
|
|
893
|
+
const params = input.params;
|
|
894
|
+
const b1 = {
|
|
895
|
+
[keys.email]: params.email,
|
|
896
|
+
[keys.phone]: params.phone
|
|
672
897
|
};
|
|
898
|
+
const external_id = input.identity?.hashedUserId;
|
|
899
|
+
const data = compactPayload$1({
|
|
900
|
+
...b1,
|
|
901
|
+
external_id
|
|
902
|
+
});
|
|
903
|
+
const entries = Object.entries(data).filter(([, value]) => {
|
|
904
|
+
return typeof value === "string" && value.length > 0;
|
|
905
|
+
});
|
|
906
|
+
if (entries.length === 0) return void 0;
|
|
907
|
+
return Object.fromEntries(entries);
|
|
908
|
+
};
|
|
909
|
+
const numItems = (items) => {
|
|
910
|
+
let total = new Big(0);
|
|
911
|
+
for (const item of items) total = total.plus(quantityOf(item.quantity) ?? 1);
|
|
912
|
+
return total.toNumber();
|
|
673
913
|
};
|
|
674
914
|
const metaContents = (items) => {
|
|
675
915
|
return items.map((item) => {
|
|
676
|
-
|
|
677
|
-
id:
|
|
678
|
-
quantity:
|
|
679
|
-
item_price: itemPrice(item)
|
|
916
|
+
const b1 = {
|
|
917
|
+
id: item.item_id,
|
|
918
|
+
quantity: quantityOf(item.quantity) ?? 1
|
|
680
919
|
};
|
|
920
|
+
return compactPayload$1({
|
|
921
|
+
...b1,
|
|
922
|
+
item_price: item.price
|
|
923
|
+
});
|
|
681
924
|
});
|
|
682
925
|
};
|
|
683
|
-
const
|
|
684
|
-
|
|
685
|
-
return
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
926
|
+
const flatValue = (value) => {
|
|
927
|
+
if (typeof value === "string" || typeof value === "number") return value;
|
|
928
|
+
if (typeof value === "boolean") return String(value);
|
|
929
|
+
if (value === void 0 || value === null) return void 0;
|
|
930
|
+
return JSON.stringify(value);
|
|
931
|
+
};
|
|
932
|
+
/** App events params must be strings or numbers. */
|
|
933
|
+
const flatParams = (params) => {
|
|
934
|
+
const next = {};
|
|
935
|
+
for (const [key, value] of Object.entries(compactPayload$1(params))) next[key] = flatValue(value);
|
|
936
|
+
return compactPayload$1(next);
|
|
937
|
+
};
|
|
938
|
+
const metaWebPayload = (input, shape) => {
|
|
939
|
+
const base = baseParams(input, shape);
|
|
940
|
+
if (!shape.ecommerce) return compactPayload$1(base);
|
|
941
|
+
const currency = hasMoney(shape) ? shape.currency : void 0;
|
|
942
|
+
const contents = metaContents(shape.items);
|
|
943
|
+
const listed = contents.length > 0;
|
|
944
|
+
const content_ids = listed ? contents.map((row) => row.id) : void 0;
|
|
945
|
+
const b1 = {
|
|
946
|
+
value: shape.value,
|
|
947
|
+
currency
|
|
948
|
+
};
|
|
949
|
+
const b2 = {
|
|
950
|
+
contents: listed ? contents : void 0,
|
|
951
|
+
content_ids
|
|
689
952
|
};
|
|
953
|
+
const b3 = { content_type: listed ? "product" : void 0 };
|
|
954
|
+
const num_items = listed ? numItems(shape.items) : void 0;
|
|
955
|
+
return compactPayload$1({
|
|
956
|
+
...base,
|
|
957
|
+
...b1,
|
|
958
|
+
...b2,
|
|
959
|
+
...b3,
|
|
960
|
+
num_items
|
|
961
|
+
});
|
|
962
|
+
};
|
|
963
|
+
const metaNativePayload = (input, shape) => {
|
|
964
|
+
const base = baseParams(input, shape);
|
|
965
|
+
if (!shape.ecommerce) return flatParams(base);
|
|
966
|
+
const contents = metaContents(shape.items);
|
|
967
|
+
const listed = contents.length > 0;
|
|
968
|
+
const ids = contents.map((row) => row.id);
|
|
969
|
+
const fb_content_id = ids.length === 1 ? ids[0] : JSON.stringify(ids);
|
|
970
|
+
const b1 = { fb_currency: hasMoney(shape) ? shape.currency : void 0 };
|
|
971
|
+
const b2 = { fb_content: listed ? JSON.stringify(contents) : void 0 };
|
|
972
|
+
const b3 = { fb_content_id: listed ? fb_content_id : void 0 };
|
|
973
|
+
const b4 = { fb_content_type: listed ? "product" : void 0 };
|
|
974
|
+
const b5 = { fb_num_items: listed ? numItems(shape.items) : void 0 };
|
|
975
|
+
const b6 = { fb_order_id: orderIdOf(input.params) };
|
|
976
|
+
return flatParams({
|
|
977
|
+
...base,
|
|
978
|
+
...b1,
|
|
979
|
+
...b2,
|
|
980
|
+
...b3,
|
|
981
|
+
...b4,
|
|
982
|
+
...b5,
|
|
983
|
+
...b6
|
|
984
|
+
});
|
|
690
985
|
};
|
|
691
986
|
const tiktokContents = (items) => {
|
|
692
987
|
return items.map((item) => {
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
quantity:
|
|
696
|
-
price:
|
|
988
|
+
const b1 = { content_id: item.item_id };
|
|
989
|
+
const b2 = {
|
|
990
|
+
quantity: quantityOf(item.quantity) ?? 1,
|
|
991
|
+
price: item.price
|
|
697
992
|
};
|
|
993
|
+
const b3 = { content_name: item.item_name };
|
|
994
|
+
const b4 = { content_category: item.item_category };
|
|
995
|
+
return compactPayload$1({
|
|
996
|
+
...b1,
|
|
997
|
+
...b2,
|
|
998
|
+
...b3,
|
|
999
|
+
...b4
|
|
1000
|
+
});
|
|
698
1001
|
});
|
|
699
1002
|
};
|
|
700
|
-
const tiktokPayload = (input,
|
|
701
|
-
const
|
|
702
|
-
|
|
703
|
-
const
|
|
1003
|
+
const tiktokPayload = (input, shape) => {
|
|
1004
|
+
const base = baseParams(input, shape);
|
|
1005
|
+
if (!shape.ecommerce) return compactPayload$1(base);
|
|
1006
|
+
const currency = hasMoney(shape) ? shape.currency : void 0;
|
|
1007
|
+
const contents = tiktokContents(shape.items);
|
|
1008
|
+
const listed = contents.length > 0;
|
|
1009
|
+
const firstId = contents.length === 1 ? contents[0]?.content_id : void 0;
|
|
1010
|
+
const content_id = stringVal(input.params.content_id) ?? firstId;
|
|
704
1011
|
const b1 = {
|
|
705
|
-
value:
|
|
1012
|
+
value: shape.value,
|
|
706
1013
|
currency
|
|
707
1014
|
};
|
|
708
|
-
const b2 = {
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
description: params.description,
|
|
712
|
-
order_id: params.order_id
|
|
1015
|
+
const b2 = {
|
|
1016
|
+
contents: listed ? contents : void 0,
|
|
1017
|
+
content_id
|
|
713
1018
|
};
|
|
714
|
-
const
|
|
715
|
-
const
|
|
1019
|
+
const b3 = { content_type: listed ? "product" : void 0 };
|
|
1020
|
+
const b4 = { order_id: orderIdOf(input.params) };
|
|
1021
|
+
return compactPayload$1({
|
|
1022
|
+
...base,
|
|
716
1023
|
...b1,
|
|
717
1024
|
...b2,
|
|
718
1025
|
...b3,
|
|
719
|
-
...b4
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
1026
|
+
...b4
|
|
1027
|
+
});
|
|
1028
|
+
};
|
|
1029
|
+
const MASIVO_ITEM_FIELDS = [
|
|
1030
|
+
"item_id",
|
|
1031
|
+
"price",
|
|
1032
|
+
"quantity",
|
|
1033
|
+
"discount"
|
|
1034
|
+
];
|
|
1035
|
+
/** Masivo product: `value` is the line total (unit price × amount). */
|
|
1036
|
+
const masivoProduct = (item) => {
|
|
1037
|
+
const sku = stringVal(item.item_id);
|
|
1038
|
+
const price = toBig(item.price);
|
|
1039
|
+
if (!sku || !price) return void 0;
|
|
1040
|
+
const amount = quantityOf(item.quantity) ?? 1;
|
|
1041
|
+
const value = price.times(amount).toNumber();
|
|
1042
|
+
const discount = toBig(item.discount);
|
|
1043
|
+
const discounted = discount ? price.minus(discount).times(amount) : null;
|
|
1044
|
+
const discounted_value = discounted?.gte(0) ? discounted.toNumber() : null;
|
|
1045
|
+
const metadata = nonEmpty(omit(item, MASIVO_ITEM_FIELDS));
|
|
1046
|
+
return compactPayload$1({
|
|
1047
|
+
sku,
|
|
1048
|
+
amount,
|
|
1049
|
+
value,
|
|
1050
|
+
discounted_value,
|
|
1051
|
+
metadata
|
|
1052
|
+
});
|
|
1053
|
+
};
|
|
1054
|
+
const masivoProducts = (items) => {
|
|
1055
|
+
return items.flatMap((item) => {
|
|
1056
|
+
const product = masivoProduct(item);
|
|
1057
|
+
return product ? [product] : [];
|
|
1058
|
+
});
|
|
1059
|
+
};
|
|
1060
|
+
const ORDER_PARAMS = [
|
|
1061
|
+
"order_id",
|
|
1062
|
+
"transaction_id",
|
|
1063
|
+
"payment_method",
|
|
1064
|
+
"payment_type",
|
|
1065
|
+
"discounted_value",
|
|
1066
|
+
"shipping",
|
|
1067
|
+
"store_id",
|
|
1068
|
+
"channel_id",
|
|
1069
|
+
"product_id",
|
|
1070
|
+
"quantity",
|
|
1071
|
+
"price",
|
|
1072
|
+
...ECOMMERCE_KEYS
|
|
1073
|
+
];
|
|
1074
|
+
const PRODUCT_PARAMS = [
|
|
1075
|
+
"product_id",
|
|
1076
|
+
"quantity",
|
|
1077
|
+
"price",
|
|
1078
|
+
"discounted_value",
|
|
1079
|
+
...ECOMMERCE_KEYS
|
|
1080
|
+
];
|
|
1081
|
+
const masivoOrder = (input, shape) => {
|
|
1082
|
+
const params = input.params;
|
|
1083
|
+
const identity = input.identity ?? {};
|
|
1084
|
+
const purchase_id = orderIdOf(params);
|
|
1085
|
+
const products = masivoProducts(shape.items);
|
|
1086
|
+
if (!purchase_id || shape.value === void 0) return void 0;
|
|
1087
|
+
if (products.length === 0) return void 0;
|
|
1088
|
+
const payment_method = masivoPaymentMethod(params.payment_method ?? params.payment_type);
|
|
1089
|
+
const store_id = stringVal(params.store_id) ?? identity.storeId;
|
|
1090
|
+
const channel_id = stringVal(params.channel_id) ?? identity.channelId;
|
|
1091
|
+
const shipping = nonEmpty({ value: amountOf(params.shipping) });
|
|
1092
|
+
const b1 = {
|
|
1093
|
+
purchase_id,
|
|
1094
|
+
value: shape.value,
|
|
1095
|
+
products,
|
|
1096
|
+
payment_method
|
|
725
1097
|
};
|
|
726
|
-
const
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
1098
|
+
const b2 = {
|
|
1099
|
+
store_id,
|
|
1100
|
+
channel_id,
|
|
1101
|
+
shipping
|
|
730
1102
|
};
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
...
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
};
|
|
737
|
-
};
|
|
738
|
-
const masivoPayload = (input, items) => {
|
|
739
|
-
const currency = merchantCurrencyCode(input.currency);
|
|
740
|
-
const ctx = input.context ?? {};
|
|
741
|
-
const products = items.map((item) => {
|
|
742
|
-
const metadata = { prices: {
|
|
743
|
-
net_price: itemPrice(item),
|
|
744
|
-
currency
|
|
745
|
-
} };
|
|
746
|
-
return {
|
|
747
|
-
id: itemId(item),
|
|
748
|
-
quantity: itemQty(item),
|
|
749
|
-
metadata
|
|
750
|
-
};
|
|
1103
|
+
const b3 = { discounted_value: amountOf(params.discounted_value) };
|
|
1104
|
+
return compactPayload$1({
|
|
1105
|
+
...b1,
|
|
1106
|
+
...b2,
|
|
1107
|
+
...b3
|
|
751
1108
|
});
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
1109
|
+
};
|
|
1110
|
+
const masivoProductOf = (input, shape) => {
|
|
1111
|
+
const first = shape.items[0];
|
|
1112
|
+
if (!first) return void 0;
|
|
1113
|
+
const product = masivoProduct(first);
|
|
1114
|
+
if (!product) return void 0;
|
|
1115
|
+
const discounted = amountOf(input.params.discounted_value);
|
|
1116
|
+
if (discounted === void 0) return product;
|
|
1117
|
+
return {
|
|
1118
|
+
...product,
|
|
1119
|
+
discounted_value: discounted
|
|
756
1120
|
};
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
1121
|
+
};
|
|
1122
|
+
const ATTRIBUTION = new Set(MASIVO_ATTRIBUTION_FIELDS);
|
|
1123
|
+
const isIso = (value) => {
|
|
1124
|
+
return typeof value === "string" && !Number.isNaN(Date.parse(value));
|
|
1125
|
+
};
|
|
1126
|
+
const masivoTopLevel = (params) => {
|
|
1127
|
+
const body = {};
|
|
1128
|
+
const used = [];
|
|
1129
|
+
const take = (key, ok) => {
|
|
1130
|
+
if (!ok) return;
|
|
1131
|
+
body[key] = params[key];
|
|
1132
|
+
used.push(key);
|
|
760
1133
|
};
|
|
1134
|
+
take("fulfilled", typeof params.fulfilled === "boolean");
|
|
1135
|
+
take("reserve", Number.isInteger(params.reserve));
|
|
1136
|
+
take("referral_code", !!stringVal(params.referral_code));
|
|
1137
|
+
take("redeem", Array.isArray(params.redeem));
|
|
1138
|
+
take("tags", isRecord(params.tags));
|
|
1139
|
+
take("ga4", isRecord(params.ga4));
|
|
1140
|
+
take("issued_at", isIso(params.issued_at));
|
|
761
1141
|
return {
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
1142
|
+
body,
|
|
1143
|
+
used
|
|
1144
|
+
};
|
|
1145
|
+
};
|
|
1146
|
+
const masivoAttribution = (params) => {
|
|
1147
|
+
const next = { ...isRecord(params.attribution) ? params.attribution : {} };
|
|
1148
|
+
for (const [key, value] of Object.entries(params)) if (ATTRIBUTION.has(key)) next[key] = value;
|
|
1149
|
+
return nonEmpty(next);
|
|
1150
|
+
};
|
|
1151
|
+
/**
|
|
1152
|
+
* Masivo "Emit event" body. Documented fields go top-level (or inside
|
|
1153
|
+
* `order` / `product`); every other param goes to `metadata`.
|
|
1154
|
+
*/
|
|
1155
|
+
const masivoPayload = (input, shape, type) => {
|
|
1156
|
+
const params = input.params;
|
|
1157
|
+
const identity = input.identity ?? {};
|
|
1158
|
+
const raw = PII_PARAM_NAMES.filter((key) => key !== "ttclid");
|
|
1159
|
+
const fixed = [
|
|
1160
|
+
"metadata",
|
|
1161
|
+
"attribution",
|
|
1162
|
+
...[
|
|
1163
|
+
"customer_id",
|
|
1164
|
+
"brand_id",
|
|
1165
|
+
"platform"
|
|
1166
|
+
],
|
|
1167
|
+
...raw
|
|
1168
|
+
];
|
|
1169
|
+
const used = /* @__PURE__ */ new Set([...fixed, ...ATTRIBUTION]);
|
|
1170
|
+
const customer_id = stringVal(params.customer_id) ?? identity.customerId;
|
|
1171
|
+
const brand_id = stringVal(params.brand_id) ?? identity.brandId;
|
|
1172
|
+
const platform = stringVal(params.platform) ?? identity.platform;
|
|
1173
|
+
const at = (/* @__PURE__ */ new Date(input.eventTime * 1e3)).toISOString();
|
|
1174
|
+
const top = masivoTopLevel(params);
|
|
1175
|
+
for (const key of top.used) used.add(key);
|
|
1176
|
+
const body = {
|
|
1177
|
+
customer_id,
|
|
1178
|
+
brand_id,
|
|
1179
|
+
type
|
|
1180
|
+
};
|
|
1181
|
+
Object.assign(body, {
|
|
1182
|
+
platform,
|
|
1183
|
+
issued_at: at
|
|
1184
|
+
}, top.body);
|
|
1185
|
+
if (MASIVO_ORDER_TYPES.has(type)) {
|
|
1186
|
+
const order = masivoOrder(input, shape);
|
|
1187
|
+
if (order) {
|
|
1188
|
+
body.order = order;
|
|
1189
|
+
for (const key of ORDER_PARAMS) used.add(key);
|
|
1190
|
+
}
|
|
1191
|
+
}
|
|
1192
|
+
if (MASIVO_PRODUCT_TYPES.has(type)) {
|
|
1193
|
+
const product = masivoProductOf(input, shape);
|
|
1194
|
+
if (product) {
|
|
1195
|
+
body.product = product;
|
|
1196
|
+
for (const key of PRODUCT_PARAMS) used.add(key);
|
|
1197
|
+
}
|
|
1198
|
+
}
|
|
1199
|
+
body.attribution = masivoAttribution(params);
|
|
1200
|
+
if (shape.ecommerce) used.add("currency");
|
|
1201
|
+
const extra = isRecord(params.metadata) ? params.metadata : {};
|
|
1202
|
+
const rest = omit(params, used);
|
|
1203
|
+
const currency = hasMoney(shape) ? shape.currency : void 0;
|
|
1204
|
+
const b1 = {
|
|
1205
|
+
store_id: identity.storeId,
|
|
1206
|
+
channel_id: identity.channelId
|
|
1207
|
+
};
|
|
1208
|
+
const b2 = {
|
|
1209
|
+
fulfillment_id: identity.fulfillmentId,
|
|
1210
|
+
currency
|
|
765
1211
|
};
|
|
1212
|
+
body.metadata = nonEmpty({
|
|
1213
|
+
...b1,
|
|
1214
|
+
...b2,
|
|
1215
|
+
...rest,
|
|
1216
|
+
...extra
|
|
1217
|
+
});
|
|
1218
|
+
return compactPayload$1(body);
|
|
766
1219
|
};
|
|
1220
|
+
/**
|
|
1221
|
+
* Builds one destination payload from a tracked event. Returns `null` when
|
|
1222
|
+
* the catalog does not send this event to `provider` in this runtime.
|
|
1223
|
+
*/
|
|
767
1224
|
const transformForProvider = (provider, input) => {
|
|
768
1225
|
const params = dropUsdAmountParams(input.params);
|
|
769
1226
|
const itemsIn = input.items?.map((item) => dropUsdAmountParams(item));
|
|
@@ -772,93 +1229,124 @@ const transformForProvider = (provider, input) => {
|
|
|
772
1229
|
params,
|
|
773
1230
|
items: itemsIn
|
|
774
1231
|
};
|
|
775
|
-
const items = itemsOf$1(next);
|
|
776
1232
|
const name = resolvedName(next, provider);
|
|
777
|
-
if (
|
|
778
|
-
|
|
779
|
-
name,
|
|
780
|
-
payload: ga4Payload(next, items)
|
|
781
|
-
};
|
|
782
|
-
if (provider === "meta") return {
|
|
1233
|
+
if (name === null) return null;
|
|
1234
|
+
if (provider === "fire-spark") return {
|
|
783
1235
|
provider,
|
|
784
1236
|
name,
|
|
785
|
-
payload:
|
|
1237
|
+
payload: compactPayload$1(params)
|
|
786
1238
|
};
|
|
787
|
-
|
|
1239
|
+
const shape = shapeOf(next);
|
|
1240
|
+
if (provider === "ga4") return {
|
|
788
1241
|
provider,
|
|
789
1242
|
name,
|
|
790
|
-
payload:
|
|
1243
|
+
payload: ga4Payload(next, shape)
|
|
791
1244
|
};
|
|
792
|
-
if (provider === "
|
|
1245
|
+
if (provider === "meta") {
|
|
1246
|
+
const userData = userDataOf(next, {
|
|
1247
|
+
email: "em",
|
|
1248
|
+
phone: "ph"
|
|
1249
|
+
});
|
|
1250
|
+
if (next.runtime === "web") return {
|
|
1251
|
+
provider,
|
|
1252
|
+
name,
|
|
1253
|
+
payload: metaWebPayload(next, shape),
|
|
1254
|
+
userData
|
|
1255
|
+
};
|
|
1256
|
+
return {
|
|
1257
|
+
provider,
|
|
1258
|
+
name,
|
|
1259
|
+
payload: metaNativePayload(next, shape),
|
|
1260
|
+
userData,
|
|
1261
|
+
valueToSum: shape.value
|
|
1262
|
+
};
|
|
1263
|
+
}
|
|
1264
|
+
if (provider === "tiktok") {
|
|
1265
|
+
const userData = userDataOf(next, {
|
|
1266
|
+
email: "email",
|
|
1267
|
+
phone: "phone_number"
|
|
1268
|
+
});
|
|
1269
|
+
return {
|
|
1270
|
+
provider,
|
|
1271
|
+
name,
|
|
1272
|
+
payload: tiktokPayload(next, shape),
|
|
1273
|
+
userData
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
return {
|
|
793
1277
|
provider,
|
|
794
1278
|
name,
|
|
795
|
-
payload: masivoPayload(next,
|
|
1279
|
+
payload: masivoPayload(next, shape, name)
|
|
796
1280
|
};
|
|
797
|
-
return {
|
|
798
|
-
provider,
|
|
799
|
-
name,
|
|
800
|
-
payload: next.params
|
|
801
|
-
};
|
|
802
|
-
};
|
|
803
|
-
//#endregion
|
|
804
|
-
//#region src/uuid.ts
|
|
805
|
-
/** UUID v4 — works when `crypto.randomUUID` is missing (React Native / Hermes). */
|
|
806
|
-
const randomUUID = () => {
|
|
807
|
-
const c = globalThis.crypto;
|
|
808
|
-
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
809
|
-
if (typeof c?.getRandomValues !== "function") throw new Error("crypto.getRandomValues is required");
|
|
810
|
-
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
811
|
-
c.getRandomValues(bytes);
|
|
812
|
-
bytes[6] = bytes[6] & 15 | 64;
|
|
813
|
-
bytes[8] = bytes[8] & 63 | 128;
|
|
814
|
-
const toHex = (b) => b.toString(16).padStart(2, "0");
|
|
815
|
-
const hex = Array.from(bytes, toHex).join("");
|
|
816
|
-
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
817
1281
|
};
|
|
818
1282
|
//#endregion
|
|
819
1283
|
//#region src/fanout.ts
|
|
820
1284
|
const ADS_PROVIDERS = /* @__PURE__ */ new Set(["meta", "tiktok"]);
|
|
1285
|
+
/** Masivo `platform` for every Fire Spark event (same as the API). */
|
|
1286
|
+
const MASIVO_PLATFORM = "firespark";
|
|
821
1287
|
const DEFAULT_CONSENT = {
|
|
822
1288
|
analytics: true,
|
|
823
1289
|
ads: true
|
|
824
1290
|
};
|
|
1291
|
+
const isAdsProvider = (provider) => {
|
|
1292
|
+
return ADS_PROVIDERS.has(provider);
|
|
1293
|
+
};
|
|
825
1294
|
const resolveRuntime = (options) => {
|
|
826
1295
|
if (options.runtime) return options.runtime;
|
|
827
1296
|
return options.platform === "web" ? "web" : "react-native";
|
|
828
1297
|
};
|
|
1298
|
+
const resolveConsent = (rt) => {
|
|
1299
|
+
if (rt.consent) return rt.consent;
|
|
1300
|
+
return rt.options?.consent?.() ?? DEFAULT_CONSENT;
|
|
1301
|
+
};
|
|
1302
|
+
const allowed = (provider, consent) => {
|
|
1303
|
+
return isAdsProvider(provider) ? consent.ads : consent.analytics;
|
|
1304
|
+
};
|
|
1305
|
+
/**
|
|
1306
|
+
* `setUser()` wins; otherwise a signed-in (non-anonymous) customer is the
|
|
1307
|
+
* user. Anonymous customers are not sent as a user id.
|
|
1308
|
+
*/
|
|
1309
|
+
const resolveUser = (rt) => {
|
|
1310
|
+
if (rt.user) return rt.user;
|
|
1311
|
+
const customer = rt.options?.getCustomer();
|
|
1312
|
+
if (!customer || customer.is_anonymous) return null;
|
|
1313
|
+
return { id: customer.id };
|
|
1314
|
+
};
|
|
829
1315
|
const resolveMerchantContext = (options) => {
|
|
830
1316
|
if (options.merchantContext) return options.merchantContext();
|
|
831
1317
|
if (typeof options.context === "function") return options.context();
|
|
832
1318
|
return { ...options.getScope?.() ?? {} };
|
|
833
1319
|
};
|
|
834
|
-
const resolveAdapters = (opts) => {
|
|
835
|
-
const constructed =
|
|
1320
|
+
const resolveAdapters = (rt, opts) => {
|
|
1321
|
+
const constructed = rt.options?.adapters ?? [];
|
|
836
1322
|
const extra = opts?.extra ?? [];
|
|
837
1323
|
const available = [...constructed, ...extra];
|
|
838
1324
|
if (opts?.only) {
|
|
839
|
-
for (const id of opts.only)
|
|
1325
|
+
for (const id of opts.only) {
|
|
1326
|
+
if (available.some((adapter) => adapter.provider === id)) continue;
|
|
1327
|
+
report(rt, {
|
|
1328
|
+
level: "warning",
|
|
1329
|
+
source: "track",
|
|
1330
|
+
message: `Adapter ${id} was never constructed; skipped`,
|
|
1331
|
+
provider: id
|
|
1332
|
+
});
|
|
1333
|
+
}
|
|
840
1334
|
return available.filter((adapter) => opts.only?.includes(adapter.provider));
|
|
841
1335
|
}
|
|
842
1336
|
if (!opts?.exclude) return available;
|
|
843
1337
|
return available.filter((adapter) => !opts.exclude?.includes(adapter.provider));
|
|
844
1338
|
};
|
|
845
|
-
const
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
detail: name
|
|
855
|
-
});
|
|
856
|
-
Promise.resolve(logged).catch((logFailure) => {
|
|
857
|
-
console.error("Masivo destination error was not logged", logFailure);
|
|
1339
|
+
const hashFn = (rt) => rt.options?.hash ?? defaultHash;
|
|
1340
|
+
const hashFailure = (rt, name) => {
|
|
1341
|
+
return (key, error) => {
|
|
1342
|
+
report(rt, {
|
|
1343
|
+
level: "warning",
|
|
1344
|
+
source: "hash",
|
|
1345
|
+
message: `Could not hash "${key}"; it was not sent`,
|
|
1346
|
+
error,
|
|
1347
|
+
event: name
|
|
858
1348
|
});
|
|
859
|
-
}
|
|
860
|
-
console.error("Masivo destination error was not logged", logFailure);
|
|
861
|
-
}
|
|
1349
|
+
};
|
|
862
1350
|
};
|
|
863
1351
|
const itemsOf = (params) => {
|
|
864
1352
|
if (!Array.isArray(params.items)) return void 0;
|
|
@@ -866,73 +1354,174 @@ const itemsOf = (params) => {
|
|
|
866
1354
|
return !!row && typeof row === "object" && !Array.isArray(row);
|
|
867
1355
|
});
|
|
868
1356
|
};
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
if (
|
|
872
|
-
if (!
|
|
873
|
-
|
|
874
|
-
|
|
1357
|
+
/** SHA-256 of the user id for ads providers; `null` clears it. */
|
|
1358
|
+
const userFor = async (rt, provider, user) => {
|
|
1359
|
+
if (!user) return void 0;
|
|
1360
|
+
if (!isAdsProvider(provider)) return user;
|
|
1361
|
+
if (typeof user.id !== "string") return { id: user.id };
|
|
1362
|
+
return { id: await hashPiiValue(user.id, hashFn(rt)) };
|
|
1363
|
+
};
|
|
1364
|
+
const identityOf = (rt, hashedUserId) => {
|
|
1365
|
+
const options = rt.options;
|
|
1366
|
+
const scope = options?.getScope?.() ?? {};
|
|
1367
|
+
const i1 = {
|
|
1368
|
+
customerId: options?.getCustomer()?.id,
|
|
1369
|
+
hashedUserId,
|
|
1370
|
+
brandId: scope.brand_id
|
|
1371
|
+
};
|
|
1372
|
+
const channelId = options?.channel_id ?? scope.channel_id;
|
|
1373
|
+
const i2 = {
|
|
1374
|
+
storeId: scope.store_id,
|
|
1375
|
+
channelId
|
|
1376
|
+
};
|
|
1377
|
+
const i3 = {
|
|
1378
|
+
fulfillmentId: scope.fulfillment_id,
|
|
1379
|
+
platform: MASIVO_PLATFORM
|
|
1380
|
+
};
|
|
1381
|
+
return {
|
|
1382
|
+
...i1,
|
|
1383
|
+
...i2,
|
|
1384
|
+
...i3
|
|
1385
|
+
};
|
|
1386
|
+
};
|
|
1387
|
+
const sendOne = async (adapter, item, ctx) => {
|
|
1388
|
+
const { rt, consent } = ctx;
|
|
1389
|
+
if (!allowed(adapter.provider, consent)) return;
|
|
1390
|
+
const ads = isAdsProvider(adapter.provider);
|
|
1391
|
+
const raw = item.event.properties ?? {};
|
|
1392
|
+
const hash = hashFn(rt);
|
|
1393
|
+
const onFailure = hashFailure(rt, item.event.name);
|
|
1394
|
+
const params = ads ? await hashPiiParams(raw, hash, onFailure) : raw;
|
|
875
1395
|
const rows = itemsOf(params);
|
|
876
|
-
const
|
|
1396
|
+
const hashRow = (row) => {
|
|
1397
|
+
return hashPiiParams(row, hash, onFailure);
|
|
1398
|
+
};
|
|
1399
|
+
const items = ads && rows ? await Promise.all(rows.map(hashRow)) : rows;
|
|
1400
|
+
const user = await userFor(rt, adapter.provider, ctx.user);
|
|
1401
|
+
const hashedUserId = ads && user?.id ? user.id : void 0;
|
|
877
1402
|
const b1 = {
|
|
878
|
-
name: event.name,
|
|
1403
|
+
name: item.event.name,
|
|
879
1404
|
params,
|
|
880
1405
|
items,
|
|
881
|
-
currency
|
|
1406
|
+
currency: rt.currency
|
|
882
1407
|
};
|
|
883
1408
|
const b2 = {
|
|
884
|
-
runtime:
|
|
885
|
-
eventId:
|
|
1409
|
+
runtime: ctx.runtime,
|
|
1410
|
+
eventId: item.eventId
|
|
886
1411
|
};
|
|
887
1412
|
const b3 = {
|
|
888
|
-
eventTime: Math.floor(
|
|
889
|
-
context
|
|
1413
|
+
eventTime: Math.floor(item.at / 1e3),
|
|
1414
|
+
context: ctx.context
|
|
890
1415
|
};
|
|
1416
|
+
const b4 = { identity: identityOf(rt, hashedUserId) };
|
|
891
1417
|
const input = {
|
|
892
1418
|
...b1,
|
|
893
1419
|
...b2,
|
|
894
|
-
...b3
|
|
1420
|
+
...b3,
|
|
1421
|
+
...b4
|
|
895
1422
|
};
|
|
896
1423
|
const transformed = transformForProvider(adapter.provider, input);
|
|
1424
|
+
if (!transformed) return;
|
|
897
1425
|
const n1 = {
|
|
898
1426
|
name: transformed.name,
|
|
899
1427
|
params: transformed.payload
|
|
900
1428
|
};
|
|
901
1429
|
const n2 = {
|
|
902
1430
|
items,
|
|
903
|
-
context,
|
|
904
|
-
runtime:
|
|
1431
|
+
context: ctx.context,
|
|
1432
|
+
runtime: ctx.runtime,
|
|
905
1433
|
consent
|
|
906
1434
|
};
|
|
1435
|
+
const n3 = {
|
|
1436
|
+
eventId: item.eventId,
|
|
1437
|
+
userData: transformed.userData
|
|
1438
|
+
};
|
|
1439
|
+
const n4 = {
|
|
1440
|
+
valueToSum: transformed.valueToSum,
|
|
1441
|
+
user
|
|
1442
|
+
};
|
|
1443
|
+
const n5 = { userProperties: user?.properties ?? void 0 };
|
|
907
1444
|
const normalized = {
|
|
908
1445
|
...n1,
|
|
909
|
-
...n2
|
|
1446
|
+
...n2,
|
|
1447
|
+
...n3,
|
|
1448
|
+
...n4,
|
|
1449
|
+
...n5
|
|
910
1450
|
};
|
|
911
1451
|
await adapter.send(normalized);
|
|
912
1452
|
};
|
|
913
|
-
const
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
1453
|
+
const destinationError = (rt, provider, name, error) => {
|
|
1454
|
+
report(rt, {
|
|
1455
|
+
level: "error",
|
|
1456
|
+
source: "destination",
|
|
1457
|
+
message: `${provider} destination failed: ${errorMessage(error)}`,
|
|
1458
|
+
error,
|
|
1459
|
+
provider,
|
|
1460
|
+
event: name
|
|
1461
|
+
});
|
|
1462
|
+
};
|
|
1463
|
+
const fanoutAdapters = async (rt, item, opts) => {
|
|
1464
|
+
const options = rt.options;
|
|
917
1465
|
if (!options) return;
|
|
918
|
-
const
|
|
919
|
-
|
|
920
|
-
const
|
|
921
|
-
|
|
1466
|
+
const adapters = resolveAdapters(rt, opts);
|
|
1467
|
+
if (adapters.length === 0) return;
|
|
1468
|
+
const c1 = {
|
|
1469
|
+
rt,
|
|
1470
|
+
consent: resolveConsent(rt)
|
|
1471
|
+
};
|
|
1472
|
+
const c2 = { runtime: resolveRuntime(options) };
|
|
1473
|
+
const c3 = {
|
|
1474
|
+
context: resolveMerchantContext(options),
|
|
1475
|
+
user: resolveUser(rt)
|
|
1476
|
+
};
|
|
1477
|
+
const ctx = {
|
|
1478
|
+
...c1,
|
|
1479
|
+
...c2,
|
|
1480
|
+
...c3
|
|
1481
|
+
};
|
|
922
1482
|
const send = async (adapter) => {
|
|
923
1483
|
try {
|
|
924
|
-
await sendOne(
|
|
925
|
-
adapter,
|
|
926
|
-
event,
|
|
927
|
-
consent,
|
|
928
|
-
runtimeId
|
|
929
|
-
], currency, context);
|
|
1484
|
+
await sendOne(adapter, item, ctx);
|
|
930
1485
|
} catch (error) {
|
|
931
|
-
|
|
1486
|
+
destinationError(rt, adapter.provider, item.event.name, error);
|
|
932
1487
|
}
|
|
933
1488
|
};
|
|
934
1489
|
await Promise.all(adapters.map(send));
|
|
935
1490
|
};
|
|
1491
|
+
/** Pushes the current user to adapters that implement `setUser`. */
|
|
1492
|
+
const pushUser = async (rt) => {
|
|
1493
|
+
const options = rt.options;
|
|
1494
|
+
if (!options) return;
|
|
1495
|
+
const runtimeId = resolveRuntime(options);
|
|
1496
|
+
const consent = resolveConsent(rt);
|
|
1497
|
+
const user = resolveUser(rt) ?? { id: null };
|
|
1498
|
+
const push = async (adapter) => {
|
|
1499
|
+
if (!adapter.setUser || !allowed(adapter.provider, consent)) return;
|
|
1500
|
+
try {
|
|
1501
|
+
const target = await userFor(rt, adapter.provider, user);
|
|
1502
|
+
await adapter.setUser(target ?? { id: null }, runtimeId);
|
|
1503
|
+
} catch (error) {
|
|
1504
|
+
destinationError(rt, adapter.provider, "set_user", error);
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
await Promise.all((options.adapters ?? []).map(push));
|
|
1508
|
+
};
|
|
1509
|
+
/** Pushes consent to every adapter, including revocations. */
|
|
1510
|
+
const pushConsent = async (rt) => {
|
|
1511
|
+
const options = rt.options;
|
|
1512
|
+
if (!options) return;
|
|
1513
|
+
const runtimeId = resolveRuntime(options);
|
|
1514
|
+
const consent = resolveConsent(rt);
|
|
1515
|
+
const push = async (adapter) => {
|
|
1516
|
+
if (!adapter.setConsent) return;
|
|
1517
|
+
try {
|
|
1518
|
+
await adapter.setConsent(consent, runtimeId);
|
|
1519
|
+
} catch (error) {
|
|
1520
|
+
destinationError(rt, adapter.provider, "set_consent", error);
|
|
1521
|
+
}
|
|
1522
|
+
};
|
|
1523
|
+
await Promise.all((options.adapters ?? []).map(push));
|
|
1524
|
+
};
|
|
936
1525
|
//#endregion
|
|
937
1526
|
//#region src/retry.ts
|
|
938
1527
|
const defaultSleep = (ms) => {
|
|
@@ -957,8 +1546,155 @@ const withExponentialRetry = async (run, options = {}) => {
|
|
|
957
1546
|
}
|
|
958
1547
|
throw lastError;
|
|
959
1548
|
};
|
|
960
|
-
|
|
961
|
-
|
|
1549
|
+
/** `is_anonymous` may be missing: it is resolved when the queue is sent. */
|
|
1550
|
+
const parseQueue = (raw) => {
|
|
1551
|
+
if (!raw) return [];
|
|
1552
|
+
try {
|
|
1553
|
+
const parsed = JSON.parse(raw);
|
|
1554
|
+
if (!Array.isArray(parsed)) return [];
|
|
1555
|
+
return parsed.filter((item) => item?.id && item.name && item.session_id);
|
|
1556
|
+
} catch {
|
|
1557
|
+
return [];
|
|
1558
|
+
}
|
|
1559
|
+
};
|
|
1560
|
+
const eventAgeMs = (event, now) => {
|
|
1561
|
+
const at = Date.parse(event.timestamp);
|
|
1562
|
+
if (!Number.isFinite(at)) return Number.POSITIVE_INFINITY;
|
|
1563
|
+
return now - at;
|
|
1564
|
+
};
|
|
1565
|
+
/** Length of `JSON.stringify(events)`, computed per event. */
|
|
1566
|
+
const serializedSizes = (events) => {
|
|
1567
|
+
return events.map((event) => JSON.stringify(event).length);
|
|
1568
|
+
};
|
|
1569
|
+
/**
|
|
1570
|
+
* Drops expired events, then the oldest ones until the queue fits
|
|
1571
|
+
* `maxEvents` and `maxBytes`. Each event is serialized once, so the cost
|
|
1572
|
+
* stays linear in the queue size.
|
|
1573
|
+
*/
|
|
1574
|
+
const pruneQueue = (events, now, limits) => {
|
|
1575
|
+
let next = events.filter((event) => eventAgeMs(event, now) <= limits.maxAgeMs);
|
|
1576
|
+
if (next.length > limits.maxEvents) next = next.slice(next.length - limits.maxEvents);
|
|
1577
|
+
const sizes = serializedSizes(next);
|
|
1578
|
+
let total = 2 + sizes.reduce((sum, size) => sum + size, 0);
|
|
1579
|
+
total += Math.max(next.length - 1, 0);
|
|
1580
|
+
let start = 0;
|
|
1581
|
+
while (start < next.length && total > limits.maxBytes) {
|
|
1582
|
+
total -= sizes[start];
|
|
1583
|
+
if (next.length - start > 1) total -= 1;
|
|
1584
|
+
start += 1;
|
|
1585
|
+
}
|
|
1586
|
+
return start === 0 ? next : next.slice(start);
|
|
1587
|
+
};
|
|
1588
|
+
const enqueueEvent = (events, event, now, limits) => {
|
|
1589
|
+
return pruneQueue([...events, event], now, limits);
|
|
1590
|
+
};
|
|
1591
|
+
const DEFAULT_SESSION_MS = 1800 * 1e3;
|
|
1592
|
+
const RETRY_MS = 6e4;
|
|
1593
|
+
const createRuntimeState = () => {
|
|
1594
|
+
const r1 = {
|
|
1595
|
+
options: null,
|
|
1596
|
+
context: null
|
|
1597
|
+
};
|
|
1598
|
+
const r2 = {
|
|
1599
|
+
sessionMs: DEFAULT_SESSION_MS,
|
|
1600
|
+
session: null
|
|
1601
|
+
};
|
|
1602
|
+
const r3 = {
|
|
1603
|
+
interactions: null,
|
|
1604
|
+
queue: []
|
|
1605
|
+
};
|
|
1606
|
+
const r4 = {
|
|
1607
|
+
hydrated: false,
|
|
1608
|
+
sessionTimer: null,
|
|
1609
|
+
retryTimer: null
|
|
1610
|
+
};
|
|
1611
|
+
const r5 = {
|
|
1612
|
+
flushTimer: null,
|
|
1613
|
+
sampleSeen: null,
|
|
1614
|
+
currency: void 0
|
|
1615
|
+
};
|
|
1616
|
+
const r6 = {
|
|
1617
|
+
pending: [],
|
|
1618
|
+
trackChain: Promise.resolve()
|
|
1619
|
+
};
|
|
1620
|
+
const r7 = {
|
|
1621
|
+
flushWait: null,
|
|
1622
|
+
user: null,
|
|
1623
|
+
consent: null
|
|
1624
|
+
};
|
|
1625
|
+
const r8 = { detachLifecycle: null };
|
|
1626
|
+
return {
|
|
1627
|
+
...r1,
|
|
1628
|
+
...r2,
|
|
1629
|
+
...r3,
|
|
1630
|
+
...r4,
|
|
1631
|
+
...r5,
|
|
1632
|
+
...r6,
|
|
1633
|
+
...r7,
|
|
1634
|
+
...r8
|
|
1635
|
+
};
|
|
1636
|
+
};
|
|
1637
|
+
/** State behind the module-level `configure`/`track`/`analytics` API. */
|
|
1638
|
+
const runtime = createRuntimeState();
|
|
1639
|
+
const storageKey = (rt, suffix) => {
|
|
1640
|
+
return `${rt.options?.storagePrefix?.trim() || "firespark:analytics"}:${suffix}`;
|
|
1641
|
+
};
|
|
1642
|
+
const getLimits = (rt) => {
|
|
1643
|
+
const limits = rt.options?.limits;
|
|
1644
|
+
return {
|
|
1645
|
+
maxEvents: limits?.maxEvents ?? 500,
|
|
1646
|
+
maxAgeMs: limits?.maxAgeMs ?? 6048e5,
|
|
1647
|
+
maxBytes: limits?.maxBytes ?? 1e6
|
|
1648
|
+
};
|
|
1649
|
+
};
|
|
1650
|
+
const readStorage = async (rt, suffix) => {
|
|
1651
|
+
const storage = rt.options?.storage;
|
|
1652
|
+
if (!storage) return null;
|
|
1653
|
+
return storage.getItem(storageKey(rt, suffix));
|
|
1654
|
+
};
|
|
1655
|
+
const writeStorage = async (rt, suffix, value) => {
|
|
1656
|
+
const storage = rt.options?.storage;
|
|
1657
|
+
if (!storage) return;
|
|
1658
|
+
await storage.setItem(storageKey(rt, suffix), value);
|
|
1659
|
+
};
|
|
1660
|
+
const clearStorage = async (rt, suffix) => {
|
|
1661
|
+
const storage = rt.options?.storage;
|
|
1662
|
+
if (!storage) return;
|
|
1663
|
+
await storage.removeItem(storageKey(rt, suffix));
|
|
1664
|
+
};
|
|
1665
|
+
const persistSession = async (rt) => {
|
|
1666
|
+
if (!rt.session) {
|
|
1667
|
+
await clearStorage(rt, "session");
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
await writeStorage(rt, "session", JSON.stringify(rt.session));
|
|
1671
|
+
};
|
|
1672
|
+
const persistQueue = async (rt) => {
|
|
1673
|
+
await writeStorage(rt, "queue", JSON.stringify(rt.queue));
|
|
1674
|
+
};
|
|
1675
|
+
const persistConfig = async (rt, sessionMs) => {
|
|
1676
|
+
const raw = JSON.stringify({ session_ms: sessionMs });
|
|
1677
|
+
await writeStorage(rt, "config", raw);
|
|
1678
|
+
};
|
|
1679
|
+
const persistInteractions = async (rt) => {
|
|
1680
|
+
if (!rt.interactions) {
|
|
1681
|
+
await clearStorage(rt, "interactions");
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
await writeStorage(rt, "interactions", JSON.stringify(rt.interactions));
|
|
1685
|
+
};
|
|
1686
|
+
const clearTimer = (rt, key) => {
|
|
1687
|
+
const timer = rt[key];
|
|
1688
|
+
if (timer) clearTimeout(timer);
|
|
1689
|
+
rt[key] = null;
|
|
1690
|
+
};
|
|
1691
|
+
const resetRuntime = (rt = runtime) => {
|
|
1692
|
+
clearTimer(rt, "sessionTimer");
|
|
1693
|
+
clearTimer(rt, "retryTimer");
|
|
1694
|
+
clearTimer(rt, "flushTimer");
|
|
1695
|
+
rt.detachLifecycle?.();
|
|
1696
|
+
Object.assign(rt, createRuntimeState());
|
|
1697
|
+
};
|
|
962
1698
|
const isPoisonChunk = (error) => {
|
|
963
1699
|
if (!(error instanceof StorefrontHttpError)) return false;
|
|
964
1700
|
return error.status === 400 || error.status === 422;
|
|
@@ -968,8 +1704,8 @@ const isTransientError = (error) => {
|
|
|
968
1704
|
if (error.status === 429) return true;
|
|
969
1705
|
return error.status >= 500;
|
|
970
1706
|
};
|
|
971
|
-
const httpOptions = async () => {
|
|
972
|
-
const options =
|
|
1707
|
+
const httpOptions = async (rt) => {
|
|
1708
|
+
const options = rt.options;
|
|
973
1709
|
if (!options) return {};
|
|
974
1710
|
const accessToken = options.getAccessToken ? await options.getAccessToken() : void 0;
|
|
975
1711
|
return {
|
|
@@ -978,88 +1714,285 @@ const httpOptions = async () => {
|
|
|
978
1714
|
fetchImpl: options.fetchImpl
|
|
979
1715
|
};
|
|
980
1716
|
};
|
|
981
|
-
const isOnline = async () => {
|
|
982
|
-
const check =
|
|
1717
|
+
const isOnline = async (rt) => {
|
|
1718
|
+
const check = rt.options?.isOnline;
|
|
983
1719
|
if (!check) return true;
|
|
984
1720
|
return check();
|
|
985
1721
|
};
|
|
986
|
-
const storefrontCall = async (path, init) => {
|
|
1722
|
+
const storefrontCall = async (rt, path, init) => {
|
|
987
1723
|
return storefrontJson(...[
|
|
988
1724
|
path,
|
|
989
1725
|
init,
|
|
990
|
-
await httpOptions()
|
|
1726
|
+
await httpOptions(rt)
|
|
991
1727
|
]);
|
|
992
1728
|
};
|
|
993
|
-
const postChunk = async (events) => {
|
|
1729
|
+
const postChunk = async (rt, events, keepalive) => {
|
|
994
1730
|
const init = {
|
|
995
1731
|
method: "POST",
|
|
996
1732
|
body: JSON.stringify({ events })
|
|
997
1733
|
};
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1734
|
+
if (keepalive) init.keepalive = true;
|
|
1735
|
+
return storefrontCall(rt, "/api/storefront/v1/analytics/events", init);
|
|
1736
|
+
};
|
|
1737
|
+
const scheduleRetry = (rt) => {
|
|
1738
|
+
if (rt.retryTimer || rt.queue.length === 0) return;
|
|
1739
|
+
rt.retryTimer = setTimeout(() => {
|
|
1740
|
+
rt.retryTimer = null;
|
|
1741
|
+
flushInBackground(rt);
|
|
1005
1742
|
}, RETRY_MS);
|
|
1006
1743
|
};
|
|
1007
|
-
const preferencesPath = () => {
|
|
1008
|
-
const scope =
|
|
1744
|
+
const preferencesPath = (rt) => {
|
|
1745
|
+
const scope = rt.options?.getScope?.() ?? {};
|
|
1009
1746
|
const params = new URLSearchParams();
|
|
1010
1747
|
if (scope.fulfillment_id) params.set("fulfillment_id", scope.fulfillment_id);
|
|
1011
1748
|
if (scope.store_id) params.set("store_id", scope.store_id);
|
|
1012
|
-
const channel_id = scope.channel_id ??
|
|
1749
|
+
const channel_id = scope.channel_id ?? rt.options?.channel_id;
|
|
1013
1750
|
if (channel_id) params.set("channel_id", channel_id);
|
|
1014
1751
|
if (scope.brand_id) params.set("brand_id", scope.brand_id);
|
|
1015
1752
|
const query = params.toString();
|
|
1016
1753
|
const path = "/api/storefront/v1/preferences";
|
|
1017
1754
|
return query ? `${path}?${query}` : path;
|
|
1018
1755
|
};
|
|
1019
|
-
const fetchRemoteConfig = async () => {
|
|
1020
|
-
const
|
|
1021
|
-
const prefs = await storefrontCall(path, { method: "GET" });
|
|
1756
|
+
const fetchRemoteConfig = async (rt) => {
|
|
1757
|
+
const prefs = await storefrontCall(rt, preferencesPath(rt), { method: "GET" });
|
|
1022
1758
|
const currency_code = prefs.currency?.code;
|
|
1023
1759
|
return {
|
|
1024
1760
|
...prefs.analytics,
|
|
1025
1761
|
currency_code
|
|
1026
1762
|
};
|
|
1027
1763
|
};
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1764
|
+
/**
|
|
1765
|
+
* Events queued before a customer existed get `is_anonymous` from the
|
|
1766
|
+
* current customer. Ingest resolves the customer from the access token.
|
|
1767
|
+
*/
|
|
1768
|
+
const resolveCustomer = async (rt) => {
|
|
1769
|
+
if (rt.queue.every((event) => typeof event.is_anonymous === "boolean")) return;
|
|
1770
|
+
const customer = rt.options?.getCustomer();
|
|
1771
|
+
if (!customer) return;
|
|
1772
|
+
const is_anonymous = customer.is_anonymous;
|
|
1773
|
+
rt.queue = rt.queue.map((event) => {
|
|
1774
|
+
if (typeof event.is_anonymous === "boolean") return event;
|
|
1775
|
+
return {
|
|
1776
|
+
...event,
|
|
1777
|
+
is_anonymous
|
|
1778
|
+
};
|
|
1779
|
+
});
|
|
1780
|
+
await persistQueue(rt);
|
|
1781
|
+
};
|
|
1782
|
+
const isResolved = (event) => {
|
|
1783
|
+
return typeof event.is_anonymous === "boolean";
|
|
1784
|
+
};
|
|
1785
|
+
const nextChunk = (rt, keepalive) => {
|
|
1786
|
+
const chunk = [];
|
|
1787
|
+
let bytes = 12;
|
|
1788
|
+
for (const event of rt.queue) {
|
|
1789
|
+
if (!isResolved(event)) continue;
|
|
1790
|
+
if (chunk.length >= 200) break;
|
|
1791
|
+
const size = JSON.stringify(event).length + 1;
|
|
1792
|
+
if (keepalive && bytes + size > 6e4 && chunk.length > 0) break;
|
|
1793
|
+
chunk.push(event);
|
|
1794
|
+
bytes += size;
|
|
1795
|
+
}
|
|
1796
|
+
return chunk;
|
|
1797
|
+
};
|
|
1798
|
+
const removeSent = async (rt, chunk) => {
|
|
1799
|
+
const ids = new Set(chunk.map((event) => event.id));
|
|
1800
|
+
rt.queue = rt.queue.filter((event) => !ids.has(event.id));
|
|
1801
|
+
await persistQueue(rt);
|
|
1802
|
+
};
|
|
1803
|
+
const sendChunk = async (rt, chunk, keepalive) => {
|
|
1804
|
+
try {
|
|
1805
|
+
await withExponentialRetry(() => postChunk(rt, chunk, keepalive), { shouldRetry: isTransientError });
|
|
1806
|
+
await removeSent(rt, chunk);
|
|
1807
|
+
return true;
|
|
1808
|
+
} catch (error) {
|
|
1809
|
+
if (!isPoisonChunk(error)) {
|
|
1810
|
+
report(rt, {
|
|
1811
|
+
level: "warning",
|
|
1812
|
+
source: "ingest",
|
|
1813
|
+
message: `Analytics ingest failed, retrying later: ${errorMessage(error)}`,
|
|
1814
|
+
error
|
|
1815
|
+
});
|
|
1816
|
+
return false;
|
|
1817
|
+
}
|
|
1818
|
+
await removeSent(rt, chunk);
|
|
1819
|
+
report(rt, {
|
|
1820
|
+
level: "error",
|
|
1821
|
+
source: "ingest",
|
|
1822
|
+
message: `Analytics ingest rejected ${chunk.length} events`,
|
|
1823
|
+
error
|
|
1824
|
+
});
|
|
1825
|
+
return true;
|
|
1826
|
+
}
|
|
1827
|
+
};
|
|
1828
|
+
const flushOnce = async (rt, keepalive) => {
|
|
1829
|
+
clearTimer(rt, "flushTimer");
|
|
1830
|
+
if (!rt.options || rt.queue.length === 0) return;
|
|
1831
|
+
if (!await isOnline(rt)) {
|
|
1832
|
+
scheduleRetry(rt);
|
|
1033
1833
|
return;
|
|
1034
1834
|
}
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
} catch (error) {
|
|
1042
|
-
if (isPoisonChunk(error)) {
|
|
1043
|
-
runtime.queue = runtime.queue.slice(chunk.length);
|
|
1044
|
-
await persistQueue();
|
|
1045
|
-
continue;
|
|
1046
|
-
}
|
|
1047
|
-
scheduleRetry();
|
|
1835
|
+
await resolveCustomer(rt);
|
|
1836
|
+
for (;;) {
|
|
1837
|
+
const chunk = nextChunk(rt, keepalive);
|
|
1838
|
+
if (chunk.length === 0) break;
|
|
1839
|
+
if (!await sendChunk(rt, chunk, keepalive)) {
|
|
1840
|
+
scheduleRetry(rt);
|
|
1048
1841
|
return;
|
|
1049
1842
|
}
|
|
1050
1843
|
}
|
|
1051
|
-
|
|
1844
|
+
if (rt.queue.length > 0) {
|
|
1845
|
+
scheduleRetry(rt);
|
|
1846
|
+
return;
|
|
1847
|
+
}
|
|
1848
|
+
clearTimer(rt, "retryTimer");
|
|
1052
1849
|
};
|
|
1053
|
-
const
|
|
1054
|
-
if (flushWait) return flushWait;
|
|
1055
|
-
flushWait = flushOnce().finally(() => {
|
|
1056
|
-
flushWait = null;
|
|
1850
|
+
const flushWith = async (rt, opts = {}) => {
|
|
1851
|
+
if (rt.flushWait) return rt.flushWait;
|
|
1852
|
+
rt.flushWait = flushOnce(rt, opts.keepalive === true).finally(() => {
|
|
1853
|
+
rt.flushWait = null;
|
|
1854
|
+
});
|
|
1855
|
+
return rt.flushWait;
|
|
1856
|
+
};
|
|
1857
|
+
/** For timers and listeners: failures are reported, never rejected. */
|
|
1858
|
+
const flushInBackground = (rt, opts) => {
|
|
1859
|
+
return flushWith(rt, opts).catch((error) => {
|
|
1860
|
+
report(rt, {
|
|
1861
|
+
level: "warning",
|
|
1862
|
+
source: "ingest",
|
|
1863
|
+
message: `Analytics flush failed: ${errorMessage(error)}`,
|
|
1864
|
+
error
|
|
1865
|
+
});
|
|
1057
1866
|
});
|
|
1058
|
-
|
|
1867
|
+
};
|
|
1868
|
+
/** Sends the queue now if it reached `flushAt`, else arms the timer. */
|
|
1869
|
+
const scheduleFlush = (rt) => {
|
|
1870
|
+
if (!rt.options || rt.queue.length === 0) return;
|
|
1871
|
+
const flushAt = rt.options.flushAt ?? 20;
|
|
1872
|
+
if (flushAt > 0 && rt.queue.length >= flushAt) {
|
|
1873
|
+
flushInBackground(rt);
|
|
1874
|
+
return;
|
|
1875
|
+
}
|
|
1876
|
+
const interval = rt.options.flushIntervalMs ?? 3e4;
|
|
1877
|
+
if (interval <= 0 || rt.flushTimer) return;
|
|
1878
|
+
rt.flushTimer = setTimeout(() => {
|
|
1879
|
+
rt.flushTimer = null;
|
|
1880
|
+
flushInBackground(rt);
|
|
1881
|
+
}, interval);
|
|
1882
|
+
};
|
|
1883
|
+
/** Sends the default instance queue to Fire Spark. */
|
|
1884
|
+
const flush = () => flushWith(runtime);
|
|
1885
|
+
//#endregion
|
|
1886
|
+
//#region src/types.ts
|
|
1887
|
+
const FUNNEL_EVENTS = [
|
|
1888
|
+
"menu_viewed",
|
|
1889
|
+
"product_viewed",
|
|
1890
|
+
"add_to_cart",
|
|
1891
|
+
"purchase"
|
|
1892
|
+
];
|
|
1893
|
+
const INTERACTION_EVENTS = ["product_visited", "category_visited"];
|
|
1894
|
+
const isFunnelEventName = (name) => {
|
|
1895
|
+
return FUNNEL_EVENTS.includes(name);
|
|
1896
|
+
};
|
|
1897
|
+
const isInteractionEventName = (name) => {
|
|
1898
|
+
return INTERACTION_EVENTS.includes(name);
|
|
1899
|
+
};
|
|
1900
|
+
//#endregion
|
|
1901
|
+
//#region src/interactions.ts
|
|
1902
|
+
const interactionKey = (name, entityId) => {
|
|
1903
|
+
return `${name}:${entityId}`;
|
|
1904
|
+
};
|
|
1905
|
+
const parseInteractions = (raw) => {
|
|
1906
|
+
if (!raw) return null;
|
|
1907
|
+
try {
|
|
1908
|
+
const parsed = JSON.parse(raw);
|
|
1909
|
+
if (!parsed?.session_id || !Array.isArray(parsed.keys)) return null;
|
|
1910
|
+
return parsed;
|
|
1911
|
+
} catch {
|
|
1912
|
+
return null;
|
|
1913
|
+
}
|
|
1914
|
+
};
|
|
1915
|
+
const bindInteractions = (state, sessionId) => {
|
|
1916
|
+
if (!state || state.session_id !== sessionId) return {
|
|
1917
|
+
session_id: sessionId,
|
|
1918
|
+
keys: []
|
|
1919
|
+
};
|
|
1920
|
+
return state;
|
|
1921
|
+
};
|
|
1922
|
+
const shouldSkipInteraction = (state, name, entityId) => {
|
|
1923
|
+
if (!isInteractionEventName(name) || !entityId) return false;
|
|
1924
|
+
return state.keys.includes(interactionKey(name, entityId));
|
|
1925
|
+
};
|
|
1926
|
+
const markInteraction = (state, name, entityId) => {
|
|
1927
|
+
if (!isInteractionEventName(name) || !entityId) return state;
|
|
1928
|
+
const key = interactionKey(name, entityId);
|
|
1929
|
+
if (state.keys.includes(key)) return state;
|
|
1930
|
+
const keys = [...state.keys, key].slice(-500);
|
|
1931
|
+
return {
|
|
1932
|
+
...state,
|
|
1933
|
+
keys
|
|
1934
|
+
};
|
|
1935
|
+
};
|
|
1936
|
+
//#endregion
|
|
1937
|
+
//#region src/lifecycle.ts
|
|
1938
|
+
const browserTargets = () => {
|
|
1939
|
+
const root = globalThis;
|
|
1940
|
+
const doc = root.document;
|
|
1941
|
+
const win = root.window;
|
|
1942
|
+
if (!doc || typeof doc.addEventListener !== "function") return null;
|
|
1943
|
+
if (!win || typeof win.addEventListener !== "function") return null;
|
|
1944
|
+
return {
|
|
1945
|
+
doc,
|
|
1946
|
+
win
|
|
1947
|
+
};
|
|
1948
|
+
};
|
|
1949
|
+
const attachBrowser = (rt) => {
|
|
1950
|
+
const targets = browserTargets();
|
|
1951
|
+
if (!targets) return null;
|
|
1952
|
+
const { doc, win } = targets;
|
|
1953
|
+
const onHide = () => {
|
|
1954
|
+
flushInBackground(rt, { keepalive: true });
|
|
1955
|
+
};
|
|
1956
|
+
const onVisibility = () => {
|
|
1957
|
+
if (doc.visibilityState === "hidden") onHide();
|
|
1958
|
+
};
|
|
1959
|
+
doc.addEventListener("visibilitychange", onVisibility);
|
|
1960
|
+
win.addEventListener("pagehide", onHide);
|
|
1961
|
+
return () => {
|
|
1962
|
+
doc.removeEventListener("visibilitychange", onVisibility);
|
|
1963
|
+
win.removeEventListener("pagehide", onHide);
|
|
1964
|
+
};
|
|
1965
|
+
};
|
|
1966
|
+
const attachAppState = (rt) => {
|
|
1967
|
+
const appState = rt.options?.appState;
|
|
1968
|
+
if (!appState) return null;
|
|
1969
|
+
const subscription = appState.addEventListener("change", (state) => {
|
|
1970
|
+
if (state !== "background" && state !== "inactive") return;
|
|
1971
|
+
flushInBackground(rt);
|
|
1972
|
+
});
|
|
1973
|
+
return () => {
|
|
1974
|
+
subscription?.remove();
|
|
1975
|
+
};
|
|
1976
|
+
};
|
|
1977
|
+
/** Sends the queue when the page hides or the app goes to background. */
|
|
1978
|
+
const attachLifecycle = (rt) => {
|
|
1979
|
+
rt.detachLifecycle?.();
|
|
1980
|
+
rt.detachLifecycle = null;
|
|
1981
|
+
const detachers = [];
|
|
1982
|
+
const native = attachAppState(rt);
|
|
1983
|
+
if (native) detachers.push(native);
|
|
1984
|
+
if (rt.options?.platform === "web" && rt.options?.flushOnHide !== false) {
|
|
1985
|
+
const browser = attachBrowser(rt);
|
|
1986
|
+
if (browser) detachers.push(browser);
|
|
1987
|
+
}
|
|
1988
|
+
if (detachers.length === 0) return;
|
|
1989
|
+
rt.detachLifecycle = () => {
|
|
1990
|
+
for (const detach of detachers) detach();
|
|
1991
|
+
rt.detachLifecycle = null;
|
|
1992
|
+
};
|
|
1059
1993
|
};
|
|
1060
1994
|
//#endregion
|
|
1061
1995
|
//#region src/sample.ts
|
|
1062
|
-
const SAMPLE_KEY = "firespark:analytics:samples";
|
|
1063
1996
|
const PLAN_SAMPLES_PATH = "/api/storefront/v1/analytics/plan-samples";
|
|
1064
1997
|
const DEFAULT_RATE = .01;
|
|
1065
1998
|
const inferType = (value) => {
|
|
@@ -1081,15 +2014,15 @@ const parseSeen = (raw) => {
|
|
|
1081
2014
|
return /* @__PURE__ */ new Set();
|
|
1082
2015
|
}
|
|
1083
2016
|
};
|
|
1084
|
-
const loadSeen = async () => {
|
|
1085
|
-
if (
|
|
1086
|
-
|
|
1087
|
-
return
|
|
2017
|
+
const loadSeen = async (rt) => {
|
|
2018
|
+
if (rt.sampleSeen) return rt.sampleSeen;
|
|
2019
|
+
rt.sampleSeen = parseSeen(await readStorage(rt, "samples"));
|
|
2020
|
+
return rt.sampleSeen;
|
|
1088
2021
|
};
|
|
1089
|
-
const persistSeen = async (seen) => {
|
|
1090
|
-
|
|
2022
|
+
const persistSeen = async (rt, seen) => {
|
|
2023
|
+
rt.sampleSeen = seen;
|
|
1091
2024
|
const keys = [...seen];
|
|
1092
|
-
await writeStorage(
|
|
2025
|
+
await writeStorage(rt, "samples", JSON.stringify({ keys }));
|
|
1093
2026
|
};
|
|
1094
2027
|
const leafName = (path) => {
|
|
1095
2028
|
const parts = path.split(".");
|
|
@@ -1141,15 +2074,15 @@ const shouldSend = (seen, firstPerEvent, rate) => {
|
|
|
1141
2074
|
if (rate <= 0) return false;
|
|
1142
2075
|
return Math.random() < rate;
|
|
1143
2076
|
};
|
|
1144
|
-
const samplePlanEvent = async (event, opts) => {
|
|
1145
|
-
const options =
|
|
2077
|
+
const samplePlanEvent = async (rt, event, opts) => {
|
|
2078
|
+
const options = rt.options;
|
|
1146
2079
|
if (!options?.planVersionId) return;
|
|
1147
2080
|
const sample = options.sample ?? {};
|
|
1148
2081
|
const firstPerEvent = sample.firstPerEvent !== false;
|
|
1149
2082
|
const rate = sample.rate ?? DEFAULT_RATE;
|
|
1150
2083
|
const variant = opts?.variant;
|
|
1151
2084
|
const key = variant ? `${event.name}:${variant}` : event.name;
|
|
1152
|
-
const seen = await loadSeen();
|
|
2085
|
+
const seen = await loadSeen(rt);
|
|
1153
2086
|
const already = seen.has(key);
|
|
1154
2087
|
if (!shouldSend(already, firstPerEvent, rate)) return;
|
|
1155
2088
|
const described = describeSample(event, opts);
|
|
@@ -1177,15 +2110,40 @@ const samplePlanEvent = async (event, opts) => {
|
|
|
1177
2110
|
method: "POST",
|
|
1178
2111
|
body: JSON.stringify(full)
|
|
1179
2112
|
};
|
|
1180
|
-
await storefrontCall(PLAN_SAMPLES_PATH, init);
|
|
2113
|
+
await storefrontCall(rt, PLAN_SAMPLES_PATH, init);
|
|
1181
2114
|
if (!already) {
|
|
1182
2115
|
seen.add(key);
|
|
1183
|
-
await persistSeen(seen);
|
|
2116
|
+
await persistSeen(rt, seen);
|
|
1184
2117
|
}
|
|
1185
2118
|
};
|
|
1186
2119
|
//#endregion
|
|
2120
|
+
//#region src/uuid.ts
|
|
2121
|
+
const randomBytes = () => {
|
|
2122
|
+
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
2123
|
+
const c = globalThis.crypto;
|
|
2124
|
+
if (typeof c?.getRandomValues === "function") {
|
|
2125
|
+
c.getRandomValues(bytes);
|
|
2126
|
+
return bytes;
|
|
2127
|
+
}
|
|
2128
|
+
for (let i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
|
2129
|
+
return bytes;
|
|
2130
|
+
};
|
|
2131
|
+
/**
|
|
2132
|
+
* UUID v4. Uses `crypto.randomUUID`, then `crypto.getRandomValues`, then
|
|
2133
|
+
* `Math.random` (React Native / Hermes without a polyfill). Never throws.
|
|
2134
|
+
*/
|
|
2135
|
+
const randomUUID = () => {
|
|
2136
|
+
const c = globalThis.crypto;
|
|
2137
|
+
if (typeof c?.randomUUID === "function") return c.randomUUID();
|
|
2138
|
+
const bytes = randomBytes();
|
|
2139
|
+
bytes[6] = bytes[6] & 15 | 64;
|
|
2140
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
2141
|
+
const toHex = (b) => b.toString(16).padStart(2, "0");
|
|
2142
|
+
const hex = Array.from(bytes, toHex).join("");
|
|
2143
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
2144
|
+
};
|
|
2145
|
+
//#endregion
|
|
1187
2146
|
//#region src/session.ts
|
|
1188
|
-
const SESSION_KEY = "firespark:analytics:session";
|
|
1189
2147
|
const createSession = (now) => {
|
|
1190
2148
|
return {
|
|
1191
2149
|
id: randomUUID(),
|
|
@@ -1231,7 +2189,14 @@ const shouldCarryMenuViewed = (prev, next) => {
|
|
|
1231
2189
|
return prev.seen.includes("menu_viewed");
|
|
1232
2190
|
};
|
|
1233
2191
|
//#endregion
|
|
1234
|
-
//#region src/
|
|
2192
|
+
//#region src/client.ts
|
|
2193
|
+
const STORAGE_SUFFIXES = [
|
|
2194
|
+
"session",
|
|
2195
|
+
"queue",
|
|
2196
|
+
"config",
|
|
2197
|
+
"interactions",
|
|
2198
|
+
"samples"
|
|
2199
|
+
];
|
|
1235
2200
|
const toTrackEvent = (nameOrEvent, params) => {
|
|
1236
2201
|
if (typeof nameOrEvent !== "string") return nameOrEvent;
|
|
1237
2202
|
if (!params) return { name: nameOrEvent };
|
|
@@ -1247,82 +2212,91 @@ const entityIdFromEvent = (event) => {
|
|
|
1247
2212
|
if ("category_id" in props && typeof props.category_id === "string") return props.category_id;
|
|
1248
2213
|
if ("order_id" in props && typeof props.order_id === "string") return props.order_id;
|
|
1249
2214
|
};
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
const
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
2215
|
+
/** Serializes configure/track/setUser/setConsent per instance. */
|
|
2216
|
+
const enqueue = (rt, run) => {
|
|
2217
|
+
const next = rt.trackChain.then(run, run);
|
|
2218
|
+
const ok = () => void 0;
|
|
2219
|
+
rt.trackChain = next.then(ok, ok);
|
|
2220
|
+
return next;
|
|
2221
|
+
};
|
|
2222
|
+
const armSessionTimer = (rt) => {
|
|
2223
|
+
clearTimer(rt, "sessionTimer");
|
|
2224
|
+
if (!rt.session) return;
|
|
2225
|
+
const last = rt.session.last_event_at;
|
|
2226
|
+
const delay = rt.sessionMs - (Date.now() - last);
|
|
2227
|
+
rt.sessionTimer = setTimeout(() => {
|
|
2228
|
+
rt.sessionTimer = null;
|
|
2229
|
+
endSessionWith(rt).catch((error) => {
|
|
2230
|
+
report(rt, {
|
|
2231
|
+
level: "warning",
|
|
2232
|
+
source: "track",
|
|
2233
|
+
message: `Could not end the session: ${errorMessage(error)}`,
|
|
2234
|
+
error
|
|
2235
|
+
});
|
|
2236
|
+
});
|
|
1258
2237
|
}, Math.max(delay, 0));
|
|
1259
2238
|
};
|
|
1260
|
-
const loadPersisted = async () => {
|
|
1261
|
-
if (
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
const rawConfig = await readStorage(
|
|
2239
|
+
const loadPersisted = async (rt) => {
|
|
2240
|
+
if (rt.hydrated) return;
|
|
2241
|
+
rt.hydrated = true;
|
|
2242
|
+
rt.session = parseSession(await readStorage(rt, "session"));
|
|
2243
|
+
rt.queue = [...parseQueue(await readStorage(rt, "queue")), ...rt.queue];
|
|
2244
|
+
rt.interactions = parseInteractions(await readStorage(rt, "interactions"));
|
|
2245
|
+
const rawConfig = await readStorage(rt, "config");
|
|
1267
2246
|
if (!rawConfig) return;
|
|
1268
2247
|
try {
|
|
1269
2248
|
const parsed = JSON.parse(rawConfig);
|
|
1270
|
-
if (typeof parsed.session_ms === "number" && parsed.session_ms > 0)
|
|
2249
|
+
if (typeof parsed.session_ms === "number" && parsed.session_ms > 0) rt.sessionMs = parsed.session_ms;
|
|
1271
2250
|
} catch {}
|
|
1272
2251
|
};
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
2252
|
+
const resolveCurrency = (rt, currency) => {
|
|
2253
|
+
if (currency === void 0 || currency === null || currency === "") return;
|
|
2254
|
+
const code = isoCurrencyCode(currency);
|
|
2255
|
+
if (code) return code;
|
|
2256
|
+
report(rt, {
|
|
2257
|
+
level: "warning",
|
|
2258
|
+
source: "configure",
|
|
2259
|
+
message: `Ignoring invalid currency "${String(currency)}"`
|
|
2260
|
+
});
|
|
2261
|
+
};
|
|
2262
|
+
/**
|
|
2263
|
+
* `sessionMs` and `currency` from `configure()` win. Preferences are
|
|
2264
|
+
* fetched whenever one of them is missing.
|
|
2265
|
+
*/
|
|
2266
|
+
const refreshConfig = async (rt) => {
|
|
2267
|
+
const provided = rt.options?.sessionMs;
|
|
2268
|
+
const hasSession = typeof provided === "number" && provided > 0;
|
|
2269
|
+
if (hasSession) {
|
|
2270
|
+
rt.sessionMs = provided;
|
|
2271
|
+
await persistConfig(rt, rt.sessionMs);
|
|
1279
2272
|
}
|
|
2273
|
+
if (hasSession && rt.currency) return;
|
|
1280
2274
|
try {
|
|
1281
|
-
const config = await fetchRemoteConfig();
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
2275
|
+
const config = await fetchRemoteConfig(rt);
|
|
2276
|
+
if (!hasSession) {
|
|
2277
|
+
rt.sessionMs = config.session_ms || 18e5;
|
|
2278
|
+
await persistConfig(rt, rt.sessionMs);
|
|
2279
|
+
}
|
|
2280
|
+
if (!rt.currency) rt.currency = isoCurrencyCode(config.currency_code);
|
|
2281
|
+
} catch (error) {
|
|
2282
|
+
report(rt, {
|
|
2283
|
+
level: "warning",
|
|
2284
|
+
source: "configure",
|
|
2285
|
+
message: `Could not load analytics preferences: ${errorMessage(error)}`,
|
|
2286
|
+
error
|
|
2287
|
+
});
|
|
1291
2288
|
}
|
|
1292
2289
|
};
|
|
1293
|
-
|
|
1294
|
-
const
|
|
1295
|
-
const
|
|
1296
|
-
const
|
|
1297
|
-
trackChain = next.then(ok, ok);
|
|
1298
|
-
return next;
|
|
1299
|
-
};
|
|
1300
|
-
const configure = async (options) => {
|
|
1301
|
-
const channel_id = options.channel_id?.trim() ?? "";
|
|
1302
|
-
if (!channel_id) throw new Error("channel_id is required");
|
|
1303
|
-
return enqueue(async () => {
|
|
1304
|
-
runtime.options = {
|
|
1305
|
-
...options,
|
|
1306
|
-
channel_id
|
|
1307
|
-
};
|
|
1308
|
-
const ctx = options.context;
|
|
1309
|
-
runtime.context = buildEventContext(typeof ctx === "function" ? void 0 : ctx);
|
|
1310
|
-
await loadPersisted();
|
|
1311
|
-
await refreshConfig();
|
|
1312
|
-
armSessionTimer();
|
|
1313
|
-
if (runtime.queue.length > 0) flush();
|
|
1314
|
-
});
|
|
1315
|
-
};
|
|
1316
|
-
const toQueued = (event, now, sessionId, customer) => {
|
|
1317
|
-
const scope = runtime.options?.getScope?.() ?? {};
|
|
1318
|
-
const platform = runtime.options?.platform ?? "web";
|
|
1319
|
-
const channel_id = runtime.options?.channel_id ?? scope.channel_id;
|
|
2290
|
+
const toQueued = (rt, event, now, sessionId, customer) => {
|
|
2291
|
+
const scope = rt.options?.getScope?.() ?? {};
|
|
2292
|
+
const platform = rt.options?.platform ?? "web";
|
|
2293
|
+
const channel_id = rt.options?.channel_id ?? scope.channel_id;
|
|
1320
2294
|
const b1 = {
|
|
1321
2295
|
id: randomUUID(),
|
|
1322
2296
|
name: event.name,
|
|
1323
2297
|
session_id: sessionId
|
|
1324
2298
|
};
|
|
1325
|
-
const b2 = { is_anonymous: customer
|
|
2299
|
+
const b2 = { is_anonymous: customer?.is_anonymous };
|
|
1326
2300
|
const b3 = { timestamp: new Date(now).toISOString() };
|
|
1327
2301
|
const b4 = {
|
|
1328
2302
|
store_id: scope.store_id,
|
|
@@ -1337,7 +2311,7 @@ const toQueued = (event, now, sessionId, customer) => {
|
|
|
1337
2311
|
properties: event.properties,
|
|
1338
2312
|
platform
|
|
1339
2313
|
};
|
|
1340
|
-
const b8 = { context:
|
|
2314
|
+
const b8 = { context: rt.context ?? buildEventContext() };
|
|
1341
2315
|
return {
|
|
1342
2316
|
...b1,
|
|
1343
2317
|
...b2,
|
|
@@ -1349,121 +2323,332 @@ const toQueued = (event, now, sessionId, customer) => {
|
|
|
1349
2323
|
...b8
|
|
1350
2324
|
};
|
|
1351
2325
|
};
|
|
1352
|
-
const
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
const
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
await persistInteractions();
|
|
1370
|
-
armSessionTimer();
|
|
1371
|
-
return;
|
|
1372
|
-
}
|
|
1373
|
-
runtime.interactions = markInteraction(bound, event.name, entityId);
|
|
1374
|
-
runtime.session = session;
|
|
1375
|
-
const queued = toQueued(event, now, session.id, customer);
|
|
1376
|
-
runtime.queue = enqueueEvent(runtime.queue, queued, now, getLimits());
|
|
1377
|
-
await persistSession();
|
|
1378
|
-
await persistInteractions();
|
|
1379
|
-
await persistQueue();
|
|
1380
|
-
armSessionTimer();
|
|
2326
|
+
const push = (rt, queued, now) => {
|
|
2327
|
+
rt.queue = enqueueEvent(rt.queue, queued, now, getLimits(rt));
|
|
2328
|
+
return queued.id;
|
|
2329
|
+
};
|
|
2330
|
+
const trackInteraction = async (rt, event, now, customer) => {
|
|
2331
|
+
const session = touchSession(rt.session, now, rt.sessionMs);
|
|
2332
|
+
const entityId = entityIdFromEvent(event);
|
|
2333
|
+
const bound = bindInteractions(rt.interactions, session.id);
|
|
2334
|
+
if (!entityId || shouldSkipInteraction(bound, event.name, entityId)) {
|
|
2335
|
+
rt.session = {
|
|
2336
|
+
...session,
|
|
2337
|
+
last_event_at: now
|
|
2338
|
+
};
|
|
2339
|
+
rt.interactions = bound;
|
|
2340
|
+
await persistSession(rt);
|
|
2341
|
+
await persistInteractions(rt);
|
|
2342
|
+
armSessionTimer(rt);
|
|
1381
2343
|
return;
|
|
1382
2344
|
}
|
|
2345
|
+
rt.interactions = markInteraction(bound, event.name, entityId);
|
|
2346
|
+
rt.session = session;
|
|
2347
|
+
const id = push(rt, toQueued(rt, event, now, session.id, customer), now);
|
|
2348
|
+
await persistSession(rt);
|
|
2349
|
+
await persistInteractions(rt);
|
|
2350
|
+
await persistQueue(rt);
|
|
2351
|
+
armSessionTimer(rt);
|
|
2352
|
+
scheduleFlush(rt);
|
|
2353
|
+
return id;
|
|
2354
|
+
};
|
|
2355
|
+
/**
|
|
2356
|
+
* Fire Spark keeps one event per funnel step per session (session funnel
|
|
2357
|
+
* metrics). Destinations receive every occurrence.
|
|
2358
|
+
*/
|
|
2359
|
+
const trackEvent = async (rt, event, now) => {
|
|
2360
|
+
if (!rt.options) return void 0;
|
|
2361
|
+
const customer = rt.options.getCustomer();
|
|
2362
|
+
if (isInteractionEventName(event.name)) return trackInteraction(rt, event, now, customer);
|
|
2363
|
+
const prev = rt.session;
|
|
2364
|
+
let session = touchSession(prev, now, rt.sessionMs);
|
|
1383
2365
|
if (shouldCarryMenuViewed(prev, session) && event.name !== "menu_viewed") {
|
|
1384
2366
|
session = markSeen(session, "menu_viewed");
|
|
1385
|
-
|
|
1386
|
-
{ name: "menu_viewed" },
|
|
1387
|
-
now,
|
|
1388
|
-
session.id,
|
|
1389
|
-
customer
|
|
1390
|
-
];
|
|
1391
|
-
const carried = toQueued(...p1);
|
|
1392
|
-
runtime.queue = enqueueEvent(runtime.queue, carried, now, getLimits());
|
|
2367
|
+
push(rt, toQueued(rt, { name: "menu_viewed" }, now, session.id, customer), now);
|
|
1393
2368
|
}
|
|
1394
2369
|
if (shouldSkipFunnelEvent(session, event.name)) {
|
|
1395
|
-
|
|
2370
|
+
rt.session = {
|
|
1396
2371
|
...session,
|
|
1397
2372
|
last_event_at: now
|
|
1398
2373
|
};
|
|
1399
|
-
await persistSession();
|
|
1400
|
-
await persistQueue();
|
|
1401
|
-
armSessionTimer();
|
|
2374
|
+
await persistSession(rt);
|
|
2375
|
+
await persistQueue(rt);
|
|
2376
|
+
armSessionTimer(rt);
|
|
1402
2377
|
return;
|
|
1403
2378
|
}
|
|
1404
2379
|
session = markSeen(session, event.name);
|
|
1405
|
-
|
|
1406
|
-
const
|
|
1407
|
-
|
|
1408
|
-
await
|
|
1409
|
-
await persistQueue();
|
|
2380
|
+
rt.session = session;
|
|
2381
|
+
const id = push(rt, toQueued(rt, event, now, session.id, customer), now);
|
|
2382
|
+
await persistSession(rt);
|
|
2383
|
+
await persistQueue(rt);
|
|
1410
2384
|
if (event.name === "purchase") {
|
|
1411
|
-
await
|
|
1412
|
-
|
|
2385
|
+
await closeSession(rt);
|
|
2386
|
+
await flushInBackground(rt);
|
|
2387
|
+
return id;
|
|
1413
2388
|
}
|
|
1414
|
-
armSessionTimer();
|
|
2389
|
+
armSessionTimer(rt);
|
|
2390
|
+
scheduleFlush(rt);
|
|
2391
|
+
return id;
|
|
2392
|
+
};
|
|
2393
|
+
const bufferPending = (rt, pending) => {
|
|
2394
|
+
rt.pending.push(pending);
|
|
2395
|
+
if (rt.pending.length <= 100) return;
|
|
2396
|
+
report(rt, {
|
|
2397
|
+
level: "warning",
|
|
2398
|
+
source: "track",
|
|
2399
|
+
message: "Too many events before configure(); dropped the oldest",
|
|
2400
|
+
event: rt.pending.shift()?.event.name
|
|
2401
|
+
});
|
|
1415
2402
|
};
|
|
1416
|
-
const
|
|
1417
|
-
|
|
2403
|
+
const reportTrackFailure = (rt, name, error) => {
|
|
2404
|
+
report(rt, {
|
|
2405
|
+
level: "error",
|
|
2406
|
+
source: "track",
|
|
2407
|
+
message: `Could not queue "${name}": ${errorMessage(error)}`,
|
|
2408
|
+
error,
|
|
2409
|
+
event: name
|
|
2410
|
+
});
|
|
1418
2411
|
};
|
|
1419
|
-
const
|
|
1420
|
-
const
|
|
1421
|
-
resolveAdapters(opts);
|
|
1422
|
-
const fanoutP = swallow(fanoutAdapters(event, opts));
|
|
2412
|
+
const storeEvent = async (rt, pending) => {
|
|
2413
|
+
const { event, objectForm, at } = pending;
|
|
1423
2414
|
const funnel = isFunnelEventName(event.name);
|
|
1424
2415
|
const interaction = isInteractionEventName(event.name);
|
|
1425
|
-
if (objectForm
|
|
2416
|
+
if (!objectForm && !funnel && !interaction) return void 0;
|
|
2417
|
+
try {
|
|
2418
|
+
return await trackEvent(rt, event, at);
|
|
2419
|
+
} catch (error) {
|
|
2420
|
+
reportTrackFailure(rt, event.name, error);
|
|
2421
|
+
return;
|
|
2422
|
+
}
|
|
2423
|
+
};
|
|
2424
|
+
/**
|
|
2425
|
+
* Only the object form, funnel and interaction events are stored in Fire
|
|
2426
|
+
* Spark. `track("name", params)` for other names goes to destinations only
|
|
2427
|
+
* (by design). A stored event shares its id with the destinations.
|
|
2428
|
+
*/
|
|
2429
|
+
const dispatch = async (rt, pending) => {
|
|
2430
|
+
if (!rt.options) {
|
|
2431
|
+
bufferPending(rt, pending);
|
|
2432
|
+
return;
|
|
2433
|
+
}
|
|
2434
|
+
const { event, opts, at } = pending;
|
|
2435
|
+
const sampleP = samplePlanEvent(rt, event, opts).catch((error) => {
|
|
2436
|
+
report(rt, {
|
|
2437
|
+
level: "warning",
|
|
2438
|
+
source: "sample",
|
|
2439
|
+
message: `Plan sample failed: ${errorMessage(error)}`,
|
|
2440
|
+
error,
|
|
2441
|
+
event: event.name
|
|
2442
|
+
});
|
|
2443
|
+
});
|
|
2444
|
+
const fanoutP = fanoutAdapters(rt, {
|
|
2445
|
+
event,
|
|
2446
|
+
eventId: await storeEvent(rt, pending) ?? randomUUID(),
|
|
2447
|
+
at
|
|
2448
|
+
}, opts).catch((error) => {
|
|
2449
|
+
report(rt, {
|
|
2450
|
+
level: "error",
|
|
2451
|
+
source: "destination",
|
|
2452
|
+
message: `Destinations failed: ${errorMessage(error)}`,
|
|
2453
|
+
error,
|
|
2454
|
+
event: event.name
|
|
2455
|
+
});
|
|
2456
|
+
});
|
|
1426
2457
|
await Promise.all([sampleP, fanoutP]);
|
|
1427
2458
|
};
|
|
1428
|
-
const
|
|
2459
|
+
const replayPending = async (rt) => {
|
|
2460
|
+
const pending = rt.pending;
|
|
2461
|
+
rt.pending = [];
|
|
2462
|
+
for (const item of pending) await dispatch(rt, item);
|
|
2463
|
+
};
|
|
2464
|
+
const configureWith = async (rt, options) => {
|
|
2465
|
+
const channel_id = options.channel_id?.trim() ?? "";
|
|
2466
|
+
if (!channel_id) throw new Error("channel_id is required");
|
|
2467
|
+
return enqueue(rt, async () => {
|
|
2468
|
+
rt.options = {
|
|
2469
|
+
...options,
|
|
2470
|
+
channel_id
|
|
2471
|
+
};
|
|
2472
|
+
rt.currency = resolveCurrency(rt, options.currency);
|
|
2473
|
+
const ctx = options.context;
|
|
2474
|
+
rt.context = buildEventContext(typeof ctx === "function" ? void 0 : ctx);
|
|
2475
|
+
await loadPersisted(rt);
|
|
2476
|
+
await refreshConfig(rt);
|
|
2477
|
+
armSessionTimer(rt);
|
|
2478
|
+
attachLifecycle(rt);
|
|
2479
|
+
if (rt.consent || options.consent) await pushConsent(rt);
|
|
2480
|
+
if (rt.user) await pushUser(rt);
|
|
2481
|
+
await replayPending(rt);
|
|
2482
|
+
if (rt.queue.length > 0) flushInBackground(rt);
|
|
2483
|
+
});
|
|
2484
|
+
};
|
|
2485
|
+
const trackWith = (rt, nameOrEvent, params, opts) => {
|
|
1429
2486
|
const objectForm = typeof nameOrEvent !== "string";
|
|
1430
|
-
const
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
2487
|
+
const pending = {
|
|
2488
|
+
event: toTrackEvent(nameOrEvent, params),
|
|
2489
|
+
objectForm,
|
|
2490
|
+
opts,
|
|
2491
|
+
at: Date.now()
|
|
2492
|
+
};
|
|
2493
|
+
return enqueue(rt, () => dispatch(rt, pending));
|
|
2494
|
+
};
|
|
2495
|
+
const closeSession = async (rt) => {
|
|
2496
|
+
clearTimer(rt, "sessionTimer");
|
|
2497
|
+
rt.session = null;
|
|
2498
|
+
await persistSession(rt);
|
|
2499
|
+
};
|
|
2500
|
+
const endSessionWith = async (rt) => {
|
|
2501
|
+
await closeSession(rt);
|
|
2502
|
+
await flushWith(rt);
|
|
2503
|
+
};
|
|
2504
|
+
const resetWith = async (rt) => {
|
|
2505
|
+
const storage = rt.options?.storage;
|
|
2506
|
+
const keys = STORAGE_SUFFIXES.map((suffix) => storageKey(rt, suffix));
|
|
2507
|
+
resetRuntime(rt);
|
|
1442
2508
|
if (!storage) return;
|
|
1443
|
-
await storage.removeItem(
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
2509
|
+
for (const key of keys) await storage.removeItem(key);
|
|
2510
|
+
};
|
|
2511
|
+
const normalizeUser = (user) => {
|
|
2512
|
+
if (!user) return null;
|
|
2513
|
+
const id = typeof user.id === "string" ? user.id.trim() || null : user.id;
|
|
2514
|
+
return {
|
|
2515
|
+
...user,
|
|
2516
|
+
id
|
|
2517
|
+
};
|
|
2518
|
+
};
|
|
2519
|
+
const setUserWith = (rt, user) => {
|
|
2520
|
+
return enqueue(rt, async () => {
|
|
2521
|
+
rt.user = normalizeUser(user);
|
|
2522
|
+
await pushUser(rt);
|
|
2523
|
+
});
|
|
2524
|
+
};
|
|
2525
|
+
const setConsentWith = (rt, consent) => {
|
|
2526
|
+
return enqueue(rt, async () => {
|
|
2527
|
+
rt.consent = {
|
|
2528
|
+
analytics: consent.analytics,
|
|
2529
|
+
ads: consent.ads
|
|
2530
|
+
};
|
|
2531
|
+
await pushConsent(rt);
|
|
2532
|
+
});
|
|
2533
|
+
};
|
|
2534
|
+
//#endregion
|
|
2535
|
+
//#region src/compact.ts
|
|
2536
|
+
/** Drops `undefined`, `null`, non-finite numbers and functions, deeply. */
|
|
2537
|
+
const compactPayload = (value) => {
|
|
2538
|
+
return compactPayload$1(value);
|
|
2539
|
+
};
|
|
2540
|
+
//#endregion
|
|
2541
|
+
//#region src/script.ts
|
|
2542
|
+
const loading = /* @__PURE__ */ new Map();
|
|
2543
|
+
const scriptDocument = () => {
|
|
2544
|
+
const doc = globalThis.document;
|
|
2545
|
+
if (!doc || typeof doc.createElement !== "function") return null;
|
|
2546
|
+
return doc;
|
|
2547
|
+
};
|
|
2548
|
+
/**
|
|
2549
|
+
* True when the page has a `<script>` whose `src` starts with `prefix`,
|
|
2550
|
+
* ignoring the one with id `exceptId` (the adapter's own).
|
|
2551
|
+
*/
|
|
2552
|
+
const hasScript = (prefix, exceptId) => {
|
|
2553
|
+
const doc = scriptDocument();
|
|
2554
|
+
if (!doc) return false;
|
|
2555
|
+
const except = exceptId ? `:not(#${exceptId})` : "";
|
|
2556
|
+
return Boolean(doc.querySelector(`script[src^="${prefix}"]${except}`));
|
|
1448
2557
|
};
|
|
2558
|
+
/**
|
|
2559
|
+
* Injects `src` once per page. A failed script is removed and forgotten, so
|
|
2560
|
+
* the next call retries. Returns null outside a browser.
|
|
2561
|
+
*/
|
|
2562
|
+
const loadScript = (src, id) => {
|
|
2563
|
+
const doc = scriptDocument();
|
|
2564
|
+
if (!doc) return null;
|
|
2565
|
+
const current = loading.get(src);
|
|
2566
|
+
if (current && current.element.isConnected !== false) return current.promise;
|
|
2567
|
+
const element = doc.createElement("script");
|
|
2568
|
+
element.id = id;
|
|
2569
|
+
element.async = true;
|
|
2570
|
+
element.src = src;
|
|
2571
|
+
const promise = new Promise((resolve, reject) => {
|
|
2572
|
+
element.onload = () => resolve();
|
|
2573
|
+
element.onerror = () => {
|
|
2574
|
+
element.remove();
|
|
2575
|
+
loading.delete(src);
|
|
2576
|
+
reject(/* @__PURE__ */ new Error(`Failed to load ${src}`));
|
|
2577
|
+
};
|
|
2578
|
+
});
|
|
2579
|
+
loading.set(src, {
|
|
2580
|
+
element,
|
|
2581
|
+
promise
|
|
2582
|
+
});
|
|
2583
|
+
doc.head.appendChild(element);
|
|
2584
|
+
return promise;
|
|
2585
|
+
};
|
|
2586
|
+
//#endregion
|
|
2587
|
+
//#region src/index.ts
|
|
2588
|
+
const configure = (options) => {
|
|
2589
|
+
return configureWith(runtime, options);
|
|
2590
|
+
};
|
|
2591
|
+
const track = (nameOrEvent, params, opts) => {
|
|
2592
|
+
return trackWith(runtime, nameOrEvent, params, opts);
|
|
2593
|
+
};
|
|
2594
|
+
const endSession = () => endSessionWith(runtime);
|
|
2595
|
+
const reset = () => resetWith(runtime);
|
|
2596
|
+
/** User for destinations (GA4 user_id, Meta/TikTok external_id). */
|
|
2597
|
+
const setUser = (user) => {
|
|
2598
|
+
return setUserWith(runtime, user);
|
|
2599
|
+
};
|
|
2600
|
+
/** Updates consent and propagates it to every destination. */
|
|
2601
|
+
const setConsent = (consent) => {
|
|
2602
|
+
return setConsentWith(runtime, consent);
|
|
2603
|
+
};
|
|
2604
|
+
/**
|
|
2605
|
+
* Independent analytics client: its own queue, session, timers and
|
|
2606
|
+
* adapters. The module-level functions use a shared default instance.
|
|
2607
|
+
*/
|
|
1449
2608
|
var Analytics = class {
|
|
2609
|
+
#rt = createRuntimeState();
|
|
2610
|
+
/** Settles when the constructor `configure()` finishes. */
|
|
2611
|
+
ready;
|
|
1450
2612
|
constructor(options) {
|
|
1451
|
-
if (!options)
|
|
2613
|
+
if (!options) {
|
|
2614
|
+
this.ready = Promise.resolve();
|
|
2615
|
+
return;
|
|
2616
|
+
}
|
|
1452
2617
|
if (!(options.channel_id?.trim() ?? "")) throw new Error("channel_id is required");
|
|
1453
|
-
configure(options);
|
|
2618
|
+
const ready = this.configure(options);
|
|
2619
|
+
ready.catch((error) => {
|
|
2620
|
+
const message = `configure() failed: ${errorMessage(error)}`;
|
|
2621
|
+
report(this.#rt, {
|
|
2622
|
+
level: "error",
|
|
2623
|
+
source: "configure",
|
|
2624
|
+
message,
|
|
2625
|
+
error
|
|
2626
|
+
});
|
|
2627
|
+
});
|
|
2628
|
+
this.ready = ready;
|
|
1454
2629
|
}
|
|
1455
|
-
configure =
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
|
|
1459
|
-
|
|
2630
|
+
configure = (options) => {
|
|
2631
|
+
return configureWith(this.#rt, options);
|
|
2632
|
+
};
|
|
2633
|
+
track = (nameOrEvent, params, opts) => {
|
|
2634
|
+
return trackWith(this.#rt, nameOrEvent, params, opts);
|
|
2635
|
+
};
|
|
2636
|
+
flush = () => flushWith(this.#rt);
|
|
2637
|
+
endSession = () => endSessionWith(this.#rt);
|
|
2638
|
+
reset = () => resetWith(this.#rt);
|
|
2639
|
+
setUser = (user) => setUserWith(this.#rt, user);
|
|
2640
|
+
setConsent = (consent) => {
|
|
2641
|
+
return setConsentWith(this.#rt, consent);
|
|
2642
|
+
};
|
|
1460
2643
|
};
|
|
1461
2644
|
const analytics = {
|
|
1462
2645
|
configure,
|
|
1463
2646
|
track,
|
|
1464
2647
|
flush,
|
|
1465
2648
|
endSession,
|
|
1466
|
-
reset
|
|
2649
|
+
reset,
|
|
2650
|
+
setUser,
|
|
2651
|
+
setConsent
|
|
1467
2652
|
};
|
|
1468
2653
|
//#endregion
|
|
1469
|
-
export { Analytics, FUNNEL_EVENTS, INTERACTION_EVENTS, analytics, configure, endSession, flush, isFunnelEventName, isInteractionEventName, reset, track };
|
|
2654
|
+
export { Analytics, FUNNEL_EVENTS, INTERACTION_EVENTS, SDK_VERSION, analytics, compactPayload, configure, endSession, flush, hasScript, isFunnelEventName, isInteractionEventName, loadScript, reset, setConsent, setUser, track };
|