@shware/analytics 13.0.3 → 13.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +3 -1
  2. package/dist/link/index.cjs +17 -13
  3. package/dist/link/index.cjs.map +1 -1
  4. package/dist/link/index.d.cts +7 -0
  5. package/dist/link/index.d.cts.map +1 -1
  6. package/dist/link/index.d.mts +7 -0
  7. package/dist/link/index.d.mts.map +1 -1
  8. package/dist/link/index.mjs +17 -13
  9. package/dist/link/index.mjs.map +1 -1
  10. package/dist/native/index.cjs +1 -1
  11. package/dist/native/index.mjs +1 -1
  12. package/dist/react-router/index.cjs +1 -1
  13. package/dist/react-router/index.mjs +1 -1
  14. package/dist/tanstack/analytics.cjs +1 -1
  15. package/dist/tanstack/analytics.mjs +1 -1
  16. package/dist/third-parties/google-analytics.cjs +1 -1
  17. package/dist/third-parties/google-analytics.cjs.map +1 -1
  18. package/dist/third-parties/google-analytics.mjs +1 -1
  19. package/dist/third-parties/google-analytics.mjs.map +1 -1
  20. package/dist/third-parties/meta-pixel.cjs +1 -1
  21. package/dist/third-parties/meta-pixel.mjs +1 -1
  22. package/dist/third-parties/posthog.cjs +7 -2
  23. package/dist/third-parties/posthog.cjs.map +1 -1
  24. package/dist/third-parties/posthog.d.cts +3 -0
  25. package/dist/third-parties/posthog.d.cts.map +1 -1
  26. package/dist/third-parties/posthog.d.mts +3 -0
  27. package/dist/third-parties/posthog.d.mts.map +1 -1
  28. package/dist/third-parties/posthog.mjs +7 -2
  29. package/dist/third-parties/posthog.mjs.map +1 -1
  30. package/dist/track/gtag.cjs.map +1 -1
  31. package/dist/track/gtag.d.cts +2 -2
  32. package/dist/track/gtag.d.mts +2 -2
  33. package/dist/track/gtag.mjs.map +1 -1
  34. package/dist/track/index.cjs +4 -1
  35. package/dist/track/index.cjs.map +1 -1
  36. package/dist/track/index.d.cts +6 -2
  37. package/dist/track/index.d.cts.map +1 -1
  38. package/dist/track/index.d.mts +6 -2
  39. package/dist/track/index.d.mts.map +1 -1
  40. package/dist/track/index.mjs +4 -1
  41. package/dist/track/index.mjs.map +1 -1
  42. package/dist/track/once.cjs +11 -1
  43. package/dist/track/once.cjs.map +1 -1
  44. package/dist/track/once.d.cts +7 -1
  45. package/dist/track/once.d.cts.map +1 -1
  46. package/dist/track/once.d.mts +7 -1
  47. package/dist/track/once.d.mts.map +1 -1
  48. package/dist/track/once.mjs +11 -1
  49. package/dist/track/once.mjs.map +1 -1
  50. package/dist/visitor/id.cjs.map +1 -1
  51. package/dist/visitor/id.mjs.map +1 -1
  52. package/dist/visitor/index.cjs +13 -4
  53. package/dist/visitor/index.cjs.map +1 -1
  54. package/dist/visitor/index.d.cts +6 -1
  55. package/dist/visitor/index.d.cts.map +1 -1
  56. package/dist/visitor/index.d.mts +6 -1
  57. package/dist/visitor/index.d.mts.map +1 -1
  58. package/dist/visitor/index.mjs +13 -4
  59. package/dist/visitor/index.mjs.map +1 -1
  60. package/dist/web/index.cjs +5 -4
  61. package/dist/web/index.cjs.map +1 -1
  62. package/dist/web/index.d.cts.map +1 -1
  63. package/dist/web/index.d.mts.map +1 -1
  64. package/dist/web/index.mjs +5 -4
  65. package/dist/web/index.mjs.map +1 -1
  66. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"gtag.mjs","names":[],"sources":["../../src/track/gtag.ts"],"sourcesContent":["/** reference: https://support.google.com/analytics/answer/13316687 */\nconst reservedWebEventNames = [\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_renew',\n 'click',\n 'error',\n 'file_download',\n 'first_open',\n 'first_visit',\n 'form_start',\n 'form_submit',\n 'in_app_purchase',\n 'page_view',\n 'scroll',\n 'session_start',\n 'user_engagement',\n 'view_complete',\n 'video_progress',\n 'video_start',\n 'view_search_results',\n] as const;\n\nconst reservedAppEventNames = [\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'firebase_campaign',\n 'firebase_in_app_message_action',\n 'firebase_in_app_message_dismiss',\n 'firebase_in_app_message_impression',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'notification_send',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n] as const;\n\nexport const reservedEventNames = [...reservedWebEventNames, ...reservedAppEventNames] as const;\n\ntype ReservedWebEventNames = (typeof reservedWebEventNames)[number];\ntype ReservedAppEventNames = (typeof reservedAppEventNames)[number];\nexport type ReservedEventNames = ReservedWebEventNames | ReservedAppEventNames;\n\nexport type ReservedEventValues =\n | 'cid'\n | 'currency'\n | 'customer_id'\n | 'customerid'\n | 'dclid'\n | 'gclid'\n | 'session_id'\n | 'sessionid'\n | 'sfmc_id'\n | 'sid'\n | 'srsltid'\n | 'uid'\n | 'user_id'\n | 'userid'\n | `_${string}`\n | `firebase_${string}`\n | `ga_${string}`\n | `google_${string}`\n | `gtag.${string}`;\n\nexport type ReservedUserPropertiesNames =\n | 'cid'\n | 'customer_id'\n | 'customerid'\n | 'first_open_after_install'\n | 'first_open_time'\n | 'first_visit_time'\n | 'google_allow_ad_personalization_signals'\n | 'last_advertising_id_reset'\n | 'last_deep_link_referrer'\n | 'last_gclid'\n | 'lifetime_user_engagement'\n | 'non_personalized_ads'\n | 'session_id'\n | 'session_number'\n | 'sessionid'\n | 'sfmc_id'\n | 'sid'\n | 'uid'\n | 'user_id'\n | 'userid'\n | `_${string}`\n | `firebase_${string}`\n | `ga_${string}`\n | `google_${string}`;\n\nexport type UserPropertiesValue = string | boolean | number | null | undefined;\nexport type UserProperties = {\n [key: string]: UserPropertiesValue;\n} & {\n [key in ReservedUserPropertiesNames]?: never;\n};\n\n/**\n * reference: https://support.google.com/analytics/answer/14078702\n * You must turn on user-provided data collection in Google Analytics.\n *\n * Validate your user-provided data implementation: https://support.google.com/analytics/answer/14171683\n *\n * Usage: gtag('set', 'user_data', { email: 'abc@abc.com' })\n *\n * To standardize the hash results, before hashing one of these values, you must:\n *\n * - Remove leading and trailing whitespaces.\n * - Convert the text to lowercase.\n * - Format phone numbers according to the E164 standard.\n * - Remove all periods (.) that precede the domain name in gmail.com and googlemail.com email addresses.\n * */\ntype UserProvidedDataAddress = {\n first_name?: string;\n last_name?: string;\n street?: string;\n city?: string;\n /** User province, state, or region. Example: `Hampshire` */\n region?: string;\n postal_code?: string;\n /**\n * User country code.\n * Example: 'UK'. Use 2-letter country codes, per the ISO 3166-1 alpha-2 standard.\n */\n country?: string;\n};\n\n/**\n * To standardize the hash results, before hashing one of these values, you must:\n *\n * - Remove leading and trailing whitespaces.\n * - Convert the text to lowercase.\n * - Format phone numbers according to the E164 standard.\n * - Remove all periods (.) that precede the domain name in gmail.com and googlemail.com email addresses.\n */\nexport type UserProvidedData = {\n email?: string | string[];\n /**\n * User phone number. Must be in E.164 format, which means it must be 11 to 15 digits including a\n * plus sign (+) prefix and country code with no dashes, parentheses, or spaces.\n *\n * Example: ‘+11231234567’\n */\n phone_number?: string | string[];\n address?: UserProvidedDataAddress | UserProvidedDataAddress[];\n};\n\nexport type GaId = `G-${Uppercase<string>}`;\n\nexport type CampaignMedium =\n | 'email'\n | 'organic'\n | 'cpc'\n | 'banner'\n | 'social'\n | 'referral'\n | 'affiliate'\n | 'video'\n | 'display'\n | 'sms'\n | 'push'\n | 'qr'\n | 'audio'\n | (string & {});\n\nexport type CampaignSource =\n | 'google' // don't need to set\n | 'googleads'\n | 'bing'\n | 'bingads'\n | 'metaads'\n | 'facebook'\n | 'twitter'\n | 'linkedin'\n | 'instagram'\n | 'tiktok'\n | 'youtube'\n | 'newsletter'\n | `website_${string}`\n | `affiliate_${string}`\n | (string & {});\n\nexport type Campaign = {\n id?: string;\n name?: string;\n term?: string;\n content?: string;\n medium?: CampaignMedium;\n source?: CampaignSource;\n};\n\nexport type Config = {\n allow_google_signals?: boolean;\n allow_ad_personalization_signals?: boolean;\n\n campaign_content?: string;\n campaign_id?: string;\n campaign_medium?: CampaignMedium;\n campaign_name?: string;\n campaign_source?: CampaignSource;\n campaign_term?: string;\n\n /**\n * @deprecated\n * Key Point: Use the campaign_ prefixed version of each campaign value instead of this field.\n */\n campaign?: Campaign;\n\n client_id?: string;\n content_group?: string;\n\n cookie_domain?: 'none' | 'auto' | (string & {});\n cookie_expires?: number;\n cookie_flags?: string;\n cookie_path?: string;\n cookie_prefix?: string;\n cookie_update?: boolean;\n\n ignore_referrer?: boolean;\n language?: string;\n\n page_location?: string;\n page_referrer?: string;\n page_title?: string;\n\n send_page_view?: boolean;\n screen_resolution?: `${number}x${number}`;\n user_id?: string;\n user_properties?: UserProperties;\n};\n\nexport type Item = {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n};\n\nexport type PromotionItem = {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n};\n\nexport type SurveyProperties = {\n id?: string;\n feature?: Lowercase<string>;\n trigger?: Lowercase<string>;\n};\n\nexport type SurveyQA = {\n q1: string;\n a1: string;\n q2?: string;\n a2?: string;\n q3?: string;\n a3?: string;\n q4?: string;\n a4?: string;\n q5?: string;\n a5?: string;\n q6?: string;\n a6?: string;\n completed?: boolean;\n};\n\nexport type NPSScore = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | (number & {});\nexport type CASTScore = 1 | 2 | 3 | 4 | 5 | (number & {});\nexport type CESScore = 1 | 2 | 3 | 4 | 5 | (number & {});\n\n/** ref: https://support.google.com/analytics/answer/9216061 */\nexport type EnhancedMeasurementEvents = {\n page_view: {\n page_path: string;\n page_title: string;\n page_referrer?: string;\n page_location?: string;\n previous_page_path?: string;\n engagement_time_msec?: number;\n };\n // Scrolls: the first time a user reaches the bottom of each page\n // (i.e., when a 90% vertical depth becomes visible)\n scroll: {\n engagement_time_msec: number;\n };\n // Outbound clicks\n click: {\n link_id: string;\n link_url: string;\n link_text: string; // added\n link_domain: string;\n link_classes: string;\n outbound: boolean;\n };\n // Site search\n view_search_results: {\n search_term: string;\n };\n // Video engagement\n video_start: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n video_progress: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n video_complete: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n // File downloads:\n file_download: {\n file_extension: string;\n file_name: string;\n link_classes: string;\n link_id: string;\n link_text: string;\n link_url: string;\n };\n // Form interactions\n form_start: {\n form_id: string;\n form_name: string;\n form_destination: string;\n };\n form_submit: {\n form_id: string;\n form_name: string;\n form_destination: string;\n form_submit_text: string;\n };\n};\n\n/** ref: https://support.google.com/analytics/answer/9234069 */\nexport type AutomaticallyCollectedEvents = EnhancedMeasurementEvents & {\n first_visit: {\n page_path: string;\n page_title: string;\n page_referrer?: string;\n page_location?: string;\n };\n first_open: {\n screen_name: string;\n screen_class: string;\n };\n in_app_purchase: {\n product_id: string;\n price: number;\n value: number;\n currency: string;\n quantity: number;\n subscription?: boolean;\n free_trial?: boolean;\n introductory_price?: number;\n };\n notification_dismiss: {\n // Android only\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_foreground: {\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_type: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_open: {\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_receive: {\n // Android only\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_type: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n // Note: The 'screen_view' event is automatically sent only when using Android or iOS native SDKs.\n // If you are using React Native, you need to send this event manually; it should not be ignored.\n session_start: undefined;\n user_engagement: {\n engagement_time_msec: number;\n trigger: 'pagehide' | 'visibilitychange' | 'background';\n };\n};\n\n/**\n * ref: https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag\n * ref: https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event\n * */\nexport type RecommendedEvents = {\n // Google Analytics 4 Recommended Events\n add_payment_info: {\n currency: string;\n value: number;\n coupon?: string;\n payment_type?: string;\n items: Item[];\n };\n add_shipping_info: {\n currency: string;\n value: number;\n coupon?: string;\n shipping_tier?: string;\n items: Item[];\n };\n add_to_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n add_to_wishlist: {\n currency: string;\n value: number;\n items: Item[];\n };\n begin_checkout: {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n source?: string; // added\n };\n close_convert_lead: {\n currency: string;\n value: number;\n };\n close_unconvert_lead: {\n currency: string;\n value: number;\n unconvert_lead_reason?: string;\n };\n disqualify_lead: {\n currency: string;\n value: number;\n disqualified_lead_reason?: string;\n };\n earn_virtual_currency: {\n virtual_currency_name?: string;\n value?: number;\n };\n generate_lead: {\n currency: string;\n value: number;\n lead_source?: string;\n };\n join_group: {\n group_id?: string;\n };\n level_end: {\n level_name?: string;\n success?: boolean;\n };\n level_start: {\n level_name?: string;\n };\n level_up: {\n level?: number;\n level_name?: string;\n character?: string;\n };\n login: {\n method?:\n | 'google'\n | 'apple'\n | 'facebook'\n | 'twitter'\n | 'linkedin'\n | 'github'\n | 'microsoft'\n | 'wechat'\n | 'onetap'\n | 'phone'\n | 'email'\n | (string & {});\n source?: string; // added\n };\n post_score: {\n score: number;\n level?: number;\n character?: string;\n };\n purchase: {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number; // Shipping cost associated with a transaction.\n tax?: number;\n items?: Item[];\n source?: string; // added\n };\n qualify_lead: {\n currency: string;\n value: number;\n };\n refund: {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n };\n remove_from_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n search: {\n search_term: string;\n };\n select_content: {\n content_type?: string;\n content_id?: string;\n };\n select_item: {\n item_list_id?: string;\n item_list_name?: string;\n items: Item[];\n };\n select_promotion: {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n items?: (Item & PromotionItem)[];\n };\n share: {\n method?: string;\n content_type?: string;\n item_id?: string;\n system_activity_type?: string; // added\n platform_post_id?: string; // added\n };\n sign_up: {\n method?: string;\n source?: string; // added\n };\n spend_virtual_currency: {\n value: number;\n virtual_currency_name: string;\n item_name?: string;\n };\n tutorial_begin: undefined;\n tutorial_complete: undefined;\n unlock_achievement: {\n achievement_id: string;\n };\n view_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n view_item: {\n currency: string;\n value: number;\n items: Item[];\n };\n view_item_list: {\n currency: string;\n item_list_id?: string;\n item_list_name?: string;\n items: Item[];\n };\n view_promotion: {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n items: (Item & PromotionItem)[];\n };\n working_lead: {\n currency: string;\n value: number;\n lead_status?: string;\n };\n\n // Firebase Analytics events, event_name 40 characters limit, 25 parameters limit\n ad_impression: {\n value?: number;\n currency?: string;\n ad_format?: string;\n ad_platform?: string;\n ad_source?: string;\n ad_unit_name?: string;\n };\n app_open: undefined;\n campaign_details: {\n source: string;\n medium: string;\n campaign: string;\n term?: string;\n content?: string;\n aclid?: string;\n cp1?: string;\n };\n screen_view: {\n screen_name?: string;\n screen_class?: string;\n previous_screen_class?: string; // added\n engagement_time_msec?: number;\n };\n};\n\n/**\n * Extra commonly used events that are NOT part of the GA standard event set.\n * Added to satisfy additional analytics needs.\n */\nexport type AddedRecommendedEvents = {\n logout: undefined;\n trial_begin: {\n currency: string;\n value: number;\n source?: string; // added\n items?: Item[]; // added, the plan(s) enrolled (first item's id maps to OpenAI plan_id)\n };\n subscribe: {\n currency: string;\n value: number;\n source?: string; // added\n items?: Item[]; // added, the plan(s) enrolled (first item's id maps to OpenAI plan_id)\n };\n // survey\n survey_shown: SurveyProperties;\n survey_sent: SurveyProperties & SurveyQA;\n survey_dismissed: SurveyProperties;\n /**\n * Net promoter score: Get an industry-recognized benchmark\n * How likely are you to recommend us to a friend?\n * */\n nps_shown: SurveyProperties;\n nps_sent: SurveyProperties & { score: NPSScore; feedback?: string };\n nps_dismissed: SurveyProperties;\n /**\n * Customer satisfaction score: Works best after a checkout or support flow\n * How satisfied are you with xxx?\n * */\n cast_shown: SurveyProperties;\n cast_sent: SurveyProperties & { score: CASTScore; feedback?: string };\n cast_dismissed: SurveyProperties;\n /**\n * Customer effort score: Works well with churn surveys\n * How easy is it to use the feature?\n * */\n ces_shown: SurveyProperties;\n ces_sent: SurveyProperties & { score: CESScore; feedback?: string };\n ces_dismissed: SurveyProperties;\n};\n\nexport type StandardEvents = AutomaticallyCollectedEvents &\n RecommendedEvents &\n AddedRecommendedEvents;\n\n/**\n * reference: https://developers.google.com/analytics/devguides/collection/ga4/reference/config\n * reference: https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag\n */\nexport interface Gtag {\n /**\n * To disable advertising features based on third-party advertising identifiers, set\n * allow_google_signals to false.\n *\n * @param event\n * @param option\n * @param allow - Whether to allow Google signals.\n * @default true\n */\n gtag(event: 'set', option: 'allow_google_signals', allow: boolean): void;\n\n /**\n * Set to false to disable advertising personalization features.\n *\n * @param event\n * @param option\n * @param allow - Whether to allow ad personalization signals.\n * @default true\n */\n gtag(event: 'set', option: 'allow_ad_personalization_signals', allow: boolean): void;\n\n /**\n * Used for A/B testing and content-targeted ads. Use campaign_content to differentiate ads or\n * links that point to the same URL.\n */\n gtag(event: 'set', option: 'campaign_content', content: string): void;\n\n /**\n * Used to identify which campaign this referral references. Use campaign_id to identify a\n * specific campaign.\n */\n gtag(event: 'set', option: 'campaign_id', id: string): void;\n\n /** Use campaign_medium to identify a medium such as email or cost-per-click. */\n gtag(event: 'set', option: 'campaign_medium', medium: CampaignMedium): void;\n\n /**\n * Used for keyword analysis. Use campaign_name to identify a specific product promotion or\n * strategic campaign.\n */\n gtag(event: 'set', option: 'campaign_name', name: string): void;\n\n /** Use campaign_source to identify a search engine, newsletter name, or other source. */\n gtag(event: 'set', option: 'campaign_source', source: CampaignSource): void;\n\n /** Used for paid search. Use campaign_term to note the keywords for this ad. */\n gtag(event: 'set', option: 'campaign_term', term: string): void;\n\n /**\n * @deprecated\n * Key Point: Use the campaign_ prefixed version of each campaign value instead of this field.\n */\n gtag(event: 'set', option: 'campaign', params: Campaign): void;\n\n /**\n * Pseudonymously identifies a browser instance. By default, this value is stored as part of the\n * first-party Analytics cookie with a two-year expiration.\n */\n gtag(event: 'set', option: 'client_id', id: string): void;\n\n /** example: gtag('set', 'content_group', '/news/sports'); */\n gtag(event: 'set', option: 'content_group', group: string): void;\n\n /**\n * Specifies the domain used to store the analytics cookie.\n * Set to 'none' to set the cookie without specifying a domain.\n * Set to 'auto' (the default value) to set the cookie to the top level domain plus one\n * subdomain (eTLD +1). For example, if cookie_domain is set to 'auto' https://example.com would\n * use example.com for the domain, and https://subdomain.example.com would also use example.com\n * for the domain.\n *\n * @param event\n * @param option\n * @param domain - The domain used to store the analytics cookie.\n * @default 'auto'\n */\n gtag(event: 'set', option: 'cookie_domain', domain: 'none' | 'auto' | (string & {})): void;\n\n /**\n * Every time a hit is sent to Google Analytics, the cookie expiration time is updated to be the\n * current time plus the value of the cookie_expires field. This means that if you use the default\n * value time of two years (63,072,000 seconds), and a user visits your site every month, their\n * cookie will never expire.\n *\n * If you set the cookie_expires time to 0 (zero) seconds, the cookie turns into a session-based\n * cookie and expires once the current browser session ends.\n *\n * Caution: If you set the cookie to expire too quickly, you will inflate your user count and\n * decrease the quality of your measurement.\n *\n * @param event\n * @param option\n * @param expires - The number of seconds until the cookie expires.\n * @default 63072000\n */\n gtag(event: 'set', option: 'cookie_expires', expires: number): void;\n\n /**\n * Appends additional flags to the cookie when set. Flags must be separated by semicolons. See\n * [write a new cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#write_a_new_cookie) for some examples of flags to set.\n */\n gtag(event: 'set', option: 'cookie_flags', flags: string): void;\n\n /** Specifies the subpath used to store the analytics cookie. */\n gtag(event: 'set', option: 'cookie_path', path: string): void;\n\n /** Specifies a prefix to prepend to analytics cookie names. */\n gtag(event: 'set', option: 'cookie_prefix', prefix: string): void;\n\n /**\n * When cookie_update is set to true, gtag.js will update cookies on each page load. This will\n * update the cookie expiration to be set relative to the most recent visit to the site. For\n * example, if cookie expiration is set to one week, and a user visits using the same browser\n * every five days, the cookie expiration will be updated on each visit and will effectively\n * never expire.\n *\n * When set to false, cookies are not updated on each page load. This has the effect of cookie\n * expiration being relative to the first time a user visited the site.\n *\n * @param event\n * @param option\n * @param update - Whether to update the cookie on each page load.\n * @default true\n */\n gtag(event: 'set', option: 'cookie_update', update: boolean): void;\n\n /**\n * Set to true to indicate to Analytics that the referrer shouldn't be displayed as a traffic\n * source. [Learn when to use this field](https://support.google.com/analytics/answer/10327750#set-parameter)\n *\n * @param event\n * @param option\n * @param ignore - Whether to ignore the referrer.\n * @default false\n */\n gtag(event: 'set', option: 'ignore_referrer', ignore: boolean): void;\n\n /**\n * Specifies the language preference of the user. Defaults to the user's `navigator.language` value.\n *\n * @param event\n * @param option\n * @param language - The language preference of the user.\n * @default navigator.language\n */\n gtag(event: 'set', option: 'language', language: string): void;\n\n /**\n * Specifies the full URL of the page. Defaults to the user's `document.location` value.\n *\n * @param event\n * @param option\n * @param location - The full URL of the page. Character limit 1000\n * @default document.location\n */\n gtag(event: 'set', option: 'page_location', location: string): void;\n\n /**\n * Specifies which referral source brought traffic to a page. This value is also used to compute\n * the traffic source. The format of this value is a URL. Defaults to the user's `document.referrer`\n * value.\n *\n * @param event\n * @param option\n * @param referrer - The referral source. Character limit 420\n * @default document.referrer\n */\n gtag(event: 'set', option: 'page_referrer', referrer: string): void;\n\n /**\n * The title of the page or document. Defaults to the user's `document.title` value.\n *\n * @param event\n * @param option\n * @param title - The title of the page or document. Character limit 300\n * @default document.title\n */\n gtag(event: 'set', option: 'page_title', title: string): void;\n\n /**\n * Set to false to prevent the default snippet from sending a page_view.\n *\n * @param event\n * @param option\n * @param send - Whether to send a page_view.\n * @default true\n */\n gtag(event: 'set', option: 'send_page_view', send: boolean): void;\n\n /**\n * Specifies the resolution of the screen. Should be two positive integers separated by an x. For\n * example, for an 800px by 600px screen, the value would be 800x600. Calculated from the user's\n * window.screen value.\n *\n * @param event\n * @param option\n * @param resolution - The resolution of the screen.\n * @default window.screen\n */\n gtag(event: 'set', option: 'screen_resolution', resolution: `${number}x${number}`): void;\n\n /**\n * Specifies a known identifier for a user provided by the site owner/library user. It must not\n * itself be PII (personally identifiable information). The value should never be persisted in\n * Google Analytics cookies or other Analytics-provided storage.\n *\n * @param event\n * @param option\n * @param userId - The user ID. Character limit 256\n */\n gtag(event: 'set', option: 'user_id', userId: string): void;\n\n /**\n * User properties are attributes that can be used to describe segments of your user base, such\n * as language preference or geographic location. Up to 25 additional user properties can be set\n * per project.\n *\n * @param event\n * @param option\n * @param properties\n */\n gtag(event: 'set', option: 'user_properties', properties: UserProperties): void;\n\n gtag(event: 'set', option: 'user_data', data: UserProvidedData): void;\n\n /**\n * gtag('config', ...) Set for a single stream\n * gtag('set', ...) Set globally\n */\n gtag(event: 'config', gaId: GaId, config?: Config): void;\n\n gtag<T extends string>(\n event: 'event',\n eventName: T extends keyof StandardEvents ? T : string,\n eventParams?: T extends keyof StandardEvents\n ? StandardEvents[T]\n : Record<string, string | number | boolean | null | undefined>\n ): void;\n}\n"],"mappings":";;AACA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,qBAAqB,CAAC,GAAG,uBAAuB,GAAG,qBAAqB"}
1
+ {"version":3,"file":"gtag.mjs","names":[],"sources":["../../src/track/gtag.ts"],"sourcesContent":["/** reference: https://support.google.com/analytics/answer/13316687 */\nconst reservedWebEventNames = [\n 'app_remove',\n 'app_store_refund',\n 'app_store_subscription_cancel',\n 'app_store_subscription_renew',\n 'click',\n 'error',\n 'file_download',\n 'first_open',\n 'first_visit',\n 'form_start',\n 'form_submit',\n 'in_app_purchase',\n 'page_view',\n 'scroll',\n 'session_start',\n 'user_engagement',\n 'view_complete',\n 'video_progress',\n 'video_start',\n 'view_search_results',\n] as const;\n\nconst reservedAppEventNames = [\n 'ad_activeview',\n 'ad_click',\n 'ad_exposure',\n 'ad_impression',\n 'ad_query',\n 'ad_reward',\n 'adunit_exposure',\n 'app_clear_data',\n 'app_exception',\n 'app_install',\n 'app_remove',\n 'app_store_refund',\n 'app_update',\n 'app_upgrade',\n 'dynamic_link_app_open',\n 'dynamic_link_app_update',\n 'dynamic_link_first_open',\n 'error',\n 'firebase_campaign',\n 'firebase_in_app_message_action',\n 'firebase_in_app_message_dismiss',\n 'firebase_in_app_message_impression',\n 'first_open',\n 'first_visit',\n 'in_app_purchase',\n 'notification_dismiss',\n 'notification_foreground',\n 'notification_open',\n 'notification_receive',\n 'notification_send',\n 'os_update',\n 'screen_view',\n 'session_start',\n 'user_engagement',\n] as const;\n\nexport const reservedEventNames = [...reservedWebEventNames, ...reservedAppEventNames] as const;\n\ntype ReservedWebEventNames = (typeof reservedWebEventNames)[number];\ntype ReservedAppEventNames = (typeof reservedAppEventNames)[number];\nexport type ReservedEventNames = ReservedWebEventNames | ReservedAppEventNames;\n\nexport type ReservedEventValues =\n | 'cid'\n | 'currency'\n | 'customer_id'\n | 'customerid'\n | 'dclid'\n | 'gclid'\n | 'session_id'\n | 'sessionid'\n | 'sfmc_id'\n | 'sid'\n | 'srsltid'\n | 'uid'\n | 'user_id'\n | 'userid'\n | `_${string}`\n | `firebase_${string}`\n | `ga_${string}`\n | `google_${string}`\n | `gtag.${string}`;\n\nexport type ReservedUserPropertiesNames =\n | 'cid'\n | 'customer_id'\n | 'customerid'\n | 'first_open_after_install'\n | 'first_open_time'\n | 'first_visit_time'\n | 'google_allow_ad_personalization_signals'\n | 'last_advertising_id_reset'\n | 'last_deep_link_referrer'\n | 'last_gclid'\n | 'lifetime_user_engagement'\n | 'non_personalized_ads'\n | 'session_id'\n | 'session_number'\n | 'sessionid'\n | 'sfmc_id'\n | 'sid'\n | 'uid'\n | 'user_id'\n | 'userid'\n | `_${string}`\n | `firebase_${string}`\n | `ga_${string}`\n | `google_${string}`;\n\nexport type UserPropertiesValue = string | boolean | number | null | undefined;\nexport type UserProperties = {\n [key: string]: UserPropertiesValue;\n} & {\n [key in ReservedUserPropertiesNames]?: never;\n};\n\n/**\n * reference: https://support.google.com/analytics/answer/14078702\n * You must turn on user-provided data collection in Google Analytics.\n *\n * Validate your user-provided data implementation: https://support.google.com/analytics/answer/14171683\n *\n * Usage: gtag('set', 'user_data', { email: 'abc@abc.com' })\n *\n * To standardize the hash results, before hashing one of these values, you must:\n *\n * - Remove leading and trailing whitespaces.\n * - Convert the text to lowercase.\n * - Format phone numbers according to the E164 standard.\n * - Remove all periods (.) that precede the domain name in gmail.com and googlemail.com email addresses.\n * */\ntype UserProvidedDataAddress = {\n first_name?: string;\n last_name?: string;\n street?: string;\n city?: string;\n /** User province, state, or region. Example: `Hampshire` */\n region?: string;\n postal_code?: string;\n /**\n * User country code.\n * Example: 'UK'. Use 2-letter country codes, per the ISO 3166-1 alpha-2 standard.\n */\n country?: string;\n};\n\n/**\n * To standardize the hash results, before hashing one of these values, you must:\n *\n * - Remove leading and trailing whitespaces.\n * - Convert the text to lowercase.\n * - Format phone numbers according to the E164 standard.\n * - Remove all periods (.) that precede the domain name in gmail.com and googlemail.com email addresses.\n */\nexport type UserProvidedData = {\n email?: string | string[];\n /**\n * User phone number. Must be in E.164 format, which means it must be 11 to 15 digits including a\n * plus sign (+) prefix and country code with no dashes, parentheses, or spaces.\n *\n * Example: ‘+11231234567’\n */\n phone_number?: string | string[];\n address?: UserProvidedDataAddress | UserProvidedDataAddress[];\n};\n\nexport type GaId = `G-${Uppercase<string>}`;\n\nexport type CampaignMedium =\n | 'email'\n | 'organic'\n | 'cpc'\n | 'banner'\n | 'social'\n | 'referral'\n | 'affiliate'\n | 'video'\n | 'display'\n | 'sms'\n | 'push'\n | 'qr'\n | 'audio'\n | (string & {});\n\nexport type CampaignSource =\n | 'google' // don't need to set\n | 'googleads'\n | 'bing'\n | 'bingads'\n | 'metaads'\n | 'facebook'\n | 'twitter'\n | 'linkedin'\n | 'instagram'\n | 'tiktok'\n | 'youtube'\n | 'newsletter'\n | `website_${string}`\n | `affiliate_${string}`\n | (string & {});\n\nexport type Campaign = {\n id?: string;\n name?: string;\n term?: string;\n content?: string;\n medium?: CampaignMedium;\n source?: CampaignSource;\n};\n\nexport type Config = {\n allow_google_signals?: boolean;\n allow_ad_personalization_signals?: boolean;\n\n campaign_content?: string;\n campaign_id?: string;\n campaign_medium?: CampaignMedium;\n campaign_name?: string;\n campaign_source?: CampaignSource;\n campaign_term?: string;\n\n /**\n * @deprecated\n * Key Point: Use the campaign_ prefixed version of each campaign value instead of this field.\n */\n campaign?: Campaign;\n\n client_id?: string;\n content_group?: string;\n\n cookie_domain?: 'none' | 'auto' | (string & {});\n cookie_expires?: number;\n cookie_flags?: string;\n cookie_path?: string;\n cookie_prefix?: string;\n cookie_update?: boolean;\n\n ignore_referrer?: boolean;\n language?: string;\n\n page_location?: string;\n page_referrer?: string;\n page_title?: string;\n\n send_page_view?: boolean;\n screen_resolution?: `${number}x${number}`;\n user_id?: string;\n user_properties?: UserProperties;\n};\n\nexport type Item = {\n item_id: string;\n item_name: string;\n affiliation?: 'Google Store' | (string & {});\n coupon?: string;\n discount?: number;\n index?: number;\n item_brand?: string;\n item_category?: string;\n item_category2?: string;\n item_category3?: string;\n item_category4?: string;\n item_category5?: string;\n item_list_id?: string;\n item_list_name?: string;\n item_variant?: string;\n location_id?: string;\n price?: number;\n quantity?: number;\n};\n\nexport type PromotionItem = {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n};\n\nexport type SurveyProperties = {\n id?: string;\n feature?: Lowercase<string>;\n trigger?: Lowercase<string>;\n};\n\nexport type SurveyQA = {\n q1: string;\n a1: string;\n q2?: string;\n a2?: string;\n q3?: string;\n a3?: string;\n q4?: string;\n a4?: string;\n q5?: string;\n a5?: string;\n q6?: string;\n a6?: string;\n completed?: boolean;\n};\n\nexport type NPSScore = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | (number & {});\nexport type CASTScore = 1 | 2 | 3 | 4 | 5 | (number & {});\nexport type CESScore = 1 | 2 | 3 | 4 | 5 | (number & {});\n\n/** ref: https://support.google.com/analytics/answer/9216061 */\nexport type EnhancedMeasurementEvents = {\n page_view: {\n page_path: string;\n page_title: string;\n page_referrer?: string;\n page_location?: string;\n previous_page_path?: string;\n engagement_time_msec?: number;\n };\n // Scrolls: the first time a user reaches the bottom of each page\n // (i.e., when a 90% vertical depth becomes visible)\n scroll: {\n engagement_time_msec: number;\n };\n // Outbound clicks\n click: {\n link_id: string;\n link_url: string;\n link_text: string; // added\n link_domain: string;\n link_classes: string;\n outbound: boolean;\n };\n // Site search\n view_search_results: {\n search_term: string;\n };\n // Video engagement\n video_start: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n video_progress: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n video_complete: {\n video_current_time: number;\n video_duration: number;\n video_percent: number;\n video_provider: 'youtube' | 'vimeo' | 'html5' | (string & {});\n video_title: string;\n video_url: string;\n visible: boolean;\n };\n // File downloads:\n file_download: {\n file_extension: string;\n file_name: string;\n link_classes: string;\n link_id: string;\n link_text: string;\n link_url: string;\n };\n // Form interactions\n form_start: {\n form_id: string;\n form_name: string;\n form_destination: string;\n };\n form_submit: {\n form_id: string;\n form_name: string;\n form_destination: string;\n form_submit_text: string;\n };\n};\n\n/** ref: https://support.google.com/analytics/answer/9234069 */\nexport type AutomaticallyCollectedEvents = EnhancedMeasurementEvents & {\n first_visit: {\n page_path: string;\n page_title: string;\n page_referrer?: string;\n page_location?: string;\n };\n first_open: {\n screen_name: string;\n screen_class: string;\n };\n in_app_purchase: {\n product_id: string;\n price: number;\n value: number;\n currency: string;\n quantity: number;\n subscription?: boolean;\n free_trial?: boolean;\n introductory_price?: number;\n };\n notification_dismiss: {\n // Android only\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_foreground: {\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_type: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_open: {\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n notification_receive: {\n // Android only\n topic: string;\n label: string;\n message_id: string;\n message_name: string;\n message_type: string;\n message_time: number;\n message_device_time: number;\n message_channel: string;\n };\n // Note: The 'screen_view' event is automatically sent only when using Android or iOS native SDKs.\n // If you are using React Native, you need to send this event manually; it should not be ignored.\n session_start: undefined;\n user_engagement: {\n engagement_time_msec: number;\n trigger: 'pagehide' | 'visibilitychange' | 'background';\n };\n};\n\n/**\n * ref: https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag\n * ref: https://firebase.google.com/docs/reference/android/com/google/firebase/analytics/FirebaseAnalytics.Event\n * */\nexport type RecommendedEvents = {\n // Google Analytics 4 Recommended Events\n add_payment_info: {\n currency: string;\n value: number;\n coupon?: string;\n payment_type?: string;\n items: Item[];\n };\n add_shipping_info: {\n currency: string;\n value: number;\n coupon?: string;\n shipping_tier?: string;\n items: Item[];\n };\n add_to_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n add_to_wishlist: {\n currency: string;\n value: number;\n items: Item[];\n };\n begin_checkout: {\n currency: string;\n value: number;\n coupon?: string;\n items: Item[];\n source?: string; // added\n };\n close_convert_lead: {\n currency: string;\n value: number;\n };\n close_unconvert_lead: {\n currency: string;\n value: number;\n unconvert_lead_reason?: string;\n };\n disqualify_lead: {\n currency: string;\n value: number;\n disqualified_lead_reason?: string;\n };\n earn_virtual_currency: {\n virtual_currency_name?: string;\n value?: number;\n };\n generate_lead: {\n currency: string;\n value: number;\n lead_source?: string;\n };\n join_group: {\n group_id?: string;\n };\n level_end: {\n level_name?: string;\n success?: boolean;\n };\n level_start: {\n level_name?: string;\n };\n level_up: {\n level?: number;\n level_name?: string;\n character?: string;\n };\n login: {\n method?:\n | 'google'\n | 'apple'\n | 'facebook'\n | 'twitter'\n | 'linkedin'\n | 'github'\n | 'microsoft'\n | 'wechat'\n | 'onetap'\n | 'phone'\n | 'email'\n | (string & {});\n source?: string; // added\n };\n post_score: {\n score: number;\n level?: number;\n character?: string;\n };\n purchase: {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number; // Shipping cost associated with a transaction.\n tax?: number;\n items?: Item[];\n source?: string; // added\n };\n qualify_lead: {\n currency: string;\n value: number;\n };\n refund: {\n currency: string;\n value: number;\n transaction_id: string;\n coupon?: string;\n shipping?: number;\n tax?: number;\n items?: Item[];\n };\n remove_from_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n search: {\n search_term: string;\n };\n select_content: {\n content_type?: string;\n content_id?: string;\n };\n select_item: {\n item_list_id?: string;\n item_list_name?: string;\n items: Item[];\n };\n select_promotion: {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n items?: (Item & PromotionItem)[];\n };\n share: {\n method?: string;\n content_type?: string;\n item_id?: string;\n system_activity_type?: string; // added\n platform_post_id?: string; // added\n };\n sign_up: {\n method?: string;\n source?: string; // added\n };\n spend_virtual_currency: {\n value: number;\n virtual_currency_name: string;\n item_name?: string;\n };\n tutorial_begin: undefined;\n tutorial_complete: undefined;\n unlock_achievement: {\n achievement_id: string;\n };\n view_cart: {\n currency: string;\n value: number;\n items: Item[];\n };\n view_item: {\n currency: string;\n value: number;\n items: Item[];\n };\n view_item_list: {\n currency: string;\n item_list_id?: string;\n item_list_name?: string;\n items: Item[];\n };\n view_promotion: {\n creative_name?: string;\n creative_slot?: string;\n promotion_id?: string;\n promotion_name?: string;\n items: (Item & PromotionItem)[];\n };\n working_lead: {\n currency: string;\n value: number;\n lead_status?: string;\n };\n\n // Firebase Analytics events, event_name 40 characters limit, 25 parameters limit\n ad_impression: {\n value?: number;\n currency?: string;\n ad_format?: string;\n ad_platform?: string;\n ad_source?: string;\n ad_unit_name?: string;\n };\n app_open: undefined;\n campaign_details: {\n source: string;\n medium: string;\n campaign: string;\n term?: string;\n content?: string;\n aclid?: string;\n cp1?: string;\n };\n screen_view: {\n screen_name?: string;\n screen_class?: string;\n previous_screen_class?: string; // added\n engagement_time_msec?: number;\n };\n};\n\n/**\n * Extra commonly used events that are NOT part of the GA standard event set.\n * Added to satisfy additional analytics needs.\n */\nexport type AddedRecommendedEvents = {\n logout: undefined;\n trial_begin: {\n currency: string;\n value: number;\n source?: string; // added\n items?: Item[]; // added, the plan(s) enrolled (first item's id maps to OpenAI plan_id)\n };\n subscribe: {\n currency: string;\n value: number;\n source?: string; // added\n items?: Item[]; // added, the plan(s) enrolled (first item's id maps to OpenAI plan_id)\n };\n // survey\n survey_shown: SurveyProperties;\n survey_sent: SurveyProperties & SurveyQA;\n survey_dismissed: SurveyProperties;\n /**\n * Net promoter score: Get an industry-recognized benchmark\n * How likely are you to recommend us to a friend?\n * */\n nps_shown: SurveyProperties;\n nps_sent: SurveyProperties & { score: NPSScore; feedback?: string };\n nps_dismissed: SurveyProperties;\n /**\n * Customer satisfaction score: Works best after a checkout or support flow\n * How satisfied are you with xxx?\n * */\n cast_shown: SurveyProperties;\n cast_sent: SurveyProperties & { score: CASTScore; feedback?: string };\n cast_dismissed: SurveyProperties;\n /**\n * Customer effort score: Works well with churn surveys\n * How easy is it to use the feature?\n * */\n ces_shown: SurveyProperties;\n ces_sent: SurveyProperties & { score: CESScore; feedback?: string };\n ces_dismissed: SurveyProperties;\n};\n\nexport type StandardEvents = AutomaticallyCollectedEvents &\n RecommendedEvents &\n AddedRecommendedEvents;\n\n/**\n * reference: https://developers.google.com/analytics/devguides/collection/ga4/reference/config\n * reference: https://developers.google.com/analytics/devguides/collection/ga4/reference/events?client_type=gtag\n */\nexport interface Gtag {\n /**\n * To disable advertising features based on third-party advertising identifiers, set\n * allow_google_signals to false.\n *\n * @param event\n * @param option\n * @param allow - Whether to allow Google signals.\n * @default true\n */\n gtag(event: 'set', option: 'allow_google_signals', allow: boolean): void;\n\n /**\n * Set to false to disable advertising personalization features.\n *\n * @param event\n * @param option\n * @param allow - Whether to allow ad personalization signals.\n * @default true\n */\n gtag(event: 'set', option: 'allow_ad_personalization_signals', allow: boolean): void;\n\n /**\n * Used for A/B testing and content-targeted ads. Use campaign_content to differentiate ads or\n * links that point to the same URL.\n */\n gtag(event: 'set', option: 'campaign_content', content: string): void;\n\n /**\n * Used to identify which campaign this referral references. Use campaign_id to identify a\n * specific campaign.\n */\n gtag(event: 'set', option: 'campaign_id', id: string): void;\n\n /** Use campaign_medium to identify a medium such as email or cost-per-click. */\n gtag(event: 'set', option: 'campaign_medium', medium: CampaignMedium): void;\n\n /**\n * Used for keyword analysis. Use campaign_name to identify a specific product promotion or\n * strategic campaign.\n */\n gtag(event: 'set', option: 'campaign_name', name: string): void;\n\n /** Use campaign_source to identify a search engine, newsletter name, or other source. */\n gtag(event: 'set', option: 'campaign_source', source: CampaignSource): void;\n\n /** Used for paid search. Use campaign_term to note the keywords for this ad. */\n gtag(event: 'set', option: 'campaign_term', term: string): void;\n\n /**\n * @deprecated\n * Key Point: Use the campaign_ prefixed version of each campaign value instead of this field.\n */\n gtag(event: 'set', option: 'campaign', params: Campaign): void;\n\n /**\n * Pseudonymously identifies a browser instance. By default, this value is stored as part of the\n * first-party Analytics cookie with a two-year expiration.\n */\n gtag(event: 'set', option: 'client_id', id: string): void;\n\n /** example: gtag('set', 'content_group', '/news/sports'); */\n gtag(event: 'set', option: 'content_group', group: string): void;\n\n /**\n * Specifies the domain used to store the analytics cookie.\n * Set to 'none' to set the cookie without specifying a domain.\n * Set to 'auto' (the default value) to set the cookie to the top level domain plus one\n * subdomain (eTLD +1). For example, if cookie_domain is set to 'auto' https://example.com would\n * use example.com for the domain, and https://subdomain.example.com would also use example.com\n * for the domain.\n *\n * @param event\n * @param option\n * @param domain - The domain used to store the analytics cookie.\n * @default 'auto'\n */\n gtag(event: 'set', option: 'cookie_domain', domain: 'none' | 'auto' | (string & {})): void;\n\n /**\n * Every time a hit is sent to Google Analytics, the cookie expiration time is updated to be the\n * current time plus the value of the cookie_expires field. This means that if you use the default\n * value time of two years (63,072,000 seconds), and a user visits your site every month, their\n * cookie will never expire.\n *\n * If you set the cookie_expires time to 0 (zero) seconds, the cookie turns into a session-based\n * cookie and expires once the current browser session ends.\n *\n * Caution: If you set the cookie to expire too quickly, you will inflate your user count and\n * decrease the quality of your measurement.\n *\n * @param event\n * @param option\n * @param expires - The number of seconds until the cookie expires.\n * @default 63072000\n */\n gtag(event: 'set', option: 'cookie_expires', expires: number): void;\n\n /**\n * Appends additional flags to the cookie when set. Flags must be separated by semicolons. See\n * [write a new cookie](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie#write_a_new_cookie) for some examples of flags to set.\n */\n gtag(event: 'set', option: 'cookie_flags', flags: string): void;\n\n /** Specifies the subpath used to store the analytics cookie. */\n gtag(event: 'set', option: 'cookie_path', path: string): void;\n\n /** Specifies a prefix to prepend to analytics cookie names. */\n gtag(event: 'set', option: 'cookie_prefix', prefix: string): void;\n\n /**\n * When cookie_update is set to true, gtag.js will update cookies on each page load. This will\n * update the cookie expiration to be set relative to the most recent visit to the site. For\n * example, if cookie expiration is set to one week, and a user visits using the same browser\n * every five days, the cookie expiration will be updated on each visit and will effectively\n * never expire.\n *\n * When set to false, cookies are not updated on each page load. This has the effect of cookie\n * expiration being relative to the first time a user visited the site.\n *\n * @param event\n * @param option\n * @param update - Whether to update the cookie on each page load.\n * @default true\n */\n gtag(event: 'set', option: 'cookie_update', update: boolean): void;\n\n /**\n * Set to true to indicate to Analytics that the referrer shouldn't be displayed as a traffic\n * source. [Learn when to use this field](https://support.google.com/analytics/answer/10327750#set-parameter)\n *\n * @param event\n * @param option\n * @param ignore - Whether to ignore the referrer.\n * @default false\n */\n gtag(event: 'set', option: 'ignore_referrer', ignore: boolean): void;\n\n /**\n * Specifies the language preference of the user. Defaults to the user's `navigator.language` value.\n *\n * @param event\n * @param option\n * @param language - The language preference of the user.\n * @default navigator.language\n */\n gtag(event: 'set', option: 'language', language: string): void;\n\n /**\n * Specifies the full URL of the page. Defaults to the user's `document.location` value.\n *\n * @param event\n * @param option\n * @param location - The full URL of the page. Character limit 1000\n * @default document.location\n */\n gtag(event: 'set', option: 'page_location', location: string): void;\n\n /**\n * Specifies which referral source brought traffic to a page. This value is also used to compute\n * the traffic source. The format of this value is a URL. Defaults to the user's `document.referrer`\n * value.\n *\n * @param event\n * @param option\n * @param referrer - The referral source. Character limit 420\n * @default document.referrer\n */\n gtag(event: 'set', option: 'page_referrer', referrer: string): void;\n\n /**\n * The title of the page or document. Defaults to the user's `document.title` value.\n *\n * @param event\n * @param option\n * @param title - The title of the page or document. Character limit 300\n * @default document.title\n */\n gtag(event: 'set', option: 'page_title', title: string): void;\n\n /**\n * Set to false to prevent the default snippet from sending a page_view.\n *\n * @param event\n * @param option\n * @param send - Whether to send a page_view.\n * @default true\n */\n gtag(event: 'set', option: 'send_page_view', send: boolean): void;\n\n /**\n * Specifies the resolution of the screen. Should be two positive integers separated by an x. For\n * example, for an 800px by 600px screen, the value would be 800x600. Calculated from the user's\n * window.screen value.\n *\n * @param event\n * @param option\n * @param resolution - The resolution of the screen.\n * @default window.screen\n */\n gtag(event: 'set', option: 'screen_resolution', resolution: `${number}x${number}`): void;\n\n /**\n * Specifies a known identifier for a user provided by the site owner/library user. It must not\n * itself be PII (personally identifiable information). The value should never be persisted in\n * Google Analytics cookies or other Analytics-provided storage.\n *\n * @param event\n * @param option\n * @param userId - The user ID. Character limit 256. `null` clears it on sign-out.\n */\n gtag(event: 'set', option: 'user_id', userId: string | null): void;\n\n /**\n * User properties are attributes that can be used to describe segments of your user base, such\n * as language preference or geographic location. Up to 25 additional user properties can be set\n * per project.\n *\n * @param event\n * @param option\n * @param properties\n */\n gtag(event: 'set', option: 'user_properties', properties: UserProperties): void;\n\n gtag(event: 'set', option: 'user_data', data: UserProvidedData): void;\n\n /**\n * gtag('config', ...) Set for a single stream\n * gtag('set', ...) Set globally\n */\n gtag(event: 'config', gaId: GaId, config?: Config): void;\n\n gtag<T extends string>(\n event: 'event',\n eventName: T extends keyof StandardEvents ? T : string,\n eventParams?: T extends keyof StandardEvents\n ? StandardEvents[T]\n : Record<string, string | number | boolean | null | undefined>\n ): void;\n}\n"],"mappings":";;AACA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,wBAAwB;CAC5B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,qBAAqB,CAAC,GAAG,uBAAuB,GAAG,qBAAqB"}
@@ -215,7 +215,10 @@ function sendPendingEvents() {
215
215
  clearTimeout(timer);
216
216
  timer = null;
217
217
  }
218
- list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));
218
+ list.splice(0).forEach((event) => event.options.onSucceed?.({
219
+ id: event.id,
220
+ beacon: true
221
+ }));
219
222
  }
220
223
  function sendBeacon(name, properties) {
221
224
  const visitor_id = require_visitor_id.visitorId();
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;C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QAAQ,CAAC,CAAC,CAE9C,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaI,mBAAAA,UAAU;CAG7B,MAAM,aAAaF,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.cjs","names":["TokenBucket","config","cache","IGNORED_EVENTS","getSession","uuidv7","visitorId","fetch"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id, beacon: true }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;AA4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B,KAAK,KAAK,UACzC,MAAM,OAAO,YAAY,MAAM,WAAWJ,oBAAAA,MAAM,QAAQ,CAAC,CAAC,CAE9C,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY;EAAE,IAAI,MAAM;EAAI,QAAQ;CAAK,CAAC,CAAC;AAC7F;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAaI,mBAAAA,UAAU;CAG7B,MAAM,aAAaF,sBAAAA,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,KAAA,GAAIC,KAAAA,GAAAA,CAAO;EACX;EACA;EAGA,MAAMH,oBAAAA,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAUD,oBAAAA,OAAO;EACjB,aAAaA,oBAAAA,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -4,9 +4,13 @@ export interface TrackOptions {
4
4
  enableThirdPartyTracking?: boolean;
5
5
  /**
6
6
  * Called once the server (or a beacon) has taken the event, with the event's id: the one
7
- * generated when it was tracked, which the third-party trackers were given too.
7
+ * generated when it was tracked, which the third-party trackers were given too. `beacon` is
8
+ * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot
9
+ * tell delivered from dropped, so it is taken, not confirmed.
8
10
  */
9
- onSucceed?: (response?: TrackEventResponse[number]) => void;
11
+ onSucceed?: (response?: TrackEventResponse[number] & {
12
+ beacon?: true;
13
+ }) => void;
10
14
  onError?: (error: unknown) => void;
11
15
  }
12
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -4,9 +4,13 @@ export interface TrackOptions {
4
4
  enableThirdPartyTracking?: boolean;
5
5
  /**
6
6
  * Called once the server (or a beacon) has taken the event, with the event's id: the one
7
- * generated when it was tracked, which the third-party trackers were given too.
7
+ * generated when it was tracked, which the third-party trackers were given too. `beacon` is
8
+ * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot
9
+ * tell delivered from dropped, so it is taken, not confirmed.
8
10
  */
9
- onSucceed?: (response?: TrackEventResponse[number]) => void;
11
+ onSucceed?: (response?: TrackEventResponse[number] & {
12
+ beacon?: true;
13
+ }) => void;
10
14
  onError?: (error: unknown) => void;
11
15
  }
12
16
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;EAKA,aAAa,WAAW;EACxB,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../src/track/index.ts"],"mappings":";;iBAgBiB;EACf;;;;;;;EAOA,aAAa,WAAW;IAA+B;;EACvD,WAAW;;;;;;;iBA2CI;EACf;EACA;;;wBA0Lc,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,YAAY,gBAAgB,gBAC5B,SAAS,cACT,OAAO;;;;;wBAeO,MAAM,UAAU,YAAY,WAC1C,MAAM,UAAU,IAChB,aAAa,gBAAgB,IAC7B,UAAS;;;;;;;;;;;;wBA0BK;wBAiBA,WAAW,UAAU,YAAY,WAC/C,MAAM,UAAU,IAChB,aAAa,gBAAgB"}
@@ -214,7 +214,10 @@ function sendPendingEvents() {
214
214
  clearTimeout(timer);
215
215
  timer = null;
216
216
  }
217
- list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));
217
+ list.splice(0).forEach((event) => event.options.onSucceed?.({
218
+ id: event.id,
219
+ beacon: true
220
+ }));
218
221
  }
219
222
  function sendBeacon(name, properties) {
220
223
  const visitor_id = visitorId();
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too.\n */\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA0BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;;;;;AAQJ,SAAS,iBAAiB;CACxB,OAAQ,gBAAgB,IAAI,YAAY;EAAE,MAAM;EAAG,UAAU;EAAI,WAAW;CAAE,CAAC;AACjF;;;;;;;;;;AA0CA,eAAe,cAAkC;CAC/C,IAAI;EACF,OAAO,MAAM,OAAO,QAAQ;CAC9B,SAAS,GAAY;EACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;EAC7C,OAAO,MAAM,QAAQ,CAAC;CACxB;AACF;;;;;;AAOA,MAAM,OAAe,CAAC;AACtB,MAAM,YAAY;AAClB,MAAM,QAAQ;AACd,IAAI,QAA8C;;;;;;;;;;;;;;;;AAiBlD,SAAS,WAAW,OAAa;CAG/B,IAAI,MAAM,QAAQ,6BAA6B,SAAS,eAAe,SAAS,MAAM,IAAI,GACxF;CAEF,MAAM,WAAW,aAAa,OAAO,oBAAoB,KAAK;CAC9D,IAAI,SAAS,WAAW,GAAG;CAC3B,iBAAiB,aAAa,UAAU,KAAK,GAAG,CAAC;AACnD;;AAGA,SAAS,aAAa,UAA+B,OAAkC;CACrF,OAAO,SAAS,QAAQ,YAAY;EAClC,IAAI;GACF,OAAO,QAAQ,MAAM,MAAM,MAAM,YAAY,MAAM,EAAE,MAAM;EAC7D,SAAS,GAAY;GAEnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC7C,OAAO;EACT;CACF,CAAC;AACH;;;;;;;;;;;;AAaA,SAAS,QACP,MACA,YACA,SACA,OAAkB,CAAC,GACb;CACN,MAAM,6BAAY,IAAI,KAAK,EAAA,CAAE,YAAY;CACzC,MA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,IAAI,CAAC,OAH4B,KAAK,KAAK,UACzC,MAAM,OAAO,YAAY,MAAM,WAAW,MAAM,QAAQ,CAAC,CAAC,CAE9C,CAAC,GAAG;EAChB,MAAW;EACX;CACF;CACA,IAAI,OAAO;EACT,aAAa,KAAK;EAClB,QAAQ;CACV;CACA,KAAK,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU,MAAM,QAAQ,YAAY,EAAE,IAAI,MAAM,GAAG,CAAC,CAAC;AAC/E;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,UAAU;CAG7B,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,IAAIA,GAAO;EACX;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
1
+ {"version":3,"file":"index.mjs","names":["uuidv7"],"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport { v7 as uuidv7 } from 'uuid';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { getSession } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { visitorId } from '../visitor/id';\nimport type {\n EventName,\n ThirdPartyTracker,\n TrackEventResponse,\n TrackName,\n TrackProperties,\n TrackTags,\n} from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n /**\n * Called once the server (or a beacon) has taken the event, with the event's id: the one\n * generated when it was tracked, which the third-party trackers were given too. `beacon` is\n * set when the event went by `sendPendingEvents`: the browser queued it, but a beacon cannot\n * tell delivered from dropped, so it is taken, not confirmed.\n */\n onSucceed?: (response?: TrackEventResponse[number] & { beacon?: true }) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = {};\n\nlet tokenBucket: TokenBucket | undefined;\n\n/**\n * The rate limiter, built on the first send rather than at module scope: its\n * constructor starts a refill `setInterval`, and Cloudflare Workers refuse to\n * set a timer outside a request handler for the same reason they refuse to\n * generate random values there — see `setup/session.ts`.\n */\nfunction getTokenBucket() {\n return (tokenBucket ??= new TokenBucket({ rate: 1, capacity: 20, requested: 2 }));\n}\n\ntype Item = {\n /**\n * The event's id, a uuidv7 generated when it is tracked. The server stores the event under it\n * (`on conflict (id) do nothing`, so a batch `fetch` retries is not stored twice), and the\n * third-party trackers are given it at once as their deduplication id — the id the server's\n * conversions API sends again for the same event.\n */\n id: string;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n tags: Promise<TrackTags>;\n /** `tags` once settled: a page being hidden can await nothing, and sends what it has. */\n settled?: TrackTags;\n /** Decided when the event happens, as GA4 and PostHog decide it, never when it is sent. */\n session_id: string;\n timestamp: string;\n options: TrackOptions;\n};\n\n/**\n * How an event is created, for the SDK's own callers (`trackOnce`); not exported from the\n * package. `id` carries over the id of an earlier attempt at the same occurrence, and\n * `pixels: false` skips the third-party trackers that attempt has already fired.\n */\nexport interface EventInit {\n id?: string;\n pixels?: boolean;\n}\n\n/**\n * Tags belong to the moment the event happened, not to the moment its batch goes out: a queued\n * event waits up to `delay` ms, and a single page app can navigate in that window, which would\n * stamp every pending event with the URL of the page the user has already left.\n *\n * The promise then sits in the queue with nothing awaiting it, so a failure has to be absorbed\n * here — an unhandled rejection would surface as a global error long before `sendEvents` could\n * catch it. Falling back to the last built tags keeps the event, minus whatever changed since.\n */\nasync function captureTags(): Promise<TrackTags> {\n try {\n return await config.getTags();\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n return cache.tags ?? {};\n }\n}\n\n/**\n * The events not yet sent, and the only place they are: a batch leaves it at the moment it is\n * handed to `fetch` or to a beacon, never earlier. So when the page is hidden or left,\n * everything still unsent is right here for `sendPendingEvents`.\n */\nconst list: Item[] = [];\nconst batchSize = 10;\nconst delay = 2000;\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\n/**\n * Hands the event to the third-party trackers now, as it is tracked, under its own id — not once\n * the server has answered. An event followed by a full-page navigation (an outbound link,\n * `begin_checkout` before the redirect to the payment page, a landing page left at once) reaches\n * the pixels before the page goes, and the server's conversions API, sending the same id, still\n * deduplicates against the browser event. A server that is down no longer takes the pixels down\n * with it either.\n *\n * A tracker that returns `false` is not ready — its pixel's global is not on the page yet, the\n * snippet still loading (the first `page_view` of a visit is tracked right as the page mounts).\n * Those trackers, and only those, are called once more on the next macrotask, with the same event\n * and id, after the inline snippets have had their turn; a tracker still not ready then is given\n * up on, as it was when it ran after the server's answer. Never more than once: a pixel's global\n * either exists by then or the script is blocked.\n */\nfunction firePixels(event: Item) {\n // An explicit false, not falsiness: a caller passing `{ onSucceed }` replaces the options\n // object wholesale, and leaving the flag out must not silently switch forwarding off.\n if (event.options.enableThirdPartyTracking === false || IGNORED_EVENTS.includes(event.name)) {\n return;\n }\n const notReady = callTrackers(config.thirdPartyTrackers, event);\n if (notReady.length === 0) return;\n setTimeout(() => callTrackers(notReady, event), 0);\n}\n\n/** Calls each tracker with the event; returns the ones that said they were not ready. */\nfunction callTrackers(trackers: ThirdPartyTracker[], event: Item): ThirdPartyTracker[] {\n return trackers.filter((tracker) => {\n try {\n return tracker(event.name, event.properties, event.id) === false;\n } catch (e: unknown) {\n // A third-party script does not get to take the tracking call, or the other trackers, with it.\n if (e instanceof Error) console.log(e.message);\n return false;\n }\n });\n}\n\n/**\n * Queues an event, preceded by a `session_start` when it is the one that opens a session, and\n * fires its third-party trackers.\n *\n * The session is decided here, when the event happens, as GA4 and PostHog decide it: the\n * `session_start` then sits in the queue right before the event that opened the session, so\n * wherever that event goes — a batch, a beacon, a retry — its announcement has gone ahead of it.\n * It carries that event's tags and time, as GA4 derives it from the hit that started the\n * session: the landing page is where the session began, whatever the page has navigated to by\n * the time the batch goes out.\n */\nfunction enqueue(\n name: Item['name'],\n properties: Item['properties'],\n options: TrackOptions,\n init: EventInit = {}\n): Item {\n const timestamp = new Date().toISOString();\n const tags = captureTags();\n const { id: session_id, started } = getSession().touch(Date.parse(timestamp));\n const item = (fields: Pick<Item, 'id' | 'name' | 'properties' | 'options'>): Item => {\n const result: Item = { ...fields, tags, timestamp, session_id };\n void tags.then((settled) => (result.settled = settled));\n return result;\n };\n if (started) {\n const options = { enableThirdPartyTracking: false };\n list.push(item({ id: uuidv7(), name: 'session_start', properties: {}, options }));\n }\n const event = item({ id: init.id ?? uuidv7(), name, properties, options });\n list.push(event);\n if (init.pixels !== false) firePixels(event);\n return event;\n}\n\nfunction toDTO(event: Item, visitor_id: string, tags: TrackTags): CreateTrackEventDTO[number] {\n return {\n id: event.id,\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: event.session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n };\n}\n\n/**\n * Sends the queue. Everything that has to be awaited is awaited first, and only then are the\n * events taken off the queue and handed to `fetch` in the same synchronous step — so there is\n * no moment at which an event is neither queued nor sent.\n */\nasync function flush() {\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n if (list.length === 0) return;\n\n let events: Item[] = [];\n try {\n await getTokenBucket().removeTokens();\n const visitor_id = visitorId();\n const headers = await config.getHeaders();\n // Settled before the events leave the queue; those queued meanwhile are a microtask away.\n await Promise.all(list.map((event) => event.tags));\n\n events = list.splice(0);\n if (events.length === 0) return;\n const dto: CreateTrackEventDTO = await Promise.all(\n events.map(async (event) => toDTO(event, visitor_id, await event.tags))\n );\n\n const body = JSON.stringify(dto);\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n // Retried although a POST: every event carries its client-generated id, and the server stores\n // a batch it already has `on conflict (id) do nothing`.\n retries: 3,\n // keepalive lets the request survive the page being unloaded mid-flight, within a 64KB\n // budget shared by every such request of the page; a body that could not fit goes as a\n // plain POST rather than failing outright.\n keepalive: body.length < 60_000,\n headers,\n body,\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n // The body is not read. Every event has had its id since it was tracked, and its trackers\n // were fired with it then. Servers still answer one `{ id }` per event (`TrackEventResponse`),\n // which a server predating client ids fills with ids of its own; neither is needed here, and\n // an answer that is not even JSON does not turn a stored batch into a failure.\n events.forEach((event) => event.options.onSucceed?.({ id: event.id }));\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n // `fetch` has already retried the transient failures by the time a batch fails here; what\n // remains is a batch the server rejected outright — one invalid event fails the whole batch\n // — or a network that stayed down past the retries. The other events are reported lost;\n // `session_start` alone goes back on the queue for the next send, because it is the\n // session's only attribution record: a session without one has no channel, and its every\n // later event drops out of an attribution join.\n const starts = events.filter((event) => event.name === 'session_start');\n list.unshift(...starts);\n events\n .filter((event) => event.name !== 'session_start')\n .forEach((event) => event.options.onError?.(e));\n }\n}\n\n/** `track`, with the `EventInit` only the SDK itself passes. */\nexport function queueEvent<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n options: TrackOptions,\n init?: EventInit\n) {\n enqueue(name, properties, options, init);\n if (list.length >= batchSize) {\n void flush();\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => void flush(), delay);\n}\n\n/**\n * Queues the event for the next batch — up to 2 s away, at once when the batch is full — and\n * hands it to the third-party trackers now, under the id it is sent with.\n */\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n queueEvent(name, properties, options);\n}\n\nfunction beacon(dto: CreateTrackEventDTO): boolean {\n // Not every runtime with a `navigator` has it: React Native has neither beacons nor pages.\n if (typeof navigator === 'undefined' || !('sendBeacon' in navigator)) return false;\n // text/plain keeps a cross-origin beacon a CORS simple request: as application/json it needs a\n // preflight, which a page being closed often cannot complete, and the beacon is then dropped.\n // The server reads it as JSON (`zBeaconJson` in @shware/http).\n const blob = new Blob([JSON.stringify(dto)], { type: 'text/plain;charset=UTF-8' });\n return navigator.sendBeacon(`${config.endpoint}/events`, blob);\n}\n\n/**\n * Sends the queue by beacon, now: for when the page is hidden or left, the last moment its\n * script is sure to run — what PostHog's `requestQueue.unload()` and GA4 do on the same events.\n * Call it before the engagement beacon: a new session's `session_start` is in this queue.\n *\n * Nothing can be awaited here, so the events go with the tags they have settled on (the last\n * built ones otherwise). Each goes with the id it was tracked with, and its third-party trackers\n * were fired then, under that id: none is fired again here. The visitor id is local\n * (`visitorId`), so a first visit left within a second is sent like any other; when no beacon\n * can take them — no `sendBeacon`, a refused body — they stay queued for the usual send.\n */\nexport function sendPendingEvents() {\n if (list.length === 0) return;\n const visitor_id = visitorId();\n const dto: CreateTrackEventDTO = list.map((event) =>\n toDTO(event, visitor_id, event.settled ?? cache.tags ?? {})\n );\n if (!beacon(dto)) {\n void flush();\n return;\n }\n if (timer) {\n clearTimeout(timer);\n timer = null;\n }\n list.splice(0).forEach((event) => event.options.onSucceed?.({ id: event.id, beacon: true }));\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n const visitor_id = visitorId();\n // No stored session means no event was ever queued from this storage, so there is no session\n // to report for — and one started here could never be announced. See `Session.extend`.\n const session_id = getSession().extend();\n if (!session_id) return;\n\n const dto: CreateTrackEventDTO = [\n {\n id: uuidv7(),\n name,\n properties,\n // Tags are worth less than the event carrying them: an empty set still reports the\n // engagement, and every field in `tagsSchema` is optional.\n tags: cache.tags ?? {},\n visitor_id,\n session_id,\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n if (beacon(dto)) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;AA4BA,MAAM,iBAA+B,CAAC;AAEtC,IAAI;;;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Q,YAAY;EAAE,IAAI,MAAM;EAAI,QAAQ;CAAK,CAAC,CAAC;AAC7F;AAEA,SAAgB,WACd,MACA,YACA;CACA,MAAM,aAAa,UAAU;CAG7B,MAAM,aAAa,WAAW,CAAC,CAAC,OAAO;CACvC,IAAI,CAAC,YAAY;CAiBjB,IAAI,OAAO,CAdT;EACE,IAAIA,GAAO;EACX;EACA;EAGA,MAAM,MAAM,QAAQ,CAAC;EACrB;EACA;EACA,UAAU,OAAO;EACjB,aAAa,OAAO;EACpB,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;CACpC,CAEW,CAAC,GAAG;CACjB,QAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD"}
@@ -101,7 +101,13 @@ function clearPending(name, key) {
101
101
  * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
102
102
  * send that fails is tried again by the next call instead of being lost — under the same event id,
103
103
  * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
104
- * one page a key already queued is not queued twice. When the storage cannot be read or written
104
+ * one page a key already queued is not queued twice.
105
+ *
106
+ * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
107
+ * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
108
+ * stays unsent with its id. The next call for the key — the result page opened again — sends the
109
+ * event once more under that id and without pixels, which the server ignores when the beacon did
110
+ * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
105
111
  * the event is tracked anyway: a rare duplicate is better than a lost conversion.
106
112
  *
107
113
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
@@ -131,6 +137,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
131
137
  ...options,
132
138
  onSucceed: (response) => {
133
139
  clearPending(name, key);
140
+ if (response?.beacon) {
141
+ options.onSucceed?.(response);
142
+ return;
143
+ }
134
144
  try {
135
145
  write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
136
146
  key,
@@ -1 +1 @@
1
- {"version":3,"file":"once.cjs","names":["config","uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQ,WAAW,IAAI,CAAC;CACnD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EACN,OAAO,CAAC;CACV;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,CAAC;CAC3D,MAAM,E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AAE,OAAO;GAC/C;GACA,QAAQ,YAAY,QAAQ;EAC9B;EACA,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,GACA,UAAU;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"once.cjs","names":["config","uuidv7"],"sources":["../../src/track/once.ts"],"sourcesContent":["import { v7 as uuidv7 } from 'uuid';\nimport { config } from '../setup/index';\nimport { type TrackOptions, queueEvent } from './index';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport interface TrackOnceOptions extends TrackOptions {\n /**\n * What makes this occurrence the same one again: a checkout session id for `purchase`, an order\n * id, a transaction id. Required, never derived from the properties, so the caller decides what\n * \"once\" means. The same key under another event name is a different occurrence.\n */\n key: string;\n /** How long a sent key is remembered, in milliseconds. 90 days by default. */\n ttl?: number;\n}\n\nconst DEFAULT_TTL = 90 * 24 * 60 * 60 * 1000;\n/** Keys remembered per event name; the oldest are forgotten first. */\nconst MAX_ENTRIES = 20;\n\n/**\n * `{\"v\":2,\"entries\":[[key, id, expiresAt, sent], …]}`, oldest first. Entries are tuples in an\n * array rather than an object keyed by `key`: an object would move integer-like keys (\"123\") to\n * the front and lose the order the oldest are dropped by. Escaping the value for the medium is the\n * storage's job, so this is plain JSON.\n *\n * `id` is the event id the key goes out under, decided by the first call and kept while `sent`\n * is false — a send that failed, or a page reloaded before its batch went out. The third-party\n * trackers fire when the event is tracked, not when it is sent, so that first call has already\n * reported the occurrence to them: the next call reuses the id, fires none of them again, and\n * the server (`on conflict (id) do nothing`) stores the event once even if the failed send had in\n * fact arrived.\n *\n * Version 1 records (`[key, expiresAt]`, written before the id was kept) are read as sent: that\n * is all a v1 record ever held, and dropping them would report every remembered occurrence again.\n */\nconst VERSION = 2;\n\ntype Entry = { key: string; id: string; expiresAt: number; sent: boolean };\n\nfunction storageKey(name: string) {\n return `track_once.${name}`;\n}\n\n/** The stored entries, or none for a record that is missing, of another version or malformed. */\nfunction read(name: string): Entry[] {\n const raw = config.storage.getItem(storageKey(name));\n if (!raw) return [];\n let record: unknown;\n try {\n record = JSON.parse(raw);\n } catch {\n return [];\n }\n if (typeof record !== 'object' || record === null) return [];\n const { v, entries } = record as { v?: unknown; entries?: unknown };\n if (!Array.isArray(entries)) return [];\n if (v === 1) {\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, expiresAt] = entry as unknown[];\n if (typeof key !== 'string' || typeof expiresAt !== 'number') return [];\n // Sent is all v1 remembered; the id it went out under is gone, and no longer needed.\n return [{ key, id: '', expiresAt, sent: true }];\n });\n }\n if (v !== VERSION) return [];\n return entries.flatMap((entry: unknown) => {\n if (!Array.isArray(entry)) return [];\n const [key, id, expiresAt, sent] = entry as unknown[];\n if (typeof key !== 'string' || typeof id !== 'string' || typeof expiresAt !== 'number') {\n return [];\n }\n if (typeof sent !== 'boolean') return [];\n return [{ key, id, expiresAt, sent }];\n });\n}\n\nfunction write(name: string, entries: Entry[]) {\n const record = {\n v: VERSION,\n entries: entries.slice(-MAX_ENTRIES).map((e) => [e.key, e.id, e.expiresAt, e.sent]),\n };\n config.storage.setItem(storageKey(name), JSON.stringify(record));\n}\n\nfunction live(entries: Entry[], now: number) {\n return entries.filter((entry) => entry.expiresAt > now);\n}\n\n/** Keys queued in this page (or app process) but not confirmed sent yet, per event name. */\nconst pending = new Map<string, Set<string>>();\n\nfunction isPending(name: string, key: string) {\n return pending.get(name)?.has(key) ?? false;\n}\n\nfunction markPending(name: string, key: string) {\n const keys = pending.get(name);\n if (keys) keys.add(key);\n else pending.set(name, new Set([key]));\n}\n\nfunction clearPending(name: string, key: string) {\n const keys = pending.get(name);\n if (!keys) return;\n keys.delete(key);\n if (keys.size === 0) pending.delete(name);\n}\n\n/**\n * Tracks an event at most once per `key`: a reloaded or revisited payment result page, a\n * re-delivered store transaction, a confirmation screen opened twice. Returns whether the event\n * was queued.\n *\n * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a\n * send that fails is tried again by the next call instead of being lost — under the same event id,\n * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within\n * one page a key already queued is not queued twice.\n *\n * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked\n * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry\n * stays unsent with its id. The next call for the key — the result page opened again — sends the\n * event once more under that id and without pixels, which the server ignores when the beacon did\n * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written\n * the event is tracked anyway: a rare duplicate is better than a lost conversion.\n *\n * Deduplication is per device and storage. A second device still reports its own occurrence, so\n * figures that must be exact (revenue) belong to server-side records.\n */\nexport function trackOnce<T extends EventName = EventName>(\n name: TrackName<T>,\n properties: TrackProperties<T> | undefined,\n { key, ttl = DEFAULT_TTL, ...options }: TrackOnceOptions\n): boolean {\n if (isPending(name, key)) return false;\n\n const now = Date.now();\n // An earlier call that failed to send: its id, and its pixels already fired.\n let earlier: Entry | undefined;\n let id = uuidv7();\n try {\n const entries = live(read(name), now);\n earlier = entries.find((entry) => entry.key === key);\n if (earlier?.sent) return false;\n if (earlier) id = earlier.id;\n else write(name, [...entries, { key, id, expiresAt: now + ttl, sent: false }]);\n } catch (e: unknown) {\n // Unrecorded, a failed send would fire the pixels again on the next call: a rare duplicate\n // there beats not tracking.\n if (e instanceof Error) console.log(e.message);\n }\n\n markPending(name, key);\n queueEvent(\n name,\n properties,\n {\n ...options,\n onSucceed: (response) => {\n clearPending(name, key);\n // A beacon was only queued by the browser: the entry stays unsent, so a later call\n // sends it again under the same id.\n if (response?.beacon) {\n options.onSucceed?.(response);\n return;\n }\n try {\n const entries = live(read(name), Date.now()).filter((entry) => entry.key !== key);\n write(name, [...entries, { key, id, expiresAt: Date.now() + ttl, sent: true }]);\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n }\n options.onSucceed?.(response);\n },\n onError: (error) => {\n // Not sent: the entry stays unsent, with its id, so a later call can try again.\n clearPending(name, key);\n options.onError?.(error);\n },\n },\n earlier ? { id, pixels: false } : { id }\n );\n return true;\n}\n"],"mappings":";;;;;AAgBA,MAAM,cAAc;;;;;;;;;;;;;;;;;AAoBpB,MAAM,UAAU;AAIhB,SAAS,WAAW,MAAc;CAChC,OAAO,cAAc;AACvB;;AAGA,SAAS,KAAK,MAAuB;CACnC,MAAM,MAAMA,oBAAAA,OAAO,QAAQ,QAAQ,WAAW,IAAI,CAAC;CACnD,IAAI,CAAC,KAAK,OAAO,CAAC;CAClB,IAAI;CACJ,IAAI;EACF,SAAS,KAAK,MAAM,GAAG;CACzB,QAAQ;EACN,OAAO,CAAC;CACV;CACA,IAAI,OAAO,WAAW,YAAY,WAAW,MAAM,OAAO,CAAC;CAC3D,MAAM,EAAE,GAAG,YAAY;CACvB,IAAI,CAAC,MAAM,QAAQ,OAAO,GAAG,OAAO,CAAC;CACrC,IAAI,MAAM,GACR,OAAO,QAAQ,SAAS,UAAmB;EACzC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;EACnC,MAAM,CAAC,KAAK,aAAa;EACzB,IAAI,OAAO,QAAQ,YAAY,OAAO,cAAc,UAAU,OAAO,CAAC;EAEtE,OAAO,CAAC;GAAE;GAAK,IAAI;GAAI;GAAW,MAAM;EAAK,CAAC;CAChD,CAAC;CAEH,IAAI,MAAM,SAAS,OAAO,CAAC;CAC3B,OAAO,QAAQ,SAAS,UAAmB;EACzC,IAAI,CAAC,MAAM,QAAQ,KAAK,GAAG,OAAO,CAAC;EACnC,MAAM,CAAC,KAAK,IAAI,WAAW,QAAQ;EACnC,IAAI,OAAO,QAAQ,YAAY,OAAO,OAAO,YAAY,OAAO,cAAc,UAC5E,OAAO,CAAC;EAEV,IAAI,OAAO,SAAS,WAAW,OAAO,CAAC;EACvC,OAAO,CAAC;GAAE;GAAK;GAAI;GAAW;EAAK,CAAC;CACtC,CAAC;AACH;AAEA,SAAS,MAAM,MAAc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AS;GAAE;GAAK;GAAI,WAAW,MAAM;GAAK,MAAM;EAAM,CAAC,CAAC;CAC/E,SAAS,GAAY;EAGnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;CAC/C;CAEA,YAAY,MAAM,GAAG;CACrB,oBAAA,WACE,MACA,YACA;EACE,GAAG;EACH,YAAY,aAAa;GACvB,aAAa,MAAM,GAAG;GAGtB,IAAI,UAAU,QAAQ;IACpB,QAAQ,YAAY,QAAQ;IAC5B;GACF;GACA,IAAI;IAEF,MAAM,MAAM,CAAC,GADG,KAAK,KAAK,IAAI,GAAG,KAAK,IAAI,CAAC,CAAC,CAAC,QAAQ,UAAU,MAAM,QAAQ,GACvD,GAAG;KAAE;KAAK;KAAI,WAAW,KAAK,IAAI,IAAI;KAAK,MAAM;IAAK,CAAC,CAAC;GAChF,SAAS,GAAY;IACnB,IAAI,aAAa,OAAO,QAAQ,IAAI,EAAE,OAAO;GAC/C;GACA,QAAQ,YAAY,QAAQ;EAC9B;EACA,UAAU,UAAU;GAElB,aAAa,MAAM,GAAG;GACtB,QAAQ,UAAU,KAAK;EACzB;CACF,GACA,UAAU;EAAE;EAAI,QAAQ;CAAM,IAAI,EAAE,GAAG,CACzC;CACA,OAAO;AACT"}
@@ -19,7 +19,13 @@ export interface TrackOnceOptions extends TrackOptions {
19
19
  * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
20
20
  * send that fails is tried again by the next call instead of being lost — under the same event id,
21
21
  * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
22
- * one page a key already queued is not queued twice. When the storage cannot be read or written
22
+ * one page a key already queued is not queued twice.
23
+ *
24
+ * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
25
+ * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
26
+ * stays unsent with its id. The next call for the key — the result page opened again — sends the
27
+ * event once more under that id and without pixels, which the server ignores when the beacon did
28
+ * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
23
29
  * the event is tracked anyway: a rare duplicate is better than a lost conversion.
24
30
  *
25
31
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
@@ -1 +1 @@
1
- {"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;wBA+Gc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
1
+ {"version":3,"file":"once.d.cts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBAqHc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
@@ -19,7 +19,13 @@ export interface TrackOnceOptions extends TrackOptions {
19
19
  * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
20
20
  * send that fails is tried again by the next call instead of being lost — under the same event id,
21
21
  * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
22
- * one page a key already queued is not queued twice. When the storage cannot be read or written
22
+ * one page a key already queued is not queued twice.
23
+ *
24
+ * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
25
+ * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
26
+ * stays unsent with its id. The next call for the key — the result page opened again — sends the
27
+ * event once more under that id and without pixels, which the server ignores when the beacon did
28
+ * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
23
29
  * the event is tracked anyway: a rare duplicate is better than a lost conversion.
24
30
  *
25
31
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
@@ -1 +1 @@
1
- {"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;wBA+Gc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
1
+ {"version":3,"file":"once.d.mts","names":[],"sources":["../../src/track/once.ts"],"mappings":";;;iBAKiB,yBAAyB;;;;;;EAMxC;;EAEA;;;;;;;;;;;;;;;;;;;;;;wBAqHc,UAAU,UAAU,YAAY,WAC9C,MAAM,UAAU,IAChB,YAAY,gBAAgB,kBAC1B,KAAK,QAAsB,WAAW"}
@@ -100,7 +100,13 @@ function clearPending(name, key) {
100
100
  * The key is marked sent in `config.storage` only once the event has been sent (`onSucceed`), so a
101
101
  * send that fails is tried again by the next call instead of being lost — under the same event id,
102
102
  * so the third-party trackers fired by the first call are not fired again (see `VERSION`); within
103
- * one page a key already queued is not queued twice. When the storage cannot be read or written
103
+ * one page a key already queued is not queued twice.
104
+ *
105
+ * An event that leaves by beacon (`sendPendingEvents`, the page hidden or left) is not marked
106
+ * sent: a beacon cannot tell delivered from dropped, so it counts as unconfirmed and the entry
107
+ * stays unsent with its id. The next call for the key — the result page opened again — sends the
108
+ * event once more under that id and without pixels, which the server ignores when the beacon did
109
+ * arrive (it drops an event id it already has): one idempotent request more, against a lost one. When the storage cannot be read or written
104
110
  * the event is tracked anyway: a rare duplicate is better than a lost conversion.
105
111
  *
106
112
  * Deduplication is per device and storage. A second device still reports its own occurrence, so
@@ -130,6 +136,10 @@ function trackOnce(name, properties, { key, ttl = DEFAULT_TTL, ...options }) {
130
136
  ...options,
131
137
  onSucceed: (response) => {
132
138
  clearPending(name, key);
139
+ if (response?.beacon) {
140
+ options.onSucceed?.(response);
141
+ return;
142
+ }
133
143
  try {
134
144
  write(name, [...live(read(name), Date.now()).filter((entry) => entry.key !== key), {
135
145
  key,