@shware/analytics 9.0.0 → 9.0.1

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.
@@ -42,11 +42,15 @@ function getScrollPercent() {
42
42
  }
43
43
  function onPageHide() {
44
44
  require_setup_session.getSession().pagehide();
45
+ require_track_index.sendPendingEvents();
45
46
  sendUserEngagement("pagehide");
46
47
  }
47
48
  function onVisibilityChange() {
48
49
  require_setup_session.getSession().visibilitychange(document.visibilityState);
49
- if (document.visibilityState === "hidden") sendUserEngagement("visibilitychange");
50
+ if (document.visibilityState === "hidden") {
51
+ require_track_index.sendPendingEvents();
52
+ sendUserEngagement("visibilitychange");
53
+ }
50
54
  }
51
55
  /**
52
56
  * 1. send session_start event when the page is loaded
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.cjs","names":["config","keys","getSession","getPageKey","usePrevious","useRef","throttle"],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, track } from '../track/index';\nimport { getPageKey } from '../web/page-key';\nimport { usePrevious } from './use-previous';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\nfunction onPageHide() {\n getSession().pagehide();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const prevPage = usePrevious(page);\n const prevPathname = usePrevious(pathname);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n previous_page_path: prevPage === undefined ? undefined : prevPathname,\n engagement_time_msec: prevPage === undefined ? undefined : getSession().flush(),\n });\n }, [page]);\n}\n"],"mappings":";;;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAIA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,gBAAgB,GAAG;CACnD,oBAAA,MAAM,eAAe;EACnB,WAAW;EACX,YAAY,SAAS;EACrB,eAAe,SAAS;EACxB,eAAe,OAAO,SAAS;CACjC,CAAC;CACD,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,mCAAkB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACxE;AAEA,SAAS,mBAAmB,SAA0C;CACpE,MAAM,uBAAuBC,sBAAAA,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG;CAC/B,oBAAA,WAAW,mBAAmB;EAAE;EAAsB;CAAQ,CAAC;AACjE;;AAGA,SAAS,aAAsB;CAC7B,MAAM,uBAAuBA,sBAAAA,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG,OAAO;CACtC,oBAAA,MAAM,UAAU,EAAE,qBAAqB,CAAC;CACxC,OAAO;AACT;AAEA,SAAS,mBAAmB;CAC1B,MAAM,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Y,QAAQ,QAAQ;EACpD,OAAO,iBAAiB,YAAY,UAAU;EAC9C,SAAS,iBAAiB,oBAAoB,kBAAkB;EAGhE,iBAAiB,SAAS,MAAM;GAC9B,OAAO,iBAAiB,GAAG,YAAY;IAAE,SAAS;IAAM,SAAS;GAAK,CAAC;EACzE,CAAC;EAED,aAAa;GACX,OAAO,oBAAoB,SAAS,QAAQ,KAAK;GACjD,OAAO,oBAAoB,QAAQ,QAAQ,IAAI;GAC/C,OAAO,oBAAoB,UAAU,QAAQ;GAC7C,OAAO,oBAAoB,YAAY,QAAQ,QAAQ;GACvD,OAAO,oBAAoB,YAAY,UAAU;GACjD,SAAS,oBAAoB,oBAAoB,kBAAkB;GACnE,iBAAiB,SAAS,MAAM,OAAO,oBAAoB,GAAG,YAAY,EAAE,SAAS,KAAK,CAAC,CAAC;GAE5F,SAAS,OAAO;GAChB,WAAW,OAAO;EACpB;CACF,GAAG,CAAC,CAAC;CAEL,CAAA,GAAA,MAAA,UAAA,OAAgB;EAGd,oBAAA,MAAM,aAAa;GACjB,WAAW;GACX,YAAY,SAAS;GACrB,eAAe,SAAS;GACxB,eAAe,OAAO,SAAS;GAC/B,oBAAoB,aAAa,KAAA,IAAY,KAAA,IAAY;GACzD,sBAAsB,aAAa,KAAA,IAAY,KAAA,IAAYJ,sBAAAA,WAAW,CAAC,CAAC,MAAM;EAChF,CAAC;CACH,GAAG,CAAC,IAAI,CAAC;AACX"}
1
+ {"version":3,"file":"use-web-analytics.cjs","names":["config","keys","getSession","getPageKey","usePrevious","useRef","throttle"],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageKey } from '../web/page-key';\nimport { usePrevious } from './use-previous';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const prevPage = usePrevious(page);\n const prevPathname = usePrevious(pathname);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n previous_page_path: prevPage === undefined ? undefined : prevPathname,\n engagement_time_msec: prevPage === undefined ? undefined : getSession().flush(),\n });\n }, [page]);\n}\n"],"mappings":";;;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAIA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,gBAAgB,GAAG;CACnD,oBAAA,MAAM,eAAe;EACnB,W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,MAAM,aAAa;GACjB,WAAW;GACX,YAAY,SAAS;GACrB,eAAe,SAAS;GACxB,eAAe,OAAO,SAAS;GAC/B,oBAAoB,aAAa,KAAA,IAAY,KAAA,IAAY;GACzD,sBAAsB,aAAa,KAAA,IAAY,KAAA,IAAYJ,sBAAAA,WAAW,CAAC,CAAC,MAAM;EAChF,CAAC;CACH,GAAG,CAAC,IAAI,CAAC;AACX"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.d.cts","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"mappings":";;;;;;;;;wBA8DgB,gBAAgB,kBAAkB"}
1
+ {"version":3,"file":"use-web-analytics.d.cts","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"mappings":";;;;;;;;;wBAmEgB,gBAAgB,kBAAkB"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.d.mts","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"mappings":";;;;;;;;;wBA8DgB,gBAAgB,kBAAkB"}
1
+ {"version":3,"file":"use-web-analytics.d.mts","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"mappings":";;;;;;;;;wBAmEgB,gBAAgB,kBAAkB"}
@@ -1,7 +1,7 @@
1
1
  import { config } from "../setup/index.mjs";
2
2
  import { keys } from "../constants/storage.mjs";
3
3
  import { getSession } from "../setup/session.mjs";
4
- import { sendBeacon, track } from "../track/index.mjs";
4
+ import { sendBeacon, sendPendingEvents, track } from "../track/index.mjs";
5
5
  import { usePrevious } from "./use-previous.mjs";
6
6
  import { getPageKey } from "../web/page-key.mjs";
7
7
  import { throttle } from "@shware/utils";
@@ -41,11 +41,15 @@ function getScrollPercent() {
41
41
  }
42
42
  function onPageHide() {
43
43
  getSession().pagehide();
44
+ sendPendingEvents();
44
45
  sendUserEngagement("pagehide");
45
46
  }
46
47
  function onVisibilityChange() {
47
48
  getSession().visibilitychange(document.visibilityState);
48
- if (document.visibilityState === "hidden") sendUserEngagement("visibilitychange");
49
+ if (document.visibilityState === "hidden") {
50
+ sendPendingEvents();
51
+ sendUserEngagement("visibilitychange");
52
+ }
49
53
  }
50
54
  /**
51
55
  * 1. send session_start event when the page is loaded
@@ -1 +1 @@
1
- {"version":3,"file":"use-web-analytics.mjs","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, track } from '../track/index';\nimport { getPageKey } from '../web/page-key';\nimport { usePrevious } from './use-previous';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\nfunction onPageHide() {\n getSession().pagehide();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const prevPage = usePrevious(page);\n const prevPathname = usePrevious(pathname);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n previous_page_path: prevPage === undefined ? undefined : prevPathname,\n engagement_time_msec: prevPage === undefined ? undefined : getSession().flush(),\n });\n }, [page]);\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAI,OAAO,QAAQ,QAAQ,KAAK,gBAAgB,GAAG;CACnD,MAAM,eAAe;EACnB,WAAW;EACX,YAAY,SAAS;EACrB,eAAe,SAAS;EACxB,eAAe,OAAO,SAAS;CACjC,CAAC;CACD,OAAO,QAAQ,QAAQ,KAAK,mCAAkB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACxE;AAEA,SAAS,mBAAmB,SAA0C;CACpE,MAAM,uBAAuB,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG;CAC/B,WAAW,mBAAmB;EAAE;EAAsB;CAAQ,CAAC;AACjE;;AAGA,SAAS,aAAsB;CAC7B,MAAM,uBAAuB,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG,OAAO;CACtC,MAAM,UAAU,EAAE,qBAAqB,CAAC;CACxC,OAAO;AACT;AAEA,SAAS,mBAAmB;CAC1B,MAAM,YAAY,OAAO,WAAW,SAAS,gBAAgB;CAC7D,MAAM,eAAe,OAAO;CAC5B,MAAM,YAAY,SAAS,gBAAgB;CAC3C,IAAI,cAAc,GAAG,OAAO;CAC5B,QAAS,YAAY,gBAAgB,MAAO;AAC9C;AAEA,SAAS,aAAa;CACpB,WAAW,CAAC,CAAC,SAAS;CACtB,mBAAmB,UAAU;AAC/B;AAEA,SAAS,qBAAqB;CAC5B,WAAW,CAAC,CAAC,iBAAiB,SAAS,eAAe;CACtD,IAAI,SAAS,oBAAoB,UAC/B,mBAAmB,kBAAkB;AAEzC;;;;;;;;;AAUA,SAAgB,gBAAgB,UAAkB,QAAgB;CAChE,MAAM,OAAO,WAAW,UAAU,MAAM;CACxC,MAAM,WAAW,YAAY,IAAI;CACjC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;GACrB,eAAe,SAAS;GACxB,eAAe,OAAO,SAAS;GAC/B,oBAAoB,aAAa,KAAA,IAAY,KAAA,IAAY;GACzD,sBAAsB,aAAa,KAAA,IAAY,KAAA,IAAY,WAAW,CAAC,CAAC,MAAM;EAChF,CAAC;CACH,GAAG,CAAC,IAAI,CAAC;AACX"}
1
+ {"version":3,"file":"use-web-analytics.mjs","names":[],"sources":["../../src/hooks/use-web-analytics.ts"],"sourcesContent":["import { throttle } from '@shware/utils';\nimport { useEffect, useRef } from 'react';\nimport { keys } from '../constants/storage';\nimport { config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { sendBeacon, sendPendingEvents, track } from '../track/index';\nimport { getPageKey } from '../web/page-key';\nimport { usePrevious } from './use-previous';\n\nfunction sendFirstVisit(pathname: string) {\n if (config.storage.getItem(keys.first_visit_time)) return;\n track('first_visit', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n });\n config.storage.setItem(keys.first_visit_time, new Date().toISOString());\n}\n\nfunction sendUserEngagement(trigger: 'pagehide' | 'visibilitychange') {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return;\n sendBeacon('user_engagement', { engagement_time_msec, trigger });\n}\n\n/** Whether the event was actually sent — a zero-engagement crossing reports nothing. */\nfunction sendScroll(): boolean {\n const engagement_time_msec = getSession().flush();\n if (engagement_time_msec <= 0) return false;\n track('scroll', { engagement_time_msec });\n return true;\n}\n\nfunction getScrollPercent() {\n const scrollTop = window.scrollY || document.documentElement.scrollTop;\n const windowHeight = window.innerHeight;\n const docHeight = document.documentElement.scrollHeight;\n if (docHeight === 0) return 0;\n return ((scrollTop + windowHeight) * 100) / docHeight;\n}\n\n// The queue goes first: a new session's `session_start` is in it, ahead of the engagement that\n// reports for that session. On `hidden` as well as on `pagehide`, as GA4 does: a mobile browser\n// often discards a hidden page without firing `pagehide`.\nfunction onPageHide() {\n getSession().pagehide();\n sendPendingEvents();\n sendUserEngagement('pagehide');\n}\n\nfunction onVisibilityChange() {\n getSession().visibilitychange(document.visibilityState);\n if (document.visibilityState === 'hidden') {\n sendPendingEvents();\n sendUserEngagement('visibilitychange');\n }\n}\n\n/**\n * 1. send session_start event when the page is loaded\n * 2. send scroll event when the user scrolls more than 90% of the page\n * 3. send user_engagement event when the page is hidden or the user is not focused\n * 4. send page_view when the page changes — path or query, see `getPageKey`; `search` is the\n * router's query string (`?a=1`, or `''`), required so no caller forgets that the query is\n * part of what makes a page\n */\nexport function useWebAnalytics(pathname: string, search: string) {\n const page = getPageKey(pathname, search);\n const prevPage = usePrevious(page);\n const prevPathname = usePrevious(pathname);\n\n // reset state when the page changes and send scroll when the user navigates to a new page\n const hasSendScroll = useRef(false);\n useEffect(() => {\n hasSendScroll.current = false;\n }, [page]);\n\n useEffect(() => {\n // One lookup for the whole effect: `addEventListener` and its matching\n // `removeEventListener` have to be handed the very same function.\n const session = getSession();\n\n sendFirstVisit(pathname);\n\n const onScroll = throttle(() => {\n session.updateAccumulator();\n if (hasSendScroll.current) return;\n // only send scroll when the user has scrolled more than 90% of the page\n if (getScrollPercent() < 90) return;\n // A crossing with no engaged time (a restored scroll position in an unfocused window) must\n // not consume the page's one shot: the flag is set only once the event is actually sent.\n hasSendScroll.current = sendScroll();\n }, 500);\n\n const checkpointEvents = ['mousedown', 'keydown', 'touchstart'];\n const checkpoint = throttle(session.updateAccumulator, 1000);\n\n window.addEventListener('focus', session.focus);\n window.addEventListener('blur', session.blur);\n window.addEventListener('scroll', onScroll, { passive: true });\n window.addEventListener('pageshow', session.pageshow);\n window.addEventListener('pagehide', onPageHide);\n document.addEventListener('visibilitychange', onVisibilityChange);\n\n // save checkpoint\n checkpointEvents.forEach((e) => {\n window.addEventListener(e, checkpoint, { passive: true, capture: true });\n });\n\n return () => {\n window.removeEventListener('focus', session.focus);\n window.removeEventListener('blur', session.blur);\n window.removeEventListener('scroll', onScroll);\n window.removeEventListener('pageshow', session.pageshow);\n window.removeEventListener('pagehide', onPageHide);\n document.removeEventListener('visibilitychange', onVisibilityChange);\n checkpointEvents.forEach((e) => window.removeEventListener(e, checkpoint, { capture: true }));\n\n onScroll.cancel();\n checkpoint.cancel();\n };\n }, []);\n\n useEffect(() => {\n // `page_path` stays the path — the query is in `page_location` — and the previous page is\n // named by its path too, so a query-only change reports the same path as its predecessor.\n track('page_view', {\n page_path: pathname,\n page_title: document.title,\n page_referrer: document.referrer,\n page_location: window.location.href,\n previous_page_path: prevPage === undefined ? undefined : prevPathname,\n engagement_time_msec: prevPage === undefined ? undefined : getSession().flush(),\n });\n }, [page]);\n}\n"],"mappings":";;;;;;;;;AASA,SAAS,eAAe,UAAkB;CACxC,IAAI,OAAO,QAAQ,QAAQ,KAAK,gBAAgB,GAAG;CACnD,MAAM,eAAe;EACnB,WAAW;EACX,YAAY,SAAS;EACrB,eAAe,SAAS;EACxB,eAAe,OAAO,SAAS;CACjC,CAAC;CACD,OAAO,QAAQ,QAAQ,KAAK,mCAAkB,IAAI,KAAK,EAAA,CAAE,YAAY,CAAC;AACxE;AAEA,SAAS,mBAAmB,SAA0C;CACpE,MAAM,uBAAuB,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG;CAC/B,WAAW,mBAAmB;EAAE;EAAsB;CAAQ,CAAC;AACjE;;AAGA,SAAS,aAAsB;CAC7B,MAAM,uBAAuB,WAAW,CAAC,CAAC,MAAM;CAChD,IAAI,wBAAwB,GAAG,OAAO;CACtC,MAAM,UAAU,EAAE,qBAAqB,CAAC;CACxC,OAAO;AACT;AAEA,SAAS,mBAAmB;CAC1B,MAAM,YAAY,OAAO,WAAW,SAAS,gBAAgB;CAC7D,MAAM,eAAe,OAAO;CAC5B,MAAM,YAAY,SAAS,gBAAgB;CAC3C,IAAI,cAAc,GAAG,OAAO;CAC5B,QAAS,YAAY,gBAAgB,MAAO;AAC9C;AAKA,SAAS,aAAa;CACpB,WAAW,CAAC,CAAC,SAAS;CACtB,kBAAkB;CAClB,mBAAmB,UAAU;A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O,oBAAoB,YAAY,UAAU;GACjD,SAAS,oBAAoB,oBAAoB,kBAAkB;GACnE,iBAAiB,SAAS,MAAM,OAAO,oBAAoB,GAAG,YAAY,EAAE,SAAS,KAAK,CAAC,CAAC;GAE5F,SAAS,OAAO;GAChB,WAAW,OAAO;EACpB;CACF,GAAG,CAAC,CAAC;CAEL,gBAAgB;EAGd,MAAM,aAAa;GACjB,WAAW;GACX,YAAY,SAAS;GACrB,eAAe,SAAS;GACxB,eAAe,OAAO,SAAS;GAC/B,oBAAoB,aAAa,KAAA,IAAY,KAAA,IAAY;GACzD,sBAAsB,aAAa,KAAA,IAAY,KAAA,IAAY,WAAW,CAAC,CAAC,MAAM;EAChF,CAAC;CACH,GAAG,CAAC,IAAI,CAAC;AACX"}
package/dist/index.cjs CHANGED
@@ -22,6 +22,7 @@ exports.getLink = require_link_index.getLink;
22
22
  exports.getVisitor = require_visitor_index.getVisitor;
23
23
  exports.sendBeacon = require_track_index.sendBeacon;
24
24
  exports.sendFeedback = require_feedback_index.sendFeedback;
25
+ exports.sendPendingEvents = require_track_index.sendPendingEvents;
25
26
  exports.setVisitor = require_visitor_index.setVisitor;
26
27
  exports.setupAnalytics = require_setup_index.setupAnalytics;
27
28
  exports.stripeMinorUnits = require_utils_stripe.stripeMinorUnits;
package/dist/index.d.cts CHANGED
@@ -5,8 +5,8 @@ import { sendFeedback } from "./feedback/index.cjs";
5
5
  import { useTrackImpression } from "./hooks/use-track-impression.cjs";
6
6
  import { VisitorProperties } from "./visitor/types.cjs";
7
7
  import { setupAnalytics } from "./setup/index.cjs";
8
- import { sendBeacon, track, trackAsync } from "./track/index.cjs";
8
+ import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.cjs";
9
9
  import { getVisitor, setVisitor } from "./visitor/index.cjs";
10
10
  import { Link, createLink, getLink } from "./link/index.cjs";
11
11
  import { stripeMinorUnits } from "./utils/stripe.cjs";
12
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CustomEventProperties, type Environment, type Link, NOT_A_BOT, type Platform, type TrackProperties, type TrackTags, type UTMParams, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
12
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CustomEventProperties, type Environment, type Link, NOT_A_BOT, type Platform, type TrackProperties, type TrackTags, type UTMParams, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
package/dist/index.d.mts CHANGED
@@ -5,8 +5,8 @@ import { sendFeedback } from "./feedback/index.mjs";
5
5
  import { useTrackImpression } from "./hooks/use-track-impression.mjs";
6
6
  import { VisitorProperties } from "./visitor/types.mjs";
7
7
  import { setupAnalytics } from "./setup/index.mjs";
8
- import { sendBeacon, track, trackAsync } from "./track/index.mjs";
8
+ import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.mjs";
9
9
  import { getVisitor, setVisitor } from "./visitor/index.mjs";
10
10
  import { Link, createLink, getLink } from "./link/index.mjs";
11
11
  import { stripeMinorUnits } from "./utils/stripe.mjs";
12
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CustomEventProperties, type Environment, type Link, NOT_A_BOT, type Platform, type TrackProperties, type TrackTags, type UTMParams, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
12
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, type AllowedPropertyValues, BOT_CATEGORIES, type Bot, type BotCategory, type CreateFeedbackDTO, type CreateLinkDTO, type CustomEventProperties, type Environment, type Link, NOT_A_BOT, type Platform, type TrackProperties, type TrackTags, type UTMParams, type UserProvidedData, type VisitorProperties, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
package/dist/index.mjs CHANGED
@@ -1,10 +1,10 @@
1
1
  import { setupAnalytics } from "./setup/index.mjs";
2
2
  import { getVisitor, setVisitor } from "./visitor/index.mjs";
3
- import { sendBeacon, track, trackAsync } from "./track/index.mjs";
3
+ import { sendBeacon, sendPendingEvents, track, trackAsync } from "./track/index.mjs";
4
4
  import { sendFeedback } from "./feedback/index.mjs";
5
5
  import { createLink, getLink } from "./link/index.mjs";
6
6
  import { ALL_ENVIRONMENTS, ALL_PLATFORMS, createFeedbackSchema, createLinkSchema, createTrackEventSchema, createVisitorSchema, updateVisitorSchema } from "./schema/index.mjs";
7
7
  import { BOT_CATEGORIES, NOT_A_BOT, botOf } from "./bot/index.mjs";
8
8
  import { stripeMinorUnits } from "./utils/stripe.mjs";
9
9
  import { useTrackImpression } from "./hooks/use-track-impression.mjs";
10
- export { ALL_ENVIRONMENTS, ALL_PLATFORMS, BOT_CATEGORIES, NOT_A_BOT, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
10
+ export { ALL_ENVIRONMENTS, ALL_PLATFORMS, BOT_CATEGORIES, NOT_A_BOT, botOf, createFeedbackSchema, createLink, createLinkSchema, createTrackEventSchema, createVisitorSchema, getLink, getVisitor, sendBeacon, sendFeedback, sendPendingEvents, setVisitor, setupAnalytics, stripeMinorUnits, track, trackAsync, updateVisitorSchema, useTrackImpression };
@@ -57,7 +57,7 @@ var Session = class {
57
57
  };
58
58
  this.extend = () => {
59
59
  const stored = readSession();
60
- if (!stored) return this.touch(Date.now()).id;
60
+ if (!stored) return void 0;
61
61
  const now = Date.now();
62
62
  if (now - stored.lastEventTime <= 18e5) writeSession({
63
63
  ...stored,
@@ -1 +1 @@
1
- {"version":3,"file":"session.cjs","names":["config","keys","uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the `pagehide` beacon, which reports what\n * the session now ending accrued. A live session is extended, as any event extends it; one\n * already past its timeout still owns that engagement, so its id comes back without being\n * revived into a session no `session_start` ever announced.\n */\n extend = (): string => {\n const stored = readSession();\n if (!stored) return this.touch(Date.now()).id;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQC,0BAAAA,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OAAO,aAAa,GAAG,OAAO,KAAA;CACnD,OAAO;AACT;AAEA,SAAS,aAAa,EAAE,IAAI,iBAAgC;CAC1D,oBAAA,OAAO,QAAQ,QAAQA,0BAAAA,KAAK,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,eAAe;AAC1E;AAEA,IAAM,UAAN,MAAc;CAgBZ,cAAc;EAeL,KAAA,SAAA,WAAmB,gBAAgB,cAA+B;GACzE,MAAM,SAAS,YAAY;GAE3B,IAAI,UAAU,YAAY,OAAO,iBAAA,MAAkC;IAGjE,aAAa;KAAE,GAAG;KAAQ,eAAe,KAAK,IAAI,OAAO,eAAe,aAAa;IAAE,CAAC;IACxF,OAAO;KAAE,IAAI,OAAO;KAAI,SAAS;IAAM;GACzC;GAIA,KAAK,kBAAkB;GAGvB,KAAK,eAAe,KAAK,IAAI;GAE7B,MAAM,UAAyB;IAAE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;IAAG;GAAc;GAC7D,aAAa,OA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AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
1
+ {"version":3,"file":"session.cjs","names":["config","keys","uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the engagement beacon, which reports what\n * the session accrued. A live session is extended, as any event extends it; one already past its\n * timeout still owns that engagement, so its id comes back without being revived into a session\n * no `session_start` ever announced. With nothing stored, no event was ever queued here, so\n * there is no session to report for, and none is started: it would never be announced.\n */\n extend = (): string | undefined => {\n const stored = readSession();\n if (!stored) return undefined;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;;AAIA,MAAa,kBAA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EAChB;EAEiB,KAAA,iBAAA,KAAK;EAEN,KAAA,gBAAA,WAAoB;GAClC,KAAK,SAAS;EAChB;EAE0B,KAAA,0BAAA;GACxB,MAAM,MAAM,KAAK,IAAI;GACrB,IAAI,KAAK,WAAW,KAAK,WAAW,KAAK,QAAQ;IAC/C,MAAM,QAAQ,MAAM,KAAK;IACzB,IAAI,QAAQ,KAAK,QAAA,MACf,KAAK,mBAAmB;GAE5B;GACA,KAAK,eAAe;EACtB;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEa,KAAA,aAAA;GACX,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEoB,KAAA,oBAAA,UAAmC;GACrD,KAAK,kBAAkB;GACvB,KAAK,UAAU,UAAU;EAC3B;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,MAAM,iBAAiB,KAAK;GAC5B,KAAK,kBAAkB;GACvB,OAAO;EACT;EArGE,KAAK,eAAe,KAAK,IAAI;EAC7B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAgGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
@@ -28,12 +28,13 @@ declare class Session {
28
28
  */
29
29
  touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
30
30
  /**
31
- * The id for an event that must not start a session — the `pagehide` beacon, which reports what
32
- * the session now ending accrued. A live session is extended, as any event extends it; one
33
- * already past its timeout still owns that engagement, so its id comes back without being
34
- * revived into a session no `session_start` ever announced.
31
+ * The id for an event that must not start a session — the engagement beacon, which reports what
32
+ * the session accrued. A live session is extended, as any event extends it; one already past its
33
+ * timeout still owns that engagement, so its id comes back without being revived into a session
34
+ * no `session_start` ever announced. With nothing stored, no event was ever queued here, so
35
+ * there is no session to report for, and none is started: it would never be announced.
35
36
  */
36
- extend: () => string;
37
+ extend: () => string | undefined;
37
38
  isActive: () => boolean;
38
39
  updateActive: (active: boolean) => void;
39
40
  updateAccumulator: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;EA4BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
1
+ {"version":3,"file":"session.d.cts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;;EA6BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
@@ -28,12 +28,13 @@ declare class Session {
28
28
  */
29
29
  touch: (eventTime: number, lastEventTime?: number) => SessionForEvent;
30
30
  /**
31
- * The id for an event that must not start a session — the `pagehide` beacon, which reports what
32
- * the session now ending accrued. A live session is extended, as any event extends it; one
33
- * already past its timeout still owns that engagement, so its id comes back without being
34
- * revived into a session no `session_start` ever announced.
31
+ * The id for an event that must not start a session — the engagement beacon, which reports what
32
+ * the session accrued. A live session is extended, as any event extends it; one already past its
33
+ * timeout still owns that engagement, so its id comes back without being revived into a session
34
+ * no `session_start` ever announced. With nothing stored, no event was ever queued here, so
35
+ * there is no session to report for, and none is started: it would never be announced.
35
36
  */
36
- extend: () => string;
37
+ extend: () => string | undefined;
37
38
  isActive: () => boolean;
38
39
  updateActive: (active: boolean) => void;
39
40
  updateAccumulator: () => void;
@@ -1 +1 @@
1
- {"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;EA4BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
1
+ {"version":3,"file":"session.d.mts","names":[],"sources":["../../src/setup/session.ts"],"mappings":";qBAIa;;UAiBH;EACR;EACA;;cA8BI;;;;;;;;;UASI;UACA;UAEA;UACA;UACA;EAER;;;;;;;EAeA,QAAK,mBAAqB,2BAA8B;;;;;;;;EA6BxD;EAWA;EAEA,eAAY;EAIZ;EAWA;EAKA;EAKA;EAKA;EAKA,mBAAgB,OAAW;EAK3B;;;;;;;;;;;;;;;;;;;;;;;;;;wBAkCc,cAAU"}
@@ -56,7 +56,7 @@ var Session = class {
56
56
  };
57
57
  this.extend = () => {
58
58
  const stored = readSession();
59
- if (!stored) return this.touch(Date.now()).id;
59
+ if (!stored) return void 0;
60
60
  const now = Date.now();
61
61
  if (now - stored.lastEventTime <= 18e5) writeSession({
62
62
  ...stored,
@@ -1 +1 @@
1
- {"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the `pagehide` beacon, which reports what\n * the session now ending accrued. A live session is extended, as any event extends it; one\n * already past its timeout still owns that engagement, so its id comes back without being\n * revived into a session no `session_start` ever announced.\n */\n extend = (): string => {\n const stored = readSession();\n if (!stored) return this.touch(Date.now()).id;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAM,OAAO,QAAQ,QAAQ,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OA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jB;EAEa,KAAA,aAAA;GACX,KAAK,kBAAkB;GACvB,KAAK,UAAU;EACjB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEiB,KAAA,iBAAA;GACf,KAAK,kBAAkB;GACvB,KAAK,SAAS;EAChB;EAEoB,KAAA,oBAAA,UAAmC;GACrD,KAAK,kBAAkB;GACvB,KAAK,UAAU,UAAU;EAC3B;EAEc,KAAA,cAAA;GACZ,KAAK,kBAAkB;GACvB,MAAM,iBAAiB,KAAK;GAC5B,KAAK,kBAAkB;GACvB,OAAO;EACT;EApGE,KAAK,eAAe,KAAK,IAAI;EAC7B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AA+FF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
1
+ {"version":3,"file":"session.mjs","names":["uuidv7"],"sources":["../../src/setup/session.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { keys } from '../constants/storage';\nimport { config } from './index';\n\nexport const SESSION_TIMEOUT = 30 * 60 * 1000;\n\n/**\n * The part of a session that outlives the page: its identity, and the clock the timeout is\n * measured against. GA4 keeps these in its `_ga_<container>` cookie — alongside the engaged flag,\n * which arrives with `session_engaged` later — and rereads them for every event, which is what\n * makes a session survive a reload, span a whole multipage visit, and stay shared between two\n * tabs of the same site. Holding them in memory instead, as this did, starts a new session on\n * every full navigation and gives every tab one of its own.\n */\ninterface StoredSession {\n id: string;\n /** When the last event was sent. The timeout is measured from here, and only from here. */\n lastEventTime: number;\n}\n\n/** The session an event belongs to, and whether that event is the one that started it. */\ninterface SessionForEvent {\n id: string;\n started: boolean;\n}\n\n/**\n * `<version>.<id>.<lastEventTime>`, compact and cookie-safe rather than JSON: `{`, `\"`\n * and `,` all have to be percent-encoded in a cookie, and a host that wants one session across\n * its subdomains will hand `setupAnalytics` a cookie-backed `storage`, where this has to survive\n * unchanged. A uuidv7 contains no dots, so the record splits cleanly.\n *\n * The version guards a change the parser could not otherwise survive. A field appended to the end\n * does not need one — a short record simply leaves it undefined.\n */\nconst VERSION = '1';\n\nfunction readSession(): StoredSession | undefined {\n const raw = config.storage.getItem(keys.session);\n if (!raw) return undefined;\n\n const [version, id, lastEventTime] = raw.split('.');\n if (version !== VERSION || !id) return undefined;\n\n const parsed = { id, lastEventTime: Number(lastEventTime) };\n if (!Number.isFinite(parsed.lastEventTime)) return undefined;\n return parsed;\n}\n\nfunction writeSession({ id, lastEventTime }: StoredSession) {\n config.storage.setItem(keys.session, `${VERSION}.${id}.${lastEventTime}`);\n}\n\nclass Session {\n /**\n * Engagement is deliberately not stored: it is the time this page has accrued and not yet\n * reported, so it belongs to the page, not to the session. GA4 draws the same line — its cookie\n * carries the session, while the engagement timer lives and dies with the document.\n *\n * `lastTickTime` is where the accumulator last settled up, rewritten on every tick — it is not\n * when the session began, and nothing here needs to know that.\n */\n private lastTickTime: number;\n private accumulatedTime: number;\n\n private active: boolean;\n private visible: boolean;\n private focused: boolean;\n\n constructor() {\n this.lastTickTime = Date.now();\n this.accumulatedTime = 0;\n\n this.active = true;\n this.visible = typeof document !== 'undefined' ? document.visibilityState === 'visible' : true;\n this.focused = typeof document !== 'undefined' ? document.hasFocus() : true;\n }\n\n /**\n * The session a batch of events belongs to: read the stored one, start a new one if it has\n * timed out or there is none, stamp it with when those events happened and write it back. Every\n * event goes through here, exactly as GA4 rereads and rewrites its cookie per event — caching\n * the session in memory would put the tabs back out of step with each other.\n */\n touch = (eventTime: number, lastEventTime = eventTime): SessionForEvent => {\n const stored = readSession();\n\n if (stored && eventTime - stored.lastEventTime <= SESSION_TIMEOUT) {\n // `Math.max`, because a batch that waited in a frozen tab can be older than what another\n // tab has since written, and a session must never be shortened by a late arrival.\n writeSession({ ...stored, lastEventTime: Math.max(stored.lastEventTime, lastEventTime) });\n return { id: stored.id, started: false };\n }\n\n // Engagement the previous session accrued but never reported dies with it rather than being\n // handed to its successor. GA4 does the same on `session_start`.\n this.accumulatedTime = 0;\n // Wall clock, not `eventTime`: this anchors the engagement timer for the page in front of the\n // visitor now, which a batch describing something that happened an hour ago says nothing about.\n this.lastTickTime = Date.now();\n\n const session: StoredSession = { id: uuidv7(), lastEventTime };\n writeSession(session);\n return { id: session.id, started: true };\n };\n\n /**\n * The id for an event that must not start a session — the engagement beacon, which reports what\n * the session accrued. A live session is extended, as any event extends it; one already past its\n * timeout still owns that engagement, so its id comes back without being revived into a session\n * no `session_start` ever announced. With nothing stored, no event was ever queued here, so\n * there is no session to report for, and none is started: it would never be announced.\n */\n extend = (): string | undefined => {\n const stored = readSession();\n if (!stored) return undefined;\n\n const now = Date.now();\n if (now - stored.lastEventTime <= SESSION_TIMEOUT) {\n writeSession({ ...stored, lastEventTime: now });\n }\n return stored.id;\n };\n\n isActive = () => this.active;\n\n updateActive = (active: boolean) => {\n this.active = active;\n };\n\n updateAccumulator = () => {\n const now = Date.now();\n if (this.focused && this.visible && this.active) {\n const delta = now - this.lastTickTime;\n if (delta > 0 && delta < SESSION_TIMEOUT) {\n this.accumulatedTime += delta;\n }\n }\n this.lastTickTime = now;\n };\n\n focus = () => {\n this.updateAccumulator();\n this.focused = true;\n };\n\n blur = () => {\n this.updateAccumulator();\n this.focused = false;\n };\n\n pageshow = () => {\n this.updateAccumulator();\n this.active = true;\n };\n\n pagehide = () => {\n this.updateAccumulator();\n this.active = false;\n };\n\n visibilitychange = (state: DocumentVisibilityState) => {\n this.updateAccumulator();\n this.visible = state === 'visible';\n };\n\n flush = () => {\n this.updateAccumulator();\n const engagementTime = this.accumulatedTime;\n this.accumulatedTime = 0;\n return engagementTime;\n };\n}\n\nlet session: Session | undefined;\n\n/**\n * The session, built the first time something asks for it.\n *\n * Deliberately not a module-scope `new Session()`. The constructor calls\n * `uuidv7()`, `uuid` draws its bytes from `crypto.getRandomValues`, and\n * Cloudflare Workers reject that outside a request handler:\n *\n * Disallowed operation called within global scope. Asynchronous I/O\n * (ex: fetch() or connect()), setting a timeout, and generating random\n * values are not allowed within global scope.\n *\n * Module scope in a Worker is evaluated once when the isolate boots and is\n * then shared by every request that isolate serves, so a random value drawn\n * there would be the same for all of them — which is why the runtime refuses\n * to produce one. A host that server-renders on Workers reaches this module\n * through `track()` on the server as well, and the throw happened as the\n * isolate booted, taking down every route before a component rendered.\n *\n * Everything here is per-visitor browser or app state, so deferring the\n * construction costs nothing and lets the server bundle be evaluated. It does\n * not make any of it safe to use there: this instance, `cache` and `config` are\n * module singletons, so calling `track()` on a server shares one session and one\n * visitor across every request the isolate serves. Import it there; do not track.\n */\nexport function getSession() {\n return (session ??= new Session());\n}\n"],"mappings":";;;;AAIA,MAAa,kBAAkB;;;;;;;;;;AA+B/B,MAAM,UAAU;AAEhB,SAAS,cAAyC;CAChD,MAAM,MAAM,OAAO,QAAQ,QAAQ,KAAK,OAAO;CAC/C,IAAI,CAAC,KAAK,OAAO,KAAA;CAEjB,MAAM,CAAC,SAAS,IAAI,iBAAiB,IAAI,MAAM,GAAG;CAClD,IAAI,YAAY,WAAW,CAAC,IAAI,OAAO,KAAA;CAEvC,MAAM,SAAS;EAAE;EAAI,eAAe,OAAO,aAAa;CAAE;CAC1D,IAAI,CAAC,OAAO,SAAS,OAAO,aAAa,GAAG,OAAO,KAAA;CACnD,OAAO;AACT;AAEA,SAAS,aAAa,EAAE,IAAI,iBAAgC;CAC1D,OAAO,QAAQ,QAAQ,KAAK,SAAS,GAAG,QAAQ,GAAG,GAAG,GAAG,eAAe;AAC1E;AAEA,IAAM,UAAN,MAAc;CAgBZ,cAAc;EAeL,KAAA,SAAA,WAAmB,gBAAgB,cAA+B;GACzE,MAAM,SAAS,YAAY;GAE3B,IAAI,UAAU,YAAY,OAAO,iBAAA,MAAkC;IAGjE,aAAa;K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O;EACT;EArGE,KAAK,eAAe,KAAK,IAAI;EAC7B,KAAK,kBAAkB;EAEvB,KAAK,SAAS;EACd,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,oBAAoB,YAAY;EAC1F,KAAK,UAAU,OAAO,aAAa,cAAc,SAAS,SAAS,IAAI;CACzE;AAgGF;AAEA,IAAI;;;;;;;;;;;;;;;;;;;;;;;;;AA0BJ,SAAgB,aAAa;CAC3B,OAAQ,YAAY,IAAI,QAAQ;AAClC"}
@@ -39,146 +39,213 @@ async function captureTags() {
39
39
  }
40
40
  }
41
41
  /**
42
- * The `session_start` a failed batch took down with it, kept for the next batch of the same
43
- * session. `fetch` has already retried the transient failures by the time a batch fails here;
44
- * what remains is a batch the server rejected outright — one invalid event fails the whole batch,
45
- * and `session_start` with it — or a network that stayed down past the retries. Neither is a
46
- * reason to lose the session's one attribution record, so it goes out again, with the tags and
47
- * timestamp of the moment the session actually began, under the same session id. Held in memory
48
- * only: a reload loses it, and with it the session_start — the same as before this existed.
42
+ * The events not yet sent, and the only place they are: a batch leaves it at the moment it is
43
+ * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,
44
+ * everything still unsent is right here for `sendPendingEvents`.
49
45
  */
50
- let pendingStart;
51
- async function sendEvents(events) {
52
- /** The announcement this batch carries, if any, so the catch below can hold it back. */
53
- let announcement;
46
+ const list = [];
47
+ const batchSize = 10;
48
+ const delay = 2e3;
49
+ let timer = null;
50
+ /**
51
+ * Queues an event, preceded by a `session_start` when it is the one that opens a session.
52
+ *
53
+ * The session is decided here, when the event happens, as GA4 and PostHog decide it: the
54
+ * `session_start` then sits in the queue right before the event that opened the session, so
55
+ * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.
56
+ * It carries that event's tags and time, as GA4 derives it from the hit that started the
57
+ * session: the landing page is where the session began, whatever the page has navigated to by
58
+ * the time the batch goes out.
59
+ */
60
+ function enqueue(name, properties, options) {
61
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
62
+ const tags = captureTags();
63
+ const { id: session_id, started } = require_setup_session.getSession().touch(Date.parse(timestamp));
64
+ const item = (fields) => {
65
+ const result = {
66
+ ...fields,
67
+ tags,
68
+ timestamp,
69
+ session_id
70
+ };
71
+ tags.then((settled) => result.settled = settled);
72
+ return result;
73
+ };
74
+ if (started) list.push(item({
75
+ name: "session_start",
76
+ properties: {},
77
+ options: { enableThirdPartyTracking: false }
78
+ }));
79
+ const event = item({
80
+ name,
81
+ properties,
82
+ options
83
+ });
84
+ list.push(event);
85
+ return event;
86
+ }
87
+ /**
88
+ * Sends the queue. Everything that has to be awaited is awaited first, and only then are the
89
+ * events taken off the queue and handed to `fetch` in the same synchronous step — so there is
90
+ * no moment at which an event is neither queued nor sent.
91
+ */
92
+ async function flush() {
93
+ if (timer) {
94
+ clearTimeout(timer);
95
+ timer = null;
96
+ }
97
+ if (list.length === 0) return;
98
+ let events = [];
54
99
  try {
55
- if (events.length === 0) return;
56
- const opening = events[0];
57
- const { id: session_id, started } = require_setup_session.getSession().touch(Date.parse(opening.timestamp), Date.parse(events[events.length - 1].timestamp));
58
- if (started || pendingStart?.session_id === session_id) {
59
- const start = pendingStart?.session_id === session_id ? pendingStart.item : {
60
- name: "session_start",
61
- properties: {},
62
- options: { enableThirdPartyTracking: false },
63
- tags: opening.tags,
64
- timestamp: opening.timestamp
65
- };
66
- pendingStart = void 0;
67
- announcement = {
68
- session_id,
69
- item: start
70
- };
71
- events.unshift(start);
72
- }
73
100
  await getTokenBucket().removeTokens();
74
101
  const visitor_id = (await require_visitor_index.getVisitor()).id;
102
+ const headers = await require_setup_index.config.getHeaders();
103
+ await Promise.all(list.map((event) => event.tags));
104
+ events = list.splice(0);
105
+ if (events.length === 0) return;
75
106
  const dto = await Promise.all(events.map(async (event) => ({
76
107
  name: event.name,
77
108
  properties: event.properties,
78
109
  tags: await event.tags,
79
110
  visitor_id,
80
- session_id,
111
+ session_id: event.session_id,
81
112
  platform: require_setup_index.config.platform,
82
113
  environment: require_setup_index.config.environment,
83
114
  timestamp: event.timestamp
84
115
  })));
116
+ const body = JSON.stringify(dto);
85
117
  const response = await (0, _shware_utils.fetch)(`${require_setup_index.config.endpoint}/events`, {
86
118
  method: "POST",
87
119
  credentials: "include",
88
- keepalive: true,
89
- headers: await require_setup_index.config.getHeaders(),
90
- body: JSON.stringify(dto)
120
+ keepalive: body.length < 6e4,
121
+ headers,
122
+ body
91
123
  });
92
124
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
93
125
  const data = await response.json();
94
- let index = 0;
95
- while (events.length > 0) {
96
- const event = events.shift();
97
- if (!event) {
98
- index++;
99
- continue;
100
- }
101
- const { options, name, properties } = event;
126
+ events.forEach((event, index) => {
102
127
  const eventId = data.at(index)?.id;
103
- options.onSucceed?.(eventId ? { id: eventId } : void 0);
104
- index++;
105
- if (options.enableThirdPartyTracking === false || require_third_parties_ignored_events.IGNORED_EVENTS.includes(name)) continue;
128
+ event.options.onSucceed?.(eventId ? { id: eventId } : void 0);
129
+ if (event.options.enableThirdPartyTracking === false || require_third_parties_ignored_events.IGNORED_EVENTS.includes(event.name)) return;
106
130
  require_setup_index.config.thirdPartyTrackers.forEach((tracker) => {
107
131
  try {
108
- tracker(name, properties, eventId);
132
+ tracker(event.name, event.properties, eventId);
109
133
  } catch (e) {
110
134
  if (e instanceof Error) console.log(e.message);
111
135
  }
112
136
  });
113
- }
137
+ });
114
138
  } catch (e) {
115
139
  if (e instanceof Error) console.log(e.message);
116
- if (announcement) pendingStart = announcement;
117
- events.forEach((event) => event.options.onError?.(e));
118
- }
119
- }
120
- const batch = 10;
121
- const delay = 2e3;
122
- const list = [];
123
- let timer = null;
124
- /**
125
- * Both paths into a send go through here, so a batch that fills up cancels the timer the
126
- * previous push armed rather than leaving it to wake up on its own with nothing to send.
127
- */
128
- function flush() {
129
- if (timer) {
130
- clearTimeout(timer);
131
- timer = null;
140
+ const starts = events.filter((event) => event.name === "session_start");
141
+ list.unshift(...starts);
142
+ events.filter((event) => event.name !== "session_start").forEach((event) => event.options.onError?.(e));
132
143
  }
133
- if (list.length === 0) return;
134
- const copy = [...list];
135
- list.length = 0;
136
- sendEvents(copy);
137
144
  }
138
145
  function track(name, properties, options = defaultOptions) {
139
- list.push({
140
- name,
141
- properties,
142
- options,
143
- tags: captureTags(),
144
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
145
- });
146
- if (list.length >= batch) {
146
+ enqueue(name, properties, options);
147
+ if (list.length >= batchSize) {
147
148
  flush();
148
149
  return;
149
150
  }
150
151
  if (timer) clearTimeout(timer);
151
- timer = setTimeout(flush, delay);
152
+ timer = setTimeout(() => void flush(), delay);
152
153
  }
154
+ /**
155
+ * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
156
+ * when no visitor could be created to send it with, at once, the event left queued for the next
157
+ * send. It never rejects: tracking must not fail the step that awaits it.
158
+ */
153
159
  async function trackAsync(name, properties, options = defaultOptions) {
154
- await sendEvents([{
155
- name,
156
- properties,
157
- options,
158
- tags: captureTags(),
159
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
160
- }]);
160
+ let settle;
161
+ const settled = new Promise((resolve) => {
162
+ settle = resolve;
163
+ });
164
+ const event = enqueue(name, properties, {
165
+ ...options,
166
+ onSucceed: (response) => {
167
+ options.onSucceed?.(response);
168
+ settle();
169
+ },
170
+ onError: (error) => {
171
+ options.onError?.(error);
172
+ settle();
173
+ }
174
+ });
175
+ await flush();
176
+ if (list.includes(event)) return;
177
+ await settled;
161
178
  }
162
- function sendBeacon(name, properties) {
179
+ /**
180
+ * The visitor id a beacon can carry. It is persisted, so a returning visitor already has one
181
+ * before `getVisitor` has finished its round trip for this page. Requiring the in-memory copy
182
+ * threw away exactly the events a beacon exists for: everything a visit accrues before its first
183
+ * batch comes back, which for a short visit is the whole of it. A visitor the server has never
184
+ * seen has none: the server would reject its events.
185
+ */
186
+ function beaconVisitorId() {
163
187
  const stored = require_setup_index.config.storage.getItem(require_constants_storage.keys.visitor_id);
164
- const visitor_id = require_setup_index.cache.visitor?.id ?? (stored && stored !== "undefined" ? stored : void 0);
188
+ return require_setup_index.cache.visitor?.id ?? (stored && stored !== "undefined" ? stored : void 0);
189
+ }
190
+ function beacon(dto) {
191
+ if (typeof navigator === "undefined" || !("sendBeacon" in navigator)) return false;
192
+ const blob = new Blob([JSON.stringify(dto)], { type: "text/plain;charset=UTF-8" });
193
+ return navigator.sendBeacon(`${require_setup_index.config.endpoint}/events`, blob);
194
+ }
195
+ /**
196
+ * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
197
+ * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
198
+ * Call it before the engagement beacon: a new session's `session_start` is in this queue.
199
+ *
200
+ * Nothing can be awaited here, so the events go with the tags they have settled on (the last
201
+ * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
202
+ * as an id-less browser event could not be deduplicated against the server's. When no beacon can
203
+ * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay
204
+ * queued for the usual send, which also creates the visitor.
205
+ */
206
+ function sendPendingEvents() {
207
+ if (list.length === 0) return;
208
+ const visitor_id = beaconVisitorId();
209
+ const dto = list.map((event) => ({
210
+ name: event.name,
211
+ properties: event.properties,
212
+ tags: event.settled ?? require_setup_index.cache.tags ?? {},
213
+ visitor_id: visitor_id ?? "",
214
+ session_id: event.session_id,
215
+ platform: require_setup_index.config.platform,
216
+ environment: require_setup_index.config.environment,
217
+ timestamp: event.timestamp
218
+ }));
219
+ if (!visitor_id || !beacon(dto)) {
220
+ flush();
221
+ return;
222
+ }
223
+ if (timer) {
224
+ clearTimeout(timer);
225
+ timer = null;
226
+ }
227
+ list.splice(0).forEach((event) => event.options.onSucceed?.(void 0));
228
+ }
229
+ function sendBeacon(name, properties) {
230
+ const visitor_id = beaconVisitorId();
165
231
  if (!visitor_id) return;
166
- const dto = [{
232
+ const session_id = require_setup_session.getSession().extend();
233
+ if (!session_id) return;
234
+ if (beacon([{
167
235
  name,
168
236
  properties,
169
237
  tags: require_setup_index.cache.tags ?? {},
170
238
  visitor_id,
171
- session_id: require_setup_session.getSession().extend(),
239
+ session_id,
172
240
  platform: require_setup_index.config.platform,
173
241
  environment: require_setup_index.config.environment,
174
242
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
175
- }];
176
- const blob = new Blob([JSON.stringify(dto)], { type: "application/json" });
177
- if (navigator.sendBeacon(`${require_setup_index.config.endpoint}/events`, blob)) return;
243
+ }])) return;
178
244
  console.warn("Failed to send beacon", name, properties);
179
245
  }
180
246
  //#endregion
181
247
  exports.sendBeacon = sendBeacon;
248
+ exports.sendPendingEvents = sendPendingEvents;
182
249
  exports.track = track;
183
250
  exports.trackAsync = trackAsync;
184
251
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","getSession","getVisitor","fetch","IGNORED_EVENTS","keys"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\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 { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The `session_start` a failed batch took down with it, kept for the next batch of the same\n * session. `fetch` has already retried the transient failures by the time a batch fails here;\n * what remains is a batch the server rejected outright — one invalid event fails the whole batch,\n * and `session_start` with it — or a network that stayed down past the retries. Neither is a\n * reason to lose the session's one attribution record, so it goes out again, with the tags and\n * timestamp of the moment the session actually began, under the same session id. Held in memory\n * only: a reload loses it, and with it the session_start — the same as before this existed.\n */\nlet pendingStart: { session_id: string; item: Item } | undefined;\n\nasync function sendEvents(events: Item[]) {\n /** The announcement this batch carries, if any, so the catch below can hold it back. */\n let announcement: { session_id: string; item: Item } | undefined;\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const opening = events[0];\n const { id: session_id, started } = getSession().touch(\n Date.parse(opening.timestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started || pendingStart?.session_id === session_id) {\n // `session_start` is derived from the event that opened the session, as GA4 derives it\n // from the hit that did: when that event happened is when the session began, and the page\n // it was captured on is where. Neither is read now — this batch goes out up to `delay` ms\n // later, a batch held in a frozen tab far later still, and a landing page that redirects\n // inside that window would stamp the session's one attribution record with the URL the utm\n // parameters were already stripped from.\n const start: Item =\n pendingStart?.session_id === session_id\n ? pendingStart.item\n : {\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: opening.tags,\n timestamp: opening.timestamp,\n };\n pendingStart = undefined;\n announcement = { session_id, item: start };\n events.unshift(start);\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\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 (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // The other events are reported lost and stay lost; `session_start` alone is worth carrying\n // over, because it is the session's only attribution record — a session without one has no\n // channel, and its every later event drops out of an attribution join.\n if (announcement) pendingStart = announcement;\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAqBA,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;;;;;;;;;;AAWA,IAAI;AAEJ,eAAe,WAAW,QAAgB;;CAExC,IAAI;CACJ,IAAI;EACF,IAAI,OAAO,WAAW,GAAG;EAMzB,MAAM,UAAU,OAAO;EACvB,MAAM,EAAE,IAAI,YAAY,YAAYC,sBAAAA,WAAW,CAAC,CAAC,MAC/C,KAAK,MAAM,QAAQ,SAAS,GAC5B,KAAK,MAAM,OAAO,OAAO,SAAS,EAAE,CAAC,SAAS,CAChD;EACA,IAAI,WAAW,cAAc,eAAe,YAAY;GAOtD,MAAM,QACJ,cAAc,eAAe,aACzB,aAAa,OACb;IACE,MAAM;IACN,YAAY,CAAC;IACb,SAAS,EAAE,0BAA0B,MAAM;IAC3C,MAAM,QAAQ;IACd,WAAW,QAAQ;GACrB;GACN,eAAe,KAAA;GACf,eAAe;IAAE;IAAY,MAAM;GAAM;GACzC,OAAO,QAAQ,KAAK;EACtB;EAEA,MAAM,eAAe,CAAC,CAAC,aAAa;EAEpC,MAAM,cAAc,MAAMC,sBAAAA,WAAW,EAAA,CAAG;EAExC,MAAM,MAA2B,MAAM,QAAQ,IAC7C,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SAAS,UAAU,IACxD,GAAG;CACb,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","getSession","getVisitor","fetch","IGNORED_EVENTS","keys"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\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 { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(name: Item['name'], properties: Item['properties'], options: TrackOptions): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ name: 'session_start', properties: {}, options }));\n }\n const event = item({ name, properties, options });\n list.push(event);\n return event;\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = (await getVisitor()).id;\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n events.forEach((event, index) => {\n const eventId = data.at(index)?.id;\n event.options.onSucceed?.(eventId ? { id: eventId } : undefined);\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(event.name, event.properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it.\n if (e instanceof Error) console.log(e.message);\n }\n });\n });\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n enqueue(name, properties, options);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when no visitor could be created to send it with, at once, the event left queued for the next\n * send. It never rejects: tracking must not fail the step that awaits it.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send could not take it — no visitor id to send it with yet. It waits for\n // the next send, but the caller, who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\n}\n\n/**\n * The visitor id a beacon can carry. It is persisted, so a returning visitor already has one\n * before `getVisitor` has finished its round trip for this page. Requiring the in-memory copy\n * threw away exactly the events a beacon exists for: everything a visit accrues before its first\n * batch comes back, which for a short visit is the whole of it. A visitor the server has never\n * seen has none: the server would reject its events.\n */\nfunction beaconVisitorId(): string | undefined {\n const stored = config.storage.getItem(keys.visitor_id);\n return cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise), and without the server's ids: their third-party trackers are not fired,\n * as an id-less browser event could not be deduplicated against the server's. When no beacon can\n * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay\n * queued for the usual send, which also creates the visitor.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = beaconVisitorId();\n const dto: CreateTrackEventDTO = list.map((event) => ({\n name: event.name,\n properties: event.properties,\n tags: event.settled ?? cache.tags ?? {},\n visitor_id: visitor_id ?? '',\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }));\n if (!visitor_id || !beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.(undefined));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = beaconVisitorId();\n if (!visitor_id) return;\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAIA,cAAAA,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAyBA,eAAe,cAAkC;CAC/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QAAQ,CAAC;EACtC,YAAY,cAAc;EAC1B,YAAY,MAAM;EAClB,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,WAAW,MAAM;CACnB,EAAE;CACF,IAAI,CAAC,cAAc,CAAC,OAAO,GAAG,GAAG;EAC/B,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,KAAA,CAAS,CAAC;AACxE;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,gBAAgB;CACnC,IAAI,CAAC,YAAY;CAGjB,MAAM,aAAaE,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAgBjB,IAAI,OAAO,CAbT;EACE;EACA;EAGA,MAAMD,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -6,7 +6,24 @@ export interface TrackOptions {
6
6
  onError?: (error: unknown) => void;
7
7
  }
8
8
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
9
+ /**
10
+ * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
11
+ * when no visitor could be created to send it with, at once, the event left queued for the next
12
+ * send. It never rejects: tracking must not fail the step that awaits it.
13
+ */
9
14
  export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
15
+ /**
16
+ * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
17
+ * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
18
+ * Call it before the engagement beacon: a new session's `session_start` is in this queue.
19
+ *
20
+ * Nothing can be awaited here, so the events go with the tags they have settled on (the last
21
+ * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
22
+ * as an id-less browser event could not be deduplicated against the server's. When no beacon can
23
+ * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay
24
+ * queued for the usual send, which also creates the visitor.
25
+ */
26
+ export declare function sendPendingEvents(): void;
10
27
  export declare function sendBeacon<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
11
28
  //#endregion
12
29
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBAyLG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;wBAiBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;wBAOxB,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBA6KG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;wBAgBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBAyDxB;wBAwBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -6,7 +6,24 @@ export interface TrackOptions {
6
6
  onError?: (error: unknown) => void;
7
7
  }
8
8
  export declare function track<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): void;
9
+ /**
10
+ * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
11
+ * when no visitor could be created to send it with, at once, the event left queued for the next
12
+ * send. It never rejects: tracking must not fail the step that awaits it.
13
+ */
9
14
  export declare function trackAsync<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>, options?: TrackOptions): Promise<void>;
15
+ /**
16
+ * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
17
+ * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
18
+ * Call it before the engagement beacon: a new session's `session_start` is in this queue.
19
+ *
20
+ * Nothing can be awaited here, so the events go with the tags they have settled on (the last
21
+ * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
22
+ * as an id-less browser event could not be deduplicated against the server's. When no beacon can
23
+ * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay
24
+ * queued for the usual send, which also creates the visitor.
25
+ */
26
+ export declare function sendPendingEvents(): void;
10
27
  export declare function sendBeacon<T extends EventName = EventName>(name: TrackName<T>, properties?: TrackProperties<T>): void;
11
28
  //#endregion
12
29
  //# sourceMappingURL=index.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBAyLG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;wBAiBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;wBAOxB,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBASiB;EACf;EACA,aAAa,WAAW;EACxB,WAAW;;wBA6KG,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;wBAgBW,WAAW,UAAU,YAAY,WACrD,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS,eAA6B;;;;;;;;;;;;wBAyDxB;wBAwBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -38,145 +38,211 @@ async function captureTags() {
38
38
  }
39
39
  }
40
40
  /**
41
- * The `session_start` a failed batch took down with it, kept for the next batch of the same
42
- * session. `fetch` has already retried the transient failures by the time a batch fails here;
43
- * what remains is a batch the server rejected outright — one invalid event fails the whole batch,
44
- * and `session_start` with it — or a network that stayed down past the retries. Neither is a
45
- * reason to lose the session's one attribution record, so it goes out again, with the tags and
46
- * timestamp of the moment the session actually began, under the same session id. Held in memory
47
- * only: a reload loses it, and with it the session_start — the same as before this existed.
41
+ * The events not yet sent, and the only place they are: a batch leaves it at the moment it is
42
+ * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,
43
+ * everything still unsent is right here for `sendPendingEvents`.
48
44
  */
49
- let pendingStart;
50
- async function sendEvents(events) {
51
- /** The announcement this batch carries, if any, so the catch below can hold it back. */
52
- let announcement;
45
+ const list = [];
46
+ const batchSize = 10;
47
+ const delay = 2e3;
48
+ let timer = null;
49
+ /**
50
+ * Queues an event, preceded by a `session_start` when it is the one that opens a session.
51
+ *
52
+ * The session is decided here, when the event happens, as GA4 and PostHog decide it: the
53
+ * `session_start` then sits in the queue right before the event that opened the session, so
54
+ * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.
55
+ * It carries that event's tags and time, as GA4 derives it from the hit that started the
56
+ * session: the landing page is where the session began, whatever the page has navigated to by
57
+ * the time the batch goes out.
58
+ */
59
+ function enqueue(name, properties, options) {
60
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
61
+ const tags = captureTags();
62
+ const { id: session_id, started } = getSession().touch(Date.parse(timestamp));
63
+ const item = (fields) => {
64
+ const result = {
65
+ ...fields,
66
+ tags,
67
+ timestamp,
68
+ session_id
69
+ };
70
+ tags.then((settled) => result.settled = settled);
71
+ return result;
72
+ };
73
+ if (started) list.push(item({
74
+ name: "session_start",
75
+ properties: {},
76
+ options: { enableThirdPartyTracking: false }
77
+ }));
78
+ const event = item({
79
+ name,
80
+ properties,
81
+ options
82
+ });
83
+ list.push(event);
84
+ return event;
85
+ }
86
+ /**
87
+ * Sends the queue. Everything that has to be awaited is awaited first, and only then are the
88
+ * events taken off the queue and handed to `fetch` in the same synchronous step — so there is
89
+ * no moment at which an event is neither queued nor sent.
90
+ */
91
+ async function flush() {
92
+ if (timer) {
93
+ clearTimeout(timer);
94
+ timer = null;
95
+ }
96
+ if (list.length === 0) return;
97
+ let events = [];
53
98
  try {
54
- if (events.length === 0) return;
55
- const opening = events[0];
56
- const { id: session_id, started } = getSession().touch(Date.parse(opening.timestamp), Date.parse(events[events.length - 1].timestamp));
57
- if (started || pendingStart?.session_id === session_id) {
58
- const start = pendingStart?.session_id === session_id ? pendingStart.item : {
59
- name: "session_start",
60
- properties: {},
61
- options: { enableThirdPartyTracking: false },
62
- tags: opening.tags,
63
- timestamp: opening.timestamp
64
- };
65
- pendingStart = void 0;
66
- announcement = {
67
- session_id,
68
- item: start
69
- };
70
- events.unshift(start);
71
- }
72
99
  await getTokenBucket().removeTokens();
73
100
  const visitor_id = (await getVisitor()).id;
101
+ const headers = await config.getHeaders();
102
+ await Promise.all(list.map((event) => event.tags));
103
+ events = list.splice(0);
104
+ if (events.length === 0) return;
74
105
  const dto = await Promise.all(events.map(async (event) => ({
75
106
  name: event.name,
76
107
  properties: event.properties,
77
108
  tags: await event.tags,
78
109
  visitor_id,
79
- session_id,
110
+ session_id: event.session_id,
80
111
  platform: config.platform,
81
112
  environment: config.environment,
82
113
  timestamp: event.timestamp
83
114
  })));
115
+ const body = JSON.stringify(dto);
84
116
  const response = await fetch(`${config.endpoint}/events`, {
85
117
  method: "POST",
86
118
  credentials: "include",
87
- keepalive: true,
88
- headers: await config.getHeaders(),
89
- body: JSON.stringify(dto)
119
+ keepalive: body.length < 6e4,
120
+ headers,
121
+ body
90
122
  });
91
123
  if (!response.ok) throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);
92
124
  const data = await response.json();
93
- let index = 0;
94
- while (events.length > 0) {
95
- const event = events.shift();
96
- if (!event) {
97
- index++;
98
- continue;
99
- }
100
- const { options, name, properties } = event;
125
+ events.forEach((event, index) => {
101
126
  const eventId = data.at(index)?.id;
102
- options.onSucceed?.(eventId ? { id: eventId } : void 0);
103
- index++;
104
- if (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) continue;
127
+ event.options.onSucceed?.(eventId ? { id: eventId } : void 0);
128
+ if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) return;
105
129
  config.thirdPartyTrackers.forEach((tracker) => {
106
130
  try {
107
- tracker(name, properties, eventId);
131
+ tracker(event.name, event.properties, eventId);
108
132
  } catch (e) {
109
133
  if (e instanceof Error) console.log(e.message);
110
134
  }
111
135
  });
112
- }
136
+ });
113
137
  } catch (e) {
114
138
  if (e instanceof Error) console.log(e.message);
115
- if (announcement) pendingStart = announcement;
116
- events.forEach((event) => event.options.onError?.(e));
117
- }
118
- }
119
- const batch = 10;
120
- const delay = 2e3;
121
- const list = [];
122
- let timer = null;
123
- /**
124
- * Both paths into a send go through here, so a batch that fills up cancels the timer the
125
- * previous push armed rather than leaving it to wake up on its own with nothing to send.
126
- */
127
- function flush() {
128
- if (timer) {
129
- clearTimeout(timer);
130
- timer = null;
139
+ const starts = events.filter((event) => event.name === "session_start");
140
+ list.unshift(...starts);
141
+ events.filter((event) => event.name !== "session_start").forEach((event) => event.options.onError?.(e));
131
142
  }
132
- if (list.length === 0) return;
133
- const copy = [...list];
134
- list.length = 0;
135
- sendEvents(copy);
136
143
  }
137
144
  function track(name, properties, options = defaultOptions) {
138
- list.push({
139
- name,
140
- properties,
141
- options,
142
- tags: captureTags(),
143
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
144
- });
145
- if (list.length >= batch) {
145
+ enqueue(name, properties, options);
146
+ if (list.length >= batchSize) {
146
147
  flush();
147
148
  return;
148
149
  }
149
150
  if (timer) clearTimeout(timer);
150
- timer = setTimeout(flush, delay);
151
+ timer = setTimeout(() => void flush(), delay);
151
152
  }
153
+ /**
154
+ * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,
155
+ * when no visitor could be created to send it with, at once, the event left queued for the next
156
+ * send. It never rejects: tracking must not fail the step that awaits it.
157
+ */
152
158
  async function trackAsync(name, properties, options = defaultOptions) {
153
- await sendEvents([{
154
- name,
155
- properties,
156
- options,
157
- tags: captureTags(),
158
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
159
- }]);
159
+ let settle;
160
+ const settled = new Promise((resolve) => {
161
+ settle = resolve;
162
+ });
163
+ const event = enqueue(name, properties, {
164
+ ...options,
165
+ onSucceed: (response) => {
166
+ options.onSucceed?.(response);
167
+ settle();
168
+ },
169
+ onError: (error) => {
170
+ options.onError?.(error);
171
+ settle();
172
+ }
173
+ });
174
+ await flush();
175
+ if (list.includes(event)) return;
176
+ await settled;
160
177
  }
161
- function sendBeacon(name, properties) {
178
+ /**
179
+ * The visitor id a beacon can carry. It is persisted, so a returning visitor already has one
180
+ * before `getVisitor` has finished its round trip for this page. Requiring the in-memory copy
181
+ * threw away exactly the events a beacon exists for: everything a visit accrues before its first
182
+ * batch comes back, which for a short visit is the whole of it. A visitor the server has never
183
+ * seen has none: the server would reject its events.
184
+ */
185
+ function beaconVisitorId() {
162
186
  const stored = config.storage.getItem(keys.visitor_id);
163
- const visitor_id = cache.visitor?.id ?? (stored && stored !== "undefined" ? stored : void 0);
187
+ return cache.visitor?.id ?? (stored && stored !== "undefined" ? stored : void 0);
188
+ }
189
+ function beacon(dto) {
190
+ if (typeof navigator === "undefined" || !("sendBeacon" in navigator)) return false;
191
+ const blob = new Blob([JSON.stringify(dto)], { type: "text/plain;charset=UTF-8" });
192
+ return navigator.sendBeacon(`${config.endpoint}/events`, blob);
193
+ }
194
+ /**
195
+ * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its
196
+ * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.
197
+ * Call it before the engagement beacon: a new session's `session_start` is in this queue.
198
+ *
199
+ * Nothing can be awaited here, so the events go with the tags they have settled on (the last
200
+ * built ones otherwise), and without the server's ids: their third-party trackers are not fired,
201
+ * as an id-less browser event could not be deduplicated against the server's. When no beacon can
202
+ * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay
203
+ * queued for the usual send, which also creates the visitor.
204
+ */
205
+ function sendPendingEvents() {
206
+ if (list.length === 0) return;
207
+ const visitor_id = beaconVisitorId();
208
+ const dto = list.map((event) => ({
209
+ name: event.name,
210
+ properties: event.properties,
211
+ tags: event.settled ?? cache.tags ?? {},
212
+ visitor_id: visitor_id ?? "",
213
+ session_id: event.session_id,
214
+ platform: config.platform,
215
+ environment: config.environment,
216
+ timestamp: event.timestamp
217
+ }));
218
+ if (!visitor_id || !beacon(dto)) {
219
+ flush();
220
+ return;
221
+ }
222
+ if (timer) {
223
+ clearTimeout(timer);
224
+ timer = null;
225
+ }
226
+ list.splice(0).forEach((event) => event.options.onSucceed?.(void 0));
227
+ }
228
+ function sendBeacon(name, properties) {
229
+ const visitor_id = beaconVisitorId();
164
230
  if (!visitor_id) return;
165
- const dto = [{
231
+ const session_id = getSession().extend();
232
+ if (!session_id) return;
233
+ if (beacon([{
166
234
  name,
167
235
  properties,
168
236
  tags: cache.tags ?? {},
169
237
  visitor_id,
170
- session_id: getSession().extend(),
238
+ session_id,
171
239
  platform: config.platform,
172
240
  environment: config.environment,
173
241
  timestamp: (/* @__PURE__ */ new Date()).toISOString()
174
- }];
175
- const blob = new Blob([JSON.stringify(dto)], { type: "application/json" });
176
- if (navigator.sendBeacon(`${config.endpoint}/events`, blob)) return;
242
+ }])) return;
177
243
  console.warn("Failed to send beacon", name, properties);
178
244
  }
179
245
  //#endregion
180
- export { sendBeacon, track, trackAsync };
246
+ export { sendBeacon, sendPendingEvents, track, trackAsync };
181
247
 
182
248
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\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 { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The `session_start` a failed batch took down with it, kept for the next batch of the same\n * session. `fetch` has already retried the transient failures by the time a batch fails here;\n * what remains is a batch the server rejected outright — one invalid event fails the whole batch,\n * and `session_start` with it — or a network that stayed down past the retries. Neither is a\n * reason to lose the session's one attribution record, so it goes out again, with the tags and\n * timestamp of the moment the session actually began, under the same session id. Held in memory\n * only: a reload loses it, and with it the session_start — the same as before this existed.\n */\nlet pendingStart: { session_id: string; item: Item } | undefined;\n\nasync function sendEvents(events: Item[]) {\n /** The announcement this batch carries, if any, so the catch below can hold it back. */\n let announcement: { session_id: string; item: Item } | undefined;\n try {\n if (events.length === 0) return;\n\n // One read-modify-write of the stored session for the whole batch: it answers which session\n // these events belong to and whether this batch is the one that started it. Timed by the\n // events themselves rather than by this moment — a tab frozen in the background can hold a\n // batch for far longer than `delay`, and those events belong to the session they happened in.\n const opening = events[0];\n const { id: session_id, started } = getSession().touch(\n Date.parse(opening.timestamp),\n Date.parse(events[events.length - 1].timestamp)\n );\n if (started || pendingStart?.session_id === session_id) {\n // `session_start` is derived from the event that opened the session, as GA4 derives it\n // from the hit that did: when that event happened is when the session began, and the page\n // it was captured on is where. Neither is read now — this batch goes out up to `delay` ms\n // later, a batch held in a frozen tab far later still, and a landing page that redirects\n // inside that window would stamp the session's one attribution record with the URL the utm\n // parameters were already stripped from.\n const start: Item =\n pendingStart?.session_id === session_id\n ? pendingStart.item\n : {\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n tags: opening.tags,\n timestamp: opening.timestamp,\n };\n pendingStart = undefined;\n announcement = { session_id, item: start };\n events.unshift(start);\n }\n\n await getTokenBucket().removeTokens();\n\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Survive the page being unloaded mid-flight: a batch waits up to `delay` ms, so closing\n // the tab inside that window would otherwise abort the request and lose every event in it.\n // The body stays far under keepalive's 64KB in-flight budget at 100 events per batch.\n keepalive: true,\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data.at(index)?.id;\n options.onSucceed?.(eventId ? { id: eventId } : undefined);\n index++;\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 (options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(name)) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(name, properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it. This loop is\n // still draining `events` with `shift`, so a throw would escape to the catch below and\n // report failure to whatever is left in the queue — for events the server has already\n // accepted, and after the ones ahead of them were told they succeeded.\n if (e instanceof Error) console.log(e.message);\n }\n });\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // The other events are reported lost and stay lost; `session_start` alone is worth carrying\n // over, because it is the session's only attribution record — a session without one has no\n // channel, and its every later event drops out of an attribution join.\n if (announcement) pendingStart = announcement;\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Both paths into a send go through here, so a batch that fills up cancels the timer the\n * previous push armed rather than leaving it to wake up on its own with nothing to send.\n */\nfunction flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n const copy = [...list];\n list.length = 0;\n void sendEvents(copy);\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({\n name,\n properties,\n options,\n tags: captureTags(),\n timestamp: new Date().toISOString(),\n });\n if (list.length >= batch) {\n flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(flush, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([\n { name, properties, options, tags: captureTags(), timestamp: new Date().toISOString() },\n ]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n // The visitor id is persisted, so a returning visitor already has one before `getVisitor` has\n // finished its round trip for this page. Requiring the in-memory copy threw away exactly the\n // events this function exists for: everything a visit accrues before its first batch comes\n // back, which for a short visit is the whole of it.\n const stored = config.storage.getItem(keys.visitor_id);\n const visitor_id = cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n if (!visitor_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id: getSession().extend(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAqBA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,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;EAAS,MAAM,YAAY;EAAG,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CAAE,CACxF,CAAC;AACH;AAEA,SAAgB,WACd,MACA,YACA;CAKA,MAAM,SAAS,OAAO,QAAQ,QAAQ,KAAK,UAAU;CACrD,MAAM,aAAa,MAAM,SAAS,OAAO,UAAU,WAAW,cAAc,SAAS,KAAA;CACrF,IAAI,CAAC,YAAY;CAEjB,MAAM,MAA2B,CAC/B;EACE;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA,YAAY,WAAW,CAAC,CAAC,OAAO;EAChC,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CACF;CACA,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;CAEzE,IADgB,UAAU,WAAW,GAAG,OAAO,SAAS,UAAU,IACxD,GAAG;CACb,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { keys } from '../constants/storage';\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 { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties, TrackTags } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(name: Item['name'], properties: Item['properties'], options: TrackOptions): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ name: 'session_start', properties: {}, options }));\n }\n const event = item({ name, properties, options });\n list.push(event);\n return event;\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = (await getVisitor()).id;\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => ({\n name: event.name,\n properties: event.properties,\n tags: await event.tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n events.forEach((event, index) => {\n const eventId = data.at(index)?.id;\n event.options.onSucceed?.(eventId ? { id: eventId } : undefined);\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n config.thirdPartyTrackers.forEach((tracker) => {\n try {\n tracker(event.name, event.properties, eventId);\n } catch (e: unknown) {\n // A third-party script does not get to take the rest of the batch with it.\n if (e instanceof Error) console.log(e.message);\n }\n });\n });\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n enqueue(name, properties, options);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Sends the event now, with whatever is queued, and resolves once it has been sent or lost — or,\n * when no visitor could be created to send it with, at once, the event left queued for the next\n * send. It never rejects: tracking must not fail the step that awaits it.\n */\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n let settle!: () => void;\n const settled = new Promise<void>((resolve) => {\n settle = resolve;\n });\n const event = enqueue(name, properties, {\n ...options,\n onSucceed: (response) => {\n options.onSucceed?.(response);\n settle();\n },\n onError: (error) => {\n options.onError?.(error);\n settle();\n },\n });\n await flush();\n // Still queued: this send could not take it — no visitor id to send it with yet. It waits for\n // the next send, but the caller, who may be holding a navigation on this, does not.\n if (list.includes(event)) return;\n await settled;\n}\n\n/**\n * The visitor id a beacon can carry. It is persisted, so a returning visitor already has one\n * before `getVisitor` has finished its round trip for this page. Requiring the in-memory copy\n * threw away exactly the events a beacon exists for: everything a visit accrues before its first\n * batch comes back, which for a short visit is the whole of it. A visitor the server has never\n * seen has none: the server would reject its events.\n */\nfunction beaconVisitorId(): string | undefined {\n const stored = config.storage.getItem(keys.visitor_id);\n return cache.visitor?.id ?? (stored && stored !== 'undefined' ? stored : undefined);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise), and without the server's ids: their third-party trackers are not fired,\n * as an id-less browser event could not be deduplicated against the server's. When no beacon can\n * take them — a visitor the server does not know yet, no `sendBeacon`, a refused body — they stay\n * queued for the usual send, which also creates the visitor.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = beaconVisitorId();\n const dto: CreateTrackEventDTO = list.map((event) => ({\n name: event.name,\n properties: event.properties,\n tags: event.settled ?? cache.tags ?? {},\n visitor_id: visitor_id ?? '',\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }));\n if (!visitor_id || !beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.(undefined));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = beaconVisitorId();\n if (!visitor_id) return;\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AAeA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AAyBA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;AAYlD,SAAS,QAAQ,MAAoB,YAAgC,SAA6B;CAChG,MAAM,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY;CACzC,MAAM,OAAO,YAAY;CACzB,MAAM,EAAE,IAAI,YAAY,YAAY,WAAW,CAAC,CAAC,MAAM,KAAK,MAAM,SAAS,CAAC;CAC5E,MAAM,QAAQ,WAAgE;EAC5E,MAAM,SAAe;GAAE,GAAG;GAAQ;GAAM;GAAW;EAAW;EAC9D,KAAU,MAAM,YAAa,OAAO,UAAU,OAAQ;EACtD,OAAO;CACT;CACA,IAAI,SAEF,KAAK,KAAK,KAAK;EAAE,MAAM;EAAiB,YAAY,CAAC;EAAG,SAAA,EADtC,0BAA0B,MACkB;CAAE,CAAC,CAAC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YAAY,OAAO;CAI7E,MAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,2BAA2B,CAAC;CACjF,OAAO,UAAU,WAAW,GAAG,OAAO,SAAS,UAAU,IAAI;AAC/D;;;;;;;;;;;;AAaA,SAAgB,oBAAoB;CAClC,IAAI,KAAK,WAAW,GAAG;CACvB,MAAM,aAAa,gBAAgB;CACnC,MAAM,MAA2B,KAAK,KAAK,WAAW;EACpD,MAAM,MAAM;EACZ,YAAY,MAAM;EAClB,MAAM,MAAM,WAAW,MAAM,QAAQ,CAAC;EACtC,YAAY,cAAc;EAC1B,YAAY,MAAM;EAClB,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,WAAW,MAAM;CACnB,EAAE;CACF,IAAI,CAAC,cAAc,CAAC,OAAO,GAAG,GAAG;EAC/B,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,KAAA,CAAS,CAAC;AACxE;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,gBAAgB;CACnC,IAAI,CAAC,YAAY;CAGjB,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAgBjB,IAAI,OAAO,CAbT;EACE;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shware/analytics",
3
- "version": "9.0.0",
3
+ "version": "9.0.1",
4
4
  "private": false,
5
5
  "repository": {
6
6
  "type": "git",