1+ import { logger } from "@/logger" ;
12import type { DatabuddyTracker } from "./types" ;
23
3- /**
4- * Checks if the Databuddy tracker script has loaded and is available.
5- * Use this before calling tracking functions in conditional scenarios.
6- *
7- * @returns `true` if tracker is available, `false` if not loaded or on server
8- *
9- * @example
10- * ```ts
11- * import { isTrackerAvailable, track } from "@databuddy/sdk";
12- *
13- * if (isTrackerAvailable()) {
14- * track("feature_used", { feature: "export" });
15- * }
16- * ```
17- */
4+ /** Check if the full tracker instance (`window.databuddy`) is available. */
185export function isTrackerAvailable ( ) : boolean {
19- return typeof window !== "undefined" && ( ! ! window . databuddy || ! ! window . db ) ;
6+ return typeof window !== "undefined" && ! ! window . databuddy ;
207}
218
22- /**
23- * Returns the raw Databuddy tracker instance for advanced use cases.
24- * Prefer using the exported functions (`track`, `flush`, etc.) instead.
25- *
26- * @returns Tracker instance or `null` if not available
27- *
28- * @example
29- * ```ts
30- * import { getTracker, getAnonymousId, getSessionId } from "@databuddy/sdk";
31- *
32- * const tracker = getTracker();
33- * if (tracker) {
34- * // Access tracker methods
35- * tracker.track("event", { prop: "value" });
36- *
37- * // Get IDs using dedicated functions
38- * const anonId = getAnonymousId();
39- * const sessionId = getSessionId();
40- * }
41- * ```
42- */
9+ /** Returns the `window.databuddy` tracker instance, or `null` if unavailable. */
4310export function getTracker ( ) : DatabuddyTracker | null {
4411 if ( typeof window === "undefined" ) {
4512 return null ;
4613 }
4714 return window . databuddy || null ;
4815}
4916
50- /**
51- * Tracks a custom event with optional properties.
52- * Events are batched and sent efficiently to minimize network overhead.
53- * Safe to call on server (no-op) or before tracker loads.
54- *
55- * @param name - Event name (e.g., "button_click", "purchase", "signup")
56- * @param properties - Key-value pairs of event data
57- *
58- * @example
59- * ```ts
60- * import { track } from "@databuddy/sdk";
61- *
62- * // Simple event
63- * track("signup_started");
64- *
65- * // Event with properties
66- * track("item_purchased", {
67- * itemId: "sku-123",
68- * price: 29.99,
69- * currency: "USD"
70- * });
71- *
72- * // In a React component
73- * function CheckoutButton() {
74- * return (
75- * <button onClick={() => track("checkout_clicked", { cartSize: 3 }) }>
76- * Checkout
77- * </button>
78- * );
79- * }
80- * ```
81- */
17+ /** Track a custom event. Safe to call on server (no-op) or before tracker loads. */
8218export function track (
8319 name : string ,
8420 properties ?: Record < string , unknown >
@@ -87,16 +23,15 @@ export function track(
8723 return ;
8824 }
8925
90- const tracker = window . db ?. track || window . databuddy ?. track ;
91-
92- if ( ! tracker ) {
26+ const fn = window . db ?. track || window . databuddy ?. track ;
27+ if ( ! fn ) {
9328 return ;
9429 }
9530
9631 try {
97- tracker ( name , properties ) ;
32+ fn ( name , properties ) ;
9833 } catch ( error ) {
99- console . error ( "Databuddy track error:" , error ) ;
34+ logger . error ( "track error:" , error ) ;
10035 }
10136}
10237
@@ -108,93 +43,43 @@ export function trackCustomEvent(
10843 track ( name , properties ) ;
10944}
11045
111- /**
112- * Clears the current user session and generates new anonymous/session IDs.
113- * Use after logout to ensure the next user gets a fresh identity.
114- *
115- * @example
116- * ```ts
117- * import { clear } from "@databuddy/sdk";
118- *
119- * async function handleLogout() {
120- * await signOut();
121- * clear(); // Reset tracking identity
122- * router.push("/login");
123- * }
124- * ```
125- */
46+ /** Reset user session — generates new anonymous and session IDs. Call after logout. */
12647export function clear ( ) : void {
12748 if ( typeof window === "undefined" ) {
12849 return ;
12950 }
13051
131- const tracker = window . db ?. clear || window . databuddy ?. clear ;
132-
133- if ( ! tracker ) {
52+ const fn = window . db ?. clear || window . databuddy ?. clear ;
53+ if ( ! fn ) {
13454 return ;
13555 }
13656
13757 try {
138- tracker ( ) ;
58+ fn ( ) ;
13959 } catch ( error ) {
140- console . error ( "Databuddy clear error:" , error ) ;
60+ logger . error ( "clear error:" , error ) ;
14161 }
14262}
14363
144- /**
145- * Forces all queued events to be sent immediately.
146- * Useful before navigation or when you need to ensure events are captured.
147- *
148- * @example
149- * ```ts
150- * import { track, flush } from "@databuddy/sdk";
151- *
152- * function handleExternalLink(url: string) {
153- * track("external_link_clicked", { url });
154- * flush(); // Ensure event is sent before leaving
155- * window.location.href = url;
156- * }
157- * ```
158- */
64+ /** Force send all queued events. Call before navigating to external sites. */
15965export function flush ( ) : void {
16066 if ( typeof window === "undefined" ) {
16167 return ;
16268 }
16369
164- const tracker = window . db ?. flush || window . databuddy ?. flush ;
165-
166- if ( ! tracker ) {
70+ const fn = window . db ?. flush || window . databuddy ?. flush ;
71+ if ( ! fn ) {
16772 return ;
16873 }
16974
17075 try {
171- tracker ( ) ;
76+ fn ( ) ;
17277 } catch ( error ) {
173- console . error ( "Databuddy flush error:" , error ) ;
78+ logger . error ( "flush error:" , error ) ;
17479 }
17580}
17681
177- /**
178- * Tracks an error event. Convenience wrapper around `track("error", ...)`.
179- *
180- * @param message - Error message
181- * @param properties - Additional error context (filename, line number, stack trace)
182- *
183- * @example
184- * ```ts
185- * import { trackError } from "@databuddy/sdk";
186- *
187- * try {
188- * await riskyOperation();
189- * } catch (error) {
190- * trackError(error.message, {
191- * stack: error.stack,
192- * error_type: error.name,
193- * context: "checkout_flow"
194- * });
195- * }
196- * ```
197- */
82+ /** Convenience wrapper: `track('error', { message, ...properties })` */
19883export function trackError (
19984 message : string ,
20085 properties ?: {
@@ -209,56 +94,15 @@ export function trackError(
20994 track ( "error" , { message, ...properties } ) ;
21095}
21196
212- /**
213- * Gets the anonymous user ID. Persists across sessions via localStorage.
214- * Useful for server-side identification or cross-domain tracking.
215- *
216- * @param urlParams - Optional URLSearchParams to check for `anonId` param (highest priority)
217- * @returns Anonymous ID or `null` if unavailable
218- *
219- * Priority: URL params → tracker instance → localStorage
220- *
221- * @example
222- * ```ts
223- * import { getAnonymousId } from "@databuddy/sdk";
224- *
225- * // Get from tracker
226- * const anonId = getAnonymousId();
227- *
228- * // Check URL params first (for cross-domain tracking)
229- * const params = new URLSearchParams(window.location.search);
230- * const anonId = getAnonymousId(params);
231- *
232- * // Pass to server
233- * await fetch("/api/identify", {
234- * body: JSON.stringify({ anonId })
235- * });
236- * ```
237- */
97+ /** Get anonymous user ID. Priority: URL params → localStorage. Persists across sessions. */
23898export function getAnonymousId ( urlParams ?: URLSearchParams ) : string | null {
23999 if ( typeof window === "undefined" ) {
240100 return null ;
241101 }
242102 return urlParams ?. get ( "anonId" ) || localStorage . getItem ( "did" ) || null ;
243103}
244104
245- /**
246- * Gets the current session ID. Resets after 30 min of inactivity.
247- * Useful for correlating events within a single browsing session.
248- *
249- * @param urlParams - Optional URLSearchParams to check for `sessionId` param (highest priority)
250- * @returns Session ID or `null` if unavailable
251- *
252- * Priority: URL params → tracker instance → sessionStorage
253- *
254- * @example
255- * ```ts
256- * import { getSessionId } from "@databuddy/sdk";
257- *
258- * const sessionId = getSessionId();
259- * console.log("Current session:", sessionId);
260- * ```
261- */
105+ /** Get current session ID. Priority: URL params → sessionStorage. Resets after 30 min inactivity. */
262106export function getSessionId ( urlParams ?: URLSearchParams ) : string | null {
263107 if ( typeof window === "undefined" ) {
264108 return null ;
@@ -268,22 +112,7 @@ export function getSessionId(urlParams?: URLSearchParams): string | null {
268112 ) ;
269113}
270114
271- /**
272- * Gets both anonymous ID and session ID in a single call.
273- *
274- * @param urlParams - Optional URLSearchParams to check for tracking params
275- * @returns Object with `anonId` and `sessionId` (either may be null)
276- *
277- * @example
278- * ```ts
279- * import { getTrackingIds } from "@databuddy/sdk";
280- *
281- * const { anonId, sessionId } = getTrackingIds();
282- *
283- * // Send to your backend
284- * await api.identify({ anonId, sessionId, userId: user.id });
285- * ```
286- */
115+ /** Get both anonymous ID and session ID in one call. */
287116export function getTrackingIds ( urlParams ?: URLSearchParams ) : {
288117 anonId : string | null ;
289118 sessionId : string | null ;
@@ -294,27 +123,7 @@ export function getTrackingIds(urlParams?: URLSearchParams): {
294123 } ;
295124}
296125
297- /**
298- * Returns tracking IDs as a URL query string for cross-domain tracking.
299- * Append to URLs when linking to other domains you own.
300- *
301- * @param urlParams - Optional URLSearchParams to preserve existing params
302- * @returns Query string like `"anonId=xxx&sessionId=yyy"` or empty string
303- *
304- * @example
305- * ```ts
306- * import { getTrackingParams } from "@databuddy/sdk";
307- *
308- * // Link to subdomain with tracking continuity
309- * const params = getTrackingParams();
310- * const url = `https://app.example.com/dashboard${params ? `?${params}` : "" }`;
311- *
312- * // In a component
313- * <a href={`https://shop.example.com?${getTrackingParams()}` }>
314- * Visit Shop
315- * </a>
316- * ```
317- */
126+ /** Returns tracking IDs as a URL query string for cross-domain tracking. */
318127export function getTrackingParams ( urlParams ?: URLSearchParams ) : string {
319128 const anonId = getAnonymousId ( urlParams ) ;
320129 const sessionId = getSessionId ( urlParams ) ;
0 commit comments