@shware/analytics 12.1.0 → 13.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -154,9 +154,34 @@ function Button() {
154
154
  }
155
155
  ```
156
156
 
157
+ ### Typed events and strict event names
158
+
159
+ An application types its own events, and adds properties to GA4's standard ones, by declaration merging into `CustomEventProperties` (see its doc comment). By default an event declared nowhere still compiles, with open properties, so `track('purchse', …)` or `track('begin_checkout ', …)` (a trailing space) quietly becomes a new event.
160
+
161
+ Turn on `strict` to make that a compile error. Merge it into `AnalyticsOptions`, preferably in the same file that declares `CustomEventProperties`, so the list of events and the rule that only they can be tracked live together:
162
+
163
+ ```ts
164
+ declare module '@shware/analytics' {
165
+ interface AnalyticsOptions {
166
+ strict: true;
167
+ }
168
+ interface CustomEventProperties {
169
+ plan_changed: { direction: 'upgrade' | 'downgrade' };
170
+ account_deleted: undefined; // an event with no properties
171
+ }
172
+ }
173
+ ```
174
+
175
+ With it on:
176
+
177
+ - Every function that takes an event name — `track`, `trackOnce`, `sendBeacon`, `useTrackImpression` and the third-party senders — accepts only GA4's standard events (`purchase`, `login`, `page_view`, …) and the keys of `CustomEventProperties`. Anything else is an error at the call site, so a new event has to be declared before it can be tracked.
178
+ - `TrackProperties` no longer falls back to the open `Record` for an undeclared event (there is none left to track); declared and standard events are typed exactly as before.
179
+
180
+ It is type-only: nothing changes at runtime, and without the merge the SDK behaves exactly as it always has.
181
+
157
182
  ### When events reach the pixels and the server
158
183
 
159
- Every event gets its id on the client, a uuidv7 generated by `track()` (and `trackOnce()`, `trackAsync()`) at the moment it is tracked. The same id goes to both places:
184
+ Every event gets its id on the client, a uuidv7 generated by `track()` (and `trackOnce()`) at the moment it is tracked. The same id goes to both places:
160
185
 
161
186
  - **The pixels get it at once.** The third-party trackers you configure are called synchronously inside `track()`, with the id as their deduplication id (table below). They do not wait for the server, the 2 s batch window or a beacon, so an event right before a full-page navigation — an outbound link, `begin_checkout` before the redirect to Stripe, a landing page left at once — reaches the pixels before the page goes. A server that is down does not stop them either. A tracker whose pixel has not loaded yet (the SDK's trackers return `false` when their global — `fbq`, `rdt`, `gtag`, … — is missing) is called once more on the next macrotask, with the same event and id, once the inline snippets have run; one that is still missing then is skipped, as before.
162
187
  - **The server gets it in the batch** (`id` in each event of `POST /events`), sent within 2 s, or right away by beacon when the page is hidden or left (`sendPendingEvents`, which the framework `Analytics` components call on `pagehide` and `visibilitychange`). A beacon fires no tracker again.
@@ -172,7 +197,7 @@ The server's conversions API, sending the stored event under the same id, then d
172
197
  | OpenAI pixel (`sendOpenAIEvent`) | `event_id` |
173
198
  | GA4, PostHog, Firebase, Facebook SDK | not passed: they have no browser/server pairing |
174
199
 
175
- `trackAsync` still sends at once and resolves once the server has answered (or the send was lost); await it when the next step needs the event stored. It is no longer needed to keep an event's pixels across a navigation: `track` does that.
200
+ Nothing waits for the server: `track` fires the pixels at once and the batch reaches the server within 2 s or by beacon when the page is left, so there is no `trackAsync` (removed in 13.0). A step that must not run before the server has the event does not belong in the client; record it server-side.
176
201
 
177
202
  ### Tracking an occurrence once (`trackOnce`)
178
203
 
package/dist/index.cjs CHANGED
@@ -35,7 +35,6 @@ Object.defineProperty(exports, "stripeMinorUnits", {
35
35
  }
36
36
  });
37
37
  exports.track = require_track_index.track;
38
- exports.trackAsync = require_track_index.trackAsync;
39
38
  exports.trackOnce = require_track_once.trackOnce;
40
39
  exports.updateVisitorSchema = require_schema_index.updateVisitorSchema;
41
40
  exports.useTrackImpression = require_hooks_use_track_impression.useTrackImpression;
package/dist/index.d.cts CHANGED
@@ -1,14 +1,14 @@
1
- import { AllowedPropertyValues, CustomEventProperties, Environment, Platform, TrackProperties, TrackTags, UTMParams, UserProvidedData } from "./track/types.cjs";
1
+ import { AllowedPropertyValues, AnalyticsOptions, CustomEventProperties, Environment, Platform, TrackProperties, TrackTags, UTMParams, UserProvidedData } from "./track/types.cjs";
2
2
  import { BOT_CATEGORIES, Bot, BotCategory, NOT_A_BOT, botOf } from "./bot/index.cjs";
3
3
  import { ALL_ENVIRONMENTS, ALL_PLATFORMS, CreateFeedbackDTO, CreateLinkDTO, CreateTrackEventDTO, CreateVisitorDTO, UpdateVisitorDTO, createFeedbackSchema, createLinkSchema, createTrackEventSchema, createVisitorSchema, updateVisitorSchema } from "./schema/index.cjs";
4
4
  import { sendFeedback } from "./feedback/index.cjs";
5
5
  import { useTrackImpression } from "./hooks/use-track-impression.cjs";
6
6
  import { VisitorProperties } from "./visitor/types.cjs";
7
7
  import { setupAnalytics } from "./setup/index.cjs";
8
- import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.cjs";
8
+ import { sendBeacon, sendPendingEvents, track } from "./track/index.cjs";
9
9
  import { TrackOnceOptions, trackOnce } from "./track/once.cjs";
10
10
  import { visitorId } from "./visitor/id.cjs";
11
11
  import { IDENTIFY_EVENT, setVisitor } from "./visitor/index.cjs";
12
12
  import { Link, createLink, getLink } from "./link/index.cjs";
13
13
  import { stripeMinorUnits } from "./utils/stripe.cjs";
14
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CreateTrackEventDTO, type CreateVisitorDTO, type CustomEventProperties, type Environment, IDENTIFY_EVENT, type Link, NOT_A_BOT, type Platform, type TrackOnceOptions, type TrackProperties, type TrackTags, type UTMParams, type UpdateVisitorDTO, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
14
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, type AnalyticsOptions, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CreateTrackEventDTO, type CreateVisitorDTO, type CustomEventProperties, type Environment, IDENTIFY_EVENT, type Link, NOT_A_BOT, type Platform, type TrackOnceOptions, type TrackProperties, type TrackTags, type UTMParams, type UpdateVisitorDTO, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
package/dist/index.d.mts CHANGED
@@ -1,14 +1,14 @@
1
- import { AllowedPropertyValues, CustomEventProperties, Environment, Platform, TrackProperties, TrackTags, UTMParams, UserProvidedData } from "./track/types.mjs";
1
+ import { AllowedPropertyValues, AnalyticsOptions, CustomEventProperties, Environment, Platform, TrackProperties, TrackTags, UTMParams, UserProvidedData } from "./track/types.mjs";
2
2
  import { BOT_CATEGORIES, Bot, BotCategory, NOT_A_BOT, botOf } from "./bot/index.mjs";
3
3
  import { ALL_ENVIRONMENTS, ALL_PLATFORMS, CreateFeedbackDTO, CreateLinkDTO, CreateTrackEventDTO, CreateVisitorDTO, UpdateVisitorDTO, createFeedbackSchema, createLinkSchema, createTrackEventSchema, createVisitorSchema, updateVisitorSchema } from "./schema/index.mjs";
4
4
  import { sendFeedback } from "./feedback/index.mjs";
5
5
  import { useTrackImpression } from "./hooks/use-track-impression.mjs";
6
6
  import { VisitorProperties } from "./visitor/types.mjs";
7
7
  import { setupAnalytics } from "./setup/index.mjs";
8
- import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.mjs";
8
+ import { sendBeacon, sendPendingEvents, track } from "./track/index.mjs";
9
9
  import { TrackOnceOptions, trackOnce } from "./track/once.mjs";
10
10
  import { visitorId } from "./visitor/id.mjs";
11
11
  import { IDENTIFY_EVENT, setVisitor } from "./visitor/index.mjs";
12
12
  import { Link, createLink, getLink } from "./link/index.mjs";
13
13
  import { stripeMinorUnits } from "./utils/stripe.mjs";
14
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CreateTrackEventDTO, type CreateVisitorDTO, type CustomEventProperties, type Environment, IDENTIFY_EVENT, type Link, NOT_A_BOT, type Platform, type TrackOnceOptions, type TrackProperties, type TrackTags, type UTMParams, type UpdateVisitorDTO, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
14
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, type AnalyticsOptions, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CreateTrackEventDTO, type CreateVisitorDTO, type CustomEventProperties, type Environment, IDENTIFY_EVENT, type Link, NOT_A_BOT, type Platform, type TrackOnceOptions, type TrackProperties, type TrackTags, type UTMParams, type UpdateVisitorDTO, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { setupAnalytics } from "./setup/index.mjs";
2
2
  import { visitorId } from "./visitor/id.mjs";
3
- import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.mjs";
3
+ import { sendBeacon, sendPendingEvents, track } from "./track/index.mjs";
4
4
  import { trackOnce } from "./track/once.mjs";
5
5
  import { IDENTIFY_EVENT, setVisitor } from "./visitor/index.mjs";
6
6
  import { sendFeedback } from "./feedback/index.mjs";
@@ -9,4 +9,4 @@ import { ALL_ENVIRONMENTS, ALL_PLATFORMS, createFeedbackSchema, createLinkSchema
9
9
  import { BOT_CATEGORIES, NOT_A_BOT, botOf } from "./bot/index.mjs";
10
10
  import { stripeMinorUnits } from "./utils/stripe.mjs";
11
11
  import { useTrackImpression } from "./hooks/use-track-impression.mjs";
12
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, BOT_CATEGORIES, IDENTIFY_EVENT, NOT_A_BOT, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
12
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, BOT_CATEGORIES, IDENTIFY_EVENT, NOT_A_BOT, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackOnce, updateVisitorSchema, useTrackImpression, visitorId };
@@ -2,7 +2,13 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  let _react_native_firebase_analytics = require("@react-native-firebase/analytics");
3
3
  //#region src/native/firebase.ts
4
4
  const analytics = (0, _react_native_firebase_analytics.getAnalytics)();
5
- async function sendFirebaseEvent(name, properties) {
5
+ /**
6
+ * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26
7
+ * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`
8
+ * (`false` meaning "not ready"), which an `async` function's promise would not satisfy. Callers
9
+ * that still `await` it keep compiling.
10
+ */
11
+ function sendFirebaseEvent(name, properties) {
6
12
  if (name === "screen_view") (0, _react_native_firebase_analytics.logEvent)(analytics, "screen_view", {
7
13
  firebase_screen: properties?.screen_name,
8
14
  firebase_screen_class: properties?.screen_class
@@ -1 +1 @@
1
- {"version":3,"file":"firebase.cjs","names":["getAnalytics"],"sources":["../../src/native/firebase.ts"],"sourcesContent":["import { getAnalytics, logEvent } from '@react-native-firebase/analytics';\nimport type { StandardEvents } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\n\nconst analytics = getAnalytics();\n\nexport async function sendFirebaseEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // @react-native-firebase/analytics 26 made the modular logEvent fire-and-forget (void).\n // sendFirebaseEvent stays async so callers that await it keep compiling.\n if (name === 'screen_view') {\n logEvent(analytics, 'screen_view', {\n firebase_screen: (properties as StandardEvents['screen_view'] | undefined)?.screen_name,\n firebase_screen_class: (properties as StandardEvents['screen_view'] | undefined)\n ?.screen_class,\n });\n } else {\n logEvent(analytics, name, properties);\n }\n}\n"],"mappings":";;;AAIA,MAAM,aAAA,GAAYA,iCAAAA,aAAAA,CAAa;AAE/B,eAAsB,kBACpB,MACA,YACA;CAGA,IAAI,SAAS,eACX,CAAA,GAAA,iCAAA,SAAA,CAAS,WAAW,eAAe;EACjC,iBAAkB,YAA0D;EAC5E,uBAAwB,YACpB;CACN,CAAC;MAED,CAAA,GAAA,iCAAA,SAAA,CAAS,WAAW,MAAM,UAAU;AAExC"}
1
+ {"version":3,"file":"firebase.cjs","names":["getAnalytics"],"sources":["../../src/native/firebase.ts"],"sourcesContent":["import { getAnalytics, logEvent } from '@react-native-firebase/analytics';\nimport type { StandardEvents } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\n\nconst analytics = getAnalytics();\n\n/**\n * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26\n * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`\n * (`false` meaning \"not ready\"), which an `async` function's promise would not satisfy. Callers\n * that still `await` it keep compiling.\n */\nexport function sendFirebaseEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (name === 'screen_view') {\n logEvent(analytics, 'screen_view', {\n firebase_screen: (properties as StandardEvents['screen_view'] | undefined)?.screen_name,\n firebase_screen_class: (properties as StandardEvents['screen_view'] | undefined)\n ?.screen_class,\n });\n } else {\n logEvent(analytics, name, properties);\n }\n}\n"],"mappings":";;;AAIA,MAAM,aAAA,GAAYA,iCAAAA,aAAAA,CAAa;;;;;;;AAQ/B,SAAgB,kBACd,MACA,YACA;CACA,IAAI,SAAS,eACX,CAAA,GAAA,iCAAA,SAAA,CAAS,WAAW,eAAe;EACjC,iBAAkB,YAA0D;EAC5E,uBAAwB,YACpB;CACN,CAAC;MAED,CAAA,GAAA,iCAAA,SAAA,CAAS,WAAW,MAAM,UAAU;AAExC"}
@@ -1,5 +1,11 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.cjs";
2
2
  //#region src/native/firebase.d.ts
3
- export declare function sendFirebaseEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): Promise<void>;
3
+ /**
4
+ * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26
5
+ * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`
6
+ * (`false` meaning "not ready"), which an `async` function's promise would not satisfy. Callers
7
+ * that still `await` it keep compiling.
8
+ */
9
+ export declare function sendFirebaseEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
4
10
  //#endregion
5
11
  //# sourceMappingURL=firebase.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"firebase.d.cts","names":[],"sources":["../../src/native/firebase.ts"],"mappings":";;wBAMsB,kBAAkB,UAAU,WAChD,MAAM,UAAU,IAChB,aAAa,gBAAgB,KAAE"}
1
+ {"version":3,"file":"firebase.d.cts","names":[],"sources":["../../src/native/firebase.ts"],"mappings":";;;;;;;;wBAYgB,kBAAkB,UAAU,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -1,5 +1,11 @@
1
1
  import { EventName, TrackName, TrackProperties } from "../track/types.mjs";
2
2
  //#region src/native/firebase.d.ts
3
- export declare function sendFirebaseEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): Promise<void>;
3
+ /**
4
+ * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26
5
+ * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`
6
+ * (`false` meaning "not ready"), which an `async` function's promise would not satisfy. Callers
7
+ * that still `await` it keep compiling.
8
+ */
9
+ export declare function sendFirebaseEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
4
10
  //#endregion
5
11
  //# sourceMappingURL=firebase.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"firebase.d.mts","names":[],"sources":["../../src/native/firebase.ts"],"mappings":";;wBAMsB,kBAAkB,UAAU,WAChD,MAAM,UAAU,IAChB,aAAa,gBAAgB,KAAE"}
1
+ {"version":3,"file":"firebase.d.mts","names":[],"sources":["../../src/native/firebase.ts"],"mappings":";;;;;;;;wBAYgB,kBAAkB,UAAU,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -1,7 +1,13 @@
1
1
  import { getAnalytics, logEvent } from "@react-native-firebase/analytics";
2
2
  //#region src/native/firebase.ts
3
3
  const analytics = getAnalytics();
4
- async function sendFirebaseEvent(name, properties) {
4
+ /**
5
+ * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26
6
+ * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`
7
+ * (`false` meaning "not ready"), which an `async` function's promise would not satisfy. Callers
8
+ * that still `await` it keep compiling.
9
+ */
10
+ function sendFirebaseEvent(name, properties) {
5
11
  if (name === "screen_view") logEvent(analytics, "screen_view", {
6
12
  firebase_screen: properties?.screen_name,
7
13
  firebase_screen_class: properties?.screen_class
@@ -1 +1 @@
1
- {"version":3,"file":"firebase.mjs","names":[],"sources":["../../src/native/firebase.ts"],"sourcesContent":["import { getAnalytics, logEvent } from '@react-native-firebase/analytics';\nimport type { StandardEvents } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\n\nconst analytics = getAnalytics();\n\nexport async function sendFirebaseEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // @react-native-firebase/analytics 26 made the modular logEvent fire-and-forget (void).\n // sendFirebaseEvent stays async so callers that await it keep compiling.\n if (name === 'screen_view') {\n logEvent(analytics, 'screen_view', {\n firebase_screen: (properties as StandardEvents['screen_view'] | undefined)?.screen_name,\n firebase_screen_class: (properties as StandardEvents['screen_view'] | undefined)\n ?.screen_class,\n });\n } else {\n logEvent(analytics, name, properties);\n }\n}\n"],"mappings":";;AAIA,MAAM,YAAY,aAAa;AAE/B,eAAsB,kBACpB,MACA,YACA;CAGA,IAAI,SAAS,eACX,SAAS,WAAW,eAAe;EACjC,iBAAkB,YAA0D;EAC5E,uBAAwB,YACpB;CACN,CAAC;MAED,SAAS,WAAW,MAAM,UAAU;AAExC"}
1
+ {"version":3,"file":"firebase.mjs","names":[],"sources":["../../src/native/firebase.ts"],"sourcesContent":["import { getAnalytics, logEvent } from '@react-native-firebase/analytics';\nimport type { StandardEvents } from '../track/gtag';\nimport type { EventName, TrackName, TrackProperties } from '../track/types';\n\nconst analytics = getAnalytics();\n\n/**\n * A `ThirdPartyTracker` for Firebase Analytics. Synchronous: @react-native-firebase/analytics 26\n * made the modular `logEvent` fire-and-forget (void), and a tracker's return is `void | boolean`\n * (`false` meaning \"not ready\"), which an `async` function's promise would not satisfy. Callers\n * that still `await` it keep compiling.\n */\nexport function sendFirebaseEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (name === 'screen_view') {\n logEvent(analytics, 'screen_view', {\n firebase_screen: (properties as StandardEvents['screen_view'] | undefined)?.screen_name,\n firebase_screen_class: (properties as StandardEvents['screen_view'] | undefined)\n ?.screen_class,\n });\n } else {\n logEvent(analytics, name, properties);\n }\n}\n"],"mappings":";;AAIA,MAAM,YAAY,aAAa;;;;;;;AAQ/B,SAAgB,kBACd,MACA,YACA;CACA,IAAI,SAAS,eACX,SAAS,WAAW,eAAe;EACjC,iBAAkB,YAA0D;EAC5E,uBAAwB,YACpB;CACN,CAAC;MAED,SAAS,WAAW,MAAM,UAAU;AAExC"}
@@ -187,36 +187,6 @@ function queueEvent(name, properties, options, init) {
187
187
  function track(name, properties, options = defaultOptions) {
188
188
  queueEvent(name, properties, options);
189
189
  }
190
- /**
191
- * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
192
- * when the send could not start (its headers or rate limit threw), at once, the event left queued
193
- * for the next send. It never rejects: tracking must not fail the step that awaits it.
194
- *
195
- * The third-party trackers are not what it waits for: as with `track`, they are fired at once.
196
- * Await it when the next step needs the event stored by the server; a page about to navigate
197
- * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`
198
- * on `pagehide` to have it reach the server.
199
- */
200
- async function trackAsync(name, properties, options = defaultOptions) {
201
- let settle;
202
- const settled = new Promise((resolve) => {
203
- settle = resolve;
204
- });
205
- const event = enqueue(name, properties, {
206
- ...options,
207
- onSucceed: (response) => {
208
- options.onSucceed?.(response);
209
- settle();
210
- },
211
- onError: (error) => {
212
- options.onError?.(error);
213
- settle();
214
- }
215
- });
216
- await flush();
217
- if (list.includes(event)) return;
218
- await settled;
219
- }
220
190
  function beacon(dto) {
221
191
  if (typeof navigator === "undefined" || !("sendBeacon" in navigator)) return false;
222
192
  const blob = new Blob([JSON.stringify(dto)], { type: "text/plain;charset=UTF-8" });
@@ -268,6 +238,5 @@ exports.queueEvent = queueEvent;
268
238
  exports.sendBeacon = sendBeacon;
269
239
  exports.sendPendingEvents = sendPendingEvents;
270
240
  exports.track = track;
271
- exports.trackAsync = trackAsync;
272
241
 
273
242
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\n/**\n * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when the send could not start (its headers or rate limit threw), at once, the event left queued\n * for the next send. It never rejects: tracking must not fail the step that awaits it.\n *\n * The third-party trackers are not what it waits for: as with `track`, they are fired at once.\n * Await it when the next step needs the event stored by the server; a page about to navigate\n * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`\n * on `pagehide` to have it reach the server.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send failed before taking it. It waits for the next send, but the caller,\n // who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAOC,oBAAAA,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAA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AO,YAAY,MAAM,WAAWJ,oBAAAA,MAAM,QAAQ,CAAC,CAAC,CAE9C,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaI,mBAAAA,UAAU;CAG7B,MAAM,aAAaF,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UA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AO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaI,mBAAAA,UAAU;CAG7B,MAAM,aAAaF,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -25,17 +25,6 @@ export declare function queueEvent<T extends EventName = EventName>(name: TrackN
25
25
  * hands it to the third-party trackers now, under the id it is sent with.
26
26
  */
27
27
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
28
- /**
29
- * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
30
- * when the send could not start (its headers or rate limit threw), at once, the event left queued
31
- * for the next send. It never rejects: tracking must not fail the step that awaits it.
32
- *
33
- * The third-party trackers are not what it waits for: as with `track`, they are fired at once.
34
- * Await it when the next step needs the event stored by the server; a page about to navigate
35
- * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`
36
- * on `pagehide` to have it reach the server.
37
- */
38
- export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
39
28
  /**
40
29
  * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
41
30
  * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBAuLc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;wBAeW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBA6CxB;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBAuLc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -25,17 +25,6 @@ export declare function queueEvent<T extends EventName = EventName>(name: TrackN
25
25
  * hands it to the third-party trackers now, under the id it is sent with.
26
26
  */
27
27
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
28
- /**
29
- * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
30
- * when the send could not start (its headers or rate limit threw), at once, the event left queued
31
- * for the next send. It never rejects: tracking must not fail the step that awaits it.
32
- *
33
- * The third-party trackers are not what it waits for: as with `track`, they are fired at once.
34
- * Await it when the next step needs the event stored by the server; a page about to navigate
35
- * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`
36
- * on `pagehide` to have it reach the server.
37
- */
38
- export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
39
28
  /**
40
29
  * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
41
30
  * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBAuLc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;wBAeW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBA6CxB;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBAuLc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -186,36 +186,6 @@ function queueEvent(name, properties, options, init) {
186
186
  function track(name, properties, options = defaultOptions) {
187
187
  queueEvent(name, properties, options);
188
188
  }
189
- /**
190
- * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
191
- * when the send could not start (its headers or rate limit threw), at once, the event left queued
192
- * for the next send. It never rejects: tracking must not fail the step that awaits it.
193
- *
194
- * The third-party trackers are not what it waits for: as with `track`, they are fired at once.
195
- * Await it when the next step needs the event stored by the server; a page about to navigate
196
- * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`
197
- * on `pagehide` to have it reach the server.
198
- */
199
- async function trackAsync(name, properties, options = defaultOptions) {
200
- let settle;
201
- const settled = new Promise((resolve) => {
202
- settle = resolve;
203
- });
204
- const event = enqueue(name, properties, {
205
- ...options,
206
- onSucceed: (response) => {
207
- options.onSucceed?.(response);
208
- settle();
209
- },
210
- onError: (error) => {
211
- options.onError?.(error);
212
- settle();
213
- }
214
- });
215
- await flush();
216
- if (list.includes(event)) return;
217
- await settled;
218
- }
219
189
  function beacon(dto) {
220
190
  if (typeof navigator === "undefined" || !("sendBeacon" in navigator)) return false;
221
191
  const blob = new Blob([JSON.stringify(dto)], { type: "text/plain;charset=UTF-8" });
@@ -263,6 +233,6 @@ function sendBeacon(name, properties) {
263
233
  console.warn("Failed to send beacon", name, properties);
264
234
  }
265
235
  //#endregion
266
- export { queueEvent, sendBeacon, sendPendingEvents, track, trackAsync };
236
+ export { queueEvent, sendBeacon, sendPendingEvents, track };
267
237
 
268
238
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\n/**\n * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when the send could not start (its headers or rate limit threw), at once, the event left queued\n * for the next send. It never rejects: tracking must not fail the step that awaits it.\n *\n * The third-party trackers are not what it waits for: as with `track`, they are fired at once.\n * Await it when the next step needs the event stored by the server; a page about to navigate\n * away needs no more than `track` to have its event reach the pixels, and `sendPendingEvents`\n * on `pagehide` to have it reach the server.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send failed before taking it. It waits for the next send, but the caller,\n // who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,OAAa;CAG/B,IAAI,MAAM,QAAQ,6BAA6B,SAAS,eAAe,SAAS,MAAM,IAAI,GACxF;CAEF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,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,IAAIA,GAAO;EACX;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,OAAa;CAG/B,IAAI,MAAM,QAAQ,6BAA6B,SAAS,eAAe,SAAS,MAAM,IAAI,GACxF;CAEF,MAAM,WAAW,aAAa,OAAO,oBAAoB,KAAK;CAC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AAK;AAC9C;;;;;AAMA,SAAgB,MACd,MACA,YACA,UAAwB,gBACxB;CACA,WAAW,MAAM,YAAY,OAAO;AACtC;AAEA,SAAS,OAAO,KAAmC;CAEjD,IAAI,OAAO,cAAc,eAAe,EAAE,gBAAgB,YAAY,OAAO;CAI7E,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,2BAA2B,CAAC;CACjF,OAAO,UAAU,WAAW,GAAG,OAAO,SAAS,UAAU,IAAI;AAC/D;;;;;;;;;;;;AAaA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,MAAM,aAAa,UAAU;CAI7B,IAAI,CAAC,OAH4B,KAAK,KAAK,UACzC,MAAM,OAAO,YAAY,MAAM,WAAW,MAAM,QAAQ,CAAC,CAAC,CAE9C,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,UAAU;CAG7B,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,IAAIA,GAAO;EACX;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -2,14 +2,50 @@ import { StandardEvents, UserProvidedData as UserProvidedData$1 } from "./gtag.c
2
2
  //#region src/track/types.d.ts
3
3
  export type AllowedPropertyValues = string | number | boolean | null;
4
4
  export type EventName = Lowercase<string> | 'CLS' | 'FCP' | 'INP' | 'LCP' | 'TTFB';
5
- export type TrackName<T extends EventName = EventName> = T extends keyof StandardEvents ? T : EventName;
5
+ /**
6
+ * Type-level switches an application turns on by declaration merging, the way it fills
7
+ * `CustomEventProperties` — usually in the same file:
8
+ *
9
+ * ```ts
10
+ * declare module '@shware/analytics' {
11
+ * interface AnalyticsOptions {
12
+ * strict: true;
13
+ * }
14
+ * }
15
+ * ```
16
+ *
17
+ * - `strict: true` — strict events: every function that takes an event name (`track`, `trackOnce`,
18
+ * `sendBeacon`, `useTrackImpression`, the third-party senders) accepts only
19
+ * GA4's standard events and the events declared in `CustomEventProperties`: a misspelled or
20
+ * undeclared name (`'purchse'`, `'begin_checkout '`) is a compile error instead of a new event.
21
+ *
22
+ * Empty by default, so nothing changes for an application that never merges into it.
23
+ */
24
+ export interface AnalyticsOptions {}
25
+ /** Whether the application turned on `AnalyticsOptions['strict']`. */
26
+ type Strict = AnalyticsOptions extends {
27
+ strict: true;
28
+ } ? true : false;
29
+ /**
30
+ * The names `track` accepts with `strict` on: GA4's standard events and the events
31
+ * the application declared. Only declared keys that are themselves valid event names, so the
32
+ * set stays within `EventName`.
33
+ */
34
+ export type DeclaredEventName = keyof StandardEvents | Extract<keyof CustomEventProperties, EventName>;
35
+ /**
36
+ * The type of an event-name parameter. `T` is inferred from the argument through both branches;
37
+ * the false branch is what the argument is checked against when it is not a known event — any
38
+ * event name by default, only a declared one with `strict` on.
39
+ */
40
+ export type TrackName<T extends EventName = EventName> = Strict extends true ? T extends DeclaredEventName ? T : DeclaredEventName : T extends keyof StandardEvents ? T : EventName;
6
41
  /**
7
42
  * Properties an application defines for its own events, keyed by event name.
8
43
  *
9
44
  * Empty here on purpose. Applications fill it by declaration merging, and it does two jobs:
10
45
  * it adds custom properties to GA4's standard events, which are otherwise closed shapes and
11
46
  * would need a cast; and it gives an application's own events a real type instead of the
12
- * open record they fall back to.
47
+ * open record they fall back to. With `AnalyticsOptions['strict']` on, it is also the
48
+ * list of the custom event names `track` accepts.
13
49
  *
14
50
  * ```ts
15
51
  * declare module '@shware/analytics' {
@@ -37,7 +73,7 @@ export interface CustomEventProperties {}
37
73
  * no declaration intersects to exactly the type it had before.
38
74
  */
39
75
  type CustomPropertiesFor<T> = T extends keyof CustomEventProperties ? CustomEventProperties[T] : unknown;
40
- export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Record<Lowercase<string>, AllowedPropertyValues>;
76
+ export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Strict extends true ? never : Record<Lowercase<string>, AllowedPropertyValues>;
41
77
  export type Platform = 'ios' | 'android' | 'web' | 'macos' | 'windows' | 'linux' | 'unknown';
42
78
  export type Environment = 'development' | 'production';
43
79
  export interface UserData {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.cts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;YAEZ,UAAU,UAAU,YAAY,aAAa,gBAAgB,iBACrE,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Ba;;;;;;;KAQZ,oBAAoB,KAAK,gBAAgB,wBAC1C,sBAAsB;YAGd,gBAAgB,UAAU,YAAY,aAAa,gBAAgB,iBAC3E,eAAe,KAAK,oBAAoB,KACxC,gBAAgB,wBACd,sBAAsB,KACtB,OAAO,mBAAmB;YAEpB;YACA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,yBAAyBA;EACxC;EACA;EACA;EACA;EACA;IAAa;IAAc;IAAe;;EAE1C;EACA;;;;;;;;;;;YAYU,qBAAqB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;iBAGe;;EAEf;EACA;;iBAGe;EACf;EACA;EACA;;;;;;;;;;iBAWe;EACf;EACA;EACA;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;iBAce;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;;;;;;;;EAQA;;;;;;EAMA;EACA;EACA;EACA;;EAEA;;EAEA;EAEA;;EAEA;EAEA;;EAEA;;EAEA;;EAEA;EAEA;;;;;EAKA;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAQe;;EAEf;;;;;;;;;;;;EAqCA;;;;;;EAuDA;;EAMA;;EAEA;;EAEA;;EAEA;;EAUA;;EAEA;;iBAGe,kBACP,cAAc,YAAY,SAAS,iBAAiB,UAAU,iBAAiB;EACvF;GACC;;iBAGc,WAAW,UAAU,YAAY;EAChD;EACA,MAAM,UAAU;EAChB,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,aAAa,gBAAgB;EAC7B;;;;;;;;;;YAWU;;EAEV"}
1
+ {"version":3,"file":"types.d.cts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;;;;;;;;;;;;;;;;;;;;iBAsBP;;KAGZ,SAAS;EAA2B;;;;;;;YAO7B,0BACF,iBACN,cAAc,uBAAuB;;;;;;YAO7B,UAAU,UAAU,YAAY,aAAa,sBACrD,UAAU,oBACR,IACA,oBACF,gBAAgB,iBACd,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCW;;;;;;;KAQZ,oBAAoB,KAAK,gBAAgB,wBAC1C,sBAAsB;YAGd,gBAAgB,UAAU,YAAY,aAAa,gBAAgB,iBAC3E,eAAe,KAAK,oBAAoB,KACxC,gBAAgB,wBACd,sBAAsB,KAGtB,8BAEE,OAAO,mBAAmB;YAEtB;YACA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,yBAAyBA;EACxC;EACA;EACA;EACA;EACA;IAAa;IAAc;IAAe;;EAE1C;EACA;;;;;;;;;;;YAYU,qBAAqB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;iBAGe;;EAEf;EACA;;iBAGe;EACf;EACA;EACA;;;;;;;;;;iBAWe;EACf;EACA;EACA;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;iBAce;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;;;;;;;;EAQA;;;;;;EAMA;EACA;EACA;EACA;;EAEA;;EAEA;EAEA;;EAEA;EAEA;;EAEA;;EAEA;;EAEA;EAEA;;;;;EAKA;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAQe;;EAEf;;;;;;;;;;;;EAqCA;;;;;;EAuDA;;EAMA;;EAEA;;EAEA;;EAEA;;EAUA;;EAEA;;iBAGe,kBACP,cAAc,YAAY,SAAS,iBAAiB,UAAU,iBAAiB;EACvF;GACC;;iBAGc,WAAW,UAAU,YAAY;EAChD;EACA,MAAM,UAAU;EAChB,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,aAAa,gBAAgB;EAC7B;;;;;;;;;;YAWU;;EAEV"}
@@ -2,14 +2,50 @@ import { StandardEvents, UserProvidedData as UserProvidedData$1 } from "./gtag.m
2
2
  //#region src/track/types.d.ts
3
3
  export type AllowedPropertyValues = string | number | boolean | null;
4
4
  export type EventName = Lowercase<string> | 'CLS' | 'FCP' | 'INP' | 'LCP' | 'TTFB';
5
- export type TrackName<T extends EventName = EventName> = T extends keyof StandardEvents ? T : EventName;
5
+ /**
6
+ * Type-level switches an application turns on by declaration merging, the way it fills
7
+ * `CustomEventProperties` — usually in the same file:
8
+ *
9
+ * ```ts
10
+ * declare module '@shware/analytics' {
11
+ * interface AnalyticsOptions {
12
+ * strict: true;
13
+ * }
14
+ * }
15
+ * ```
16
+ *
17
+ * - `strict: true` — strict events: every function that takes an event name (`track`, `trackOnce`,
18
+ * `sendBeacon`, `useTrackImpression`, the third-party senders) accepts only
19
+ * GA4's standard events and the events declared in `CustomEventProperties`: a misspelled or
20
+ * undeclared name (`'purchse'`, `'begin_checkout '`) is a compile error instead of a new event.
21
+ *
22
+ * Empty by default, so nothing changes for an application that never merges into it.
23
+ */
24
+ export interface AnalyticsOptions {}
25
+ /** Whether the application turned on `AnalyticsOptions['strict']`. */
26
+ type Strict = AnalyticsOptions extends {
27
+ strict: true;
28
+ } ? true : false;
29
+ /**
30
+ * The names `track` accepts with `strict` on: GA4's standard events and the events
31
+ * the application declared. Only declared keys that are themselves valid event names, so the
32
+ * set stays within `EventName`.
33
+ */
34
+ export type DeclaredEventName = keyof StandardEvents | Extract<keyof CustomEventProperties, EventName>;
35
+ /**
36
+ * The type of an event-name parameter. `T` is inferred from the argument through both branches;
37
+ * the false branch is what the argument is checked against when it is not a known event — any
38
+ * event name by default, only a declared one with `strict` on.
39
+ */
40
+ export type TrackName<T extends EventName = EventName> = Strict extends true ? T extends DeclaredEventName ? T : DeclaredEventName : T extends keyof StandardEvents ? T : EventName;
6
41
  /**
7
42
  * Properties an application defines for its own events, keyed by event name.
8
43
  *
9
44
  * Empty here on purpose. Applications fill it by declaration merging, and it does two jobs:
10
45
  * it adds custom properties to GA4's standard events, which are otherwise closed shapes and
11
46
  * would need a cast; and it gives an application's own events a real type instead of the
12
- * open record they fall back to.
47
+ * open record they fall back to. With `AnalyticsOptions['strict']` on, it is also the
48
+ * list of the custom event names `track` accepts.
13
49
  *
14
50
  * ```ts
15
51
  * declare module '@shware/analytics' {
@@ -37,7 +73,7 @@ export interface CustomEventProperties {}
37
73
  * no declaration intersects to exactly the type it had before.
38
74
  */
39
75
  type CustomPropertiesFor<T> = T extends keyof CustomEventProperties ? CustomEventProperties[T] : unknown;
40
- export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Record<Lowercase<string>, AllowedPropertyValues>;
76
+ export type TrackProperties<T extends EventName = EventName> = T extends keyof StandardEvents ? StandardEvents[T] & CustomPropertiesFor<T> : T extends keyof CustomEventProperties ? CustomEventProperties[T] : Strict extends true ? never : Record<Lowercase<string>, AllowedPropertyValues>;
41
77
  export type Platform = 'ios' | 'android' | 'web' | 'macos' | 'windows' | 'linux' | 'unknown';
42
78
  export type Environment = 'development' | 'production';
43
79
  export interface UserData {
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.mts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;YAEZ,UAAU,UAAU,YAAY,aAAa,gBAAgB,iBACrE,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;iBA+Ba;;;;;;;KAQZ,oBAAoB,KAAK,gBAAgB,wBAC1C,sBAAsB;YAGd,gBAAgB,UAAU,YAAY,aAAa,gBAAgB,iBAC3E,eAAe,KAAK,oBAAoB,KACxC,gBAAgB,wBACd,sBAAsB,KACtB,OAAO,mBAAmB;YAEpB;YACA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,yBAAyBA;EACxC;EACA;EACA;EACA;EACA;IAAa;IAAc;IAAe;;EAE1C;EACA;;;;;;;;;;;YAYU,qBAAqB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;iBAGe;;EAEf;EACA;;iBAGe;EACf;EACA;EACA;;;;;;;;;;iBAWe;EACf;EACA;EACA;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;iBAce;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;;;;;;;;EAQA;;;;;;EAMA;EACA;EACA;EACA;;EAEA;;EAEA;EAEA;;EAEA;EAEA;;EAEA;;EAEA;;EAEA;EAEA;;;;;EAKA;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAQe;;EAEf;;;;;;;;;;;;EAqCA;;;;;;EAuDA;;EAMA;;EAEA;;EAEA;;EAEA;;EAUA;;EAEA;;iBAGe,kBACP,cAAc,YAAY,SAAS,iBAAiB,UAAU,iBAAiB;EACvF;GACC;;iBAGc,WAAW,UAAU,YAAY;EAChD;EACA,MAAM,UAAU;EAChB,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,aAAa,gBAAgB;EAC7B;;;;;;;;;;YAWU;;EAEV"}
1
+ {"version":3,"file":"types.d.mts","names":["GAUserProvidedData"],"sources":["../../src/track/types.ts"],"mappings":";;YAEY;YACA,YAAY;;;;;;;;;;;;;;;;;;;;iBAsBP;;KAGZ,SAAS;EAA2B;;;;;;;YAO7B,0BACF,iBACN,cAAc,uBAAuB;;;;;;YAO7B,UAAU,UAAU,YAAY,aAAa,sBACrD,UAAU,oBACR,IACA,oBACF,gBAAgB,iBACd,IACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAgCW;;;;;;;KAQZ,oBAAoB,KAAK,gBAAgB,wBAC1C,sBAAsB;YAGd,gBAAgB,UAAU,YAAY,aAAa,gBAAgB,iBAC3E,eAAe,KAAK,oBAAoB,KACxC,gBAAgB,wBACd,sBAAsB,KAGtB,8BAEE,OAAO,mBAAmB;YAEtB;YACA;iBAEK;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;iBAGe,yBAAyBA;EACxC;EACA;EACA;EACA;EACA;IAAa;IAAc;IAAe;;EAE1C;EACA;;;;;;;;;;;YAYU,qBAAqB,UAAU,WACzC,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;;iBAGe;EACf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAEA;;iBAGe;;EAEf;EACA;;iBAGe;EACf;EACA;EACA;;;;;;;;;;iBAWe;EACf;EACA;EACA;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;iBAce;EAEf;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;;;;;EAMA;;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;;;;;;;;EAQA;;;;;;EAMA;EACA;EACA;EACA;;EAEA;;EAEA;EAEA;;EAEA;EAEA;;EAEA;;EAEA;;EAEA;EAEA;;;;;EAKA;EAEA;;EAEA;;EAEA;EAEA;EACA;EACA;EACA;EACA;EACA;;;;;;;iBAQe;;EAEf;;;;;;;;;;;;EAqCA;;;;;;EAuDA;;EAMA;;EAEA;;EAEA;;EAEA;;EAUA;;EAEA;;iBAGe,kBACP,cAAc,YAAY,SAAS,iBAAiB,UAAU,iBAAiB;EACvF;GACC;;iBAGc,WAAW,UAAU,YAAY;EAChD;EACA,MAAM,UAAU;EAChB,MAAM;EACN;EACA;EACA,UAAU;EACV,aAAa;EACb,aAAa,gBAAgB;EAC7B;;;;;;;;;;YAWU;;EAEV"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "12.1.0",
3
+ "version": "13.0.0",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",
@@ -254,7 +254,7 @@
254
254
  },
255
255
  "scripts": {
256
256
  "dev": "tsc --watch",
257
- "check-types": "tsc --noEmit",
257
+ "check-types": "tsc --noEmit && tsc --noEmit -p src/track/strict-event-names",
258
258
  "test": "vitest run --passWithNoTests",
259
259
  "lint": "oxlint --type-aware . --fix",
260
260
  "build": "tsdown"