@shware/analytics 12.0.0 → 12.2.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.
Files changed (76) hide show
  1. package/README.md +63 -1
  2. package/dist/index.d.cts +2 -2
  3. package/dist/index.d.mts +2 -2
  4. package/dist/native/firebase.cjs +7 -1
  5. package/dist/native/firebase.cjs.map +1 -1
  6. package/dist/native/firebase.d.cts +7 -1
  7. package/dist/native/firebase.d.cts.map +1 -1
  8. package/dist/native/firebase.d.mts +7 -1
  9. package/dist/native/firebase.d.mts.map +1 -1
  10. package/dist/native/firebase.mjs +7 -1
  11. package/dist/native/firebase.mjs.map +1 -1
  12. package/dist/schema/index.cjs +10 -2
  13. package/dist/schema/index.cjs.map +1 -1
  14. package/dist/schema/index.d.cts +3 -0
  15. package/dist/schema/index.d.cts.map +1 -1
  16. package/dist/schema/index.d.mts +3 -0
  17. package/dist/schema/index.d.mts.map +1 -1
  18. package/dist/schema/index.mjs +10 -2
  19. package/dist/schema/index.mjs.map +1 -1
  20. package/dist/third-parties/google-analytics.cjs +1 -1
  21. package/dist/third-parties/google-analytics.cjs.map +1 -1
  22. package/dist/third-parties/google-analytics.d.cts +1 -1
  23. package/dist/third-parties/google-analytics.d.mts +1 -1
  24. package/dist/third-parties/google-analytics.mjs +1 -1
  25. package/dist/third-parties/google-analytics.mjs.map +1 -1
  26. package/dist/third-parties/linkedin-insight-tag.cjs +1 -1
  27. package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
  28. package/dist/third-parties/linkedin-insight-tag.d.cts +1 -1
  29. package/dist/third-parties/linkedin-insight-tag.d.mts +1 -1
  30. package/dist/third-parties/linkedin-insight-tag.mjs +1 -1
  31. package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
  32. package/dist/third-parties/meta-pixel.cjs +1 -1
  33. package/dist/third-parties/meta-pixel.cjs.map +1 -1
  34. package/dist/third-parties/meta-pixel.d.cts +1 -1
  35. package/dist/third-parties/meta-pixel.d.mts +1 -1
  36. package/dist/third-parties/meta-pixel.mjs +1 -1
  37. package/dist/third-parties/meta-pixel.mjs.map +1 -1
  38. package/dist/third-parties/microsoft-uet.cjs +1 -1
  39. package/dist/third-parties/microsoft-uet.cjs.map +1 -1
  40. package/dist/third-parties/microsoft-uet.d.cts +1 -1
  41. package/dist/third-parties/microsoft-uet.d.mts +1 -1
  42. package/dist/third-parties/microsoft-uet.mjs +1 -1
  43. package/dist/third-parties/microsoft-uet.mjs.map +1 -1
  44. package/dist/third-parties/openai-pixel.cjs +1 -1
  45. package/dist/third-parties/openai-pixel.cjs.map +1 -1
  46. package/dist/third-parties/openai-pixel.d.cts +1 -1
  47. package/dist/third-parties/openai-pixel.d.mts +1 -1
  48. package/dist/third-parties/openai-pixel.mjs +1 -1
  49. package/dist/third-parties/openai-pixel.mjs.map +1 -1
  50. package/dist/third-parties/reddit-pixel.cjs +1 -1
  51. package/dist/third-parties/reddit-pixel.cjs.map +1 -1
  52. package/dist/third-parties/reddit-pixel.d.cts +1 -1
  53. package/dist/third-parties/reddit-pixel.d.mts +1 -1
  54. package/dist/third-parties/reddit-pixel.mjs +1 -1
  55. package/dist/third-parties/reddit-pixel.mjs.map +1 -1
  56. package/dist/track/index.cjs +77 -42
  57. package/dist/track/index.cjs.map +1 -1
  58. package/dist/track/index.d.cts +28 -4
  59. package/dist/track/index.d.cts.map +1 -1
  60. package/dist/track/index.d.mts +28 -4
  61. package/dist/track/index.d.mts.map +1 -1
  62. package/dist/track/index.mjs +77 -43
  63. package/dist/track/index.mjs.map +1 -1
  64. package/dist/track/once.cjs +65 -17
  65. package/dist/track/once.cjs.map +1 -1
  66. package/dist/track/once.d.cts +5 -4
  67. package/dist/track/once.d.cts.map +1 -1
  68. package/dist/track/once.d.mts +5 -4
  69. package/dist/track/once.d.mts.map +1 -1
  70. package/dist/track/once.mjs +66 -18
  71. package/dist/track/once.mjs.map +1 -1
  72. package/dist/track/types.d.cts +58 -5
  73. package/dist/track/types.d.cts.map +1 -1
  74. package/dist/track/types.d.mts +58 -5
  75. package/dist/track/types.d.mts.map +1 -1
  76. package/package.json +2 -2
@@ -4,6 +4,7 @@ const require_setup_session = require("../setup/session.cjs");
4
4
  const require_third_parties_ignored_events = require("../third-parties/ignored-events.cjs");
5
5
  const require_visitor_id = require("../visitor/id.cjs");
6
6
  let _shware_utils = require("@shware/utils");
7
+ let uuid = require("uuid");
7
8
  //#region src/track/index.ts
8
9
  const defaultOptions = {};
9
10
  let tokenBucket;
@@ -47,7 +48,40 @@ const batchSize = 10;
47
48
  const delay = 2e3;
48
49
  let timer = null;
49
50
  /**
50
- * Queues an event, preceded by a `session_start` when it is the one that opens a session.
51
+ * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once
52
+ * the server has answered. An event followed by a full-page navigation (an outbound link,
53
+ * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches
54
+ * the pixels before the page goes, and the server's conversions API, sending the same id, still
55
+ * deduplicates against the browser event. A server that is down no longer takes the pixels down
56
+ * with it either.
57
+ *
58
+ * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the
59
+ * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).
60
+ * Those trackers, and only those, are called once more on the next macrotask, with the same event
61
+ * and id, after the inline snippets have had their turn; a tracker still not ready then is given
62
+ * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global
63
+ * either exists by then or the script is blocked.
64
+ */
65
+ function firePixels(event) {
66
+ if (event.options.enableThirdPartyTracking === false || require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)) return;
67
+ const notReady = callTrackers(require_setup_index.config.thirdPartyTrackers, event);
68
+ if (notReady.length === 0) return;
69
+ setTimeout(() => callTrackers(notReady, event), 0);
70
+ }
71
+ /** Calls each tracker with the event; returns the ones that said they were not ready. */
72
+ function callTrackers(trackers, event) {
73
+ return trackers.filter((tracker) => {
74
+ try {
75
+ return tracker(event.name, event.properties, event.id) === false;
76
+ } catch (e) {
77
+ if (e instanceof Error) console.log(e.message);
78
+ return false;
79
+ }
80
+ });
81
+ }
82
+ /**
83
+ * Queues an event, preceded by a `session_start` when it is the one that opens a session, and
84
+ * fires its third-party trackers.
51
85
  *
52
86
  * The session is decided here, when the event happens, as GA4 and PostHog decide it: the
53
87
  * `session_start` then sits in the queue right before the event that opened the session, so
@@ -56,7 +90,7 @@ let timer = null;
56
90
  * session: the landing page is where the session began, whatever the page has navigated to by
57
91
  * the time the batch goes out.
58
92
  */
59
- function enqueue(name, properties, options) {
93
+ function enqueue(name, properties, options, init = {}) {
60
94
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
61
95
  const tags = captureTags();
62
96
  const { id: session_id, started } = require_setup_session.getSession().touch(Date.parse(timestamp));
@@ -71,18 +105,34 @@ function enqueue(name, properties, options) {
71
105
  return result;
72
106
  };
73
107
  if (started) list.push(item({
108
+ id: (0, uuid.v7)(),
74
109
  name: "session_start",
75
110
  properties: {},
76
111
  options: { enableThirdPartyTracking: false }
77
112
  }));
78
113
  const event = item({
114
+ id: init.id ?? (0, uuid.v7)(),
79
115
  name,
80
116
  properties,
81
117
  options
82
118
  });
83
119
  list.push(event);
120
+ if (init.pixels !== false) firePixels(event);
84
121
  return event;
85
122
  }
123
+ function toDTO(event, visitor_id, tags) {
124
+ return {
125
+ id: event.id,
126
+ name: event.name,
127
+ properties: event.properties,
128
+ tags,
129
+ visitor_id,
130
+ session_id: event.session_id,
131
+ platform: require_setup_index.config.platform,
132
+ environment: require_setup_index.config.environment,
133
+ timestamp: event.timestamp
134
+ };
135
+ }
86
136
  /**
87
137
  * Sends the queue. Everything that has to be awaited is awaited first, and only then are the
88
138
  * events taken off the queue and handed to `fetch` in the same synchronous step — so there is
@@ -102,16 +152,7 @@ async function flush() {
102
152
  await Promise.all(list.map((event) => event.tags));
103
153
  events = list.splice(0);
104
154
  if (events.length === 0) return;
105
- const dto = await Promise.all(events.map(async (event) => ({
106
- name: event.name,
107
- properties: event.properties,
108
- tags: await event.tags,
109
- visitor_id,
110
- session_id: event.session_id,
111
- platform: require_setup_index.config.platform,
112
- environment: require_setup_index.config.environment,
113
- timestamp: event.timestamp
114
- })));
155
+ const dto = await Promise.all(events.map(async (event) => toDTO(event, visitor_id, await event.tags)));
115
156
  const body = JSON.stringify(dto);
116
157
  const response = await (0, _shware_utils.fetch)(`${require_setup_index.config.endpoint}/events`, {
117
158
  method: "POST",
@@ -121,19 +162,7 @@ async function flush() {
121
162
  body
122
163
  });
123
164
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
124
- const data = await response.json();
125
- events.forEach((event, index) => {
126
- const eventId = data.at(index)?.id;
127
- event.options.onSucceed?.(eventId ? { id: eventId } : void 0);
128
- if (event.options.enableThirdPartyTracking === false || require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)) return;
129
- require_setup_index.config.thirdPartyTrackers.forEach((tracker) => {
130
- try {
131
- tracker(event.name, event.properties, eventId);
132
- } catch (e) {
133
- if (e instanceof Error) console.log(e.message);
134
- }
135
- });
136
- });
165
+ events.forEach((event) => event.options.onSucceed?.({ id: event.id }));
137
166
  } catch (e) {
138
167
  if (e instanceof Error) console.log(e.message);
139
168
  const starts = events.filter((event) => event.name === "session_start");
@@ -141,8 +170,9 @@ async function flush() {
141
170
  events.filter((event) => event.name !== "session_start").forEach((event) => event.options.onError?.(e));
142
171
  }
143
172
  }
144
- function track(name, properties, options = defaultOptions) {
145
- enqueue(name, properties, options);
173
+ /** `track`, with the `EventInit` only the SDK itself passes. */
174
+ function queueEvent(name, properties, options, init) {
175
+ enqueue(name, properties, options, init);
146
176
  if (list.length >= batchSize) {
147
177
  flush();
148
178
  return;
@@ -151,9 +181,21 @@ function track(name, properties, options = defaultOptions) {
151
181
  timer = setTimeout(() => void flush(), delay);
152
182
  }
153
183
  /**
184
+ * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and
185
+ * hands it to the third-party trackers now, under the id it is sent with.
186
+ */
187
+ function track(name, properties, options = defaultOptions) {
188
+ queueEvent(name, properties, options);
189
+ }
190
+ /**
154
191
  * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
155
192
  * when the send could not start (its headers or rate limit threw), at once, the event left queued
156
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.
157
199
  */
158
200
  async function trackAsync(name, properties, options = defaultOptions) {
159
201
  let settle;
@@ -186,24 +228,15 @@ function beacon(dto) {
186
228
  * Call it before the engagement beacon: a new session's `session_start` is in this queue.
187
229
  *
188
230
  * Nothing can be awaited here, so the events go with the tags they have settled on (the last
189
- * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
190
- * as an id-less browser event could not be deduplicated against the server's. The visitor id is
191
- * local (`visitorId`), so a first visit left within a second is sent like any other; when no
192
- * beacon can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
231
+ * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers
232
+ * were fired then, under that id: none is fired again here. The visitor id is local
233
+ * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon
234
+ * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
193
235
  */
194
236
  function sendPendingEvents() {
195
237
  if (list.length === 0) return;
196
238
  const visitor_id = require_visitor_id.visitorId();
197
- if (!beacon(list.map((event) => ({
198
- name: event.name,
199
- properties: event.properties,
200
- tags: event.settled ?? require_setup_index.cache.tags ?? {},
201
- visitor_id,
202
- session_id: event.session_id,
203
- platform: require_setup_index.config.platform,
204
- environment: require_setup_index.config.environment,
205
- timestamp: event.timestamp
206
- })))) {
239
+ if (!beacon(list.map((event) => toDTO(event, visitor_id, event.settled ?? require_setup_index.cache.tags ?? {})))) {
207
240
  flush();
208
241
  return;
209
242
  }
@@ -211,13 +244,14 @@ function sendPendingEvents() {
211
244
  clearTimeout(timer);
212
245
  timer = null;
213
246
  }
214
- list.splice(0).forEach((event) => event.options.onSucceed?.(void 0));
247
+ list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));
215
248
  }
216
249
  function sendBeacon(name, properties) {
217
250
  const visitor_id = require_visitor_id.visitorId();
218
251
  const session_id = require_setup_session.getSession().extend();
219
252
  if (!session_id) return;
220
253
  if (beacon([{
254
+ id: (0, uuid.v7)(),
221
255
  name,
222
256
  properties,
223
257
  tags: require_setup_index.cache.tags ?? {},
@@ -230,6 +264,7 @@ function sendBeacon(name, properties) {
230
264
  console.warn("Failed to send beacon", name, properties);
231
265
  }
232
266
  //#endregion
267
+ exports.queueEvent = queueEvent;
233
268
  exports.sendBeacon = sendBeacon;
234
269
  exports.sendPendingEvents = sendPendingEvents;
235
270
  exports.track = track;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","getSession","visitorId","fetch","IGNORED_EVENTS"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\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 { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\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 // 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 * 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 * Queues an event, preceded by a `session_start` when it is the one that opens a session.\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(name: Item['name'], properties: Item['properties'], options: TrackOptions): 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, '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({ name: 'session_start', properties: {}, options }));\n }\n const event = item({ name, properties, options });\n list.push(event);\n return event;\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) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.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 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 const data = (await response.json()) as TrackEventResponse;\n\n events.forEach((event, index) => {\n const eventId = data.at(index)?.id;\n event.options.onSucceed?.(eventId ? { id: eventId } : undefined);\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 config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(event.name, event.properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it.\n if (e instanceof Error) console.log(e.message);\n }\n });\n });\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\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n enqueue(name, properties, options);\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 * 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 */\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), and without the server's ids: their third-party trackers are not fired,\n * as an id-less browser event could not be deduplicated against the server's. The visitor id is\n * local (`visitorId`), so a first visit left within a second is sent like any other; when no\n * beacon 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 name: event.name,\n properties: event.properties,\n tags: event.settled ?? cache.tags ?? {},\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\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?.(undefined));\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 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":";;;;;;;AAcA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MA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pB,WAAW,MAAM;CACnB,EACc,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,KAAA,CAAS,CAAC;AACxE;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaG,mBAAAA,UAAU;CAG7B,MAAM,aAAaD,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAgBjB,IAAI,OAAO,CAbT;EACE;EACA;EAGA,MAAMD,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\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,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,OAAa;CAG/B,IAAI,MAAM,QAAQ,6BAA6B,SAASC,qCAAAA,eAAe,SAAS,MAAM,IAAI,GACxF;CAEF,MAAM,WAAW,aAAaF,oBAAAA,OAAO,oBAAoB,KAAK;CAC9D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,aAAa,UAAU,KAAK,GAAG,CAAC;AACnD;;AAGA,SAAS,aAAa,UAA+B,OAAkC;CACrF,OAAO,SAAS,QAAQ,YAAY;EAClC,IAAI;GACF,OAAO,QAAQ,MAAM,MAAM,MAAM,YAAY,MAAM,EAAE,MAAM;EAC7D,S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X;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"}
@@ -2,14 +2,38 @@ import { EventName, TrackEventResponse, TrackName, TrackProperties } from "./typ
2
2
  //#region src/track/index.d.ts
3
3
  export interface TrackOptions {
4
4
  enableThirdPartyTracking?: boolean;
5
+ /**
6
+ * Called once the server (or a beacon) has taken the event, with the event's id: the one
7
+ * generated when it was tracked, which the third-party trackers were given too.
8
+ */
5
9
  onSucceed?: (response?: TrackEventResponse[number]) => void;
6
10
  onError?: (error: unknown) => void;
7
11
  }
12
+ /**
13
+ * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the
14
+ * package. `id` carries over the id of an earlier attempt at the same occurrence, and
15
+ * `pixels: false` skips the third-party trackers that attempt has already fired.
16
+ */
17
+ export interface EventInit {
18
+ id?: string;
19
+ pixels?: boolean;
20
+ }
21
+ /** `track`, with the `EventInit` only the SDK itself passes. */
22
+ export declare function queueEvent<T extends EventName = EventName>(name: TrackName<T>, properties: TrackProperties<T> | undefined, options: TrackOptions, init?: EventInit): void;
23
+ /**
24
+ * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and
25
+ * hands it to the third-party trackers now, under the id it is sent with.
26
+ */
8
27
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
9
28
  /**
10
29
  * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
11
30
  * when the send could not start (its headers or rate limit threw), at once, the event left queued
12
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.
13
37
  */
14
38
  export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
15
39
  /**
@@ -18,10 +42,10 @@ export declare function trackAsync<T extends EventName = EventName>(name: TrackN
18
42
  * Call it before the engagement beacon: a new session's `session_start` is in this queue.
19
43
  *
20
44
  * Nothing can be awaited here, so the events go with the tags they have settled on (the last
21
- * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
22
- * as an id-less browser event could not be deduplicated against the server's. The visitor id is
23
- * local (`visitorId`), so a first visit left within a second is sent like any other; when no
24
- * beacon can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
45
+ * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers
46
+ * were fired then, under that id: none is fired again here. The visitor id is local
47
+ * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon
48
+ * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
25
49
  */
26
50
  export declare function sendPendingEvents(): void;
27
51
  export declare function sendBeacon<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAQiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBA6KG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;wBAgBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBA6CxB;wBAwBA,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;;;;;;;;;;;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"}
@@ -2,14 +2,38 @@ import { EventName, TrackEventResponse, TrackName, TrackProperties } from "./typ
2
2
  //#region src/track/index.d.ts
3
3
  export interface TrackOptions {
4
4
  enableThirdPartyTracking?: boolean;
5
+ /**
6
+ * Called once the server (or a beacon) has taken the event, with the event's id: the one
7
+ * generated when it was tracked, which the third-party trackers were given too.
8
+ */
5
9
  onSucceed?: (response?: TrackEventResponse[number]) => void;
6
10
  onError?: (error: unknown) => void;
7
11
  }
12
+ /**
13
+ * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the
14
+ * package. `id` carries over the id of an earlier attempt at the same occurrence, and
15
+ * `pixels: false` skips the third-party trackers that attempt has already fired.
16
+ */
17
+ export interface EventInit {
18
+ id?: string;
19
+ pixels?: boolean;
20
+ }
21
+ /** `track`, with the `EventInit` only the SDK itself passes. */
22
+ export declare function queueEvent<T extends EventName = EventName>(name: TrackName<T>, properties: TrackProperties<T> | undefined, options: TrackOptions, init?: EventInit): void;
23
+ /**
24
+ * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and
25
+ * hands it to the third-party trackers now, under the id it is sent with.
26
+ */
8
27
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
9
28
  /**
10
29
  * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
11
30
  * when the send could not start (its headers or rate limit threw), at once, the event left queued
12
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.
13
37
  */
14
38
  export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
15
39
  /**
@@ -18,10 +42,10 @@ export declare function trackAsync<T extends EventName = EventName>(name: TrackN
18
42
  * Call it before the engagement beacon: a new session's `session_start` is in this queue.
19
43
  *
20
44
  * Nothing can be awaited here, so the events go with the tags they have settled on (the last
21
- * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
22
- * as an id-less browser event could not be deduplicated against the server's. The visitor id is
23
- * local (`visitorId`), so a first visit left within a second is sent like any other; when no
24
- * beacon can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
45
+ * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers
46
+ * were fired then, under that id: none is fired again here. The visitor id is local
47
+ * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon
48
+ * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
25
49
  */
26
50
  export declare function sendPendingEvents(): void;
27
51
  export declare function sendBeacon<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAQiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBA6KG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;wBAgBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBA6CxB;wBAwBA,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;;;;;;;;;;;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"}
@@ -3,6 +3,7 @@ import { getSession } from "../setup/session.mjs";
3
3
  import { IGNORED_EVENTS } from "../third-parties/ignored-events.mjs";
4
4
  import { visitorId } from "../visitor/id.mjs";
5
5
  import { TokenBucket, fetch } from "@shware/utils";
6
+ import { v7 } from "uuid";
6
7
  //#region src/track/index.ts
7
8
  const defaultOptions = {};
8
9
  let tokenBucket;
@@ -46,7 +47,40 @@ const batchSize = 10;
46
47
  const delay = 2e3;
47
48
  let timer = null;
48
49
  /**
49
- * Queues an event, preceded by a `session_start` when it is the one that opens a session.
50
+ * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once
51
+ * the server has answered. An event followed by a full-page navigation (an outbound link,
52
+ * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches
53
+ * the pixels before the page goes, and the server's conversions API, sending the same id, still
54
+ * deduplicates against the browser event. A server that is down no longer takes the pixels down
55
+ * with it either.
56
+ *
57
+ * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the
58
+ * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).
59
+ * Those trackers, and only those, are called once more on the next macrotask, with the same event
60
+ * and id, after the inline snippets have had their turn; a tracker still not ready then is given
61
+ * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global
62
+ * either exists by then or the script is blocked.
63
+ */
64
+ function firePixels(event) {
65
+ if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) return;
66
+ const notReady = callTrackers(config.thirdPartyTrackers, event);
67
+ if (notReady.length === 0) return;
68
+ setTimeout(() => callTrackers(notReady, event), 0);
69
+ }
70
+ /** Calls each tracker with the event; returns the ones that said they were not ready. */
71
+ function callTrackers(trackers, event) {
72
+ return trackers.filter((tracker) => {
73
+ try {
74
+ return tracker(event.name, event.properties, event.id) === false;
75
+ } catch (e) {
76
+ if (e instanceof Error) console.log(e.message);
77
+ return false;
78
+ }
79
+ });
80
+ }
81
+ /**
82
+ * Queues an event, preceded by a `session_start` when it is the one that opens a session, and
83
+ * fires its third-party trackers.
50
84
  *
51
85
  * The session is decided here, when the event happens, as GA4 and PostHog decide it: the
52
86
  * `session_start` then sits in the queue right before the event that opened the session, so
@@ -55,7 +89,7 @@ let timer = null;
55
89
  * session: the landing page is where the session began, whatever the page has navigated to by
56
90
  * the time the batch goes out.
57
91
  */
58
- function enqueue(name, properties, options) {
92
+ function enqueue(name, properties, options, init = {}) {
59
93
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
60
94
  const tags = captureTags();
61
95
  const { id: session_id, started } = getSession().touch(Date.parse(timestamp));
@@ -70,18 +104,34 @@ function enqueue(name, properties, options) {
70
104
  return result;
71
105
  };
72
106
  if (started) list.push(item({
107
+ id: v7(),
73
108
  name: "session_start",
74
109
  properties: {},
75
110
  options: { enableThirdPartyTracking: false }
76
111
  }));
77
112
  const event = item({
113
+ id: init.id ?? v7(),
78
114
  name,
79
115
  properties,
80
116
  options
81
117
  });
82
118
  list.push(event);
119
+ if (init.pixels !== false) firePixels(event);
83
120
  return event;
84
121
  }
122
+ function toDTO(event, visitor_id, tags) {
123
+ return {
124
+ id: event.id,
125
+ name: event.name,
126
+ properties: event.properties,
127
+ tags,
128
+ visitor_id,
129
+ session_id: event.session_id,
130
+ platform: config.platform,
131
+ environment: config.environment,
132
+ timestamp: event.timestamp
133
+ };
134
+ }
85
135
  /**
86
136
  * Sends the queue. Everything that has to be awaited is awaited first, and only then are the
87
137
  * events taken off the queue and handed to `fetch` in the same synchronous step — so there is
@@ -101,16 +151,7 @@ async function flush() {
101
151
  await Promise.all(list.map((event) => event.tags));
102
152
  events = list.splice(0);
103
153
  if (events.length === 0) return;
104
- const dto = await Promise.all(events.map(async (event) => ({
105
- name: event.name,
106
- properties: event.properties,
107
- tags: await event.tags,
108
- visitor_id,
109
- session_id: event.session_id,
110
- platform: config.platform,
111
- environment: config.environment,
112
- timestamp: event.timestamp
113
- })));
154
+ const dto = await Promise.all(events.map(async (event) => toDTO(event, visitor_id, await event.tags)));
114
155
  const body = JSON.stringify(dto);
115
156
  const response = await fetch(`${config.endpoint}/events`, {
116
157
  method: "POST",
@@ -120,19 +161,7 @@ async function flush() {
120
161
  body
121
162
  });
122
163
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
123
- const data = await response.json();
124
- events.forEach((event, index) => {
125
- const eventId = data.at(index)?.id;
126
- event.options.onSucceed?.(eventId ? { id: eventId } : void 0);
127
- if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) return;
128
- config.thirdPartyTrackers.forEach((tracker) => {
129
- try {
130
- tracker(event.name, event.properties, eventId);
131
- } catch (e) {
132
- if (e instanceof Error) console.log(e.message);
133
- }
134
- });
135
- });
164
+ events.forEach((event) => event.options.onSucceed?.({ id: event.id }));
136
165
  } catch (e) {
137
166
  if (e instanceof Error) console.log(e.message);
138
167
  const starts = events.filter((event) => event.name === "session_start");
@@ -140,8 +169,9 @@ async function flush() {
140
169
  events.filter((event) => event.name !== "session_start").forEach((event) => event.options.onError?.(e));
141
170
  }
142
171
  }
143
- function track(name, properties, options = defaultOptions) {
144
- enqueue(name, properties, options);
172
+ /** `track`, with the `EventInit` only the SDK itself passes. */
173
+ function queueEvent(name, properties, options, init) {
174
+ enqueue(name, properties, options, init);
145
175
  if (list.length >= batchSize) {
146
176
  flush();
147
177
  return;
@@ -150,9 +180,21 @@ function track(name, properties, options = defaultOptions) {
150
180
  timer = setTimeout(() => void flush(), delay);
151
181
  }
152
182
  /**
183
+ * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and
184
+ * hands it to the third-party trackers now, under the id it is sent with.
185
+ */
186
+ function track(name, properties, options = defaultOptions) {
187
+ queueEvent(name, properties, options);
188
+ }
189
+ /**
153
190
  * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
154
191
  * when the send could not start (its headers or rate limit threw), at once, the event left queued
155
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.
156
198
  */
157
199
  async function trackAsync(name, properties, options = defaultOptions) {
158
200
  let settle;
@@ -185,24 +227,15 @@ function beacon(dto) {
185
227
  * Call it before the engagement beacon: a new session's `session_start` is in this queue.
186
228
  *
187
229
  * Nothing can be awaited here, so the events go with the tags they have settled on (the last
188
- * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
189
- * as an id-less browser event could not be deduplicated against the server's. The visitor id is
190
- * local (`visitorId`), so a first visit left within a second is sent like any other; when no
191
- * beacon can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
230
+ * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers
231
+ * were fired then, under that id: none is fired again here. The visitor id is local
232
+ * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon
233
+ * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.
192
234
  */
193
235
  function sendPendingEvents() {
194
236
  if (list.length === 0) return;
195
237
  const visitor_id = visitorId();
196
- if (!beacon(list.map((event) => ({
197
- name: event.name,
198
- properties: event.properties,
199
- tags: event.settled ?? cache.tags ?? {},
200
- visitor_id,
201
- session_id: event.session_id,
202
- platform: config.platform,
203
- environment: config.environment,
204
- timestamp: event.timestamp
205
- })))) {
238
+ if (!beacon(list.map((event) => toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})))) {
206
239
  flush();
207
240
  return;
208
241
  }
@@ -210,13 +243,14 @@ function sendPendingEvents() {
210
243
  clearTimeout(timer);
211
244
  timer = null;
212
245
  }
213
- list.splice(0).forEach((event) => event.options.onSucceed?.(void 0));
246
+ list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));
214
247
  }
215
248
  function sendBeacon(name, properties) {
216
249
  const visitor_id = visitorId();
217
250
  const session_id = getSession().extend();
218
251
  if (!session_id) return;
219
252
  if (beacon([{
253
+ id: v7(),
220
254
  name,
221
255
  properties,
222
256
  tags: cache.tags ?? {},
@@ -229,6 +263,6 @@ function sendBeacon(name, properties) {
229
263
  console.warn("Failed to send beacon", name, properties);
230
264
  }
231
265
  //#endregion
232
- export { sendBeacon, sendPendingEvents, track, trackAsync };
266
+ export { queueEvent, sendBeacon, sendPendingEvents, track, trackAsync };
233
267
 
234
268
  //# sourceMappingURL=index.mjs.map