@bzbs/react-providers
Version:
A collection of React Context Provider for Buzzebees apps
1,701 lines (1,684 loc) • 127 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
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 __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());
});
};
// src/providers/auth_provider.tsx
import React4, { createContext as createContext4, useContext as useContext4, useRef, useState as useState3 } from "react";
// src/providers/buzzebees_service_provider.tsx
import React, { createContext, useContext } from "react";
var BuzzebeesServiceContext = createContext({
appId: "",
appName: "",
bzbsService: {},
urls: {
webCallback: "",
cart: ""
}
});
function useBuzzebeesServiceContext() {
return useContext(BuzzebeesServiceContext);
}
function BuzzebeesServiceProvider({
appId,
appName,
bzbsService,
urls,
children
}) {
return /* @__PURE__ */ React.createElement(
BuzzebeesServiceContext.Provider,
{
value: {
appId,
appName,
urls,
bzbsService
}
},
children
);
}
// src/providers/locale_provider.tsx
import React2, { createContext as createContext2, useContext as useContext2, useState } from "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 = createContext2({
appLocale: EN,
locale: "en",
localeId: 1033,
setAppLocale: () => {
}
});
var useAppLocaleContext = () => {
return useContext2(LocaleContext);
};
var AppLocaleProvider = ({ initLocale, children }) => {
const [locale, setLocale] = useState(initLocale);
const setAppLocale = (locale2) => {
if (typeof locale2 === "string") {
setLocale(findBestLocaleFromString(locale2));
} else {
setLocale(locale2);
}
};
return /* @__PURE__ */ React2.createElement(
LocaleContext.Provider,
{
value: {
appLocale: locale,
locale: locale.locale,
localeId: locale.localeId,
setAppLocale
}
},
children
);
};
// src/providers/analytics_provider.tsx
import MatomoTracker, { MatomoProvider, useMatomo } from "matomo-tracker-react-native";
import React3, { createContext as createContext3, useContext as useContext3, useState as useState2 } from "react";
var AnalyticsContext = createContext3({
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 useContext3(AnalyticsContext);
}
function AnalyticsInner({
children,
userId,
enableLogging
}) {
const { trackEvent, trackScreenView, trackAppStart, trackAction, trackSiteSearch, trackLink, trackDownload } = useMatomo();
const [isEnabled, setIsEnabled] = useState2(true);
const [userIdState, setUserIdState] = useState2(userId);
const [presetUserInfo, setPresetUserInfoState] = useState2(void 0);
const [log] = useState2(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__ */ React3.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__ */ React3.createElement(AnalyticsContext.Provider, { value: noOpContextValue }, children);
}
const matomoInstance = instance || new MatomoTracker({
urlBase: "https://placeholder.com",
siteId: 1,
disabled: true
// Disabled until properly initialized
});
return /* @__PURE__ */ React3.createElement(MatomoProvider, { instance: matomoInstance }, /* @__PURE__ */ React3.createElement(AnalyticsInner, { userId, enableLogging }, children));
}
// src/providers/auth_provider.tsx
var AuthContext = createContext4({
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 useContext4(AuthContext);
}
function AuthProvider({
tokenFunctions,
children
}) {
const [versionData, setVersionData] = useState3(null);
const [isLoading, setIsLoading] = useState3(false);
const [error, setError] = useState3(null);
const [isLoggedIn, setIsLoggedIn] = useState3(false);
const [isLoadingToken, setIsLoadingToken] = useState3(false);
const [token, setToken] = useState3(null);
const [isInitialized, setIsInitialized] = useState3(false);
const [loginResponseHandler, setLoginResponseHandler] = useState3(() => {
});
const { bzbsService } = useBuzzebeesServiceContext();
const { localeId } = useAppLocaleContext();
const { actions: analyticsActions } = useAnalyticsContext();
const uuid = useRef("");
const appId = useRef("");
const deviceToken = useRef("");
const clientVersion = useRef("");
const os = useRef("");
const platform = 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__ */ React4.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
import React5, { createContext as createContext5, useContext as useContext5, useEffect, useState as useState4 } from "react";
// src/service/bzbs_service.ts
import * as blake from "blakejs";
import Emittery from "emittery";
import { v7 as uuidv7 } from "uuid";
var eventEmitter = new Emittery();
function defaultCorelationIdGenerator() {
return uuidv7();
}
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 = createContext5({
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 useContext5(UserContext);
}
function UserProvider({ children }) {
const [user, setUser] = useState4(null);
const [points, setPoints] = useState4(0);
const [expiringPoints, setExpiringPoints] = useState4([]);
const [cartCount, setCartCount] = useState4(0);
const [isLoading, setIsLoading] = useState4(false);
const [error, setError] = useState4(null);
const [recentPoints, setRecentPoints] = useState4(0);
const [recentBadge, setRecentBadge] = useState4(null);
const [badgeList, setBadgeList] = useState4([]);
const [recentTrace, setRecentTrace] = useState4(null);
const [traceList, setTraceList] = useState4([]);
const { bzbsService } = useBuzzebeesServiceContext();
const auth = useAuthContext();
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__ */ React5.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
import React6, { createContext as createContext6, useContext as useContext6, useState as useState5 } from "react";
var CartContext = createContext6({
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 useContext6(CartContext);
}
function CartProvider({ children }) {
const [count, setCount] = useState5(0);
const [isLoading, setIsLoading] = useState5(false);
const [error, setError] = useState5(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 getCount = () => __async(null, null, function* () {
var _a;
setIsLoading(true);
const response = yield bzbsService.cartApi.cartCount();
setIsLoading(false);
if (response.type === "success") {
setCount((_a = response.model.cart_count) != null ? _a : 0);
setError(null);
} else {
setError(response);
}
return response;
});
return /* @__PURE__ */ React6.createElement(
CartContext.Provider,
{
value: {
count,
isLoading,
error,
actions: {
getCartUrl,
addToCart,
getCount
}
}
},
children
);
}
// src/providers/alert_provider.tsx
import React7, { createContext as createContext7, useContext as useContext7, useState as useState6 } from "react";
var AlertContext = createContext7({
// eslint-disable-next-line @typescript-eslint/no-unused-vars
openAlert: (request) => {
},
closeAlert: () => {
}
});
var useAlertContext = () => {
return useContext7(AlertContext);
};
var AlertProvider = ({ children }) => {
const [isAlertOpen, setIsAlertOpen] = useState6(false);
const [alertRequest, setAlertRequest] = useState6({
title: "",
content: "",
onClose: () => {
}
});
const openAlert = (request) => {
setAlertRequest(request);
setIsAlertOpen(true);
};
const closeAlert = () => {
alertRequest.onClose();
setIsAlertOpen(false);
};
return /* @__PURE__ */ React7.createElement(
AlertContext.Provider,
{
value: {
isOpen: isAlertOpen,
alertRequest,
openAlert,
closeAlert
}
},
children
);
};
// src/providers/loading_indicator_provider.tsx
import React8, { createContext as createContext8, useContext as useContext8, useEffect as useEffect2, useState as useState7 } from "react";
var LoadingContext = createContext8({
loading: false,
show: () => {
},
hide: () => {
}
});
var useLoadingContext = () => {
return useContext8(LoadingContext);
};
var LoadingProvider = ({ children }) => {
const [loading, setLoading] = useState7(false);
const show = () => setLoading(true);
const hide = () => setLoading(false);
return /* @__PURE__ */ React8.createElement(LoadingContext.Provider, { value: { loading, show, hide } }, children);
};
var useLoading = (isLoading) => {
const loadingContext = useLoadingContext();
useEffect2(() => {
if (isLoading) {
loadingContext.show();
} else {
loadingContext.hide();
}
}, [isLoading]);
};
// src/providers/confirm_provider.tsx
import React9, { createContext as createContext9, useContext as useContext9, useState as useState8 } from "react";
var ConfirmContext = createContext9({
isOpen: false,
confirmRequest: {
title: "",
content: ""
},
openConfirm: () => {
},
closeConfirm: () => {
}
});
var useConfirmContext = () => {
return useContext9(ConfirmContext);
};
var ConfirmProvider = ({ children }) => {
const [isOpen, setIsOpen] = useState8(false);
const [confirmRequest, setConfirmRequest] = useState8({
title: "",
content: ""
});
const openConfirm = (request) => {
setConfirmRequest(request);
setIsOpen(true);
};
const closeConfirm = () => {
setIsOpen(false);
};
return /* @__PURE__ */ React9.createElement(ConfirmContext.Provider, { value: { isOpen, confirmRequest, openConfirm, closeConfirm } }, children);
};
// src/providers/popup_provider.tsx
import React10 from "react";
var PopupProvider = ({ children }) => {
return /* @__PURE__ */ React10.createElement(AlertProvider, null, /* @__PURE__ */ React10.createElement(ConfirmProvider, null, children));
};
// src/providers/address_provider.tsx
import React11, { createContext as createContext10, useContext as useContext10, useState as useState9 } from "react";
var AddressContext = createContext10({
addresses: [],
taxAddresses: [],
isLoading: false,
error: null,
actions: {
fetchAddresses: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
addAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
editAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
deleteAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
fetchTaxAddresses: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
addTaxAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
editTaxAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
}),
deleteTaxAddress: () => __async(null, null, function* () {
return { type: "client-error", message: "Not implemented" };
})
}
});
function useAddressContext() {
return useContext10(AddressContext);
}
function AddressProvider({ children }) {
const [addresses, setAddresses] = useState9([]);
const [taxAddresses, setTaxAddresses] = useState9([]);
const [isLoading, setIsLoading] = useState9(false);
const [error, setError] = useState9(null);
const { bzbsService } = useBuzzebeesServiceContext();
const fetchAddresses = () => __async(null, null, function* () {
setIsLoading(true);
const response = yield bzbsService.addressApi.userAddresses();
setIsLoading(false);
if (response.type === "success") {
setAddresses(response.model);
setError(null);
} else {
setError(response);
}
return response;
});
const addAddress = (addressForm) => __async(null, null, function* () {
setIsLoading(true);
const response = yield bzbsService.addressApi.updateAddress(__spreadProps(__spreadValues({}, addressForm), {
rowKey: ""
}));
setIsLoading(false);
if (response.type === "success") {
fetchAddresses();
setError(null);