-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
72 lines (63 loc) · 1.88 KB
/
index.js
File metadata and controls
72 lines (63 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
const VERSION = "1.1.0";
const endpoint = () => {
if (typeof process !== "undefined") return process.env?.TELESINK_ENDPOINT;
if (typeof window !== "undefined") return window.TELESINK_ENDPOINT;
return null;
};
const enabled = () => {
if (typeof process !== "undefined") return !process.env?.TELESINK_DISABLED;
if (typeof window !== "undefined") return !window.TELESINK_DISABLED;
return true;
};
const uuid = () =>
typeof crypto !== "undefined" && crypto.randomUUID
? crypto.randomUUID()
: "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
return (c === "x" ? r : (r & 0x3) | 0x8).toString(16);
});
const track = async ({
event,
text,
emoji,
properties = {},
occurredAt,
idempotencyKey,
endpoint: overrideEndpoint,
} = {}) => {
const finalEndpoint = overrideEndpoint ?? endpoint();
if (!enabled() || !finalEndpoint) return false;
const payload = Object.fromEntries(
Object.entries({
event,
text,
emoji,
properties,
occurred_at: new Date(occurredAt ?? Date.now()).toISOString(),
idempotency_key: idempotencyKey ?? uuid(),
sdk: { name: "telesink", version: VERSION },
}).filter(([, v]) => v != null),
);
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 3000);
try {
const res = await fetch(finalEndpoint, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": `telesink.javascript/${VERSION}`,
"Idempotency-Key": payload.idempotency_key,
},
body: JSON.stringify(payload),
signal: controller.signal,
});
return res.ok;
} catch (e) {
console.error(`[Telesink] ${e.constructor.name}: ${e.message}`);
return false;
} finally {
clearTimeout(timeout);
}
};
export { track };
export default { track };