@databuddy/sdk 2.3.2 → 2.3.22

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.
@@ -1,4 +1,5 @@
1
- import { D as DatabuddyConfig } from '../shared/@databuddy/sdk.C9b3SVYK.js';
1
+ import { D as DatabuddyConfig } from '../shared/@databuddy/sdk.BsF1xr6_.js';
2
+ export { c as clear, f as flush, d as getAnonymousId, e as getSessionId, g as getTracker, h as getTrackingIds, j as getTrackingParams, i as isTrackerAvailable, t as track, b as trackError } from '../shared/@databuddy/sdk.BsF1xr6_.js';
2
3
  import React, { ReactNode } from 'react';
3
4
  import { F as FlagsConfig, a as FeatureState, b as FlagState, c as FlagsContext } from '../shared/@databuddy/sdk.B6nwxnPC.js';
4
5
 
@@ -1,10 +1,11 @@
1
1
  'use client';
2
2
 
3
- import { i as isScriptInjected, c as createScript } from '../shared/@databuddy/sdk.F8Xt1uF7.mjs';
4
- import { d as detectClientId } from '../shared/@databuddy/sdk.BUsPV0LH.mjs';
3
+ import { detectClientId } from '../core/index.mjs';
4
+ export { clear, flush, getAnonymousId, getSessionId, getTracker, getTrackingIds, getTrackingParams, isTrackerAvailable, track, trackError } from '../core/index.mjs';
5
+ import { i as isScriptInjected, c as createScript } from '../shared/@databuddy/sdk.C8vEu9Y4.mjs';
5
6
  import React, { useRef, useMemo, useEffect, useSyncExternalStore, createContext, useContext } from 'react';
6
- import { B as BrowserFlagStorage, C as CoreFlagsManager } from '../shared/@databuddy/sdk.Du7SE7-M.mjs';
7
- import { l as logger } from '../shared/@databuddy/sdk.3kaCzyfu.mjs';
7
+ import { B as BrowserFlagStorage, C as CoreFlagsManager } from '../shared/@databuddy/sdk.DBtQ5j2L.mjs';
8
+ import { l as logger } from '../shared/@databuddy/sdk.DCKr2Zpd.mjs';
8
9
 
9
10
  function Databuddy(props) {
10
11
  const clientId = detectClientId(props.clientId);
@@ -361,4 +361,227 @@ type TrackFunction = <T extends EventName>(eventName: T, properties?: Properties
361
361
  type ScreenViewFunction = (properties?: Record<string, unknown>) => void;
362
362
  type SetGlobalPropertiesFunction = (properties: EventProperties) => void;
363
363
 
364
- export type { BaseEventProperties as B, DatabuddyConfig as D, EventProperties as E, PropertiesForEvent as P, ScreenViewFunction as S, TrackFunction as T, DatabuddyTracker as a, EventTypeMap as b, EventName as c, DataAttributes as d, SetGlobalPropertiesFunction as e };
364
+ /**
365
+ * Checks if the Databuddy tracker script has loaded and is available.
366
+ * Use this before calling tracking functions in conditional scenarios.
367
+ *
368
+ * @returns `true` if tracker is available, `false` if not loaded or on server
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * import { isTrackerAvailable, track } from "@databuddy/sdk";
373
+ *
374
+ * if (isTrackerAvailable()) {
375
+ * track("feature_used", { feature: "export" });
376
+ * }
377
+ * ```
378
+ */
379
+ declare function isTrackerAvailable(): boolean;
380
+ /**
381
+ * Returns the raw Databuddy tracker instance for advanced use cases.
382
+ * Prefer using the exported functions (`track`, `flush`, etc.) instead.
383
+ *
384
+ * @returns Tracker instance or `null` if not available
385
+ *
386
+ * @example
387
+ * ```ts
388
+ * import { getTracker, getAnonymousId, getSessionId } from "@databuddy/sdk";
389
+ *
390
+ * const tracker = getTracker();
391
+ * if (tracker) {
392
+ * // Access tracker methods
393
+ * tracker.track("event", { prop: "value" });
394
+ *
395
+ * // Get IDs using dedicated functions
396
+ * const anonId = getAnonymousId();
397
+ * const sessionId = getSessionId();
398
+ * }
399
+ * ```
400
+ */
401
+ declare function getTracker(): DatabuddyTracker | null;
402
+ /**
403
+ * Tracks a custom event with optional properties.
404
+ * Events are batched and sent efficiently to minimize network overhead.
405
+ * Safe to call on server (no-op) or before tracker loads.
406
+ *
407
+ * @param name - Event name (e.g., "button_click", "purchase", "signup")
408
+ * @param properties - Key-value pairs of event data
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * import { track } from "@databuddy/sdk";
413
+ *
414
+ * // Simple event
415
+ * track("signup_started");
416
+ *
417
+ * // Event with properties
418
+ * track("item_purchased", {
419
+ * itemId: "sku-123",
420
+ * price: 29.99,
421
+ * currency: "USD"
422
+ * });
423
+ *
424
+ * // In a React component
425
+ * function CheckoutButton() {
426
+ * return (
427
+ * <button onClick={() => track("checkout_clicked", { cartSize: 3 })}>
428
+ * Checkout
429
+ * </button>
430
+ * );
431
+ * }
432
+ * ```
433
+ */
434
+ declare function track(name: string, properties?: Record<string, unknown>): void;
435
+ /** @deprecated Use `track()` instead. Will be removed in v3.0. */
436
+ declare function trackCustomEvent(name: string, properties?: Record<string, unknown>): void;
437
+ /**
438
+ * Clears the current user session and generates new anonymous/session IDs.
439
+ * Use after logout to ensure the next user gets a fresh identity.
440
+ *
441
+ * @example
442
+ * ```ts
443
+ * import { clear } from "@databuddy/sdk";
444
+ *
445
+ * async function handleLogout() {
446
+ * await signOut();
447
+ * clear(); // Reset tracking identity
448
+ * router.push("/login");
449
+ * }
450
+ * ```
451
+ */
452
+ declare function clear(): void;
453
+ /**
454
+ * Forces all queued events to be sent immediately.
455
+ * Useful before navigation or when you need to ensure events are captured.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * import { track, flush } from "@databuddy/sdk";
460
+ *
461
+ * function handleExternalLink(url: string) {
462
+ * track("external_link_clicked", { url });
463
+ * flush(); // Ensure event is sent before leaving
464
+ * window.location.href = url;
465
+ * }
466
+ * ```
467
+ */
468
+ declare function flush(): void;
469
+ /**
470
+ * Tracks an error event. Convenience wrapper around `track("error", ...)`.
471
+ *
472
+ * @param message - Error message
473
+ * @param properties - Additional error context (filename, line number, stack trace)
474
+ *
475
+ * @example
476
+ * ```ts
477
+ * import { trackError } from "@databuddy/sdk";
478
+ *
479
+ * try {
480
+ * await riskyOperation();
481
+ * } catch (error) {
482
+ * trackError(error.message, {
483
+ * stack: error.stack,
484
+ * error_type: error.name,
485
+ * context: "checkout_flow"
486
+ * });
487
+ * }
488
+ * ```
489
+ */
490
+ declare function trackError(message: string, properties?: {
491
+ filename?: string;
492
+ lineno?: number;
493
+ colno?: number;
494
+ stack?: string;
495
+ error_type?: string;
496
+ [key: string]: string | number | boolean | null | undefined;
497
+ }): void;
498
+ /**
499
+ * Gets the anonymous user ID. Persists across sessions via localStorage.
500
+ * Useful for server-side identification or cross-domain tracking.
501
+ *
502
+ * @param urlParams - Optional URLSearchParams to check for `anonId` param (highest priority)
503
+ * @returns Anonymous ID or `null` if unavailable
504
+ *
505
+ * Priority: URL params → tracker instance → localStorage
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * import { getAnonymousId } from "@databuddy/sdk";
510
+ *
511
+ * // Get from tracker
512
+ * const anonId = getAnonymousId();
513
+ *
514
+ * // Check URL params first (for cross-domain tracking)
515
+ * const params = new URLSearchParams(window.location.search);
516
+ * const anonId = getAnonymousId(params);
517
+ *
518
+ * // Pass to server
519
+ * await fetch("/api/identify", {
520
+ * body: JSON.stringify({ anonId })
521
+ * });
522
+ * ```
523
+ */
524
+ declare function getAnonymousId(urlParams?: URLSearchParams): string | null;
525
+ /**
526
+ * Gets the current session ID. Resets after 30 min of inactivity.
527
+ * Useful for correlating events within a single browsing session.
528
+ *
529
+ * @param urlParams - Optional URLSearchParams to check for `sessionId` param (highest priority)
530
+ * @returns Session ID or `null` if unavailable
531
+ *
532
+ * Priority: URL params → tracker instance → sessionStorage
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * import { getSessionId } from "@databuddy/sdk";
537
+ *
538
+ * const sessionId = getSessionId();
539
+ * console.log("Current session:", sessionId);
540
+ * ```
541
+ */
542
+ declare function getSessionId(urlParams?: URLSearchParams): string | null;
543
+ /**
544
+ * Gets both anonymous ID and session ID in a single call.
545
+ *
546
+ * @param urlParams - Optional URLSearchParams to check for tracking params
547
+ * @returns Object with `anonId` and `sessionId` (either may be null)
548
+ *
549
+ * @example
550
+ * ```ts
551
+ * import { getTrackingIds } from "@databuddy/sdk";
552
+ *
553
+ * const { anonId, sessionId } = getTrackingIds();
554
+ *
555
+ * // Send to your backend
556
+ * await api.identify({ anonId, sessionId, userId: user.id });
557
+ * ```
558
+ */
559
+ declare function getTrackingIds(urlParams?: URLSearchParams): {
560
+ anonId: string | null;
561
+ sessionId: string | null;
562
+ };
563
+ /**
564
+ * Returns tracking IDs as a URL query string for cross-domain tracking.
565
+ * Append to URLs when linking to other domains you own.
566
+ *
567
+ * @param urlParams - Optional URLSearchParams to preserve existing params
568
+ * @returns Query string like `"anonId=xxx&sessionId=yyy"` or empty string
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * import { getTrackingParams } from "@databuddy/sdk";
573
+ *
574
+ * // Link to subdomain with tracking continuity
575
+ * const params = getTrackingParams();
576
+ * const url = `https://app.example.com/dashboard${params ? `?${params}` : ""}`;
577
+ *
578
+ * // In a component
579
+ * <a href={`https://shop.example.com?${getTrackingParams()}`}>
580
+ * Visit Shop
581
+ * </a>
582
+ * ```
583
+ */
584
+ declare function getTrackingParams(urlParams?: URLSearchParams): string;
585
+
586
+ export { trackCustomEvent as a, trackError as b, clear as c, getAnonymousId as d, getSessionId as e, flush as f, getTracker as g, getTrackingIds as h, isTrackerAvailable as i, getTrackingParams as j, track as t };
587
+ export type { BaseEventProperties as B, DatabuddyConfig as D, EventProperties as E, PropertiesForEvent as P, ScreenViewFunction as S, TrackFunction as T, EventTypeMap as k, EventName as l, DatabuddyTracker as m, DataAttributes as n, SetGlobalPropertiesFunction as o };
@@ -361,4 +361,227 @@ type TrackFunction = <T extends EventName>(eventName: T, properties?: Properties
361
361
  type ScreenViewFunction = (properties?: Record<string, unknown>) => void;
362
362
  type SetGlobalPropertiesFunction = (properties: EventProperties) => void;
363
363
 
364
- export type { BaseEventProperties as B, DatabuddyConfig as D, EventProperties as E, PropertiesForEvent as P, ScreenViewFunction as S, TrackFunction as T, DatabuddyTracker as a, EventTypeMap as b, EventName as c, DataAttributes as d, SetGlobalPropertiesFunction as e };
364
+ /**
365
+ * Checks if the Databuddy tracker script has loaded and is available.
366
+ * Use this before calling tracking functions in conditional scenarios.
367
+ *
368
+ * @returns `true` if tracker is available, `false` if not loaded or on server
369
+ *
370
+ * @example
371
+ * ```ts
372
+ * import { isTrackerAvailable, track } from "@databuddy/sdk";
373
+ *
374
+ * if (isTrackerAvailable()) {
375
+ * track("feature_used", { feature: "export" });
376
+ * }
377
+ * ```
378
+ */
379
+ declare function isTrackerAvailable(): boolean;
380
+ /**
381
+ * Returns the raw Databuddy tracker instance for advanced use cases.
382
+ * Prefer using the exported functions (`track`, `flush`, etc.) instead.
383
+ *
384
+ * @returns Tracker instance or `null` if not available
385
+ *
386
+ * @example
387
+ * ```ts
388
+ * import { getTracker, getAnonymousId, getSessionId } from "@databuddy/sdk";
389
+ *
390
+ * const tracker = getTracker();
391
+ * if (tracker) {
392
+ * // Access tracker methods
393
+ * tracker.track("event", { prop: "value" });
394
+ *
395
+ * // Get IDs using dedicated functions
396
+ * const anonId = getAnonymousId();
397
+ * const sessionId = getSessionId();
398
+ * }
399
+ * ```
400
+ */
401
+ declare function getTracker(): DatabuddyTracker | null;
402
+ /**
403
+ * Tracks a custom event with optional properties.
404
+ * Events are batched and sent efficiently to minimize network overhead.
405
+ * Safe to call on server (no-op) or before tracker loads.
406
+ *
407
+ * @param name - Event name (e.g., "button_click", "purchase", "signup")
408
+ * @param properties - Key-value pairs of event data
409
+ *
410
+ * @example
411
+ * ```ts
412
+ * import { track } from "@databuddy/sdk";
413
+ *
414
+ * // Simple event
415
+ * track("signup_started");
416
+ *
417
+ * // Event with properties
418
+ * track("item_purchased", {
419
+ * itemId: "sku-123",
420
+ * price: 29.99,
421
+ * currency: "USD"
422
+ * });
423
+ *
424
+ * // In a React component
425
+ * function CheckoutButton() {
426
+ * return (
427
+ * <button onClick={() => track("checkout_clicked", { cartSize: 3 })}>
428
+ * Checkout
429
+ * </button>
430
+ * );
431
+ * }
432
+ * ```
433
+ */
434
+ declare function track(name: string, properties?: Record<string, unknown>): void;
435
+ /** @deprecated Use `track()` instead. Will be removed in v3.0. */
436
+ declare function trackCustomEvent(name: string, properties?: Record<string, unknown>): void;
437
+ /**
438
+ * Clears the current user session and generates new anonymous/session IDs.
439
+ * Use after logout to ensure the next user gets a fresh identity.
440
+ *
441
+ * @example
442
+ * ```ts
443
+ * import { clear } from "@databuddy/sdk";
444
+ *
445
+ * async function handleLogout() {
446
+ * await signOut();
447
+ * clear(); // Reset tracking identity
448
+ * router.push("/login");
449
+ * }
450
+ * ```
451
+ */
452
+ declare function clear(): void;
453
+ /**
454
+ * Forces all queued events to be sent immediately.
455
+ * Useful before navigation or when you need to ensure events are captured.
456
+ *
457
+ * @example
458
+ * ```ts
459
+ * import { track, flush } from "@databuddy/sdk";
460
+ *
461
+ * function handleExternalLink(url: string) {
462
+ * track("external_link_clicked", { url });
463
+ * flush(); // Ensure event is sent before leaving
464
+ * window.location.href = url;
465
+ * }
466
+ * ```
467
+ */
468
+ declare function flush(): void;
469
+ /**
470
+ * Tracks an error event. Convenience wrapper around `track("error", ...)`.
471
+ *
472
+ * @param message - Error message
473
+ * @param properties - Additional error context (filename, line number, stack trace)
474
+ *
475
+ * @example
476
+ * ```ts
477
+ * import { trackError } from "@databuddy/sdk";
478
+ *
479
+ * try {
480
+ * await riskyOperation();
481
+ * } catch (error) {
482
+ * trackError(error.message, {
483
+ * stack: error.stack,
484
+ * error_type: error.name,
485
+ * context: "checkout_flow"
486
+ * });
487
+ * }
488
+ * ```
489
+ */
490
+ declare function trackError(message: string, properties?: {
491
+ filename?: string;
492
+ lineno?: number;
493
+ colno?: number;
494
+ stack?: string;
495
+ error_type?: string;
496
+ [key: string]: string | number | boolean | null | undefined;
497
+ }): void;
498
+ /**
499
+ * Gets the anonymous user ID. Persists across sessions via localStorage.
500
+ * Useful for server-side identification or cross-domain tracking.
501
+ *
502
+ * @param urlParams - Optional URLSearchParams to check for `anonId` param (highest priority)
503
+ * @returns Anonymous ID or `null` if unavailable
504
+ *
505
+ * Priority: URL params → tracker instance → localStorage
506
+ *
507
+ * @example
508
+ * ```ts
509
+ * import { getAnonymousId } from "@databuddy/sdk";
510
+ *
511
+ * // Get from tracker
512
+ * const anonId = getAnonymousId();
513
+ *
514
+ * // Check URL params first (for cross-domain tracking)
515
+ * const params = new URLSearchParams(window.location.search);
516
+ * const anonId = getAnonymousId(params);
517
+ *
518
+ * // Pass to server
519
+ * await fetch("/api/identify", {
520
+ * body: JSON.stringify({ anonId })
521
+ * });
522
+ * ```
523
+ */
524
+ declare function getAnonymousId(urlParams?: URLSearchParams): string | null;
525
+ /**
526
+ * Gets the current session ID. Resets after 30 min of inactivity.
527
+ * Useful for correlating events within a single browsing session.
528
+ *
529
+ * @param urlParams - Optional URLSearchParams to check for `sessionId` param (highest priority)
530
+ * @returns Session ID or `null` if unavailable
531
+ *
532
+ * Priority: URL params → tracker instance → sessionStorage
533
+ *
534
+ * @example
535
+ * ```ts
536
+ * import { getSessionId } from "@databuddy/sdk";
537
+ *
538
+ * const sessionId = getSessionId();
539
+ * console.log("Current session:", sessionId);
540
+ * ```
541
+ */
542
+ declare function getSessionId(urlParams?: URLSearchParams): string | null;
543
+ /**
544
+ * Gets both anonymous ID and session ID in a single call.
545
+ *
546
+ * @param urlParams - Optional URLSearchParams to check for tracking params
547
+ * @returns Object with `anonId` and `sessionId` (either may be null)
548
+ *
549
+ * @example
550
+ * ```ts
551
+ * import { getTrackingIds } from "@databuddy/sdk";
552
+ *
553
+ * const { anonId, sessionId } = getTrackingIds();
554
+ *
555
+ * // Send to your backend
556
+ * await api.identify({ anonId, sessionId, userId: user.id });
557
+ * ```
558
+ */
559
+ declare function getTrackingIds(urlParams?: URLSearchParams): {
560
+ anonId: string | null;
561
+ sessionId: string | null;
562
+ };
563
+ /**
564
+ * Returns tracking IDs as a URL query string for cross-domain tracking.
565
+ * Append to URLs when linking to other domains you own.
566
+ *
567
+ * @param urlParams - Optional URLSearchParams to preserve existing params
568
+ * @returns Query string like `"anonId=xxx&sessionId=yyy"` or empty string
569
+ *
570
+ * @example
571
+ * ```ts
572
+ * import { getTrackingParams } from "@databuddy/sdk";
573
+ *
574
+ * // Link to subdomain with tracking continuity
575
+ * const params = getTrackingParams();
576
+ * const url = `https://app.example.com/dashboard${params ? `?${params}` : ""}`;
577
+ *
578
+ * // In a component
579
+ * <a href={`https://shop.example.com?${getTrackingParams()}`}>
580
+ * Visit Shop
581
+ * </a>
582
+ * ```
583
+ */
584
+ declare function getTrackingParams(urlParams?: URLSearchParams): string;
585
+
586
+ export { trackCustomEvent as a, trackError as b, clear as c, getAnonymousId as d, getSessionId as e, flush as f, getTracker as g, getTrackingIds as h, isTrackerAvailable as i, getTrackingParams as j, track as t };
587
+ export type { BaseEventProperties as B, DatabuddyConfig as D, EventProperties as E, PropertiesForEvent as P, ScreenViewFunction as S, TrackFunction as T, EventTypeMap as k, EventName as l, DatabuddyTracker as m, DataAttributes as n, SetGlobalPropertiesFunction as o };
@@ -1,4 +1,4 @@
1
- const version = "2.3.2";
1
+ const version = "2.3.21";
2
2
 
3
3
  const INJECTED_SCRIPT_ATTRIBUTE = "data-databuddy-injected";
4
4
  function isScriptInjected() {
@@ -1,15 +1,25 @@
1
- import { l as logger, c as createCacheEntry, i as isCacheValid, b as buildQueryParams, R as RequestBatcher, a as isCacheStale, D as DEFAULT_RESULT, g as getCacheKey, f as fetchAllFlags } from './sdk.3kaCzyfu.mjs';
1
+ import { l as logger, c as createCacheEntry, i as isCacheValid, b as buildQueryParams, R as RequestBatcher, a as isCacheStale, D as DEFAULT_RESULT, g as getCacheKey, f as fetchAllFlags } from './sdk.DCKr2Zpd.mjs';
2
2
 
3
+ const isBrowser = typeof window !== "undefined" && typeof localStorage !== "undefined";
3
4
  class BrowserFlagStorage {
4
5
  ttl = 24 * 60 * 60 * 1e3;
5
6
  // 24 hours in milliseconds
6
7
  get(key) {
8
+ if (!isBrowser) {
9
+ return null;
10
+ }
7
11
  return this.getFromLocalStorage(key);
8
12
  }
9
13
  set(key, value) {
14
+ if (!isBrowser) {
15
+ return;
16
+ }
10
17
  this.setToLocalStorage(key, value);
11
18
  }
12
19
  getAll() {
20
+ if (!isBrowser) {
21
+ return {};
22
+ }
13
23
  const result = {};
14
24
  const now = Date.now();
15
25
  const keys = Object.keys(localStorage).filter(
@@ -33,6 +43,9 @@ class BrowserFlagStorage {
33
43
  return result;
34
44
  }
35
45
  clear() {
46
+ if (!isBrowser) {
47
+ return;
48
+ }
36
49
  const keys = Object.keys(localStorage).filter(
37
50
  (key) => key.startsWith("db-flag-")
38
51
  );
@@ -77,14 +90,23 @@ class BrowserFlagStorage {
77
90
  return Date.now() > expiresAt;
78
91
  }
79
92
  delete(key) {
93
+ if (!isBrowser) {
94
+ return;
95
+ }
80
96
  localStorage.removeItem(`db-flag-${key}`);
81
97
  }
82
98
  deleteMultiple(keys) {
99
+ if (!isBrowser) {
100
+ return;
101
+ }
83
102
  for (const key of keys) {
84
103
  localStorage.removeItem(`db-flag-${key}`);
85
104
  }
86
105
  }
87
106
  setAll(flags) {
107
+ if (!isBrowser) {
108
+ return;
109
+ }
88
110
  const currentFlags = this.getAll();
89
111
  const currentKeys = Object.keys(currentFlags);
90
112
  const newKeys = Object.keys(flags);
@@ -97,6 +119,9 @@ class BrowserFlagStorage {
97
119
  }
98
120
  }
99
121
  cleanupExpired() {
122
+ if (!isBrowser) {
123
+ return;
124
+ }
100
125
  const now = Date.now();
101
126
  const keys = Object.keys(localStorage).filter(
102
127
  (key) => key.startsWith("db-flag-")
@@ -181,6 +206,16 @@ class CoreFlagsManager {
181
206
  document.removeEventListener("visibilitychange", handleVisibility);
182
207
  };
183
208
  }
209
+ removeStaleKeys(validKeys, user) {
210
+ const ctx = user ?? this.config.user;
211
+ const suffix = ctx?.userId || ctx?.email ? `:${ctx.userId ?? ""}:${ctx.email ?? ""}` : "";
212
+ for (const key of this.cache.keys()) {
213
+ const belongsToUser = suffix ? key.endsWith(suffix) : !key.includes(":");
214
+ if (belongsToUser && !validKeys.has(key)) {
215
+ this.cache.delete(key);
216
+ }
217
+ }
218
+ }
184
219
  async initialize() {
185
220
  if (!this.config.skipStorage && this.storage) {
186
221
  this.loadFromStorage();
@@ -201,7 +236,10 @@ class CoreFlagsManager {
201
236
  const staleTime = this.config.staleTime ?? ttl / 2;
202
237
  for (const [key, value] of Object.entries(stored)) {
203
238
  if (value && typeof value === "object") {
204
- this.cache.set(key, createCacheEntry(value, ttl, staleTime));
239
+ this.cache.set(
240
+ key,
241
+ createCacheEntry(value, ttl, staleTime)
242
+ );
205
243
  }
206
244
  }
207
245
  if (this.cache.size > 0) {
@@ -331,13 +369,20 @@ class CoreFlagsManager {
331
369
  }
332
370
  const apiUrl = this.config.apiUrl ?? "https://api.databuddy.cc";
333
371
  const params = buildQueryParams(this.config, user);
372
+ const ttl = this.config.cacheTtl ?? 6e4;
373
+ const staleTime = this.config.staleTime ?? ttl / 2;
334
374
  try {
335
375
  const flags = await fetchAllFlags(apiUrl, params);
336
- const ttl = this.config.cacheTtl ?? 6e4;
337
- const staleTime = this.config.staleTime ?? ttl / 2;
338
- for (const [key, result] of Object.entries(flags)) {
339
- const cacheKey = getCacheKey(key, user ?? this.config.user);
340
- this.cache.set(cacheKey, createCacheEntry(result, ttl, staleTime));
376
+ const flagCacheEntries = Object.entries(flags).map(([key, result]) => ({
377
+ cacheKey: getCacheKey(key, user ?? this.config.user),
378
+ cacheEntry: createCacheEntry(result, ttl, staleTime)
379
+ }));
380
+ this.removeStaleKeys(
381
+ new Set(flagCacheEntries.map(({ cacheKey }) => cacheKey)),
382
+ user
383
+ );
384
+ for (const { cacheKey, cacheEntry } of flagCacheEntries) {
385
+ this.cache.set(cacheKey, cacheEntry);
341
386
  }
342
387
  this.ready = true;
343
388
  this.notifyUpdate();
@@ -173,7 +173,10 @@ class RequestBatcher {
173
173
  try {
174
174
  const results = await fetchFlags(this.apiUrl, keys, this.params);
175
175
  for (const [key, cbs] of callbacks) {
176
- const result = results[key] ?? { ...DEFAULT_RESULT, reason: "NOT_FOUND" };
176
+ const result = results[key] ?? {
177
+ ...DEFAULT_RESULT,
178
+ reason: "NOT_FOUND"
179
+ };
177
180
  for (const cb of cbs) {
178
181
  cb.resolve(result);
179
182
  }
@@ -1,7 +1,7 @@
1
1
  import { defineComponent, ref, onMounted, onUnmounted, watch, reactive, watchEffect, computed } from 'vue';
2
- import { i as isScriptInjected, c as createScript } from '../shared/@databuddy/sdk.F8Xt1uF7.mjs';
3
- import { B as BrowserFlagStorage, C as CoreFlagsManager } from '../shared/@databuddy/sdk.Du7SE7-M.mjs';
4
- import '../shared/@databuddy/sdk.3kaCzyfu.mjs';
2
+ import { i as isScriptInjected, c as createScript } from '../shared/@databuddy/sdk.C8vEu9Y4.mjs';
3
+ import { B as BrowserFlagStorage, C as CoreFlagsManager } from '../shared/@databuddy/sdk.DBtQ5j2L.mjs';
4
+ import '../shared/@databuddy/sdk.DCKr2Zpd.mjs';
5
5
 
6
6
  const Databuddy = defineComponent({
7
7
  props: {},
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@databuddy/sdk",
3
- "version": "2.3.2",
3
+ "version": "2.3.22",
4
4
  "description": "Official Databuddy Analytics SDK",
5
5
  "main": "./dist/core/index.mjs",
6
6
  "types": "./dist/core/index.d.ts",
@@ -1,25 +0,0 @@
1
- function detectClientId(providedClientId) {
2
- if (providedClientId) {
3
- return providedClientId;
4
- }
5
- if (typeof process !== "undefined" && process.env) {
6
- return process.env.NEXT_PUBLIC_DATABUDDY_CLIENT_ID || process.env.NUXT_PUBLIC_DATABUDDY_CLIENT_ID || process.env.VITE_DATABUDDY_CLIENT_ID || process.env.REACT_APP_DATABUDDY_CLIENT_ID;
7
- }
8
- if (typeof window !== "undefined") {
9
- const nextEnv = window.__NEXT_DATA__?.env?.NEXT_PUBLIC_DATABUDDY_CLIENT_ID;
10
- if (nextEnv) {
11
- return nextEnv;
12
- }
13
- const nuxtEnv = window.__NUXT__?.env?.NUXT_PUBLIC_DATABUDDY_CLIENT_ID;
14
- if (nuxtEnv) {
15
- return nuxtEnv;
16
- }
17
- const viteEnv = window.__VITE_ENV__?.VITE_DATABUDDY_CLIENT_ID;
18
- if (viteEnv) {
19
- return viteEnv;
20
- }
21
- }
22
- return;
23
- }
24
-
25
- export { detectClientId as d };