@temps-sdk/react-analytics 0.0.9 → 0.1.0-beta.64

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 CHANGED
@@ -311,6 +311,10 @@ function PricingSection() {
311
311
  | `once` | `boolean` | `true` | Track only the first time |
312
312
  | `enabled` | `boolean` | `true` | Enable/disable tracking |
313
313
 
314
+ ### `useFlag(key, fallback)` / `useFlagVariant(key)` / `useFeatureFlags()`
315
+
316
+ Feature flag reads; see [Feature Flags](#feature-flags).
317
+
314
318
  ### `useSessionRecording()`
315
319
 
316
320
  Control session recording programmatically from within the provider.
@@ -361,6 +365,73 @@ const track = useAnalytics({
361
365
  });
362
366
  ```
363
367
 
368
+ ## Feature Flags
369
+
370
+ Read Temps feature flags marked **Expose to browsers**. The server evaluates
371
+ them for the visitor (targeting rules, percentage rollouts, variants) and sends
372
+ only the results to your own origin (`POST /api/_temps/flags`). Nothing is
373
+ fetched until a component first reads a flag.
374
+
375
+ ```tsx
376
+ import { useFlag, useFlagVariant, useFeatureFlags } from "@temps-sdk/react-analytics";
377
+
378
+ function Checkout() {
379
+ // The fallback until flags arrive, or if the flag is unknown or of another type.
380
+ const newCheckout = useFlag("checkout.v2", false);
381
+ const pricing = useFlagVariant("pricing.page"); // "control" | "test" | null
382
+ const { status, reload } = useFeatureFlags(); // "idle" | "loading" | "ready" | "error"
383
+ return newCheckout ? <CheckoutV2 /> : <CheckoutV1 />;
384
+ }
385
+ ```
386
+
387
+ Target a signed-in user instead of the anonymous visitor, and avoid a flash of
388
+ the wrong value by passing server-rendered values:
389
+
390
+ ```tsx
391
+ <TempsAnalyticsProvider
392
+ flags={{
393
+ key: user.id,
394
+ attributes: { plan: user.plan },
395
+ bootstrap: { "checkout.v2": true },
396
+ }}
397
+ >
398
+ ```
399
+
400
+ or call `reload({ key: user.id })` from `useFeatureFlags()` after sign-in.
401
+
402
+ When a flag has exposure recording turned on, the first read of each served
403
+ variant on a page sends a `flag_exposure` event (`flag_key`, `variant`,
404
+ `reason`). Flags keep working when analytics is off for localhost; only
405
+ `disabled` turns them off.
406
+
407
+ ## Surveys
408
+
409
+ Show in-app surveys defined in the Temps console (**Analytics → Surveys**).
410
+ Place `<TempsSurveys />` once inside the provider; it fetches the surveys this
411
+ visitor should see from your own origin (`POST /api/_temps/surveys`) and opens
412
+ the built-in widget when one's page, event and once-per-visitor conditions
413
+ are met.
414
+
415
+ ```tsx
416
+ import { TempsAnalyticsProvider, TempsSurveys } from "@temps-sdk/react-analytics";
417
+ import { usePathname } from "next/navigation";
418
+
419
+ export function Providers({ children }: { children: React.ReactNode }) {
420
+ return (
421
+ <TempsAnalyticsProvider>
422
+ {children}
423
+ {/* visitorKey and attributes feed sampling and flag conditions. */}
424
+ <TempsSurveys pathname={usePathname()} visitorKey={user?.id} />
425
+ </TempsAnalyticsProvider>
426
+ );
427
+ }
428
+ ```
429
+
430
+ A survey with a triggering event opens when you call `trackEvent` with that
431
+ name. Answers are recorded as `survey_shown`, `survey_dismissed` and
432
+ `survey_sent` events, so surveys only appear where analytics is enabled (not
433
+ on localhost unless `ignoreLocalhost={false}`).
434
+
364
435
  ## Session Recording
365
436
 
366
437
  Session recording captures DOM mutations and user interactions using [rrweb](https://www.rrweb.io/) and streams them to your Temps instance for replay.
@@ -1,5 +1,7 @@
1
1
  import type { ReactElement } from "react";
2
2
  import type { AnalyticsContextValue, TempsAnalyticsProviderProps } from "./types";
3
- export declare function TempsAnalyticsProvider({ basePath, disabled, ignoreLocalhost, autoTrackPageviews, autoTrackPageLeave, pageLeaveEventName, autoTrackSpeedAnalytics, autoTrackEngagement, heartbeatInterval, inactivityTimeout, engagementThreshold, enableSessionRecording, sessionRecordingConfig, domain, ingestKey, children, }: TempsAnalyticsProviderProps): ReactElement;
3
+ /** Window event dispatched for every tracked custom event, `{ detail: { name } }`. */
4
+ export declare const TRACK_EVENT = "temps:track";
5
+ export declare function TempsAnalyticsProvider({ basePath, disabled, ignoreLocalhost, autoTrackPageviews, autoTrackPageLeave, pageLeaveEventName, autoTrackSpeedAnalytics, autoTrackEngagement, heartbeatInterval, inactivityTimeout, engagementThreshold, enableSessionRecording, sessionRecordingConfig, domain, ingestKey, autoTrackOutboundLinks, autoTrackFileDownloads, fileDownloadExtensions, autoTrackNotFound, cookieless, flags: flagOptions, children, }: TempsAnalyticsProviderProps): ReactElement;
4
6
  export declare function useTempsAnalytics(): AnalyticsContextValue;
5
7
  //# sourceMappingURL=Provider.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"Provider.d.ts","sourceRoot":"","sources":["../src/Provider.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,KAAK,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAUlF,wBAAgB,sBAAsB,CAAC,EACrC,QAA4B,EAC5B,QAAgB,EAChB,eAAsB,EACtB,kBAAyB,EACzB,kBAAyB,EACzB,kBAAiC,EACjC,uBAA8B,EAC9B,mBAA0B,EAC1B,iBAAyB,EACzB,iBAAyB,EACzB,mBAA2B,EAC3B,sBAA8B,EAC9B,sBAA2B,EAC3B,MAAM,EACN,SAAS,EACT,QAAQ,GACT,EAAE,2BAA2B,GAAG,YAAY,CAsO5C;AAED,wBAAgB,iBAAiB,IAAI,qBAAqB,CAMzD"}
1
+ {"version":3,"file":"Provider.d.ts","sourceRoot":"","sources":["../src/Provider.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,OAAO,CAAC;AAC1C,OAAO,KAAK,EAAE,qBAAqB,EAAE,2BAA2B,EAAE,MAAM,SAAS,CAAC;AAqBlF,sFAAsF;AACtF,eAAO,MAAM,WAAW,gBAAgB,CAAC;AAIzC,wBAAgB,sBAAsB,CAAC,EACrC,QAA4B,EAC5B,QAAgB,EAChB,eAAsB,EACtB,kBAAyB,EACzB,kBAAyB,EACzB,kBAAiC,EACjC,uBAA8B,EAC9B,mBAA0B,EAC1B,iBAAyB,EACzB,iBAAyB,EACzB,mBAA2B,EAC3B,sBAA8B,EAC9B,sBAA2B,EAC3B,MAAM,EACN,SAAS,EACT,sBAA6B,EAC7B,sBAA6B,EAC7B,sBAAsB,EACtB,iBAAwB,EACxB,UAAkB,EAClB,KAAK,EAAE,WAAW,EAClB,QAAQ,GACT,EAAE,2BAA2B,GAAG,YAAY,CA8V5C;AAED,wBAAgB,iBAAiB,IAAI,qBAAqB,CAMzD"}
package/dist/Provider.js CHANGED
@@ -9,8 +9,16 @@ import { EngagementTracker } from "./EngagementTracker";
9
9
  import { SessionRecorder } from "./SessionRecorder";
10
10
  import { SessionRecordingProvider, useSessionRecordingControl } from "./useSessionRecording";
11
11
  import { DEFAULT_BASE_PATH } from "./constants";
12
+ import { FeatureFlags, NOT_FOUND_EVENT, NotFoundMarkerWatcher, enableCookielessIdentity, exposureEventData, getStoredVisitorId, identifyVisitor, isCookielessIdentity, notFoundEventData, resetVisitor, setupLinkTracking, } from "@temps-sdk/analytics-core";
13
+ /** Window event dispatched for every tracked custom event, `{ detail: { name } }`. */
14
+ export const TRACK_EVENT = "temps:track";
12
15
  const AnalyticsContext = createContext(undefined);
13
- export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled = false, ignoreLocalhost = true, autoTrackPageviews = true, autoTrackPageLeave = true, pageLeaveEventName = "page_leave", autoTrackSpeedAnalytics = true, autoTrackEngagement = true, heartbeatInterval = 30000, inactivityTimeout = 30000, engagementThreshold = 10000, enableSessionRecording = false, sessionRecordingConfig = {}, domain, ingestKey, children, }) {
16
+ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled = false, ignoreLocalhost = true, autoTrackPageviews = true, autoTrackPageLeave = true, pageLeaveEventName = "page_leave", autoTrackSpeedAnalytics = true, autoTrackEngagement = true, heartbeatInterval = 30000, inactivityTimeout = 30000, engagementThreshold = 10000, enableSessionRecording = false, sessionRecordingConfig = {}, domain, ingestKey, autoTrackOutboundLinks = true, autoTrackFileDownloads = true, fileDownloadExtensions, autoTrackNotFound = true, cookieless = false, flags: flagOptions, children, }) {
17
+ // Cookieless mode (ADR 109 D3) is switched on during render, not in an
18
+ // effect: children's effects run before this component's, and one of them
19
+ // may send the first event. Idempotent, and a no-op during SSR.
20
+ if (cookieless && !isCookielessIdentity())
21
+ enableCookielessIdentity();
14
22
  const enabled = useMemo(() => {
15
23
  if (disabled)
16
24
  return false;
@@ -30,6 +38,10 @@ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled
30
38
  const trackEvent = useCallback(async (eventName, data = {}) => {
31
39
  if (!enabled)
32
40
  return;
41
+ // Lets <TempsSurveys /> show a survey triggered by this event.
42
+ if (!eventName.startsWith("survey_")) {
43
+ window.dispatchEvent(new CustomEvent(TRACK_EVENT, { detail: { name: eventName } }));
44
+ }
33
45
  await sendAnalytics("event", {
34
46
  event_name: eventName,
35
47
  request_query: window.location.search,
@@ -40,10 +52,26 @@ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled
40
52
  event_data: data,
41
53
  }, "POST", basePath, ingestKey);
42
54
  }, [enabled, basePath, domain, ingestKey]);
55
+ const trackNotFound = useCallback(
56
+ // Checks `enabled` before reading the page, so a call while rendering
57
+ // on the server does nothing, like the other tracking methods.
58
+ async (data = {}) => {
59
+ if (!enabled)
60
+ return;
61
+ await trackEvent(NOT_FOUND_EVENT, notFoundEventData(data));
62
+ }, [enabled, trackEvent]);
63
+ // Looks for the `data-temps-404` marker after each page view (ADR 109 D1).
64
+ const notFoundWatcher = useMemo(() => enabled && autoTrackNotFound
65
+ ? new NotFoundMarkerWatcher(() => void trackNotFound())
66
+ : null, [enabled, autoTrackNotFound, trackNotFound]);
67
+ useEffect(() => () => notFoundWatcher?.cancel(), [notFoundWatcher]);
68
+ // The last page view in flight: identify waits for it, because a first
69
+ // visit's visitor only exists once its first event has been recorded.
70
+ const pendingPageviewRef = useRef(Promise.resolve());
43
71
  const trackPageview = useCallback(() => {
44
72
  if (!enabled)
45
73
  return;
46
- void sendAnalytics("event", {
74
+ pendingPageviewRef.current = sendAnalytics("event", {
47
75
  event_name: "page_view",
48
76
  request_query: window.location.search,
49
77
  request_path: window.location.pathname,
@@ -56,10 +84,25 @@ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled
56
84
  timestamp: new Date().toISOString(),
57
85
  },
58
86
  }, "POST", basePath, ingestKey);
59
- }, [enabled, basePath, domain, ingestKey]);
60
- const identify = useCallback(async () => {
61
- // no-op placeholder for SDK parity; implement when identity endpoint is available
62
- }, []);
87
+ notFoundWatcher?.afterPageview();
88
+ }, [enabled, basePath, domain, ingestKey, notFoundWatcher]);
89
+ const identify = useCallback(async (userId, traits) => {
90
+ if (!enabled) {
91
+ return { applied: false, outcome: "disabled", message: "Analytics is disabled on this page." };
92
+ }
93
+ return identifyVisitor({
94
+ basePath,
95
+ ingestKey,
96
+ userId,
97
+ traits,
98
+ ready: pendingPageviewRef.current,
99
+ });
100
+ }, [enabled, basePath, ingestKey]);
101
+ const reset = useCallback(async () => {
102
+ if (!enabled)
103
+ return;
104
+ await resetVisitor({ basePath, ingestKey });
105
+ }, [enabled, basePath, ingestKey]);
63
106
  // Route change monitoring (pushState/popstate)
64
107
  const currentPathRef = useRef(typeof window !== "undefined" ? window.location.pathname : "");
65
108
  useEffect(() => {
@@ -135,6 +178,28 @@ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled
135
178
  document.addEventListener("click", onClick);
136
179
  return () => document.removeEventListener("click", onClick);
137
180
  }, [enabled, trackEvent]);
181
+ // Outbound links and file downloads: one delegated listener (ADR 109 D1).
182
+ // Beacon transport, because the click usually navigates away.
183
+ const fileDownloadExtensionsKey = fileDownloadExtensions?.join(",");
184
+ useEffect(() => {
185
+ if (!enabled)
186
+ return;
187
+ return setupLinkTracking({
188
+ autoTrackOutboundLinks,
189
+ autoTrackFileDownloads,
190
+ fileDownloadExtensions: fileDownloadExtensionsKey?.split(","),
191
+ }, (eventName, data) => {
192
+ sendAnalyticsReliable("event", {
193
+ event_name: eventName,
194
+ request_query: window.location.search,
195
+ request_path: window.location.pathname,
196
+ // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing -- an empty domain falls back too
197
+ domain: domain || window.location.hostname,
198
+ language: navigator.language,
199
+ event_data: data,
200
+ }, basePath, ingestKey);
201
+ });
202
+ }, [enabled, autoTrackOutboundLinks, autoTrackFileDownloads, fileDownloadExtensionsKey, domain, basePath, ingestKey]);
138
203
  // Engagement tracking with heartbeats and page leave
139
204
  useEffect(() => {
140
205
  if (!enabled)
@@ -197,11 +262,54 @@ export function TempsAnalyticsProvider({ basePath = DEFAULT_BASE_PATH, disabled
197
262
  });
198
263
  // Session recording control
199
264
  const { isEnabled: isRecordingEnabled } = useSessionRecordingControl(enableSessionRecording);
200
- const value = useMemo(() => ({ trackEvent, identify, trackPageview, enabled }), [trackEvent, identify, trackPageview, enabled]);
265
+ // One flags client for the provider's lifetime. Exposure events go
266
+ // through the latest `trackEvent`, so they respect `enabled` as it changes.
267
+ const trackEventRef = useRef(trackEvent);
268
+ trackEventRef.current = trackEvent;
269
+ const flagsRef = useRef(null);
270
+ if (flagsRef.current === null) {
271
+ flagsRef.current = new FeatureFlags({
272
+ ...flagOptions,
273
+ basePath,
274
+ disabled,
275
+ onExposure: (exposure) => {
276
+ void trackEventRef.current("flag_exposure", exposureEventData(exposure));
277
+ },
278
+ });
279
+ }
280
+ const flags = flagsRef.current;
281
+ // The client is created once, so later prop changes are applied to it: a
282
+ // provider that starts disabled can be enabled, and a sign-in that changes
283
+ // `flags={{ key, attributes }}` re-evaluates with the new context.
284
+ useEffect(() => {
285
+ flags.setDisabled(disabled);
286
+ }, [flags, disabled]);
287
+ const flagContext = JSON.stringify({ key: flagOptions?.key, attributes: flagOptions?.attributes });
288
+ const appliedContext = useRef(flagContext);
289
+ useEffect(() => {
290
+ if (appliedContext.current === flagContext)
291
+ return;
292
+ appliedContext.current = flagContext;
293
+ flags.setContext({ key: flagOptions?.key, attributes: flagOptions?.attributes });
294
+ // `flagContext` is the serialized form of the two options read here.
295
+ // eslint-disable-next-line react-hooks/exhaustive-deps
296
+ }, [flags, flagContext]);
297
+ const value = useMemo(() => ({
298
+ trackEvent,
299
+ identify,
300
+ reset,
301
+ getVisitorId: getStoredVisitorId,
302
+ trackPageview,
303
+ trackNotFound,
304
+ enabled,
305
+ flags,
306
+ basePath,
307
+ }), [trackEvent, identify, reset, trackPageview, trackNotFound, enabled, flags, basePath]);
201
308
  return (_jsx(AnalyticsContext.Provider, { value: value, children: _jsxs(SessionRecordingProvider, { defaultEnabled: enableSessionRecording, children: [children, enabled && (
202
309
  // Forward the whole config; the provider-level values go last so the
203
- // config cannot override them.
204
- _jsx(SessionRecorder, { ...sessionRecordingConfig, basePath: basePath, ingestKey: ingestKey, domain: domain, enabled: isRecordingEnabled }))] }) }));
310
+ // config cannot override them. A replay needs an id stored on the
311
+ // device, which cookieless mode never writes.
312
+ _jsx(SessionRecorder, { ...sessionRecordingConfig, basePath: basePath, ingestKey: ingestKey, domain: domain, enabled: isRecordingEnabled && !cookieless && !isCookielessIdentity() }))] }) }));
205
313
  }
206
314
  export function useTempsAnalytics() {
207
315
  const ctx = useContext(AnalyticsContext);
@@ -1 +1 @@
1
- {"version":3,"file":"SessionRecorder.d.ts","sourceRoot":"","sources":["../src/SessionRecorder.tsx"],"names":[],"mappings":"AAKA,OAAO,EAEL,KAAK,sBAAsB,EAC5B,MAAM,2BAA2B,CAAC;AAEnC,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,uDAAuD;AACvD,MAAM,WAAW,wBAAwB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,OAAO,GAAG;QAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,IAAI,CAAC,EAAE,OAAO,CAAC;QACf,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,IAAI,CAAC,EAAE,OAAO,CAAC;QACf,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB,CAAC;IACF,SAAS,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC7B,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACzB;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,qBAAqB,GAAG,IAAI,CACtC,sBAAsB,EACtB,UAAU,GAAG,WAAW,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAC7D,GAAG;IACF,QAAQ,CAAC,EAAE,wBAAwB,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,qBAAqB,GAAG;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,GAAG,IAAI,CA6BjE"}
1
+ {"version":3,"file":"SessionRecorder.d.ts","sourceRoot":"","sources":["../src/SessionRecorder.tsx"],"names":[],"mappings":"AAKA,OAAO,EAKL,KAAK,sBAAsB,EAC5B,MAAM,2BAA2B,CAAC;AAEnC,eAAO,MAAM,yBAAyB,mBAAmB,CAAC;AAE1D,uDAAuD;AACvD,MAAM,WAAW,wBAAwB;IACvC,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,gBAAgB,CAAC,EAAE,OAAO,GAAG;QAC3B,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,KAAK,CAAC,EAAE,OAAO,CAAC;QAChB,IAAI,CAAC,EAAE,OAAO,CAAC;QACf,UAAU,CAAC,EAAE,OAAO,CAAC;QACrB,QAAQ,CAAC,EAAE,OAAO,CAAC;QACnB,WAAW,CAAC,EAAE,OAAO,CAAC;QACtB,IAAI,CAAC,EAAE,OAAO,CAAC;QACf,KAAK,CAAC,EAAE,OAAO,CAAC;KACjB,CAAC;IACF,SAAS,CAAC,EAAE,OAAO,GAAG,MAAM,CAAC;IAC7B,KAAK,CAAC,EAAE,KAAK,GAAG,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,GAAG,KAAK,CAAC;CACzB;AAED;;;;;;;;;GASG;AACH,MAAM,MAAM,qBAAqB,GAAG,IAAI,CACtC,sBAAsB,EACtB,UAAU,GAAG,WAAW,GAAG,QAAQ,GAAG,SAAS,GAAG,UAAU,CAC7D,GAAG;IACF,QAAQ,CAAC,EAAE,wBAAwB,CAAC;CACrC,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG,qBAAqB,GAAG;IACzD,QAAQ,EAAE,MAAM,CAAC;IACjB;;;OAGG;IACH,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,oBAAoB,GAAG,IAAI,CAiDjE"}
@@ -2,7 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT OR Apache-2.0
3
3
  "use client";
4
4
  import { useEffect, useMemo, useRef } from "react";
5
- import { SessionRecorder as CoreSessionRecorder, } from "@temps-sdk/analytics-core";
5
+ import { SessionRecorder as CoreSessionRecorder, isCookielessIdentity, onCookielessIdentity, onIdentityReset, } from "@temps-sdk/analytics-core";
6
6
  export const SESSION_RECORDER_ENDPOINT = "session-replay";
7
7
  /**
8
8
  * React binding for the framework-agnostic recorder in `@temps-sdk/analytics-core`.
@@ -22,7 +22,9 @@ export function SessionRecorder(props) {
22
22
  // options instead.
23
23
  const optionsKey = useMemo(() => JSON.stringify(props), [props]);
24
24
  useEffect(() => {
25
- if (!props.enabled)
25
+ // A replay needs a visitor id stored on the device, which a cookieless page
26
+ // never writes (ADR 109 D3).
27
+ if (!props.enabled || isCookielessIdentity())
26
28
  return;
27
29
  const { enabled: _enabled, sampling, ...options } = props;
28
30
  const recorder = new CoreSessionRecorder({
@@ -31,8 +33,30 @@ export function SessionRecorder(props) {
31
33
  enabled: true,
32
34
  });
33
35
  recorderRef.current = recorder;
36
+ // Another analytics instance switching the page to cookieless after this
37
+ // mounted ends the replay and drops what was not uploaded yet.
38
+ let discarded = false;
39
+ const unsubscribe = onCookielessIdentity(() => {
40
+ discarded = true;
41
+ recorder.discard();
42
+ recorderRef.current = null;
43
+ });
44
+ // `reset()` after a sign-out gives the page a new visitor: end this
45
+ // replay, and record what follows in a new session once the server
46
+ // confirmed the reset.
47
+ const unsubscribeReset = onIdentityReset((phase) => {
48
+ if (discarded)
49
+ return;
50
+ if (phase === "started")
51
+ recorder.endForReset();
52
+ else
53
+ recorder.resumeAfterReset();
54
+ });
34
55
  return () => {
35
- recorder.destroy();
56
+ unsubscribe();
57
+ unsubscribeReset();
58
+ if (!discarded)
59
+ recorder.destroy();
36
60
  recorderRef.current = null;
37
61
  };
38
62
  // eslint-disable-next-line react-hooks/exhaustive-deps
@@ -0,0 +1,29 @@
1
+ import { type SurveysOptions } from "@temps-sdk/analytics-core";
2
+ export interface TempsSurveysProps extends Pick<SurveysOptions, "attributes" | "onError"> {
3
+ /** Subject for sampling and flag conditions, e.g. a signed-in user id.
4
+ * Defaults to the Temps visitor cookie. */
5
+ visitorKey?: string;
6
+ /**
7
+ * The current path. Pass your router's (`usePathname()` in Next.js) so a
8
+ * survey for `/checkout/*` appears on client-side navigation. Defaults to
9
+ * `window.location.pathname`, re-read on back/forward navigation.
10
+ */
11
+ pathname?: string;
12
+ }
13
+ /**
14
+ * Shows in-app surveys defined in the Temps console (ADR 110 D1) with the
15
+ * built-in widget. Place it once inside `<TempsAnalyticsProvider>`:
16
+ *
17
+ * ```tsx
18
+ * <TempsAnalyticsProvider>
19
+ * <App />
20
+ * <TempsSurveys pathname={usePathname()} />
21
+ * </TempsAnalyticsProvider>
22
+ * ```
23
+ *
24
+ * Answers are recorded as `survey_shown`, `survey_dismissed` and
25
+ * `survey_sent` analytics events, so nothing is shown while analytics is
26
+ * disabled (for example on localhost unless `ignoreLocalhost={false}`).
27
+ */
28
+ export declare function TempsSurveys({ pathname, visitorKey, attributes, onError }: TempsSurveysProps): null;
29
+ //# sourceMappingURL=TempsSurveys.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"TempsSurveys.d.ts","sourceRoot":"","sources":["../src/TempsSurveys.tsx"],"names":[],"mappings":"AAKA,OAAO,EAGL,KAAK,cAAc,EACpB,MAAM,2BAA2B,CAAC;AAGnC,MAAM,WAAW,iBAAkB,SAAQ,IAAI,CAAC,cAAc,EAAE,YAAY,GAAG,SAAS,CAAC;IACvF;+CAC2C;IAC3C,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB;;;;OAIG;IACH,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,YAAY,CAAC,EAAE,QAAQ,EAAE,UAAU,EAAE,UAAU,EAAE,OAAO,EAAE,EAAE,iBAAiB,GAAG,IAAI,CA4FnG"}
@@ -0,0 +1,113 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ "use client";
4
+ import { useEffect, useRef } from "react";
5
+ import { renderSurveyWidget, Surveys, } from "@temps-sdk/analytics-core";
6
+ import { TRACK_EVENT, useTempsAnalytics } from "./Provider";
7
+ /**
8
+ * Shows in-app surveys defined in the Temps console (ADR 110 D1) with the
9
+ * built-in widget. Place it once inside `<TempsAnalyticsProvider>`:
10
+ *
11
+ * ```tsx
12
+ * <TempsAnalyticsProvider>
13
+ * <App />
14
+ * <TempsSurveys pathname={usePathname()} />
15
+ * </TempsAnalyticsProvider>
16
+ * ```
17
+ *
18
+ * Answers are recorded as `survey_shown`, `survey_dismissed` and
19
+ * `survey_sent` analytics events, so nothing is shown while analytics is
20
+ * disabled (for example on localhost unless `ignoreLocalhost={false}`).
21
+ */
22
+ export function TempsSurveys({ pathname, visitorKey, attributes, onError }) {
23
+ const { trackEvent, enabled, basePath } = useTempsAnalytics();
24
+ const trackRef = useRef(trackEvent);
25
+ trackRef.current = trackEvent;
26
+ const surveysRef = useRef(null);
27
+ const openRef = useRef(null);
28
+ // The subject and attributes as a value, so a new object with the same
29
+ // contents is not a change.
30
+ const context = JSON.stringify([visitorKey ?? null, attributes ?? {}]);
31
+ const appliedContextRef = useRef(context);
32
+ // One client per mounted component. A later change of `visitorKey` or
33
+ // `attributes` (a user signing in) is applied in the effect below.
34
+ if (surveysRef.current === null && enabled) {
35
+ appliedContextRef.current = context;
36
+ surveysRef.current = new Surveys({
37
+ // The provider's path, so delivery and the answers' events agree.
38
+ basePath,
39
+ key: visitorKey,
40
+ attributes,
41
+ onError,
42
+ onEvent: (name, data) => {
43
+ void trackRef.current(name, data);
44
+ },
45
+ });
46
+ }
47
+ useEffect(() => {
48
+ const surveys = surveysRef.current;
49
+ // Analytics turned off: close what is open and listen for nothing, since
50
+ // answers could not be recorded.
51
+ if (!surveys || !enabled) {
52
+ openRef.current?.();
53
+ return undefined;
54
+ }
55
+ if (appliedContextRef.current !== context) {
56
+ // Sampling and flag conditions depend on the subject: drop what was
57
+ // fetched for the previous one and fetch again.
58
+ appliedContextRef.current = context;
59
+ surveys.setContext(visitorKey, attributes);
60
+ }
61
+ let cancelled = false;
62
+ const show = async (event) => {
63
+ // Loaded even while a survey is open, so a new context is fetched at
64
+ // once; `load()` is a no-op once loaded.
65
+ await surveys.load();
66
+ if (cancelled || openRef.current)
67
+ return;
68
+ const path = pathname ?? window.location.pathname;
69
+ const next = surveys.eligible(path, event)[0];
70
+ if (!next)
71
+ return;
72
+ surveys.markShown(next);
73
+ // Owned until the card has left the page, thank-you message included,
74
+ // so a later event cannot open a second one over it and unmounting
75
+ // can still remove it.
76
+ let closed = false;
77
+ const close = renderSurveyWidget(next, {
78
+ onSubmit: (answers) => {
79
+ const result = surveys.submit(next, answers);
80
+ return result.ok ? null : result.errors;
81
+ },
82
+ onDismiss: () => surveys.dismiss(next),
83
+ onClosed: () => {
84
+ closed = true;
85
+ if (openRef.current === closeThis)
86
+ openRef.current = null;
87
+ },
88
+ });
89
+ const closeThis = () => close();
90
+ if (!closed)
91
+ openRef.current = closeThis;
92
+ };
93
+ void show();
94
+ const onTrack = (event) => {
95
+ const name = event.detail?.name;
96
+ if (typeof name === "string")
97
+ void show(name);
98
+ };
99
+ const onPop = () => void show();
100
+ window.addEventListener(TRACK_EVENT, onTrack);
101
+ window.addEventListener("popstate", onPop);
102
+ return () => {
103
+ cancelled = true;
104
+ window.removeEventListener(TRACK_EVENT, onTrack);
105
+ window.removeEventListener("popstate", onPop);
106
+ };
107
+ // `context` stands for `visitorKey` and `attributes`, compared by value.
108
+ // eslint-disable-next-line react-hooks/exhaustive-deps
109
+ }, [pathname, enabled, context]);
110
+ // Close an open survey when the component goes away.
111
+ useEffect(() => () => openRef.current?.(), []);
112
+ return null;
113
+ }
package/dist/index.d.ts CHANGED
@@ -7,6 +7,10 @@ export * from "./usePageLeave";
7
7
  export * from "./useSpeedAnalytics";
8
8
  export * from "./useEngagementTracking";
9
9
  export * from "./useScrollVisibility";
10
+ export * from "./useFlag";
11
+ export * from "./TempsSurveys";
12
+ export type { FlagContext, FlagEvaluation, FlagExposure } from "@temps-sdk/analytics-core";
13
+ export { Surveys, type Survey, type SurveyAnswers, type SurveyQuestion, } from "@temps-sdk/analytics-core";
10
14
  export { EngagementTracker, type EngagementTrackerOptions, type EngagementData } from "./EngagementTracker";
11
15
  export { SessionRecorder, SESSION_RECORDER_ENDPOINT, type SessionRecorderConfig, type SessionRecorderProps, type SessionRecordingSampling, } from "./SessionRecorder";
12
16
  export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EACL,eAAe,EACf,yBAAyB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAIA,cAAc,SAAS,CAAC;AACxB,cAAc,YAAY,CAAC;AAC3B,cAAc,gBAAgB,CAAC;AAC/B,cAAc,iBAAiB,CAAC;AAChC,cAAc,oBAAoB,CAAC;AACnC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,WAAW,CAAC;AAC1B,cAAc,gBAAgB,CAAC;AAC/B,YAAY,EAAE,WAAW,EAAE,cAAc,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAC3F,OAAO,EACL,OAAO,EACP,KAAK,MAAM,EACX,KAAK,aAAa,EAClB,KAAK,cAAc,GACpB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,KAAK,wBAAwB,EAAE,KAAK,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAC5G,OAAO,EACL,eAAe,EACf,yBAAyB,EACzB,KAAK,qBAAqB,EAC1B,KAAK,oBAAoB,EACzB,KAAK,wBAAwB,GAC9B,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EACL,wBAAwB,EACxB,mBAAmB,EACnB,0BAA0B,EAC3B,MAAM,uBAAuB,CAAC"}
package/dist/index.js CHANGED
@@ -10,6 +10,9 @@ export * from "./usePageLeave";
10
10
  export * from "./useSpeedAnalytics";
11
11
  export * from "./useEngagementTracking";
12
12
  export * from "./useScrollVisibility";
13
+ export * from "./useFlag";
14
+ export * from "./TempsSurveys";
15
+ export { Surveys, } from "@temps-sdk/analytics-core";
13
16
  export { EngagementTracker } from "./EngagementTracker";
14
17
  export { SessionRecorder, SESSION_RECORDER_ENDPOINT, } from "./SessionRecorder";
15
18
  export { SessionRecordingProvider, useSessionRecording, useSessionRecordingControl } from "./useSessionRecording";
package/dist/types.d.ts CHANGED
@@ -1,18 +1,45 @@
1
1
  import type React from "react";
2
- import type { JsonValue, AnalyticsClientOptions } from "@temps-sdk/analytics-core";
2
+ import type { JsonValue, AnalyticsClientOptions, AutoTrackOptions, FeatureFlags, FeatureFlagsOptions, IdentifyResult } from "@temps-sdk/analytics-core";
3
3
  import type { SessionRecorderConfig } from "./SessionRecorder";
4
- export type { JsonPrimitive, JsonValue, AnalyticsEventBase, AnalyticsClientOptions, WebVitalMetric, SpeedMetric, } from "@temps-sdk/analytics-core";
4
+ export type { JsonPrimitive, JsonValue, AnalyticsEventBase, AnalyticsClientOptions, WebVitalMetric, SpeedMetric, IdentifyResult, } from "@temps-sdk/analytics-core";
5
5
  export interface AnalyticsContextValue {
6
6
  /** Send a custom event. */
7
7
  trackEvent: (eventName: string, data?: Record<string, JsonValue>) => Promise<void>;
8
- /** Identify an user if needed. No-op by default. */
9
- identify: (userId: string, traits?: Record<string, JsonValue>) => Promise<void> | void;
8
+ /**
9
+ * Attach your app's user id (and optional traits) to this visitor, e.g.
10
+ * right after signup or sign-in. Repeating the same call sends nothing; in
11
+ * cookieless mode nothing is sent at all.
12
+ */
13
+ identify: (userId: string, traits?: Record<string, JsonValue>) => Promise<IdentifyResult>;
14
+ /** Forget the identity on sign-out; the next event is a new visitor. */
15
+ reset: () => Promise<void>;
16
+ /**
17
+ * The visitor id the tracker stored; `undefined` in cookieless mode or
18
+ * before the first event. A backend on Temps does not need it: the Node
19
+ * SDK's `analytics.identify(request, …)` reads the proxy's cookie.
20
+ */
21
+ getVisitorId: () => string | undefined;
10
22
  /** Manually trigger a pageview. */
11
23
  trackPageview: () => void;
24
+ /**
25
+ * Report the current page as missing: sends a `not_found` event whose
26
+ * `path` property is the current path. Call it from your "not found" view,
27
+ * or mark that view with `data-temps-404` and let the provider do it.
28
+ */
29
+ trackNotFound: (data?: Record<string, JsonValue>) => Promise<void>;
12
30
  /** Whether analytics are currently enabled. */
13
31
  enabled: boolean;
32
+ /** Client-visible feature flags for this visitor. Prefer `useFlag`. */
33
+ flags: FeatureFlags;
34
+ /** Where the Temps endpoints live, as configured on the provider. */
35
+ basePath: string;
14
36
  }
15
- export interface TempsAnalyticsProviderProps extends AnalyticsClientOptions {
37
+ export interface TempsAnalyticsProviderProps extends AnalyticsClientOptions, AutoTrackOptions {
38
+ /**
39
+ * Feature-flag context (`key`, `attributes`) and server-rendered
40
+ * `bootstrap` values. Read flags with `useFlag`.
41
+ */
42
+ flags?: Pick<FeatureFlagsOptions, "key" | "attributes" | "bootstrap" | "onError">;
16
43
  /** Auto track pageviews on route changes. Defaults to true. */
17
44
  autoTrackPageviews?: boolean;
18
45
  /** Auto track page leave events. Defaults to true. */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EAAE,SAAS,EAAE,sBAAsB,EAAE,MAAM,2BAA2B,CAAC;AACnF,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAE/D,YAAY,EACV,aAAa,EACb,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,cAAc,EACd,WAAW,GACZ,MAAM,2BAA2B,CAAC;AAEnC,MAAM,WAAW,qBAAqB;IACpC,2BAA2B;IAC3B,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACnF,oDAAoD;IACpD,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACvF,mCAAmC;IACnC,aAAa,EAAE,MAAM,IAAI,CAAC;IAC1B,+CAA+C;IAC/C,OAAO,EAAE,OAAO,CAAC;CAClB;AAED,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB;IACzE,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,sDAAsD;IACtD,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,yEAAyE;IACzE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,iEAAiE;IACjE,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,+DAA+D;IAC/D,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,0EAA0E;IAC1E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,0EAA0E;IAC1E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,wGAAwG;IACxG,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,mDAAmD;IACnD,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,qBAAqB,CAAC;IAC/C,8CAA8C;IAC9C,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B"}
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAC;AAC/B,OAAO,KAAK,EACV,SAAS,EACT,sBAAsB,EACtB,gBAAgB,EAChB,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACf,MAAM,2BAA2B,CAAC;AACnC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,mBAAmB,CAAC;AAE/D,YAAY,EACV,aAAa,EACb,SAAS,EACT,kBAAkB,EAClB,sBAAsB,EACtB,cAAc,EACd,WAAW,EACX,cAAc,GACf,MAAM,2BAA2B,CAAC;AAEnC,MAAM,WAAW,qBAAqB;IACpC,2BAA2B;IAC3B,UAAU,EAAE,CAAC,SAAS,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACnF;;;;OAIG;IACH,QAAQ,EAAE,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IAC1F,wEAAwE;IACxE,KAAK,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B;;;;OAIG;IACH,YAAY,EAAE,MAAM,MAAM,GAAG,SAAS,CAAC;IACvC,mCAAmC;IACnC,aAAa,EAAE,MAAM,IAAI,CAAC;IAC1B;;;;OAIG;IACH,aAAa,EAAE,CAAC,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,SAAS,CAAC,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;IACnE,+CAA+C;IAC/C,OAAO,EAAE,OAAO,CAAC;IACjB,uEAAuE;IACvE,KAAK,EAAE,YAAY,CAAC;IACpB,qEAAqE;IACrE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,2BAA4B,SAAQ,sBAAsB,EAAE,gBAAgB;IAC3F;;;OAGG;IACH,KAAK,CAAC,EAAE,IAAI,CAAC,mBAAmB,EAAE,KAAK,GAAG,YAAY,GAAG,WAAW,GAAG,SAAS,CAAC,CAAC;IAClF,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,sDAAsD;IACtD,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,yEAAyE;IACzE,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,iEAAiE;IACjE,uBAAuB,CAAC,EAAE,OAAO,CAAC;IAClC,+DAA+D;IAC/D,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,0EAA0E;IAC1E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,0EAA0E;IAC1E,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,wGAAwG;IACxG,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,mDAAmD;IACnD,sBAAsB,CAAC,EAAE,OAAO,CAAC;IACjC;;;;OAIG;IACH,sBAAsB,CAAC,EAAE,qBAAqB,CAAC;IAC/C,8CAA8C;IAC9C,QAAQ,EAAE,KAAK,CAAC,SAAS,CAAC;CAC3B"}
@@ -0,0 +1,30 @@
1
+ import type { FeatureFlags, FlagContext } from "@temps-sdk/analytics-core";
2
+ /**
3
+ * The value Temps serves for a client-visible flag, for this visitor.
4
+ *
5
+ * Returns `fallback` until flags arrive (or if the flag does not exist, is
6
+ * not client-visible, or the request fails), then re-renders with the served
7
+ * value. Reading a flag that records exposures sends one `flag_exposure`
8
+ * event per page.
9
+ *
10
+ * ```tsx
11
+ * const newCheckout = useFlag("checkout.v2", false);
12
+ * ```
13
+ */
14
+ export declare function useFlag<T>(key: string, fallback: T): T;
15
+ /** The variant served for a flag (`"control"`, `"test"`, ...), or `null`. */
16
+ export declare function useFlagVariant(key: string): string | null;
17
+ /**
18
+ * The flags client, for re-evaluating with a new context after sign-in:
19
+ *
20
+ * ```tsx
21
+ * const { reload } = useFeatureFlags();
22
+ * useEffect(() => { if (user) void reload({ key: user.id, attributes: { plan: user.plan } }); }, [user]);
23
+ * ```
24
+ */
25
+ export declare function useFeatureFlags(): {
26
+ flags: FeatureFlags;
27
+ status: FeatureFlags["status"];
28
+ reload: (context?: FlagContext) => Promise<void>;
29
+ };
30
+ //# sourceMappingURL=useFlag.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useFlag.d.ts","sourceRoot":"","sources":["../src/useFlag.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAS3E;;;;;;;;;;;GAWG;AACH,wBAAgB,OAAO,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,CAAC,CActD;AAED,6EAA6E;AAC7E,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAQzD;AAED;;;;;;;GAOG;AACH,wBAAgB,eAAe,IAAI;IACjC,KAAK,EAAE,YAAY,CAAC;IACpB,MAAM,EAAE,YAAY,CAAC,QAAQ,CAAC,CAAC;IAC/B,MAAM,EAAE,CAAC,OAAO,CAAC,EAAE,WAAW,KAAK,OAAO,CAAC,IAAI,CAAC,CAAC;CAClD,CAKA"}
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: 2024-2026 Temps Contributors
2
+ // SPDX-License-Identifier: MIT OR Apache-2.0
3
+ "use client";
4
+ import { useCallback, useEffect, useSyncExternalStore } from "react";
5
+ import { useTempsAnalytics } from "./Provider";
6
+ function useFlagsVersion(flags) {
7
+ const subscribe = useCallback((listener) => flags.subscribe(listener), [flags]);
8
+ const version = useCallback(() => flags.version, [flags]);
9
+ return useSyncExternalStore(subscribe, version, version);
10
+ }
11
+ /**
12
+ * The value Temps serves for a client-visible flag, for this visitor.
13
+ *
14
+ * Returns `fallback` until flags arrive (or if the flag does not exist, is
15
+ * not client-visible, or the request fails), then re-renders with the served
16
+ * value. Reading a flag that records exposures sends one `flag_exposure`
17
+ * event per page.
18
+ *
19
+ * ```tsx
20
+ * const newCheckout = useFlag("checkout.v2", false);
21
+ * ```
22
+ */
23
+ export function useFlag(key, fallback) {
24
+ const { flags } = useTempsAnalytics();
25
+ const version = useFlagsVersion(flags);
26
+ const value = flags.peek(key, fallback);
27
+ // Fetching and exposure recording happen after commit, so a render React
28
+ // discards neither starts a request nor records an exposure. `get` dedupes
29
+ // per variant and records nothing when the value is not of `fallback`'s type.
30
+ useEffect(() => {
31
+ flags.get(key, fallback);
32
+ // `fallback` is deliberately left out: an inline object or array would
33
+ // re-run this on every render, and its type is all that matters here.
34
+ // eslint-disable-next-line react-hooks/exhaustive-deps
35
+ }, [flags, key, version]);
36
+ return value;
37
+ }
38
+ /** The variant served for a flag (`"control"`, `"test"`, ...), or `null`. */
39
+ export function useFlagVariant(key) {
40
+ const { flags } = useTempsAnalytics();
41
+ const version = useFlagsVersion(flags);
42
+ const variant = flags.peekVariant(key);
43
+ useEffect(() => {
44
+ flags.getVariant(key);
45
+ }, [flags, key, version]);
46
+ return variant;
47
+ }
48
+ /**
49
+ * The flags client, for re-evaluating with a new context after sign-in:
50
+ *
51
+ * ```tsx
52
+ * const { reload } = useFeatureFlags();
53
+ * useEffect(() => { if (user) void reload({ key: user.id, attributes: { plan: user.plan } }); }, [user]);
54
+ * ```
55
+ */
56
+ export function useFeatureFlags() {
57
+ const { flags } = useTempsAnalytics();
58
+ useFlagsVersion(flags);
59
+ const reload = useCallback((context) => flags.reload(context), [flags]);
60
+ return { flags, status: flags.status, reload };
61
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@temps-sdk/react-analytics",
3
- "version": "0.0.9",
3
+ "version": "0.1.0-beta.64",
4
4
  "private": false,
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -18,7 +18,7 @@
18
18
  "build:types": "tsc -p tsconfig.types.json",
19
19
  "build": "bun run build:js && bun run build:types",
20
20
  "clean": "rm -rf dist",
21
- "prepublishOnly": "bun run clean && bun run build",
21
+ "prepublishOnly": "node ../../scripts/require-bun-publish.mjs && bun run clean && bun run build",
22
22
  "test": "vitest",
23
23
  "test:coverage": "vitest run --coverage",
24
24
  "lint": "eslint src --ext .ts,.tsx",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "dependencies": {
40
40
  "@rrweb/packer": "^2.0.0-alpha.17",
41
- "@temps-sdk/analytics-core": "0.0.6",
41
+ "@temps-sdk/analytics-core": "0.1.0-beta.64",
42
42
  "rrweb": "^2.0.0-alpha.17",
43
43
  "web-vitals": "^4.2.4"
44
44
  },
@@ -60,5 +60,10 @@
60
60
  "typescript": "^5.5.4",
61
61
  "vitest": "^4.1.0"
62
62
  },
63
- "sideEffects": false
63
+ "sideEffects": false,
64
+ "repository": {
65
+ "type": "git",
66
+ "url": "git+https://github.com/gotempsh/temps.git",
67
+ "directory": "sdks/node/packages/react-analytics"
68
+ }
64
69
  }