UNPKG

@bzbs/react-providers

Version:

A collection of React Context Provider for Buzzebees apps

1,616 lines (1,604 loc) 135 kB
"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __defProps = Object.defineProperties; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropDescs = Object.getOwnPropertyDescriptors; var __getOwnPropNames = Object.getOwnPropertyNames; var __getOwnPropSymbols = Object.getOwnPropertySymbols; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __propIsEnum = Object.prototype.propertyIsEnumerable; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __spreadValues = (a, b) => { for (var prop in b || (b = {})) if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); if (__getOwnPropSymbols) for (var prop of __getOwnPropSymbols(b)) { if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); } return a; }; var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // context.ts var context_exports = {}; __export(context_exports, { AddressProvider: () => AddressProvider, AlertContext: () => AlertContext, AlertProvider: () => AlertProvider, AnalyticsContext: () => AnalyticsContext, AnalyticsProvider: () => AnalyticsProvider, AppLocaleProvider: () => AppLocaleProvider, AuthContext: () => AuthContext, AuthProvider: () => AuthProvider, BuzzebeesServiceContext: () => BuzzebeesServiceContext, BuzzebeesServiceProvider: () => BuzzebeesServiceProvider, CampaignContext: () => CampaignContext, CampaignDetailContext: () => CampaignDetailContext, CampaignDetailProvider: () => CampaignDetailProvider, CampaignProvider: () => CampaignProvider, CartProvider: () => CartProvider, CategoriesProvider: () => CategoriesProvider, ConfirmContext: () => ConfirmContext, ConfirmProvider: () => ConfirmProvider, ConsentContext: () => ConsentContext, ConsentProvider: () => ConsentProvider, CouponProvider: () => CouponProvider, DashboardProvider: () => DashboardProvider, DefaultMainAppProvider: () => DefaultMainAppProvider, EN: () => EN, LoadingProvider: () => LoadingProvider, LocaleContext: () => LocaleContext, MaintenanceContext: () => MaintenanceContext, MaintenanceProvider: () => MaintenanceProvider, NotificationContext: () => NotificationContext, NotificationProvider: () => NotificationProvider, PointLogProvider: () => PointLogProvider, PopupProvider: () => PopupProvider, PurchaseProvider: () => PurchaseProvider, RegisterProvider: () => RegisterProvider, TH: () => TH, UserContext: () => UserContext, UserProvider: () => UserProvider, ZipCodeProvider: () => ZipCodeProvider, addBlake2OtpSignatureInterceptor: () => addBlake2OtpSignatureInterceptor, addDefaultHeaderInterceptor: () => addDefaultHeaderInterceptor, analytics: () => analytics, avatarUrl: () => avatarUrl, campaignInterfaceType: () => campaignInterfaceType, campaignPointType: () => campaignPointType, campaignType: () => campaignType, createCartUrl: () => createCartUrl, createInterfaceToken: () => createInterfaceToken, eventEmitter: () => eventEmitter, fetchImage: () => fetchImage, findBestLocaleFromString: () => findBestLocaleFromString, generateBlake2bSignatureHex: () => generateBlake2bSignatureHex, generateShortLivedId: () => generateShortLivedId, getOtpSignatureHeaders: () => getOtpSignatureHeaders, getPurchaseItemStatus: () => getPurchaseItemStatus, initializeAnalytics: () => initializeAnalytics, interfaceWebsite: () => createInterfaceWebsiteUrl, isValidEmail: () => isValidEmail, largeImage: () => largeImage, localeToLCIDMap: () => localeToLCIDMap, trackCommonEvents: () => trackCommonEvents, useAddressContext: () => useAddressContext, useAlertContext: () => useAlertContext, useAnalytics: () => useAnalytics, useAnalyticsContext: () => useAnalyticsContext, useAnalyticsState: () => useAnalyticsState, useAppLocaleContext: () => useAppLocaleContext, useAuthContext: () => useAuthContext, useBuzzebeesServiceContext: () => useBuzzebeesServiceContext, useCampaignContext: () => useCampaignContext, useCampaignDetailContext: () => useCampaignDetailContext, useCartContext: () => useCartContext, useCategoriesContext: () => useCategoriesContext, useConfirmContext: () => useConfirmContext, useConsentContext: () => useConsentContext, useCouponContext: () => useCouponContext, useDashboardContext: () => useDashboardContext, useLoading: () => useLoading, useLoadingContext: () => useLoadingContext, useMaintenanceContext: () => useMaintenanceContext, useNotificationContext: () => useNotificationContext, usePageTracking: () => usePageTracking, usePointLogContext: () => usePointLogContext, usePurchaseContext: () => usePurchaseContext, useRegisterContext: () => useRegisterContext, useUserContext: () => useUserContext, useZipCodeContext: () => useZipCodeContext, withPageTracking: () => withPageTracking }); module.exports = __toCommonJS(context_exports); // src/providers/auth_provider.tsx var import_react4 = __toESM(require("react")); // src/providers/buzzebees_service_provider.tsx var import_react = __toESM(require("react")); var BuzzebeesServiceContext = (0, import_react.createContext)({ appId: "", appName: "", bzbsService: {}, urls: { webCallback: "", cart: "" } }); function useBuzzebeesServiceContext() { return (0, import_react.useContext)(BuzzebeesServiceContext); } function BuzzebeesServiceProvider({ appId, appName, bzbsService, urls, children }) { return /* @__PURE__ */ import_react.default.createElement( BuzzebeesServiceContext.Provider, { value: { appId, appName, urls, bzbsService } }, children ); } // src/providers/locale_provider.tsx var import_react2 = __toESM(require("react")); // src/utils/locale.ts var localeToLCIDMap = { "ar-SA": 1025, "bg-BG": 1026, "ca-ES": 1027, "zh-TW": 1028, "cs-CZ": 1029, "da-DK": 1030, "de-DE": 1031, "el-GR": 1032, "en-US": 1033, "es-ES": 1034, "fi-FI": 1035, "fr-FR": 1036, "he-IL": 1037, "hu-HU": 1038, "is-IS": 1039, "it-IT": 1040, "ja-JP": 1041, "ko-KR": 1042, "nl-NL": 1043, "nb-NO": 1044, "pl-PL": 1045, "pt-BR": 1046, "rm-CH": 1047, "ro-RO": 1048, "ru-RU": 1049, "hr-HR": 1050, "sk-SK": 1051, "sq-AL": 1052, "sv-SE": 1053, "th-TH": 1054, "tr-TR": 1055, "ur-PK": 1056, "id-ID": 1057, "uk-UA": 1058, "be-BY": 1059, "sl-SI": 1060, "et-EE": 1061, "lv-LV": 1062, "lt-LT": 1063, "tg-Cyrl-TJ": 1064, "fa-IR": 1065, "vi-VN": 1066, "hy-AM": 1067, "az-Latn-AZ": 1068, "eu-ES": 1069, "wen-DE": 1070, "mk-MK": 1071, "st-ZA": 1072, "ts-ZA": 1073, "tn-ZA": 1074, "ven-ZA": 1075, "xh-ZA": 1076, "zu-ZA": 1077, "af-ZA": 1078, "ka-GE": 1079, "fo-FO": 1080, "hi-IN": 1081, "mt-MT": 1082, "se-NO": 1083, "gd-GB": 1084, yi: 1085, "ms-MY": 1086, "kk-KZ": 1087, "ky-KG": 1088, "sw-KE": 1089, "tk-TM": 1090, "uz-Latn-UZ": 1091, "tt-RU": 1092, "bn-IN": 1093, "pa-IN": 1094, "gu-IN": 1095, "or-IN": 1096, "ta-IN": 1097, "te-IN": 1098, "kn-IN": 1099, "ml-IN": 1100, "as-IN": 1101, "mr-IN": 1102, "sa-IN": 1103, "mn-MN": 1104, "bo-CN": 1105, "cy-GB": 1106, "km-KH": 1107, "lo-LA": 1108, "my-MM": 1109, "gl-ES": 1110, "kok-IN": 1111, mni: 1112, "sd-IN": 1113, "syr-SY": 1114, "si-LK": 1115, "chr-US": 1116, "iu-Cans-CA": 1117, "am-ET": 1118, tmz: 1119, "ks-Arab-IN": 1120, "ne-NP": 1121, "fy-NL": 1122, "ps-AF": 1123, "fil-PH": 1124, "dv-MV": 1125, "bin-NG": 1126, "fuv-NG": 1127, "ha-Latn-NG": 1128, "ibb-NG": 1129, "yo-NG": 1130, "quz-BO": 1131, "nso-ZA": 1132, "ig-NG": 1136, "kr-NG": 1137, "gaz-ET": 1138, "ti-ER": 1139, "gn-PY": 1140, "haw-US": 1141, la: 1142, "so-SO": 1143, "ii-CN": 1144, "pap-AN": 1145, "ug-Arab-CN": 1152, "mi-NZ": 1153, "ar-IQ": 2049, "zh-CN": 2052, "de-CH": 2055, "en-GB": 2057, "es-MX": 2058, "fr-BE": 2060, "it-CH": 2064, "nl-BE": 2067, "nn-NO": 2068, "pt-PT": 2070, "ro-MD": 2072, "ru-MD": 2073, "sr-Latn-CS": 2074, "sv-FI": 2077, "ur-IN": 2080, "az-Cyrl-AZ": 2092, "ga-IE": 2108, "ms-BN": 2110, "uz-Cyrl-UZ": 2115, "bn-BD": 2117, "pa-PK": 2118, "mn-Mong-CN": 2128, "bo-BT": 2129, "sd-PK": 2137, "tzm-Latn-DZ": 2143, "ks-Deva-IN": 2144, "ne-IN": 2145, "quz-EC": 2155, "ti-ET": 2163, "ar-EG": 3073, "zh-HK": 3076, "de-AT": 3079, "en-AU": 3081, "fr-CA": 3084, "sr-Cyrl-CS": 3098, "ar-LY": 4097, "zh-SG": 4100, "de-LU": 4103, "en-CA": 4105, "fr-CH": 4108, "hr-BA": 4122, "ar-DZ": 5121, "zh-MO": 5124, "de-LI": 5127, "en-NZ": 5129, "fr-LU": 5132, "bs-Latn-BA": 5146, "ar-MO": 6145, "fr-MC": 6156, "ar-TN": 7169, "ar-OM": 8193, "ar-YE": 9217, "en-BZ": 10249, "es-PE": 10250, "fr-SN": 10252, "ar-JO": 11265, "fr-CM": 11276, "en-ID": 14345, "es-CL": 13322, "en-HK": 15369, "fr-MA": 14348, "en-MY": 17417, "es-SV": 17418, "es-NI": 19466, "es-PR": 20490, "es-US": 21514, "fr-015": 58380 }; function findBestLocaleFromString(value) { if (localeToLCIDMap[value]) { return { locale: value, localeId: localeToLCIDMap[value] }; } const partialMatch = Object.keys(localeToLCIDMap).find((key) => key.startsWith(value.split("-")[0])); if (partialMatch) { return { locale: partialMatch, localeId: localeToLCIDMap[partialMatch] }; } throw new Error(`Locale '${value}' is not supported.`); } // src/providers/locale_provider.tsx var EN = { locale: "en", localeId: 1033 }; var TH = { locale: "th", localeId: 1054 }; var LocaleContext = (0, import_react2.createContext)({ appLocale: EN, locale: "en", localeId: 1033, setAppLocale: () => { } }); var useAppLocaleContext = () => { return (0, import_react2.useContext)(LocaleContext); }; var AppLocaleProvider = ({ initLocale, children }) => { const [locale, setLocale] = (0, import_react2.useState)(initLocale); const setAppLocale = (locale2) => { if (typeof locale2 === "string") { setLocale(findBestLocaleFromString(locale2)); } else { setLocale(locale2); } }; return /* @__PURE__ */ import_react2.default.createElement( LocaleContext.Provider, { value: { appLocale: locale, locale: locale.locale, localeId: locale.localeId, setAppLocale } }, children ); }; // src/providers/analytics_provider.tsx var import_matomo_tracker_react_native = __toESM(require("matomo-tracker-react-native")); var import_react3 = __toESM(require("react")); var AnalyticsContext = (0, import_react3.createContext)({ isInitialized: false, isEnabled: true, actions: { setEnabled: () => { }, setPresetUserInfo: () => { }, clearPresetUserInfo: () => { }, trackAppStart: () => __async(null, null, function* () { }), trackEvent: () => __async(null, null, function* () { }), trackScreenView: () => __async(null, null, function* () { }), trackAction: () => __async(null, null, function* () { }), trackSiteSearch: () => __async(null, null, function* () { }), trackLink: () => __async(null, null, function* () { }), trackDownload: () => __async(null, null, function* () { }), setUserId: () => { }, setCustomDimension: () => { }, reset: () => { } } }); function useAnalyticsContext() { return (0, import_react3.useContext)(AnalyticsContext); } function AnalyticsInner({ children, userId, enableLogging }) { const { trackEvent, trackScreenView, trackAppStart, trackAction, trackSiteSearch, trackLink, trackDownload } = (0, import_matomo_tracker_react_native.useMatomo)(); const [isEnabled, setIsEnabled] = (0, import_react3.useState)(true); const [userIdState, setUserIdState] = (0, import_react3.useState)(userId); const [presetUserInfo, setPresetUserInfoState] = (0, import_react3.useState)(void 0); const [log] = (0, import_react3.useState)(enableLogging || false); const handleSetEnabled = (enabled) => { setIsEnabled(enabled); }; const handleSetPresetUserInfo = (userInfo) => { setPresetUserInfoState(userInfo); }; const handleClearPresetUserInfo = () => { setPresetUserInfoState(void 0); }; const handleTrackAppStart = (userInfo) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track App Start skipped - not initialized or disabled"); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), userInfo); yield trackAppStart({ userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: App start tracked successfully", { userInfo: mergedUserInfo }); } } catch (error) { console.error("Analytics: Failed to track app start", error); } }); const handleTrackEvent = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Event skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackEvent({ category: params.category || "User Action", action: params.action, name: params.name, value: params.value, campaign: params.campaign, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Event tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track event", error, params); } }); const handleTrackScreenView = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Screen View skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackScreenView({ name: params.name, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Screen view tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track screen view", error, params); } }); const handleTrackAction = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Action skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackAction({ name: params.name, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Action tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track action", error, params); } }); const handleTrackSiteSearch = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Site Search skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackSiteSearch({ keyword: params.keyword, category: params.category, count: params.count, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Site search tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track site search", error, params); } }); const handleTrackLink = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Link skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackLink({ link: params.link, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Link tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track link", error, params); } }); const handleTrackDownload = (params) => __async(null, null, function* () { if (!userIdState || !isEnabled) { if (log) { console.debug("Analytics: Track Download skipped - not initialized or disabled", params); } return; } try { const mergedUserInfo = __spreadValues(__spreadValues({}, presetUserInfo), params.userInfo); yield trackDownload({ download: params.download, userInfo: Object.keys(mergedUserInfo).length > 0 ? mergedUserInfo : void 0 }); if (log) { console.debug("Analytics: Download tracked successfully", params); } } catch (error) { console.error("Analytics: Failed to track download", error, params); } }); const handleSetUserId = (userId2) => { setUserIdState(userId2 || void 0); if (userId2) { setPresetUserInfoState((prev) => __spreadProps(__spreadValues({}, prev), { uid: userId2 })); } else { setPresetUserInfoState((prev) => { if (prev == null ? void 0 : prev.uid) { const updatedUserInfo = __spreadValues({}, prev); delete updatedUserInfo.uid; return Object.keys(updatedUserInfo).length > 0 ? updatedUserInfo : void 0; } return prev; }); } if (log) { console.debug("Analytics: User ID updated in preset userInfo", userId2); } }; const handleSetCustomDimension = (id, value) => { if (!presetUserInfo) { setPresetUserInfoState({ [`dimension${id}`]: value }); } else { setPresetUserInfoState(__spreadProps(__spreadValues({}, presetUserInfo), { [`dimension${id}`]: value })); } if (log) { console.debug("Analytics: Custom dimension set in preset userInfo", { id, value }); } }; const reset = () => { setUserIdState(void 0); setPresetUserInfoState(void 0); setIsEnabled(true); console.debug("Analytics: Provider reset successfully"); }; const contextValue = { isInitialized: true, // Always true since initialization is handled by MatomoProvider isEnabled, userId: userIdState, presetUserInfo, actions: { setEnabled: handleSetEnabled, setPresetUserInfo: handleSetPresetUserInfo, clearPresetUserInfo: handleClearPresetUserInfo, trackAppStart: handleTrackAppStart, trackEvent: handleTrackEvent, trackScreenView: handleTrackScreenView, trackAction: handleTrackAction, trackSiteSearch: handleTrackSiteSearch, trackLink: handleTrackLink, trackDownload: handleTrackDownload, setUserId: handleSetUserId, setCustomDimension: handleSetCustomDimension, reset } }; return /* @__PURE__ */ import_react3.default.createElement(AnalyticsContext.Provider, { value: contextValue }, children); } function AnalyticsProvider({ children, disabled = false, instance, userId, enableLogging = false }) { if (disabled) { const noOpContextValue = { isInitialized: false, isEnabled: false, actions: { setEnabled: () => { }, setPresetUserInfo: () => { }, clearPresetUserInfo: () => { }, trackAppStart: () => __async(null, null, function* () { }), trackEvent: () => __async(null, null, function* () { }), trackScreenView: () => __async(null, null, function* () { }), trackAction: () => __async(null, null, function* () { }), trackSiteSearch: () => __async(null, null, function* () { }), trackLink: () => __async(null, null, function* () { }), trackDownload: () => __async(null, null, function* () { }), setUserId: () => { }, setCustomDimension: () => { }, reset: () => { } } }; return /* @__PURE__ */ import_react3.default.createElement(AnalyticsContext.Provider, { value: noOpContextValue }, children); } const matomoInstance = instance || new import_matomo_tracker_react_native.default({ urlBase: "https://placeholder.com", siteId: 1, disabled: true // Disabled until properly initialized }); return /* @__PURE__ */ import_react3.default.createElement(import_matomo_tracker_react_native.MatomoProvider, { instance: matomoInstance }, /* @__PURE__ */ import_react3.default.createElement(AnalyticsInner, { userId, enableLogging }, children)); } // src/providers/auth_provider.tsx var AuthContext = (0, import_react4.createContext)({ isInitialized: false, authData: null, versionData: null, isLoading: false, isLoggedIn: false, error: null, token: null, isLoadingToken: false, actions: { init: () => { }, setUUID: () => { }, setAppId: () => { }, setDeviceToken: () => { }, setClientVersion: () => { }, setOs: () => { }, setPlatform: () => { }, setError: () => { }, setLoginResponseHandler: () => { }, clearData: () => { }, loginWithUsernamePassword: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), loginWithGoogle: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), loginWithFacebook: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), loginWithApple: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), loginWithUUID: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), logout: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), forgetPassword: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), resetPassword: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), sendOtp: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), validateOtp: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), confirmOtp: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), resume: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), version: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }) } }); function useAuthContext() { return (0, import_react4.useContext)(AuthContext); } function AuthProvider({ tokenFunctions, children }) { const [versionData, setVersionData] = (0, import_react4.useState)(null); const [isLoading, setIsLoading] = (0, import_react4.useState)(false); const [error, setError] = (0, import_react4.useState)(null); const [isLoggedIn, setIsLoggedIn] = (0, import_react4.useState)(false); const [isLoadingToken, setIsLoadingToken] = (0, import_react4.useState)(false); const [token, setToken] = (0, import_react4.useState)(null); const [isInitialized, setIsInitialized] = (0, import_react4.useState)(false); const [loginResponseHandler, setLoginResponseHandler] = (0, import_react4.useState)(() => { }); const { bzbsService } = useBuzzebeesServiceContext(); const { localeId } = useAppLocaleContext(); const { actions: analyticsActions } = useAnalyticsContext(); const uuid = (0, import_react4.useRef)(""); const appId = (0, import_react4.useRef)(""); const deviceToken = (0, import_react4.useRef)(""); const clientVersion = (0, import_react4.useRef)(""); const os = (0, import_react4.useRef)(""); const platform = (0, import_react4.useRef)(""); const setUUID = (value) => { uuid.current = value; }; const setAppId = (value) => { appId.current = value; }; const setDeviceToken = (value) => { deviceToken.current = value; }; const setClientVersion = (value) => { clientVersion.current = value; }; const setOs = (value) => { os.current = value; }; const setPlatform = (value) => { platform.current = value; }; const init = (uuid2, appId2, deviceToken2) => { setUUID(uuid2); setAppId(appId2); setDeviceToken(deviceToken2); checkLoggedIn(); }; const checkLoggedIn = () => __async(null, null, function* () { try { setIsLoadingToken(true); const savedToken = yield tokenFunctions.getToken(); setIsLoadingToken(false); if (savedToken) { setIsLoggedIn(true); } else { setIsLoggedIn(false); } setToken(savedToken); } catch (error2) { setIsLoggedIn(false); } setIsInitialized(true); }); const clearData = () => { setVersionData(null); setError(null); setIsLoading(false); setIsLoggedIn(false); setToken(null); }; const login = (loginFn) => __async(null, null, function* () { setIsLoading(true); const response = yield loginFn(); setIsLoading(false); if (response.type === "success") { tokenFunctions.setToken(response.model.token); setToken(response.model.token); setIsLoggedIn(true); setError(null); loginResponseHandler(response.model); analyticsActions.trackEvent({ action: "on_click", name: "login_success", category: "login" }); } else { setError(response); } return response; }); const loginWithUsernamePassword = (username, password) => __async(null, null, function* () { const response = yield login( () => bzbsService.authApi.usernamePasswordLogin({ username, password, appId: appId.current, uuid: uuid.current, deviceToken: deviceToken.current, clientVersion: clientVersion.current, os: os.current, platform: platform.current, deviceLocale: localeId.toString(), deviceNotificationEnabled: true }) ); return response; }); const loginWithGoogle = (token2) => __async(null, null, function* () { const response = yield login( () => bzbsService.authApi.googleLogin({ idToken: token2, appId: appId.current, uuid: uuid.current, deviceToken: deviceToken.current, clientVersion: clientVersion.current, os: os.current, platform: platform.current, deviceLocale: localeId.toString(), deviceNotificationEnabled: true }) ); return response; }); const loginWithFacebook = (token2) => __async(null, null, function* () { const response = yield login( () => bzbsService.authApi.facebookLogin({ accessToken: token2, appId: appId.current, uuid: uuid.current, deviceToken: deviceToken.current, clientVersion: clientVersion.current, os: os.current, platform: platform.current, deviceLocale: localeId.toString(), deviceNotificationEnabled: true }) ); return response; }); const loginWithApple = (token2, refreshToken) => __async(null, null, function* () { const response = yield login( () => bzbsService.authApi.appleLogin({ idToken: token2, refreshToken, appId: appId.current, uuid: uuid.current, deviceToken: deviceToken.current, clientVersion: clientVersion.current, os: os.current, platform: platform.current, deviceLocale: localeId.toString(), deviceNotificationEnabled: true }) ); return response; }); const loginWithUUID = () => __async(null, null, function* () { const response = yield login( () => bzbsService.authApi.deviceLogin({ appId: appId.current, uuid: uuid.current, deviceToken: deviceToken.current, clientVersion: clientVersion.current, os: os.current, platform: platform.current, deviceLocale: localeId.toString(), deviceNotificationEnabled: true }) ); return response; }); const logout = () => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.logout({ uuid: uuid.current }); setIsLoading(false); tokenFunctions.removeToken(); setToken(null); setIsLoggedIn(false); setError(null); return response; }); const forgetPassword = (contact, type) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.forgetPassword({ contact, type }); setIsLoading(false); return response; }); const resetPassword = (contact, otp, refCode, newPassword) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.resetPassword({ contact, refCode, otp, newPassword }); setIsLoading(false); return response; }); const sendOtp = (contact) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.otp({ uuid: uuid.current, appId: appId.current, contactNumber: contact }); setIsLoading(false); return response; }); const validateOtp = (contact, otp, refCode, channel) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.validateOtp({ appId: appId.current, otp, refCode, contactNumber: contact, use: false, channel }); setIsLoading(false); return response; }); const confirmOtp = (contact, otp, refCode) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.confirmOtp({ otp, refCode, contactNumber: contact }); setIsLoading(false); return response; }); const resume = (clientVersion2) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.resume({ uuid: uuid.current, appId: appId.current, clientVersion: clientVersion2, deviceToken: deviceToken.current }); setIsLoading(false); return response; }); const version = (clientVersion2) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.authApi.version(clientVersion2); if (response.type === "success") { setVersionData(response.model); } setIsLoading(false); return response; }); return /* @__PURE__ */ import_react4.default.createElement( AuthContext.Provider, { value: { isInitialized, versionData, isLoading, isLoggedIn, token, isLoadingToken, error, actions: { init, setUUID, setAppId, setDeviceToken, setClientVersion, setOs, setPlatform, setError, setLoginResponseHandler, clearData, loginWithUsernamePassword, loginWithGoogle, loginWithFacebook, loginWithApple, loginWithUUID, logout, forgetPassword, resetPassword, sendOtp, validateOtp, confirmOtp, resume, version } } }, children ); } // src/providers/user_provider.tsx var import_react5 = __toESM(require("react")); // src/service/bzbs_service.ts var blake = __toESM(require("blakejs")); var import_emittery = __toESM(require("emittery")); var import_uuid = require("uuid"); var eventEmitter = new import_emittery.default(); function defaultCorelationIdGenerator() { return (0, import_uuid.v7)(); } function isJWT(token) { return typeof token === "string" && token.split(".").length === 3; } function addDefaultHeaderInterceptor(axiosInstance, appId, subscriptionKey, tokenFunctions, apiVersion, corelationIdGenerator = defaultCorelationIdGenerator) { axiosInstance.interceptors.request.use( (config) => __async(null, null, function* () { config.headers.set("App-Id", appId); if (subscriptionKey) { config.headers.set("Ocp-Apim-Subscription-Key", subscriptionKey); } if (apiVersion) { config.headers.set("api-version", apiVersion); } config.headers.set("X-Corelation-Id", corelationIdGenerator()); const token = yield tokenFunctions.getToken(); if (token) { if (isJWT(token)) { config.headers.set("Authorization", `Bearer ${token}`); } else { config.headers.set("Authorization", `token ${token}`); } } return config; }), (error) => { return Promise.reject(error); } ); axiosInstance.interceptors.response.use( (response) => { const responseData = response.data; const buzzebeesObj = responseData.buzzebees; if (buzzebeesObj) { const points = buzzebeesObj.points; const badges = buzzebeesObj.badges; if (typeof points === "number") { eventEmitter.emit("get_points", buzzebeesObj); } if (badges) { eventEmitter.emit("get_badges", badges); } } if (responseData.error) { const id = responseData.error.id; const code = responseData.error.code; if (code === 409 && (id === 1905 || id === 2076)) { eventEmitter.emit("session_expired", responseData.error); } } return response; }, (error) => { return Promise.reject(error); } ); } function generateShortLivedId() { return Math.random().toString(36).substring(2, 15); } function avatarUrl(baseUrl, appId, userId, token) { const url = `${baseUrl}/profile/${userId}/picture?timestamp=${Date.now()}&type=large${token === null ? "" : `&token=${token}&device_app_id=${appId}`}`; console.log(url); return url; } function largeImage(url) { if (!url) return ""; const result = url.replace("?", "-large?"); return result; } function fetchImage(axiosClient, imageUrl) { return __async(this, null, function* () { try { const response = yield axiosClient.get(imageUrl, { responseType: "blob" }); return response.data; } catch (error) { console.error("Error fetching image:", error); } }); } function createInterfaceWebsiteUrl(url, token, returnUrl = "", params) { if (token) { params = __spreadValues({ token: createInterfaceToken(token), return_url: returnUrl }, params); } const searchParams = new URLSearchParams(params).toString(); const result = url.includes("?") ? `${url}&${searchParams}` : `${url}?${searchParams}`; return result; } function createInterfaceToken(token) { if (token.length <= 5) { return token; } const firstChar = token.substring(0, 1); const last5Chars = token.substring(token.length - 5); const remainingChars = token.substring(1, token.length - 5); return firstChar === "." ? `${last5Chars}${remainingChars}` : token; } function createCartUrl(cartUrl, appName, accessKey, params) { const newUrl = cartUrl.endsWith("/") ? `${cartUrl}landing/${appName}` : `${cartUrl}/landing/${appName}`; const newParams = __spreadValues({ access_key: accessKey, appname_config: appName }, params); const searchParams = new URLSearchParams(newParams).toString(); return searchParams ? `${newUrl}?${searchParams}` : newUrl; } function generateBlake2bSignatureHex(data, key, encoder) { const keyBytes = encoder.encode(key); return blake.blake2bHex(data, keyBytes, 32); } function getOtpSignatureHeaders({ appId, contactNumber, channel, encoder, now = /* @__PURE__ */ new Date() }) { const dateTime = now.toISOString().split(".")[0] + "Z"; const timeStamp = Math.floor(now.getTime() / 1e3); const data = `${appId}|${contactNumber}|${channel}|${dateTime}`; const signature = generateBlake2bSignatureHex(data, appId, encoder); return { "OTP-Signature": signature, Timestamp: timeStamp }; } function addBlake2OtpSignatureInterceptor(axiosInstance, paths, encoder, getCurrentDateTime = () => /* @__PURE__ */ new Date()) { axiosInstance.interceptors.request.use((config) => { if (paths.some((path) => config.url && config.url.includes(path))) { const getParam = (key) => { if (config.params && config.params[key]) return config.params[key]; if (config.data && typeof config.data === "object" && config.data[key]) return config.data[key]; return void 0; }; const appId = getParam("app_id"); const contactNumber = getParam("contact_number"); const channel = getParam("channel"); if (appId && contactNumber && channel) { const now = getCurrentDateTime(); const headers = getOtpSignatureHeaders({ appId, contactNumber, channel, now, encoder }); config.headers.set("OTP-Signature", headers["OTP-Signature"]); config.headers.set("Timestamp", headers["Timestamp"]); } } return config; }); } // src/providers/user_provider.tsx var UserContext = (0, import_react5.createContext)({ user: null, points: 0, expiringPoints: [], recentPoints: 0, recentBadge: null, recentTrace: null, cartCount: 0, isLoading: false, error: null, actions: { fetchUser: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), fetchPoint: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), fetchExpiringPoints: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), fetchCartCount: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), editUser: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), changePassword: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), changeContactNumber: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), changeAvatar: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), consumeRecentPoints: () => { }, consumeRecentBadge: () => { }, consumeRecentTrace: () => { }, deleteUser: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), setError: () => { }, clearData: () => { } } }); function useUserContext() { return (0, import_react5.useContext)(UserContext); } function UserProvider({ children }) { const [user, setUser] = (0, import_react5.useState)(null); const [points, setPoints] = (0, import_react5.useState)(0); const [expiringPoints, setExpiringPoints] = (0, import_react5.useState)([]); const [cartCount, setCartCount] = (0, import_react5.useState)(0); const [isLoading, setIsLoading] = (0, import_react5.useState)(false); const [error, setError] = (0, import_react5.useState)(null); const [recentPoints, setRecentPoints] = (0, import_react5.useState)(0); const [recentBadge, setRecentBadge] = (0, import_react5.useState)(null); const [badgeList, setBadgeList] = (0, import_react5.useState)([]); const [recentTrace, setRecentTrace] = (0, import_react5.useState)(null); const [traceList, setTraceList] = (0, import_react5.useState)([]); const { bzbsService } = useBuzzebeesServiceContext(); const auth = useAuthContext(); (0, import_react5.useEffect)(() => { eventEmitter.on("get_points", (buzzebees) => { console.log("get_points", buzzebees); const points2 = buzzebees.points; if (points2) { setRecentPoints(points2); } const traces = buzzebees.traces; if (traces) { if (traces.length > 0) { const first = traces.shift(); if (first) { setRecentTrace(first); } setTraceList(traces); } } }); eventEmitter.on("get_badges", (badges) => { if (badges.length > 0) { const first = badges.shift(); if (first) { setRecentBadge(first); } setBadgeList(badges); } }); eventEmitter.on("session_expired", () => { auth.actions.logout(); }); return () => { console.log("UserProvider cleanup"); eventEmitter.clearListeners(["get_points", "get_badges", "session_expired"]); }; }, []); const fetchUser = () => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.profile(); setIsLoading(false); if (response.type === "success") { setUser(response.model); setError(null); } else { setError(response); } return response; }); const fetchPoint = () => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.points(); setIsLoading(false); if (response.type === "success") { setPoints(response.model.points); setError(null); } else { setError(response); } return response; }); const fetchExpiringPoints = () => __async(null, null, function* () { var _a; setIsLoading(true); const response = yield bzbsService.profileApi.expiringPoints(); setIsLoading(false); if (response.type === "success") { setExpiringPoints((_a = response.model.expiring_points) != null ? _a : []); setError(null); } else { setError(response); } return response; }); const fetchCartCount = () => __async(null, null, function* () { var _a; setIsLoading(true); const response = yield bzbsService.cartApi.cartCount(); setIsLoading(false); if (response.type === "success") { setCartCount((_a = response.model.cart_count) != null ? _a : 0); } else { setError(response); setCartCount(0); } return response; }); const editUser = (data) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.updateProfile(data); setIsLoading(false); if (response.type === "success") { setUser(response.model); setError(null); } else { setError(response); } return response; }); const changePassword = (oldPassword, newPassword) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.changePassword({ current: oldPassword, change: newPassword }); setIsLoading(false); if (response.type === "success") { setIsLoading(false); setError(null); } else { setError(response); } return response; }); const changeContactNumber = (contactNumber, otp, refCode) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.changeContactNumber({ contactNumber, otp, refCode }); setIsLoading(false); if (response.type === "success") { setError(null); } else { setError(response); } return response; }); const changeAvatar = (avatar) => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.updateProfile({ profileImage: avatar }); setIsLoading(false); if (response.type === "success") { setUser(response.model); setError(null); } else { setError(response); } return response; }); const consumeRecentPoints = () => { setRecentPoints(0); }; const consumeRecentBadge = () => { setRecentBadge(null); const next = badgeList.shift(); if (next) { setRecentBadge(next); setBadgeList(badgeList); } }; const consumeRecentTrace = () => { setRecentTrace(null); const next = traceList.shift(); if (next) { setRecentTrace(next); setTraceList(traceList); } }; const deleteUser = () => __async(null, null, function* () { setIsLoading(true); const response = yield bzbsService.profileApi.deactivate(); setIsLoading(false); if (response.type === "success") { clearData(); } else { setError(response); } return response; }); const clearData = () => { setUser(null); setPoints(0); setExpiringPoints([]); setError(null); }; return /* @__PURE__ */ import_react5.default.createElement( UserContext.Provider, { value: { user, points, expiringPoints, recentPoints, recentBadge, recentTrace, cartCount, isLoading, error, actions: { fetchUser, fetchPoint, fetchExpiringPoints, fetchCartCount, editUser, changePassword, changeContactNumber, changeAvatar, consumeRecentPoints, consumeRecentBadge, consumeRecentTrace, deleteUser, setError, clearData } } }, children ); } // src/providers/cart_provider.tsx var import_react6 = __toESM(require("react")); var CartContext = (0, import_react6.createContext)({ count: 0, isLoading: false, error: null, actions: { getCartUrl: () => __async(null, null, function* () { return ""; }), addToCart: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }), getCount: () => __async(null, null, function* () { return { type: "client-error", message: "Not implemented" }; }) } }); function useCartContext() { return (0, import_react6.useContext)(CartContext); } function CartProvider({ children }) { const [count, setCount] = (0, import_react6.useState)(0); const [isLoading, setIsLoading] = (0, import_react6.useState)(false); const [error, setError] = (0, import_react6.useState)(null); const { bzbsService, appId, appName, urls } = useBuzzebeesServiceContext(); const getCartUrl = (returnUrl) => __async(null, null, function* () { var _a, _b; setIsLoading(true); const response = yield bzbsService.cartApi.cartAccess({ errorUrl: returnUrl, successUrl: returnUrl, returnUrl, appId, appName }); setIsLoading(false); if (response.type === "success") { const accessKey = (_b = (_a = response.model.data) == null ? void 0 : _a.key) != null ? _b : ""; const result = createCartUrl(urls.cart, appName, accessKey); return result; } return null; }); const addToCart = (id, mode, qty, data) => __async(null, null, function* () { var _a; setIsLoading(true); const response = yield bzbsService.cartApi.addCart({ id, mode, qty, sideCampaignJson: data }); setIsLoading(false); if (response.type === "success") { setCount((_a = response.model.cart_count) != null ? _a : 0); setError(null); } else { setError(response); } return response; }); const