@telemetry-tracker/core 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,32 @@
1
+ import { SDK_VERSION } from "./version.js";
2
+ export { SDK_VERSION };
3
+ export declare function getAnonymousId(): string;
4
+ export type TelemetryConfig = {
5
+ ingestUrl: string;
6
+ app: string;
7
+ /** Project API key (`tt_live_<publicId>_<secret>`). Required in production ingest. */
8
+ apiKey?: string;
9
+ platform?: string;
10
+ environment?: string;
11
+ release?: string;
12
+ /** Flush interval in ms. Default 5000. Set 0 to disable batching. */
13
+ batchInterval?: number;
14
+ /** Max queue size before flush. Default 10. */
15
+ batchSize?: number;
16
+ };
17
+ export declare function getSessionId(): string | null;
18
+ /** End the current session and clear the in-memory session id. */
19
+ export declare function endSession(): void;
20
+ export declare function init(c: TelemetryConfig): void;
21
+ export declare function identify(id: string | null): void;
22
+ /** Headers for ingest POST requests (Authorization + Content-Type). */
23
+ export declare function buildIngestHeaders(cfg: Pick<TelemetryConfig, "apiKey">): Record<string, string>;
24
+ export declare function trackEvent(name: string, properties?: Record<string, unknown>): void;
25
+ export declare function trackError(error: Error | {
26
+ message: string;
27
+ stack?: string;
28
+ }, context?: Record<string, unknown>): void;
29
+ export declare function screen(name: string): void;
30
+ export declare function getUserId(): string | null;
31
+ export declare function getConfigOrNull(): TelemetryConfig | null;
32
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAE3C,OAAO,EAAE,WAAW,EAAE,CAAC;AAiBvB,wBAAgB,cAAc,IAAI,MAAM,CAkBvC;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,SAAS,EAAE,MAAM,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,sFAAsF;IACtF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,qEAAqE;IACrE,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,+CAA+C;IAC/C,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,CAAC;AA6GF,wBAAgB,YAAY,IAAI,MAAM,GAAG,IAAI,CAE5C;AAED,kEAAkE;AAClE,wBAAgB,UAAU,IAAI,IAAI,CAOjC;AA4CD,wBAAgB,IAAI,CAAC,CAAC,EAAE,eAAe,GAAG,IAAI,CAgB7C;AAED,wBAAgB,QAAQ,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAEhD;AAYD,uEAAuE;AACvE,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,IAAI,CAAC,eAAe,EAAE,QAAQ,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAO/F;AA4DD,wBAAgB,UAAU,CACxB,IAAI,EAAE,MAAM,EACZ,UAAU,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACnC,IAAI,CAqBN;AAED,wBAAgB,UAAU,CACxB,KAAK,EAAE,KAAK,GAAG;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,EAClD,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAChC,IAAI,CAcN;AAED,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAEzC;AAED,wBAAgB,SAAS,IAAI,MAAM,GAAG,IAAI,CAEzC;AAED,wBAAgB,eAAe,IAAI,eAAe,GAAG,IAAI,CAExD"}
package/dist/index.js ADDED
@@ -0,0 +1,324 @@
1
+ const REPORTED = Symbol.for("telemetry.reported");
2
+ import { SDK_VERSION } from "./version.js";
3
+ export { SDK_VERSION };
4
+ const ANON_STORAGE_KEY = "tacko_telemetry_anon_id";
5
+ let anonymousId = null;
6
+ function generateUUID() {
7
+ if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
8
+ return crypto.randomUUID();
9
+ }
10
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
11
+ const r = (Math.random() * 16) | 0;
12
+ const v = c === "x" ? r : (r & 0x3) | 0x8;
13
+ return v.toString(16);
14
+ });
15
+ }
16
+ export function getAnonymousId() {
17
+ if (anonymousId)
18
+ return anonymousId;
19
+ if (typeof localStorage !== "undefined") {
20
+ try {
21
+ const stored = localStorage.getItem(ANON_STORAGE_KEY);
22
+ if (stored) {
23
+ anonymousId = stored;
24
+ return anonymousId;
25
+ }
26
+ }
27
+ catch (_) { }
28
+ }
29
+ anonymousId = generateUUID();
30
+ if (typeof localStorage !== "undefined") {
31
+ try {
32
+ localStorage.setItem(ANON_STORAGE_KEY, anonymousId);
33
+ }
34
+ catch (_) { }
35
+ }
36
+ return anonymousId;
37
+ }
38
+ let config = null;
39
+ let userId = null;
40
+ let browserHandlersInstalled = false;
41
+ let sessionLifecycleInstalled = false;
42
+ let sessionId = null;
43
+ let sessionStartedAt = null;
44
+ const DEFAULT_BATCH_INTERVAL = 5000;
45
+ const DEFAULT_BATCH_SIZE = 10;
46
+ const eventQueue = [];
47
+ let flushTimer = null;
48
+ function ensureUrlFromCfg(cfg, path) {
49
+ const base = cfg.ingestUrl.replace(/\/$/, "");
50
+ return `${base}${path}`;
51
+ }
52
+ function buildSessionPayload(cfg, endedAt) {
53
+ return {
54
+ session_id: sessionId,
55
+ app: cfg.app,
56
+ platform: cfg.platform ?? undefined,
57
+ environment: cfg.environment ?? undefined,
58
+ user_id: userId ?? undefined,
59
+ anonymous_id: getAnonymousId(),
60
+ sdk_version: SDK_VERSION,
61
+ started_at: sessionStartedAt?.toISOString(),
62
+ ended_at: endedAt?.toISOString(),
63
+ };
64
+ }
65
+ async function postSession(cfg, endedAt) {
66
+ if (!sessionId)
67
+ return;
68
+ try {
69
+ const res = await fetch(ensureUrlFromCfg(cfg, "/ingest/session"), {
70
+ method: "POST",
71
+ headers: buildIngestHeaders(cfg),
72
+ body: JSON.stringify(buildSessionPayload(cfg, endedAt)),
73
+ });
74
+ if (!res.ok) {
75
+ console.warn("[telemetry] session ingest failed:", res.status, await res.text());
76
+ }
77
+ }
78
+ catch (e) {
79
+ console.warn("[telemetry] session send error:", e);
80
+ }
81
+ }
82
+ function postSessionKeepalive(endedAt) {
83
+ const cfg = getConfigOrNull();
84
+ if (!cfg || !sessionId)
85
+ return;
86
+ try {
87
+ void fetch(ensureUrlFromCfg(cfg, "/ingest/session"), {
88
+ method: "POST",
89
+ headers: buildIngestHeaders(cfg),
90
+ body: JSON.stringify(buildSessionPayload(cfg, endedAt)),
91
+ keepalive: true,
92
+ });
93
+ }
94
+ catch (_) { }
95
+ }
96
+ /** End the current session via keepalive POST and clear in-memory session state. */
97
+ function closeSessionKeepalive(endedAt) {
98
+ if (!sessionId)
99
+ return;
100
+ postSessionKeepalive(endedAt);
101
+ sessionId = null;
102
+ sessionStartedAt = null;
103
+ }
104
+ function startSession() {
105
+ sessionId = generateUUID();
106
+ sessionStartedAt = new Date();
107
+ const cfg = getConfigOrNull();
108
+ if (cfg) {
109
+ void postSession(cfg);
110
+ }
111
+ }
112
+ function installBrowserSessionLifecycle() {
113
+ if (sessionLifecycleInstalled)
114
+ return;
115
+ if (typeof window === "undefined" ||
116
+ typeof window.addEventListener !== "function" ||
117
+ typeof document === "undefined")
118
+ return;
119
+ sessionLifecycleInstalled = true;
120
+ window.addEventListener("pagehide", (event) => {
121
+ if (event.persisted)
122
+ return;
123
+ closeSessionKeepalive(new Date());
124
+ });
125
+ window.addEventListener("pageshow", (event) => {
126
+ if (event.persisted)
127
+ return;
128
+ if (!sessionId) {
129
+ startSession();
130
+ }
131
+ });
132
+ }
133
+ export function getSessionId() {
134
+ return sessionId;
135
+ }
136
+ /** End the current session and clear the in-memory session id. */
137
+ export function endSession() {
138
+ const cfg = getConfigOrNull();
139
+ if (!cfg || !sessionId)
140
+ return;
141
+ const ended = new Date();
142
+ void postSession(cfg, ended);
143
+ sessionId = null;
144
+ sessionStartedAt = null;
145
+ }
146
+ /** Only install in real browser environments; skip in React Native / Node even if `window` is polyfilled. */
147
+ function installBrowserErrorHandlers() {
148
+ if (browserHandlersInstalled)
149
+ return;
150
+ if (typeof window === "undefined" ||
151
+ typeof window.addEventListener !== "function")
152
+ return;
153
+ browserHandlersInstalled = true;
154
+ window.onerror = (message, source, lineno, colno, error) => {
155
+ const cfg = getConfigOrNull();
156
+ if (!cfg)
157
+ return false;
158
+ const err = error && error instanceof Error
159
+ ? error
160
+ : new Error(typeof message === "string" ? message : String(message));
161
+ trackError(err, {
162
+ source: "window.onerror",
163
+ filename: source,
164
+ lineno,
165
+ colno,
166
+ });
167
+ return false; // let other handlers run
168
+ };
169
+ window.addEventListener("unhandledrejection", (event) => {
170
+ const cfg = getConfigOrNull();
171
+ if (!cfg)
172
+ return;
173
+ const reason = event.reason;
174
+ const err = reason instanceof Error ? reason : new Error(reason != null ? String(reason) : "Unhandled rejection");
175
+ trackError(err, { source: "unhandledrejection" });
176
+ });
177
+ }
178
+ export function init(c) {
179
+ if (sessionId) {
180
+ endSession();
181
+ }
182
+ config = { ...c };
183
+ warnIfMissingApiKey(config);
184
+ getAnonymousId(); // ensure anonymous id exists and is persisted (browser) or set in memory (Node)
185
+ const interval = c.batchInterval ?? DEFAULT_BATCH_INTERVAL;
186
+ if (interval > 0 && typeof setInterval !== "undefined") {
187
+ flushTimer = setInterval(flushEvents, interval);
188
+ const t = flushTimer;
189
+ if (typeof t.unref === "function")
190
+ t.unref();
191
+ }
192
+ installBrowserErrorHandlers();
193
+ startSession();
194
+ installBrowserSessionLifecycle();
195
+ }
196
+ export function identify(id) {
197
+ userId = id;
198
+ }
199
+ function getConfig() {
200
+ if (!config)
201
+ throw new Error("telemetry-core: init() must be called first");
202
+ return config;
203
+ }
204
+ function ensureUrl(url) {
205
+ const base = getConfig().ingestUrl.replace(/\/$/, "");
206
+ return `${base}${url}`;
207
+ }
208
+ /** Headers for ingest POST requests (Authorization + Content-Type). */
209
+ export function buildIngestHeaders(cfg) {
210
+ const headers = { "Content-Type": "application/json" };
211
+ const key = cfg.apiKey?.trim();
212
+ if (key) {
213
+ headers.Authorization = `Bearer ${key}`;
214
+ }
215
+ return headers;
216
+ }
217
+ function warnIfMissingApiKey(cfg) {
218
+ if (cfg.apiKey?.trim())
219
+ return;
220
+ const env = cfg.environment?.toLowerCase();
221
+ if (env === "development" || env === "dev" || env === "test")
222
+ return;
223
+ console.warn("[telemetry] apiKey is not set — ingest requests will fail unless the server allows unauthenticated ingest.");
224
+ }
225
+ async function send(path, body) {
226
+ const cfg = getConfig();
227
+ try {
228
+ const res = await fetch(ensureUrl(path), {
229
+ method: "POST",
230
+ headers: buildIngestHeaders(cfg),
231
+ body: JSON.stringify({
232
+ ...body,
233
+ app: cfg.app,
234
+ platform: cfg.platform ?? undefined,
235
+ environment: cfg.environment ?? undefined,
236
+ release: cfg.release ?? undefined,
237
+ anonymous_id: getAnonymousId(),
238
+ sdk_version: SDK_VERSION,
239
+ }),
240
+ });
241
+ if (!res.ok) {
242
+ console.warn("[telemetry] ingest failed:", res.status, await res.text());
243
+ }
244
+ }
245
+ catch (e) {
246
+ console.warn("[telemetry] send error:", e);
247
+ }
248
+ }
249
+ function flushEvents() {
250
+ const cfg = getConfigOrNull();
251
+ if (!cfg || eventQueue.length === 0)
252
+ return;
253
+ const batch = eventQueue.splice(0, eventQueue.length);
254
+ const base = cfg.ingestUrl.replace(/\/$/, "");
255
+ const anonId = getAnonymousId();
256
+ const events = batch.map((e) => ({
257
+ app: cfg.app,
258
+ platform: cfg.platform,
259
+ environment: cfg.environment,
260
+ release: cfg.release,
261
+ name: e.name,
262
+ user_id: e.user_id ?? undefined,
263
+ session_id: e.session_id,
264
+ anonymous_id: anonId,
265
+ sdk_version: SDK_VERSION,
266
+ properties: e.properties,
267
+ }));
268
+ fetch(`${base}/ingest/batch`, {
269
+ method: "POST",
270
+ headers: buildIngestHeaders(cfg),
271
+ body: JSON.stringify({ events }),
272
+ }).catch((e) => console.warn("[telemetry] batch send error:", e));
273
+ }
274
+ export function trackEvent(name, properties) {
275
+ const cfg = getConfigOrNull();
276
+ const interval = cfg?.batchInterval ?? DEFAULT_BATCH_INTERVAL;
277
+ const batchSize = cfg?.batchSize ?? DEFAULT_BATCH_SIZE;
278
+ const item = {
279
+ name,
280
+ user_id: userId,
281
+ session_id: sessionId ?? undefined,
282
+ properties: properties ?? undefined,
283
+ };
284
+ if (interval > 0 && typeof setInterval !== "undefined") {
285
+ eventQueue.push(item);
286
+ if (eventQueue.length >= batchSize)
287
+ flushEvents();
288
+ }
289
+ else {
290
+ send("/ingest/event", {
291
+ name: item.name,
292
+ user_id: item.user_id ?? undefined,
293
+ session_id: item.session_id,
294
+ properties: item.properties,
295
+ }).catch(() => { });
296
+ }
297
+ }
298
+ export function trackError(error, context) {
299
+ if (!getConfigOrNull())
300
+ return;
301
+ const err = error instanceof Error ? error : { message: error.message, stack: error.stack };
302
+ if (err && typeof err === "object" && err[REPORTED])
303
+ return;
304
+ const message = err instanceof Error ? err.message : err.message;
305
+ const stack = err instanceof Error ? err.stack : err.stack;
306
+ if (err instanceof Error)
307
+ err[REPORTED] = true;
308
+ send("/ingest/error", {
309
+ message,
310
+ stack: stack ?? undefined,
311
+ context: context ?? undefined,
312
+ user_id: userId ?? undefined,
313
+ session_id: sessionId ?? undefined,
314
+ }).catch(() => { });
315
+ }
316
+ export function screen(name) {
317
+ trackEvent("$screen", { name });
318
+ }
319
+ export function getUserId() {
320
+ return userId;
321
+ }
322
+ export function getConfigOrNull() {
323
+ return config;
324
+ }
@@ -0,0 +1,3 @@
1
+ /** Injected at build time from package.json. Do not edit manually. */
2
+ export declare const SDK_VERSION = "1.3.0";
3
+ //# sourceMappingURL=version.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"version.d.ts","sourceRoot":"","sources":["../src/version.ts"],"names":[],"mappings":"AAAA,sEAAsE;AACtE,eAAO,MAAM,WAAW,UAAU,CAAC"}
@@ -0,0 +1,2 @@
1
+ /** Injected at build time from package.json. Do not edit manually. */
2
+ export const SDK_VERSION = "1.3.0";
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@telemetry-tracker/core",
3
+ "version": "1.3.0",
4
+ "description": "Lightweight telemetry client: events, errors, sessions. Framework-agnostic core.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://github.com/Telemetry-Tracker/telemetry-tracker.git",
9
+ "directory": "packages/telemetry-core"
10
+ },
11
+ "type": "module",
12
+ "main": "dist/index.js",
13
+ "types": "dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "import": "./dist/index.js",
17
+ "types": "./dist/index.d.ts"
18
+ }
19
+ },
20
+ "files": [
21
+ "dist"
22
+ ],
23
+ "keywords": [
24
+ "telemetry",
25
+ "analytics",
26
+ "events",
27
+ "errors",
28
+ "tracking"
29
+ ],
30
+ "devDependencies": {
31
+ "typescript": "^5.6.3",
32
+ "vitest": "^3.2.6"
33
+ },
34
+ "scripts": {
35
+ "build": "node scripts/inject-version.cjs && rm -rf dist && tsc",
36
+ "dev": "tsc --watch",
37
+ "test": "vitest run"
38
+ }
39
+ }