@codefast/tracking 0.0.0 → 0.5.0-canary.4

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.
Files changed (71) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +46 -8
  3. package/dist/client/consent-storage.d.mts +11 -3
  4. package/dist/client/consent-storage.mjs +45 -9
  5. package/dist/client/create-client-tracker.d.mts +10 -0
  6. package/dist/client/create-client-tracker.mjs +14 -1
  7. package/dist/client/gpc.d.mts +2 -0
  8. package/dist/client/gpc.mjs +2 -0
  9. package/dist/client/lifecycle.d.mts +5 -0
  10. package/dist/client/lifecycle.mjs +2 -0
  11. package/dist/client/local-storage.d.mts +5 -2
  12. package/dist/client/local-storage.mjs +12 -5
  13. package/dist/client/queue.d.mts +7 -0
  14. package/dist/client/queue.mjs +2 -0
  15. package/dist/client/router.d.mts +4 -0
  16. package/dist/client/router.mjs +2 -0
  17. package/dist/core/consent.d.mts +61 -9
  18. package/dist/core/consent.mjs +39 -7
  19. package/dist/core/destination.d.mts +10 -0
  20. package/dist/core/event-catalog.d.mts +8 -0
  21. package/dist/core/event-catalog.mjs +2 -0
  22. package/dist/core/event-id.d.mts +2 -0
  23. package/dist/core/event-id.mjs +2 -0
  24. package/dist/core/index.d.mts +2 -2
  25. package/dist/core/index.mjs +2 -2
  26. package/dist/core/tracked-event.d.mts +2 -0
  27. package/dist/destinations/ga4-measurement-protocol.d.mts +54 -0
  28. package/dist/destinations/ga4-measurement-protocol.mjs +89 -0
  29. package/dist/destinations/google-analytics.d.mts +98 -0
  30. package/dist/destinations/google-analytics.mjs +126 -0
  31. package/dist/destinations/http-destination.d.mts +5 -0
  32. package/dist/destinations/http-destination.mjs +2 -0
  33. package/dist/destinations/index.d.mts +3 -1
  34. package/dist/destinations/index.mjs +3 -1
  35. package/dist/destinations/vercel-analytics.d.mts +4 -2
  36. package/dist/destinations/vercel-analytics.mjs +5 -2
  37. package/dist/index.d.mts +2 -2
  38. package/dist/index.mjs +2 -2
  39. package/dist/react/consent-banner.d.mts +48 -14
  40. package/dist/react/consent-banner.mjs +94 -22
  41. package/dist/react/index.d.mts +2 -2
  42. package/dist/react/use-consent.d.mts +30 -5
  43. package/dist/react/use-consent.mjs +38 -15
  44. package/dist/server/create-server-tracker.d.mts +14 -0
  45. package/dist/server/create-server-tracker.mjs +24 -5
  46. package/dist/server/region.d.mts +4 -0
  47. package/dist/server/region.mjs +4 -0
  48. package/package.json +12 -2
  49. package/src/client/consent-storage.ts +75 -10
  50. package/src/client/create-client-tracker.ts +30 -1
  51. package/src/client/gpc.ts +2 -0
  52. package/src/client/lifecycle.ts +5 -0
  53. package/src/client/local-storage.ts +21 -6
  54. package/src/client/queue.ts +7 -0
  55. package/src/client/router.ts +4 -0
  56. package/src/core/consent.ts +85 -11
  57. package/src/core/destination.ts +10 -0
  58. package/src/core/event-catalog.ts +8 -0
  59. package/src/core/event-id.ts +2 -0
  60. package/src/core/index.ts +15 -2
  61. package/src/core/tracked-event.ts +2 -0
  62. package/src/destinations/ga4-measurement-protocol.ts +166 -0
  63. package/src/destinations/google-analytics.ts +233 -0
  64. package/src/destinations/http-destination.ts +5 -0
  65. package/src/destinations/index.ts +16 -0
  66. package/src/destinations/vercel-analytics.ts +5 -2
  67. package/src/react/consent-banner.tsx +121 -22
  68. package/src/react/index.ts +1 -1
  69. package/src/react/use-consent.ts +81 -23
  70. package/src/server/create-server-tracker.ts +39 -16
  71. package/src/server/region.ts +4 -0
@@ -2,19 +2,26 @@ import type { EventQueueStorage } from "#/client/queue";
2
2
  import type { TrackedEvent } from "#/core/tracked-event";
3
3
 
4
4
  /**
5
- * `localStorage`-backed queue storage — corrupt/missing state is treated as empty
6
- * rather than thrown, since a lost offline queue is preferable to a crashing app.
5
+ * `localStorage`-backed queue storage — corrupt/missing state, a private-mode/quota
6
+ * error, or no `window` (SSR) are all treated as empty rather than thrown, since a lost
7
+ * offline queue is preferable to a crashing app.
8
+ *
9
+ * @since 0.5.0-canary.4
7
10
  */
8
11
  export function createLocalStorageQueueStorage(storageKey: string): EventQueueStorage {
9
12
  return {
10
13
  load(): Array<TrackedEvent> {
11
- const raw = localStorage.getItem(storageKey);
12
-
13
- if (!raw) {
14
+ if (typeof globalThis.window === "undefined") {
14
15
  return [];
15
16
  }
16
17
 
17
18
  try {
19
+ const raw = globalThis.window.localStorage.getItem(storageKey);
20
+
21
+ if (!raw) {
22
+ return [];
23
+ }
24
+
18
25
  const parsed: unknown = JSON.parse(raw);
19
26
 
20
27
  return Array.isArray(parsed) ? (parsed as Array<TrackedEvent>) : [];
@@ -23,7 +30,15 @@ export function createLocalStorageQueueStorage(storageKey: string): EventQueueSt
23
30
  }
24
31
  },
25
32
  save(events: Array<TrackedEvent>): void {
26
- localStorage.setItem(storageKey, JSON.stringify(events));
33
+ if (typeof globalThis.window === "undefined") {
34
+ return;
35
+ }
36
+
37
+ try {
38
+ globalThis.window.localStorage.setItem(storageKey, JSON.stringify(events));
39
+ } catch {
40
+ /* storage blocked (private mode / quota) */
41
+ }
27
42
  },
28
43
  };
29
44
  }
@@ -4,12 +4,17 @@ import type { TrackedEvent } from "#/core/tracked-event";
4
4
  /**
5
5
  * Persistence backend for the offline queue — a thin wrapper so tests and non-browser
6
6
  * environments can swap in an in-memory implementation instead of real `localStorage`.
7
+ *
8
+ * @since 0.5.0-canary.4
7
9
  */
8
10
  export interface EventQueueStorage {
9
11
  load: () => Array<TrackedEvent>;
10
12
  save: (events: Array<TrackedEvent>) => void;
11
13
  }
12
14
 
15
+ /**
16
+ * @since 0.5.0-canary.4
17
+ */
13
18
  export interface EventQueueOptions {
14
19
  destinations: Array<Destination>;
15
20
  flushBatchSize?: number | undefined;
@@ -26,6 +31,8 @@ interface QueuedEvent {
26
31
  /**
27
32
  * Client-side batching/offline queue: persists across reloads, caps its size
28
33
  * (drop-oldest), and retries a failed batch up to `maxRetries` times.
34
+ *
35
+ * @since 0.5.0-canary.4
29
36
  */
30
37
  export class EventQueue {
31
38
  private readonly destinations: Array<Destination>;
@@ -11,6 +11,8 @@ interface ResolvedNavigation {
11
11
  /**
12
12
  * Structurally matches `Router["subscribe"]` from `@tanstack/router-core` for the
13
13
  * `"onResolved"` event — duck-typed so this package doesn't depend on TanStack Router.
14
+ *
15
+ * @since 0.5.0-canary.4
14
16
  */
15
17
  export interface RouterLike {
16
18
  subscribe: (eventType: "onResolved", fn: (event: ResolvedNavigation) => void) => () => void;
@@ -21,6 +23,8 @@ export interface RouterLike {
21
23
  * `popstate` only fires for browser back/forward. Page views are low-frequency, so this
22
24
  * flushes right away instead of waiting on the batch queue's interval/size threshold —
23
25
  * a slow navigation shouldn't leave a pageview stranded if the tab closes right after.
26
+ *
27
+ * @since 0.5.0-canary.4
24
28
  */
25
29
  export function attachRouterPageTracking<Catalog extends EventCatalog>(
26
30
  tracker: Pick<ClientTracker<Catalog>, "flush" | "page">,
@@ -1,11 +1,19 @@
1
+ /**
2
+ * @since 0.5.0-canary.4
3
+ */
1
4
  export type ConsentRegion = "eu" | "other" | "us" | "vn";
2
5
 
6
+ /**
7
+ * @since 0.5.0-canary.4
8
+ */
3
9
  export type ConsentMode = "opt-in" | "opt-out";
4
10
 
5
11
  /**
6
12
  * GDPR (EU) and Nghị định 13/2023 (VN) require explicit opt-in before any non-essential
7
13
  * tracking; CCPA/CPRA (US) defaults to opt-out instead. There is no single global default
8
14
  * that satisfies both, so the mode is resolved per region.
15
+ *
16
+ * @since 0.5.0-canary.4
9
17
  */
10
18
  export function resolveConsentMode(region: ConsentRegion): ConsentMode {
11
19
  switch (region) {
@@ -22,24 +30,83 @@ export function resolveConsentMode(region: ConsentRegion): ConsentMode {
22
30
  }
23
31
 
24
32
  /**
25
- * Under CCPA/CPRA, a Global Privacy Control signal must be honored as an opt-out even
26
- * though the region default is opt-out. Under opt-in regions, tracking never starts
27
- * until consent is explicitly granted, GPC signal or not.
33
+ * Consent purposes, mirroring Google Consent Mode v2's split: `analytics` gates
34
+ * measurement (`analytics_storage`), `ads` gates advertising storage and data sharing
35
+ * (`ad_storage`/`ad_user_data`/`ad_personalization`).
36
+ *
37
+ * @since 0.5.0-canary.4
38
+ */
39
+ export type ConsentCategory = "ads" | "analytics";
40
+
41
+ /**
42
+ * @since 0.5.0-canary.4
43
+ */
44
+ export const CONSENT_CATEGORIES: ReadonlyArray<ConsentCategory> = ["ads", "analytics"];
45
+
46
+ /**
47
+ * Per-category consent — GDPR consent must be granular per purpose, so a single
48
+ * granted/denied flag can't represent it. `true` means the visitor granted that purpose.
49
+ *
50
+ * @since 0.5.0-canary.4
51
+ */
52
+ export type ConsentDecision = Record<ConsentCategory, boolean>;
53
+
54
+ /**
55
+ * A decision granting exactly the given categories and denying every other one.
56
+ *
57
+ * @since 0.5.0-canary.4
28
58
  */
29
- export function shouldTrackByDefault(mode: ConsentMode, hasGlobalPrivacyControlSignal: boolean): boolean {
59
+ export function createConsentDecision(grantedCategories: ReadonlyArray<ConsentCategory>): ConsentDecision {
60
+ return { ads: grantedCategories.includes("ads"), analytics: grantedCategories.includes("analytics") };
61
+ }
62
+
63
+ /**
64
+ * Guards stored JSON — the record is tamperable, so every category must be an explicit boolean.
65
+ *
66
+ * @since 0.5.0-canary.4
67
+ */
68
+ export function isConsentDecision(value: unknown): value is ConsentDecision {
69
+ return (
70
+ typeof value === "object" &&
71
+ value !== null &&
72
+ CONSENT_CATEGORIES.every((category) => typeof (value as Record<string, unknown>)[category] === "boolean")
73
+ );
74
+ }
75
+
76
+ /**
77
+ * The effective consent before the visitor decides: opt-in regions start all-denied,
78
+ * opt-out regions grant the categories the app asks for.
79
+ *
80
+ * @remarks
81
+ * A Global Privacy Control signal is a "do not sell or share" opt-out (CCPA/CPRA), so it
82
+ * forces `ads` denied — it does not withdraw first-party analytics measurement.
83
+ *
84
+ * @since 0.5.0-canary.4
85
+ */
86
+ export function resolveDefaultConsent(
87
+ mode: ConsentMode,
88
+ requestedCategories: ReadonlyArray<ConsentCategory>,
89
+ hasGlobalPrivacyControlSignal: boolean,
90
+ ): ConsentDecision {
30
91
  if (mode === "opt-in") {
31
- return false;
92
+ return createConsentDecision([]);
32
93
  }
33
94
 
34
- return !hasGlobalPrivacyControlSignal;
35
- }
95
+ const decision = createConsentDecision(requestedCategories);
36
96
 
37
- export type ConsentDecision = "denied" | "granted";
97
+ if (hasGlobalPrivacyControlSignal) {
98
+ decision.ads = false;
99
+ }
100
+
101
+ return decision;
102
+ }
38
103
 
39
104
  /**
40
105
  * NĐ 13/2023 and GDPR both expect a record of *when* and *under what policy* consent
41
- * was given, not just a yes/no flag — `policyVersion` lets a later policy change
106
+ * was given, not just per-category flags — `policyVersion` lets a later policy change
42
107
  * invalidate stale consent.
108
+ *
109
+ * @since 0.5.0-canary.4
43
110
  */
44
111
  export interface ConsentRecord {
45
112
  decision: ConsentDecision;
@@ -48,11 +115,18 @@ export interface ConsentRecord {
48
115
  }
49
116
 
50
117
  /**
51
- * Persistence backend for the visitor's consent decision — mirrors `EventQueueStorage`
52
- * so a non-browser environment can swap in its own implementation.
118
+ * Persistence backend for the visitor's consent decision — swap in your own
119
+ * implementation for non-browser environments or a different persistence layer.
120
+ *
121
+ * @since 0.5.0-canary.4
53
122
  */
54
123
  export interface ConsentStorage {
55
124
  clear: () => void;
56
125
  load: () => ConsentRecord | undefined;
57
126
  save: (record: ConsentRecord) => void;
127
+ /**
128
+ * Notify on any change to the stored record, including writes from other tabs — this
129
+ * is what drives `useConsent`'s external-store subscription. Returns an unsubscribe.
130
+ */
131
+ subscribe: (listener: () => void) => () => void;
58
132
  }
@@ -3,8 +3,18 @@ import type { TrackedEvent } from "#/core/tracked-event";
3
3
  /**
4
4
  * Fan-out target for tracked events (PostHog, GA4, a self-hosted store, ...).
5
5
  * Trackers depend only on this interface, never on a specific provider SDK.
6
+ *
7
+ * @since 0.5.0-canary.4
6
8
  */
7
9
  export interface Destination {
10
+ /**
11
+ * "immediate" for SDK-backed destinations that own their transport (gtag.js, Vercel's
12
+ * in-page queue) — the client tracker calls `send` at track time and never queues,
13
+ * persists, or retries for them.
14
+ *
15
+ * @defaultValue "queued"
16
+ */
17
+ delivery?: "immediate" | "queued";
8
18
  name: string;
9
19
  send: (event: TrackedEvent) => Promise<void> | void;
10
20
  }
@@ -2,6 +2,8 @@ import type { z } from "zod";
2
2
 
3
3
  /**
4
4
  * One event's Zod schema plus which side of the app is allowed to fire it.
5
+ *
6
+ * @since 0.5.0-canary.4
5
7
  */
6
8
  export interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
7
9
  owner: "client" | "server";
@@ -11,6 +13,8 @@ export interface EventDefinition<Schema extends z.ZodType = z.ZodType> {
11
13
  /**
12
14
  * An app-defined map of event name to its definition. `@codefast/tracking` ships no
13
15
  * events of its own — every consuming app builds and passes in its own catalog.
16
+ *
17
+ * @since 0.5.0-canary.4
14
18
  */
15
19
  export type EventCatalog = Record<string, EventDefinition>;
16
20
 
@@ -18,6 +22,8 @@ export type EventCatalog = Record<string, EventDefinition>;
18
22
  * Filters a catalog down to the events a given owner may fire. Client and server
19
23
  * trackers are built from this, so calling a server-owned event from client code
20
24
  * (or vice versa) is a compile-time error, not a runtime surprise.
25
+ *
26
+ * @since 0.5.0-canary.4
21
27
  */
22
28
  export type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "server"> = {
23
29
  [Key in keyof Catalog as Catalog[Key]["owner"] extends Owner ? Key : never]: Catalog[Key];
@@ -26,6 +32,8 @@ export type EventsOf<Catalog extends EventCatalog, Owner extends "client" | "ser
26
32
  /**
27
33
  * Identity helper for declaring a catalog with inference — nicer call-site than
28
34
  * `satisfies EventCatalog` when the catalog is assembled across multiple files.
35
+ *
36
+ * @since 0.5.0-canary.4
29
37
  */
30
38
  export function defineEventCatalog<Catalog extends EventCatalog>(catalog: Catalog): Catalog {
31
39
  return catalog;
@@ -1,6 +1,8 @@
1
1
  /**
2
2
  * Client-owned events use this at enqueue time; server-owned events derive an ID
3
3
  * from the request instead so retries of the same request don't double-count.
4
+ *
5
+ * @since 0.5.0-canary.4
4
6
  */
5
7
  export function generateEventId(): string {
6
8
  return crypto.randomUUID();
package/src/core/index.ts CHANGED
@@ -1,5 +1,18 @@
1
- export type { ConsentDecision, ConsentMode, ConsentRecord, ConsentRegion, ConsentStorage } from "#/core/consent";
2
- export { resolveConsentMode, shouldTrackByDefault } from "#/core/consent";
1
+ export type {
2
+ ConsentCategory,
3
+ ConsentDecision,
4
+ ConsentMode,
5
+ ConsentRecord,
6
+ ConsentRegion,
7
+ ConsentStorage,
8
+ } from "#/core/consent";
9
+ export {
10
+ CONSENT_CATEGORIES,
11
+ createConsentDecision,
12
+ isConsentDecision,
13
+ resolveConsentMode,
14
+ resolveDefaultConsent,
15
+ } from "#/core/consent";
3
16
 
4
17
  export type { Destination } from "#/core/destination";
5
18
 
@@ -1,5 +1,7 @@
1
1
  /**
2
2
  * Envelope every tracker (client/server) builds before handing an event to a destination.
3
+ *
4
+ * @since 0.5.0-canary.4
3
5
  */
4
6
  export interface TrackedEvent {
5
7
  anonymousId: string;
@@ -0,0 +1,166 @@
1
+ import type { Destination } from "#/core/destination";
2
+
3
+ type MeasurementProtocolParamValue = boolean | number | string;
4
+
5
+ /**
6
+ * Measurement Protocol event params must be flat string/number/boolean — stringify
7
+ * anything else instead of letting GA4 silently drop it.
8
+ */
9
+ function toMeasurementProtocolParams(props: Record<string, unknown>): Record<string, MeasurementProtocolParamValue> {
10
+ const result: Record<string, MeasurementProtocolParamValue> = {};
11
+
12
+ for (const [key, value] of Object.entries(props)) {
13
+ if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
14
+ result[key] = value;
15
+ } else if (value !== undefined && value !== null) {
16
+ result[key] = JSON.stringify(value);
17
+ }
18
+ }
19
+
20
+ return result;
21
+ }
22
+
23
+ function readCookie(cookieHeader: string | undefined, cookieName: string): string | undefined {
24
+ if (!cookieHeader) {
25
+ return undefined;
26
+ }
27
+
28
+ for (const part of cookieHeader.split(";")) {
29
+ const separatorIndex = part.indexOf("=");
30
+
31
+ if (separatorIndex !== -1 && part.slice(0, separatorIndex).trim() === cookieName) {
32
+ return part.slice(separatorIndex + 1).trim();
33
+ }
34
+ }
35
+
36
+ return undefined;
37
+ }
38
+
39
+ /**
40
+ * Reads gtag.js's own client ID from a request Cookie header — `_ga=GA1.1.123.456` →
41
+ * `123.456`. This (not an app-generated anonymous ID) is the value GA4 joins hits on, so
42
+ * pass it as `clientId` to make server events land on the same user as the visitor's
43
+ * client-side hits.
44
+ *
45
+ * @since 0.5.0-canary.4
46
+ */
47
+ export function extractGa4ClientId(cookieHeader: string | undefined): string | undefined {
48
+ const value = readCookie(cookieHeader, "_ga");
49
+
50
+ if (!value) {
51
+ return undefined;
52
+ }
53
+
54
+ // Format: GA1.<domain-depth>.<random>.<timestamp> — the client ID is the last two segments.
55
+ const segments = value.split(".");
56
+
57
+ return segments.length >= 4 ? segments.slice(-2).join(".") : undefined;
58
+ }
59
+
60
+ /**
61
+ * Reads the current GA4 session ID from the per-stream `_ga_<suffix>` cookie
62
+ * (`G-ABC123` → `_ga_ABC123`) — handles both the dot-delimited `GS1` and the
63
+ * `$`-delimited `GS2` value formats.
64
+ *
65
+ * @since 0.5.0-canary.4
66
+ */
67
+ export function extractGa4SessionId(cookieHeader: string | undefined, measurementId: string): string | undefined {
68
+ const value = readCookie(cookieHeader, `_ga_${measurementId.replace(/^G-/, "")}`);
69
+
70
+ if (!value) {
71
+ return undefined;
72
+ }
73
+
74
+ // GS1.1.<session_id>.<count>... vs GS2.1.s<session_id>$o<count>... — the session ID is
75
+ // the first number after the version prefix either way.
76
+ const match = /^GS\d+\.\d+\.s?(\d+)/.exec(value);
77
+
78
+ return match?.[1];
79
+ }
80
+
81
+ /**
82
+ * @since 0.5.0-canary.4
83
+ */
84
+ export interface Ga4MeasurementProtocolDestinationOptions {
85
+ apiSecret: string;
86
+ /**
87
+ * gtag.js's client ID for this visitor (see `extractGa4ClientId`). Without it the
88
+ * event falls back to the tracker's anonymous ID, which GA4 treats as a *different
89
+ * user* than the visitor's client-side hits — pass it whenever the request carries a
90
+ * `_ga` cookie.
91
+ */
92
+ clientId?: string | undefined;
93
+ /** Routes to GA4's `/debug/mp/collect` validation endpoint — hits are validated but never recorded. */
94
+ debug?: boolean;
95
+ measurementId: string;
96
+ name?: string;
97
+ /**
98
+ * Current GA4 session for this visitor (see `extractGa4SessionId`). Without a
99
+ * `session_id`, GA4 accepts the event but leaves it out of session-scoped and realtime
100
+ * reporting.
101
+ */
102
+ sessionId?: string | undefined;
103
+ }
104
+
105
+ /**
106
+ * Server-side GA4 via the Measurement Protocol — for server-owned events (checkout,
107
+ * signup) that must land in GA4 without depending on client-side gtag.js. MP is designed
108
+ * to *augment* gtag.js data, so correlation hinges on echoing gtag's own identifiers:
109
+ * `clientId` from the `_ga` cookie and `sessionId` from the `_ga_<stream>` cookie.
110
+ *
111
+ * @since 0.5.0-canary.4
112
+ */
113
+ export function createGa4MeasurementProtocolDestination(
114
+ options: Ga4MeasurementProtocolDestinationOptions,
115
+ ): Destination {
116
+ const name = options.name ?? "ga4-measurement-protocol";
117
+ const host = options.debug
118
+ ? "https://www.google-analytics.com/debug/mp/collect"
119
+ : "https://www.google-analytics.com/mp/collect";
120
+ const endpoint = `${host}?measurement_id=${encodeURIComponent(options.measurementId)}&api_secret=${encodeURIComponent(options.apiSecret)}`;
121
+
122
+ return {
123
+ name,
124
+ async send(event) {
125
+ // GA4 has no alias concept — identity merge happens via user_id on later events.
126
+ if (event.name === "$alias") {
127
+ return;
128
+ }
129
+
130
+ // join_group is GA4's recommended-event equivalent of a group association.
131
+ const eventName = event.name === "$group" ? "join_group" : event.name;
132
+ const props = event.name === "$group" ? renameGroupIdProp(event.props) : event.props;
133
+ const params = toMeasurementProtocolParams(props);
134
+
135
+ if (options.sessionId !== undefined && params.session_id === undefined) {
136
+ params.session_id = options.sessionId;
137
+ }
138
+
139
+ // Without an engagement time GA4 won't count the user as active in realtime;
140
+ // 100ms is the fallback Google's own MP examples use when elapsed time is unknown.
141
+ params.engagement_time_msec ??= 100;
142
+
143
+ const response = await fetch(endpoint, {
144
+ body: JSON.stringify({
145
+ client_id: options.clientId ?? event.anonymousId,
146
+ events: [{ name: eventName, params }],
147
+ // MP stamps receipt time otherwise — retried events would drift.
148
+ timestamp_micros: event.timestamp * 1000,
149
+ ...(event.userId === undefined ? {} : { user_id: event.userId }),
150
+ }),
151
+ headers: { "content-type": "application/json" },
152
+ method: "POST",
153
+ });
154
+
155
+ if (!response.ok) {
156
+ throw new Error(`"${name}" destination responded with ${String(response.status)}`);
157
+ }
158
+ },
159
+ };
160
+ }
161
+
162
+ function renameGroupIdProp(props: Record<string, unknown>): Record<string, unknown> {
163
+ const { groupId, ...traits } = props;
164
+
165
+ return { group_id: groupId, ...traits };
166
+ }