@shware/analytics 3.5.2 → 3.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/server/index.cjs +3 -0
- package/dist/server/index.cjs.map +1 -1
- package/dist/server/index.d.cts +2 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.mjs +2 -0
- package/dist/server/index.mjs.map +1 -1
- package/dist/server/linkedin-conversions-api.cjs.map +1 -1
- package/dist/server/linkedin-conversions-api.mjs.map +1 -1
- package/dist/server/meta-conversions-api.cjs.map +1 -1
- package/dist/server/meta-conversions-api.mjs.map +1 -1
- package/dist/server/openai-conversions-api.cjs +107 -0
- package/dist/server/openai-conversions-api.cjs.map +1 -0
- package/dist/server/openai-conversions-api.d.cts +47 -0
- package/dist/server/openai-conversions-api.d.ts +47 -0
- package/dist/server/openai-conversions-api.mjs +81 -0
- package/dist/server/openai-conversions-api.mjs.map +1 -0
- package/dist/server/reddit-conversions-api.cjs.map +1 -1
- package/dist/server/reddit-conversions-api.mjs.map +1 -1
- package/dist/tanstack/index.cjs +28 -0
- package/dist/tanstack/index.cjs.map +1 -1
- package/dist/tanstack/index.d.cts +2 -1
- package/dist/tanstack/index.d.ts +2 -1
- package/dist/tanstack/index.mjs +28 -0
- package/dist/tanstack/index.mjs.map +1 -1
- package/dist/third-parties/google-analytics.cjs.map +1 -1
- package/dist/third-parties/google-analytics.mjs.map +1 -1
- package/dist/third-parties/index.cjs +5 -0
- package/dist/third-parties/index.cjs.map +1 -1
- package/dist/third-parties/index.d.cts +2 -0
- package/dist/third-parties/index.d.ts +2 -0
- package/dist/third-parties/index.mjs +3 -0
- package/dist/third-parties/index.mjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.cjs.map +1 -1
- package/dist/third-parties/linkedin-insight-tag.mjs.map +1 -1
- package/dist/third-parties/meta-pixel.cjs.map +1 -1
- package/dist/third-parties/meta-pixel.mjs.map +1 -1
- package/dist/third-parties/openai-pixel.cjs +77 -0
- package/dist/third-parties/openai-pixel.cjs.map +1 -0
- package/dist/third-parties/openai-pixel.d.cts +23 -0
- package/dist/third-parties/openai-pixel.d.ts +23 -0
- package/dist/third-parties/openai-pixel.mjs +51 -0
- package/dist/third-parties/openai-pixel.mjs.map +1 -0
- package/dist/third-parties/reddit-pixel.cjs.map +1 -1
- package/dist/third-parties/reddit-pixel.mjs.map +1 -1
- package/dist/track/gtag.cjs.map +1 -1
- package/dist/track/gtag.d.cts +45 -12
- package/dist/track/gtag.d.ts +45 -12
- package/dist/track/gtag.mjs.map +1 -1
- package/dist/track/index.cjs.map +1 -1
- package/dist/track/index.mjs.map +1 -1
- package/dist/track/oaiq.cjs +169 -0
- package/dist/track/oaiq.cjs.map +1 -0
- package/dist/track/oaiq.d.cts +111 -0
- package/dist/track/oaiq.d.ts +111 -0
- package/dist/track/oaiq.mjs +141 -0
- package/dist/track/oaiq.mjs.map +1 -0
- package/package.json +1 -1
package/dist/track/gtag.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"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 * In order to standardize the hash results, prior to 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 * In order to standardize the hash results, prior to 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>}`;\nexport type GtmId = `GTM-${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\nexport type AddedRecommendedEvents = {\n logout: undefined;\n trial_begin: {\n currency: string;\n value: number;\n source?: string; // added\n };\n subscribe: {\n currency: string;\n value: number;\n source?: string; // added\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 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 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 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 (63072000 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 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 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 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 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 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 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 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 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 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 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 name - The name of the user property. Character limit 24\n * @param value - The value of the user property. Character limit 36\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,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,qBAAqB,CAAC,GAAG,uBAAuB,GAAG,qBAAqB;","names":[]}
|
|
1
|
+
{"version":3,"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>}`;\nexport type GtmId = `GTM-${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,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEA,IAAM,wBAAwB;AAAA,EAC5B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAEO,IAAM,qBAAqB,CAAC,GAAG,uBAAuB,GAAG,qBAAqB;","names":[]}
|
package/dist/track/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { session } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = { enableThirdPartyTracking: true };\nconst tokenBucket = new TokenBucket({ rate: 1, capacity: 20, requested: 2 });\n\ntype Item = {\n //
|
|
1
|
+
{"version":3,"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { session } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = { enableThirdPartyTracking: true };\nconst tokenBucket = new TokenBucket({ rate: 1, capacity: 20, requested: 2 });\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n timestamp: string;\n options: TrackOptions;\n};\n\nasync function sendEvents(events: Item[]) {\n try {\n if (events.length === 0) return;\n\n if (session.isExpired()) {\n session.refresh();\n events.unshift({\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n timestamp: new Date().toISOString(),\n });\n } else {\n session.updateLastActiveTime();\n }\n\n await tokenBucket.removeTokens();\n\n const tags = await config.getTags();\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = events.map((event) => ({\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: session.getId(),\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }));\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data[index].id;\n options.onSucceed?.({ id: eventId });\n index++;\n if (\n !config.thirdPartyTrackers ||\n !options.enableThirdPartyTracking ||\n IGNORED_EVENTS.includes(name)\n ) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => tracker(name, properties, eventId));\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({ name, properties, options, timestamp: new Date().toISOString() });\n if (list.length >= batch) {\n const copy = [...list];\n list.length = 0;\n sendEvents(copy);\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n const copy = [...list];\n list.length = 0;\n sendEvents(copy);\n }, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([{ name, properties, options, timestamp: new Date().toISOString() }]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (!cache.tags || !cache.visitor) return;\n session.updateLastActiveTime();\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n tags: cache.tags,\n visitor_id: cache.visitor.id,\n session_id: session.getId(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAmC;AAEnC,mBAA8B;AAC9B,qBAAwB;AACxB,4BAA+B;AAC/B,qBAA2B;AAS3B,IAAM,iBAA+B,EAAE,0BAA0B,KAAK;AACtE,IAAM,cAAc,IAAI,yBAAY,EAAE,MAAM,GAAG,UAAU,IAAI,WAAW,EAAE,CAAC;AAW3E,eAAe,WAAW,QAAgB;AA1B1C;AA2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AAY,mBAAM,QAAQ;AAAA,MAC1B,YAAY,uBAAQ,MAAM;AAAA,MAC1B,UAAU,oBAAO;AAAA,MACjB,aAAa,oBAAO;AAAA,MACpB,YAAW,oBAAI,KAAK,GAAE,YAAY;AAAA,IACpC;AAAA,EACF;AACA,QAAM,OAAO,IAAI,KAAK,CAAC,KAAK,UAAU,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACzE,QAAM,UAAU,UAAU,WAAW,GAAG,oBAAO,QAAQ,WAAW,IAAI;AACtE,MAAI,QAAS;AACb,UAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD;","names":["_a"]}
|
package/dist/track/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { session } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = { enableThirdPartyTracking: true };\nconst tokenBucket = new TokenBucket({ rate: 1, capacity: 20, requested: 2 });\n\ntype Item = {\n //
|
|
1
|
+
{"version":3,"sources":["../../src/track/index.ts"],"sourcesContent":["import { TokenBucket, fetch } from '@shware/utils';\nimport type { CreateTrackEventDTO } from '../schema/index';\nimport { cache, config } from '../setup/index';\nimport { session } from '../setup/session';\nimport { IGNORED_EVENTS } from '../third-parties/ignored-events';\nimport { getVisitor } from '../visitor/index';\nimport type { EventName, TrackEventResponse, TrackName, TrackProperties } from './types';\n\nexport interface TrackOptions {\n enableThirdPartyTracking?: boolean;\n onSucceed?: (response?: TrackEventResponse[number]) => void;\n onError?: (error: unknown) => void;\n}\n\nconst defaultOptions: TrackOptions = { enableThirdPartyTracking: true };\nconst tokenBucket = new TokenBucket({ rate: 1, capacity: 20, requested: 2 });\n\ntype Item = {\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n name: TrackName<any>;\n // oxlint-disable-next-line @typescript-eslint/no-explicit-any\n properties: TrackProperties<any>;\n timestamp: string;\n options: TrackOptions;\n};\n\nasync function sendEvents(events: Item[]) {\n try {\n if (events.length === 0) return;\n\n if (session.isExpired()) {\n session.refresh();\n events.unshift({\n name: 'session_start',\n properties: {},\n options: { enableThirdPartyTracking: false },\n timestamp: new Date().toISOString(),\n });\n } else {\n session.updateLastActiveTime();\n }\n\n await tokenBucket.removeTokens();\n\n const tags = await config.getTags();\n const visitor_id = (await getVisitor()).id;\n\n const dto: CreateTrackEventDTO = events.map((event) => ({\n name: event.name,\n properties: event.properties,\n tags,\n visitor_id,\n session_id: session.getId(),\n platform: config.platform,\n environment: config.environment,\n timestamp: event.timestamp,\n }));\n\n const response = await fetch(`${config.endpoint}/events`, {\n method: 'POST',\n credentials: 'include',\n headers: await config.getHeaders(),\n body: JSON.stringify(dto),\n });\n\n if (!response.ok) {\n throw new Error(`Failed to send track event: ${response.status} ${await response.text()}`);\n }\n\n const data = (await response.json()) as TrackEventResponse;\n\n let index = 0;\n while (events.length > 0) {\n const event = events.shift();\n if (!event) {\n index++;\n continue;\n }\n const { options, name, properties } = event;\n const eventId = data[index].id;\n options.onSucceed?.({ id: eventId });\n index++;\n if (\n !config.thirdPartyTrackers ||\n !options.enableThirdPartyTracking ||\n IGNORED_EVENTS.includes(name)\n ) {\n continue;\n }\n config.thirdPartyTrackers.forEach((tracker) => tracker(name, properties, eventId));\n }\n } catch (e: unknown) {\n if (e instanceof Error) console.log(e.message);\n events.forEach((event) => event.options.onError?.(e));\n }\n}\n\nconst batch = 10;\nconst delay = 2000;\nconst list: Item[] = [];\nlet timer: ReturnType<typeof setTimeout> | null = null;\n\nexport function track<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n list.push({ name, properties, options, timestamp: new Date().toISOString() });\n if (list.length >= batch) {\n const copy = [...list];\n list.length = 0;\n sendEvents(copy);\n return;\n }\n if (timer) clearTimeout(timer);\n timer = setTimeout(() => {\n timer = null;\n const copy = [...list];\n list.length = 0;\n sendEvents(copy);\n }, delay);\n}\n\nexport async function trackAsync<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>,\n options: TrackOptions = defaultOptions\n) {\n await sendEvents([{ name, properties, options, timestamp: new Date().toISOString() }]);\n}\n\nexport function sendBeacon<T extends EventName = EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n) {\n if (!cache.tags || !cache.visitor) return;\n session.updateLastActiveTime();\n\n const dto: CreateTrackEventDTO = [\n {\n name,\n properties,\n tags: cache.tags,\n visitor_id: cache.visitor.id,\n session_id: session.getId(),\n platform: config.platform,\n environment: config.environment,\n timestamp: new Date().toISOString(),\n },\n ];\n const blob = new Blob([JSON.stringify(dto)], { type: 'application/json' });\n const success = navigator.sendBeacon(`${config.endpoint}/events`, blob);\n if (success) return;\n console.warn('Failed to send beacon', name, properties);\n}\n"],"mappings":";AAAA,SAAS,aAAa,aAAa;AAEnC,SAAS,OAAO,cAAc;AAC9B,SAAS,eAAe;AACxB,SAAS,sBAAsB;AAC/B,SAAS,kBAAkB;AAS3B,IAAM,iBAA+B,EAAE,0BAA0B,KAAK;AACtE,IAAM,cAAc,IAAI,YAAY,EAAE,MAAM,GAAG,UAAU,IAAI,WAAW,EAAE,CAAC;AAW3E,eAAe,WAAW,QAAgB;AA1B1C;AA2BE,MAAI;AACF,QAAI,OAAO,WAAW,EAAG;AAEzB,QAAI,QAAQ,UAAU,GAAG;AACvB,cAAQ,QAAQ;AAChB,aAAO,QAAQ;AAAA,QACb,MAAM;AAAA,QACN,YAAY,CAAC;AAAA,QACb,SAAS,EAAE,0BAA0B,MAAM;A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U,GAAG,CAAC,GAAG,EAAE,MAAM,mBAAmB,CAAC;AACzE,QAAM,UAAU,UAAU,WAAW,GAAG,OAAO,QAAQ,WAAW,IAAI;AACtE,MAAI,QAAS;AACb,UAAQ,KAAK,yBAAyB,MAAM,UAAU;AACxD;","names":["_a"]}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/track/oaiq.ts
|
|
21
|
+
var oaiq_exports = {};
|
|
22
|
+
__export(oaiq_exports, {
|
|
23
|
+
NON_AD_EVENTS: () => NON_AD_EVENTS,
|
|
24
|
+
mapContents: () => mapContents,
|
|
25
|
+
mapOAIEvent: () => mapOAIEvent,
|
|
26
|
+
toMinorUnits: () => toMinorUnits
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(oaiq_exports);
|
|
29
|
+
var NON_AD_EVENTS = [
|
|
30
|
+
// metrics
|
|
31
|
+
"CLS",
|
|
32
|
+
"FCP",
|
|
33
|
+
"FID",
|
|
34
|
+
"INP",
|
|
35
|
+
"LCP",
|
|
36
|
+
"TTFB",
|
|
37
|
+
// promotions
|
|
38
|
+
"view_promotion",
|
|
39
|
+
"select_promotion"
|
|
40
|
+
];
|
|
41
|
+
var ZERO_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set([
|
|
42
|
+
"BIF",
|
|
43
|
+
"CLP",
|
|
44
|
+
"DJF",
|
|
45
|
+
"GNF",
|
|
46
|
+
"ISK",
|
|
47
|
+
"JPY",
|
|
48
|
+
"KMF",
|
|
49
|
+
"KRW",
|
|
50
|
+
"MGA",
|
|
51
|
+
"PYG",
|
|
52
|
+
"RWF",
|
|
53
|
+
"UGX",
|
|
54
|
+
"VND",
|
|
55
|
+
"VUV",
|
|
56
|
+
"XAF",
|
|
57
|
+
"XOF",
|
|
58
|
+
"XPF"
|
|
59
|
+
]);
|
|
60
|
+
var THREE_DECIMAL_CURRENCIES = /* @__PURE__ */ new Set(["BHD", "IQD", "JOD", "KWD", "LYD", "OMR", "TND"]);
|
|
61
|
+
function toMinorUnits(value, currency) {
|
|
62
|
+
if (value === void 0 || value === null || Number.isNaN(value)) return void 0;
|
|
63
|
+
const code = currency == null ? void 0 : currency.toUpperCase();
|
|
64
|
+
const exponent = code && ZERO_DECIMAL_CURRENCIES.has(code) ? 0 : code && THREE_DECIMAL_CURRENCIES.has(code) ? 3 : 2;
|
|
65
|
+
return Math.round(value * 10 ** exponent);
|
|
66
|
+
}
|
|
67
|
+
function mapContents(items, currency) {
|
|
68
|
+
if (!items || items.length === 0) return void 0;
|
|
69
|
+
const code = currency == null ? void 0 : currency.toUpperCase();
|
|
70
|
+
return items.map((item) => ({
|
|
71
|
+
id: item.item_id,
|
|
72
|
+
name: item.item_name,
|
|
73
|
+
content_type: item.item_category,
|
|
74
|
+
quantity: item.quantity,
|
|
75
|
+
amount: toMinorUnits(item.price, currency),
|
|
76
|
+
currency: item.price !== void 0 ? code : void 0
|
|
77
|
+
}));
|
|
78
|
+
}
|
|
79
|
+
function prop(properties, key) {
|
|
80
|
+
return typeof properties === "object" && properties !== null ? properties[key] : void 0;
|
|
81
|
+
}
|
|
82
|
+
function readValue(properties) {
|
|
83
|
+
const value = prop(properties, "value");
|
|
84
|
+
return typeof value === "number" ? value : void 0;
|
|
85
|
+
}
|
|
86
|
+
function readCurrency(properties) {
|
|
87
|
+
const currency = prop(properties, "currency");
|
|
88
|
+
return typeof currency === "string" ? currency : void 0;
|
|
89
|
+
}
|
|
90
|
+
function readItems(properties) {
|
|
91
|
+
const items = prop(properties, "items");
|
|
92
|
+
return Array.isArray(items) ? items : void 0;
|
|
93
|
+
}
|
|
94
|
+
function contentsData(properties) {
|
|
95
|
+
const currency = readCurrency(properties);
|
|
96
|
+
return {
|
|
97
|
+
type: "contents",
|
|
98
|
+
amount: toMinorUnits(readValue(properties), currency),
|
|
99
|
+
currency: currency == null ? void 0 : currency.toUpperCase(),
|
|
100
|
+
contents: mapContents(readItems(properties), currency)
|
|
101
|
+
};
|
|
102
|
+
}
|
|
103
|
+
function customerActionData(properties) {
|
|
104
|
+
const currency = readCurrency(properties);
|
|
105
|
+
return {
|
|
106
|
+
type: "customer_action",
|
|
107
|
+
amount: toMinorUnits(readValue(properties), currency),
|
|
108
|
+
currency: currency == null ? void 0 : currency.toUpperCase()
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
function planEnrollmentData(properties) {
|
|
112
|
+
var _a;
|
|
113
|
+
const currency = readCurrency(properties);
|
|
114
|
+
const items = readItems(properties);
|
|
115
|
+
return {
|
|
116
|
+
type: "plan_enrollment",
|
|
117
|
+
plan_id: (_a = items == null ? void 0 : items[0]) == null ? void 0 : _a.item_id,
|
|
118
|
+
amount: toMinorUnits(readValue(properties), currency),
|
|
119
|
+
currency: currency == null ? void 0 : currency.toUpperCase(),
|
|
120
|
+
contents: mapContents(items, currency)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
function mapOAIEvent(name, properties) {
|
|
124
|
+
switch (name) {
|
|
125
|
+
case "page_view":
|
|
126
|
+
return { type: "page_viewed", data: contentsData(properties) };
|
|
127
|
+
case "view_item":
|
|
128
|
+
case "view_item_list":
|
|
129
|
+
return { type: "contents_viewed", data: contentsData(properties) };
|
|
130
|
+
case "begin_checkout":
|
|
131
|
+
return { type: "checkout_started", data: contentsData(properties) };
|
|
132
|
+
case "add_to_cart":
|
|
133
|
+
return { type: "items_added", data: contentsData(properties) };
|
|
134
|
+
case "purchase":
|
|
135
|
+
return { type: "order_created", data: contentsData(properties) };
|
|
136
|
+
case "generate_lead":
|
|
137
|
+
case "qualify_lead":
|
|
138
|
+
return { type: "lead_created", data: customerActionData(properties) };
|
|
139
|
+
case "sign_up":
|
|
140
|
+
case "login":
|
|
141
|
+
return { type: "registration_completed", data: customerActionData(properties) };
|
|
142
|
+
case "schedule":
|
|
143
|
+
return { type: "appointment_scheduled", data: customerActionData(properties) };
|
|
144
|
+
case "subscribe":
|
|
145
|
+
return { type: "subscription_created", data: planEnrollmentData(properties) };
|
|
146
|
+
case "trial_begin":
|
|
147
|
+
return { type: "trial_started", data: planEnrollmentData(properties) };
|
|
148
|
+
default: {
|
|
149
|
+
const currency = readCurrency(properties);
|
|
150
|
+
return {
|
|
151
|
+
type: "custom",
|
|
152
|
+
data: {
|
|
153
|
+
type: "custom",
|
|
154
|
+
amount: toMinorUnits(readValue(properties), currency),
|
|
155
|
+
currency: currency == null ? void 0 : currency.toUpperCase(),
|
|
156
|
+
contents: mapContents(readItems(properties), currency)
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
163
|
+
0 && (module.exports = {
|
|
164
|
+
NON_AD_EVENTS,
|
|
165
|
+
mapContents,
|
|
166
|
+
mapOAIEvent,
|
|
167
|
+
toMinorUnits
|
|
168
|
+
});
|
|
169
|
+
//# sourceMappingURL=oaiq.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/track/oaiq.ts"],"sourcesContent":["import type { Item } from './gtag';\nimport type { EventName, TrackName, TrackProperties } from './types';\n\nexport const NON_AD_EVENTS = [\n // metrics\n 'CLS',\n 'FCP',\n 'FID',\n 'INP',\n 'LCP',\n 'TTFB',\n // promotions\n 'view_promotion',\n 'select_promotion',\n];\n\n/**\n * Content item shared by `contents` and `plan_enrollment` events.\n * https://developers.openai.com/ads/supported-events\n */\nexport type ContentItem = {\n id?: string;\n name?: string;\n content_type?: string;\n quantity?: number;\n /** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n};\n\nexport type ContentsData = {\n type: 'contents';\n /** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomerActionData = {\n type: 'customer_action';\n amount?: number;\n currency?: string;\n};\n\nexport type PlanEnrollmentData = {\n type: 'plan_enrollment';\n plan_id?: string;\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type CustomEventData = {\n type: 'custom';\n amount?: number;\n currency?: string;\n contents?: ContentItem[];\n};\n\nexport type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;\n\n/**\n * Standard event names and the `data` shape each one expects.\n * https://developers.openai.com/ads/supported-events\n */\nexport type StandardEvents = {\n appointment_scheduled: CustomerActionData;\n checkout_started: ContentsData;\n contents_viewed: ContentsData;\n items_added: ContentsData;\n lead_created: CustomerActionData;\n order_created: ContentsData;\n page_viewed: ContentsData;\n registration_completed: CustomerActionData;\n subscription_created: PlanEnrollmentData;\n trial_started: PlanEnrollmentData;\n};\n\nexport type StandardEvent = keyof StandardEvents;\n\n/**\n * Identity fields passed to `oaiq(\"init\", ...)` for conversion matching. Email and external id\n * must be pre-hashed as lowercase 64-char SHA-256 hex strings; the rest are sent as raw values.\n * https://developers.openai.com/ads/measurement-pixel\n */\nexport type OAIQUser = {\n email_sha256?: string;\n external_id_sha256?: string;\n /** Two-letter ISO 3166-1 country code (e.g. \"US\"). */\n country?: string;\n /** Lowercased, max 128 characters. */\n city?: string;\n /** Max 32 characters. */\n zip_code?: string;\n};\n\nexport type InitConfig = {\n pixelId: string;\n /** Log SDK activity to the browser console. */\n debug?: boolean;\n user?: OAIQUser;\n};\n\n/**\n * Fourth argument of `oaiq(\"measure\", ...)`. Required for custom events (carries\n * `custom_event_name`); optional for standard events.\n */\nexport type MeasureOptions = {\n /** Shared with the Conversions API to deduplicate the same conversion across browser and server. */\n event_id?: string;\n /** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */\n custom_event_name?: string;\n /** When true, opts the event out of user-level personalization. */\n opt_out?: boolean;\n};\n\nexport interface OAIQ {\n oaiq(command: 'init', config: InitConfig): void;\n oaiq<T extends StandardEvent>(\n command: 'measure',\n event: T,\n data: StandardEvents[T],\n options?: MeasureOptions\n ): void;\n oaiq(\n command: 'measure',\n event: 'custom',\n data: CustomEventData,\n options: MeasureOptions & { custom_event_name: string }\n ): void;\n}\n\n/**\n * Currencies whose minor unit has 0 or 3 decimal places; everything else uses 2.\n * Follows Stripe's zero-decimal convention (e.g., MGA is treated as 0, ISK is included),\n * which can differ from strict ISO 4217 exponents.\n * https://docs.stripe.com/currencies#zero-decimal\n */\nconst ZERO_DECIMAL_CURRENCIES = new Set([\n 'BIF',\n 'CLP',\n 'DJF',\n 'GNF',\n 'ISK',\n 'JPY',\n 'KMF',\n 'KRW',\n 'MGA',\n 'PYG',\n 'RWF',\n 'UGX',\n 'VND',\n 'VUV',\n 'XAF',\n 'XOF',\n 'XPF',\n]);\nconst THREE_DECIMAL_CURRENCIES = new Set(['BHD', 'IQD', 'JOD', 'KWD', 'LYD', 'OMR', 'TND']);\n\n/** Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). */\nexport function toMinorUnits(value?: number, currency?: string): number | undefined {\n if (value === undefined || value === null || Number.isNaN(value)) return undefined;\n const code = currency?.toUpperCase();\n const exponent =\n code && ZERO_DECIMAL_CURRENCIES.has(code)\n ? 0\n : code && THREE_DECIMAL_CURRENCIES.has(code)\n ? 3\n : 2;\n return Math.round(value * 10 ** exponent);\n}\n\nexport function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined {\n if (!items || items.length === 0) return undefined;\n const code = currency?.toUpperCase();\n return items.map((item) => ({\n id: item.item_id,\n name: item.item_name,\n content_type: item.item_category,\n quantity: item.quantity,\n amount: toMinorUnits(item.price, currency),\n currency: item.price !== undefined ? code : undefined,\n }));\n}\n\n/** Safely read a property off loosely typed track properties without widening to `any`. */\nfunction prop(properties: unknown, key: string): unknown {\n return typeof properties === 'object' && properties !== null\n ? (properties as Record<string, unknown>)[key]\n : undefined;\n}\n\nfunction readValue(properties: unknown): number | undefined {\n const value = prop(properties, 'value');\n return typeof value === 'number' ? value : undefined;\n}\n\nfunction readCurrency(properties: unknown): string | undefined {\n const currency = prop(properties, 'currency');\n return typeof currency === 'string' ? currency : undefined;\n}\n\nfunction readItems(properties: unknown): Item[] | undefined {\n const items = prop(properties, 'items');\n return Array.isArray(items) ? (items as Item[]) : undefined;\n}\n\nfunction contentsData(properties: unknown): ContentsData {\n const currency = readCurrency(properties);\n return {\n type: 'contents',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n };\n}\n\nfunction customerActionData(properties: unknown): CustomerActionData {\n const currency = readCurrency(properties);\n return {\n type: 'customer_action',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n };\n}\n\nfunction planEnrollmentData(properties: unknown): PlanEnrollmentData {\n const currency = readCurrency(properties);\n const items = readItems(properties);\n return {\n type: 'plan_enrollment',\n plan_id: items?.[0]?.item_id,\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(items, currency),\n };\n}\n\nexport type MappedOAIEvent = {\n type: StandardEvent | 'custom';\n data: EventData;\n};\n\n/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */\nexport function mapOAIEvent<T extends EventName>(\n name: TrackName<T>,\n properties?: TrackProperties<T>\n): MappedOAIEvent {\n switch (name) {\n case 'page_view':\n return { type: 'page_viewed', data: contentsData(properties) };\n case 'view_item':\n case 'view_item_list':\n return { type: 'contents_viewed', data: contentsData(properties) };\n case 'begin_checkout':\n return { type: 'checkout_started', data: contentsData(properties) };\n case 'add_to_cart':\n return { type: 'items_added', data: contentsData(properties) };\n case 'purchase':\n return { type: 'order_created', data: contentsData(properties) };\n case 'generate_lead':\n case 'qualify_lead':\n return { type: 'lead_created', data: customerActionData(properties) };\n case 'sign_up':\n case 'login':\n return { type: 'registration_completed', data: customerActionData(properties) };\n case 'schedule':\n return { type: 'appointment_scheduled', data: customerActionData(properties) };\n case 'subscribe':\n return { type: 'subscription_created', data: planEnrollmentData(properties) };\n case 'trial_begin':\n return { type: 'trial_started', data: planEnrollmentData(properties) };\n default: {\n const currency = readCurrency(properties);\n return {\n type: 'custom',\n data: {\n type: 'custom',\n amount: toMinorUnits(readValue(properties), currency),\n currency: currency?.toUpperCase(),\n contents: mapContents(readItems(properties), currency),\n },\n };\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAGO,IAAM,gBAAgB;AAAA;AAAA,EAE3B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AACF;AA4HA,IAAM,0BAA0B,oBAAI,IAAI;AAAA,EACtC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,2BAA2B,oBAAI,IAAI,CAAC,OAAO,OAA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AAU,EAAE;AAAA,IAC/E,KAAK;AACH,aAAO,EAAE,MAAM,wBAAwB,MAAM,mBAAmB,UAAU,EAAE;AAAA,IAC9E,KAAK;AACH,aAAO,EAAE,MAAM,iBAAiB,MAAM,mBAAmB,UAAU,EAAE;AAAA,IACvE,SAAS;AACP,YAAM,WAAW,aAAa,UAAU;AACxC,aAAO;AAAA,QACL,MAAM;AAAA,QACN,MAAM;AAAA,UACJ,MAAM;AAAA,UACN,QAAQ,aAAa,UAAU,UAAU,GAAG,QAAQ;AAAA,UACpD,UAAU,qCAAU;AAAA,UACpB,UAAU,YAAY,UAAU,UAAU,GAAG,QAAQ;AAAA,QACvD;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":[]}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Item } from './gtag.cjs';
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from './types.cjs';
|
|
3
|
+
|
|
4
|
+
declare const NON_AD_EVENTS: string[];
|
|
5
|
+
/**
|
|
6
|
+
* Content item shared by `contents` and `plan_enrollment` events.
|
|
7
|
+
* https://developers.openai.com/ads/supported-events
|
|
8
|
+
*/
|
|
9
|
+
type ContentItem = {
|
|
10
|
+
id?: string;
|
|
11
|
+
name?: string;
|
|
12
|
+
content_type?: string;
|
|
13
|
+
quantity?: number;
|
|
14
|
+
/** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */
|
|
15
|
+
amount?: number;
|
|
16
|
+
currency?: string;
|
|
17
|
+
};
|
|
18
|
+
type ContentsData = {
|
|
19
|
+
type: 'contents';
|
|
20
|
+
/** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */
|
|
21
|
+
amount?: number;
|
|
22
|
+
currency?: string;
|
|
23
|
+
contents?: ContentItem[];
|
|
24
|
+
};
|
|
25
|
+
type CustomerActionData = {
|
|
26
|
+
type: 'customer_action';
|
|
27
|
+
amount?: number;
|
|
28
|
+
currency?: string;
|
|
29
|
+
};
|
|
30
|
+
type PlanEnrollmentData = {
|
|
31
|
+
type: 'plan_enrollment';
|
|
32
|
+
plan_id?: string;
|
|
33
|
+
amount?: number;
|
|
34
|
+
currency?: string;
|
|
35
|
+
contents?: ContentItem[];
|
|
36
|
+
};
|
|
37
|
+
type CustomEventData = {
|
|
38
|
+
type: 'custom';
|
|
39
|
+
amount?: number;
|
|
40
|
+
currency?: string;
|
|
41
|
+
contents?: ContentItem[];
|
|
42
|
+
};
|
|
43
|
+
type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;
|
|
44
|
+
/**
|
|
45
|
+
* Standard event names and the `data` shape each one expects.
|
|
46
|
+
* https://developers.openai.com/ads/supported-events
|
|
47
|
+
*/
|
|
48
|
+
type StandardEvents = {
|
|
49
|
+
appointment_scheduled: CustomerActionData;
|
|
50
|
+
checkout_started: ContentsData;
|
|
51
|
+
contents_viewed: ContentsData;
|
|
52
|
+
items_added: ContentsData;
|
|
53
|
+
lead_created: CustomerActionData;
|
|
54
|
+
order_created: ContentsData;
|
|
55
|
+
page_viewed: ContentsData;
|
|
56
|
+
registration_completed: CustomerActionData;
|
|
57
|
+
subscription_created: PlanEnrollmentData;
|
|
58
|
+
trial_started: PlanEnrollmentData;
|
|
59
|
+
};
|
|
60
|
+
type StandardEvent = keyof StandardEvents;
|
|
61
|
+
/**
|
|
62
|
+
* Identity fields passed to `oaiq("init", ...)` for conversion matching. Email and external id
|
|
63
|
+
* must be pre-hashed as lowercase 64-char SHA-256 hex strings; the rest are sent as raw values.
|
|
64
|
+
* https://developers.openai.com/ads/measurement-pixel
|
|
65
|
+
*/
|
|
66
|
+
type OAIQUser = {
|
|
67
|
+
email_sha256?: string;
|
|
68
|
+
external_id_sha256?: string;
|
|
69
|
+
/** Two-letter ISO 3166-1 country code (e.g. "US"). */
|
|
70
|
+
country?: string;
|
|
71
|
+
/** Lowercased, max 128 characters. */
|
|
72
|
+
city?: string;
|
|
73
|
+
/** Max 32 characters. */
|
|
74
|
+
zip_code?: string;
|
|
75
|
+
};
|
|
76
|
+
type InitConfig = {
|
|
77
|
+
pixelId: string;
|
|
78
|
+
/** Log SDK activity to the browser console. */
|
|
79
|
+
debug?: boolean;
|
|
80
|
+
user?: OAIQUser;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Fourth argument of `oaiq("measure", ...)`. Required for custom events (carries
|
|
84
|
+
* `custom_event_name`); optional for standard events.
|
|
85
|
+
*/
|
|
86
|
+
type MeasureOptions = {
|
|
87
|
+
/** Shared with the Conversions API to deduplicate the same conversion across browser and server. */
|
|
88
|
+
event_id?: string;
|
|
89
|
+
/** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */
|
|
90
|
+
custom_event_name?: string;
|
|
91
|
+
/** When true, opts the event out of user-level personalization. */
|
|
92
|
+
opt_out?: boolean;
|
|
93
|
+
};
|
|
94
|
+
interface OAIQ {
|
|
95
|
+
oaiq(command: 'init', config: InitConfig): void;
|
|
96
|
+
oaiq<T extends StandardEvent>(command: 'measure', event: T, data: StandardEvents[T], options?: MeasureOptions): void;
|
|
97
|
+
oaiq(command: 'measure', event: 'custom', data: CustomEventData, options: MeasureOptions & {
|
|
98
|
+
custom_event_name: string;
|
|
99
|
+
}): void;
|
|
100
|
+
}
|
|
101
|
+
/** Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). */
|
|
102
|
+
declare function toMinorUnits(value?: number, currency?: string): number | undefined;
|
|
103
|
+
declare function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined;
|
|
104
|
+
type MappedOAIEvent = {
|
|
105
|
+
type: StandardEvent | 'custom';
|
|
106
|
+
data: EventData;
|
|
107
|
+
};
|
|
108
|
+
/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */
|
|
109
|
+
declare function mapOAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): MappedOAIEvent;
|
|
110
|
+
|
|
111
|
+
export { type ContentItem, type ContentsData, type CustomEventData, type CustomerActionData, type EventData, type InitConfig, type MappedOAIEvent, type MeasureOptions, NON_AD_EVENTS, type OAIQ, type OAIQUser, type PlanEnrollmentData, type StandardEvent, type StandardEvents, mapContents, mapOAIEvent, toMinorUnits };
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { Item } from './gtag.js';
|
|
2
|
+
import { EventName, TrackName, TrackProperties } from './types.js';
|
|
3
|
+
|
|
4
|
+
declare const NON_AD_EVENTS: string[];
|
|
5
|
+
/**
|
|
6
|
+
* Content item shared by `contents` and `plan_enrollment` events.
|
|
7
|
+
* https://developers.openai.com/ads/supported-events
|
|
8
|
+
*/
|
|
9
|
+
type ContentItem = {
|
|
10
|
+
id?: string;
|
|
11
|
+
name?: string;
|
|
12
|
+
content_type?: string;
|
|
13
|
+
quantity?: number;
|
|
14
|
+
/** Per-item monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */
|
|
15
|
+
amount?: number;
|
|
16
|
+
currency?: string;
|
|
17
|
+
};
|
|
18
|
+
type ContentsData = {
|
|
19
|
+
type: 'contents';
|
|
20
|
+
/** Monetary value in ISO 4217 minor units (e.g., 12,999 = $129.99 USD). */
|
|
21
|
+
amount?: number;
|
|
22
|
+
currency?: string;
|
|
23
|
+
contents?: ContentItem[];
|
|
24
|
+
};
|
|
25
|
+
type CustomerActionData = {
|
|
26
|
+
type: 'customer_action';
|
|
27
|
+
amount?: number;
|
|
28
|
+
currency?: string;
|
|
29
|
+
};
|
|
30
|
+
type PlanEnrollmentData = {
|
|
31
|
+
type: 'plan_enrollment';
|
|
32
|
+
plan_id?: string;
|
|
33
|
+
amount?: number;
|
|
34
|
+
currency?: string;
|
|
35
|
+
contents?: ContentItem[];
|
|
36
|
+
};
|
|
37
|
+
type CustomEventData = {
|
|
38
|
+
type: 'custom';
|
|
39
|
+
amount?: number;
|
|
40
|
+
currency?: string;
|
|
41
|
+
contents?: ContentItem[];
|
|
42
|
+
};
|
|
43
|
+
type EventData = ContentsData | CustomerActionData | PlanEnrollmentData | CustomEventData;
|
|
44
|
+
/**
|
|
45
|
+
* Standard event names and the `data` shape each one expects.
|
|
46
|
+
* https://developers.openai.com/ads/supported-events
|
|
47
|
+
*/
|
|
48
|
+
type StandardEvents = {
|
|
49
|
+
appointment_scheduled: CustomerActionData;
|
|
50
|
+
checkout_started: ContentsData;
|
|
51
|
+
contents_viewed: ContentsData;
|
|
52
|
+
items_added: ContentsData;
|
|
53
|
+
lead_created: CustomerActionData;
|
|
54
|
+
order_created: ContentsData;
|
|
55
|
+
page_viewed: ContentsData;
|
|
56
|
+
registration_completed: CustomerActionData;
|
|
57
|
+
subscription_created: PlanEnrollmentData;
|
|
58
|
+
trial_started: PlanEnrollmentData;
|
|
59
|
+
};
|
|
60
|
+
type StandardEvent = keyof StandardEvents;
|
|
61
|
+
/**
|
|
62
|
+
* Identity fields passed to `oaiq("init", ...)` for conversion matching. Email and external id
|
|
63
|
+
* must be pre-hashed as lowercase 64-char SHA-256 hex strings; the rest are sent as raw values.
|
|
64
|
+
* https://developers.openai.com/ads/measurement-pixel
|
|
65
|
+
*/
|
|
66
|
+
type OAIQUser = {
|
|
67
|
+
email_sha256?: string;
|
|
68
|
+
external_id_sha256?: string;
|
|
69
|
+
/** Two-letter ISO 3166-1 country code (e.g. "US"). */
|
|
70
|
+
country?: string;
|
|
71
|
+
/** Lowercased, max 128 characters. */
|
|
72
|
+
city?: string;
|
|
73
|
+
/** Max 32 characters. */
|
|
74
|
+
zip_code?: string;
|
|
75
|
+
};
|
|
76
|
+
type InitConfig = {
|
|
77
|
+
pixelId: string;
|
|
78
|
+
/** Log SDK activity to the browser console. */
|
|
79
|
+
debug?: boolean;
|
|
80
|
+
user?: OAIQUser;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Fourth argument of `oaiq("measure", ...)`. Required for custom events (carries
|
|
84
|
+
* `custom_event_name`); optional for standard events.
|
|
85
|
+
*/
|
|
86
|
+
type MeasureOptions = {
|
|
87
|
+
/** Shared with the Conversions API to deduplicate the same conversion across browser and server. */
|
|
88
|
+
event_id?: string;
|
|
89
|
+
/** Required for custom events; 1-64 chars of letters, numbers, underscores, or dashes. */
|
|
90
|
+
custom_event_name?: string;
|
|
91
|
+
/** When true, opts the event out of user-level personalization. */
|
|
92
|
+
opt_out?: boolean;
|
|
93
|
+
};
|
|
94
|
+
interface OAIQ {
|
|
95
|
+
oaiq(command: 'init', config: InitConfig): void;
|
|
96
|
+
oaiq<T extends StandardEvent>(command: 'measure', event: T, data: StandardEvents[T], options?: MeasureOptions): void;
|
|
97
|
+
oaiq(command: 'measure', event: 'custom', data: CustomEventData, options: MeasureOptions & {
|
|
98
|
+
custom_event_name: string;
|
|
99
|
+
}): void;
|
|
100
|
+
}
|
|
101
|
+
/** Convert a major-unit amount (e.g., 129.99) into ISO 4217 minor units (e.g., 12,999). */
|
|
102
|
+
declare function toMinorUnits(value?: number, currency?: string): number | undefined;
|
|
103
|
+
declare function mapContents(items?: Item[], currency?: string): ContentItem[] | undefined;
|
|
104
|
+
type MappedOAIEvent = {
|
|
105
|
+
type: StandardEvent | 'custom';
|
|
106
|
+
data: EventData;
|
|
107
|
+
};
|
|
108
|
+
/** Map an internal track event onto an OpenAI standard (or custom) conversion event. */
|
|
109
|
+
declare function mapOAIEvent<T extends EventName>(name: TrackName<T>, properties?: TrackProperties<T>): MappedOAIEvent;
|
|
110
|
+
|
|
111
|
+
export { type ContentItem, type ContentsData, type CustomEventData, type CustomerActionData, type EventData, type InitConfig, type MappedOAIEvent, type MeasureOptions, NON_AD_EVENTS, type OAIQ, type OAIQUser, type PlanEnrollmentData, type StandardEvent, type StandardEvents, mapContents, mapOAIEvent, toMinorUnits };
|