@shware/analytics 16.3.5 → 16.4.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 (53) hide show
  1. package/dist/native/fingerprint.cjs +6 -1
  2. package/dist/native/fingerprint.cjs.map +1 -1
  3. package/dist/native/fingerprint.d.cts +5 -0
  4. package/dist/native/fingerprint.d.cts.map +1 -1
  5. package/dist/native/fingerprint.d.mts +5 -0
  6. package/dist/native/fingerprint.d.mts.map +1 -1
  7. package/dist/native/fingerprint.mjs +6 -1
  8. package/dist/native/fingerprint.mjs.map +1 -1
  9. package/dist/native/setup.cjs +2 -2
  10. package/dist/native/setup.cjs.map +1 -1
  11. package/dist/native/setup.mjs +2 -2
  12. package/dist/native/setup.mjs.map +1 -1
  13. package/dist/next/index.cjs +1 -2
  14. package/dist/next/index.cjs.map +1 -1
  15. package/dist/next/index.d.cts.map +1 -1
  16. package/dist/next/index.d.mts.map +1 -1
  17. package/dist/next/index.mjs +1 -2
  18. package/dist/next/index.mjs.map +1 -1
  19. package/dist/server/linkedin-conversions-api.cjs +9 -3
  20. package/dist/server/linkedin-conversions-api.cjs.map +1 -1
  21. package/dist/server/linkedin-conversions-api.d.cts +3 -1
  22. package/dist/server/linkedin-conversions-api.d.cts.map +1 -1
  23. package/dist/server/linkedin-conversions-api.d.mts +3 -1
  24. package/dist/server/linkedin-conversions-api.d.mts.map +1 -1
  25. package/dist/server/linkedin-conversions-api.mjs +9 -3
  26. package/dist/server/linkedin-conversions-api.mjs.map +1 -1
  27. package/dist/server/meta-capi.cjs +5 -1
  28. package/dist/server/meta-capi.cjs.map +1 -1
  29. package/dist/server/meta-capi.d.cts.map +1 -1
  30. package/dist/server/meta-capi.d.mts.map +1 -1
  31. package/dist/server/meta-capi.mjs +5 -1
  32. package/dist/server/meta-capi.mjs.map +1 -1
  33. package/dist/third-parties/analytics-props.cjs +1 -2
  34. package/dist/third-parties/analytics-props.cjs.map +1 -1
  35. package/dist/third-parties/analytics-props.mjs +1 -2
  36. package/dist/third-parties/analytics-props.mjs.map +1 -1
  37. package/dist/third-parties/integration.cjs +6 -24
  38. package/dist/third-parties/integration.cjs.map +1 -1
  39. package/dist/third-parties/integration.d.cts +1 -15
  40. package/dist/third-parties/integration.d.cts.map +1 -1
  41. package/dist/third-parties/integration.d.mts +1 -15
  42. package/dist/third-parties/integration.d.mts.map +1 -1
  43. package/dist/third-parties/integration.mjs +7 -23
  44. package/dist/third-parties/integration.mjs.map +1 -1
  45. package/dist/track/index.cjs +4 -4
  46. package/dist/track/index.cjs.map +1 -1
  47. package/dist/track/index.mjs +4 -4
  48. package/dist/track/index.mjs.map +1 -1
  49. package/dist/web/index.cjs +2 -2
  50. package/dist/web/index.cjs.map +1 -1
  51. package/dist/web/index.mjs +2 -2
  52. package/dist/web/index.mjs.map +1 -1
  53. package/package.json +1 -1
@@ -34,7 +34,7 @@ async function captureTags() {
34
34
  try {
35
35
  return await require_setup_index.config.getTags();
36
36
  } catch (e) {
37
- if (e instanceof Error) console.log(e.message);
37
+ if (e instanceof Error) console.warn(e.message);
38
38
  return require_setup_index.cache.tags ?? {};
39
39
  }
40
40
  }
@@ -74,7 +74,7 @@ function callIntegrations(integrations, event) {
74
74
  try {
75
75
  return track(event.name, event.properties, event.id) === false;
76
76
  } catch (e) {
77
- if (e instanceof Error) console.log(e.message);
77
+ if (e instanceof Error) console.warn(e.message);
78
78
  return false;
79
79
  }
80
80
  });
@@ -175,7 +175,7 @@ async function flush() {
175
175
  headers = await require_setup_index.config.getHeaders();
176
176
  await Promise.all(list.map((item) => item.tagged));
177
177
  } catch (e) {
178
- if (e instanceof Error) console.log(e.message);
178
+ if (e instanceof Error) console.warn(e.message);
179
179
  return;
180
180
  }
181
181
  await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));
@@ -207,7 +207,7 @@ async function send(items, headers) {
207
207
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
208
208
  items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));
209
209
  } catch (e) {
210
- if (e instanceof Error) console.log(e.message);
210
+ if (e instanceof Error) console.warn(e.message);
211
211
  fail(items, e);
212
212
  }
213
213
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","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 type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } 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. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => 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\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\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};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\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, options }: 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 (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(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 * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\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: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\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 headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.log(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\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 items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\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. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\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 // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,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,EAAE,OAAO,WAAiB;CAG5C,IACE,QAAQ,6BAA6B,SACrCD,oBAAAA,OAAO,wBAAwB,SAAS,MAAM,IAAI,KAClDE,qCAAAA,eAAe,SAAS,MAAM,IAAI,GAElC;CAEF,MAAM,WAAW,iBAAiBF,oBAAAA,OAAO,cAAc,KAAK;CAC5D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,iBAAiB,UAAU,KAAK,GAAG,CAAC;AACvD;;AAGA,SAAS,iBAAiB,cAAsC,OAAkC;CAChG,OAAO,aAAa,QAAQ,EAAE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ACvB,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,UAAU;EAC3C,IAAI,CAAC,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GAC5C,KAAK,KAAK,GAAG,KAAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAaI,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","visitorId","getSession","uuidv7","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 type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } 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. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => 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\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\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};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\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.warn(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, options }: 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 (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(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.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\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: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\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 headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\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 items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\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. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\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 // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAMC,oBAAAA,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,KAAK,EAAE,OAAO;EAC9C,OAA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) {
36
- if (e instanceof Error) console.log(e.message);
36
+ if (e instanceof Error) console.warn(e.message);
37
37
  return cache.tags ?? {};
38
38
  }
39
39
  }
@@ -73,7 +73,7 @@ function callIntegrations(integrations, event) {
73
73
  try {
74
74
  return track(event.name, event.properties, event.id) === false;
75
75
  } catch (e) {
76
- if (e instanceof Error) console.log(e.message);
76
+ if (e instanceof Error) console.warn(e.message);
77
77
  return false;
78
78
  }
79
79
  });
@@ -174,7 +174,7 @@ async function flush() {
174
174
  headers = await config.getHeaders();
175
175
  await Promise.all(list.map((item) => item.tagged));
176
176
  } catch (e) {
177
- if (e instanceof Error) console.log(e.message);
177
+ if (e instanceof Error) console.warn(e.message);
178
178
  return;
179
179
  }
180
180
  await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));
@@ -206,7 +206,7 @@ async function send(items, headers) {
206
206
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
207
207
  items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));
208
208
  } catch (e) {
209
- if (e instanceof Error) console.log(e.message);
209
+ if (e instanceof Error) console.warn(e.message);
210
210
  fail(items, e);
211
211
  }
212
212
  }
@@ -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 type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } 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. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => 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\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\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};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\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, options }: 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 (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(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 * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\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: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\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 headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.log(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\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 items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\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. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\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 // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAiDA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,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AAM,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;;;;;;;;;;;;;AAcA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,UAAU,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS,UAAU;EAC3C,IAAI,CAAC,OAAO,MAAM,KAAK,SAAS,KAAK,KAAK,CAAC,GAAG;GAC5C,KAAK,KAAK,GAAG,KAAK;GAClB;EACF;EACA,MAAM,SAAS,EAAE,OAAO,cAAc,QAAQ,YAAY;GAAE,IAAI,MAAM;GAAI,QAAQ;EAAK,CAAC,CAAC;CAC3F,CAAC;CACD,IAAI,KAAK,SAAS,GAAG,MAAW;AAClC;AAEA,SAAgB,WACd,MACA,YACA;CAGA,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAIjB,IAAI,OAAO,CAAC;EAAE,GAAG,QAAQ,UAAU;EAAG,IAAIA,GAAO;EAAG;EAAM;CAAW,CAAC,CAAC,GAAG;CAC1E,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 type { Integration } from '../third-parties/integration';\nimport { visitorId } from '../visitor/id';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } 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. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => 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\n/**\n * An event as the server takes it, one element of a `POST /events` batch — with the id the SDK\n * always generates, and the name and properties as `track` types them.\n */\ntype TrackEvent = Omit<CreateTrackEventDTO[number], 'id' | 'name' | 'properties'> & {\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};\n\ntype Item = {\n /**\n * The event as it is sent, complete from the moment it is tracked: its id (a uuidv7 the server\n * stores it under, `on conflict (id) do nothing`, and the deduplication id the third-party\n * trackers are given at once), and the visitor, session and time it happened in — decided then,\n * as GA4 and PostHog decide them, never when the batch goes out. `reset()` replaces the visitor\n * and session, and an event tracked before it still belongs to the ones it happened in.\n *\n * `tags` starts as the last built tags and is replaced by the event's own once they are\n * captured (`tagged`): a page being hidden can await nothing, and sends what it has.\n */\n event: TrackEvent;\n tagged: Promise<void>;\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.warn(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, options }: 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 (\n options.enableThirdPartyTracking === false ||\n config.excludeFromIntegrations.includes(event.name) ||\n IGNORED_EVENTS.includes(event.name)\n ) {\n return;\n }\n const notReady = callIntegrations(config.integrations, event);\n if (notReady.length === 0) return;\n setTimeout(() => callIntegrations(notReady, event), 0);\n}\n\n/** Hands the event to each integration; returns the ones that said they were not ready. */\nfunction callIntegrations(integrations: readonly Integration[], event: TrackEvent): Integration[] {\n return integrations.filter(({ track }) => {\n try {\n return track(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.warn(e.message);\n return false;\n }\n });\n}\n\n/**\n * What an event shares with every other event of the moment it happens: the visitor, the session,\n * the time and the client, with the last built tags until the event's own are captured.\n */\nfunction context(session_id: string, timestamp = new Date().toISOString()) {\n return {\n visitor_id: visitorId(),\n session_id,\n timestamp,\n platform: config.platform,\n environment: config.environment,\n tags: cache.tags ?? {},\n };\n}\n\n/** Queues the event, its tags to be filled in once `tags` settles. */\nfunction push(event: TrackEvent, tags: Promise<TrackTags>, options: TrackOptions): Item {\n const tagged = tags.then((settled) => {\n event.tags = settled;\n });\n const item = { event, tagged, options };\n list.push(item);\n return item;\n}\n\nconst silent: TrackOptions = { enableThirdPartyTracking: false };\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: TrackEvent['name'],\n properties: TrackEvent['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const at = context(session_id, timestamp);\n const tags = captureTags();\n if (started) push({ ...at, id: uuidv7(), name: 'session_start', properties: {} }, tags, silent);\n const item = push({ ...at, id: init.id ?? uuidv7(), name, properties }, tags, options);\n if (init.pixels !== false) firePixels(item);\n return item;\n}\n\n/**\n * Ends the current session for `reset()`. What it accrued and has not reported goes out as a\n * `user_engagement`, as when the page is closed, and the queue is sent. Synchronous: every queued\n * event already carries its visitor and session, so the caller can replace the visitor right after.\n */\nexport function endSession() {\n const { id, engagement_time_msec } = getSession().end();\n if (id && engagement_time_msec > 0) {\n const properties = { engagement_time_msec, trigger: 'reset' };\n push(\n { ...context(id), id: uuidv7(), name: 'user_engagement', properties },\n captureTags(),\n silent\n );\n }\n if (list.length > 0) void flush();\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 headers: Record<string, string>;\n try {\n await getTokenBucket().removeTokens();\n headers = await config.getHeaders();\n // Tagged before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((item) => item.tagged));\n } catch (e: unknown) {\n // Nothing has left the queue yet: the events wait for the next send.\n if (e instanceof Error) console.warn(e.message);\n return;\n }\n\n // The server takes one visitor per request, and a queue spans two after `reset()`. `send`\n // settles its own failures, so neither batch can take the other down.\n await Promise.all(byVisitor(list.splice(0)).map((batch) => send(batch, headers)));\n}\n\n/**\n * The items grouped by the visitor they were tracked under, each group in queue order. Not\n * `Map.groupBy`: it is ES2024, missing from Safari before 17.4 and from Hermes before V1.\n */\nfunction byVisitor(items: Item[]): Item[][] {\n const groups = new Map<string, Item[]>();\n for (const item of items) {\n const { visitor_id } = item.event;\n groups.set(visitor_id, [...(groups.get(visitor_id) ?? []), item]);\n }\n return [...groups.values()];\n}\n\n/** One visitor's batch, as one request. */\nasync function send(items: Item[], headers: Record<string, string>) {\n try {\n const body = JSON.stringify(items.map((item) => item.event));\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\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 items.forEach(({ event, options }) => options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.warn(e.message);\n fail(items, e);\n }\n}\n\n/**\n * `fetch` has already retried the transient failures by the time a batch fails; what remains is a\n * batch the server rejected outright — one invalid event fails the whole batch — or a network that\n * stayed down past the retries. The other events are reported lost; `session_start` alone goes\n * back on the queue for the next send, because it is the session's only attribution record: a\n * session without one has no channel, and its every later event drops out of an attribution join.\n */\nfunction fail(items: Item[], e: unknown) {\n const isStart = (item: Item) => item.event.name === 'session_start';\n list.unshift(...items.filter(isStart));\n items.filter((item) => !isStart(item)).forEach((item) => item.options.onError?.(e));\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. One beacon per\n * visitor, as one request per visitor in `flush`; a visitor's events no beacon can take — no\n * `sendBeacon`, a refused body — stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n byVisitor(list.splice(0)).forEach((batch) => {\n if (!beacon(batch.map((item) => item.event))) {\n list.push(...batch);\n return;\n }\n batch.forEach(({ event, options }) => options.onSucceed?.({ id: event.id, beacon: true }));\n });\n if (list.length > 0) void flush();\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\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 // With the last built tags: they are worth less than the event carrying them, and an empty set\n // still reports the engagement (every field in `tagsSchema` is optional).\n if (beacon([{ ...context(session_id), id: uuidv7(), name, properties }])) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAsBA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,O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
- console.error("localStorage is not available");
179
+ console.warn("localStorage is not available; falling back to in-memory storage");
180
180
  return map.get(key) ?? null;
181
181
  }
182
182
  },
@@ -184,7 +184,7 @@ const storage = {
184
184
  try {
185
185
  localStorage.setItem(key, value);
186
186
  } catch {
187
- console.error("localStorage is not available");
187
+ console.warn("localStorage is not available; falling back to in-memory storage");
188
188
  map.set(key, value);
189
189
  }
190
190
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["uuidv4","config","keys","redactUrl","getPageKey","getLink","Bowser","parseCookie"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then(\n // `null` is the server saying the id names no link (a 4xx) and stays cached: an unknown `?s=`\n // would otherwise put a request on the wire for every event of the page.\n (result) => result,\n (e: unknown) => {\n // A 5xx or a network failure says nothing about the link, and losing its utm params for\n // every later event costs more than repeating a rare request: forget it, try again next time.\n if (e instanceof Error) console.error(e.message);\n links.delete(id);\n return null;\n }\n );\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,KAAA,GAAIA,KAAAA,GAAAA,CAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAASC,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAAK,WAAW;CACtB,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,WAAW,EAAE;CACzC,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,IAAI;AAEJ,SAAS,cAAc;CACrB,MAAM,OAAOC,yBAAAA,UAAU,OAAO,SAAS,IAAI;CAC3C,MAAM,OAAOC,qBAAAA,WAAW,OAAO,SAAS,UAAU,OAAO,SAAS,MAAM;CACxE,IAAI,UAAU,SAAS,MAAM;EAG3B,SAAS,OAAO;EAChB,OAAO;CACT;CACA,MAAM,WAAW,WAAW,SAAS,OAAOD,yBAAAA,UAAU,SAAS,QAAQ,KAAK,KAAA;CAC5E,WAAW;EAAE;EAAM,IAAI,WAAW;EAAG;EAAM;CAAS;CACpD,OAAO;AACT;;;;;AAMA,SAAgB,kBAA0B;CACxC,OAAOA,yBAAAA,UAAU,OAAO,SAAS,IAAI;AACvC;;AAGA,SAAgB,kBAAsC;CACpD,OAAO,YAAY,CAAC,CAAC;AACvB;AAEA,MAAM,wBAAQ,IAAI,IAAkC;;;;;;AAOpD,SAAS,cAAc,IAAY;CACjC,MAAM,SAAS,MAAM,IAAI,EAAE;CAC3B,IAAI,QAAQ,OAAO;CACnB,MAAM,OAAOE,mBAAAA,QAAQ,EAAE,CAAC,CAAC,M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AC3B,SAAS,OAAO,WAAW,KAAA;EAC3B,aAAa,OAAO,eAAe,KAAA;EACnC,UAAU,OAAO,YAAY,KAAA;EAC7B,WAAW,OAAO,aAAa,KAAA;EAG/B,YAAY,OAAO,aAAa,KAAA;EAChC,UAAU,OAAO,YAAY,KAAA;EAC7B,SAAS,OAAO,WAAW,KAAA;EAE3B,YAAY,MAAM,cAAc,OAAO,IAAI,YAAY,KAAK,KAAA;EAC5D,YAAY,MAAM,cAAc,OAAO,IAAI,YAAY,KAAK,KAAA;EAC5D,cAAc,MAAM,gBAAgB,OAAO,IAAI,cAAc,KAAK,KAAA;EAClE,UAAU,MAAM,YAAY,OAAO,IAAI,UAAU,KAAK,KAAA;EACtD,aAAa,MAAM,eAAe,OAAO,IAAI,aAAa,KAAK,KAAA;EAC/D,QAAQ,MAAM,UAAU,OAAO,IAAI,QAAQ,KAAK,KAAA;EAChD,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,sBACE,MAAM,wBAAwB,OAAO,IAAI,sBAAsB,KAAK,KAAA;CACxE;CAEA,oBAAA,MAAM,OAAO;CACb,OAAO;AACT;AAEA,MAAM,sBAAM,IAAI,IAAoB;AAEpC,MAAa,UAAmB;CAC9B,UAAU,QAAQ;EAChB,IAAI;GACF,OAAO,aAAa,QAAQ,GAAG;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,OAAO,IAAI,IAAI,GAAG,KAAK;EACzB;CACF;CACA,UAAU,KAAK,UAAU;EACvB,IAAI;GACF,aAAa,QAAQ,KAAK,KAAK;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
1
+ {"version":3,"file":"index.cjs","names":["uuidv4","config","keys","redactUrl","getPageKey","getLink","Bowser","parseCookie"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then(\n // `null` is the server saying the id names no link (a 4xx) and stays cached: an unknown `?s=`\n // would otherwise put a request on the wire for every event of the page.\n (result) => result,\n (e: unknown) => {\n // A 5xx or a network failure says nothing about the link, and losing its utm params for\n // every later event costs more than repeating a rare request: forget it, try again next time.\n if (e instanceof Error) console.error(e.message);\n links.delete(id);\n return null;\n }\n );\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.warn('localStorage is not available; falling back to in-memory storage');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.warn('localStorage is not available; falling back to in-memory storage');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,KAAA,GAAIA,KAAAA,GAAAA,CAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,M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Ac,MAAM,gBAAgB,OAAO,IAAI,cAAc,KAAK,KAAA;EAClE,UAAU,MAAM,YAAY,OAAO,IAAI,UAAU,KAAK,KAAA;EACtD,aAAa,MAAM,eAAe,OAAO,IAAI,aAAa,KAAK,KAAA;EAC/D,QAAQ,MAAM,UAAU,OAAO,IAAI,QAAQ,KAAK,KAAA;EAChD,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,sBACE,MAAM,wBAAwB,OAAO,IAAI,sBAAsB,KAAK,KAAA;CACxE;CAEA,oBAAA,MAAM,OAAO;CACb,OAAO;AACT;AAEA,MAAM,sBAAM,IAAI,IAAoB;AAEpC,MAAa,UAAmB;CAC9B,UAAU,QAAQ;EAChB,IAAI;GACF,OAAO,aAAa,QAAQ,GAAG;EACjC,QAAQ;GACN,QAAQ,KAAK,kEAAkE;GAC/E,OAAO,IAAI,IAAI,GAAG,KAAK;EACzB;CACF;CACA,UAAU,KAAK,UAAU;EACvB,IAAI;GACF,aAAa,QAAQ,KAAK,KAAK;EACjC,QAAQ;GACN,QAAQ,KAAK,kEAAkE;GAC/E,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
@@ -175,7 +175,7 @@ const storage = {
175
175
  try {
176
176
  return localStorage.getItem(key);
177
177
  } catch {
178
- console.error("localStorage is not available");
178
+ console.warn("localStorage is not available; falling back to in-memory storage");
179
179
  return map.get(key) ?? null;
180
180
  }
181
181
  },
@@ -183,7 +183,7 @@ const storage = {
183
183
  try {
184
184
  localStorage.setItem(key, value);
185
185
  } catch {
186
- console.error("localStorage is not available");
186
+ console.warn("localStorage is not available; falling back to in-memory storage");
187
187
  map.set(key, value);
188
188
  }
189
189
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["uuidv4","Bowser"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then(\n // `null` is the server saying the id names no link (a 4xx) and stays cached: an unknown `?s=`\n // would otherwise put a request on the wire for every event of the page.\n (result) => result,\n (e: unknown) => {\n // A 5xx or a network failure says nothing about the link, and losing its utm params for\n // every later event costs more than repeating a rare request: forget it, try again next time.\n if (e instanceof Error) console.error(e.message);\n links.delete(id);\n return null;\n }\n );\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.error('localStorage is not available');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.error('localStorage is not available');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,IAAIA,GAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAA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AAK,KAAA;EAChD,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,qBACE,MAAM,uBAAuB,OAAO,IAAI,qBAAqB,KAAK,KAAA;EACpE,sBACE,MAAM,wBAAwB,OAAO,IAAI,sBAAsB,KAAK,KAAA;CACxE;CAEA,MAAM,OAAO;CACb,OAAO;AACT;AAEA,MAAM,sBAAM,IAAI,IAAoB;AAEpC,MAAa,UAAmB;CAC9B,UAAU,QAAQ;EAChB,IAAI;GACF,OAAO,aAAa,QAAQ,GAAG;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,OAAO,IAAI,IAAI,GAAG,KAAK;EACzB;CACF;CACA,UAAU,KAAK,UAAU;EACvB,IAAI;GACF,aAAa,QAAQ,KAAK,KAAK;EACjC,QAAQ;GACN,QAAQ,MAAM,+BAA+B;GAC7C,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
1
+ {"version":3,"file":"index.mjs","names":["uuidv4","Bowser"],"sources":["../../src/web/index.ts"],"sourcesContent":["import Bowser from 'bowser';\nimport { parseCookie } from 'cookie';\nimport { v4 as uuidv4 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { type Link, getLink } from '../link/index';\nimport { type Storage, cache, config } from '../setup/index';\nimport type { TrackTags } from '../track/types';\nimport { redactUrl } from '../utils/redact-url';\nimport { getPageKey } from './page-key';\n\n// lib.dom types `crypto.randomUUID` as always present, but it is missing in insecure contexts\n// and older browsers, so probe it before use.\nfunction randomUUID(): string {\n return (crypto as Partial<Crypto>).randomUUID ? crypto.randomUUID() : uuidv4();\n}\n\nexport function getDeviceId() {\n const cached = config.storage.getItem(keys.device_id);\n if (cached) return cached;\n const id = randomUUID();\n config.storage.setItem(keys.device_id, id);\n return id;\n}\n\n/**\n * The current page load, keyed by the page it was loaded at. A module variable and nothing more\n * persistent: the id must die with the page (a reload is a new page load, and storage would\n * carry it over — or, shared across tabs, let two pages overwrite each other's).\n *\n * Keyed by `getPageKey` because that is what the SDK's own `page_view` fires on (see\n * `useWebAnalytics`): the id exists to link an event to the `page_view` of the page it happened\n * on, so it must rotate exactly when a `page_view` is sent — path or query change, yes; hash\n * change or tracking-parameter cleanup, no.\n *\n * `referrer` is the page's referrer as GA4 reports it in a single page app: `document.referrer`\n * for the document's first page, and the previous page's URL after an in-app navigation. The\n * browser never updates `document.referrer` on a `pushState`, so read alone it would name the\n * site the visit came from on every later page — and a session opened there, after 30 minutes\n * idle, would count that site as a second visit from it. With the previous page as its referrer,\n * that session's referrer is the product's own host: no touch, a direct session, which the\n * attribution view then credits to the touch before it.\n */\nlet pageLoad: { page: string; id: string; href: string; referrer: string | undefined } | undefined;\n\nfunction currentPage() {\n const href = redactUrl(window.location.href);\n const page = getPageKey(window.location.pathname, window.location.search);\n if (pageLoad?.page === page) {\n // The same page, its URL maybe cleaned of tracking parameters since: the next page's\n // referrer is the URL as it last was, as the browser's own would be.\n pageLoad.href = href;\n return pageLoad;\n }\n const referrer = pageLoad ? pageLoad.href : redactUrl(document.referrer) || undefined;\n pageLoad = { page, id: randomUUID(), href, referrer };\n return pageLoad;\n}\n\n/**\n * The current page's URL as reported, without its credential parameters (`redactUrl`), so\n * `page_location` never carries an OAuth code or a checkout session id.\n */\nexport function getPageLocation(): string {\n return redactUrl(window.location.href);\n}\n\n/** The current page's referrer, without its credential parameters: see `pageLoad`. */\nexport function getPageReferrer(): string | undefined {\n return currentPage().referrer;\n}\n\nconst links = new Map<string, Promise<Link | null>>();\n\n/**\n * `getTags` runs once per event now, and the link a `?s=` id points at cannot change while the\n * page is open, so an uncached lookup would put an identical request on the wire for every\n * event the page sends.\n */\nfunction getCachedLink(id: string) {\n const cached = links.get(id);\n if (cached) return cached;\n const link = getLink(id).then(\n // `null` is the server saying the id names no link (a 4xx) and stays cached: an unknown `?s=`\n // would otherwise put a request on the wire for every event of the page.\n (result) => result,\n (e: unknown) => {\n // A 5xx or a network failure says nothing about the link, and losing its utm params for\n // every later event costs more than repeating a rare request: forget it, try again next time.\n if (e instanceof Error) console.error(e.message);\n links.delete(id);\n return null;\n }\n );\n links.set(id, link);\n return link;\n}\n\n/** The user agent cannot change while the page is open, so it is parsed once. */\nlet parser: ReturnType<typeof Bowser.getParser> | undefined;\n\nexport async function getTags() {\n // Read the page before the first await: `getTags` runs when the event happens, and a single\n // page app can navigate while the link lookup below is still in flight.\n const page_location = redactUrl(window.location.href);\n const { id: page_load_id, referrer: page_referrer } = currentPage();\n const page_title = document.title;\n\n parser ??= Bowser.getParser(window.navigator.userAgent);\n const params = new URLSearchParams(window.location.search);\n const os = parser.getOS();\n const browser = parser.getBrowser();\n const platform = parser.getPlatform();\n const parsed = parseCookie(document.cookie);\n\n const linkId = params.get('s');\n const link = linkId ? await getCachedLink(linkId) : null;\n\n const tags: TrackTags = {\n os: `${os.name} ${os.version}`,\n os_name: os.name,\n os_version: os.version,\n browser: `${browser.name} ${browser.version}`,\n browser_name: browser.name,\n browser_version: browser.version,\n device: platform.model,\n device_id: getDeviceId(),\n device_type: platform.type,\n device_vendor: platform.vendor,\n device_pixel_ratio: window.devicePixelRatio,\n screen_width: window.screen.width,\n screen_height: window.screen.height,\n screen_resolution: `${window.screen.width}x${window.screen.height}`,\n webdriver: navigator.webdriver || undefined,\n release: config.release,\n language: navigator.language,\n time_zone: Intl.DateTimeFormat().resolvedOptions().timeZone,\n page_location,\n page_referrer,\n page_title,\n page_load_id,\n // Ad click ids from the URL, each under its parameter's name: this page's click, which\n // names the visit's channel (`CLICK_ID_CHANNELS`). Never filled from a cookie — a cookie\n // outlives the click; the cookies go below under their own names.\n fbclid: params.get('fbclid') ?? undefined,\n ad_id: params.get('ad_id') ?? undefined,\n ad_name: params.get('ad_name') ?? undefined,\n adset_id: params.get('adset_id') ?? undefined,\n adset_name: params.get('adset_name') ?? undefined,\n campaign_id: params.get('campaign_id') ?? undefined,\n campaign_name: params.get('campaign_name') ?? undefined,\n placement: params.get('placement') ?? undefined,\n gclid: params.get('gclid') ?? undefined,\n gclsrc: params.get('gclsrc') ?? undefined,\n gad_source: params.get('gad_source') ?? undefined,\n gad_campaignid: params.get('gad_campaignid') ?? undefined,\n network: params.get('network') ?? undefined,\n match_type: params.get('match_type') ?? undefined,\n wbraid: params.get('wbraid') ?? undefined,\n gbraid: params.get('gbraid') ?? undefined,\n dclid: params.get('dclid') ?? undefined,\n msclkid: params.get('msclkid') ?? undefined,\n rdt_cid: params.get('rdt_cid') ?? undefined,\n li_fat_id: params.get('li_fat_id') ?? undefined,\n oppref: params.get('oppref') ?? undefined,\n ko_click_id: params.get('ko_click_id') ?? undefined,\n // Snapchat appends `ScCid`, and URL parameters are case-sensitive.\n ScCid: params.get('ScCid') ?? undefined,\n ttclid: params.get('ttclid') ?? undefined,\n twclid: params.get('twclid') ?? undefined,\n yclid: params.get('yclid') ?? undefined,\n epik: params.get('epik') ?? undefined,\n // The ad platforms' first-party cookies, raw and under the cookie's own name, for the\n // conversion senders only: they carry the click to the later pages and visits where the\n // URL no longer does. `_fbc`, `_rdt_cid`, `_gcl_*` and `_uetmsclkid` are kept alive\n // server-side (see @shware/analytics/server resolveClickIdCookies); the rest are the pixels'.\n _fbc: parsed._fbc || undefined,\n _fbp: parsed._fbp || undefined,\n _gcl_aw: parsed._gcl_aw || undefined,\n _gcl_gb: parsed._gcl_gb || undefined,\n _uetmsclkid: parsed._uetmsclkid || undefined,\n _rdt_cid: parsed._rdt_cid || undefined,\n _rdt_uuid: parsed._rdt_uuid || undefined,\n // The Insight Tag's cookie is itself named `li_fat_id`; renamed so it cannot pass for the\n // URL parameter.\n _li_fat_id: parsed.li_fat_id || undefined,\n __oppref: parsed.__oppref || undefined,\n __obref: parsed.__obref || undefined,\n // utm params\n utm_source: link?.utm_source ?? params.get('utm_source') ?? undefined,\n utm_medium: link?.utm_medium ?? params.get('utm_medium') ?? undefined,\n utm_campaign: link?.utm_campaign ?? params.get('utm_campaign') ?? undefined,\n utm_term: link?.utm_term ?? params.get('utm_term') ?? undefined,\n utm_content: link?.utm_content ?? params.get('utm_content') ?? undefined,\n utm_id: link?.utm_id ?? params.get('utm_id') ?? undefined,\n utm_source_platform:\n link?.utm_source_platform ?? params.get('utm_source_platform') ?? undefined,\n utm_creative_format:\n link?.utm_creative_format ?? params.get('utm_creative_format') ?? undefined,\n utm_marketing_tactic:\n link?.utm_marketing_tactic ?? params.get('utm_marketing_tactic') ?? undefined,\n };\n\n cache.tags = tags;\n return tags;\n}\n\nconst map = new Map<string, string>();\n\nexport const storage: Storage = {\n getItem: (key) => {\n try {\n return localStorage.getItem(key);\n } catch {\n console.warn('localStorage is not available; falling back to in-memory storage');\n return map.get(key) ?? null;\n }\n },\n setItem: (key, value) => {\n try {\n localStorage.setItem(key, value);\n } catch {\n console.warn('localStorage is not available; falling back to in-memory storage');\n map.set(key, value);\n }\n },\n};\n"],"mappings":";;;;;;;;;;;AAYA,SAAS,aAAqB;CAC5B,OAAQ,OAA2B,aAAa,OAAO,WAAW,IAAIA,GAAO;AAC/E;AAEA,SAAgB,cAAc;CAC5B,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,SAAS;CACpD,IAAI,QAAQ,OAAO;CACnB,MAAM,KAAK,WAAW;CACtB,OAAO,QAAQ,QAAQ,KAAK,WAAW,EAAE;CACzC,OAAO;AACT;;;;;;;;;;;;;;;;;;;AAoBA,IAAI;AAEJ,SAAS,cAAc;CACrB,MAAM,OAAO,UAAU,OAAO,SAAS,IAAI;CAC3C,MAAM,OAAO,WAAW,OAAO,SAAS,UAAU,OAAO,SAAS,MAAM;CACxE,IAAI,UAAU,SAAS,MAAM;EAG3B,SAAS,OAAO;EAChB,OAAO;CACT;CACA,MAAM,WAAW,WAAW,SAAS,OAAO,UAAU,SAAS,QAAQ,KAAK,KAAA;CAC5E,WAAW;EAAE;EAAM,IAAI,WAAW;EAAG;EAAM;CAAS;CACpD,OAAO;AACT;;;;;AAMA,SAAgB,kBAA0B;CACxC,OAAO,UAAU,OAAO,SAAS,IAAI;AACvC;;AAGA,SAAgB,k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AQ,KAAK,kEAAkE;GAC/E,IAAI,IAAI,KAAK,KAAK;EACpB;CACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "16.3.5",
3
+ "version": "16.4.0",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",