@bizfly/cdp-web 0.0.0-stage → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3447 @@
1
+ // src/generated/catalog.runtime.json
2
+ var catalog_runtime_default = { version: "0.2", params: { account_number: { type: "string", sensitive: true }, account_type: { type: "string", enum: ["current", "fancy_number", "business", "joint", "payroll"] }, acquisition_source: { type: "string", enum: ["organic", "referral", "rm", "partner", "paid_ads", "branch", "other"] }, action_result: { type: "string", enum: ["executed", "skipped", "failed"] }, answer_id: { type: "string" }, answer_text: { type: "string", free: true }, applicable_product: { type: "string" }, attempt_no: { type: "number" }, attribution_window_hours: { type: "number" }, auth_method: { type: "string", enum: ["soft_otp", "sms_otp", "face_biometric", "fingerprint", "pin", "password"] }, auth_requirement: { type: "string", enum: ["single_txn_over_10m", "daily_total_over_20m", "new_device", "no_biometric_on_file"] }, auto_deposit_amount: { type: "number" }, auto_deposit_frequency: { type: "string", enum: ["daily", "weekly", "monthly"] }, bill_saved: { type: "boolean" }, bounce_type: { type: "string", enum: ["hard", "soft"] }, business_type: { type: "string", enum: ["household_business", "sole_proprietor", "sme"] }, button_id: { type: "string" }, button_text: { type: "string", free: true }, call_duration: { type: "number" }, call_result: { type: "string", enum: ["answered", "no_answer", "busy", "rejected", "invalid_number", "provider_error"] }, card_brand: { type: "string", enum: ["visa", "mastercard", "jcb", "amex", "unionpay", "napas"] }, card_form: { type: "string", enum: ["physical", "virtual"] }, card_id: { type: "string" }, card_product: { type: "string" }, card_txn_channel: { type: "string", enum: ["pos", "contactless", "ecom", "atm", "qr", "recurring"] }, card_type: { type: "string", enum: ["credit", "debit", "prepaid"] }, change_amount: { type: "number", sensitive: true }, change_source: { type: "string", enum: ["app_settings", "web_settings", "lead_form", "email_link", "sms_keyword", "zalo", "branch", "api", "admin"] }, click_action: { type: "string", enum: ["deeplink", "url", "go_to_page", "dismiss", "open_settings", "request_push_permission", "trigger_event", "update_attribute", "copy_code"] }, consent_status: { type: "string", enum: ["granted", "withdrawn"] }, consent_type: { type: "string" }, conversion_event: { type: "string" }, conversion_event_id: { type: "string" }, conversion_value: { type: "number" }, cost: { type: "number" }, counterparty_bank_code: { type: "string" }, coupon_code: { type: "string" }, coupon_list_id: { type: "string" }, credit_limit: { type: "number", sensitive: true }, currency: { type: "string" }, debt_group: { type: "number", sensitive: true, enum: ["1", "2", "3", "4", "5"] }, deep_link: { type: "string" }, disbursement_mode: { type: "string", enum: ["instant", "separate"] }, dismiss_type: { type: "string", enum: ["close_button", "auto_close", "tap_outside", "back", "app_exit"] }, document_type: { type: "string", enum: ["cccd_chip", "cccd", "cmnd", "passport"] }, dpd: { type: "number" }, due_date: { type: "date" }, earn_rule: { type: "string" }, eligible_amount: { type: "number" }, email: { type: "string", sensitive: true }, endpoint_id: { type: "string" }, entry_point: { type: "string", enum: ["home_shortcut", "menu", "search", "banner", "push", "inapp", "inbox", "deeplink", "qr", "contact", "chat", "paste_text", "partner_hub", "cross_sell", "other"] }, entry_reason: { type: "string", enum: ["natural", "re_entry", "merged"] }, error_code: { type: "string" }, error_message: { type: "string", free: true }, exit_reason: { type: "string", enum: ["completed", "goal_reached", "exit_rule", "dropped", "journey_stopped", "merged", "unreachable"] }, expiry_time: { type: "datetime" }, failure_reason: { type: "string", enum: ["invalid_token", "opted_out", "no_address", "invalid_address", "provider_rejected", "expired", "quota", "template_invalid", "timeout", "unknown"] }, fee_amount: { type: "number" }, fields_submitted: { type: "string[]" }, flag_source: { type: "string", free: true }, flag_values: { type: "string[]" }, form_data: { type: "string", sensitive: true }, form_id: { type: "string" }, form_name: { type: "string" }, from_channel: { type: "string" }, funding_source: { type: "string", enum: ["account", "credit_card", "debit_card", "loyalty_points", "account_points", "card_points", "overdraft"] }, game_type: { type: "string", enum: ["spin_wheel", "scratch_card", "gift_box", "quiz"] }, goal_id: { type: "string" }, http_status: { type: "number" }, human_open: { type: "boolean" }, identify_type: { type: "string", enum: ["login", "identifier_change", "account_switch", "server_request"] }, image_url: { type: "string" }, inapp_id: { type: "string" }, inbox_message_id: { type: "string" }, industry_code: { type: "string" }, inference_source: { type: "string", enum: ["push_token_invalid", "inactivity"] }, insurance_type: { type: "string", enum: ["life", "health", "accident", "motor", "card_protection", "fraud_protection", "travel", "home"] }, interest_payment_method: { type: "string", enum: ["end_of_term", "monthly", "quarterly", "upfront"] }, investment_type: { type: "string", enum: ["securities", "fund", "bond", "gold", "certificate"] }, is_international: { type: "boolean" }, is_reinstall: { type: "boolean" }, is_win: { type: "boolean" }, issue_type: { type: "string", enum: ["new", "reissue", "replacement", "preapproved_limit"] }, ivr_input: { type: "string" }, landing_url: { type: "string" }, launch_source: { type: "string", enum: ["direct", "push", "deeplink", "inbox", "widget"] }, link_id: { type: "string" }, loan_action: { type: "string", enum: ["new_loan", "limit_adjust", "top_up", "repayment", "settlement"] }, loan_id: { type: "string" }, login_method: { type: "string", enum: ["password", "fingerprint", "face_id", "soft_otp", "qr_login"] }, logout_reason: { type: "string", enum: ["user", "timeout", "forced", "account_switch"] }, machine_open: { type: "boolean" }, maturity_date: { type: "date" }, mcc: { type: "string" }, merchant_country: { type: "string" }, merchant_name: { type: "string", free: true }, message_text: { type: "string", free: true }, new_balance: { type: "number", sensitive: true }, node_id: { type: "string" }, node_type: { type: "string", enum: ["message", "wait", "wait_for_event", "condition", "ab_split", "update_attribute", "add_to_segment", "remove_from_segment", "webhook"] }, not_displayed_reason: { type: "string", enum: ["stale_instruction", "page_mismatch", "invalid_content", "unsupported", "media_load_failed"] }, offer_id: { type: "string" }, offer_name: { type: "string", free: true }, overdue_amount: { type: "number", sensitive: true }, page_count: { type: "number" }, page_index: { type: "number" }, page_title: { type: "string", free: true }, partner_name: { type: "string" }, payment_mode: { type: "string", enum: ["one_time", "recurring"] }, permission_status: { type: "string", enum: ["granted", "denied", "provisional", "not_determined"] }, points: { type: "number" }, policy_number: { type: "string" }, position: { type: "number" }, previous_app_version: { type: "string" }, previous_screen_name: { type: "string" }, previous_status: { type: "string" }, prize_id: { type: "string" }, product_id: { type: "string" }, product_name: { type: "string", free: true }, product_type: { type: "string" }, promotion_code: { type: "string", free: true }, prompt_type: { type: "string", enum: ["soft", "native"] }, provider_status_code: { type: "string" }, push_provider: { type: "string", enum: ["fcm", "apns", "hms"] }, qr_type: { type: "string", enum: ["vietqr_transfer", "merchant_qr", "international_qr", "atm_withdrawal"] }, question_id: { type: "string" }, question_text: { type: "string", free: true }, question_type: { type: "string", enum: ["single_choice", "multi_choice", "rating", "nps", "text"] }, referral_code: { type: "string", free: true }, referral_milestone: { type: "number" }, referred_customer_id: { type: "string", sensitive: true }, repay_type: { type: "string", enum: ["installment", "partial", "full"] }, reply_text: { type: "string", free: true }, resolution_case: { type: "number" }, response_time_ms: { type: "number" }, result_count: { type: "number" }, result_position: { type: "number" }, result_title: { type: "string", free: true }, reward_name: { type: "string", free: true }, rm_code: { type: "string" }, rolled_over: { type: "boolean" }, rollover_type: { type: "string", enum: ["principal_and_interest", "principal_only", "no_rollover"] }, savings_account_number: { type: "string", sensitive: true }, score: { type: "number" }, screen_name: { type: "string" }, search_keyword: { type: "string", free: true }, segment_count: { type: "number" }, sender_id: { type: "string" }, service_type: { type: "string", enum: ["electricity", "water", "internet", "telco_postpaid", "tv", "tuition", "insurance_premium", "tax", "fee", "other"] }, slot_id: { type: "string" }, source_profile_id: { type: "string" }, status: { type: "string", enum: ["success", "pending", "fail"] }, step_name: { type: "string" }, step_no: { type: "number" }, step_result: { type: "string", enum: ["pass", "fail", "manual_review"] }, subject: { type: "string", free: true }, suppression_level: { type: "string", enum: ["global", "channel", "campaign"] }, suppression_reason: { type: "string", enum: ["frequency_cap", "dnd", "opted_out", "block_list", "no_address", "priority_lost", "message_spacing", "consent_missing", "profile_erased"] }, survey_id: { type: "string" }, target_profile_id: { type: "string" }, template_id: { type: "string" }, term: { type: "string" }, title: { type: "string", free: true }, to_channel: { type: "string" }, topic_id: { type: "string" }, transaction_amount: { type: "number" }, transaction_category: { type: "string", enum: ["salary", "transfer_in", "cash_deposit", "interest", "refund", "loan_disbursement", "card_payment", "bill_payment", "transfer_out", "other"] }, transaction_id: { type: "string" }, transfer_type: { type: "string", enum: ["own_account", "internal", "interbank_fast", "interbank_normal", "card", "international", "split", "scheduled"] }, unsubscribe_type: { type: "string", enum: ["global", "topic"] }, update_flow: { type: "string", enum: ["update", "change"] }, url: { type: "string" }, verification_method: { type: "string", enum: ["nfc_chip", "vneid", "ocr", "face_match", "branch"] }, voucher_code: { type: "string", free: true }, voucher_name: { type: "string", free: true }, wallet_provider: { type: "string", enum: ["apple_pay", "google_pay", "samsung_pay", "garmin_pay", "none"] }, zalo_user_id: { type: "string", sensitive: true } }, attributes: { profile_id: { type: "string", platformOnly: true }, profile_state: { type: "string", platformOnly: true }, created_date: { type: "datetime", platformOnly: true }, last_update_date: { type: "datetime", platformOnly: true }, identified_date: { type: "datetime", platformOnly: true }, first_seen_date: { type: "datetime", platformOnly: true }, last_seen_date: { type: "datetime", platformOnly: true }, last_active_channel: { type: "string", platformOnly: true }, last_app_open_date: { type: "datetime", platformOnly: true }, is_test_profile: { type: "boolean", platformOnly: true }, customer_id: { type: "string", identifier: true }, national_id: { type: "string", identifier: true }, phone_number: { type: "string", identifier: true }, email: { type: "string", identifier: true }, advertising_id: { type: "string", identifier: true }, full_name: { type: "string" }, first_name: { type: "string" }, last_name: { type: "string" }, gender: { type: "string" }, birthday: { type: "date" }, age: { type: "number", platformOnly: true }, city: { type: "string" }, country: { type: "string" }, language: { type: "string" }, platform: { type: "string" }, os_version: { type: "string" }, device_model: { type: "string" }, carrier: { type: "string" }, app_version: { type: "string" }, sdk_version: { type: "string" }, app_language: { type: "string" }, device_language: { type: "string" }, timezone: { type: "string" }, udid: { type: "string" }, push_provider: { type: "string" }, app_install_date: { type: "datetime", platformOnly: true }, app_uninstall_date: { type: "datetime", platformOnly: true }, is_app_installed: { type: "boolean", platformOnly: true }, app_login_status: { type: "boolean" }, web_device_type: { type: "string" }, app_push_optin: { type: "boolean" }, web_push_optin: { type: "boolean" }, email_optin: { type: "boolean" }, sms_optin: { type: "boolean" }, zns_optin: { type: "boolean" }, zalo_oa_follower: { type: "boolean", platformOnly: true }, autocall_optin: { type: "boolean" }, location_optin: { type: "boolean" }, data_processing_consent: { type: "boolean" }, unsubscribed_topics: { type: "string[]", platformOnly: true }, email_global_unsubscribe: { type: "boolean", platformOnly: true }, email_bounced: { type: "boolean", platformOnly: true }, email_blocked: { type: "boolean", platformOnly: true }, email_spam_reported: { type: "boolean", platformOnly: true }, email_invalid: { type: "boolean", platformOnly: true }, email_verified: { type: "boolean" }, last_push_sent_date: { type: "datetime", platformOnly: true }, last_push_open_date: { type: "datetime", platformOnly: true }, last_email_open_date: { type: "datetime", platformOnly: true }, last_email_click_date: { type: "datetime", platformOnly: true }, last_email_unsubscribe_date: { type: "datetime", platformOnly: true }, active_journey_ids: { type: "string[]", platformOnly: true }, active_journey_names: { type: "string[]", platformOnly: true }, static_segment_ids: { type: "string[]", platformOnly: true }, customer_tier: { type: "string" }, customer_type: { type: "string" }, customer_since_date: { type: "date" }, home_branch_code: { type: "string" }, rm_code: { type: "string" }, is_employee: { type: "boolean" }, is_payroll_customer: { type: "boolean" }, acquisition_source: { type: "string" }, customer_flags: { type: "string[]" }, is_active_customer: { type: "boolean" }, active_last_year: { type: "boolean" }, last_financial_transaction_date: { type: "datetime" }, has_logged_in_app: { type: "boolean" }, digital_banking_registered_date: { type: "date" }, kyc_level: { type: "string" }, biometric_nfc_status: { type: "string" }, identity_document_expiry_date: { type: "date" }, device_nfc_supported: { type: "boolean" }, debt_group: { type: "number" }, card_credit_limit_total: { type: "number" }, card_credit_limit_available: { type: "number" }, loyalty_points_balance: { type: "number" }, loyalty_tier: { type: "string" }, linked_wallets: { type: "string[]" }, soft_otp_registered: { type: "boolean" } }, events: { mobile_app_open: { name: "mobile_app_open", web: false, app: true }, app_install: { name: "app_install", web: false, app: true }, app_update: { name: "app_update", web: false, app: true }, app_uninstall: { name: "app_uninstall", web: false, app: false }, push_token_refreshed: { name: "push_token_refreshed", web: false, app: true }, push_permission_changed: { name: "push_permission_changed", web: false, app: true }, screen_view: { name: "screen_view", web: false, app: true }, user_identified: { name: "user_identified", web: false, app: false }, user_logout: { name: "user_logout", web: true, app: true, sendMode: "batch", params: { logout_reason: { type: "string" } } }, profile_created: { name: "profile_created", web: false, app: false }, profile_merged: { name: "profile_merged", web: false, app: false }, session_start: { name: "session_start", web: true, app: false, sendMode: "realtime", params: { landing_url: { type: "string", required: true } } }, page_view: { name: "page_view", web: true, app: false, sendMode: "batch", params: { page_title: { type: "string" } } }, consent_updated: { name: "consent_updated", web: true, app: true, sendMode: "realtime", params: { consent_type: { type: "string", required: true }, consent_status: { type: "string", required: true }, change_source: { type: "string", required: true }, channel: { type: "string" } } }, channel_subscription_changed: { name: "channel_subscription_changed", web: false, app: false }, push_sent: { name: "push_sent", web: false, app: false }, push_failed: { name: "push_failed", web: false, app: false }, push_delivered: { name: "push_delivered", web: false, app: true }, push_session: { name: "push_session", web: false, app: true }, push_action_clicked: { name: "push_action_clicked", web: false, app: true }, inapp_seen: { name: "inapp_seen", web: false, app: true }, inapp_clicked: { name: "inapp_clicked", web: false, app: true }, inapp_dismissed: { name: "inapp_dismissed", web: false, app: true }, inapp_not_displayed: { name: "inapp_not_displayed", web: false, app: true }, survey_result: { name: "survey_result", web: true, app: true, sendMode: "realtime", correlation: true, params: { survey_id: { type: "string", required: true }, question_id: { type: "string", required: true }, question_text: { type: "string" }, question_type: { type: "string", required: true }, answer_id: { type: "string" }, answer_text: { type: "string" }, score: { type: "number" } } }, lead_collected: { name: "lead_collected", web: true, app: true, sendMode: "realtime", correlation: true, params: { form_id: { type: "string", required: true }, fields_submitted: { type: "string[]", required: true } } }, gamification_played: { name: "gamification_played", web: true, app: true, sendMode: "realtime", correlation: true, params: { game_type: { type: "string", required: true }, is_win: { type: "boolean", required: true }, prize_id: { type: "string" } } }, coupon_assigned: { name: "coupon_assigned", web: false, app: false }, coupon_redeemed: { name: "coupon_redeemed", web: false, app: false }, banner_seen: { name: "banner_seen", web: false, app: true }, banner_click: { name: "banner_click", web: false, app: true }, inbox_message_received: { name: "inbox_message_received", web: false, app: false }, inbox_message_viewed: { name: "inbox_message_viewed", web: false, app: true }, inbox_message_clicked: { name: "inbox_message_clicked", web: false, app: true }, inbox_message_deleted: { name: "inbox_message_deleted", web: false, app: true }, web_push_subscribed: { name: "web_push_subscribed", web: true, app: false, sendMode: "realtime", params: { prompt_type: { type: "string" } } }, web_push_unsubscribed: { name: "web_push_unsubscribed", web: true, app: false, sendMode: "realtime", params: {} }, web_push_sent: { name: "web_push_sent", web: false, app: false }, web_push_delivered: { name: "web_push_delivered", web: true, app: false, sendMode: "realtime", correlation: true, params: {} }, web_push_clicked: { name: "web_push_clicked", web: true, app: false, sendMode: "realtime", correlation: true, params: { url: { type: "string" } } }, web_popup_seen: { name: "web_popup_seen", web: true, app: false, sendMode: "realtime", correlation: true, params: { inapp_id: { type: "string", required: true } } }, web_popup_clicked: { name: "web_popup_clicked", web: true, app: false, sendMode: "realtime", correlation: true, params: { inapp_id: { type: "string", required: true }, click_action: { type: "string", required: true }, button_text: { type: "string" }, url: { type: "string" } } }, web_popup_dismissed: { name: "web_popup_dismissed", web: true, app: false, sendMode: "realtime", correlation: true, params: { inapp_id: { type: "string", required: true }, dismiss_type: { type: "string", required: true } } }, web_banner_seen: { name: "web_banner_seen", web: true, app: false, sendMode: "realtime", correlation: true, params: { slot_id: { type: "string", required: true }, position: { type: "number" } } }, web_banner_clicked: { name: "web_banner_clicked", web: true, app: false, sendMode: "realtime", correlation: true, params: { slot_id: { type: "string", required: true }, position: { type: "number" }, url: { type: "string" } } }, email_sent: { name: "email_sent", web: false, app: false }, email_delivered: { name: "email_delivered", web: false, app: false }, email_dropped: { name: "email_dropped", web: false, app: false }, email_bounce: { name: "email_bounce", web: false, app: false }, email_blocked: { name: "email_blocked", web: false, app: false }, email_open: { name: "email_open", web: false, app: false }, email_clicked: { name: "email_clicked", web: false, app: false }, email_spamreport: { name: "email_spamreport", web: false, app: false }, email_unsubscribe: { name: "email_unsubscribe", web: false, app: false }, email_resubscribe: { name: "email_resubscribe", web: false, app: false }, sms_sent: { name: "sms_sent", web: false, app: false }, sms_delivered: { name: "sms_delivered", web: false, app: false }, sms_failed: { name: "sms_failed", web: false, app: false }, sms_clicked: { name: "sms_clicked", web: false, app: false }, sms_reply: { name: "sms_reply", web: false, app: false }, zns_sent: { name: "zns_sent", web: false, app: false }, zns_delivered: { name: "zns_delivered", web: false, app: false }, zns_failed: { name: "zns_failed", web: false, app: false }, zns_clicked: { name: "zns_clicked", web: false, app: false }, zalo_oa_follow: { name: "zalo_oa_follow", web: false, app: false }, zalo_oa_unfollow: { name: "zalo_oa_unfollow", web: false, app: false }, zalo_oa_sent: { name: "zalo_oa_sent", web: false, app: false }, zalo_oa_delivered: { name: "zalo_oa_delivered", web: false, app: false }, zalo_oa_seen: { name: "zalo_oa_seen", web: false, app: false }, zalo_oa_clicked: { name: "zalo_oa_clicked", web: false, app: false }, zalo_oa_failed: { name: "zalo_oa_failed", web: false, app: false }, zalo_oa_user_message: { name: "zalo_oa_user_message", web: false, app: false }, webhook_sent: { name: "webhook_sent", web: false, app: false }, webhook_failed: { name: "webhook_failed", web: false, app: false }, autocall_initiated: { name: "autocall_initiated", web: false, app: false }, autocall_completed: { name: "autocall_completed", web: false, app: false }, autocall_failed: { name: "autocall_failed", web: false, app: false }, message_suppressed: { name: "message_suppressed", web: false, app: false }, message_fallback_triggered: { name: "message_fallback_triggered", web: false, app: false }, campaign_conversion: { name: "campaign_conversion", web: false, app: false }, journey_enter: { name: "journey_enter", web: false, app: false }, journey_exit: { name: "journey_exit", web: false, app: false }, journey_action: { name: "journey_action", web: false, app: false }, journey_goal_reached: { name: "journey_goal_reached", web: false, app: false }, form_submitted: { name: "form_submitted", web: true, app: true, sendMode: "realtime", params: { form_id: { type: "string", required: true }, form_name: { type: "string" }, form_data: { type: "string" } } }, login_start: { name: "login_start", web: true, app: true, sendMode: "batch", params: { login_method: { type: "string" } } }, login_success: { name: "login_success", web: true, app: true, sendMode: "realtime", params: { login_method: { type: "string" } } }, login_fail: { name: "login_fail", web: true, app: true, sendMode: "realtime", params: { login_method: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, first_login: { name: "first_login", web: false, app: true }, app_reactivation_start: { name: "app_reactivation_start", web: false, app: true }, app_reactivation_success: { name: "app_reactivation_success", web: false, app: true }, app_reactivation_fail: { name: "app_reactivation_fail", web: false, app: true }, forgot_password_start: { name: "forgot_password_start", web: true, app: true, sendMode: "batch", params: {} }, forgot_password_success: { name: "forgot_password_success", web: true, app: true, sendMode: "realtime", params: {} }, change_password_start: { name: "change_password_start", web: true, app: true, sendMode: "batch", params: {} }, change_password_success: { name: "change_password_success", web: true, app: true, sendMode: "realtime", params: {} }, soft_otp_register_start: { name: "soft_otp_register_start", web: false, app: true }, soft_otp_register_success: { name: "soft_otp_register_success", web: false, app: true }, email_verify_start: { name: "email_verify_start", web: true, app: true, sendMode: "batch", params: { email: { type: "string" } } }, email_verify_success: { name: "email_verify_success", web: true, app: true, sendMode: "realtime", params: { email: { type: "string" } } }, transaction_auth_blocked: { name: "transaction_auth_blocked", web: false, app: true }, transaction_auth_fail: { name: "transaction_auth_fail", web: false, app: true }, onboarding_start: { name: "onboarding_start", web: true, app: true, sendMode: "realtime", params: { acquisition_source: { type: "string" }, referral_code: { type: "string" } } }, onboarding_step_completed: { name: "onboarding_step_completed", web: true, app: true, sendMode: "realtime", params: { step_no: { type: "number", required: true }, step_name: { type: "string", required: true }, step_result: { type: "string" }, verification_method: { type: "string" } } }, onboarding_success: { name: "onboarding_success", web: true, app: true, sendMode: "realtime", params: { verification_method: { type: "string" }, acquisition_source: { type: "string" }, referral_code: { type: "string" }, account_number: { type: "string" } } }, onboarding_fail: { name: "onboarding_fail", web: true, app: true, sendMode: "realtime", params: { step_name: { type: "string", required: true }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, identity_document_view: { name: "identity_document_view", web: false, app: true }, identity_document_update_start: { name: "identity_document_update_start", web: false, app: true }, identity_document_update_confirm: { name: "identity_document_update_confirm", web: false, app: true }, identity_document_update_success: { name: "identity_document_update_success", web: true, app: true, sendMode: "realtime", params: { update_flow: { type: "string", required: true }, verification_method: { type: "string", required: true }, document_type: { type: "string" } } }, identity_document_update_pending: { name: "identity_document_update_pending", web: false, app: true }, identity_document_update_fail: { name: "identity_document_update_fail", web: false, app: true }, search_submit: { name: "search_submit", web: true, app: true, sendMode: "batch", params: { search_keyword: { type: "string", required: true }, result_count: { type: "number" } } }, search_result_click: { name: "search_result_click", web: true, app: true, sendMode: "batch", params: { search_keyword: { type: "string", required: true }, result_title: { type: "string", required: true }, result_position: { type: "number" } } }, account_view: { name: "account_view", web: true, app: true, sendMode: "batch", params: {} }, account_open_start: { name: "account_open_start", web: true, app: true, sendMode: "realtime", params: { account_type: { type: "string", required: true }, entry_point: { type: "string" } } }, account_open_confirm: { name: "account_open_confirm", web: true, app: true, sendMode: "batch", params: { account_type: { type: "string", required: true }, fee_amount: { type: "number" }, voucher_code: { type: "string" } } }, account_open_success: { name: "account_open_success", web: true, app: true, sendMode: "realtime", params: { account_number: { type: "string" }, account_type: { type: "string", required: true }, fee_amount: { type: "number" }, voucher_code: { type: "string" } } }, account_close_success: { name: "account_close_success", web: true, app: true, sendMode: "realtime", params: { account_number: { type: "string", required: true }, account_type: { type: "string" } } }, transfer_view: { name: "transfer_view", web: true, app: true, sendMode: "batch", params: { entry_point: { type: "string" } } }, transfer_start: { name: "transfer_start", web: true, app: true, sendMode: "realtime", params: { entry_point: { type: "string" }, transfer_type: { type: "string" } } }, transfer_confirm: { name: "transfer_confirm", web: true, app: true, sendMode: "realtime", params: { transfer_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, currency: { type: "string" }, entry_point: { type: "string" } } }, transfer_success: { name: "transfer_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, transfer_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, currency: { type: "string" }, fee_amount: { type: "number" }, auth_method: { type: "string" }, funding_source: { type: "string" }, counterparty_bank_code: { type: "string" }, entry_point: { type: "string" } } }, transfer_fail: { name: "transfer_fail", web: true, app: true, sendMode: "realtime", params: { transfer_type: { type: "string" }, transaction_amount: { type: "number" }, funding_source: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" }, entry_point: { type: "string" } } }, transaction_success: { name: "transaction_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, transaction_category: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, currency: { type: "string" } } }, qr_scan: { name: "qr_scan", web: false, app: true }, qr_payment_start: { name: "qr_payment_start", web: false, app: true }, qr_payment_success: { name: "qr_payment_success", web: false, app: true }, qr_payment_fail: { name: "qr_payment_fail", web: false, app: true }, billpayment_view: { name: "billpayment_view", web: true, app: true, sendMode: "batch", params: { entry_point: { type: "string" } } }, billpayment_start: { name: "billpayment_start", web: true, app: true, sendMode: "realtime", params: { service_type: { type: "string", required: true }, partner_name: { type: "string" }, entry_point: { type: "string" }, payment_mode: { type: "string" } } }, billpayment_confirm: { name: "billpayment_confirm", web: true, app: true, sendMode: "realtime", params: { service_type: { type: "string", required: true }, partner_name: { type: "string" }, transaction_amount: { type: "number", required: true }, funding_source: { type: "string" }, voucher_code: { type: "string" } } }, billpayment_success: { name: "billpayment_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, service_type: { type: "string", required: true }, partner_name: { type: "string" }, transaction_amount: { type: "number", required: true }, funding_source: { type: "string" }, voucher_code: { type: "string" }, bill_saved: { type: "boolean" }, payment_mode: { type: "string" }, entry_point: { type: "string" } } }, billpayment_fail: { name: "billpayment_fail", web: true, app: true, sendMode: "realtime", params: { service_type: { type: "string" }, partner_name: { type: "string" }, transaction_amount: { type: "number" }, funding_source: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, billpayment_autopay_start: { name: "billpayment_autopay_start", web: true, app: true, sendMode: "batch", params: { service_type: { type: "string", required: true }, partner_name: { type: "string" } } }, billpayment_autopay_success: { name: "billpayment_autopay_success", web: true, app: true, sendMode: "realtime", params: { service_type: { type: "string", required: true }, partner_name: { type: "string" }, transaction_amount: { type: "number" }, funding_source: { type: "string" }, voucher_code: { type: "string" } } }, bill_save_success: { name: "bill_save_success", web: true, app: true, sendMode: "batch", params: { service_type: { type: "string" }, partner_name: { type: "string" } } }, bill_delete_success: { name: "bill_delete_success", web: true, app: true, sendMode: "batch", params: { service_type: { type: "string" }, partner_name: { type: "string" } } }, mobile_topup_start: { name: "mobile_topup_start", web: true, app: true, sendMode: "batch", params: { partner_name: { type: "string" } } }, mobile_topup_success: { name: "mobile_topup_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, partner_name: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, funding_source: { type: "string" } } }, cardless_withdrawal_start: { name: "cardless_withdrawal_start", web: false, app: true }, cardless_withdrawal_confirm: { name: "cardless_withdrawal_confirm", web: false, app: true }, cardless_withdrawal_success: { name: "cardless_withdrawal_success", web: false, app: true }, card_view: { name: "card_view", web: true, app: true, sendMode: "batch", params: { card_type: { type: "string" } } }, card_issue_start: { name: "card_issue_start", web: true, app: true, sendMode: "realtime", params: { card_type: { type: "string", required: true }, card_product: { type: "string" }, card_form: { type: "string" }, issue_type: { type: "string" }, entry_point: { type: "string" } } }, card_issue_success: { name: "card_issue_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string" }, card_type: { type: "string", required: true }, card_product: { type: "string" }, card_brand: { type: "string" }, card_form: { type: "string" }, issue_type: { type: "string" }, credit_limit: { type: "number" } } }, card_issue_fail: { name: "card_issue_fail", web: true, app: true, sendMode: "realtime", params: { card_type: { type: "string" }, card_product: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, card_activate_start: { name: "card_activate_start", web: false, app: true }, card_activate_success: { name: "card_activate_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string" }, card_type: { type: "string", required: true }, card_product: { type: "string" }, issue_type: { type: "string" }, credit_limit: { type: "number" } } }, card_physical_request_start: { name: "card_physical_request_start", web: false, app: true }, card_physical_request_success: { name: "card_physical_request_success", web: false, app: true }, card_lock_success: { name: "card_lock_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string", required: true }, card_type: { type: "string" } } }, card_unlock_success: { name: "card_unlock_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string", required: true }, card_type: { type: "string" } } }, card_payment_start: { name: "card_payment_start", web: true, app: true, sendMode: "batch", params: { card_id: { type: "string" } } }, card_payment_success: { name: "card_payment_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, card_id: { type: "string" }, transaction_amount: { type: "number", required: true }, repay_type: { type: "string" } } }, card_limit_adjust_start: { name: "card_limit_adjust_start", web: true, app: true, sendMode: "batch", params: { card_id: { type: "string" } } }, card_limit_adjust_success: { name: "card_limit_adjust_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string" }, credit_limit: { type: "number", required: true } } }, card_installment_view: { name: "card_installment_view", web: true, app: true, sendMode: "batch", params: { card_id: { type: "string" } } }, card_installment_start: { name: "card_installment_start", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string" } } }, card_installment_success: { name: "card_installment_success", web: true, app: true, sendMode: "realtime", params: { card_id: { type: "string" }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, card_tokenize_start: { name: "card_tokenize_start", web: false, app: true }, card_tokenize_success: { name: "card_tokenize_success", web: false, app: true }, loan_view: { name: "loan_view", web: true, app: true, sendMode: "batch", params: { entry_point: { type: "string" } } }, loan_product_view: { name: "loan_product_view", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" }, product_name: { type: "string" } } }, loan_eligibility_check_start: { name: "loan_eligibility_check_start", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" } } }, loan_eligibility_check_success: { name: "loan_eligibility_check_success", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" }, eligible_amount: { type: "number" } } }, loan_apply_start: { name: "loan_apply_start", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" }, loan_action: { type: "string", required: true }, disbursement_mode: { type: "string", required: true }, step_no: { type: "number" }, entry_point: { type: "string" } } }, loan_apply_confirm: { name: "loan_apply_confirm", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" }, loan_action: { type: "string", required: true }, disbursement_mode: { type: "string", required: true }, transaction_amount: { type: "number" }, term: { type: "string" } } }, loan_apply_success: { name: "loan_apply_success", web: true, app: true, sendMode: "realtime", params: { loan_id: { type: "string" }, product_type: { type: "string", required: true }, product_id: { type: "string" }, loan_action: { type: "string", required: true }, disbursement_mode: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, loan_apply_fail: { name: "loan_apply_fail", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, product_id: { type: "string" }, loan_action: { type: "string" }, disbursement_mode: { type: "string" }, transaction_amount: { type: "number" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, loan_disburse_start: { name: "loan_disburse_start", web: true, app: true, sendMode: "realtime", params: { loan_id: { type: "string" }, product_type: { type: "string", required: true }, product_id: { type: "string" }, transaction_amount: { type: "number" }, step_no: { type: "number" } } }, loan_disburse_confirm: { name: "loan_disburse_confirm", web: true, app: true, sendMode: "batch", params: { loan_id: { type: "string" }, product_type: { type: "string", required: true }, product_id: { type: "string" }, transaction_amount: { type: "number" } } }, loan_disburse_success: { name: "loan_disburse_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string" }, loan_id: { type: "string" }, product_type: { type: "string", required: true }, product_id: { type: "string" }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, loan_disburse_fail: { name: "loan_disburse_fail", web: true, app: true, sendMode: "realtime", params: { loan_id: { type: "string" }, product_type: { type: "string", required: true }, product_id: { type: "string" }, transaction_amount: { type: "number" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, loan_repay_start: { name: "loan_repay_start", web: true, app: true, sendMode: "batch", params: { loan_id: { type: "string" }, product_type: { type: "string" } } }, loan_repay_success: { name: "loan_repay_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string", required: true }, loan_id: { type: "string" }, product_type: { type: "string" }, transaction_amount: { type: "number", required: true }, repay_type: { type: "string" } } }, loan_close_start: { name: "loan_close_start", web: true, app: true, sendMode: "batch", params: { loan_id: { type: "string" }, product_type: { type: "string" } } }, loan_close_success: { name: "loan_close_success", web: true, app: true, sendMode: "realtime", params: { loan_id: { type: "string" }, product_type: { type: "string" }, transaction_amount: { type: "number" } } }, saving_view: { name: "saving_view", web: true, app: true, sendMode: "batch", params: { product_type: { type: "string" } } }, saving_detail_view: { name: "saving_detail_view", web: true, app: true, sendMode: "batch", params: { savings_account_number: { type: "string" }, product_type: { type: "string" }, transaction_amount: { type: "number" }, term: { type: "string" } } }, saving_open_start: { name: "saving_open_start", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, interest_payment_method: { type: "string" }, entry_point: { type: "string" } } }, saving_open_confirm: { name: "saving_open_confirm", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, term: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, interest_payment_method: { type: "string" }, auto_deposit_frequency: { type: "string" }, auto_deposit_amount: { type: "number" }, promotion_code: { type: "string" } } }, saving_open_success: { name: "saving_open_success", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, term: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, interest_payment_method: { type: "string" }, auto_deposit_frequency: { type: "string" }, auto_deposit_amount: { type: "number" }, voucher_code: { type: "string" }, promotion_code: { type: "string" } } }, saving_open_fail: { name: "saving_open_fail", web: true, app: true, sendMode: "realtime", params: { product_type: { type: "string", required: true }, term: { type: "string" }, transaction_amount: { type: "number" }, interest_payment_method: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, saving_deposit_more_start: { name: "saving_deposit_more_start", web: true, app: true, sendMode: "batch", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, term: { type: "string" } } }, saving_deposit_more_confirm: { name: "saving_deposit_more_confirm", web: true, app: true, sendMode: "batch", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, auto_deposit_frequency: { type: "string" }, auto_deposit_amount: { type: "number" } } }, saving_deposit_more_success: { name: "saving_deposit_more_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string" }, savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, auto_deposit_frequency: { type: "string" }, auto_deposit_amount: { type: "number" } } }, saving_autodeposit_setup_start: { name: "saving_autodeposit_setup_start", web: true, app: true, sendMode: "batch", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true } } }, saving_autodeposit_setup_success: { name: "saving_autodeposit_setup_success", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, auto_deposit_amount: { type: "number", required: true }, auto_deposit_frequency: { type: "string", required: true }, status: { type: "string", required: true } } }, saving_withdraw_partial_start: { name: "saving_withdraw_partial_start", web: true, app: true, sendMode: "batch", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, term: { type: "string" } } }, saving_withdraw_partial_success: { name: "saving_withdraw_partial_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string" }, savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, saving_withdraw_partial_fail: { name: "saving_withdraw_partial_fail", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number" }, error_code: { type: "string", required: true } } }, saving_settle_start: { name: "saving_settle_start", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number" }, term: { type: "string" } } }, saving_settle_success: { name: "saving_settle_success", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, saving_settle_fail: { name: "saving_settle_fail", web: true, app: true, sendMode: "realtime", params: { savings_account_number: { type: "string" }, product_type: { type: "string", required: true }, error_code: { type: "string", required: true } } }, insurance_view: { name: "insurance_view", web: true, app: true, sendMode: "batch", params: { insurance_type: { type: "string" }, partner_name: { type: "string" } } }, insurance_product_view: { name: "insurance_product_view", web: true, app: true, sendMode: "realtime", params: { insurance_type: { type: "string", required: true }, partner_name: { type: "string" }, product_id: { type: "string" }, product_name: { type: "string" } } }, insurance_purchase_start: { name: "insurance_purchase_start", web: true, app: true, sendMode: "realtime", params: { insurance_type: { type: "string", required: true }, partner_name: { type: "string" }, product_id: { type: "string" } } }, insurance_purchase_success: { name: "insurance_purchase_success", web: true, app: true, sendMode: "realtime", params: { policy_number: { type: "string" }, insurance_type: { type: "string", required: true }, partner_name: { type: "string" }, product_id: { type: "string" }, transaction_amount: { type: "number", required: true }, term: { type: "string" } } }, insurance_claim_view: { name: "insurance_claim_view", web: true, app: true, sendMode: "batch", params: { partner_name: { type: "string" } } }, investment_view: { name: "investment_view", web: true, app: true, sendMode: "batch", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string" } } }, investment_product_view: { name: "investment_product_view", web: true, app: true, sendMode: "batch", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string" }, product_name: { type: "string" } } }, investment_account_open_start: { name: "investment_account_open_start", web: true, app: true, sendMode: "realtime", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string", required: true } } }, investment_account_open_success: { name: "investment_account_open_success", web: true, app: true, sendMode: "realtime", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string", required: true } } }, investment_purchase_start: { name: "investment_purchase_start", web: true, app: true, sendMode: "realtime", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string" }, product_name: { type: "string" }, transaction_amount: { type: "number" } } }, investment_purchase_success: { name: "investment_purchase_success", web: true, app: true, sendMode: "realtime", params: { transaction_id: { type: "string" }, investment_type: { type: "string", required: true }, partner_name: { type: "string" }, product_name: { type: "string" }, transaction_amount: { type: "number", required: true } } }, investment_purchase_fail: { name: "investment_purchase_fail", web: true, app: true, sendMode: "realtime", params: { investment_type: { type: "string", required: true }, partner_name: { type: "string" }, product_name: { type: "string" }, transaction_amount: { type: "number" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, wallet_view: { name: "wallet_view", web: false, app: true }, wallet_link_start: { name: "wallet_link_start", web: false, app: true }, wallet_link_success: { name: "wallet_link_success", web: false, app: true }, wallet_topup_start: { name: "wallet_topup_start", web: false, app: true }, wallet_topup_success: { name: "wallet_topup_success", web: false, app: true }, loyalty_view: { name: "loyalty_view", web: true, app: true, sendMode: "batch", params: {} }, loyalty_redeem_success: { name: "loyalty_redeem_success", web: true, app: true, sendMode: "realtime", params: { points: { type: "number", required: true }, reward_name: { type: "string" } } }, offer_view: { name: "offer_view", web: true, app: true, sendMode: "batch", params: {} }, offer_detail_view: { name: "offer_detail_view", web: true, app: true, sendMode: "realtime", params: { offer_id: { type: "string" }, offer_name: { type: "string", required: true }, partner_name: { type: "string" } } }, voucher_view: { name: "voucher_view", web: true, app: true, sendMode: "batch", params: {} }, voucher_detail_view: { name: "voucher_detail_view", web: true, app: true, sendMode: "batch", params: { voucher_name: { type: "string", required: true }, voucher_code: { type: "string" } } }, voucher_use_click: { name: "voucher_use_click", web: true, app: true, sendMode: "realtime", params: { voucher_name: { type: "string", required: true }, voucher_code: { type: "string" } } }, voucher_issue_success: { name: "voucher_issue_success", web: true, app: true, sendMode: "realtime", params: { voucher_code: { type: "string" }, promotion_code: { type: "string", required: true }, applicable_product: { type: "string" } } }, referral_view: { name: "referral_view", web: false, app: true }, referral_link_create: { name: "referral_link_create", web: false, app: true }, referral_success: { name: "referral_success", web: true, app: true, sendMode: "realtime", params: { referred_customer_id: { type: "string" }, referral_milestone: { type: "number" } } }, business_account_open_start: { name: "business_account_open_start", web: true, app: true, sendMode: "realtime", params: { business_type: { type: "string", required: true }, step_no: { type: "number" } } }, business_account_open_confirm: { name: "business_account_open_confirm", web: true, app: true, sendMode: "batch", params: { business_type: { type: "string", required: true } } }, business_account_open_success: { name: "business_account_open_success", web: true, app: true, sendMode: "realtime", params: { account_number: { type: "string" }, business_type: { type: "string", required: true }, industry_code: { type: "string" }, rm_code: { type: "string" } } }, business_account_open_fail: { name: "business_account_open_fail", web: true, app: true, sendMode: "realtime", params: { business_type: { type: "string", required: true }, industry_code: { type: "string" }, error_code: { type: "string", required: true }, error_message: { type: "string" } } }, merchant_qr_register_start: { name: "merchant_qr_register_start", web: false, app: true }, merchant_qr_register_success: { name: "merchant_qr_register_success", web: false, app: true }, card_transaction: { name: "card_transaction", web: false, app: false }, card_transaction_posted: { name: "card_transaction_posted", web: false, app: false }, money_received: { name: "money_received", web: false, app: false }, balance_changed: { name: "balance_changed", web: false, app: false }, card_shipment_success: { name: "card_shipment_success", web: false, app: false }, card_close_success: { name: "card_close_success", web: false, app: false }, loan_overdue: { name: "loan_overdue", web: false, app: false }, saving_matured: { name: "saving_matured", web: false, app: false }, loyalty_points_earned: { name: "loyalty_points_earned", web: false, app: false }, audience_flag_update: { name: "audience_flag_update", web: false, app: false } } };
3
+
4
+ // src/core/catalog.ts
5
+ var catalog = { ...catalog_runtime_default, source: "builtin" };
6
+
7
+ // src/core/config.ts
8
+ var DEFAULT_SENSITIVE_QUERY = ["token", "access_token", "id_token", "otp", "password", "pwd", "email", "phone", "secret"];
9
+ function resolveConfig(c) {
10
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H;
11
+ const sdkKey = ((_b = (_a = c.sdkKey) != null ? _a : c.apiKey) != null ? _b : "").trim();
12
+ const apiHost = ((_d = (_c = c.apiHost) != null ? _c : c.endpoint) != null ? _d : "").trim().replace(/\/+$/, "");
13
+ if (!apiHost) return { error: "apiHost is required (host API public d\xE0nh cho SDK)" };
14
+ if (!/^https?:\/\//i.test(apiHost)) return { error: "apiHost must start with https:// (or http:// for local dev)" };
15
+ if (!sdkKey) return { error: "sdkKey is required" };
16
+ const wp = (_e = c.webPush) != null ? _e : {};
17
+ const vapid = (_f = wp.vapidPublicKey) != null ? _f : c.vapidPublicKey;
18
+ return {
19
+ cfg: {
20
+ sdkKey,
21
+ apiHost,
22
+ env: (_g = c.env) != null ? _g : "production",
23
+ autoPageView: (_j = (_i = c.autoPageView) != null ? _i : (_h = c.autoTrack) == null ? void 0 : _h.pageView) != null ? _j : true,
24
+ autoSession: (_l = (_k = c.autoTrack) == null ? void 0 : _k.session) != null ? _l : true,
25
+ sessionTimeoutMs: c.sessionTimeoutMin ? c.sessionTimeoutMin * 6e4 : (_m = c.sessionTimeoutMs) != null ? _m : 30 * 6e4,
26
+ requireConsent: !!c.requireConsent,
27
+ cookieDomain: c.cookieDomain,
28
+ batchSize: Math.max(1, Math.min(100, (_p = (_o = (_n = c.batch) == null ? void 0 : _n.size) != null ? _o : c.batchSize) != null ? _p : 20)),
29
+ batchIntervalMs: Math.max(0, (_s = (_r = (_q = c.batch) == null ? void 0 : _q.intervalMs) != null ? _r : c.flushIntervalMs) != null ? _s : 5e3),
30
+ webPush: { enabled: !!c.webPush || !!vapid, serviceWorkerPath: (_u = (_t = wp.serviceWorkerPath) != null ? _t : c.serviceWorkerUrl) != null ? _u : "/bizcdp-sw.js", serviceWorkerScope: (_v = wp.serviceWorkerScope) != null ? _v : "/", vapidPublicKey: vapid, softPrompt: !!wp.softPrompt },
31
+ inApp: { popups: (_y = (_x = (_w = c.inApp) == null ? void 0 : _w.popups) != null ? _x : c.campaigns) != null ? _y : true, banners: (_B = (_A = (_z = c.inApp) == null ? void 0 : _z.banners) != null ? _A : c.campaigns) != null ? _B : true, scriptUrl: (_C = c.inApp) == null ? void 0 : _C.scriptUrl },
32
+ debug: !!c.debug,
33
+ appVersion: c.appVersion,
34
+ maxQueueSize: (_D = c.maxQueueSize) != null ? _D : 1e3,
35
+ maxQueueAgeMs: ((_E = c.maxQueueAgeDays) != null ? _E : 7) * 864e5,
36
+ allowUnknownEvents: !!c.allowUnknownEvents || !!c.debug,
37
+ allowUnknownAttributes: !!c.allowUnknownAttributes,
38
+ sensitiveQueryParams: ((_F = c.sensitiveQueryParams) != null ? _F : DEFAULT_SENSITIVE_QUERY).map((s) => s.toLowerCase()),
39
+ storagePrefix: (_G = c.storagePrefix) != null ? _G : "_bzc_",
40
+ campaignsRefreshMs: (_H = c.campaignsRefreshMs) != null ? _H : 0,
41
+ contentProvider: c.contentProvider
42
+ }
43
+ };
44
+ }
45
+
46
+ // src/core/dictionary.ts
47
+ var TYPE = { STRING: "string", NUMBER: "number", BOOLEAN: "boolean", DATE: "date", DATETIME: "datetime", LIST: "string[]" };
48
+ var INTERACTION = /^(web_push_(delivered|clicked)|web_popup_|web_banner_|survey_result$|lead_collected$|gamification_played$)/;
49
+ var toType = (t) => {
50
+ var _a;
51
+ return (_a = TYPE[String(t).toUpperCase()]) != null ? _a : "string";
52
+ };
53
+ function fromServer(raw) {
54
+ var _a, _b, _c, _d, _e;
55
+ const own = !!raw.param_meta;
56
+ const params = own ? {} : catalog.params;
57
+ const note = (p) => {
58
+ var _a2;
59
+ if (!own || params[p.key]) return;
60
+ params[p.key] = { type: toType(p.data_type), ...((_a2 = p.allowed_values) == null ? void 0 : _a2.length) ? { enum: p.allowed_values } : {}, ...p.free_text ? { free: true } : {} };
61
+ };
62
+ const events = {};
63
+ for (const e of (_a = raw.events) != null ? _a : []) {
64
+ const defs = {};
65
+ for (const p of (_b = e.params) != null ? _b : []) {
66
+ defs[p.key] = { type: toType(p.data_type), required: !!p.required };
67
+ note(p);
68
+ }
69
+ const correlation = own && typeof e.correlation === "boolean" ? e.correlation : catalog.events[e.key] ? !!catalog.events[e.key].correlation : INTERACTION.test(e.key);
70
+ events[e.key] = { name: e.key, web: true, app: false, sendMode: e.send_mode === "batch" ? "batch" : "realtime", correlation, params: defs };
71
+ }
72
+ const mutual = {};
73
+ for (const p of (_c = raw.mutual_params) != null ? _c : []) {
74
+ mutual[p.key] = { type: toType(p.data_type) };
75
+ note(p);
76
+ }
77
+ const attributes = {};
78
+ for (const a of (_d = raw.attributes) != null ? _d : []) attributes[a.key] = { type: toType(a.data_type), ...((_e = a.options) == null ? void 0 : _e.length) ? { options: a.options } : {} };
79
+ return { version: raw.version, params, attributes, events, mutual, source: "server" };
80
+ }
81
+ var Dictionary = class {
82
+ constructor(store) {
83
+ this.store = store;
84
+ this.cat = catalog;
85
+ var _a, _b;
86
+ const s = store.getJSON("dict");
87
+ if ((_a = s == null ? void 0 : s.data) == null ? void 0 : _a.version) {
88
+ this.cat = fromServer(s.data);
89
+ this.etag = (_b = s.etag) != null ? _b : `"${s.version}"`;
90
+ }
91
+ }
92
+ get current() {
93
+ return this.cat;
94
+ }
95
+ /** Đã có từ điển của server (tải được, hoặc bản lưu từ lần trước) */
96
+ get fromServer() {
97
+ return this.cat.source === "server";
98
+ }
99
+ /** Tải từ điển; 304 = giữ bản cache. Lỗi mạng thì giữ bản đang có. */
100
+ async refresh(tr) {
101
+ var _a;
102
+ const r = await tr.dictionary(this.etag);
103
+ if (r.status === 304) return true;
104
+ const j = r.json;
105
+ if (r.status !== 200 || !j || !Array.isArray(j.events)) return false;
106
+ this.cat = fromServer(j);
107
+ this.etag = (_a = r.etag) != null ? _a : `"${j.version}"`;
108
+ this.store.setJSON("dict", { version: j.version, etag: this.etag, data: j });
109
+ return true;
110
+ }
111
+ };
112
+
113
+ // src/core/storage.ts
114
+ var Storage = class {
115
+ constructor(prefix, cookieDomain) {
116
+ this.prefix = prefix;
117
+ this.cookieDomain = cookieDomain;
118
+ this.mem = /* @__PURE__ */ new Map();
119
+ }
120
+ get(key) {
121
+ var _a;
122
+ try {
123
+ const v = localStorage.getItem(this.prefix + key);
124
+ if (v !== null) return v;
125
+ } catch {
126
+ }
127
+ return (_a = this.mem.get(key)) != null ? _a : null;
128
+ }
129
+ set(key, value) {
130
+ this.mem.set(key, value);
131
+ try {
132
+ localStorage.setItem(this.prefix + key, value);
133
+ } catch {
134
+ }
135
+ }
136
+ remove(key) {
137
+ this.mem.delete(key);
138
+ try {
139
+ localStorage.removeItem(this.prefix + key);
140
+ } catch {
141
+ }
142
+ }
143
+ getJSON(key) {
144
+ const v = this.get(key);
145
+ if (!v) return null;
146
+ try {
147
+ return JSON.parse(v);
148
+ } catch {
149
+ return null;
150
+ }
151
+ }
152
+ setJSON(key, value) {
153
+ this.set(key, JSON.stringify(value));
154
+ }
155
+ getSession(key) {
156
+ var _a;
157
+ try {
158
+ return sessionStorage.getItem(this.prefix + key);
159
+ } catch {
160
+ return (_a = this.mem.get("s:" + key)) != null ? _a : null;
161
+ }
162
+ }
163
+ setSession(key, value) {
164
+ this.mem.set("s:" + key, value);
165
+ try {
166
+ sessionStorage.setItem(this.prefix + key, value);
167
+ } catch {
168
+ }
169
+ }
170
+ removeCookie(name) {
171
+ this.setCookie(name, "", -1);
172
+ }
173
+ getCookie(name) {
174
+ try {
175
+ const n = (this.prefix + name).replace(/[.$?*|{}()[\]\\/+^]/g, "\\$&");
176
+ const m = document.cookie.match(new RegExp("(?:^|; )" + n + "=([^;]*)"));
177
+ return m ? decodeURIComponent(m[1]) : null;
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+ setCookie(name, value, days = 365) {
183
+ try {
184
+ const secure = location.protocol === "https:" ? "; Secure" : "";
185
+ const domain = this.cookieDomain ? `; Domain=${this.cookieDomain}` : "";
186
+ document.cookie = `${this.prefix + name}=${encodeURIComponent(value)}; Max-Age=${days * 86400}; Path=/; SameSite=Lax${secure}${domain}`;
187
+ } catch {
188
+ }
189
+ }
190
+ };
191
+
192
+ // src/core/queue.ts
193
+ var DB = "bzc-sdk";
194
+ var STORE = "queue";
195
+ var IdbBackend = class _IdbBackend {
196
+ constructor(db) {
197
+ this.db = db;
198
+ }
199
+ static open() {
200
+ return new Promise((ok2, fail) => {
201
+ try {
202
+ const r = indexedDB.open(DB, 1);
203
+ r.onupgradeneeded = () => r.result.createObjectStore(STORE, { keyPath: "seq", autoIncrement: true });
204
+ r.onsuccess = () => {
205
+ r.result.onversionchange = () => r.result.close();
206
+ ok2(new _IdbBackend(r.result));
207
+ };
208
+ r.onerror = () => fail(r.error);
209
+ r.onblocked = () => fail(new Error("blocked"));
210
+ } catch (e) {
211
+ fail(e);
212
+ }
213
+ });
214
+ }
215
+ run(mode, fn) {
216
+ return new Promise((ok2, fail) => {
217
+ const t = this.db.transaction(STORE, mode);
218
+ const req = fn(t.objectStore(STORE));
219
+ t.oncomplete = () => ok2(req ? req.result : void 0);
220
+ t.onerror = () => fail(t.error);
221
+ t.onabort = () => fail(t.error);
222
+ });
223
+ }
224
+ add(item) {
225
+ return this.run("readwrite", (s) => s.add(item));
226
+ }
227
+ all() {
228
+ return this.run("readonly", (s) => s.getAll());
229
+ }
230
+ remove(seqs) {
231
+ return this.run("readwrite", (s) => {
232
+ seqs.forEach((q) => s.delete(q));
233
+ });
234
+ }
235
+ clear() {
236
+ return this.run("readwrite", (s) => s.clear());
237
+ }
238
+ };
239
+ var LocalBackend = class {
240
+ constructor(store) {
241
+ this.store = store;
242
+ }
243
+ read() {
244
+ var _a;
245
+ return (_a = this.store.getJSON("queue")) != null ? _a : [];
246
+ }
247
+ write(v) {
248
+ this.store.setJSON("queue", v);
249
+ }
250
+ async add(item) {
251
+ var _a, _b;
252
+ const a = this.read();
253
+ a.push({ ...item, seq: ((_b = (_a = a[a.length - 1]) == null ? void 0 : _a.seq) != null ? _b : 0) + 1 });
254
+ this.write(a);
255
+ }
256
+ async all() {
257
+ return this.read();
258
+ }
259
+ async remove(seqs) {
260
+ const s = new Set(seqs);
261
+ this.write(this.read().filter((x) => !s.has(x.seq)));
262
+ }
263
+ async clear() {
264
+ this.write([]);
265
+ }
266
+ };
267
+ var EventQueue = class {
268
+ constructor(store, maxItems, maxAgeMs) {
269
+ this.maxItems = maxItems;
270
+ this.maxAgeMs = maxAgeMs;
271
+ this.ready = (typeof indexedDB !== "undefined" ? IdbBackend.open() : Promise.reject(new Error("no idb"))).then((b) => {
272
+ this.backend = b;
273
+ }, () => {
274
+ this.backend = new LocalBackend(store);
275
+ }).then(() => this.trim()).catch(() => void 0);
276
+ }
277
+ async add(rec) {
278
+ await this.ready;
279
+ await this.backend.add({ t: Date.now(), rec });
280
+ }
281
+ async count() {
282
+ await this.ready;
283
+ return (await this.backend.all()).length;
284
+ }
285
+ async clear() {
286
+ await this.ready;
287
+ await this.backend.clear();
288
+ }
289
+ async remove(items) {
290
+ await this.ready;
291
+ await this.backend.remove(items.map((i) => i.seq));
292
+ }
293
+ /** Lấy tối đa n bản ghi cũ nhất, tổng kích thước ≤ maxBytes */
294
+ async peek(n, maxBytes) {
295
+ await this.ready;
296
+ const out = [];
297
+ let bytes = 0;
298
+ for (const it of (await this.backend.all()).sort((a, b) => a.seq - b.seq)) {
299
+ const len = JSON.stringify(it.rec).length + 1;
300
+ if (out.length && (out.length >= n || bytes + len > maxBytes)) break;
301
+ out.push(it);
302
+ bytes += len;
303
+ }
304
+ return out;
305
+ }
306
+ /** Bỏ bản ghi quá hạn, và bỏ bản cũ nhất khi vượt giới hạn (TI-R-16) */
307
+ async trim() {
308
+ const all = (await this.backend.all()).sort((a, b) => a.seq - b.seq);
309
+ const old = /* @__PURE__ */ new Set();
310
+ const cutoff = Date.now() - this.maxAgeMs;
311
+ all.forEach((i) => {
312
+ if (i.t < cutoff) old.add(i.seq);
313
+ });
314
+ const rest = all.filter((i) => !old.has(i.seq));
315
+ rest.slice(0, Math.max(0, rest.length - this.maxItems)).forEach((i) => old.add(i.seq));
316
+ if (old.size) await this.backend.remove([...old]);
317
+ }
318
+ };
319
+
320
+ // src/core/transport.ts
321
+ var KEEPALIVE_MAX = 60 * 1024;
322
+ var parse = async (res) => {
323
+ try {
324
+ return await res.json();
325
+ } catch {
326
+ return void 0;
327
+ }
328
+ };
329
+ var Transport = class {
330
+ constructor(o, log) {
331
+ this.o = o;
332
+ this.log = log;
333
+ }
334
+ get host() {
335
+ return this.o.apiHost;
336
+ }
337
+ get key() {
338
+ return this.o.sdkKey;
339
+ }
340
+ /** Gọi API thô. Trả status 0 khi lỗi mạng. */
341
+ async request(method, path, body, extra = {}) {
342
+ var _a, _b, _c, _d;
343
+ try {
344
+ const headers = { "x-api-key": this.o.sdkKey };
345
+ let payload;
346
+ if (body !== void 0) {
347
+ headers["Content-Type"] = "application/json";
348
+ payload = JSON.stringify(body);
349
+ }
350
+ if (extra.etag) headers["If-None-Match"] = extra.etag;
351
+ const res = await fetch(`${this.o.apiHost}${path}`, { method, headers, body: payload, keepalive: !!extra.keepalive && ((_a = payload == null ? void 0 : payload.length) != null ? _a : 0) < KEEPALIVE_MAX });
352
+ const json = res.status === 204 || res.status === 304 ? void 0 : await parse(res);
353
+ return { status: res.status, ok: res.ok, json, etag: (_d = (_c = (_b = res.headers) == null ? void 0 : _b.get) == null ? void 0 : _c.call(_b, "ETag")) != null ? _d : void 0 };
354
+ } catch (e) {
355
+ this.log.warn("network error", path, e);
356
+ return { status: 0, ok: false };
357
+ }
358
+ }
359
+ /** POST /ingest/records: phân loại kết quả để hàng đợi biết phải làm gì tiếp */
360
+ async sendRecords(records, keepalive = true) {
361
+ var _a, _b, _c, _d;
362
+ const r = await this.request("POST", "/ingest/records", { records }, { keepalive });
363
+ if (r.status === 200) return { kind: "ok", results: (_b = (_a = r.json) == null ? void 0 : _a.results) != null ? _b : [] };
364
+ if (r.status === 429) return { kind: "pause", until: (Math.floor(Date.now() / 6e4) + 1) * 6e4 + Math.floor(Math.random() * 2e3) };
365
+ if (r.status === 401 || r.status === 403) return { kind: "stop", reason: ((_c = r.json) == null ? void 0 : _c.errorCode) || String(r.status) };
366
+ if (r.status === 0 || r.status >= 500 || r.status === 408) return { kind: "retry" };
367
+ this.log.warn("ingest rejected", r.status, r.json);
368
+ return { kind: "drop", status: r.status, message: (_d = r.json) == null ? void 0 : _d.message };
369
+ }
370
+ getOrCreateDevice(body) {
371
+ return this.request("POST", "/identity/device/get-or-create", body);
372
+ }
373
+ identify(body) {
374
+ return this.request("POST", "/identity/identify-and-unify", body);
375
+ }
376
+ logout(deviceId) {
377
+ return this.request("POST", "/identity/logout", { deviceId });
378
+ }
379
+ pushToken(body) {
380
+ return this.request("POST", "/identity/push-token", body);
381
+ }
382
+ dictionary(etag) {
383
+ return this.request("GET", "/sdk/dictionary?platform=web", void 0, { etag });
384
+ }
385
+ webConfig() {
386
+ return this.request("GET", "/sdk/web/config");
387
+ }
388
+ slots(etag) {
389
+ return this.request("GET", "/sdk/web/slots", void 0, { etag });
390
+ }
391
+ };
392
+
393
+ // src/core/util.ts
394
+ var SDK_VERSION = true ? "1.2.0" : "dev";
395
+ function uuid() {
396
+ const c = typeof crypto !== "undefined" ? crypto : void 0;
397
+ if (c == null ? void 0 : c.randomUUID) return c.randomUUID();
398
+ const b = new Uint8Array(16);
399
+ if (c == null ? void 0 : c.getRandomValues) c.getRandomValues(b);
400
+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);
401
+ b[6] = b[6] & 15 | 64;
402
+ b[8] = b[8] & 63 | 128;
403
+ const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
404
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
405
+ }
406
+ var p2 = (n) => String(n).padStart(2, "0");
407
+ function rfc3339(d = /* @__PURE__ */ new Date()) {
408
+ const off = -d.getTimezoneOffset();
409
+ const sign = off >= 0 ? "+" : "-";
410
+ const a = Math.abs(off);
411
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}T${p2(d.getHours())}:${p2(d.getMinutes())}:${p2(d.getSeconds())}${sign}${p2(Math.floor(a / 60))}:${p2(a % 60)}`;
412
+ }
413
+ function isoDate(d) {
414
+ return `${d.getFullYear()}-${p2(d.getMonth() + 1)}-${p2(d.getDate())}`;
415
+ }
416
+ function osVersion(ua) {
417
+ const m = ua.match(/Windows NT ([\d.]+)/) || ua.match(/OS ([\d_]+) like Mac OS X/) || ua.match(/Mac OS X ([\d_.]+)/) || ua.match(/Android ([\d.]+)/);
418
+ return m ? m[1].replace(/_/g, ".") : void 0;
419
+ }
420
+ var Logger = class {
421
+ constructor(debug) {
422
+ this.debug = debug;
423
+ }
424
+ log(...a) {
425
+ if (this.debug) console.log("[cdp-sdk]", ...a);
426
+ }
427
+ warn(...a) {
428
+ if (this.debug) console.warn("[cdp-sdk]", ...a);
429
+ }
430
+ };
431
+ function cleanUrl(href, sensitive) {
432
+ try {
433
+ const u = new URL(href);
434
+ u.hash = "";
435
+ for (const k of [...u.searchParams.keys()]) if (sensitive.includes(k.toLowerCase())) u.searchParams.delete(k);
436
+ return u.href;
437
+ } catch {
438
+ return href.split("#")[0];
439
+ }
440
+ }
441
+ async function hashText(text) {
442
+ try {
443
+ if (typeof crypto !== "undefined" && crypto.subtle) {
444
+ const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
445
+ return Array.from(new Uint8Array(d), (x) => x.toString(16).padStart(2, "0")).join("");
446
+ }
447
+ } catch {
448
+ }
449
+ let h1 = 2166136261, h2 = 16777619;
450
+ for (let i = 0; i < text.length; i++) {
451
+ h1 = Math.imul(h1 ^ text.charCodeAt(i), 16777619);
452
+ h2 = Math.imul(h2 ^ text.charCodeAt(i), 2246822507);
453
+ }
454
+ return "f" + (h1 >>> 0).toString(16).padStart(8, "0") + (h2 >>> 0).toString(16).padStart(8, "0");
455
+ }
456
+ function backoff(attempt) {
457
+ const base = Math.min(1e3 * 2 ** Math.max(0, attempt - 1), 5 * 6e4);
458
+ return Math.round(base * (0.8 + Math.random() * 0.4));
459
+ }
460
+
461
+ // src/core/identity.ts
462
+ var DID_DAYS = 400;
463
+ function loadDeviceId(store, persist) {
464
+ let id = store.getCookie("did") || store.get("did");
465
+ if (!id) id = uuid();
466
+ if (persist) savePersist(store, id);
467
+ return id;
468
+ }
469
+ function savePersist(store, id) {
470
+ store.set("did", id);
471
+ store.setCookie("did", id, DID_DAYS);
472
+ }
473
+ var getProfile = (store) => {
474
+ var _a;
475
+ return (_a = store.getJSON("profile")) != null ? _a : void 0;
476
+ };
477
+ var setProfile = (store, p) => {
478
+ if (p) store.setJSON("profile", p);
479
+ else store.remove("profile");
480
+ };
481
+ var Session = class {
482
+ constructor(store, timeoutMs) {
483
+ this.store = store;
484
+ this.timeoutMs = timeoutMs;
485
+ }
486
+ /** Cập nhật hoạt động; trả isNew=true khi bắt đầu phiên mới: chưa có phiên hoặc hoạt động cuối cách ≥ timeout hoặc sau logout (TI-R-11). Các tab dùng chung một phiên. */
487
+ touch(now = Date.now()) {
488
+ const cur = this.store.getJSON("sid");
489
+ if (cur && now - cur.last < this.timeoutMs) {
490
+ this.store.setJSON("sid", { id: cur.id, last: now });
491
+ return { id: cur.id, isNew: false };
492
+ }
493
+ const id = uuid();
494
+ this.store.setJSON("sid", { id, last: now });
495
+ return { id, isNew: true };
496
+ }
497
+ reset() {
498
+ this.store.remove("sid");
499
+ }
500
+ };
501
+ function normalizeIdentifiers(i) {
502
+ const out = {};
503
+ for (const [k, v] of Object.entries(i)) {
504
+ if (v === void 0 || v === null || String(v).trim() === "") continue;
505
+ const s = String(v).trim();
506
+ if (k === "national_id") out[k] = s.toUpperCase();
507
+ else if (k === "email") out[k] = s.toLowerCase();
508
+ else if (k === "phone_number") {
509
+ const d = s.replace(/[\s.\-()]/g, "");
510
+ out[k] = d.startsWith("+") ? d : d.startsWith("84") ? `+${d}` : d.startsWith("0") ? `+84${d.slice(1)}` : d;
511
+ } else out[k] = s;
512
+ }
513
+ return out;
514
+ }
515
+ var toIdentifierList = (i) => Object.entries(i).filter(([, v]) => v).map(([type, value]) => ({ type, value }));
516
+ var identifiersHash = (i) => hashText(JSON.stringify(Object.entries(i).sort(([a], [b]) => a.localeCompare(b))));
517
+
518
+ // src/core/normalize.ts
519
+ var MAX_STRING = 1024;
520
+ var TRUE = /* @__PURE__ */ new Set(["true", "y", "yes", "1"]);
521
+ var FALSE = /* @__PURE__ */ new Set(["false", "n", "no", "0"]);
522
+ var DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
523
+ var DATETIME_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/;
524
+ var ok = (value) => ({ ok: true, value });
525
+ var bad = (reason) => ({ ok: false, reason });
526
+ function normalize(value, type) {
527
+ switch (type) {
528
+ case "string":
529
+ return str(value);
530
+ case "number":
531
+ return num(value);
532
+ case "boolean":
533
+ return bool(value);
534
+ case "date":
535
+ return date(value);
536
+ case "datetime":
537
+ return datetime(value);
538
+ case "string[]":
539
+ return arr(value, str);
540
+ case "number[]":
541
+ return arr(value, num);
542
+ }
543
+ }
544
+ function str(v) {
545
+ if (typeof v === "string") return ok(v.length > MAX_STRING ? v.slice(0, MAX_STRING) : v);
546
+ if (typeof v === "number" && Number.isFinite(v)) return ok(String(v));
547
+ if (typeof v === "boolean") return ok(String(v));
548
+ return bad("expected string");
549
+ }
550
+ function num(v) {
551
+ let n;
552
+ if (typeof v === "number") n = v;
553
+ else if (typeof v === "string" && /^\s*-?\d+(\.\d+)?\s*$/.test(v)) n = Number(v);
554
+ else return bad("expected number");
555
+ if (!Number.isFinite(n) || Math.abs(n) >= 1e18) return bad("number out of range (max 18 integer digits)");
556
+ return ok(Math.round(n * 1e4) / 1e4);
557
+ }
558
+ function bool(v) {
559
+ if (typeof v === "boolean") return ok(v);
560
+ if (typeof v !== "string" && typeof v !== "number") return bad("expected boolean");
561
+ const s = String(v).trim().toLowerCase();
562
+ if (TRUE.has(s)) return ok(true);
563
+ if (FALSE.has(s)) return ok(false);
564
+ return bad("expected boolean");
565
+ }
566
+ function date(v) {
567
+ if (v instanceof Date && !isNaN(v.getTime())) return ok(isoDate(v));
568
+ if (typeof v === "string" && DATE_RE.test(v)) return ok(v);
569
+ if (typeof v === "string" && DATETIME_RE.test(v)) return ok(v.slice(0, 10));
570
+ return bad("expected date YYYY-MM-DD");
571
+ }
572
+ function datetime(v) {
573
+ if (v instanceof Date && !isNaN(v.getTime())) return ok(rfc3339(v));
574
+ if (typeof v === "string" && DATETIME_RE.test(v)) return ok(v);
575
+ return bad("expected RFC 3339 datetime with offset");
576
+ }
577
+ function arr(v, f) {
578
+ if (!Array.isArray(v)) return bad("expected array");
579
+ const out = [];
580
+ for (const x of v) {
581
+ const r = f(x);
582
+ if (!r.ok) return bad(`array element: ${r.reason}`);
583
+ out.push(r.value);
584
+ }
585
+ return ok(out);
586
+ }
587
+
588
+ // src/core/validate.ts
589
+ var FORBIDDEN_PARAMS = /* @__PURE__ */ new Set(["customer_id", "cif", "national_id", "phone_number", "email", "profile_id"]);
590
+ var NAME_RE = /^[a-z][a-z0-9]*(_[a-z0-9]+)*$/;
591
+ var CORRELATION = {
592
+ channel: "string",
593
+ message_id: "string",
594
+ variant_id: "string",
595
+ message_type: "string",
596
+ campaign_id: "string",
597
+ campaign_name: "string",
598
+ campaign_type: "string",
599
+ journey_id: "string",
600
+ journey_name: "string",
601
+ journey_version: "number",
602
+ journey_node_id: "string",
603
+ content_id: "string",
604
+ is_test: "boolean",
605
+ dry_run: "boolean"
606
+ };
607
+ var CORRELATION_REQUIRED = ["channel", "message_id", "variant_id", "message_type"];
608
+ function prepareEvent(name, raw, opts, cat = catalog) {
609
+ var _a, _b, _c, _d, _e, _f, _g;
610
+ const errors = [];
611
+ const warnings = [];
612
+ if (!NAME_RE.test(name) || name.length > 64) return { ok: false, errors: [`event name "${name}" must be lower_snake_case, max 64 chars (R-01)`] };
613
+ const def = cat.events[name];
614
+ if (def && !def.web) return { ok: false, errors: [`event "${name}" is not sent by Web SDK (source: ${def.app ? "App SDK" : "platform / server"})`] };
615
+ if (!def && !opts.allowUnknown) {
616
+ return { ok: false, errors: [`event "${name}" is not in catalog v${cat.version}; set allowUnknownEvents to send as Pending (R-09)`] };
617
+ }
618
+ const out = {};
619
+ const corrOut = {};
620
+ const input = raw != null ? raw : {};
621
+ for (const [key, value] of Object.entries(input)) {
622
+ if (value === void 0 || value === null) continue;
623
+ if (FORBIDDEN_PARAMS.has(key)) {
624
+ errors.push(`param "${key}" is an identifier; use identify() instead (R-02)`);
625
+ continue;
626
+ }
627
+ const pdef = (_b = def == null ? void 0 : def.params[key]) != null ? _b : (_a = cat.mutual) == null ? void 0 : _a[key];
628
+ const corr = (def == null ? void 0 : def.correlation) || !def ? CORRELATION[key] : void 0;
629
+ const type = (_e = (_c = pdef == null ? void 0 : pdef.type) != null ? _c : corr) != null ? _e : def ? void 0 : (_d = cat.params[key]) == null ? void 0 : _d.type;
630
+ if (corr && !(def == null ? void 0 : def.params[key])) {
631
+ const r2 = normalize(value, corr);
632
+ if (r2.ok) corrOut[key] = r2.value;
633
+ else errors.push(`param "${key}": ${r2.reason}`);
634
+ continue;
635
+ }
636
+ if (!def) {
637
+ const t = type != null ? type : inferType(value);
638
+ const r2 = normalize(value, t);
639
+ if (r2.ok) out[key] = r2.value;
640
+ else warnings.push(`param "${key}" dropped: ${r2.reason}`);
641
+ continue;
642
+ }
643
+ if (!type) {
644
+ warnings.push(`param "${key}" is not defined for event "${name}" and was dropped`);
645
+ continue;
646
+ }
647
+ const r = normalize(value, type);
648
+ if (!r.ok) {
649
+ errors.push(`param "${key}": ${r.reason}`);
650
+ continue;
651
+ }
652
+ let v = r.value;
653
+ const en = (_f = cat.params[key]) == null ? void 0 : _f.enum;
654
+ if (en && type === "string") {
655
+ const raw2 = String(v).trim();
656
+ const hit = en.includes(raw2) ? raw2 : en.find((x) => x.toLowerCase() === raw2.toLowerCase());
657
+ if (hit !== void 0) v = hit;
658
+ else warnings.push(`param "${key}": "${raw2}" not in [${en.join(", ")}] (value_not_allowed)`);
659
+ }
660
+ if (((_g = cat.params[key]) == null ? void 0 : _g.free) && !key.endsWith("_code") && typeof v === "string") v = redactPii(v, warnings, key);
661
+ out[key] = v;
662
+ }
663
+ if (def) {
664
+ for (const [k, p] of Object.entries(def.params)) if (p.required && !(k in out)) errors.push(`missing required param "${k}"`);
665
+ if (def.correlation) {
666
+ for (const k of CORRELATION_REQUIRED) if (!(k in out) && !(k in corrOut)) errors.push(`missing correlation param "${k}" (R-07)`);
667
+ }
668
+ }
669
+ if (errors.length) return { ok: false, errors };
670
+ return { ok: true, def, params: out, correlation: corrOut, warnings };
671
+ }
672
+ function inferType(v) {
673
+ if (typeof v === "number") return "number";
674
+ if (typeof v === "boolean") return "boolean";
675
+ if (v instanceof Date) return "datetime";
676
+ if (Array.isArray(v)) return v.every((x) => typeof x === "number") && v.length ? "number[]" : "string[]";
677
+ return "string";
678
+ }
679
+ var PII = [
680
+ /[\w.+-]+@[\w-]+\.[\w.-]+/g,
681
+ // email
682
+ /(?:\+84|0)(?:[\s.-]?\d){9,10}\b/g,
683
+ // số điện thoại VN
684
+ /\b\d{12}\b|\b\d{9}\b/g
685
+ // CCCD 12 số / CMND 9 số
686
+ ];
687
+ function redactPii(text, warnings, key) {
688
+ let out = text;
689
+ for (const re of PII) out = out.replace(re, "[redacted]");
690
+ if (out !== text) warnings.push(`param "${key}": personal data redacted from free text (R-06)`);
691
+ return out;
692
+ }
693
+
694
+ // src/core/sdk.ts
695
+ var UTM_KEYS = ["utm_source", "utm_medium", "utm_campaign", "utm_content", "utm_term"];
696
+ var MAX_REQUEST_BYTES = 64 * 1024;
697
+ var MAX_REQUEST_RECORDS = 100;
698
+ var QUEUED_AFTER_MS = 1e4;
699
+ var DICT_WAIT_MS = 3e3;
700
+ var err = (code, message, errors) => Object.assign(new Error(message), { code, errors });
701
+ var CdpSdk = class {
702
+ constructor() {
703
+ this.log = new Logger(false);
704
+ this.deviceId = "";
705
+ this.ready = false;
706
+ this.activated = false;
707
+ this.gate = Promise.resolve();
708
+ this.flushing = false;
709
+ this.flushAgain = false;
710
+ this.attempt = 0;
711
+ this.pausedUntil = 0;
712
+ this.stopped = "";
713
+ this.timerAt = 0;
714
+ this.consents = {};
715
+ this.lastPageUrl = "";
716
+ this.waiters = /* @__PURE__ */ new Map();
717
+ this.unsent = /* @__PURE__ */ new Map();
718
+ // bản ghi của tab này chưa được server xác nhận (dùng khi rời trang)
719
+ /** Event gọi khi từ điển của server chưa có (lần mở trang đầu): chạy lần lượt khi từ điển tải xong / lỗi / quá DICT_WAIT_MS */
720
+ this.waiting = null;
721
+ this.handlers = /* @__PURE__ */ new Map();
722
+ this.listeners = [];
723
+ /** Event giữ lại cho module gắn vào sau (bộ chạy popup / banner tải sau ở bản <script>): xem holdEvents() */
724
+ this.held = null;
725
+ this.grantedHooks = [];
726
+ /** Cho phép module ngoài (autotrack…) gắn hook sau khi init */
727
+ this.onInit = [];
728
+ }
729
+ get http() {
730
+ return this.transport;
731
+ }
732
+ get storage() {
733
+ return this.store;
734
+ }
735
+ get config() {
736
+ return this.cfg;
737
+ }
738
+ get catalog() {
739
+ var _a, _b;
740
+ return (_b = (_a = this.dict) == null ? void 0 : _a.current) != null ? _b : catalog;
741
+ }
742
+ get isReady() {
743
+ return this.ready;
744
+ }
745
+ get sessionId() {
746
+ return this.session.touch().id;
747
+ }
748
+ get trackingBlocked() {
749
+ return this.blocked();
750
+ }
751
+ /** Resolve khi cid đã đồng bộ với server (đăng ký thiết bị, và identify đang chạy nếu có). */
752
+ whenSynced() {
753
+ return this.gate;
754
+ }
755
+ // ---------- vòng đời ----------
756
+ /** Khởi tạo. Không bao giờ ném lỗi: thiếu cấu hình thì ghi cảnh báo và SDK ở trạng thái tắt. Promise resolve khi thiết bị đã đăng ký với nền tảng. */
757
+ init(config) {
758
+ if (this.ready) {
759
+ this.log.warn("init() called twice, ignored");
760
+ return this.gate;
761
+ }
762
+ const r = resolveConfig(config != null ? config : {});
763
+ if ("error" in r) {
764
+ console.warn(`[bizcdp] ${r.error}`);
765
+ return Promise.resolve();
766
+ }
767
+ this.cfg = r.cfg;
768
+ this.log = new Logger(this.cfg.debug);
769
+ this.store = new Storage(this.cfg.storagePrefix, this.cfg.cookieDomain);
770
+ this.queue = new EventQueue(this.store, this.cfg.maxQueueSize, this.cfg.maxQueueAgeMs);
771
+ this.transport = new Transport({ apiHost: this.cfg.apiHost, sdkKey: this.cfg.sdkKey }, this.log);
772
+ this.session = new Session(this.store, this.cfg.sessionTimeoutMs);
773
+ this.dict = new Dictionary(this.store);
774
+ this.consents = this.loadConsents();
775
+ this.ready = true;
776
+ this.deviceId = loadDeviceId(this.store, !this.blocked());
777
+ this.log.log("initialised", { sdk: SDK_VERSION, env: this.cfg.env, deviceId: this.deviceId, dictionary: this.dict.current.version });
778
+ if (!this.blocked()) this.activate();
779
+ this.onInit.forEach((f) => {
780
+ try {
781
+ f();
782
+ } catch (e) {
783
+ this.log.warn("onInit error", e);
784
+ }
785
+ });
786
+ return this.gate;
787
+ }
788
+ /** Bắt đầu thu thập: lưu device_id, đăng ký thiết bị, tải từ điển, gắn sự kiện trình duyệt */
789
+ activate() {
790
+ if (this.activated) return;
791
+ this.activated = true;
792
+ savePersist(this.store, this.deviceId);
793
+ this.gate = this.registerDevice().then(() => {
794
+ this.fire("ready");
795
+ this.schedule(this.cfg.batchIntervalMs);
796
+ }, () => void 0);
797
+ const loading = this.dict.refresh(this.transport).catch(() => false);
798
+ if (!this.dict.fromServer) {
799
+ this.waiting = [];
800
+ const t = setTimeout(() => this.releaseWaiting(), DICT_WAIT_MS);
801
+ void loading.then(() => {
802
+ clearTimeout(t);
803
+ this.releaseWaiting();
804
+ });
805
+ }
806
+ if (typeof window !== "undefined") {
807
+ window.addEventListener("online", () => {
808
+ this.attempt = 0;
809
+ void this.flush();
810
+ });
811
+ window.addEventListener("pagehide", () => {
812
+ this.releaseWaiting();
813
+ this.flushOnUnload();
814
+ });
815
+ document.addEventListener("visibilitychange", () => {
816
+ if (document.visibilityState === "hidden") {
817
+ this.releaseWaiting();
818
+ this.flushOnUnload();
819
+ }
820
+ });
821
+ }
822
+ }
823
+ /**
824
+ * Mỗi lần mở trang: hỏi server hồ sơ hiện tại của thiết bị, vì cid lưu ở trình duyệt có thể không còn đúng (hồ sơ bị
825
+ * gộp / xoá, dữ liệu được đặt lại). cid đổi thì quên những gì đã gửi theo cid cũ (identify, đăng ký push) để gửi lại.
826
+ * Gọi lỗi thì dùng tiếp cid đang lưu.
827
+ */
828
+ async registerDevice() {
829
+ var _a, _b;
830
+ const p = getProfile(this.store);
831
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : "";
832
+ const r = await this.transport.getOrCreateDevice({ deviceId: this.deviceId, platform: "web", model: null, osVersion: (_a = osVersion(ua)) != null ? _a : null, appVersion: (_b = this.cfg.appVersion) != null ? _b : null, sdkVersion: SDK_VERSION });
833
+ if (r.ok && r.json && typeof r.json.cid === "number") {
834
+ setProfile(this.store, { cid: r.json.cid, profileStatus: r.json.profileStatus, mappingVersion: r.json.mappingVersion, fetchedAt: Date.now() });
835
+ if (p && p.cid !== r.json.cid) {
836
+ this.store.remove("idh");
837
+ this.store.remove("push");
838
+ this.fire("cidChanged", { cid: r.json.cid, previous: p.cid });
839
+ }
840
+ } else this.onHttpFailure("device/get-or-create", r.status);
841
+ }
842
+ releaseWaiting() {
843
+ const w = this.waiting;
844
+ if (!w) return;
845
+ this.waiting = null;
846
+ w.forEach((f) => {
847
+ try {
848
+ f();
849
+ } catch (e) {
850
+ this.log.warn("deferred event error", e);
851
+ }
852
+ });
853
+ }
854
+ onHttpFailure(where, status) {
855
+ if (status === 401 || status === 403) this.halt(`${where}: ${status}`);
856
+ else this.log.warn(`${where} failed`, status);
857
+ }
858
+ halt(reason) {
859
+ this.stopped = reason;
860
+ this.waiters.forEach((w) => w.res({ status: "queued", reason: "stopped" }));
861
+ this.waiters.clear();
862
+ console.warn(`[bizcdp] g\u1EEDi d\u1EEF li\u1EC7u b\u1ECB d\u1EEBng: ${reason} (ki\u1EC3m tra sdkKey / allowed_origins)`);
863
+ this.fire("error", { code: "stopped", reason });
864
+ }
865
+ // ---------- sự kiện công khai ----------
866
+ on(event, cb) {
867
+ var _a;
868
+ const a = (_a = this.handlers.get(event)) != null ? _a : [];
869
+ a.push(cb);
870
+ this.handlers.set(event, a);
871
+ return () => {
872
+ var _a2;
873
+ return this.handlers.set(event, ((_a2 = this.handlers.get(event)) != null ? _a2 : []).filter((x) => x !== cb));
874
+ };
875
+ }
876
+ fire(event, data) {
877
+ var _a;
878
+ ((_a = this.handlers.get(event)) != null ? _a : []).forEach((f) => {
879
+ try {
880
+ f(data);
881
+ } catch (e) {
882
+ this.log.warn("handler error", e);
883
+ }
884
+ });
885
+ }
886
+ /** Module (campaign trigger) lắng nghe mọi event đã được chấp nhận */
887
+ /** `replay`: nhận lại các event đã giữ từ lúc holdEvents() (rồi thôi giữ). */
888
+ onEvent(fn, replay = false) {
889
+ this.listeners.push(fn);
890
+ if (!replay || !this.held) return;
891
+ const held = this.held;
892
+ this.held = null;
893
+ held.forEach(([n, p]) => {
894
+ try {
895
+ fn(n, p);
896
+ } catch (e) {
897
+ this.log.warn("listener error", e);
898
+ }
899
+ });
900
+ }
901
+ /** Bắt đầu giữ event đã chấp nhận (tối đa 100) cho tới khi có listener `onEvent(fn, true)`: module tải sau không lỡ event
902
+ * (trigger "khi có event", điều kiện "mọi event đã xảy ra trong phiên"). */
903
+ holdEvents() {
904
+ if (!this.held) this.held = [];
905
+ }
906
+ onIdentify(fn) {
907
+ this.on("identified", fn);
908
+ }
909
+ onConsentGranted(fn) {
910
+ this.grantedHooks.push(fn);
911
+ }
912
+ track(name, params) {
913
+ return this.record(name, params);
914
+ }
915
+ /** Gửi page_view thủ công (khi autoPageView = false hoặc trang tự dựng) */
916
+ page(params) {
917
+ return this.record("page_view", { page_title: typeof document !== "undefined" ? document.title || void 0 : void 0, ...params });
918
+ }
919
+ /** Gọi sau khi đăng nhập / đổi tài khoản. Mã KH, CCCD, SĐT, email chỉ đi qua đây. */
920
+ identify(ids) {
921
+ if (!this.ready) return Promise.reject(err("not_initialised", "identify() called before init()"));
922
+ const run = this.gate.then(() => this.doIdentify(ids));
923
+ this.gate = run.then(() => void 0, () => void 0);
924
+ return run;
925
+ }
926
+ async doIdentify(ids) {
927
+ var _a, _b, _c, _d, _e, _f, _g;
928
+ if (this.blocked()) throw err("consent_required", "identify skipped: no analytics consent");
929
+ if (this.stopped) throw err("stopped", this.stopped);
930
+ const identifiers = normalizeIdentifiers(ids != null ? ids : {});
931
+ const list = toIdentifierList(identifiers);
932
+ if (!list.length) throw err("no_identifier", "identify needs at least one identifier");
933
+ const hash = await identifiersHash(identifiers);
934
+ const cur = getProfile(this.store);
935
+ if (cur && this.store.get("idh") === hash) return { cid: cur.cid, action: "use", mappingVersion: cur.mappingVersion };
936
+ const send = (currentCid) => this.transport.identify({ deviceId: this.deviceId, currentCid, platform: "web", identifiers: list });
937
+ let r = await send((_a = cur == null ? void 0 : cur.cid) != null ? _a : null);
938
+ if (cur && r.status === 400 && ((_b = r.json) == null ? void 0 : _b.errorCode) === "unknown_profile") {
939
+ this.log.warn("stored cid is unknown to the server, registering the device again", cur.cid);
940
+ setProfile(this.store, void 0);
941
+ this.store.remove("idh");
942
+ this.store.remove("push");
943
+ await this.registerDevice();
944
+ r = await send((_d = (_c = getProfile(this.store)) == null ? void 0 : _c.cid) != null ? _d : null);
945
+ if (this.cfg.webPush.enabled) void ((_e = this.webPush) == null ? void 0 : _e.refresh());
946
+ }
947
+ if (!r.ok || !r.json || typeof r.json.cid !== "number") {
948
+ if (r.status === 400) throw err(((_f = r.json) == null ? void 0 : _f.errorCode) || "no_identifier", ((_g = r.json) == null ? void 0 : _g.message) || "identify rejected");
949
+ this.onHttpFailure("identify", r.status);
950
+ const known = getProfile(this.store);
951
+ if (known) setProfile(this.store, { ...known, fetchedAt: 0 });
952
+ throw err(r.status === 0 ? "network_error" : `http_${r.status}`, "identify failed");
953
+ }
954
+ const out = r.json;
955
+ this.store.set("idh", hash);
956
+ setProfile(this.store, { cid: out.cid, profileStatus: "identified", mappingVersion: out.mappingVersion, fetchedAt: Date.now() });
957
+ this.log.log("identified", out);
958
+ if (cur && cur.cid !== out.cid) this.fire("cidChanged", { cid: out.cid, previous: cur.cid, action: out.action });
959
+ this.fire("identified", out);
960
+ return { cid: out.cid, caseCode: out.caseCode, action: out.action, mappingVersion: out.mappingVersion };
961
+ }
962
+ /** Đăng xuất: giữ device_id và cid trong bộ nhớ (TI-R-07), bắt đầu phiên mới, quên hash identify. */
963
+ async logout() {
964
+ if (!this.ready) return;
965
+ this.store.remove("idh");
966
+ this.session.reset();
967
+ if (this.blocked()) return;
968
+ await this.flush();
969
+ const r = await this.transport.logout(this.deviceId);
970
+ if (!r.ok) this.onHttpFailure("logout", r.status);
971
+ }
972
+ setAttribute(name, value, mode = "replace") {
973
+ return this.setAttributes({ [name]: value }, mode);
974
+ }
975
+ /** Cập nhật thuộc tính hồ sơ theo từ điển. Giá trị là định danh (SĐT, email…) không đi qua đây mà qua identify (TI-R-08). */
976
+ setAttributes(attrs, mode = "replace") {
977
+ if (!this.ready) return Promise.reject(err("not_initialised", "setAttributes() called before init()"));
978
+ if (this.blocked()) return Promise.resolve({ status: "dropped", reason: "consent" });
979
+ const defs = this.dict.current.attributes;
980
+ const out = {};
981
+ const errors = [];
982
+ for (const [k, raw] of Object.entries(attrs != null ? attrs : {})) {
983
+ if (raw === void 0) continue;
984
+ const def = defs[k];
985
+ const meta = def != null ? def : catalog.attributes[k];
986
+ const forbidden = (meta == null ? void 0 : meta.identifier) ? "identifier_as_attribute" : (meta == null ? void 0 : meta.platformOnly) ? "platform_attribute" : "";
987
+ if (forbidden || !def) {
988
+ if (!forbidden && this.cfg.allowUnknownAttributes) {
989
+ out[k] = raw instanceof Date ? raw.toISOString() : raw;
990
+ continue;
991
+ }
992
+ const code = forbidden || "unknown_attribute";
993
+ this.log.warn(`attribute "${k}" not sent (${forbidden === "identifier_as_attribute" ? "d\xF9ng identify()" : code})`);
994
+ errors.push({ field: k, code });
995
+ continue;
996
+ }
997
+ if (raw === null) {
998
+ out[k] = null;
999
+ continue;
1000
+ }
1001
+ const r = normalize(raw, def.type);
1002
+ if (!r.ok) {
1003
+ this.log.warn(`attribute "${k}" dropped: ${r.reason}`);
1004
+ errors.push({ field: k, code: "bad_type" });
1005
+ continue;
1006
+ }
1007
+ if (def.options && !(Array.isArray(r.value) ? r.value : [r.value]).every((v) => def.options.includes(String(v)))) {
1008
+ this.log.warn(`attribute "${k}": value not in [${def.options.join(", ")}]`);
1009
+ errors.push({ field: k, code: "value_not_allowed" });
1010
+ continue;
1011
+ }
1012
+ out[k] = r.value;
1013
+ }
1014
+ if (!Object.keys(out).length) return Promise.reject(err("validation_failed", "no valid attribute to send", errors));
1015
+ const id = uuid();
1016
+ const rec = { record_type: "attribute", source_record_id: id, device_id: this.deviceId, values: out, ...mode !== "replace" ? { update_mode: mode } : {} };
1017
+ return this.enqueue(id, rec, true);
1018
+ }
1019
+ /** Đồng ý / rút đồng ý. `setConsent('analytics', true)`; dạng cũ `setConsent('granted')` = analytics. Phát event consent_updated. */
1020
+ setConsent(category, value, opts = {}) {
1021
+ var _a;
1022
+ if (!this.ready) return Promise.reject(err("not_initialised", "setConsent() called before init()"));
1023
+ if (value === void 0 && (category === "granted" || category === "withdrawn")) {
1024
+ value = category;
1025
+ category = "analytics";
1026
+ }
1027
+ const status = value === true || value === "granted" ? "granted" : "withdrawn";
1028
+ this.consents[category] = status;
1029
+ this.store.setJSON("consent", this.consents);
1030
+ const values = { consent_type: category, consent_status: status, change_source: (_a = opts.changeSource) != null ? _a : "web_settings", ...opts.channel ? { channel: opts.channel } : {} };
1031
+ if (category === "analytics" && status === "withdrawn") {
1032
+ this.unsent.clear();
1033
+ this.rejectAll("consent");
1034
+ return this.queue.clear().then(() => this.record("consent_updated", values, { bypass: true, direct: true }));
1035
+ }
1036
+ if (category === "analytics" && status === "granted") {
1037
+ if (!this.activated) this.activate();
1038
+ const p = this.record("consent_updated", values, { bypass: true });
1039
+ this.grantedHooks.forEach((f) => {
1040
+ try {
1041
+ f();
1042
+ } catch (e) {
1043
+ this.log.warn("hook error", e);
1044
+ }
1045
+ });
1046
+ return p;
1047
+ }
1048
+ return this.record("consent_updated", values);
1049
+ }
1050
+ /** Xoá toàn bộ dữ liệu cục bộ (device_id, cid, phiên, hàng đợi) — dùng khi phát triển / kiểm thử */
1051
+ async reset() {
1052
+ if (!this.ready) return;
1053
+ for (const k of ["did", "profile", "sid", "utm", "idh", "dict", "consent"]) this.store.remove(k);
1054
+ this.store.removeCookie("did");
1055
+ this.unsent.clear();
1056
+ this.rejectAll("reset");
1057
+ await this.queue.clear();
1058
+ this.consents = {};
1059
+ }
1060
+ getDeviceId() {
1061
+ return this.deviceId;
1062
+ }
1063
+ getCid() {
1064
+ var _a;
1065
+ return this.ready ? (_a = getProfile(this.store)) == null ? void 0 : _a.cid : void 0;
1066
+ }
1067
+ /** Thiết bị đang gắn với hồ sơ đã định danh (không còn anonymous) */
1068
+ isIdentified() {
1069
+ const p = this.ready ? getProfile(this.store) : void 0;
1070
+ return !!p && !!p.profileStatus && p.profileStatus !== "anonymous";
1071
+ }
1072
+ /** Gửi ngay mọi bản ghi đang chờ. */
1073
+ async flush() {
1074
+ if (!this.ready || !this.activated || this.stopped || this.blocked()) return;
1075
+ if (this.flushing) {
1076
+ this.flushAgain = true;
1077
+ return;
1078
+ }
1079
+ this.flushing = true;
1080
+ try {
1081
+ await this.gate;
1082
+ await this.queue.ready;
1083
+ await this.locked(async () => {
1084
+ for (; ; ) {
1085
+ if (this.stopped || Date.now() < this.pausedUntil) return;
1086
+ const batch = await this.queue.peek(MAX_REQUEST_RECORDS, MAX_REQUEST_BYTES);
1087
+ if (!batch.length) {
1088
+ this.attempt = 0;
1089
+ return;
1090
+ }
1091
+ const out = await this.transport.sendRecords(batch.map((b) => b.rec));
1092
+ if (out.kind === "ok") {
1093
+ this.attempt = 0;
1094
+ await this.queue.remove(batch);
1095
+ this.settle(batch, out.results);
1096
+ continue;
1097
+ }
1098
+ if (out.kind === "retry") {
1099
+ this.attempt++;
1100
+ this.schedule(backoff(this.attempt), true);
1101
+ return;
1102
+ }
1103
+ if (out.kind === "pause") {
1104
+ this.pausedUntil = out.until;
1105
+ this.log.warn("rate limited, pause until", new Date(out.until).toISOString());
1106
+ this.schedule(out.until - Date.now() + 50, true);
1107
+ return;
1108
+ }
1109
+ if (out.kind === "stop") {
1110
+ this.halt(out.reason);
1111
+ return;
1112
+ }
1113
+ await this.queue.remove(batch);
1114
+ this.settle(batch, batch.map((_, index) => {
1115
+ var _a, _b;
1116
+ return { index, status: "rejected", reason: (_a = out.message) != null ? _a : `http_${out.status}`, errors: [{ code: (_b = out.message) != null ? _b : `http_${out.status}` }] };
1117
+ }));
1118
+ }
1119
+ });
1120
+ } catch (e) {
1121
+ this.log.warn("flush error", e);
1122
+ } finally {
1123
+ this.flushing = false;
1124
+ if (this.flushAgain) {
1125
+ this.flushAgain = false;
1126
+ this.schedule(0);
1127
+ }
1128
+ }
1129
+ }
1130
+ // ---------- nội bộ ----------
1131
+ /** Dùng bởi module (autotrack, popup, push): gửi event, lỗi chỉ được log */
1132
+ emit(name, params, bypassConsent = false, internal = false) {
1133
+ this.record(name, params, { bypass: bypassConsent, internal }).catch((e) => {
1134
+ var _a;
1135
+ return this.log.warn(`event "${name}" not sent:`, e.message, (_a = e.errors) != null ? _a : "");
1136
+ });
1137
+ }
1138
+ /** Hàm xử lý chung cho track/emit */
1139
+ record(name, params, o = {}) {
1140
+ if (!this.ready) return Promise.reject(err("not_initialised", `${name}: track() called before init()`));
1141
+ if (!o.bypass && this.blocked()) return Promise.resolve({ status: "dropped", reason: "consent" });
1142
+ if (this.waiting) {
1143
+ const ctx = this.capture(name, o);
1144
+ return new Promise((res, rej) => {
1145
+ this.waiting.push(() => {
1146
+ this.recordNow(name, params, o, ctx).then(res, rej);
1147
+ });
1148
+ });
1149
+ }
1150
+ return this.recordNow(name, params, o);
1151
+ }
1152
+ /** Phiên + giờ + trang lúc event xảy ra. Mở phiên mới thì phát session_start trước. */
1153
+ capture(name, o) {
1154
+ const s = this.session.touch();
1155
+ if (s.isNew && !o.internal && !o.direct && name !== "session_start" && this.cfg.autoSession) this.emit("session_start", { landing_url: this.url() }, false, true);
1156
+ return { time: rfc3339(), sid: s.id, url: this.url(), ref: document.referrer ? cleanUrl(document.referrer, this.cfg.sensitiveQueryParams) : void 0, utm: this.captureUtm() };
1157
+ }
1158
+ recordNow(name, params, o, ctx) {
1159
+ const prep = prepareEvent(name, params, { allowUnknown: this.cfg.allowUnknownEvents }, this.dict.current);
1160
+ if (!prep.ok) {
1161
+ const e = err("validation_failed", `event "${name}" rejected: ${prep.errors.join("; ")}`, prep.errors.map((m) => ({ code: m })));
1162
+ this.fire("error", e);
1163
+ return Promise.reject(e);
1164
+ }
1165
+ prep.warnings.forEach((w) => this.log.warn(`${name}: ${w}`));
1166
+ const c = ctx != null ? ctx : this.capture(name, o);
1167
+ const ua = typeof navigator !== "undefined" ? navigator.userAgent : void 0;
1168
+ const id = uuid();
1169
+ const rec = {
1170
+ record_type: "event",
1171
+ name,
1172
+ event_id: id,
1173
+ event_time: c.time,
1174
+ source: "web_sdk",
1175
+ device_id: this.deviceId,
1176
+ session_id: c.sid,
1177
+ platform: "web",
1178
+ sdk_version: SDK_VERSION,
1179
+ app_version: this.cfg.appVersion,
1180
+ os_version: ua ? osVersion(ua) : void 0,
1181
+ user_agent: ua,
1182
+ page_url: c.url,
1183
+ referrer: c.ref,
1184
+ ...c.utm,
1185
+ ...prep.correlation,
1186
+ values: prep.params
1187
+ };
1188
+ if (name === "session_start" && !("landing_url" in rec.values)) rec.values = { landing_url: c.url, ...rec.values };
1189
+ this.log.log("track", name, rec);
1190
+ this.listeners.forEach((f) => {
1191
+ try {
1192
+ f(name, prep.params);
1193
+ } catch (e) {
1194
+ this.log.warn("listener error", e);
1195
+ }
1196
+ });
1197
+ if (this.held && this.held.length < 100) this.held.push([name, prep.params]);
1198
+ if (o.direct) return this.sendDirect(rec);
1199
+ const realtime = prep.def ? prep.def.sendMode === "realtime" : true;
1200
+ return this.enqueue(id, rec, realtime);
1201
+ }
1202
+ enqueue(id, rec, realtime) {
1203
+ return new Promise((res, rej) => {
1204
+ this.waiters.set(id, { res, rej });
1205
+ this.unsent.set(id, rec);
1206
+ if (this.stopped) {
1207
+ this.waiters.delete(id);
1208
+ res({ status: "queued", reason: "stopped" });
1209
+ } else setTimeout(() => {
1210
+ if (this.waiters.delete(id)) res({ status: "queued" });
1211
+ }, QUEUED_AFTER_MS);
1212
+ void this.queue.add(rec).then(() => {
1213
+ if (realtime) this.schedule(20);
1214
+ else if (this.unsent.size >= this.cfg.batchSize) this.schedule(0);
1215
+ else this.schedule(this.cfg.batchIntervalMs);
1216
+ }, () => this.log.warn("queue write failed"));
1217
+ });
1218
+ }
1219
+ /** Gửi riêng một bản ghi, không qua hàng đợi (event rút consent: hàng đợi đã bị xoá và việc gửi bình thường đã dừng) */
1220
+ async sendDirect(rec) {
1221
+ var _a;
1222
+ if (!this.activated || this.stopped) return { status: "dropped", reason: "not_sending" };
1223
+ await this.gate;
1224
+ for (let i = 1; i <= 3; i++) {
1225
+ const out = await this.transport.sendRecords([rec]);
1226
+ if (out.kind === "ok") {
1227
+ const r = out.results[0];
1228
+ return (r == null ? void 0 : r.status) === "rejected" ? Promise.reject(err(r.reason || "rejected", "server rejected consent_updated", r.errors)) : { status: (_a = r == null ? void 0 : r.status) != null ? _a : "accepted", warnings: r == null ? void 0 : r.warnings };
1229
+ }
1230
+ if (out.kind !== "retry") break;
1231
+ await new Promise((ok2) => setTimeout(ok2, backoff(i)));
1232
+ }
1233
+ return { status: "dropped", reason: "send_failed" };
1234
+ }
1235
+ /** Báo kết quả từng bản ghi cho nơi gọi track()/setAttributes() */
1236
+ settle(batch, results) {
1237
+ batch.forEach((b, i) => {
1238
+ var _a, _b, _c, _d, _e, _f;
1239
+ const id = (_a = b.rec.event_id) != null ? _a : b.rec.source_record_id;
1240
+ this.unsent.delete(id);
1241
+ const r = (_b = results.find((x) => x.index === i)) != null ? _b : { index: i, status: "accepted" };
1242
+ const w = this.waiters.get(id);
1243
+ this.waiters.delete(id);
1244
+ if (r.status === "rejected") {
1245
+ const e = err(r.reason || "rejected", `server rejected ${(_c = b.rec.name) != null ? _c : "attribute"}: ${(_f = (_e = r.reason) != null ? _e : (_d = r.errors) == null ? void 0 : _d.map((x) => x.code).join(",")) != null ? _f : ""}`, r.errors);
1246
+ this.log.warn(e.message);
1247
+ this.fire("error", e);
1248
+ w == null ? void 0 : w.rej(e);
1249
+ } else w == null ? void 0 : w.res({ status: r.status, warnings: r.warnings });
1250
+ });
1251
+ }
1252
+ rejectAll(reason) {
1253
+ this.waiters.forEach((w) => w.res({ status: "dropped", reason }));
1254
+ this.waiters.clear();
1255
+ }
1256
+ blocked() {
1257
+ var _a;
1258
+ const a = this.consents.analytics;
1259
+ return a === "withdrawn" || !!((_a = this.cfg) == null ? void 0 : _a.requireConsent) && a !== "granted";
1260
+ }
1261
+ loadConsents() {
1262
+ var _a;
1263
+ const raw = (_a = this.store.getJSON("consent")) != null ? _a : this.store.get("consent");
1264
+ if (raw === "granted" || raw === "withdrawn") return { analytics: raw };
1265
+ return raw && typeof raw === "object" ? raw : {};
1266
+ }
1267
+ url() {
1268
+ return cleanUrl(location.href, this.cfg.sensitiveQueryParams);
1269
+ }
1270
+ /** utm_* lấy từ URL landing, giữ suốt phiên web */
1271
+ captureUtm() {
1272
+ const stored = this.store.getSession("utm");
1273
+ let utm = {};
1274
+ try {
1275
+ utm = stored ? JSON.parse(stored) : {};
1276
+ } catch {
1277
+ }
1278
+ try {
1279
+ const q = new URLSearchParams(location.search);
1280
+ const fresh = {};
1281
+ for (const k of UTM_KEYS) {
1282
+ const v = q.get(k);
1283
+ if (v) fresh[k] = v.slice(0, 256);
1284
+ }
1285
+ if (Object.keys(fresh).length) {
1286
+ utm = fresh;
1287
+ this.store.setSession("utm", JSON.stringify(utm));
1288
+ }
1289
+ } catch {
1290
+ }
1291
+ return utm;
1292
+ }
1293
+ /** Lên lịch gửi: lịch sớm hơn thắng lịch muộn hơn; `force` (backoff) thay lịch hiện có */
1294
+ schedule(ms, force = false) {
1295
+ const at = Date.now() + ms;
1296
+ if (this.timer && !force && this.timerAt <= at) return;
1297
+ if (this.timer) clearTimeout(this.timer);
1298
+ this.timerAt = at;
1299
+ this.timer = setTimeout(() => {
1300
+ this.timer = void 0;
1301
+ void this.flush();
1302
+ }, Math.max(0, ms));
1303
+ }
1304
+ /** Nhiều tab: chỉ một tab gửi tại một thời điểm (Web Locks), tránh gửi trùng */
1305
+ locked(fn) {
1306
+ const locks = typeof navigator !== "undefined" ? navigator.locks : void 0;
1307
+ return locks ? locks.request("bzc-flush", fn) : fn();
1308
+ }
1309
+ /** Rời trang: gửi bản ghi chưa được xác nhận bằng fetch keepalive (sendBeacon không có header x-api-key). Giữ trong hàng đợi, server loại trùng theo event_id. */
1310
+ flushOnUnload() {
1311
+ if (!this.activated || this.stopped || this.blocked() || !this.unsent.size || Date.now() < this.pausedUntil) return;
1312
+ void this.transport.sendRecords([...this.unsent.values()].slice(0, MAX_REQUEST_RECORDS), true);
1313
+ }
1314
+ /** Cho module autotrack */
1315
+ markPage(url) {
1316
+ if (url === this.lastPageUrl) return false;
1317
+ this.lastPageUrl = url;
1318
+ return true;
1319
+ }
1320
+ };
1321
+
1322
+ // src/modules/renderer.ts
1323
+ var HEX = /^#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i;
1324
+ var color = (v, fallback) => v && HEX.test(v) ? v : fallback;
1325
+ var clip = (s, n = 500) => String(s != null ? s : "").slice(0, n);
1326
+ var runtime = {
1327
+ deeplinks: false,
1328
+ open: (url, newTab) => {
1329
+ if (newTab) window.open(url, "_blank", "noopener,noreferrer");
1330
+ else location.assign(url);
1331
+ }
1332
+ };
1333
+ var BLOCKED_SCHEMES = /^(?:javascript|data|vbscript|file|blob|about|filesystem):$/i;
1334
+ function safeUrl(u) {
1335
+ if (typeof u !== "string" || !u.trim()) return null;
1336
+ try {
1337
+ const url = new URL(u, location.href);
1338
+ if (url.protocol === "http:" || url.protocol === "https:") return url.href;
1339
+ return runtime.deeplinks && /^[a-z][a-z0-9+.-]*:$/i.test(url.protocol) && !BLOCKED_SCHEMES.test(url.protocol) ? url.href : null;
1340
+ } catch {
1341
+ return null;
1342
+ }
1343
+ }
1344
+ var CSS = `
1345
+ :host{all:initial}
1346
+ *{box-sizing:border-box;font-family:system-ui,-apple-system,Segoe UI,Roboto,sans-serif}
1347
+ .root{--bg:#fff;--fg:#1a1a1a;--ac:#0a6cff;color:var(--fg)}
1348
+ .overlay{position:fixed;inset:0;background:rgba(0,0,0,.5);display:flex;align-items:center;justify-content:center;z-index:2147483000;padding:16px}
1349
+ .card{background:var(--bg);color:var(--fg);border-radius:12px;box-shadow:0 10px 40px rgba(0,0,0,.3);max-width:440px;width:100%;max-height:90vh;overflow:auto;position:relative;padding:20px}
1350
+ .slide{position:fixed;right:16px;bottom:16px;z-index:2147483000;width:min(360px,calc(100vw - 32px))}
1351
+ .bar{position:fixed;left:0;right:0;z-index:2147483000;display:flex;align-items:center;gap:12px;justify-content:center;padding:10px 44px 10px 16px;flex-wrap:wrap;background:var(--bg);color:var(--fg);box-shadow:0 2px 12px rgba(0,0,0,.2)}
1352
+ .bar.top{top:0}.bar.bottom{bottom:0}
1353
+ .inline{display:block;width:100%;padding:16px;background:var(--bg);color:var(--fg);border-radius:8px;position:relative}
1354
+ .close{position:absolute;top:6px;right:8px;border:0;background:transparent;font-size:22px;line-height:1;cursor:pointer;color:inherit;padding:4px 8px}
1355
+ h2{margin:0 0 8px;font-size:18px}p{margin:0 0 12px;font-size:14px;line-height:1.5;white-space:pre-line}
1356
+ img{max-width:100%;border-radius:8px;margin-bottom:12px;display:block}
1357
+ .btns{display:flex;gap:8px;flex-wrap:wrap}
1358
+ button.b{border:1px solid var(--ac);background:var(--ac);color:#fff;border-radius:8px;padding:9px 14px;font-size:14px;cursor:pointer}
1359
+ button.b.secondary{background:transparent;color:var(--ac)}
1360
+ button.opt{display:block;width:100%;text-align:left;border:1px solid #c8c8c8;background:#fff;color:#1a1a1a;border-radius:8px;padding:9px 12px;margin:0 0 8px;font-size:14px;cursor:pointer}
1361
+ button.opt.sel{border-color:var(--ac);background:#eef4ff}
1362
+ .scale{display:flex;gap:6px;flex-wrap:wrap;margin-bottom:12px}.scale button{min-width:36px;padding:8px}
1363
+ label{display:block;font-size:13px;margin:0 0 10px}label span{display:block;margin-bottom:4px}
1364
+ input[type=text],input[type=email],input[type=tel],textarea{width:100%;border:1px solid #b8b8b8;border-radius:6px;padding:8px;font-size:14px;background:#fff;color:#1a1a1a}
1365
+ .err{color:#c62828;font-size:12px;margin:0 0 8px;min-height:1em}
1366
+ .prog{font-size:12px;opacity:.7;margin-bottom:8px}
1367
+ .game{text-align:center}.wheel{width:150px;height:150px;border-radius:50%;margin:8px auto 14px;border:6px solid var(--ac);display:flex;align-items:center;justify-content:center;font-size:42px;transition:transform 2s cubic-bezier(.2,.8,.2,1)}
1368
+ .result{font-size:16px;font-weight:600;margin:12px 0}
1369
+ .cp{display:block;width:100%;margin:0 0 12px;border:2px dashed var(--ac);border-radius:8px;padding:10px 12px;background:transparent;color:var(--ac);cursor:pointer;font:700 16px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:1px;text-align:center}
1370
+ .cp[aria-busy=true]{opacity:.6;cursor:progress}
1371
+ .cph{font-size:12px;opacity:.7;margin:-6px 0 12px;text-align:center}
1372
+ @media (prefers-reduced-motion:reduce){.wheel{transition:none}}
1373
+ `;
1374
+ function el(tag, props = {}, ...kids) {
1375
+ const e = document.createElement(tag);
1376
+ for (const [k, v] of Object.entries(props)) {
1377
+ if (k === "class") e.className = String(v);
1378
+ else if (k === "text") e.textContent = String(v);
1379
+ else if (k.startsWith("on") && typeof v === "function") e.addEventListener(k.slice(2), v);
1380
+ else if (v !== void 0 && v !== false) e.setAttribute(k, String(v));
1381
+ }
1382
+ kids.forEach((c) => e.append(c));
1383
+ return e;
1384
+ }
1385
+ function mountShadow(host, extraCss = "") {
1386
+ const root = host.attachShadow({ mode: "open" });
1387
+ try {
1388
+ const sheet = new CSSStyleSheet();
1389
+ sheet.replaceSync(CSS + extraCss);
1390
+ root.adoptedStyleSheets = [sheet];
1391
+ } catch {
1392
+ root.append(el("style", { text: CSS + extraCss }));
1393
+ }
1394
+ return root;
1395
+ }
1396
+ function render(c, h) {
1397
+ var _a, _b, _c;
1398
+ const t = c.template;
1399
+ let slotEl = null;
1400
+ if (t === "inline") {
1401
+ slotEl = c.slot_id ? document.querySelector(`[data-cdp-slot="${CSS_ESC(c.slot_id)}"]`) : null;
1402
+ if (!slotEl) return null;
1403
+ }
1404
+ const host = el("div", { "data-cdp-campaign": c.id });
1405
+ const root = mountShadow(host);
1406
+ const th = (_a = c.content) == null ? void 0 : _a.theme;
1407
+ const wrap = el("div", { class: "root" });
1408
+ wrap.style.setProperty("--bg", color(th == null ? void 0 : th.background, "#ffffff"));
1409
+ wrap.style.setProperty("--fg", color(th == null ? void 0 : th.text, "#1a1a1a"));
1410
+ wrap.style.setProperty("--ac", color(th == null ? void 0 : th.accent, "#0a6cff"));
1411
+ let closed = false;
1412
+ const prevFocus = document.activeElement;
1413
+ const close = (type = "close_button") => {
1414
+ var _a2;
1415
+ if (closed) return;
1416
+ closed = true;
1417
+ document.removeEventListener("keydown", onKey, true);
1418
+ host.remove();
1419
+ (_a2 = prevFocus == null ? void 0 : prevFocus.focus) == null ? void 0 : _a2.call(prevFocus);
1420
+ h.onDismiss(type);
1421
+ };
1422
+ const onKey = (e) => {
1423
+ if (e.key === "Escape") close("back");
1424
+ };
1425
+ const body = buildBody(c, h, close);
1426
+ const closeBtn = el("button", { class: "close", "aria-label": "\u0110\xF3ng", text: "\xD7", onclick: () => close("close_button") });
1427
+ if (t === "modal") {
1428
+ const card = el("div", { class: "card", role: "dialog", "aria-modal": "true", "aria-label": clip(((_b = c.content) == null ? void 0 : _b.title) || c.name, 100), tabindex: "-1" }, closeBtn, ...body);
1429
+ const overlay = el("div", { class: "overlay", onclick: (e) => {
1430
+ if (e.target === overlay) close("tap_outside");
1431
+ } }, card);
1432
+ wrap.append(overlay);
1433
+ document.addEventListener("keydown", onKey, true);
1434
+ queueMicrotask(() => card.focus());
1435
+ } else if (t === "slide_in") {
1436
+ wrap.append(el("div", { class: "slide" }, el("div", { class: "card", role: "dialog", "aria-label": clip(((_c = c.content) == null ? void 0 : _c.title) || c.name, 100) }, closeBtn, ...body)));
1437
+ } else if (t === "banner_top" || t === "banner_bottom") {
1438
+ wrap.append(el("div", { class: `bar ${t === "banner_top" ? "top" : "bottom"}`, role: "region", "aria-label": clip(c.name, 100) }, ...body, closeBtn));
1439
+ } else {
1440
+ wrap.append(el("div", { class: "inline", role: "region", "aria-label": clip(c.name, 100) }, closeBtn, ...body));
1441
+ }
1442
+ root.append(wrap);
1443
+ if (slotEl) slotEl.append(host);
1444
+ else document.body.append(host);
1445
+ h.onSeen();
1446
+ return { close, host };
1447
+ }
1448
+ var CSS_ESC = (s) => s.replace(/["\\]/g, "\\$&");
1449
+ function buildBody(c, h, close) {
1450
+ var _a, _b, _c, _d, _e, _f, _g, _h;
1451
+ const out = [];
1452
+ const kind = (_a = c.kind) != null ? _a : "message";
1453
+ const img = safeUrl((_b = c.content) == null ? void 0 : _b.image_url);
1454
+ if (img) out.push(el("img", { src: img, alt: "", referrerpolicy: "no-referrer" }));
1455
+ const textBox = el("div");
1456
+ if ((_c = c.content) == null ? void 0 : _c.title) textBox.append(el("h2", { text: clip((_d = c.content) == null ? void 0 : _d.title, 120) }));
1457
+ if ((_e = c.content) == null ? void 0 : _e.body) textBox.append(el("p", { text: clip((_f = c.content) == null ? void 0 : _f.body, 600) }));
1458
+ out.push(textBox);
1459
+ if (kind === "survey" && c.survey) out.push(surveyUi(c.survey.questions, h, close, c.survey.thanks));
1460
+ else if (kind === "lead_form" && c.lead_form) out.push(leadUi(c.lead_form.fields, c.lead_form.submit_text, h, close));
1461
+ else if (kind === "gamification" && c.game) out.push(gameUi(c.game.game_type, c.game.prizes, c.game.play_text, h, !!c.game.server));
1462
+ const btns = (_h = (_g = c.content) == null ? void 0 : _g.buttons) != null ? _h : [];
1463
+ if (btns.length) out.push(el("div", { class: "btns" }, ...btns.slice(0, 3).map((b) => el("button", { class: `b ${b.style === "secondary" ? "secondary" : ""}`, type: "button", text: clip(b.text, 40), onclick: () => h.onClick(b) }))));
1464
+ return out;
1465
+ }
1466
+ function couponBox(code, h) {
1467
+ const wrap = el("div");
1468
+ const b = el("button", { class: "cp", type: "button", text: typeof code === "string" ? clip(code, 200) : "\u2022\u2022\u2022\u2022\u2022\u2022", "aria-label": "Sao ch\xE9p m\xE3" });
1469
+ let value = typeof code === "string" ? clip(code, 200) : "";
1470
+ b.addEventListener("click", () => {
1471
+ if (value) h.onClick({ id: "coupon", text: "Sao ch\xE9p m\xE3", action: { type: "copy_code", code: value } });
1472
+ });
1473
+ wrap.append(b, el("div", { class: "cph", text: "Ch\u1EA1m \u0111\u1EC3 sao ch\xE9p m\xE3" }));
1474
+ if (typeof code !== "string") {
1475
+ b.setAttribute("aria-busy", "true");
1476
+ void code.then((v) => {
1477
+ if (v) {
1478
+ value = clip(v, 200);
1479
+ b.textContent = value;
1480
+ b.removeAttribute("aria-busy");
1481
+ } else wrap.remove();
1482
+ });
1483
+ }
1484
+ return wrap;
1485
+ }
1486
+ function surveyUi(qs, h, close, thanks) {
1487
+ const box = el("div");
1488
+ let i = 0;
1489
+ const answers = [];
1490
+ const answer = (q, a) => {
1491
+ h.onSurveyAnswer(q, a);
1492
+ answers.push({ question_id: q.id, answer_ids: a.ids, ...a.score !== void 0 ? { score: a.score } : {}, ...q.type === "text" && a.text ? { text: a.text } : {} });
1493
+ };
1494
+ const next = () => {
1495
+ i++;
1496
+ show();
1497
+ };
1498
+ const show = () => {
1499
+ var _a, _b;
1500
+ box.replaceChildren();
1501
+ if (i >= qs.length) {
1502
+ box.append(el("p", { text: clip((thanks == null ? void 0 : thanks.text) || "C\u1EA3m \u01A1n b\u1EA1n \u0111\xE3 ph\u1EA3n h\u1ED3i!", 300) }));
1503
+ if ((thanks == null ? void 0 : thanks.coupon_ref) && h.surveyCoupon) box.append(couponBox(h.surveyCoupon(answers).catch(() => null), h));
1504
+ else setTimeout(() => close("auto_close"), 1500);
1505
+ return;
1506
+ }
1507
+ const q = qs[i];
1508
+ box.append(el("div", { class: "prog", text: `C\xE2u ${i + 1}/${qs.length}` }), el("p", { text: clip(q.text, 300) }));
1509
+ if (q.type === "single_choice") {
1510
+ ((_a = q.options) != null ? _a : []).slice(0, 10).forEach((o) => box.append(el("button", {
1511
+ class: "opt",
1512
+ type: "button",
1513
+ text: clip(o.text, 120),
1514
+ onclick: () => {
1515
+ answer(q, { ids: [o.id], text: o.text });
1516
+ next();
1517
+ }
1518
+ })));
1519
+ } else if (q.type === "multi_choice") {
1520
+ const picked = /* @__PURE__ */ new Set();
1521
+ ((_b = q.options) != null ? _b : []).slice(0, 10).forEach((o) => {
1522
+ const b = el("button", {
1523
+ class: "opt",
1524
+ type: "button",
1525
+ "aria-pressed": "false",
1526
+ text: clip(o.text, 120),
1527
+ onclick: () => {
1528
+ picked.has(o.id) ? picked.delete(o.id) : picked.add(o.id);
1529
+ b.classList.toggle("sel");
1530
+ b.setAttribute("aria-pressed", String(picked.has(o.id)));
1531
+ }
1532
+ });
1533
+ box.append(b);
1534
+ });
1535
+ box.append(el("button", { class: "b", type: "button", text: "G\u1EEDi", onclick: () => {
1536
+ if (!picked.size) return;
1537
+ answer(q, { ids: [...picked] });
1538
+ next();
1539
+ } }));
1540
+ } else if (q.type === "rating" || q.type === "nps") {
1541
+ const [lo, hi] = q.type === "rating" ? [1, 5] : [0, 10];
1542
+ const row = el("div", { class: "scale" });
1543
+ for (let n = lo; n <= hi; n++) row.append(el("button", { class: "opt", type: "button", style: "width:auto", text: String(n), onclick: () => {
1544
+ answer(q, { ids: [], score: n });
1545
+ next();
1546
+ } }));
1547
+ box.append(row);
1548
+ } else {
1549
+ const ta = el("textarea", { rows: "3", maxlength: "512", "aria-label": "C\xE2u tr\u1EA3 l\u1EDDi" });
1550
+ box.append(ta, el("button", { class: "b", type: "button", text: "G\u1EEDi", onclick: () => {
1551
+ const v = ta.value.trim();
1552
+ if (!v) return;
1553
+ answer(q, { ids: [], text: v });
1554
+ next();
1555
+ } }));
1556
+ }
1557
+ };
1558
+ show();
1559
+ return box;
1560
+ }
1561
+ var EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
1562
+ var PHONE = /^(?:\+84|0)\d{9,10}$/;
1563
+ function leadUi(fields, submitText, h, close) {
1564
+ const form = el("form", { novalidate: "true" });
1565
+ const inputs = /* @__PURE__ */ new Map();
1566
+ const err2 = el("div", { class: "err", role: "alert" });
1567
+ for (const f of fields.slice(0, 8)) {
1568
+ const type = f.type === "checkbox" ? "checkbox" : f.type === "email" ? "email" : f.type === "phone" ? "tel" : "text";
1569
+ const input = el("input", { type, name: f.name, autocomplete: f.type === "email" ? "email" : f.type === "phone" ? "tel" : "off" });
1570
+ inputs.set(f.name, input);
1571
+ form.append(type === "checkbox" ? el("label", {}, input, ` ${clip(f.label, 120)}`) : el("label", {}, el("span", { text: clip(f.label, 80) + (f.required ? " *" : "") }), input));
1572
+ }
1573
+ form.append(err2, el("button", { class: "b", type: "submit", text: clip(submitText || "G\u1EEDi", 40) }));
1574
+ form.addEventListener("submit", async (e) => {
1575
+ e.preventDefault();
1576
+ const values = {};
1577
+ for (const f of fields) {
1578
+ const inp = inputs.get(f.name);
1579
+ if (!inp) continue;
1580
+ const v = f.type === "checkbox" ? inp.checked : inp.value.trim();
1581
+ if (f.required && (v === "" || v === false)) {
1582
+ err2.textContent = `Vui l\xF2ng nh\u1EADp: ${f.label}`;
1583
+ inp.focus();
1584
+ return;
1585
+ }
1586
+ if (v === "" || v === false) continue;
1587
+ if (f.type === "email" && !EMAIL.test(String(v))) {
1588
+ err2.textContent = "Email kh\xF4ng h\u1EE3p l\u1EC7";
1589
+ inp.focus();
1590
+ return;
1591
+ }
1592
+ if (f.type === "phone" && !PHONE.test(String(v).replace(/[\s.-]/g, ""))) {
1593
+ err2.textContent = "S\u1ED1 \u0111i\u1EC7n tho\u1EA1i kh\xF4ng h\u1EE3p l\u1EC7";
1594
+ inp.focus();
1595
+ return;
1596
+ }
1597
+ values[f.name] = v;
1598
+ }
1599
+ err2.textContent = "";
1600
+ await h.onLeadSubmit(values, fields);
1601
+ form.replaceChildren(el("p", { text: "C\u1EA3m \u01A1n b\u1EA1n! Ch\xFAng t\xF4i s\u1EBD li\xEAn h\u1EC7 s\u1EDBm." }));
1602
+ setTimeout(() => close("auto_close"), 1800);
1603
+ });
1604
+ return form;
1605
+ }
1606
+ function pick(prizes) {
1607
+ var _a;
1608
+ const total = prizes.reduce((s, p) => {
1609
+ var _a2;
1610
+ return s + Math.max((_a2 = p.weight) != null ? _a2 : 1, 0);
1611
+ }, 0) || 1;
1612
+ let r = Math.random() * total;
1613
+ for (const p of prizes) {
1614
+ r -= Math.max((_a = p.weight) != null ? _a : 1, 0);
1615
+ if (r <= 0) return p;
1616
+ }
1617
+ return prizes[prizes.length - 1];
1618
+ }
1619
+ function gameUi(type, prizes, playText, h, server = false) {
1620
+ const box = el("div", { class: "game" });
1621
+ const icon = type === "spin_wheel" ? "\u{1F3A1}" : type === "scratch_card" ? "\u{1F39F}\uFE0F" : "\u{1F381}";
1622
+ const wheel = el("div", { class: "wheel", "aria-hidden": "true", text: icon });
1623
+ const result = el("div", { class: "result", role: "status" });
1624
+ let played = false;
1625
+ const btn = el("button", {
1626
+ class: "b",
1627
+ type: "button",
1628
+ text: clip(playText || (type === "spin_wheel" ? "Quay ngay" : type === "scratch_card" ? "C\xE0o ngay" : "M\u1EDF qu\xE0"), 30),
1629
+ onclick: () => {
1630
+ if (played || !prizes.length) return;
1631
+ played = true;
1632
+ btn.setAttribute("disabled", "true");
1633
+ if (type === "spin_wheel") wheel.style.transform = `rotate(${720 + Math.floor(Math.random() * 360)}deg)`;
1634
+ if (server) {
1635
+ const started = Date.now();
1636
+ void (h.play ? h.play() : Promise.resolve(null)).then((r) => {
1637
+ setTimeout(() => {
1638
+ var _a, _b;
1639
+ if (!r) {
1640
+ result.textContent = "Ch\u01B0a th\u1EC3 tham gia l\xFAc n\xE0y. Vui l\xF2ng th\u1EED l\u1EA1i sau.";
1641
+ return;
1642
+ }
1643
+ const p3 = prizes.find((x) => x.id === r.prize_id);
1644
+ const label = clip((_a = p3 == null ? void 0 : p3.label) != null ? _a : "", 80);
1645
+ if (r.status === "limit") result.textContent = label ? `B\u1EA1n \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t ch\u01A1i. K\u1EBFt qu\u1EA3 c\u1EE7a b\u1EA1n: ${label}` : "B\u1EA1n \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t ch\u01A1i.";
1646
+ else result.textContent = r.is_win ? `\u{1F389} ${label}` : label;
1647
+ if (r.code) box.append(couponBox(r.code, h));
1648
+ if (r.status === "played") h.onGame({ is_win: r.is_win, prize_id: (_b = r.prize_id) != null ? _b : void 0 });
1649
+ }, Math.max(0, (type === "spin_wheel" ? 2e3 : 300) - (Date.now() - started)));
1650
+ });
1651
+ return;
1652
+ }
1653
+ const p = pick(prizes);
1654
+ setTimeout(() => {
1655
+ const win = p.is_win !== false;
1656
+ result.textContent = win ? `\u{1F389} ${clip(p.label, 80)}` : clip(p.label, 80);
1657
+ h.onGame({ is_win: win, prize_id: p.id });
1658
+ }, type === "spin_wheel" ? 2e3 : 300);
1659
+ }
1660
+ });
1661
+ box.append(wheel, result, btn);
1662
+ return box;
1663
+ }
1664
+
1665
+ // src/modules/design-renderer.ts
1666
+ var num2 = (v, d, lo = 0, hi = 4e3) => typeof v === "number" && isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d;
1667
+ var COLOR = /^(?:#[0-9a-f]{3,8}|rgba?\([\d\s.,%]+\)|transparent|[a-z]{3,20})$/i;
1668
+ var col = (v, d = "") => typeof v === "string" && COLOR.test(v.trim()) ? v.trim() : d;
1669
+ var pad4 = (v, d) => {
1670
+ const a = Array.isArray(v) && v.length === 4 ? v : d;
1671
+ return a.map((x) => `${num2(x, 0, 0, 200)}px`).join(" ");
1672
+ };
1673
+ var ALIGN = /* @__PURE__ */ new Set(["left", "center", "right", "justify"]);
1674
+ var FONT_OK = /^[\w\s,'"-]{1,80}$/;
1675
+ var CSS2 = `
1676
+ .dz-overlay{position:fixed;inset:0;z-index:2147483000;display:flex}
1677
+ .dz-card{background:var(--bg,#fff);color:#1a1a1a;position:relative;overflow:auto;max-height:100vh;box-shadow:0 10px 40px rgba(0,0,0,.3)}
1678
+ .dz-block{display:grid;gap:8px;width:100%}
1679
+ .dz-cell{display:flex;flex-direction:column;gap:8px;min-width:0}
1680
+ .dz-t{margin:0;white-space:pre-line;word-break:break-word}
1681
+ .dz-img{display:block;max-width:100%;border-radius:0;margin:0}
1682
+ .dz-btn{border:0;cursor:pointer;font:inherit;display:inline-block;text-align:center}
1683
+ .dz-line{border:0;border-top:1px solid #ddd;margin:4px 0;width:100%}
1684
+ .dz-in{width:100%;border:1px solid #b8b8b8;border-radius:6px;padding:8px;font-size:14px;background:#fff;color:#1a1a1a}
1685
+ .dz-fl{font-size:13px;display:block;margin:0 0 4px}
1686
+ .dz-rate{display:flex;gap:6px;flex-wrap:wrap}.dz-rate button{min-width:34px;padding:6px;border:1px solid #c8c8c8;background:#fff;border-radius:6px;cursor:pointer;font-size:15px}
1687
+ .dz-rate button.sel{border-color:#0a6cff;background:#eef4ff}
1688
+ .dz-x{position:absolute;border:0;background:rgba(0,0,0,.35);color:#fff;border-radius:50%;cursor:pointer;line-height:1;width:28px;height:28px;font-size:18px;z-index:2}
1689
+ .dz-err{color:#c62828;font-size:12px;min-height:1em}
1690
+ .dz-cp{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;border:2px dashed currentColor;border-radius:8px;padding:8px 12px;background:transparent;cursor:pointer;font:700 15px/1.3 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:1px;color:#c4541b}
1691
+ .dz-cp[aria-busy=true]{opacity:.6;cursor:progress}
1692
+ .dz-game{display:flex;flex-direction:column;align-items:center;gap:10px;margin:8px 0}
1693
+ .dz-wheelbox{position:relative;width:180px;height:180px}
1694
+ .dz-wheel{width:100%;height:100%;border-radius:50%;border:4px solid #fff;box-shadow:0 2px 10px rgba(0,0,0,.2);transition:transform 2.4s cubic-bezier(.17,.67,.12,.99)}
1695
+ .dz-ptr{position:absolute;top:-6px;left:50%;transform:translateX(-50%);width:0;height:0;border-left:9px solid transparent;border-right:9px solid transparent;border-top:16px solid #1d2433}
1696
+ .dz-scratch{width:200px;height:110px;border-radius:12px;background:repeating-linear-gradient(45deg,#9aa3b2,#9aa3b2 8px,#b5bcc8 8px,#b5bcc8 16px);display:flex;align-items:center;justify-content:center;color:#fff;font-weight:700;transition:opacity .4s}
1697
+ .dz-gifts{display:grid;grid-template-columns:repeat(3,52px);gap:8px}.dz-gifts i{display:block;width:52px;height:52px;border-radius:10px;box-shadow:0 1px 4px rgba(0,0,0,.2)}
1698
+ .dz-res{font-size:16px;font-weight:600;text-align:center;min-height:1.2em}
1699
+ @media (prefers-reduced-motion:reduce){.dz-wheel{transition:none}}
1700
+ .dz-fade{animation:dzf .25s ease}.dz-zoom{animation:dzz .25s ease}.dz-slide{animation:dzs .25s ease}
1701
+ @keyframes dzf{from{opacity:0}to{opacity:1}}@keyframes dzz{from{transform:scale(.9);opacity:0}to{transform:none;opacity:1}}@keyframes dzs{from{transform:translateY(24px);opacity:0}to{transform:none;opacity:1}}
1702
+ @media (prefers-reduced-motion:reduce){.dz-fade,.dz-zoom,.dz-slide{animation:none}}
1703
+ .bn{display:block;width:100%;position:relative;overflow:hidden}.bn img{display:block;width:100%;height:auto;border:0}
1704
+ .bn a{display:block}.bn .tr{display:flex;transition:transform .4s}.bn .tr>div{min-width:100%}
1705
+ .bn .dots{position:absolute;bottom:6px;left:0;right:0;display:flex;gap:6px;justify-content:center}
1706
+ .bn .dots i{width:8px;height:8px;border-radius:50%;background:rgba(255,255,255,.6);display:block}.bn .dots i.on{background:#fff;box-shadow:0 0 2px #000}
1707
+ `;
1708
+ var ANCHOR = {
1709
+ top_left: ["flex-start", "flex-start"],
1710
+ top_center: ["flex-start", "center"],
1711
+ top_right: ["flex-start", "flex-end"],
1712
+ middle_left: ["center", "flex-start"],
1713
+ middle_center: ["center", "center"],
1714
+ middle_right: ["center", "flex-end"],
1715
+ bottom_left: ["flex-end", "flex-start"],
1716
+ bottom_center: ["flex-end", "center"],
1717
+ bottom_right: ["flex-end", "flex-end"]
1718
+ };
1719
+ function remaining(e, startedAt) {
1720
+ var _a;
1721
+ const left = e.countdownMode === "duration" ? num2(e.countdownSec, 0, 0, 31536e3) * 1e3 - (Date.now() - startedAt) : Date.parse(String((_a = e.countdownEndAt) != null ? _a : "")) - Date.now();
1722
+ return isFinite(left) && left > 0 ? left : null;
1723
+ }
1724
+ var fmtLeft = (ms) => {
1725
+ const s = Math.floor(ms / 1e3), d = Math.floor(s / 86400);
1726
+ const p = (n) => String(n).padStart(2, "0");
1727
+ return `${d ? `${d}d ` : ""}${p(Math.floor(s % 86400 / 3600))}:${p(Math.floor(s % 3600 / 60))}:${p(s % 60)}`;
1728
+ };
1729
+ function renderPopupDesign(c, h) {
1730
+ var _a, _b, _c, _d, _e;
1731
+ const d = c.design;
1732
+ const pages = Array.isArray(d == null ? void 0 : d.pages) ? d.pages : [];
1733
+ if (!d || !pages.length) return null;
1734
+ const pos = (_a = d.position) != null ? _a : {};
1735
+ const lay = (_b = d.layout) != null ? _b : {};
1736
+ const host = el("div", { "data-cdp-campaign": c.id });
1737
+ const root = mountShadow(host, CSS2);
1738
+ const startedAt = Date.now();
1739
+ const timers = [];
1740
+ let closed = false, pageIdx = 0;
1741
+ const prevFocus = document.activeElement;
1742
+ const close = (type = "close_button") => {
1743
+ var _a2;
1744
+ if (closed) return;
1745
+ closed = true;
1746
+ timers.forEach((t) => {
1747
+ clearInterval(t);
1748
+ clearTimeout(t);
1749
+ });
1750
+ document.removeEventListener("keydown", onKey, true);
1751
+ host.remove();
1752
+ (_a2 = prevFocus == null ? void 0 : prevFocus.focus) == null ? void 0 : _a2.call(prevFocus);
1753
+ h.onDismiss(type);
1754
+ };
1755
+ const onKey = (e) => {
1756
+ if (e.key === "Escape") close("back");
1757
+ };
1758
+ const fullscreen = pos.anchor === "fullscreen";
1759
+ const [ay, ax] = (_c = ANCHOR[String(pos.anchor)]) != null ? _c : ANCHOR.middle_center;
1760
+ const m = (_d = pos.margin) != null ? _d : {};
1761
+ const overlay = el("div", { class: "dz-overlay" });
1762
+ overlay.style.alignItems = fullscreen ? "stretch" : ay;
1763
+ overlay.style.justifyContent = fullscreen ? "stretch" : ax;
1764
+ overlay.style.padding = fullscreen ? "0" : `${num2(m.top, 16, 0, 400)}px ${num2(m.right, 16, 0, 400)}px ${num2(m.bottom, 16, 0, 400)}px ${num2(m.left, 16, 0, 400)}px`;
1765
+ const dim = el("div");
1766
+ if (pos.overlayOpacity) {
1767
+ dim.style.position = "absolute";
1768
+ dim.style.inset = "0";
1769
+ dim.style.background = col(pos.overlayColor, "#000");
1770
+ dim.style.opacity = String(num2(pos.overlayOpacity, 0.5, 0, 1));
1771
+ }
1772
+ if (!pos.overlayOpacity) overlay.style.pointerEvents = "none";
1773
+ const card = el("div", { class: `dz-card ${["fade", "zoom", "slide"].includes(pos.effect) ? `dz-${pos.effect}` : ""}`, role: "dialog", "aria-modal": "true", "aria-label": clip(c.name, 100), tabindex: "-1" });
1774
+ card.style.pointerEvents = "auto";
1775
+ card.style.setProperty("--bg", col(lay.bgColor, "#ffffff"));
1776
+ card.style.width = fullscreen ? "100%" : `${num2(lay.widthPct, 90, 10, 100)}%`;
1777
+ if (!fullscreen && lay.maxWidthPx) card.style.maxWidth = `${num2(lay.maxWidthPx, 480, 120, 1600)}px`;
1778
+ card.style.borderRadius = fullscreen ? "0" : `${num2(lay.radius, 12, 0, 48)}px`;
1779
+ card.style.padding = pad4(lay.padding, [16, 16, 16, 16]);
1780
+ if (fullscreen) card.style.maxHeight = "100%";
1781
+ const body = el("div");
1782
+ card.append(body);
1783
+ const pageIndexById = (id) => pages.findIndex((p) => p.id === id);
1784
+ const go = (i, tr) => {
1785
+ pageIdx = i;
1786
+ draw(tr);
1787
+ };
1788
+ const coupons = /* @__PURE__ */ new Map();
1789
+ const couponOf = (ref) => {
1790
+ let p = coupons.get(ref);
1791
+ if (!p) {
1792
+ p = h.coupon ? h.coupon(ref).catch(() => null) : Promise.resolve(null);
1793
+ coupons.set(ref, p);
1794
+ }
1795
+ return p;
1796
+ };
1797
+ let prizeCode = null;
1798
+ const codeOf = (e) => e.prizeCoupon ? Promise.resolve(prizeCode) : typeof e.couponCode === "string" && e.couponCode ? Promise.resolve(clip(e.couponCode, 200)) : typeof e.couponRef === "string" && e.couponRef ? couponOf(e.couponRef) : Promise.resolve(null);
1799
+ const inputs = [];
1800
+ function drawElement(e, into) {
1801
+ var _a2;
1802
+ switch (e.kind) {
1803
+ case "text": {
1804
+ const t = el("p", { class: "dz-t", text: clip(e.text, 2e3) });
1805
+ t.style.fontSize = `${num2(e.fontSize, 14, 8, 72)}px`;
1806
+ t.style.fontWeight = String(num2(e.fontWeight, 400, 100, 900));
1807
+ t.style.color = col(e.color, "inherit");
1808
+ if (ALIGN.has(e.textAlign)) t.style.textAlign = e.textAlign;
1809
+ if (e.lineHeight) t.style.lineHeight = `${num2(e.lineHeight, 130, 80, 300)}%`;
1810
+ if (e.letterSpacing) t.style.letterSpacing = `${num2(e.letterSpacing, 0, -5, 20)}px`;
1811
+ if (typeof e.fontFamily === "string" && FONT_OK.test(e.fontFamily)) t.style.fontFamily = e.fontFamily;
1812
+ if (e.bgColor) t.style.background = col(e.bgColor);
1813
+ into.append(t);
1814
+ return;
1815
+ }
1816
+ case "image": {
1817
+ const url = safeUrl((_a2 = e.media) == null ? void 0 : _a2.url);
1818
+ if (!url) return;
1819
+ const img = el("img", { class: "dz-img", src: url, alt: clip(e.altText, 200), referrerpolicy: "no-referrer" });
1820
+ if (e.imageFit === "cover") {
1821
+ img.style.objectFit = "cover";
1822
+ img.style.width = "100%";
1823
+ }
1824
+ if (e.imageFit === "stretch") img.style.width = "100%";
1825
+ if (e.radius) img.style.borderRadius = `${num2(e.radius, 0, 0, 100)}px`;
1826
+ into.append(wrapLink(e, img));
1827
+ return;
1828
+ }
1829
+ case "button": {
1830
+ const b = el("button", { class: "dz-btn", type: "button", text: clip(e.text, 80) });
1831
+ b.style.background = col(e.bgColor, "#0a6cff");
1832
+ b.style.color = col(e.color, "#fff");
1833
+ b.style.fontSize = `${num2(e.fontSize, 14, 8, 48)}px`;
1834
+ b.style.fontWeight = String(num2(e.fontWeight, 600, 100, 900));
1835
+ b.style.borderRadius = `${num2(e.radius, 8, 0, 60)}px`;
1836
+ b.style.padding = pad4(e.padding, [10, 16, 10, 16]);
1837
+ if (e.borderWidth) b.style.border = `${num2(e.borderWidth, 0, 0, 10)}px ${["dashed", "dotted"].includes(e.borderStyle) ? e.borderStyle : "solid"} ${col(e.borderColor, "currentColor")}`;
1838
+ if (e.buttonWidth === "full") b.style.width = "100%";
1839
+ else if (e.buttonWidth === "manual") b.style.width = `${num2(e.buttonWidthPct, 100, 10, 100)}%`;
1840
+ b.addEventListener("click", () => act(e));
1841
+ const row = el("div");
1842
+ row.style.textAlign = ALIGN.has(e.textAlign) ? e.textAlign : "center";
1843
+ row.append(b);
1844
+ into.append(row);
1845
+ return;
1846
+ }
1847
+ case "line":
1848
+ into.append(el("hr", { class: "dz-line" }));
1849
+ return;
1850
+ case "coupon": {
1851
+ const fixed = e.prizeCoupon ? prizeCode != null ? prizeCode : "" : typeof e.couponCode === "string" && e.couponCode ? clip(e.couponCode, 200) : "";
1852
+ if (!fixed && (e.prizeCoupon || !(typeof e.couponRef === "string" && e.couponRef))) return;
1853
+ const b = el("button", { class: "dz-cp", type: "button", text: fixed || "\u2022\u2022\u2022\u2022\u2022\u2022", "aria-label": "Sao ch\xE9p m\xE3" });
1854
+ if (e.color) b.style.color = col(e.color, "#c4541b");
1855
+ if (e.bgColor) b.style.background = col(e.bgColor);
1856
+ if (!fixed) {
1857
+ b.setAttribute("aria-busy", "true");
1858
+ void codeOf(e).then((code) => {
1859
+ if (code) {
1860
+ b.textContent = code;
1861
+ b.removeAttribute("aria-busy");
1862
+ } else b.remove();
1863
+ });
1864
+ }
1865
+ b.addEventListener("click", () => act({ ...e, action: "copy_coupon" }));
1866
+ into.append(b);
1867
+ return;
1868
+ }
1869
+ case "countdown": {
1870
+ const t = el("p", { class: "dz-t" });
1871
+ t.style.textAlign = "center";
1872
+ t.style.fontSize = `${num2(e.fontSize, 22, 10, 72)}px`;
1873
+ t.style.fontWeight = "700";
1874
+ t.style.color = col(e.color, "inherit");
1875
+ const tick = () => {
1876
+ const left = remaining(e, startedAt);
1877
+ if (left === null) {
1878
+ clearInterval(iv);
1879
+ if (e.countdownOnEnd === "close_popup") close("auto_close");
1880
+ else if (e.countdownOnEnd === "go_to_page") {
1881
+ const i = pageIndexById(e.countdownPageId);
1882
+ if (i >= 0) go(i);
1883
+ else t.remove();
1884
+ } else t.remove();
1885
+ return;
1886
+ }
1887
+ t.textContent = fmtLeft(left);
1888
+ };
1889
+ const iv = setInterval(tick, 1e3);
1890
+ timers.push(iv);
1891
+ tick();
1892
+ into.append(t);
1893
+ return;
1894
+ }
1895
+ case "input_text":
1896
+ case "select":
1897
+ case "radio":
1898
+ case "checkbox":
1899
+ case "rating": {
1900
+ drawField(e, into);
1901
+ return;
1902
+ }
1903
+ default:
1904
+ return;
1905
+ }
1906
+ }
1907
+ function wrapLink(e, node) {
1908
+ if (e.action === "open_link" || e.action === "go_to_page") {
1909
+ node.style.cursor = "pointer";
1910
+ node.addEventListener("click", () => act(e));
1911
+ }
1912
+ return node;
1913
+ }
1914
+ function drawField(e, into) {
1915
+ const wrap = el("div");
1916
+ if (e.fieldLabel) wrap.append(el("span", { class: "dz-fl", text: clip(e.fieldLabel, 120) + (e.required ? " *" : "") }));
1917
+ let get = () => null;
1918
+ if (e.kind === "input_text") {
1919
+ const type = e.inputType === "email" ? "email" : e.inputType === "phone" ? "tel" : e.inputType === "number" ? "number" : "text";
1920
+ const i = el("input", { class: "dz-in", type, placeholder: clip(e.placeholder, 80), maxlength: "255" });
1921
+ wrap.append(i);
1922
+ get = () => i.value.trim() || null;
1923
+ } else if (e.kind === "select") {
1924
+ const s = el("select", { class: "dz-in" }, el("option", { value: "", text: clip(e.placeholder || "\u2014", 60) }));
1925
+ for (const o of (Array.isArray(e.options) ? e.options : []).slice(0, 50)) s.append(el("option", { value: clip(o.value, 100), text: clip(o.label, 100) }));
1926
+ wrap.append(s);
1927
+ get = () => s.value || null;
1928
+ } else if (e.kind === "radio") {
1929
+ const name = `r-${e.id}`;
1930
+ let v = null;
1931
+ for (const o of (Array.isArray(e.options) ? e.options : []).slice(0, 20)) {
1932
+ const r = el("input", { type: "radio", name, value: clip(o.value, 100) });
1933
+ r.addEventListener("change", () => {
1934
+ v = o.value;
1935
+ });
1936
+ wrap.append(el("label", { class: "dz-fl" }, r, ` ${clip(o.label, 100)}`));
1937
+ }
1938
+ get = () => v;
1939
+ } else if (e.kind === "checkbox") {
1940
+ const picks = /* @__PURE__ */ new Set();
1941
+ for (const o of (Array.isArray(e.options) ? e.options : []).slice(0, 20)) {
1942
+ const k = el("input", { type: "checkbox", value: clip(o.value, 100) });
1943
+ k.addEventListener("change", () => {
1944
+ k.checked ? picks.add(o.value) : picks.delete(o.value);
1945
+ });
1946
+ wrap.append(el("label", { class: "dz-fl" }, k, ` ${clip(o.label, 100)}`));
1947
+ }
1948
+ get = () => picks.size ? [...picks].join(",") : null;
1949
+ } else {
1950
+ const from = e.ratingFrom === 0 ? 0 : 1, levels = Math.min(Math.max(Math.round(num2(e.ratingLevels, 5, 2, 11)), 2), 11);
1951
+ const row = el("div", { class: "dz-rate" });
1952
+ let v = null;
1953
+ for (let n = from; n < from + levels; n++) {
1954
+ const label = e.ratingStyle === "star" ? "\u2605" : e.ratingStyle === "emoji" ? ["\u{1F621}", "\u{1F641}", "\u{1F610}", "\u{1F642}", "\u{1F60D}"][Math.min(4, Math.round((n - from) / Math.max(levels - 1, 1) * 4))] : String(n);
1955
+ const b = el("button", { type: "button", text: label, "aria-label": String(n) });
1956
+ b.addEventListener("click", () => {
1957
+ v = String(n);
1958
+ row.querySelectorAll("button").forEach((x2) => x2.classList.remove("sel"));
1959
+ b.classList.add("sel");
1960
+ });
1961
+ row.append(b);
1962
+ }
1963
+ wrap.append(row);
1964
+ get = () => v;
1965
+ }
1966
+ inputs.push({ e, get, node: wrap });
1967
+ into.append(wrap);
1968
+ }
1969
+ function collect(err2) {
1970
+ const values = {};
1971
+ for (const f of inputs) {
1972
+ const v = f.get();
1973
+ if (f.e.required && (v === null || v === "")) {
1974
+ err2.textContent = `Vui l\xF2ng nh\u1EADp: ${clip(f.e.fieldLabel || f.e.placeholder || "", 60)}`;
1975
+ return null;
1976
+ }
1977
+ if (v === null || v === "") continue;
1978
+ if (f.e.inputType === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(v))) {
1979
+ err2.textContent = "Email kh\xF4ng h\u1EE3p l\u1EC7";
1980
+ return null;
1981
+ }
1982
+ if (f.e.inputType === "phone" && !/^(?:\+84|0)\d{9,10}$/.test(String(v).replace(/[\s.-]/g, ""))) {
1983
+ err2.textContent = "S\u1ED1 \u0111i\u1EC7n tho\u1EA1i kh\xF4ng h\u1EE3p l\u1EC7";
1984
+ return null;
1985
+ }
1986
+ values[typeof f.e.attr === "string" && f.e.attr ? f.e.attr : `field_${f.e.id}`] = String(v);
1987
+ }
1988
+ err2.textContent = "";
1989
+ return values;
1990
+ }
1991
+ let curErr = el("div");
1992
+ function act(e) {
1993
+ var _a2, _b2, _c2;
1994
+ const text = clip(e.text, 80);
1995
+ if (((_a2 = e.logEvent) == null ? void 0 : _a2.event) === "__form_submit") {
1996
+ const values = collect(curErr);
1997
+ if (!values) return;
1998
+ h.onSideEffect({ kind: "form", values });
1999
+ } else if ((_b2 = e.logEvent) == null ? void 0 : _b2.event) {
2000
+ let params = {};
2001
+ try {
2002
+ const p = JSON.parse(String(e.logEvent.params || "{}"));
2003
+ if (p && typeof p === "object") params = p;
2004
+ } catch {
2005
+ }
2006
+ h.onSideEffect({ kind: "event", name: String(e.logEvent.event), params });
2007
+ }
2008
+ if (Array.isArray(e.updateAttrs) && e.updateAttrs.length) {
2009
+ const attrs = {};
2010
+ for (const a of e.updateAttrs.slice(0, 20)) if (a == null ? void 0 : a.attr) attrs[String(a.attr)] = clip(a.value, 200);
2011
+ h.onSideEffect({ kind: "attrs", attrs });
2012
+ }
2013
+ switch (e.action) {
2014
+ case "close":
2015
+ h.onClick({ action: "dismiss", text });
2016
+ close("close_button");
2017
+ return;
2018
+ case "open_link": {
2019
+ const url = safeUrl(e.url);
2020
+ if (!url) return;
2021
+ h.onClick({ action: "url", text, url });
2022
+ runtime.open(url, e.openMode === "new_tab");
2023
+ return;
2024
+ }
2025
+ case "go_to_page": {
2026
+ h.onClick({ action: "go_to_page", text });
2027
+ const n = pages.length;
2028
+ let i = e.goMode === "next" ? pageIdx + 1 : e.goMode === "prev" ? pageIdx - 1 : pageIndexById(e.targetPageId);
2029
+ if (i < 0 || i >= n) i = e.noTargetFallback === "specific" ? pageIndexById(e.fallbackPageId) : -1;
2030
+ if (i < 0) close("auto_close");
2031
+ else go(i, e.transition);
2032
+ return;
2033
+ }
2034
+ case "request_push":
2035
+ h.onClick({ action: "request_push_permission", text });
2036
+ h.onSideEffect({ kind: "push" });
2037
+ return;
2038
+ case "copy_coupon":
2039
+ void codeOf(e).then((code) => {
2040
+ if (code) {
2041
+ h.onClick({ action: "copy_code", text });
2042
+ h.onSideEffect({ kind: "copy", code });
2043
+ }
2044
+ });
2045
+ return;
2046
+ default:
2047
+ h.onClick({ action: ((_c2 = e.logEvent) == null ? void 0 : _c2.event) ? "trigger_event" : "none", text });
2048
+ }
2049
+ }
2050
+ const game = d.game && Array.isArray(d.game.prizes) && d.game.prizes.length ? d.game : null;
2051
+ const prizes = game ? game.prizes.slice(0, 12) : [];
2052
+ let played = false;
2053
+ let resultText = "";
2054
+ const localPick = () => {
2055
+ var _a2;
2056
+ const total = prizes.reduce((t, p3) => t + Math.max(num2(p3.pct, 0, 0, 100), 0), 0) || 1;
2057
+ let r = Math.random() * total;
2058
+ const p = (_a2 = prizes.find((x2) => (r -= Math.max(num2(x2.pct, 0, 0, 100), 0)) < 0)) != null ? _a2 : prizes[prizes.length - 1];
2059
+ return { status: "played", prize_id: String(p.id), is_win: !p.noWin, code: null };
2060
+ };
2061
+ function gameWidget() {
2062
+ var _a2;
2063
+ const box = el("div", { class: "dz-game" });
2064
+ const kind = String((_a2 = game.kind) != null ? _a2 : "wheel");
2065
+ const seg = 360 / Math.max(prizes.length, 1);
2066
+ let wheel = null;
2067
+ let scratch = null;
2068
+ if (kind === "scratch") {
2069
+ scratch = el("div", { class: "dz-scratch", text: "?" });
2070
+ box.append(scratch);
2071
+ } else if (kind === "giftbox") {
2072
+ const g = el("div", { class: "dz-gifts" });
2073
+ prizes.slice(0, 9).forEach((p) => {
2074
+ const i = el("i");
2075
+ i.style.background = col(p.color, "#c4541b");
2076
+ g.append(i);
2077
+ });
2078
+ box.append(g);
2079
+ } else {
2080
+ const wb = el("div", { class: "dz-wheelbox" });
2081
+ wheel = el("div", { class: "dz-wheel" });
2082
+ wheel.style.background = `conic-gradient(${prizes.map((p, i) => `${col(p.color, i % 2 ? "#f2b705" : "#c4541b")} ${i * seg}deg ${(i + 1) * seg}deg`).join(",")})`;
2083
+ wb.append(wheel, el("div", { class: "dz-ptr" }));
2084
+ box.append(wb);
2085
+ }
2086
+ const res = el("div", { class: "dz-res", role: "status", text: resultText });
2087
+ const label = typeof game.playText === "string" && game.playText ? clip(game.playText, 30) : kind === "scratch" ? "C\xE0o ngay" : kind === "giftbox" ? "M\u1EDF qu\xE0" : "Quay ngay";
2088
+ const btn = el("button", { class: "dz-btn", type: "button", text: label });
2089
+ btn.style.background = "#c4541b";
2090
+ btn.style.color = "#fff";
2091
+ btn.style.borderRadius = "8px";
2092
+ btn.style.padding = "10px 20px";
2093
+ if (played) btn.setAttribute("disabled", "true");
2094
+ btn.addEventListener("click", () => {
2095
+ if (played) return;
2096
+ played = true;
2097
+ btn.setAttribute("disabled", "true");
2098
+ const server = prizes.some((p) => p.hasCoupon);
2099
+ const started = Date.now();
2100
+ void (server ? h.play ? h.play().catch(() => null) : Promise.resolve(null) : Promise.resolve(localPick())).then((r) => {
2101
+ const idx = r ? prizes.findIndex((p) => String(p.id) === r.prize_id) : -1;
2102
+ if (wheel && idx >= 0) wheel.style.transform = `rotate(${360 * 5 + 360 - (idx + 0.5) * seg}deg)`;
2103
+ if (scratch) scratch.style.opacity = "0.15";
2104
+ const wait = Math.max(0, (wheel ? 2500 : 500) - (wheel ? 0 : Date.now() - started));
2105
+ timers.push(setTimeout(() => finish(r, res), wait));
2106
+ });
2107
+ });
2108
+ box.append(res, btn);
2109
+ return box;
2110
+ }
2111
+ function finish(r, res) {
2112
+ var _a2, _b2, _c2;
2113
+ if (closed) return;
2114
+ if (!r) {
2115
+ resultText = "Ch\u01B0a th\u1EC3 tham gia l\xFAc n\xE0y. Vui l\xF2ng th\u1EED l\u1EA1i sau.";
2116
+ res.textContent = resultText;
2117
+ return;
2118
+ }
2119
+ prizeCode = r.code;
2120
+ const p = prizes.find((x2) => String(x2.id) === r.prize_id);
2121
+ if (r.status === "played") (_b2 = h.onGame) == null ? void 0 : _b2.call(h, { is_win: r.is_win, prize_id: (_a2 = r.prize_id) != null ? _a2 : void 0 });
2122
+ const target = (p == null ? void 0 : p.resultPageId) ? pageIndexById(p.resultPageId) : -1;
2123
+ const name = clip((_c2 = p == null ? void 0 : p.name) != null ? _c2 : "", 80);
2124
+ resultText = r.status === "limit" ? name ? `B\u1EA1n \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t ch\u01A1i. K\u1EBFt qu\u1EA3 c\u1EE7a b\u1EA1n: ${name}` : "B\u1EA1n \u0111\xE3 h\u1EBFt l\u01B0\u1EE3t ch\u01A1i." : r.is_win ? `\u{1F389} ${name}` : name;
2125
+ if (target > 0) {
2126
+ go(target, "fade");
2127
+ return;
2128
+ }
2129
+ res.textContent = resultText;
2130
+ if (prizeCode) drawElement({ kind: "coupon", prizeCoupon: true, action: "copy_coupon" }, res.parentElement);
2131
+ }
2132
+ function draw(transition) {
2133
+ var _a2, _b2, _c2;
2134
+ inputs.length = 0;
2135
+ body.replaceChildren();
2136
+ const page = (_a2 = pages[pageIdx]) != null ? _a2 : pages[0];
2137
+ const err2 = el("div", { class: "dz-err", role: "alert" });
2138
+ curErr = err2;
2139
+ for (const b of Array.isArray(page.blocks) ? page.blocks : []) {
2140
+ const blk = el("div", { class: "dz-block" });
2141
+ const layout = String((_b2 = b.layout) != null ? _b2 : "vertical");
2142
+ const cols = layout === "cols_2" ? 2 : layout === "cols_3" ? 3 : layout === "horizontal" ? 99 : 1;
2143
+ const cells = Array.isArray(b.cells) && b.cells.length === cols ? b.cells : [];
2144
+ blk.style.gridTemplateColumns = cols === 99 ? "repeat(auto-fit,minmax(0,1fr))" : cells.length ? cells.map((x2) => `${num2(x2, 1, 1, 12)}fr`).join(" ") : `repeat(${cols},minmax(0,1fr))`;
2145
+ if (layout === "rows_2" || layout === "rows_3") blk.style.gridTemplateColumns = "1fr";
2146
+ blk.style.background = col(b.bgColor);
2147
+ blk.style.borderRadius = `${num2(b.radius, 0, 0, 60)}px`;
2148
+ if (b.borderColor) blk.style.border = `${num2(b.borderWidth, 1, 0, 10)}px ${["dashed", "dotted"].includes(b.borderStyle) ? b.borderStyle : "solid"} ${col(b.borderColor)}`;
2149
+ if (b.padding) blk.style.padding = pad4(b.padding, [0, 0, 0, 0]);
2150
+ if (b.height) blk.style.minHeight = `${num2(b.height, 0, 0, 2e3)}px`;
2151
+ const n = cols === 99 ? Math.max(1, ((_c2 = b.elements) != null ? _c2 : []).length) : cols;
2152
+ const cellEls = Array.from({ length: n }, () => el("div", { class: "dz-cell" }));
2153
+ cellEls.forEach((x2) => blk.append(x2));
2154
+ for (const e of Array.isArray(b.elements) ? b.elements : []) {
2155
+ if (e.kind === "close_button") continue;
2156
+ drawElement(e, cellEls[Math.min(num2(e.col, 0, 0, 20), cellEls.length - 1)]);
2157
+ }
2158
+ body.append(blk);
2159
+ }
2160
+ if (game && pageIdx === 0) body.append(gameWidget());
2161
+ body.append(err2);
2162
+ if (transition === "fade") body.className = "dz-fade";
2163
+ else if (transition === "slide") body.className = "dz-slide";
2164
+ else body.className = "";
2165
+ }
2166
+ draw();
2167
+ const closeEl = pages.flatMap((p) => {
2168
+ var _a2;
2169
+ return ((_a2 = p.blocks) != null ? _a2 : []).flatMap((b) => {
2170
+ var _a3;
2171
+ return (_a3 = b.elements) != null ? _a3 : [];
2172
+ });
2173
+ }).find((e) => e.kind === "close_button");
2174
+ const cornerOf = String((_e = closeEl == null ? void 0 : closeEl.closeCorner) != null ? _e : "top_right");
2175
+ const x = el("button", { class: "dz-x", type: "button", "aria-label": "\u0110\xF3ng", text: "\xD7", onclick: () => close("close_button") });
2176
+ x.style[cornerOf.startsWith("bottom") ? "bottom" : "top"] = "6px";
2177
+ x.style[cornerOf.endsWith("left") ? "left" : "right"] = "6px";
2178
+ if ((closeEl == null ? void 0 : closeEl.closeSize) === "lg") {
2179
+ x.style.width = "36px";
2180
+ x.style.height = "36px";
2181
+ } else if ((closeEl == null ? void 0 : closeEl.closeSize) === "sm") {
2182
+ x.style.width = "22px";
2183
+ x.style.height = "22px";
2184
+ x.style.fontSize = "14px";
2185
+ }
2186
+ card.append(x);
2187
+ if (pos.tapOutsideClose) {
2188
+ dim.addEventListener("click", () => close("tap_outside"));
2189
+ overlay.addEventListener("click", (e) => {
2190
+ if (e.target === overlay) close("tap_outside");
2191
+ });
2192
+ overlay.style.pointerEvents = "auto";
2193
+ }
2194
+ if (pos.autoCloseSec) timers.push(setTimeout(() => close("auto_close"), num2(pos.autoCloseSec, 0, 1, 3600) * 1e3));
2195
+ overlay.append(dim, card);
2196
+ root.append(overlay);
2197
+ document.body.append(host);
2198
+ document.addEventListener("keydown", onKey, true);
2199
+ queueMicrotask(() => card.focus());
2200
+ h.onSeen();
2201
+ return { close };
2202
+ }
2203
+ function renderBannerDesign(c, h) {
2204
+ const d = c.design;
2205
+ const images = Array.isArray(d == null ? void 0 : d.images) ? d.images.filter((i) => {
2206
+ var _a;
2207
+ return safeUrl((_a = i == null ? void 0 : i.media) == null ? void 0 : _a.url);
2208
+ }) : [];
2209
+ if (!d || !images.length || !c.slot_id) return null;
2210
+ const slot = document.querySelector(`[data-cdp-slot="${CSS_ESC(c.slot_id)}"]`);
2211
+ if (!slot) return null;
2212
+ const host = el("div", { "data-cdp-campaign": c.id });
2213
+ const root = mountShadow(host, CSS2);
2214
+ const bn = el("div", { class: "bn", role: "region", "aria-label": clip(c.name, 100) });
2215
+ const track = el("div", { class: "tr" });
2216
+ images.forEach((im, idx) => {
2217
+ var _a;
2218
+ const img = el("img", { src: (_a = safeUrl(im.media.url)) != null ? _a : "", alt: clip(im.alt, 200), referrerpolicy: "no-referrer" });
2219
+ const link = safeUrl(im.link);
2220
+ const cell = el("div", {}, link ? el("a", { href: link, rel: "noopener", target: "_self" }, img) : img);
2221
+ if (link) cell.querySelector("a").addEventListener("click", (ev) => {
2222
+ h.onClick({ action: "url", url: link, text: String(idx + 1) });
2223
+ if (runtime.deeplinks) {
2224
+ ev.preventDefault();
2225
+ runtime.open(link, false);
2226
+ }
2227
+ });
2228
+ track.append(cell);
2229
+ });
2230
+ bn.append(track);
2231
+ let timer, io, dwell;
2232
+ if (d.mode === "carousel" && images.length > 1) {
2233
+ const dots = el("div", { class: "dots" });
2234
+ images.forEach(() => dots.append(el("i")));
2235
+ bn.append(dots);
2236
+ let i = 0;
2237
+ const set = () => {
2238
+ track.style.transform = `translateX(-${i * 100}%)`;
2239
+ dots.querySelectorAll("i").forEach((x, k) => x.classList.toggle("on", k === i));
2240
+ };
2241
+ set();
2242
+ timer = setInterval(() => {
2243
+ i = (i + 1) % images.length;
2244
+ set();
2245
+ }, 5e3);
2246
+ }
2247
+ root.append(bn);
2248
+ slot.append(host);
2249
+ let seen = false;
2250
+ const fire = () => {
2251
+ if (!seen) {
2252
+ seen = true;
2253
+ h.onSeen();
2254
+ io == null ? void 0 : io.disconnect();
2255
+ }
2256
+ };
2257
+ if (typeof IntersectionObserver === "undefined") fire();
2258
+ else {
2259
+ io = new IntersectionObserver((es) => {
2260
+ const vis = es.some((e) => e.isIntersecting && e.intersectionRatio >= 0.5);
2261
+ if (vis && !dwell) dwell = setTimeout(fire, 1e3);
2262
+ else if (!vis && dwell) {
2263
+ clearTimeout(dwell);
2264
+ dwell = void 0;
2265
+ }
2266
+ }, { threshold: [0, 0.5, 1] });
2267
+ io.observe(bn);
2268
+ }
2269
+ return { host, close: () => {
2270
+ if (timer) clearInterval(timer);
2271
+ if (dwell) clearTimeout(dwell);
2272
+ io == null ? void 0 : io.disconnect();
2273
+ host.remove();
2274
+ h.onDismiss("auto_close");
2275
+ } };
2276
+ }
2277
+
2278
+ // src/modules/campaigns.ts
2279
+ var ID_KEYS = /* @__PURE__ */ new Set(["customer_id", "national_id", "phone_number", "email"]);
2280
+ var day = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2281
+ function urlMatches(rules, href) {
2282
+ if (!rules || !rules.length) return true;
2283
+ let path = href;
2284
+ try {
2285
+ const u = new URL(href);
2286
+ path = u.pathname + u.search + u.hash;
2287
+ } catch {
2288
+ }
2289
+ return rules.some((r) => {
2290
+ const t = [href, path];
2291
+ switch (r.match) {
2292
+ case "equals":
2293
+ return t.includes(r.value);
2294
+ case "contains":
2295
+ return t.some((x) => x.includes(r.value));
2296
+ case "starts_with":
2297
+ return t.some((x) => x.startsWith(r.value));
2298
+ case "regex":
2299
+ try {
2300
+ return t.some((x) => new RegExp(r.value).test(x));
2301
+ } catch {
2302
+ return false;
2303
+ }
2304
+ }
2305
+ });
2306
+ }
2307
+ function nowIn(tz, at = /* @__PURE__ */ new Date()) {
2308
+ try {
2309
+ const parts = new Intl.DateTimeFormat("en-GB", { timeZone: tz, weekday: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hourCycle: "h23" }).formatToParts(at);
2310
+ const get = (t) => {
2311
+ var _a, _b;
2312
+ return (_b = (_a = parts.find((p) => p.type === t)) == null ? void 0 : _a.value) != null ? _b : "";
2313
+ };
2314
+ const wd = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"].indexOf(get("weekday")) + 1;
2315
+ return { weekday: wd || 1, monthDay: Number(get("day")), minutes: Number(get("hour")) * 60 + Number(get("minute")) };
2316
+ } catch {
2317
+ return { weekday: at.getDay() || 7, monthDay: at.getDate(), minutes: at.getHours() * 60 + at.getMinutes() };
2318
+ }
2319
+ }
2320
+ var hm = (s) => {
2321
+ const [h, m] = String(s).split(":").map(Number);
2322
+ return (h || 0) * 60 + (m || 0);
2323
+ };
2324
+ function periodKey(t, period) {
2325
+ const d = new Date(t + 7 * 36e5);
2326
+ if (period === "weekly") d.setUTCDate(d.getUTCDate() - (d.getUTCDay() + 6) % 7);
2327
+ return d.toISOString().slice(0, period === "monthly" ? 7 : 10);
2328
+ }
2329
+ function windowOk(w, at = /* @__PURE__ */ new Date()) {
2330
+ var _a, _b;
2331
+ if (!w) return true;
2332
+ const n = nowIn(w.tz || "Asia/Ho_Chi_Minh", at);
2333
+ if (w.freq === "weekly" && ((_a = w.weekdays) == null ? void 0 : _a.length) && !w.weekdays.includes(n.weekday)) return false;
2334
+ if (w.freq === "monthly" && ((_b = w.month_days) == null ? void 0 : _b.length) && !w.month_days.includes(n.monthDay)) return false;
2335
+ const a = hm(w.start), b = hm(w.end);
2336
+ return a <= b ? n.minutes >= a && n.minutes <= b : n.minutes >= a || n.minutes <= b;
2337
+ }
2338
+ function adapt(c) {
2339
+ var _a, _b, _c, _d, _e, _f, _g, _h;
2340
+ if (c.render !== "design") return c;
2341
+ const d = c.design;
2342
+ const sub = d == null ? void 0 : d.subtype;
2343
+ const title = (_b = ((_a = d == null ? void 0 : d.pages) != null ? _a : []).flatMap((p) => {
2344
+ var _a2;
2345
+ return ((_a2 = p.blocks) != null ? _a2 : []).flatMap((b) => {
2346
+ var _a3;
2347
+ return (_a3 = b.elements) != null ? _a3 : [];
2348
+ });
2349
+ }).find((e) => e.kind === "text")) == null ? void 0 : _b.text;
2350
+ if (sub === "survey" && ((_d = (_c = d == null ? void 0 : d.survey) == null ? void 0 : _c.steps) == null ? void 0 : _d.length)) {
2351
+ const qs = d.survey.steps.filter((s) => !["welcome", "thank_you"].includes(s.kind)).map((s) => {
2352
+ var _a2;
2353
+ return {
2354
+ id: s.id,
2355
+ text: s.title,
2356
+ type: s.kind === "short_text" ? "text" : s.kind === "multi_choice" ? "multi_choice" : s.kind === "nps" ? "nps" : ["scale", "csat", "ces"].includes(s.kind) ? "rating" : "single_choice",
2357
+ options: ((_a2 = s.options) != null ? _a2 : []).map((o) => {
2358
+ var _a3;
2359
+ return { id: (_a3 = o.id) != null ? _a3 : o.value, text: o.label };
2360
+ })
2361
+ };
2362
+ });
2363
+ const ty = d.survey.steps.find((s) => s.kind === "thank_you");
2364
+ const thanks = ty ? { text: typeof ty.title === "string" ? ty.title : void 0, coupon_ref: typeof ty.couponRef === "string" ? ty.couponRef : void 0 } : void 0;
2365
+ if (qs.length) return { ...c, kind: "survey", survey: { survey_id: c.id, questions: qs, ...thanks ? { thanks } : {} }, content: { title } };
2366
+ }
2367
+ if (sub === "lead_form" && ((_f = (_e = d == null ? void 0 : d.form) == null ? void 0 : _e.fields) == null ? void 0 : _f.length)) {
2368
+ const fields = d.form.fields.map((f) => ({ name: f.attr || f.id, label: f.label, required: !!f.required, type: f.kind === "email" ? "email" : f.kind === "phone" ? "phone" : f.kind === "consent" ? "checkbox" : "text" }));
2369
+ return { ...c, kind: "lead_form", lead_form: { form_id: c.id, submit_text: d.form.submitLabel, fields }, content: { title } };
2370
+ }
2371
+ if (sub === "game" && ((_h = (_g = d == null ? void 0 : d.game) == null ? void 0 : _g.prizes) == null ? void 0 : _h.length)) {
2372
+ const g = d.game;
2373
+ const type = g.kind === "scratch" ? "scratch_card" : g.kind === "giftbox" ? "gift_box" : "spin_wheel";
2374
+ const prizes = g.prizes.map((p) => ({ id: p.id, label: p.name, weight: p.pct, is_win: !p.noWin, has_coupon: !!p.hasCoupon }));
2375
+ return { ...c, kind: "gamification", game: { game_type: type, prizes, server: prizes.some((p) => p.has_coupon) }, content: { title } };
2376
+ }
2377
+ return c;
2378
+ }
2379
+ var CampaignEngine = class {
2380
+ constructor(sdk, app) {
2381
+ this.sdk = sdk;
2382
+ this.app = app;
2383
+ this.campaigns = [];
2384
+ this.pending = /* @__PURE__ */ new Map();
2385
+ this.active = /* @__PURE__ */ new Map();
2386
+ // đang hiển thị
2387
+ this.shownAt = /* @__PURE__ */ new Map();
2388
+ // campaign -> URL đã hiện (không tự hiện lại khi tải lại danh sách)
2389
+ this.seenEvents = /* @__PURE__ */ new Set();
2390
+ this.waiting = [];
2391
+ // modal/slide-in chờ lượt
2392
+ this.modalOpen = false;
2393
+ this.cleanup = [];
2394
+ this.slotSig = "";
2395
+ // tập khung banner đã gửi ở lần nạp gần nhất (so với DOM hiện tại để biết có cần nạp lại)
2396
+ this.seenSig = "";
2397
+ this.loading = false;
2398
+ // đang nạp: yêu cầu nạp tiếp theo được gộp lại, chạy ngay sau khi xong
2399
+ this.reloadAfter = false;
2400
+ // ---------- tần suất ----------
2401
+ this.freqKey = "freq";
2402
+ }
2403
+ /** Trang đang xem (website) / màn hình đang mở (app): điều kiện "trang", nhớ campaign đã hiện ở đâu. */
2404
+ here() {
2405
+ return this.app ? this.app.screen() : location.href;
2406
+ }
2407
+ get api() {
2408
+ return this.app ? "/sdk/app" : "/sdk/web";
2409
+ }
2410
+ lang() {
2411
+ return this.app ? this.app.lang() : (document.documentElement.lang || "vi").toLowerCase().startsWith("en") ? "en" : "vi";
2412
+ }
2413
+ /** Thân chung của các API nội dung: website gửi đường dẫn trang, app gửi màn hình + nền tảng. */
2414
+ where() {
2415
+ return this.app ? { screen: this.app.screen(), platform: this.app.platform } : { page_url: location.pathname + location.search };
2416
+ }
2417
+ /** App: báo native còn popup đang hiện / đang chờ hay không (để hiện / ẩn WebView). */
2418
+ visibility() {
2419
+ var _a;
2420
+ (_a = this.app) == null ? void 0 : _a.onVisible(this.active.size > 0);
2421
+ }
2422
+ start() {
2423
+ if (!this.sdk.config.inApp.popups && !this.sdk.config.inApp.banners) return;
2424
+ this.sdk.onEvent((name, params) => {
2425
+ if (name === "page_view" || this.app && name === "screen_view") {
2426
+ this.onPage();
2427
+ this.scheduleSlotCheck();
2428
+ }
2429
+ this.onTrackedEvent(name, params);
2430
+ }, true);
2431
+ this.watchSlots();
2432
+ this.sdk.onIdentify(() => void this.load());
2433
+ const ms = this.sdk.config.campaignsRefreshMs;
2434
+ if (ms > 0) this.refreshTimer = setInterval(() => void this.load(), ms);
2435
+ void this.load();
2436
+ }
2437
+ stop() {
2438
+ var _a;
2439
+ this.cleanup.forEach((f) => f());
2440
+ this.cleanup = [];
2441
+ this.pending.forEach((p) => p.timer && clearTimeout(p.timer));
2442
+ this.pending.clear();
2443
+ this.active.forEach((r) => r.close("auto_close"));
2444
+ this.active.clear();
2445
+ if (this.refreshTimer) clearInterval(this.refreshTimer);
2446
+ (_a = this.slotObserver) == null ? void 0 : _a.disconnect();
2447
+ this.slotObserver = void 0;
2448
+ if (this.slotTimer) clearTimeout(this.slotTimer);
2449
+ }
2450
+ /** Các khung banner (`data-cdp-slot`) đang có trên trang, đã khử trùng lặp và sắp xếp. */
2451
+ slotsOnPage() {
2452
+ if (typeof document === "undefined") return [];
2453
+ return [...new Set(Array.from(document.querySelectorAll("[data-cdp-slot]")).map((e) => {
2454
+ var _a;
2455
+ return (_a = e.getAttribute("data-cdp-slot")) != null ? _a : "";
2456
+ }).filter(Boolean))].sort();
2457
+ }
2458
+ /** Website SPA dựng khung banner sau khi SDK đã nạp nội dung (hoặc đổi khung khi chuyển trang): theo dõi DOM,
2459
+ * tập khung khác với lần nạp trước thì nạp lại để lấy banner cho các khung mới. Chỉ khi dùng API của nền tảng (không có contentProvider). */
2460
+ watchSlots() {
2461
+ if (this.app || !this.sdk.config.inApp.banners || this.sdk.config.contentProvider || typeof MutationObserver === "undefined" || typeof document === "undefined") return;
2462
+ this.slotObserver = new MutationObserver(() => this.scheduleSlotCheck());
2463
+ this.slotObserver.observe(document.documentElement, { childList: true, subtree: true });
2464
+ }
2465
+ scheduleSlotCheck() {
2466
+ if (this.slotTimer || !this.slotObserver) return;
2467
+ this.slotTimer = setTimeout(() => {
2468
+ this.slotTimer = void 0;
2469
+ const pruned = this.pruneDetached();
2470
+ const sig = this.slotsOnPage().join(",");
2471
+ if (pruned || sig !== this.seenSig) this.onPage();
2472
+ this.seenSig = sig;
2473
+ if (sig && sig !== this.slotSig) void this.load();
2474
+ }, 150);
2475
+ }
2476
+ /** Gỡ các banner đã vẽ nhưng phần tử không còn trong trang. Trả về true nếu có. */
2477
+ pruneDetached() {
2478
+ let any = false;
2479
+ for (const [id, r] of [...this.active]) {
2480
+ if (r.host && !r.host.isConnected) {
2481
+ r.close("auto_close");
2482
+ this.shownAt.delete(id);
2483
+ any = true;
2484
+ }
2485
+ }
2486
+ return any;
2487
+ }
2488
+ /** Đóng popup hiện lên sau cùng (nút Back của app). false = không có popup nào đang hiện. */
2489
+ closeTop(type = "back") {
2490
+ const last = [...this.active.values()].pop();
2491
+ if (!last) return false;
2492
+ last.close(type);
2493
+ return true;
2494
+ }
2495
+ /** Ghi đè danh sách campaign (dùng cho test/preview) */
2496
+ setCampaigns(list) {
2497
+ this.campaigns = list.filter(valid);
2498
+ this.onPage();
2499
+ }
2500
+ get loaded() {
2501
+ return this.campaigns;
2502
+ }
2503
+ async load() {
2504
+ if (this.loading) {
2505
+ this.reloadAfter = true;
2506
+ return;
2507
+ }
2508
+ this.loading = true;
2509
+ try {
2510
+ await this.loadNow();
2511
+ } finally {
2512
+ this.loading = false;
2513
+ if (this.reloadAfter) {
2514
+ this.reloadAfter = false;
2515
+ void this.load();
2516
+ }
2517
+ }
2518
+ }
2519
+ async loadNow() {
2520
+ const provider = this.sdk.config.contentProvider;
2521
+ let list;
2522
+ if (provider) {
2523
+ let raw = [];
2524
+ try {
2525
+ raw = await provider({ deviceId: this.sdk.getDeviceId(), cid: this.sdk.getCid(), pageUrl: this.here() });
2526
+ } catch (e) {
2527
+ this.sdk.log.warn("content provider failed", e);
2528
+ return;
2529
+ }
2530
+ if (!Array.isArray(raw)) {
2531
+ this.sdk.log.warn("content provider must return an array");
2532
+ return;
2533
+ }
2534
+ list = raw;
2535
+ } else {
2536
+ await this.sdk.whenSynced();
2537
+ const got = await this.fetchServer();
2538
+ if (!got) return;
2539
+ list = got;
2540
+ }
2541
+ this.campaigns = list.map(adapt).filter(valid).sort((a, b) => {
2542
+ var _a, _b;
2543
+ return ((_a = b.priority) != null ? _a : 0) - ((_b = a.priority) != null ? _b : 0);
2544
+ });
2545
+ this.sdk.log.log("campaigns loaded", this.campaigns.length);
2546
+ this.onPage();
2547
+ }
2548
+ /** Gọi hai API nội dung. null = lỗi (giữ danh sách cũ). Chỉ gọi khi thiết bị đã đăng ký. */
2549
+ async fetchServer() {
2550
+ const deviceId = this.sdk.getDeviceId();
2551
+ if (!deviceId || this.sdk.trackingBlocked) return null;
2552
+ const c = this.sdk.config.inApp;
2553
+ const slots = this.app ? this.app.slots() : this.slotsOnPage();
2554
+ this.slotSig = slots.join(",");
2555
+ const body = { device_id: deviceId, cid: this.sdk.getCid(), ...this.where(), logged_in: this.sdk.isIdentified(), lang: this.lang() };
2556
+ const calls = [];
2557
+ if (c.popups) calls.push(this.sdk.http.request("POST", `${this.api}/popup`, body));
2558
+ if (c.banners && slots.length) calls.push(this.sdk.http.request("POST", `${this.api}/banners`, { ...body, slots, supports: ["banner_fallback"] }));
2559
+ if (!calls.length) return [];
2560
+ const res = await Promise.all(calls);
2561
+ let ttl = 300;
2562
+ const out = [];
2563
+ for (const r of res) {
2564
+ if (r.status === 429) {
2565
+ this.schedule(60);
2566
+ return null;
2567
+ }
2568
+ if (r.status !== 200 || !r.json) {
2569
+ this.sdk.log.warn("in-app content request failed", r.status);
2570
+ return null;
2571
+ }
2572
+ if (Array.isArray(r.json.campaigns)) out.push(...r.json.campaigns);
2573
+ if (typeof r.json.ttl_sec === "number") ttl = Math.min(ttl, Math.max(30, r.json.ttl_sec));
2574
+ }
2575
+ this.schedule(ttl);
2576
+ return out;
2577
+ }
2578
+ /**
2579
+ * Mã coupon của popup đang hiện (phần tử coupon có `couponRef`): server cấp lúc này, mỗi khách 1 mã / danh sách /
2580
+ * campaign, hiện lại ra đúng mã cũ (docs/sdk-inapp-contract.md mục 2.3). null = không có mã (404, lỗi mạng, chặn theo dõi).
2581
+ */
2582
+ async couponCode(c, listId) {
2583
+ var _a;
2584
+ const deviceId = this.sdk.getDeviceId();
2585
+ if (!deviceId || this.sdk.trackingBlocked || this.sdk.config.contentProvider) return null;
2586
+ try {
2587
+ const r = await this.sdk.http.request("POST", `${this.api}/coupon`, { device_id: deviceId, ...this.where(), lang: this.lang(), campaign_id: c.id, list_id: listId });
2588
+ return r.status === 200 && typeof ((_a = r.json) == null ? void 0 : _a.code) === "string" && r.json.code ? r.json.code.slice(0, 200) : null;
2589
+ } catch (e) {
2590
+ this.sdk.log.warn("coupon request failed", e);
2591
+ return null;
2592
+ }
2593
+ }
2594
+ /**
2595
+ * Mã của bước "Cảm ơn" của khảo sát: gửi câu trả lời mọi câu hỏi, máy chủ kiểm tra rồi mới cấp (mỗi khách 1 mã / danh
2596
+ * sách / campaign; docs/sdk-inapp-contract.md mục 2.5). null = không có mã (trả lời chưa đủ, hết mã, lỗi mạng…).
2597
+ */
2598
+ async surveyCode(c, answers) {
2599
+ var _a;
2600
+ const deviceId = this.sdk.getDeviceId();
2601
+ if (!deviceId || this.sdk.trackingBlocked || this.sdk.config.contentProvider || !answers.length) return null;
2602
+ try {
2603
+ const r = await this.sdk.http.request("POST", `${this.api}/survey`, { device_id: deviceId, ...this.where(), lang: this.lang(), campaign_id: c.id, answers: answers.slice(0, 50) });
2604
+ return r.status === 200 && typeof ((_a = r.json) == null ? void 0 : _a.code) === "string" && r.json.code ? r.json.code.slice(0, 200) : null;
2605
+ } catch (e) {
2606
+ this.sdk.log.warn("survey coupon request failed", e);
2607
+ return null;
2608
+ }
2609
+ }
2610
+ /**
2611
+ * Một lượt chơi mini game có giải kèm mã: máy chủ quyết giải, giới hạn lượt chơi, cấp mã (docs/sdk-inapp-contract.md
2612
+ * mục 2.4). null = không chơi được (popup không còn dành cho khách, khách chưa có hồ sơ, lỗi mạng).
2613
+ */
2614
+ async gamePlay(c) {
2615
+ const deviceId = this.sdk.getDeviceId();
2616
+ if (!deviceId || this.sdk.trackingBlocked || this.sdk.config.contentProvider) return null;
2617
+ try {
2618
+ const r = await this.sdk.http.request("POST", `${this.api}/game/play`, { device_id: deviceId, ...this.where(), lang: this.lang(), campaign_id: c.id });
2619
+ const j = r.json;
2620
+ if (r.status !== 200 || !j || j.status !== "played" && j.status !== "limit") return null;
2621
+ return { status: j.status, prize_id: typeof j.prize_id === "string" ? j.prize_id : null, is_win: j.is_win === true, code: typeof j.code === "string" && j.code ? j.code.slice(0, 200) : null };
2622
+ } catch (e) {
2623
+ this.sdk.log.warn("game play request failed", e);
2624
+ return null;
2625
+ }
2626
+ }
2627
+ /** Gọi lại khi hết `ttl_sec`. */
2628
+ schedule(sec) {
2629
+ if (this.ttlTimer) clearTimeout(this.ttlTimer);
2630
+ this.ttlTimer = setTimeout(() => void this.load(), sec * 1e3);
2631
+ }
2632
+ /** Điều kiện trang: nhiều điều kiện (`trigger.list`) hoặc `trigger.urls` cũ. */
2633
+ urlGate(c) {
2634
+ var _a, _b;
2635
+ if (((_a = c.display_pages) == null ? void 0 : _a.length) && !urlMatches(c.display_pages, this.here())) return false;
2636
+ const t = c.trigger;
2637
+ const list = t == null ? void 0 : t.list;
2638
+ if (!(list == null ? void 0 : list.length)) return urlMatches(t == null ? void 0 : t.urls, this.here());
2639
+ const pages = list.flatMap((x) => x.kind === "page" ? x.urls : []);
2640
+ const hasEvents = list.some((x) => x.kind === "event");
2641
+ if (!pages.length) return true;
2642
+ if (((_b = t == null ? void 0 : t.mode) != null ? _b : "any") === "any" && hasEvents) return true;
2643
+ return urlMatches(pages, this.here());
2644
+ }
2645
+ /** Các điều kiện trang / event đã thỏa theo `mode` (chỉ cho `trigger.list`). */
2646
+ listOk(c) {
2647
+ var _a, _b, _c;
2648
+ const list = (_a = c.trigger) == null ? void 0 : _a.list;
2649
+ if (!(list == null ? void 0 : list.length)) return true;
2650
+ const pages = list.flatMap((x) => x.kind === "page" ? x.urls : []);
2651
+ const results = list.map((x) => x.kind === "page" ? urlMatches(x.urls, this.here()) : this.seenEvents.has(x.name));
2652
+ void pages;
2653
+ return ((_c = (_b = c.trigger) == null ? void 0 : _b.mode) != null ? _c : "any") === "all" ? results.every(Boolean) : results.some(Boolean);
2654
+ }
2655
+ // ---------- đánh giá điều kiện ----------
2656
+ onPage() {
2657
+ this.pruneDetached();
2658
+ for (const [id, p] of this.pending) if (!this.urlGate(p.c)) {
2659
+ p.timer && clearTimeout(p.timer);
2660
+ this.pending.delete(id);
2661
+ }
2662
+ this.cleanup.forEach((f) => f());
2663
+ this.cleanup = [];
2664
+ for (const c of this.campaigns) if (this.shownAt.get(c.id) !== this.here() && this.eligible(c)) this.arm(c);
2665
+ for (const [id, r] of this.active) {
2666
+ const c = this.campaigns.find((x) => x.id === id);
2667
+ if (c && !this.urlGate(c)) {
2668
+ r.close("auto_close");
2669
+ }
2670
+ }
2671
+ }
2672
+ eligible(c) {
2673
+ if (this.active.has(c.id) || this.waiting.some((w) => w.id === c.id)) return false;
2674
+ if (this.sdk.trackingBlocked) return false;
2675
+ if (c.fallback && this.slotHeld(c)) return false;
2676
+ return this.allowed(c);
2677
+ }
2678
+ /** Banner mặc định phải nhường: khung có banner thường đang hiện, hoặc còn hiện được. */
2679
+ slotHeld(fallback) {
2680
+ return this.campaigns.some((o) => !o.fallback && o.slot_id === fallback.slot_id && (this.active.has(o.id) || this.allowed(o)));
2681
+ }
2682
+ /** Hiệu lực, trang, khung giờ, đăng nhập và tần suất. */
2683
+ allowed(c) {
2684
+ var _a;
2685
+ const now = Date.now();
2686
+ if (c.start_time && Date.parse(c.start_time) > now) return false;
2687
+ if (c.end_time && Date.parse(c.end_time) < now) return false;
2688
+ if (!this.urlGate(c)) return false;
2689
+ if (!windowOk(c.display_window)) return false;
2690
+ if (((_a = c.audience) == null ? void 0 : _a.logged_in) !== void 0 && c.audience.logged_in !== this.sdk.isIdentified()) return false;
2691
+ if (!this.freqOk(c)) return false;
2692
+ return true;
2693
+ }
2694
+ arm(c) {
2695
+ var _a;
2696
+ if (this.pending.has(c.id)) return;
2697
+ const t = (_a = c.trigger) != null ? _a : {};
2698
+ const p = { c, delay: !t.delay_ms, scroll: !t.scroll_percent, exit: !t.exit_intent, event: (!t.event || this.seenEvents.has(t.event.name)) && this.listOk(c), armedAt: Date.now() };
2699
+ this.pending.set(c.id, p);
2700
+ if (t.delay_ms) p.timer = setTimeout(() => {
2701
+ p.delay = true;
2702
+ this.check(p);
2703
+ }, t.delay_ms);
2704
+ if (t.scroll_percent) {
2705
+ const on = () => {
2706
+ const doc = document.documentElement;
2707
+ const pct = (window.scrollY + window.innerHeight) / Math.max(doc.scrollHeight, 1) * 100;
2708
+ if (pct >= t.scroll_percent) {
2709
+ p.scroll = true;
2710
+ window.removeEventListener("scroll", on);
2711
+ this.check(p);
2712
+ }
2713
+ };
2714
+ window.addEventListener("scroll", on, { passive: true });
2715
+ this.cleanup.push(() => window.removeEventListener("scroll", on));
2716
+ on();
2717
+ }
2718
+ if (t.exit_intent) {
2719
+ const on = (e) => {
2720
+ if (e.clientY <= 0 && !e.relatedTarget) {
2721
+ p.exit = true;
2722
+ document.removeEventListener("mouseout", on);
2723
+ this.check(p);
2724
+ }
2725
+ };
2726
+ document.addEventListener("mouseout", on);
2727
+ this.cleanup.push(() => document.removeEventListener("mouseout", on));
2728
+ }
2729
+ this.check(p);
2730
+ }
2731
+ onTrackedEvent(name, params) {
2732
+ var _a, _b, _c;
2733
+ this.seenEvents.add(name);
2734
+ for (const [id, p] of this.pending) {
2735
+ const cx = (_a = p.c.trigger) == null ? void 0 : _a.cancel;
2736
+ if (!cx || cx.event !== name) continue;
2737
+ if (cx.wait_ms && Date.now() - p.armedAt > cx.wait_ms) continue;
2738
+ if (p.timer) clearTimeout(p.timer);
2739
+ this.pending.delete(id);
2740
+ this.shownAt.set(id, this.here());
2741
+ }
2742
+ for (const p of this.pending.values()) {
2743
+ const t = p.c.trigger;
2744
+ if ((_b = t == null ? void 0 : t.list) == null ? void 0 : _b.length) {
2745
+ if (!p.event && this.listOk(p.c)) {
2746
+ p.event = true;
2747
+ this.check(p);
2748
+ }
2749
+ continue;
2750
+ }
2751
+ const ev = t == null ? void 0 : t.event;
2752
+ if (!ev || p.event || ev.name !== name) continue;
2753
+ if (ev.params && !Object.entries(ev.params).every(([k, v]) => params[k] === v)) continue;
2754
+ p.event = true;
2755
+ this.check(p);
2756
+ }
2757
+ for (const c of this.campaigns) {
2758
+ if (this.pending.has(c.id) || !this.eligible(c)) continue;
2759
+ const t = c.trigger;
2760
+ if ((_c = t == null ? void 0 : t.list) == null ? void 0 : _c.length) {
2761
+ if (!t.list.some((x) => x.kind === "event" && x.name === name) || !this.listOk(c)) continue;
2762
+ this.arm(c);
2763
+ const p3 = this.pending.get(c.id);
2764
+ if (p3) {
2765
+ p3.event = true;
2766
+ this.check(p3);
2767
+ }
2768
+ continue;
2769
+ }
2770
+ const ev = t == null ? void 0 : t.event;
2771
+ if (!ev || ev.name !== name) continue;
2772
+ if (ev.params && !Object.entries(ev.params).every(([k, v]) => params[k] === v)) continue;
2773
+ this.arm(c);
2774
+ const p = this.pending.get(c.id);
2775
+ if (p) {
2776
+ p.event = true;
2777
+ this.check(p);
2778
+ }
2779
+ }
2780
+ }
2781
+ check(p) {
2782
+ if (!(p.delay && p.scroll && p.exit && p.event)) return;
2783
+ this.pending.delete(p.c.id);
2784
+ if (this.eligible(p.c)) this.show(p.c);
2785
+ }
2786
+ freqAll() {
2787
+ var _a;
2788
+ return (_a = this.sdk.storage.getJSON(this.freqKey)) != null ? _a : {};
2789
+ }
2790
+ freqOk(c) {
2791
+ var _a;
2792
+ const f = this.freqAll()[c.id];
2793
+ const r = c.frequency;
2794
+ if (!f || !r) return true;
2795
+ if (r.hide_after_dismiss && f.dismissed) return false;
2796
+ if (r.hide_after_click && f.clicked) return false;
2797
+ if (r.max_total !== void 0 && f.total >= r.max_total) return false;
2798
+ if (r.max_in_window && f.hits && f.hits.filter((t) => t > Date.now() - r.max_in_window.days * 864e5).length >= r.max_in_window.count) return false;
2799
+ if (r.max_per_period && ((_a = f.hits) != null ? _a : []).filter((t) => periodKey(t, r.max_per_period.period) === periodKey(Date.now(), r.max_per_period.period)).length >= r.max_per_period.count) return false;
2800
+ if (r.max_per_day !== void 0 && f.day === day() && f.today >= r.max_per_day) return false;
2801
+ if (r.cooldown_ms && Date.now() - f.last < r.cooldown_ms) return false;
2802
+ return true;
2803
+ }
2804
+ freqUpdate(c, fn) {
2805
+ var _a;
2806
+ const all = this.freqAll();
2807
+ const f = (_a = all[c.id]) != null ? _a : { total: 0, day: day(), today: 0, last: 0 };
2808
+ if (f.day !== day()) {
2809
+ f.day = day();
2810
+ f.today = 0;
2811
+ }
2812
+ fn(f);
2813
+ if (f.hits) f.hits = f.hits.filter((t) => t > Date.now() - 366 * 864e5).slice(-200);
2814
+ all[c.id] = f;
2815
+ this.sdk.storage.setJSON(this.freqKey, all);
2816
+ }
2817
+ // ---------- hiển thị ----------
2818
+ show(c) {
2819
+ const overlayLike = c.template === "modal" || c.template === "slide_in";
2820
+ if (overlayLike && this.modalOpen) {
2821
+ this.waiting.push(c);
2822
+ return;
2823
+ }
2824
+ this.display(c);
2825
+ }
2826
+ display(c) {
2827
+ var _a;
2828
+ const message_id = c.message_id || uuid();
2829
+ const app = !!this.app;
2830
+ const banner = !(c.template === "modal" || c.template === "slide_in");
2831
+ const channel = app ? banner ? "app_banner" : "inapp_popup" : banner ? "web_banner" : "web_popup";
2832
+ const corr = {
2833
+ channel,
2834
+ message_id,
2835
+ variant_id: c.variant_id || "control",
2836
+ message_type: c.message_type || "advertisement",
2837
+ campaign_id: c.id,
2838
+ campaign_name: c.name,
2839
+ campaign_type: c.campaign_type,
2840
+ content_id: c.content_id
2841
+ };
2842
+ const isBanner = banner;
2843
+ const bannerSeen = () => {
2844
+ var _a2;
2845
+ return emit(app ? "banner_seen" : "web_banner_seen", { slot_id: c.slot_id || `${c.template}`, position: (_a2 = c.position) != null ? _a2 : 1 });
2846
+ };
2847
+ const bannerClick = (url) => {
2848
+ var _a2, _b;
2849
+ return app ? emit("banner_click", { slot_id: c.slot_id || c.template, position: (_a2 = c.position) != null ? _a2 : 1, deep_link: url }) : emit("web_banner_clicked", { slot_id: c.slot_id || c.template, position: (_b = c.position) != null ? _b : 1, url });
2850
+ };
2851
+ const seen = () => app ? emit("inapp_seen", { inapp_id: c.id }) : emit("web_popup_seen", { inapp_id: c.id });
2852
+ const clickedEv = (p) => app ? emit("inapp_clicked", { inapp_id: c.id, click_action: p.action === "url" && p.url && !/^https?:/i.test(p.url) ? "deeplink" : p.action, button_text: p.text, deep_link: p.url }) : emit("web_popup_clicked", { inapp_id: c.id, click_action: p.action, button_text: p.text, url: p.url });
2853
+ const dismissedEv = (type) => emit(app ? "inapp_dismissed" : "web_popup_dismissed", { inapp_id: c.id, dismiss_type: type });
2854
+ const copy = (code) => {
2855
+ var _a2;
2856
+ if (this.app) this.app.copy(code.slice(0, 200));
2857
+ else void ((_a2 = navigator.clipboard) == null ? void 0 : _a2.writeText(code.slice(0, 200)).catch(() => void 0));
2858
+ };
2859
+ const askPush = () => {
2860
+ var _a2;
2861
+ if (this.app) this.app.requestPush();
2862
+ else void ((_a2 = this.sdk.webPush) == null ? void 0 : _a2.subscribe("soft"));
2863
+ };
2864
+ const emit = (name, p) => this.sdk.emit(name, { ...corr, ...p });
2865
+ const overlayLike = !isBanner;
2866
+ let clicked = false;
2867
+ const dz = c.design;
2868
+ const designedGame = c.render === "design" && c.kind === "gamification" && !!(dz == null ? void 0 : dz.game) && Array.isArray(dz.pages) && dz.pages.length > 0;
2869
+ const designed = designedGame || c.render === "design" && ((_a = c.kind) != null ? _a : "message") === "message" && !c.content;
2870
+ const rendered = designed ? (isBanner ? renderBannerDesign : renderPopupDesign)(c, {
2871
+ coupon: (listId) => this.couponCode(c, listId),
2872
+ play: () => this.gamePlay(c),
2873
+ onGame: (r) => {
2874
+ var _a2, _b;
2875
+ return this.sdk.emit("gamification_played", { ...corr, game_type: (_b = (_a2 = c.game) == null ? void 0 : _a2.game_type) != null ? _b : "spin_wheel", is_win: r.is_win, prize_id: r.prize_id });
2876
+ },
2877
+ onSeen: () => {
2878
+ this.freqUpdate(c, (f) => {
2879
+ var _a2;
2880
+ f.total++;
2881
+ f.today++;
2882
+ f.last = Date.now();
2883
+ ((_a2 = f.hits) != null ? _a2 : f.hits = []).push(f.last);
2884
+ });
2885
+ if (isBanner) bannerSeen();
2886
+ else seen();
2887
+ },
2888
+ onClick: (info) => {
2889
+ clicked = true;
2890
+ this.freqUpdate(c, (f) => {
2891
+ f.clicked = true;
2892
+ });
2893
+ if (isBanner) bannerClick(info.url);
2894
+ else clickedEv(info);
2895
+ void this.sdk.flush();
2896
+ },
2897
+ onDismiss: (type) => {
2898
+ this.active.delete(c.id);
2899
+ if (overlayLike) {
2900
+ this.modalOpen = false;
2901
+ }
2902
+ if (!clicked && type !== "auto_close") this.freqUpdate(c, (f) => {
2903
+ f.dismissed = true;
2904
+ });
2905
+ if (!isBanner) dismissedEv(type);
2906
+ const nextC = this.waiting.shift();
2907
+ if (nextC) setTimeout(() => this.display(nextC), 300);
2908
+ else this.visibility();
2909
+ },
2910
+ onSideEffect: (e) => {
2911
+ switch (e.kind) {
2912
+ case "push":
2913
+ askPush();
2914
+ return;
2915
+ case "copy":
2916
+ copy(e.code);
2917
+ return;
2918
+ case "event":
2919
+ this.sdk.track(e.name, e.params).catch((er) => this.sdk.log.warn("popup event not sent", er.message));
2920
+ return;
2921
+ case "attrs":
2922
+ void this.sdk.setAttributes(e.attrs).catch((er) => this.sdk.log.warn("popup attributes not accepted", er.message));
2923
+ return;
2924
+ case "form": {
2925
+ const ids = {};
2926
+ const attrs = {};
2927
+ for (const [k, v] of Object.entries(e.values)) {
2928
+ if (ID_KEYS.has(k)) ids[k] = String(v);
2929
+ else attrs[k] = String(v);
2930
+ }
2931
+ const submitted = Object.keys(e.values);
2932
+ void (async () => {
2933
+ if (Object.keys(attrs).length) await this.sdk.setAttributes(attrs).catch((er) => this.sdk.log.warn("form attributes not accepted", er.message));
2934
+ if (Object.keys(ids).length) await this.sdk.identify(ids).catch((er) => this.sdk.log.warn("form identify failed", er.message));
2935
+ this.sdk.emit("lead_collected", { ...corr, form_id: c.id, fields_submitted: submitted });
2936
+ })();
2937
+ }
2938
+ }
2939
+ }
2940
+ }) : render(c, {
2941
+ onSeen: () => {
2942
+ this.freqUpdate(c, (f) => {
2943
+ var _a2;
2944
+ f.total++;
2945
+ f.today++;
2946
+ f.last = Date.now();
2947
+ ((_a2 = f.hits) != null ? _a2 : f.hits = []).push(f.last);
2948
+ });
2949
+ if (isBanner) bannerSeen();
2950
+ else seen();
2951
+ },
2952
+ onClick: (b) => {
2953
+ clicked = true;
2954
+ this.freqUpdate(c, (f) => {
2955
+ f.clicked = true;
2956
+ });
2957
+ this.runAction(c, b, isBanner, clickedEv, bannerClick, copy, askPush);
2958
+ },
2959
+ onDismiss: (type) => {
2960
+ this.active.delete(c.id);
2961
+ if (overlayLike) {
2962
+ this.modalOpen = false;
2963
+ }
2964
+ if (!clicked && type !== "auto_close") this.freqUpdate(c, (f) => {
2965
+ f.dismissed = true;
2966
+ });
2967
+ if (!isBanner) dismissedEv(type);
2968
+ const nextC = this.waiting.shift();
2969
+ if (nextC) setTimeout(() => this.display(nextC), 300);
2970
+ else this.visibility();
2971
+ },
2972
+ onSurveyAnswer: (q, a) => {
2973
+ var _a2, _b;
2974
+ const base = { ...corr, survey_id: c.survey.survey_id, question_id: q.id, question_text: q.text, question_type: q.type };
2975
+ if (q.type === "multi_choice") {
2976
+ for (const id of a.ids) this.sdk.emit("survey_result", { ...base, answer_id: id, answer_text: (_b = (_a2 = q.options) == null ? void 0 : _a2.find((o) => o.id === id)) == null ? void 0 : _b.text });
2977
+ } else this.sdk.emit("survey_result", { ...base, answer_id: a.ids[0], answer_text: a.text, score: a.score });
2978
+ },
2979
+ onLeadSubmit: async (values, fields) => {
2980
+ var _a2, _b;
2981
+ const ids = {};
2982
+ const attrs = {};
2983
+ for (const [k, v] of Object.entries(values)) {
2984
+ if (ID_KEYS.has(k)) ids[k] = String(v);
2985
+ else attrs[k] = v;
2986
+ }
2987
+ if (Object.keys(attrs).length) await this.sdk.setAttributes(attrs).catch((e) => this.sdk.log.warn("lead form: attributes were not accepted", e.message));
2988
+ if (Object.keys(ids).length) await this.sdk.identify(ids).catch((e) => this.sdk.log.warn("lead form: identify failed", e.message));
2989
+ this.sdk.emit("lead_collected", { ...corr, form_id: (_b = (_a2 = c.lead_form) == null ? void 0 : _a2.form_id) != null ? _b : c.id, fields_submitted: fields.filter((f) => f.name in values).map((f) => f.name) });
2990
+ },
2991
+ onGame: (r) => this.sdk.emit("gamification_played", { ...corr, game_type: c.game.game_type, is_win: r.is_win, prize_id: r.prize_id }),
2992
+ coupon: (listId) => this.couponCode(c, listId),
2993
+ surveyCoupon: (answers) => this.surveyCode(c, answers),
2994
+ play: () => this.gamePlay(c)
2995
+ });
2996
+ if (!rendered) return;
2997
+ this.shownAt.set(c.id, this.here());
2998
+ this.active.set(c.id, rendered);
2999
+ if (overlayLike) this.modalOpen = true;
3000
+ this.visibility();
3001
+ }
3002
+ runAction(c, b, isBanner, clickedEv, bannerClick, copy, askPush) {
3003
+ var _a;
3004
+ const a = b.action;
3005
+ const click = (action, url) => {
3006
+ if (isBanner) bannerClick(url);
3007
+ else clickedEv({ action, text: b.text, url });
3008
+ };
3009
+ switch (a.type) {
3010
+ case "url":
3011
+ case "go_to_page": {
3012
+ const url = safeUrl(a.url);
3013
+ if (!url) {
3014
+ this.sdk.log.warn("blocked unsafe url", a.url);
3015
+ return;
3016
+ }
3017
+ click(a.type, url);
3018
+ void this.sdk.flush();
3019
+ runtime.open(url, a.type === "url" && !!a.newTab);
3020
+ return;
3021
+ }
3022
+ case "dismiss":
3023
+ click("dismiss");
3024
+ (_a = this.active.get(c.id)) == null ? void 0 : _a.close("close_button");
3025
+ return;
3026
+ case "request_push_permission":
3027
+ click("request_push_permission");
3028
+ askPush();
3029
+ return;
3030
+ case "trigger_event":
3031
+ click("trigger_event");
3032
+ void this.sdk.track(a.event, a.params);
3033
+ return;
3034
+ case "update_attribute":
3035
+ click("update_attribute");
3036
+ void this.sdk.setAttributes(a.attributes);
3037
+ return;
3038
+ case "copy_code":
3039
+ click("copy_code");
3040
+ copy(String(a.code));
3041
+ return;
3042
+ }
3043
+ }
3044
+ };
3045
+ function valid(c) {
3046
+ return !!c && typeof c.id === "string" && typeof c.name === "string" && (!!c.content || c.render === "design" && !!c.design) && ["modal", "slide_in", "banner_top", "banner_bottom", "inline"].includes(c.template);
3047
+ }
3048
+
3049
+ // src/modules/webpush.ts
3050
+ var b64ToBytes = (b64) => {
3051
+ const pad = "=".repeat((4 - b64.length % 4) % 4);
3052
+ const raw = atob((b64 + pad).replace(/-/g, "+").replace(/_/g, "/"));
3053
+ return Uint8Array.from(raw, (c) => c.charCodeAt(0));
3054
+ };
3055
+ var sameKey = (sub, key) => {
3056
+ var _a;
3057
+ const have = (_a = sub.options) == null ? void 0 : _a.applicationServerKey;
3058
+ if (!have) return true;
3059
+ const a = new Uint8Array(have), b = b64ToBytes(key);
3060
+ return a.length === b.length && a.every((v, i) => v === b[i]);
3061
+ };
3062
+ var SW_ACTIVATE_MS = 1e4;
3063
+ var WebPush = class {
3064
+ // refresh() và phần đăng ký của subscribe() không chạy chồng nhau
3065
+ constructor(sdk) {
3066
+ this.sdk = sdk;
3067
+ this.failure = null;
3068
+ // subscribe đang chạy: gọi lần nữa (nút bấm + tự hỏi lúc vào trang) dùng chung, không mở hai hộp hỏi
3069
+ this.lock = Promise.resolve();
3070
+ }
3071
+ get supported() {
3072
+ return typeof navigator !== "undefined" && "serviceWorker" in navigator && typeof window !== "undefined" && "PushManager" in window && "Notification" in window;
3073
+ }
3074
+ get swUrl() {
3075
+ return this.sdk.config.webPush.serviceWorkerPath;
3076
+ }
3077
+ get enabled() {
3078
+ var _a;
3079
+ return this.supported && this.enabledByServer !== false && !!((_a = this.vapid) != null ? _a : this.sdk.config.webPush.vapidPublicKey);
3080
+ }
3081
+ /** Lý do lần subscribe() gần nhất thất bại; null nếu thành công hoặc chưa thử */
3082
+ get lastError() {
3083
+ return this.failure;
3084
+ }
3085
+ /** Trang hiện tại có nằm trong scope của service worker không. Ngoài scope (ví dụ /shop so với scope /shop/) thì service worker
3086
+ * không bao giờ điều khiển trang, navigator.serviceWorker.ready treo mãi. */
3087
+ get inScope() {
3088
+ try {
3089
+ return location.href.startsWith(new URL(this.sdk.config.webPush.serviceWorkerScope, location.href).href);
3090
+ } catch {
3091
+ return true;
3092
+ }
3093
+ }
3094
+ serialize(fn) {
3095
+ const run = this.lock.then(fn, fn);
3096
+ this.lock = run.catch(() => void 0);
3097
+ return run;
3098
+ }
3099
+ /** Lấy khoá VAPID của tenant từ nền tảng. enabled=false (tenant chưa có kênh Web Push) thì SDK ẩn mọi nút đăng ký. */
3100
+ async loadConfig() {
3101
+ var _a;
3102
+ const r = await this.sdk.http.webConfig();
3103
+ if (r.ok && ((_a = r.json) == null ? void 0 : _a.webPush)) {
3104
+ this.enabledByServer = !!r.json.webPush.enabled;
3105
+ this.vapid = r.json.webPush.vapidPublicKey || this.vapid;
3106
+ }
3107
+ return this.enabled;
3108
+ }
3109
+ async state() {
3110
+ if (!this.supported) return { supported: false, permission: "unsupported", subscribed: false, enabled: false, lastError: this.failure };
3111
+ const reg = await navigator.serviceWorker.getRegistration(this.swUrl).catch(() => void 0);
3112
+ const sub = await (reg == null ? void 0 : reg.pushManager.getSubscription().catch(() => null));
3113
+ return { supported: true, permission: Notification.permission, subscribed: !!sub, enabled: this.enabled, lastError: this.failure };
3114
+ }
3115
+ /** Gọi sau cử chỉ người dùng (nút bấm). `soft` = đã hỏi bằng UI riêng trước hộp xin quyền của trình duyệt.
3116
+ * Trả true/false; lý do thất bại ở `lastError`. Gọi lại khi lần trước chưa xong thì dùng chung kết quả lần đó. */
3117
+ subscribe(opts = {}) {
3118
+ var _a;
3119
+ return (_a = this.pending) != null ? _a : this.pending = this.doSubscribe(opts).finally(() => {
3120
+ this.pending = void 0;
3121
+ });
3122
+ }
3123
+ fail(reason, msg, e) {
3124
+ this.failure = reason;
3125
+ if (e === void 0) this.sdk.log.warn(msg);
3126
+ else this.sdk.log.warn(msg, e);
3127
+ return false;
3128
+ }
3129
+ async doSubscribe(opts) {
3130
+ const soft = opts === "soft" || typeof opts === "object" && !!opts.soft;
3131
+ this.failure = null;
3132
+ if (!this.supported) return this.fail("unsupported", "web push unsupported");
3133
+ if (this.sdk.trackingBlocked) return this.fail("no_consent", "web push skipped: no consent");
3134
+ if (!this.inScope) return this.fail("out_of_scope", `web push: page ${location.pathname} is outside serviceWorkerScope ${this.sdk.config.webPush.serviceWorkerScope}`);
3135
+ if (this.enabledByServer === void 0) await this.loadConfig();
3136
+ if (!this.enabled) return this.fail("disabled", "web push disabled (tenant has no Web Push channel or /sdk/web/config failed)");
3137
+ try {
3138
+ if (this.sdk.config.webPush.softPrompt && !soft && Notification.permission === "default" && !await askSoft()) return this.fail("dismissed", "web push: soft prompt declined");
3139
+ const perm = Notification.permission === "granted" ? "granted" : await Notification.requestPermission();
3140
+ if (perm !== "granted") return this.fail(perm === "denied" ? "denied" : "dismissed", `web push permission ${perm}`);
3141
+ const ok2 = await this.serialize(async () => {
3142
+ const reg = await navigator.serviceWorker.register(this.swUrl, { scope: this.sdk.config.webPush.serviceWorkerScope });
3143
+ if (!await activeWorker(reg)) return this.fail("sw_timeout", "web push: service worker did not activate");
3144
+ return this.register(reg);
3145
+ });
3146
+ if (ok2) this.sdk.emit("web_push_subscribed", { prompt_type: soft || this.sdk.config.webPush.softPrompt ? "soft" : "native" });
3147
+ return ok2;
3148
+ } catch (e) {
3149
+ const unavailable = e instanceof Error && /permission denied/i.test(e.message);
3150
+ return this.fail(unavailable ? "push_unavailable" : "push_service", "web push subscribe failed", e);
3151
+ }
3152
+ }
3153
+ async unsubscribe() {
3154
+ if (!this.supported) return false;
3155
+ try {
3156
+ const reg = await navigator.serviceWorker.getRegistration(this.swUrl);
3157
+ const sub = await (reg == null ? void 0 : reg.pushManager.getSubscription());
3158
+ if (!sub) return false;
3159
+ await this.sdk.http.pushToken({ deviceId: this.sdk.getDeviceId(), provider: "webpush", token: JSON.stringify(sub.toJSON()), optIn: false });
3160
+ await sub.unsubscribe();
3161
+ this.sdk.storage.remove("push");
3162
+ this.sdk.emit("web_push_unsubscribed", {});
3163
+ return true;
3164
+ } catch (e) {
3165
+ this.sdk.log.warn("web push unsubscribe failed", e);
3166
+ return false;
3167
+ }
3168
+ }
3169
+ /** Mỗi lần init: đồng bộ trạng thái thực với nền tảng (đổi khoá VAPID, đổi endpoint, bị thu hồi quyền). */
3170
+ async refresh() {
3171
+ if (!this.supported || !this.sdk.config.webPush.enabled || this.sdk.trackingBlocked) return;
3172
+ return this.serialize(() => this.doRefresh());
3173
+ }
3174
+ async doRefresh() {
3175
+ var _a, _b;
3176
+ try {
3177
+ await this.sdk.whenSynced();
3178
+ await this.loadConfig();
3179
+ const saved = this.sdk.storage.getJSON("push");
3180
+ const reg = await navigator.serviceWorker.getRegistration(this.swUrl);
3181
+ const sub = await (reg == null ? void 0 : reg.pushManager.getSubscription());
3182
+ if (!this.enabled) return;
3183
+ const key = (_b = (_a = this.vapid) != null ? _a : this.sdk.config.webPush.vapidPublicKey) != null ? _b : "";
3184
+ if (!sub) {
3185
+ if (saved) {
3186
+ await this.sdk.http.pushToken({ deviceId: this.sdk.getDeviceId(), provider: "webpush", token: saved.token, optIn: false });
3187
+ this.sdk.storage.remove("push");
3188
+ this.sdk.emit("web_push_unsubscribed", {});
3189
+ }
3190
+ return;
3191
+ }
3192
+ if (reg && Notification.permission === "granted") {
3193
+ if (saved && saved.key !== key) {
3194
+ await sub.unsubscribe();
3195
+ await this.register(reg);
3196
+ return;
3197
+ }
3198
+ if (!saved || saved.endpoint !== sub.endpoint) {
3199
+ await this.register(reg);
3200
+ return;
3201
+ }
3202
+ await this.configureWorker(reg);
3203
+ }
3204
+ } catch (e) {
3205
+ this.sdk.log.warn("web push refresh failed", e);
3206
+ }
3207
+ }
3208
+ /** Lấy/tạo subscription với khoá hiện hành rồi gửi lên nền tảng */
3209
+ async register(reg) {
3210
+ var _a, _b;
3211
+ const key = (_b = (_a = this.vapid) != null ? _a : this.sdk.config.webPush.vapidPublicKey) != null ? _b : "";
3212
+ let sub = await reg.pushManager.getSubscription();
3213
+ if (sub && !sameKey(sub, key)) {
3214
+ await sub.unsubscribe().catch(() => false);
3215
+ sub = null;
3216
+ }
3217
+ if (!sub) sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64ToBytes(key) });
3218
+ const token = JSON.stringify(sub.toJSON());
3219
+ const r = await this.sdk.http.pushToken({ deviceId: this.sdk.getDeviceId(), provider: "webpush", token, optIn: true });
3220
+ await this.configureWorker(reg);
3221
+ if (!r.ok) return this.fail("push_token", `push-token failed ${r.status}`);
3222
+ this.sdk.storage.setJSON("push", { endpoint: sub.endpoint, key, token });
3223
+ return true;
3224
+ }
3225
+ /** Service worker không có localStorage: SDK gửi cấu hình để nó ghi vào IndexedDB và tự báo event */
3226
+ async configureWorker(reg) {
3227
+ var _a;
3228
+ const w = await activeWorker(reg);
3229
+ w == null ? void 0 : w.postMessage({ type: "bzc-config", sdkKey: this.sdk.config.sdkKey, apiHost: this.sdk.config.apiHost, deviceId: this.sdk.getDeviceId(), vapidPublicKey: (_a = this.vapid) != null ? _a : this.sdk.config.webPush.vapidPublicKey });
3230
+ }
3231
+ };
3232
+ function activeWorker(reg, ms = SW_ACTIVATE_MS) {
3233
+ if (reg.active) return Promise.resolve(reg.active);
3234
+ const w = reg.installing || reg.waiting;
3235
+ if (!w) return Promise.resolve(null);
3236
+ return new Promise((done) => {
3237
+ const t = setTimeout(() => {
3238
+ var _a;
3239
+ w.removeEventListener("statechange", on);
3240
+ done((_a = reg.active) != null ? _a : null);
3241
+ }, ms);
3242
+ const on = () => {
3243
+ var _a;
3244
+ if (w.state === "activated") {
3245
+ clearTimeout(t);
3246
+ w.removeEventListener("statechange", on);
3247
+ done(w);
3248
+ } else if (w.state === "redundant") {
3249
+ clearTimeout(t);
3250
+ w.removeEventListener("statechange", on);
3251
+ done((_a = reg.active) != null ? _a : null);
3252
+ }
3253
+ };
3254
+ w.addEventListener("statechange", on);
3255
+ });
3256
+ }
3257
+ function askSoft() {
3258
+ return new Promise((done) => {
3259
+ const host = document.createElement("div");
3260
+ const root = host.attachShadow({ mode: "open" });
3261
+ root.innerHTML = '<style>.b{position:fixed;inset:0;background:rgba(0,0,0,.45);display:flex;align-items:center;justify-content:center;z-index:2147483647;font:14px system-ui}.c{background:#fff;color:#222;border-radius:12px;padding:20px;max-width:340px;width:calc(100% - 32px)}.a{display:flex;gap:8px;justify-content:flex-end;margin-top:16px}button{border:0;border-radius:8px;padding:8px 14px;cursor:pointer}.y{background:#2563eb;color:#fff}</style><div class="b" role="dialog" aria-modal="true"><div class="c"><p>B\u1EADt th\xF4ng b\xE1o \u0111\u1EC3 nh\u1EADn \u01B0u \u0111\xE3i v\xE0 c\u1EADp nh\u1EADt m\u1EDBi nh\u1EA5t?</p><div class="a"><button class="n">\u0110\u1EC3 sau</button><button class="y">B\u1EADt th\xF4ng b\xE1o</button></div></div></div>';
3262
+ const end = (v) => {
3263
+ host.remove();
3264
+ done(v);
3265
+ };
3266
+ root.querySelector(".y").addEventListener("click", () => end(true));
3267
+ root.querySelector(".n").addEventListener("click", () => end(false));
3268
+ document.body.appendChild(host);
3269
+ });
3270
+ }
3271
+
3272
+ // src/modules/autotrack.ts
3273
+ function startAutoTrack(sdk) {
3274
+ if (!sdk.config.autoPageView) return;
3275
+ const view = () => {
3276
+ if (!sdk.markPage(location.href)) return;
3277
+ sdk.emit("page_view", { page_title: document.title || void 0 });
3278
+ };
3279
+ view();
3280
+ sdk.onConsentGranted(() => sdk.emit("page_view", { page_title: document.title || void 0 }));
3281
+ const wrap = (m) => {
3282
+ const orig = history[m];
3283
+ history[m] = function(...a) {
3284
+ const r = orig.apply(this, a);
3285
+ setTimeout(view, 0);
3286
+ return r;
3287
+ };
3288
+ };
3289
+ wrap("pushState");
3290
+ wrap("replaceState");
3291
+ window.addEventListener("popstate", () => setTimeout(view, 0));
3292
+ }
3293
+
3294
+ // src/setup.ts
3295
+ function assembleSdk(config, inApp) {
3296
+ const sdk = new CdpSdk();
3297
+ sdk.onInit.push(() => {
3298
+ sdk.webPush = new WebPush(sdk);
3299
+ startAutoTrack(sdk);
3300
+ inApp(sdk);
3301
+ if (sdk.config.webPush.enabled) void sdk.webPush.refresh();
3302
+ });
3303
+ if (config) void sdk.init(config);
3304
+ return sdk;
3305
+ }
3306
+
3307
+ // src/generated/event-names.ts
3308
+ var CATALOG_VERSION = "0.2";
3309
+
3310
+ // src/client.ts
3311
+ var KEY = "__bizcdpShared";
3312
+ var DROPPED = { status: "dropped", reason: "server" };
3313
+ var EMPTY_STATE = Object.freeze({ ready: false, identified: false });
3314
+ function serverClient() {
3315
+ const done = (v) => Promise.resolve(v);
3316
+ return {
3317
+ sdk: null,
3318
+ state: EMPTY_STATE,
3319
+ subscribe: () => () => void 0,
3320
+ track: () => done(DROPPED),
3321
+ page: () => done(DROPPED),
3322
+ identify: () => done(void 0),
3323
+ logout: () => done(void 0),
3324
+ setAttribute: () => done(DROPPED),
3325
+ setAttributes: () => done(DROPPED),
3326
+ setConsent: () => done(DROPPED),
3327
+ flush: () => done(void 0),
3328
+ reset: () => done(void 0),
3329
+ getCid: () => void 0,
3330
+ getDeviceId: () => void 0,
3331
+ on: () => () => void 0,
3332
+ refreshCampaigns: () => done(void 0),
3333
+ webPush: { subscribe: () => done(false), unsubscribe: () => done(false), getState: () => done(void 0) }
3334
+ };
3335
+ }
3336
+ var safe = (f) => {
3337
+ try {
3338
+ return Promise.resolve(f());
3339
+ } catch (e) {
3340
+ return Promise.reject(e);
3341
+ }
3342
+ };
3343
+ function browserClient(sdk) {
3344
+ let state = EMPTY_STATE;
3345
+ let ready = false;
3346
+ const listeners = /* @__PURE__ */ new Set();
3347
+ const refresh = () => {
3348
+ const on = sdk.isReady;
3349
+ const next = { ready, cid: on ? sdk.getCid() : void 0, deviceId: on ? sdk.getDeviceId() || void 0 : void 0, identified: on ? sdk.isIdentified() : false };
3350
+ if (next.ready === state.ready && next.cid === state.cid && next.deviceId === state.deviceId && next.identified === state.identified) return;
3351
+ state = next;
3352
+ listeners.forEach((l) => {
3353
+ try {
3354
+ l();
3355
+ } catch {
3356
+ }
3357
+ });
3358
+ };
3359
+ sdk.on("ready", () => {
3360
+ ready = true;
3361
+ refresh();
3362
+ });
3363
+ ["identified", "cidChanged"].forEach((e) => sdk.on(e, refresh));
3364
+ refresh();
3365
+ return {
3366
+ sdk,
3367
+ get state() {
3368
+ return state;
3369
+ },
3370
+ subscribe(l) {
3371
+ listeners.add(l);
3372
+ return () => {
3373
+ listeners.delete(l);
3374
+ };
3375
+ },
3376
+ track: (n, p) => safe(() => sdk.track(n, p)),
3377
+ page: (p) => safe(() => sdk.page(p)),
3378
+ identify: (ids) => safe(() => sdk.identify(ids)).then((r) => {
3379
+ refresh();
3380
+ return r;
3381
+ }),
3382
+ logout: () => safe(() => sdk.logout()).then(() => refresh()),
3383
+ setAttribute: (n, v, m) => safe(() => sdk.setAttribute(n, v, m)),
3384
+ setAttributes: (a, m) => safe(() => sdk.setAttributes(a, m)),
3385
+ setConsent: (c, v, o) => safe(() => sdk.setConsent(c, v, o)),
3386
+ flush: () => safe(() => sdk.flush()),
3387
+ reset: () => safe(() => sdk.reset()).then(() => refresh()),
3388
+ getCid: () => sdk.getCid(),
3389
+ getDeviceId: () => sdk.getDeviceId() || void 0,
3390
+ on: (e, cb) => sdk.on(e, cb),
3391
+ refreshCampaigns: () => safe(() => {
3392
+ var _a;
3393
+ return (_a = sdk.campaigns) == null ? void 0 : _a.load();
3394
+ }),
3395
+ webPush: {
3396
+ subscribe: (o) => safe(() => {
3397
+ var _a, _b;
3398
+ return (_b = (_a = sdk.webPush) == null ? void 0 : _a.subscribe(o)) != null ? _b : false;
3399
+ }),
3400
+ unsubscribe: () => safe(() => {
3401
+ var _a, _b;
3402
+ return (_b = (_a = sdk.webPush) == null ? void 0 : _a.unsubscribe()) != null ? _b : false;
3403
+ }),
3404
+ getState: () => safe(() => {
3405
+ var _a;
3406
+ return (_a = sdk.webPush) == null ? void 0 : _a.state();
3407
+ })
3408
+ }
3409
+ };
3410
+ }
3411
+ function createClient(config) {
3412
+ var _a, _b;
3413
+ if (typeof window === "undefined" || typeof document === "undefined") return serverClient();
3414
+ const holder = window;
3415
+ const sdkKey = ((_b = (_a = config == null ? void 0 : config.sdkKey) != null ? _a : config == null ? void 0 : config.apiKey) != null ? _b : "").trim();
3416
+ const cur = holder[KEY];
3417
+ if (cur) {
3418
+ if (sdkKey && cur.sdkKey !== sdkKey) console.warn("[bizcdp] createClient: SDK \u0111\xE3 kh\u1EDFi t\u1EA1o v\u1EDBi kh\xF3a kh\xE1c, d\xF9ng l\u1EA1i SDK \u0111ang ch\u1EA1y");
3419
+ return cur.client;
3420
+ }
3421
+ const sdk = createSdk(config);
3422
+ const client = browserClient(sdk);
3423
+ holder[KEY] = { sdk, client, sdkKey };
3424
+ return client;
3425
+ }
3426
+ function getClient() {
3427
+ var _a, _b;
3428
+ if (typeof window === "undefined") return null;
3429
+ return (_b = (_a = window[KEY]) == null ? void 0 : _a.client) != null ? _b : null;
3430
+ }
3431
+
3432
+ // src/index.ts
3433
+ function createSdk(config) {
3434
+ return assembleSdk(config, (sdk) => {
3435
+ sdk.campaigns = new CampaignEngine(sdk);
3436
+ sdk.campaigns.start();
3437
+ });
3438
+ }
3439
+ export {
3440
+ CATALOG_VERSION,
3441
+ CampaignEngine,
3442
+ CdpSdk,
3443
+ WebPush,
3444
+ createClient,
3445
+ createSdk,
3446
+ getClient
3447
+ };