@datlv-trustshop/shopify-inapp-components 0.2.8 → 0.2.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (220) hide show
  1. package/dist/components/AppList.d.ts +1 -0
  2. package/dist/components/AppList.d.ts.map +1 -0
  3. package/dist/components/AppList.js +1 -0
  4. package/dist/components/AppList.js.map +1 -0
  5. package/dist/components/ArticleList.d.ts +1 -0
  6. package/dist/components/ArticleList.d.ts.map +1 -0
  7. package/dist/components/ArticleList.js +1 -0
  8. package/dist/components/ArticleList.js.map +1 -0
  9. package/dist/components/ArticleSlide.d.ts +1 -0
  10. package/dist/components/ArticleSlide.d.ts.map +1 -0
  11. package/dist/components/ArticleSlide.js +1 -0
  12. package/dist/components/ArticleSlide.js.map +1 -0
  13. package/dist/components/FloatingCard.d.ts +1 -0
  14. package/dist/components/FloatingCard.d.ts.map +1 -0
  15. package/dist/components/FloatingCard.js +5 -4
  16. package/dist/components/FloatingCard.js.map +1 -0
  17. package/dist/components/FooterBanner.d.ts +1 -0
  18. package/dist/components/FooterBanner.d.ts.map +1 -0
  19. package/dist/components/FooterBanner.js +1 -0
  20. package/dist/components/FooterBanner.js.map +1 -0
  21. package/dist/components/GrowApps.d.ts +6 -6
  22. package/dist/components/GrowApps.d.ts.map +1 -0
  23. package/dist/components/GrowApps.js +11 -3
  24. package/dist/components/GrowApps.js.map +1 -0
  25. package/dist/components/ImageLoading.d.ts +1 -0
  26. package/dist/components/ImageLoading.d.ts.map +1 -0
  27. package/dist/components/ImageLoading.js +1 -0
  28. package/dist/components/ImageLoading.js.map +1 -0
  29. package/dist/components/PartnerIntegration.d.ts +8 -8
  30. package/dist/components/PartnerIntegration.d.ts.map +1 -0
  31. package/dist/components/PartnerIntegration.js +15 -76
  32. package/dist/components/PartnerIntegration.js.map +1 -0
  33. package/dist/components/PartnerList.d.ts +1 -0
  34. package/dist/components/PartnerList.d.ts.map +1 -0
  35. package/dist/components/PartnerList.js +1 -0
  36. package/dist/components/PartnerList.js.map +1 -0
  37. package/dist/components/PopupBanner.d.ts +4 -4
  38. package/dist/components/PopupBanner.d.ts.map +1 -0
  39. package/dist/components/PopupBanner.js +5 -1
  40. package/dist/components/PopupBanner.js.map +1 -0
  41. package/dist/components/TopBanner.d.ts +7 -7
  42. package/dist/components/TopBanner.d.ts.map +1 -0
  43. package/dist/components/TopBanner.js +15 -30
  44. package/dist/components/TopBanner.js.map +1 -0
  45. package/dist/components/WhatsNew.d.ts +6 -7
  46. package/dist/components/WhatsNew.d.ts.map +1 -0
  47. package/dist/components/WhatsNew.js +23 -25
  48. package/dist/components/WhatsNew.js.map +1 -0
  49. package/dist/components/index.d.ts +1 -0
  50. package/dist/components/index.d.ts.map +1 -0
  51. package/dist/components/index.js +1 -0
  52. package/dist/components/index.js.map +1 -0
  53. package/dist/components/inlineStyles.d.ts +1 -0
  54. package/dist/components/inlineStyles.d.ts.map +1 -0
  55. package/dist/components/inlineStyles.js +1 -0
  56. package/dist/components/inlineStyles.js.map +1 -0
  57. package/dist/components/styles.d.ts +1 -0
  58. package/dist/components/styles.d.ts.map +1 -0
  59. package/dist/components/styles.js +1 -0
  60. package/dist/components/styles.js.map +1 -0
  61. package/dist/config/component-defaults.d.ts +71 -0
  62. package/dist/config/component-defaults.d.ts.map +1 -0
  63. package/dist/config/component-defaults.js +106 -0
  64. package/dist/config/component-defaults.js.map +1 -0
  65. package/dist/config/internal-config.d.ts +28 -0
  66. package/dist/config/internal-config.d.ts.map +1 -0
  67. package/dist/config/internal-config.js +100 -0
  68. package/dist/config/internal-config.js.map +1 -0
  69. package/dist/core/SDKManager.d.ts +262 -0
  70. package/dist/core/SDKManager.d.ts.map +1 -0
  71. package/dist/core/SDKManager.js +527 -0
  72. package/dist/core/SDKManager.js.map +1 -0
  73. package/dist/core/adapter.d.ts +1 -0
  74. package/dist/core/adapter.d.ts.map +1 -0
  75. package/dist/core/adapter.js +1 -0
  76. package/dist/core/adapter.js.map +1 -0
  77. package/dist/core/engine.d.ts +1 -0
  78. package/dist/core/engine.d.ts.map +1 -0
  79. package/dist/core/engine.js +1 -0
  80. package/dist/core/engine.js.map +1 -0
  81. package/dist/core/fetcher.d.ts +1 -0
  82. package/dist/core/fetcher.d.ts.map +1 -0
  83. package/dist/core/fetcher.js +1 -0
  84. package/dist/core/fetcher.js.map +1 -0
  85. package/dist/core/global-manager.d.ts +1 -0
  86. package/dist/core/global-manager.d.ts.map +1 -0
  87. package/dist/core/global-manager.js +1 -0
  88. package/dist/core/global-manager.js.map +1 -0
  89. package/dist/hooks/index.d.ts +2 -3
  90. package/dist/hooks/index.d.ts.map +1 -0
  91. package/dist/hooks/index.js +2 -3
  92. package/dist/hooks/index.js.map +1 -0
  93. package/dist/hooks/useApps.d.ts +1 -0
  94. package/dist/hooks/useApps.d.ts.map +1 -0
  95. package/dist/hooks/useApps.js +10 -9
  96. package/dist/hooks/useApps.js.map +1 -0
  97. package/dist/hooks/useArticles.d.ts +1 -0
  98. package/dist/hooks/useArticles.d.ts.map +1 -0
  99. package/dist/hooks/useArticles.js +10 -14
  100. package/dist/hooks/useArticles.js.map +1 -0
  101. package/dist/hooks/useBanner.d.ts +1 -0
  102. package/dist/hooks/useBanner.d.ts.map +1 -0
  103. package/dist/hooks/useBanner.js +6 -5
  104. package/dist/hooks/useBanner.js.map +1 -0
  105. package/dist/hooks/useCampaignTracking.d.ts +1 -0
  106. package/dist/hooks/useCampaignTracking.d.ts.map +1 -0
  107. package/dist/hooks/useCampaignTracking.js +1 -0
  108. package/dist/hooks/useCampaignTracking.js.map +1 -0
  109. package/dist/hooks/useDashboard.d.ts +1 -0
  110. package/dist/hooks/useDashboard.d.ts.map +1 -0
  111. package/dist/hooks/useDashboard.js +18 -9
  112. package/dist/hooks/useDashboard.js.map +1 -0
  113. package/dist/hooks/useFloatingCards.d.ts +4 -2
  114. package/dist/hooks/useFloatingCards.d.ts.map +1 -0
  115. package/dist/hooks/useFloatingCards.js +52 -76
  116. package/dist/hooks/useFloatingCards.js.map +1 -0
  117. package/dist/hooks/usePartnerIntegration.d.ts +7 -2
  118. package/dist/hooks/usePartnerIntegration.d.ts.map +1 -0
  119. package/dist/hooks/usePartnerIntegration.js +26 -37
  120. package/dist/hooks/usePartnerIntegration.js.map +1 -0
  121. package/dist/hooks/useTranslations.d.ts +1 -0
  122. package/dist/hooks/useTranslations.d.ts.map +1 -0
  123. package/dist/hooks/useTranslations.js +5 -3
  124. package/dist/hooks/useTranslations.js.map +1 -0
  125. package/dist/hooks/useWhatsNew.d.ts +1 -0
  126. package/dist/hooks/useWhatsNew.d.ts.map +1 -0
  127. package/dist/hooks/useWhatsNew.js +9 -8
  128. package/dist/hooks/useWhatsNew.js.map +1 -0
  129. package/dist/index.d.ts +38 -22
  130. package/dist/index.d.ts.map +1 -0
  131. package/dist/index.js +76 -22
  132. package/dist/index.js.map +1 -0
  133. package/dist/translations/default.d.ts +1 -0
  134. package/dist/translations/default.d.ts.map +1 -0
  135. package/dist/translations/default.js +1 -0
  136. package/dist/translations/default.js.map +1 -0
  137. package/dist/translations/locales/cn.json +39 -0
  138. package/dist/translations/locales/de.json +39 -0
  139. package/dist/translations/locales/dk.json +39 -0
  140. package/dist/translations/locales/en.json +39 -0
  141. package/dist/translations/locales/es.json +39 -0
  142. package/dist/translations/locales/fr.json +39 -0
  143. package/dist/translations/locales/ie.json +39 -0
  144. package/dist/translations/locales/in.json +39 -0
  145. package/dist/translations/locales/it.json +39 -0
  146. package/dist/translations/locales/jp.json +39 -0
  147. package/dist/translations/locales/nl.json +39 -0
  148. package/dist/translations/locales/nz.json +39 -0
  149. package/dist/translations/locales/pt.json +39 -0
  150. package/dist/translations/locales/se.json +39 -0
  151. package/dist/translations/locales/vi.json +39 -0
  152. package/dist/translations/translation-manager.d.ts +89 -0
  153. package/dist/translations/translation-manager.d.ts.map +1 -0
  154. package/dist/translations/translation-manager.js +239 -0
  155. package/dist/translations/translation-manager.js.map +1 -0
  156. package/dist/types/app.d.ts +1 -0
  157. package/dist/types/app.d.ts.map +1 -0
  158. package/dist/types/app.js +1 -0
  159. package/dist/types/app.js.map +1 -0
  160. package/dist/types/article.d.ts +1 -0
  161. package/dist/types/article.d.ts.map +1 -0
  162. package/dist/types/article.js +1 -0
  163. package/dist/types/article.js.map +1 -0
  164. package/dist/types/banner.d.ts +1 -0
  165. package/dist/types/banner.d.ts.map +1 -0
  166. package/dist/types/banner.js +1 -0
  167. package/dist/types/banner.js.map +1 -0
  168. package/dist/types/component-props.d.ts +140 -0
  169. package/dist/types/component-props.d.ts.map +1 -0
  170. package/dist/types/component-props.js +6 -0
  171. package/dist/types/component-props.js.map +1 -0
  172. package/dist/types/dashboard.d.ts +1 -0
  173. package/dist/types/dashboard.d.ts.map +1 -0
  174. package/dist/types/dashboard.js +1 -0
  175. package/dist/types/dashboard.js.map +1 -0
  176. package/dist/types/index.d.ts +1 -0
  177. package/dist/types/index.d.ts.map +1 -0
  178. package/dist/types/index.js +1 -0
  179. package/dist/types/index.js.map +1 -0
  180. package/dist/types/integration.d.ts +1 -0
  181. package/dist/types/integration.d.ts.map +1 -0
  182. package/dist/types/integration.js +1 -0
  183. package/dist/types/integration.js.map +1 -0
  184. package/dist/types/partner.d.ts +1 -0
  185. package/dist/types/partner.d.ts.map +1 -0
  186. package/dist/types/partner.js +1 -0
  187. package/dist/types/partner.js.map +1 -0
  188. package/dist/types/product-update.d.ts +1 -0
  189. package/dist/types/product-update.d.ts.map +1 -0
  190. package/dist/types/product-update.js +1 -0
  191. package/dist/types/product-update.js.map +1 -0
  192. package/dist/types/translations.d.ts +1 -0
  193. package/dist/types/translations.d.ts.map +1 -0
  194. package/dist/types/translations.js +1 -0
  195. package/dist/types/translations.js.map +1 -0
  196. package/dist/utils/campaignTracking.d.ts +1 -0
  197. package/dist/utils/campaignTracking.d.ts.map +1 -0
  198. package/dist/utils/campaignTracking.js +1 -0
  199. package/dist/utils/campaignTracking.js.map +1 -0
  200. package/dist/utils/cls-monitor.d.ts +1 -0
  201. package/dist/utils/cls-monitor.d.ts.map +1 -0
  202. package/dist/utils/cls-monitor.js +1 -0
  203. package/dist/utils/cls-monitor.js.map +1 -0
  204. package/dist/utils/injectStyles.d.ts +1 -0
  205. package/dist/utils/injectStyles.d.ts.map +1 -0
  206. package/dist/utils/injectStyles.js +1 -0
  207. package/dist/utils/injectStyles.js.map +1 -0
  208. package/dist/utils/sessionManager.d.ts +1 -0
  209. package/dist/utils/sessionManager.d.ts.map +1 -0
  210. package/dist/utils/sessionManager.js +1 -0
  211. package/dist/utils/sessionManager.js.map +1 -0
  212. package/package.json +4 -3
  213. package/dist/hooks/useFloatingCardActions.d.ts +0 -17
  214. package/dist/hooks/useFloatingCardActions.js +0 -54
  215. package/dist/hooks/useFloatingCardEngine.d.ts +0 -21
  216. package/dist/hooks/useFloatingCardEngine.js +0 -39
  217. package/dist/hooks/useGrowApps.d.ts +0 -10
  218. package/dist/hooks/useGrowApps.js +0 -14
  219. package/dist/provider/DashboardProvider.d.ts +0 -36
  220. package/dist/provider/DashboardProvider.js +0 -200
@@ -0,0 +1,527 @@
1
+ /**
2
+ * SDK Manager - Internal singleton for managing global state
3
+ * Components automatically connect to this without manual provider setup
4
+ */
5
+ import { loadTranslations, getTranslations, mergeTranslations, } from "../translations/translation-manager";
6
+ import { generateDashboardConfig, } from "../config/internal-config";
7
+ import { COMPONENT_DEFAULTS } from "../config/component-defaults";
8
+ import { DashboardEngine } from "./engine";
9
+ // ============================================
10
+ // SDK Manager Singleton
11
+ // ============================================
12
+ class SDKManagerClass {
13
+ constructor() {
14
+ this.listeners = new Set();
15
+ /**
16
+ * Handle custom locale change events
17
+ */
18
+ this.handleCustomLocaleChange = (event) => {
19
+ const newLocale = event.detail?.locale || event.detail;
20
+ if (newLocale && typeof newLocale === "string") {
21
+ const normalizedLocale = this.normalizeLocale(newLocale);
22
+ // console.log("Received locale change event:", normalizedLocale);
23
+ this.handleLocaleChange(normalizedLocale);
24
+ }
25
+ };
26
+ this.state = {
27
+ initialized: false,
28
+ locale: "en",
29
+ translations: getTranslations("en"),
30
+ config: generateDashboardConfig(),
31
+ loading: false,
32
+ };
33
+ // Try to auto-detect Shopify context and locale
34
+ this.autoDetectShopInfo();
35
+ this.autoDetectLocale();
36
+ this.setupLocaleWatcher();
37
+ }
38
+ /**
39
+ * Auto-detect current locale from browser/Shopify context
40
+ */
41
+ autoDetectLocale() {
42
+ if (typeof window === "undefined")
43
+ return;
44
+ try {
45
+ // Method 1: Check Shopify Admin locale (if available)
46
+ const shopifyLocale = this.getShopifyAdminLocale();
47
+ if (shopifyLocale) {
48
+ this.currentDetectedLocale = shopifyLocale;
49
+ this.updateLocale(shopifyLocale);
50
+ // console.log("Auto-detected Shopify locale:", shopifyLocale);
51
+ return;
52
+ }
53
+ // Method 2: Browser language
54
+ const browserLocale = navigator.language || navigator.languages?.[0];
55
+ if (browserLocale) {
56
+ const normalizedLocale = this.normalizeLocale(browserLocale);
57
+ this.currentDetectedLocale = normalizedLocale;
58
+ this.updateLocale(normalizedLocale);
59
+ // console.log("Auto-detected browser locale:", normalizedLocale);
60
+ }
61
+ }
62
+ catch (error) {
63
+ console.warn("Failed to auto-detect locale:", error);
64
+ }
65
+ }
66
+ /**
67
+ * Get locale from Shopify Admin context
68
+ */
69
+ getShopifyAdminLocale() {
70
+ try {
71
+ // Check if we can detect locale from Shopify admin
72
+ const html = document.documentElement;
73
+ const lang = html.getAttribute("lang") || html.getAttribute("xml:lang");
74
+ if (lang) {
75
+ return this.normalizeLocale(lang);
76
+ }
77
+ // Check meta tags
78
+ const metaLang = document.querySelector('meta[http-equiv="content-language"]');
79
+ if (metaLang) {
80
+ const content = metaLang.getAttribute("content");
81
+ if (content) {
82
+ return this.normalizeLocale(content);
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ catch {
88
+ return null;
89
+ }
90
+ }
91
+ /**
92
+ * Setup watcher for locale changes in the DOM
93
+ */
94
+ setupLocaleWatcher() {
95
+ if (typeof window === "undefined")
96
+ return;
97
+ try {
98
+ this.localeObserver = new MutationObserver((mutations) => {
99
+ mutations.forEach((mutation) => {
100
+ if (mutation.type === "attributes" &&
101
+ (mutation.attributeName === "lang" ||
102
+ mutation.attributeName === "xml:lang")) {
103
+ const newLocale = this.getShopifyAdminLocale();
104
+ if (newLocale && newLocale !== this.currentDetectedLocale) {
105
+ // console.log(
106
+ // "Detected locale change:",
107
+ // this.currentDetectedLocale,
108
+ // "→",
109
+ // newLocale,
110
+ // );
111
+ this.currentDetectedLocale = newLocale;
112
+ this.handleLocaleChange(newLocale);
113
+ }
114
+ }
115
+ });
116
+ });
117
+ // Watch for changes to document element attributes
118
+ this.localeObserver.observe(document.documentElement, {
119
+ attributes: true,
120
+ attributeFilter: ["lang", "xml:lang"],
121
+ });
122
+ // Also listen for custom locale change events
123
+ window.addEventListener("trustshop-locale-change", this.handleCustomLocaleChange.bind(this));
124
+ window.addEventListener("shopify-locale-change", this.handleCustomLocaleChange.bind(this));
125
+ // console.log("Locale watcher initialized");
126
+ }
127
+ catch (error) {
128
+ console.warn("Failed to setup locale watcher:", error);
129
+ }
130
+ }
131
+ /**
132
+ * Handle locale changes (re-fetch data and translations)
133
+ */
134
+ async handleLocaleChange(newLocale) {
135
+ if (newLocale === this.state.locale)
136
+ return;
137
+ try {
138
+ // console.log(Updating SDK locale:", this.state.locale, "→", newLocale);
139
+ this.updateState({ loading: true });
140
+ // Load new translations
141
+ const baseTranslations = await loadTranslations(newLocale);
142
+ const translations = mergeTranslations(baseTranslations);
143
+ // Update config with new locale
144
+ const newConfig = { ...this.state.config, locale: newLocale };
145
+ // Update state
146
+ this.updateState({
147
+ locale: newLocale,
148
+ translations,
149
+ config: newConfig,
150
+ loading: false,
151
+ });
152
+ // Trigger re-fetch of API data with new locale
153
+ await this.refreshDashboardData(newLocale);
154
+ // console.log("SDK locale updated successfully");
155
+ }
156
+ catch (error) {
157
+ console.error(" Failed to update SDK locale:", error);
158
+ this.updateState({ loading: false, error: error });
159
+ }
160
+ }
161
+ /**
162
+ * Refresh dashboard data with new locale
163
+ */
164
+ async refreshDashboardData(locale) {
165
+ try {
166
+ this.updateState({ dashboardLoading: true, dashboardError: null });
167
+ const currentLocale = locale || this.state.locale;
168
+ const config = { ...this.state.config, locale: currentLocale };
169
+ // Initialize or update dashboard engine
170
+ if (!this.dashboardEngine) {
171
+ this.dashboardEngine = DashboardEngine.getInstance(config);
172
+ }
173
+ else {
174
+ // Update engine config with new locale
175
+ await this.dashboardEngine.setLocale(currentLocale);
176
+ }
177
+ // Fetch dashboard data
178
+ await this.dashboardEngine.init();
179
+ const dashboardData = this.dashboardEngine.getData();
180
+ this.updateState({
181
+ dashboardData,
182
+ dashboardLoading: false,
183
+ dashboardError: null,
184
+ });
185
+ // Also refresh campaigns data
186
+ await this.refreshCampaignsData(currentLocale);
187
+ // Emit event for components to refresh
188
+ window.dispatchEvent(new CustomEvent("trustshop-data-refresh", {
189
+ detail: {
190
+ locale: currentLocale,
191
+ reason: "locale-change",
192
+ data: dashboardData,
193
+ },
194
+ }));
195
+ // console.log(`Dashboard data refreshed for locale: ${currentLocale}`);
196
+ }
197
+ catch (error) {
198
+ console.error("Failed to refresh dashboard data:", error);
199
+ this.updateState({
200
+ dashboardLoading: false,
201
+ dashboardError: error,
202
+ });
203
+ }
204
+ }
205
+ /**
206
+ * Refresh campaigns data with new locale
207
+ */
208
+ async refreshCampaignsData(locale) {
209
+ try {
210
+ // Only fetch campaigns if we have a shop ID
211
+ if (!this.state.shopInfo?.id) {
212
+ // console.log("Skipping campaigns fetch - no shop ID available");
213
+ return;
214
+ }
215
+ this.updateState({ campaignsLoading: true, campaignsError: null });
216
+ const currentLocale = locale || this.state.locale;
217
+ const shopId = this.state.shopInfo.id;
218
+ // Build campaigns API URL
219
+ let baseUrl;
220
+ if (this.state.config?.apiUrl) {
221
+ const configUrl = this.state.config.apiUrl;
222
+ if (configUrl.includes("/dashboard")) {
223
+ baseUrl = configUrl.replace("/dashboard", "");
224
+ }
225
+ else {
226
+ baseUrl = configUrl;
227
+ }
228
+ }
229
+ else {
230
+ baseUrl =
231
+ typeof window !== "undefined" &&
232
+ window.location.hostname === "localhost"
233
+ ? "/api"
234
+ : "https://ops.trustshop.io/api";
235
+ }
236
+ const apiUrl = `${baseUrl}/campaigns?shop_id=${shopId}&locale=${currentLocale}`;
237
+ const response = await fetch(apiUrl, {
238
+ method: "GET",
239
+ headers: {
240
+ Accept: "application/json",
241
+ "Content-Type": "application/json",
242
+ "Accept-Language": currentLocale,
243
+ ...(this.state.config?.headers || {}),
244
+ },
245
+ credentials: "include",
246
+ });
247
+ if (!response.ok) {
248
+ throw new Error(`Failed to fetch campaigns: ${response.statusText}`);
249
+ }
250
+ const data = await response.json();
251
+ const campaignsData = data.success && Array.isArray(data.data) ? data.data : [];
252
+ this.updateState({
253
+ campaignsData,
254
+ campaignsLoading: false,
255
+ campaignsError: null,
256
+ });
257
+ // Emit event for campaigns refresh
258
+ window.dispatchEvent(new CustomEvent("trustshop-campaigns-refresh", {
259
+ detail: { locale: currentLocale, data: campaignsData, shopId },
260
+ }));
261
+ }
262
+ catch (error) {
263
+ console.error("Failed to refresh campaigns data:", error);
264
+ this.updateState({
265
+ campaignsLoading: false,
266
+ campaignsError: error,
267
+ });
268
+ }
269
+ }
270
+ /**
271
+ * Normalize locale string to supported format
272
+ */
273
+ normalizeLocale(locale) {
274
+ if (!locale)
275
+ return "en";
276
+ // Use the same normalization as translation manager
277
+ const SUPPORTED_LOCALES = [
278
+ "cn",
279
+ "de",
280
+ "dk",
281
+ "en",
282
+ "es",
283
+ "fr",
284
+ "ie",
285
+ "in",
286
+ "it",
287
+ "jp",
288
+ "nl",
289
+ "nz",
290
+ "pt",
291
+ "se",
292
+ "vi",
293
+ ];
294
+ // Direct match
295
+ if (SUPPORTED_LOCALES.includes(locale)) {
296
+ return locale;
297
+ }
298
+ // Extract base locale (en-US → en)
299
+ const base = locale.split(/[-_]/)[0].toLowerCase();
300
+ // Special mappings
301
+ const mappings = {
302
+ zh: "cn",
303
+ da: "dk",
304
+ ga: "ie",
305
+ hi: "in",
306
+ ja: "jp",
307
+ mi: "nz",
308
+ sv: "se",
309
+ };
310
+ const mapped = mappings[base] || base;
311
+ if (SUPPORTED_LOCALES.includes(mapped)) {
312
+ return mapped;
313
+ }
314
+ return "en";
315
+ }
316
+ /**
317
+ * Manually update locale (for programmatic changes)
318
+ */
319
+ async updateLocale(newLocale) {
320
+ const normalizedLocale = this.normalizeLocale(newLocale);
321
+ await this.handleLocaleChange(normalizedLocale);
322
+ }
323
+ /**
324
+ * Auto-detect shop info from Shopify App Bridge or URL
325
+ */
326
+ autoDetectShopInfo() {
327
+ if (typeof window === "undefined")
328
+ return;
329
+ try {
330
+ // Method 1: Check if Shopify App Bridge is available
331
+ const shopifyApp = window.ShopifyApp;
332
+ if (shopifyApp) {
333
+ }
334
+ // Method 2: Parse from URL (admin.shopify.com)
335
+ const currentUrl = window.location.href;
336
+ const shopifyAdminMatch = currentUrl.match(/https:\/\/admin\.shopify\.com\/store\/([^\/]+)/);
337
+ if (shopifyAdminMatch) {
338
+ const [, storeName] = shopifyAdminMatch;
339
+ this.updateState({
340
+ shopInfo: {
341
+ domain: `${storeName}.myshopify.com`,
342
+ id: storeName,
343
+ },
344
+ });
345
+ }
346
+ }
347
+ catch (error) {
348
+ console.warn("Failed to auto-detect shop info:", error);
349
+ }
350
+ }
351
+ /**
352
+ * Initialize SDK with options (called automatically by components)
353
+ */
354
+ async initialize(options = {}) {
355
+ if (this.initPromise) {
356
+ return this.initPromise;
357
+ }
358
+ this.initPromise = this.performInitialization(options);
359
+ return this.initPromise;
360
+ }
361
+ async performInitialization(options) {
362
+ try {
363
+ this.updateState({ loading: true });
364
+ const locale = options.locale || this.state.locale;
365
+ const shopInfo = options.shopInfo || this.state.shopInfo;
366
+ // Load translations
367
+ const baseTranslations = await loadTranslations(locale);
368
+ const translations = mergeTranslations(baseTranslations, options.translations);
369
+ // Generate config with locale
370
+ const config = {
371
+ ...generateDashboardConfig(shopInfo, options.config),
372
+ locale,
373
+ };
374
+ this.updateState({
375
+ initialized: true,
376
+ locale,
377
+ shopInfo,
378
+ translations,
379
+ config,
380
+ loading: false,
381
+ error: undefined,
382
+ });
383
+ // Automatically fetch dashboard data after initialization
384
+ await this.refreshDashboardData(locale);
385
+ // console.log("SDK initialized successfully with dashboard data", {
386
+ // locale,
387
+ // shopInfo,
388
+ // });
389
+ }
390
+ catch (error) {
391
+ this.updateState({
392
+ loading: false,
393
+ error: error,
394
+ });
395
+ console.error("SDK initialization failed:", error);
396
+ throw error;
397
+ }
398
+ }
399
+ /**
400
+ * Update SDK state and notify listeners
401
+ */
402
+ updateState(updates) {
403
+ this.state = { ...this.state, ...updates };
404
+ this.notifyListeners();
405
+ }
406
+ /**
407
+ * Update configuration (called when components pass new props)
408
+ */
409
+ async updateConfig(options) {
410
+ const hasChanges = options.locale !== this.state.locale ||
411
+ JSON.stringify(options.shopInfo) !== JSON.stringify(this.state.shopInfo);
412
+ if (hasChanges) {
413
+ this.initPromise = undefined; // Reset init promise to allow re-initialization
414
+ await this.initialize(options);
415
+ }
416
+ }
417
+ /**
418
+ * Get current state
419
+ */
420
+ getState() {
421
+ return this.state;
422
+ }
423
+ /**
424
+ * Subscribe to state changes
425
+ */
426
+ subscribe(listener) {
427
+ this.listeners.add(listener);
428
+ return () => this.listeners.delete(listener);
429
+ }
430
+ notifyListeners() {
431
+ this.listeners.forEach((listener) => listener());
432
+ }
433
+ /**
434
+ * Get component defaults
435
+ */
436
+ getDefaults() {
437
+ return COMPONENT_DEFAULTS;
438
+ }
439
+ /**
440
+ * Get dashboard engine instance
441
+ */
442
+ getDashboardEngine() {
443
+ return this.dashboardEngine;
444
+ }
445
+ /**
446
+ * Get dashboard data
447
+ */
448
+ getDashboardData() {
449
+ return this.state.dashboardData;
450
+ }
451
+ /**
452
+ * Get campaigns data
453
+ */
454
+ getCampaignsData() {
455
+ return this.state.campaignsData;
456
+ }
457
+ /**
458
+ * Check if SDK is ready for use
459
+ */
460
+ isReady() {
461
+ return (this.state.initialized &&
462
+ !this.state.loading &&
463
+ !this.state.error &&
464
+ !this.state.dashboardLoading);
465
+ }
466
+ /**
467
+ * Cleanup observers and listeners
468
+ */
469
+ destroy() {
470
+ if (this.localeObserver) {
471
+ this.localeObserver.disconnect();
472
+ }
473
+ if (typeof window !== "undefined") {
474
+ window.removeEventListener("trustshop-locale-change", this.handleCustomLocaleChange);
475
+ window.removeEventListener("shopify-locale-change", this.handleCustomLocaleChange);
476
+ }
477
+ this.listeners.clear();
478
+ // console.log("SDK Manager cleaned up");
479
+ }
480
+ }
481
+ // ============================================
482
+ // Export Singleton Instance
483
+ // ============================================
484
+ export const SDKManager = new SDKManagerClass();
485
+ // ============================================
486
+ // React Hook for Components
487
+ // ============================================
488
+ import { useState, useEffect } from "react";
489
+ /**
490
+ * Hook for components to connect to SDK Manager
491
+ * Automatically initializes SDK on first use
492
+ */
493
+ export function useSDK(options = {}) {
494
+ const [state, setState] = useState(() => SDKManager.getState());
495
+ const [isInitializing, setIsInitializing] = useState(false);
496
+ // Subscribe to state changes
497
+ useEffect(() => {
498
+ const unsubscribe = SDKManager.subscribe(() => {
499
+ setState(SDKManager.getState());
500
+ });
501
+ return unsubscribe;
502
+ }, []);
503
+ // Auto-initialize SDK when component mounts
504
+ useEffect(() => {
505
+ if (!state.initialized && !isInitializing) {
506
+ setIsInitializing(true);
507
+ SDKManager.initialize(options).finally(() => {
508
+ setIsInitializing(false);
509
+ });
510
+ }
511
+ }, [state.initialized, isInitializing]);
512
+ // Update config if options change
513
+ useEffect(() => {
514
+ if (state.initialized) {
515
+ SDKManager.updateConfig(options);
516
+ }
517
+ }, [state.initialized, JSON.stringify(options)]);
518
+ return {
519
+ ...state,
520
+ isInitializing,
521
+ defaults: SDKManager.getDefaults(),
522
+ isReady: SDKManager.isReady(),
523
+ dashboardEngine: SDKManager.getDashboardEngine(),
524
+ };
525
+ }
526
+ export default SDKManager;
527
+ //# sourceMappingURL=SDKManager.js.map
@@ -0,0 +1 @@
1
+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AAC,WAAW,EAAE,cAAc,CAAC,CAAC,CAAC;IAExC,kCAAkC;IAClC,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,KAAK,CAAC,WAAW,EAAE,CAAC;YACtB,UAAU,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;IACH,CAAC,EAAE,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;IAEjD,OAAO;QACL,GAAG,KAAK;QACR,cAAc;QACd,QAAQ,EAAE,UAAU,CAAC,WAAW,EAAE;QAClC,OAAO,EAAE,UAAU,CAAC,OAAO,EAAE;QAC7B,eAAe,EAAE,UAAU,CAAC,kBAAkB,EAAE;KACjD,CAAC;AACJ,CAAC;AAED,eAAe,UAAU,CAAC","sourcesContent":["/**\n * SDK Manager - Internal singleton for managing global state\n * Components automatically connect to this without manual provider setup\n */\n\nimport {\n loadTranslations,\n getTranslations,\n mergeTranslations,\n type SupportedLocale,\n type SDKTranslations,\n} from \"../translations/translation-manager\";\nimport {\n generateDashboardConfig,\n type ShopInfo,\n type SDKInternalConfig,\n} from \"../config/internal-config\";\nimport { COMPONENT_DEFAULTS } from \"../config/component-defaults\";\nimport { DashboardEngine } from \"./engine\";\nimport { DashboardData } from \"../types\";\n\n// ============================================\n// SDK Global State\n// ============================================\n\ninterface SDKState {\n initialized: boolean;\n shopInfo?: ShopInfo;\n locale: SupportedLocale;\n translations: SDKTranslations;\n config: SDKInternalConfig;\n loading: boolean;\n error?: Error;\n dashboardData?: DashboardData | null;\n dashboardLoading?: boolean;\n dashboardError?: Error | null;\n campaignsData?: any[] | null;\n campaignsLoading?: boolean;\n campaignsError?: Error | null;\n}\n\ninterface SDKOptions {\n shopInfo?: ShopInfo;\n locale?: SupportedLocale;\n translations?: Partial<SDKTranslations>;\n config?: Partial<SDKInternalConfig>;\n}\n\n// ============================================\n// SDK Manager Singleton\n// ============================================\n\nclass SDKManagerClass {\n private state: SDKState;\n private listeners: Set<() => void> = new Set();\n private initPromise?: Promise<void>;\n private localeObserver?: MutationObserver;\n private currentDetectedLocale?: SupportedLocale;\n private dashboardEngine?: DashboardEngine;\n\n constructor() {\n this.state = {\n initialized: false,\n locale: \"en\",\n translations: getTranslations(\"en\"),\n config: generateDashboardConfig(),\n loading: false,\n };\n\n // Try to auto-detect Shopify context and locale\n this.autoDetectShopInfo();\n this.autoDetectLocale();\n this.setupLocaleWatcher();\n }\n\n /**\n * Auto-detect current locale from browser/Shopify context\n */\n private autoDetectLocale(): void {\n if (typeof window === \"undefined\") return;\n\n try {\n // Method 1: Check Shopify Admin locale (if available)\n const shopifyLocale = this.getShopifyAdminLocale();\n if (shopifyLocale) {\n this.currentDetectedLocale = shopifyLocale;\n this.updateLocale(shopifyLocale);\n // console.log(\"Auto-detected Shopify locale:\", shopifyLocale);\n return;\n }\n\n // Method 2: Browser language\n const browserLocale = navigator.language || navigator.languages?.[0];\n if (browserLocale) {\n const normalizedLocale = this.normalizeLocale(browserLocale);\n this.currentDetectedLocale = normalizedLocale;\n this.updateLocale(normalizedLocale);\n // console.log(\"Auto-detected browser locale:\", normalizedLocale);\n }\n } catch (error) {\n console.warn(\"Failed to auto-detect locale:\", error);\n }\n }\n\n /**\n * Get locale from Shopify Admin context\n */\n private getShopifyAdminLocale(): SupportedLocale | null {\n try {\n // Check if we can detect locale from Shopify admin\n const html = document.documentElement;\n const lang = html.getAttribute(\"lang\") || html.getAttribute(\"xml:lang\");\n\n if (lang) {\n return this.normalizeLocale(lang);\n }\n\n // Check meta tags\n const metaLang = document.querySelector(\n 'meta[http-equiv=\"content-language\"]',\n );\n if (metaLang) {\n const content = metaLang.getAttribute(\"content\");\n if (content) {\n return this.normalizeLocale(content);\n }\n }\n\n return null;\n } catch {\n return null;\n }\n }\n\n /**\n * Setup watcher for locale changes in the DOM\n */\n private setupLocaleWatcher(): void {\n if (typeof window === \"undefined\") return;\n\n try {\n this.localeObserver = new MutationObserver((mutations) => {\n mutations.forEach((mutation) => {\n if (\n mutation.type === \"attributes\" &&\n (mutation.attributeName === \"lang\" ||\n mutation.attributeName === \"xml:lang\")\n ) {\n const newLocale = this.getShopifyAdminLocale();\n if (newLocale && newLocale !== this.currentDetectedLocale) {\n // console.log(\n // \"Detected locale change:\",\n // this.currentDetectedLocale,\n // \"→\",\n // newLocale,\n // );\n this.currentDetectedLocale = newLocale;\n this.handleLocaleChange(newLocale);\n }\n }\n });\n });\n\n // Watch for changes to document element attributes\n this.localeObserver.observe(document.documentElement, {\n attributes: true,\n attributeFilter: [\"lang\", \"xml:lang\"],\n });\n\n // Also listen for custom locale change events\n window.addEventListener(\n \"trustshop-locale-change\",\n this.handleCustomLocaleChange.bind(this),\n );\n window.addEventListener(\n \"shopify-locale-change\",\n this.handleCustomLocaleChange.bind(this),\n );\n\n // console.log(\"Locale watcher initialized\");\n } catch (error) {\n console.warn(\"Failed to setup locale watcher:\", error);\n }\n }\n\n /**\n * Handle custom locale change events\n */\n private handleCustomLocaleChange = (event: any) => {\n const newLocale = event.detail?.locale || event.detail;\n if (newLocale && typeof newLocale === \"string\") {\n const normalizedLocale = this.normalizeLocale(newLocale);\n // console.log(\"Received locale change event:\", normalizedLocale);\n this.handleLocaleChange(normalizedLocale);\n }\n };\n\n /**\n * Handle locale changes (re-fetch data and translations)\n */\n private async handleLocaleChange(newLocale: SupportedLocale): Promise<void> {\n if (newLocale === this.state.locale) return;\n\n try {\n // console.log(Updating SDK locale:\", this.state.locale, \"→\", newLocale);\n this.updateState({ loading: true });\n\n // Load new translations\n const baseTranslations = await loadTranslations(newLocale);\n const translations = mergeTranslations(baseTranslations);\n\n // Update config with new locale\n const newConfig = { ...this.state.config, locale: newLocale };\n\n // Update state\n this.updateState({\n locale: newLocale,\n translations,\n config: newConfig,\n loading: false,\n });\n\n // Trigger re-fetch of API data with new locale\n await this.refreshDashboardData(newLocale);\n\n // console.log(\"SDK locale updated successfully\");\n } catch (error) {\n console.error(\" Failed to update SDK locale:\", error);\n this.updateState({ loading: false, error: error as Error });\n }\n }\n\n /**\n * Refresh dashboard data with new locale\n */\n private async refreshDashboardData(locale?: SupportedLocale): Promise<void> {\n try {\n this.updateState({ dashboardLoading: true, dashboardError: null });\n\n const currentLocale = locale || this.state.locale;\n const config = { ...this.state.config, locale: currentLocale };\n\n // Initialize or update dashboard engine\n if (!this.dashboardEngine) {\n this.dashboardEngine = DashboardEngine.getInstance(config);\n } else {\n // Update engine config with new locale\n await this.dashboardEngine.setLocale(currentLocale);\n }\n\n // Fetch dashboard data\n await this.dashboardEngine.init();\n const dashboardData = this.dashboardEngine.getData();\n\n this.updateState({\n dashboardData,\n dashboardLoading: false,\n dashboardError: null,\n });\n\n // Also refresh campaigns data\n await this.refreshCampaignsData(currentLocale);\n\n // Emit event for components to refresh\n window.dispatchEvent(\n new CustomEvent(\"trustshop-data-refresh\", {\n detail: {\n locale: currentLocale,\n reason: \"locale-change\",\n data: dashboardData,\n },\n }),\n );\n\n // console.log(`Dashboard data refreshed for locale: ${currentLocale}`);\n } catch (error) {\n console.error(\"Failed to refresh dashboard data:\", error);\n this.updateState({\n dashboardLoading: false,\n dashboardError: error as Error,\n });\n }\n }\n\n /**\n * Refresh campaigns data with new locale\n */\n private async refreshCampaignsData(locale?: SupportedLocale): Promise<void> {\n try {\n // Only fetch campaigns if we have a shop ID\n if (!this.state.shopInfo?.id) {\n // console.log(\"Skipping campaigns fetch - no shop ID available\");\n return;\n }\n\n this.updateState({ campaignsLoading: true, campaignsError: null });\n\n const currentLocale = locale || this.state.locale;\n const shopId = this.state.shopInfo.id;\n\n // Build campaigns API URL\n let baseUrl: string;\n if (this.state.config?.apiUrl) {\n const configUrl = this.state.config.apiUrl;\n if (configUrl.includes(\"/dashboard\")) {\n baseUrl = configUrl.replace(\"/dashboard\", \"\");\n } else {\n baseUrl = configUrl;\n }\n } else {\n baseUrl =\n typeof window !== \"undefined\" &&\n window.location.hostname === \"localhost\"\n ? \"/api\"\n : \"https://ops.trustshop.io/api\";\n }\n\n const apiUrl = `${baseUrl}/campaigns?shop_id=${shopId}&locale=${currentLocale}`;\n\n const response = await fetch(apiUrl, {\n method: \"GET\",\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n \"Accept-Language\": currentLocale,\n ...(this.state.config?.headers || {}),\n },\n credentials: \"include\",\n });\n\n if (!response.ok) {\n throw new Error(`Failed to fetch campaigns: ${response.statusText}`);\n }\n\n const data = await response.json();\n\n const campaignsData =\n data.success && Array.isArray(data.data) ? data.data : [];\n\n this.updateState({\n campaignsData,\n campaignsLoading: false,\n campaignsError: null,\n });\n\n // Emit event for campaigns refresh\n window.dispatchEvent(\n new CustomEvent(\"trustshop-campaigns-refresh\", {\n detail: { locale: currentLocale, data: campaignsData, shopId },\n }),\n );\n } catch (error) {\n console.error(\"Failed to refresh campaigns data:\", error);\n this.updateState({\n campaignsLoading: false,\n campaignsError: error as Error,\n });\n }\n }\n\n /**\n * Normalize locale string to supported format\n */\n private normalizeLocale(locale: string): SupportedLocale {\n if (!locale) return \"en\";\n\n // Use the same normalization as translation manager\n const SUPPORTED_LOCALES: SupportedLocale[] = [\n \"cn\",\n \"de\",\n \"dk\",\n \"en\",\n \"es\",\n \"fr\",\n \"ie\",\n \"in\",\n \"it\",\n \"jp\",\n \"nl\",\n \"nz\",\n \"pt\",\n \"se\",\n \"vi\",\n ];\n\n // Direct match\n if (SUPPORTED_LOCALES.includes(locale as SupportedLocale)) {\n return locale as SupportedLocale;\n }\n\n // Extract base locale (en-US → en)\n const base = locale.split(/[-_]/)[0].toLowerCase();\n\n // Special mappings\n const mappings: Record<string, SupportedLocale> = {\n zh: \"cn\",\n da: \"dk\",\n ga: \"ie\",\n hi: \"in\",\n ja: \"jp\",\n mi: \"nz\",\n sv: \"se\",\n };\n\n const mapped = mappings[base] || base;\n\n if (SUPPORTED_LOCALES.includes(mapped as SupportedLocale)) {\n return mapped as SupportedLocale;\n }\n\n return \"en\";\n }\n\n /**\n * Manually update locale (for programmatic changes)\n */\n async updateLocale(newLocale: string | SupportedLocale): Promise<void> {\n const normalizedLocale = this.normalizeLocale(newLocale);\n await this.handleLocaleChange(normalizedLocale);\n }\n\n /**\n * Auto-detect shop info from Shopify App Bridge or URL\n */\n private autoDetectShopInfo(): void {\n if (typeof window === \"undefined\") return;\n\n try {\n // Method 1: Check if Shopify App Bridge is available\n const shopifyApp = (window as any).ShopifyApp;\n if (shopifyApp) {\n }\n\n // Method 2: Parse from URL (admin.shopify.com)\n const currentUrl = window.location.href;\n const shopifyAdminMatch = currentUrl.match(\n /https:\\/\\/admin\\.shopify\\.com\\/store\\/([^\\/]+)/,\n );\n\n if (shopifyAdminMatch) {\n const [, storeName] = shopifyAdminMatch;\n this.updateState({\n shopInfo: {\n domain: `${storeName}.myshopify.com`,\n id: storeName,\n },\n });\n }\n } catch (error) {\n console.warn(\"Failed to auto-detect shop info:\", error);\n }\n }\n\n /**\n * Initialize SDK with options (called automatically by components)\n */\n async initialize(options: SDKOptions = {}): Promise<void> {\n if (this.initPromise) {\n return this.initPromise;\n }\n\n this.initPromise = this.performInitialization(options);\n return this.initPromise;\n }\n\n private async performInitialization(options: SDKOptions): Promise<void> {\n try {\n this.updateState({ loading: true });\n\n const locale = options.locale || this.state.locale;\n const shopInfo = options.shopInfo || this.state.shopInfo;\n\n // Load translations\n const baseTranslations = await loadTranslations(locale);\n const translations = mergeTranslations(\n baseTranslations,\n options.translations,\n );\n\n // Generate config with locale\n const config = {\n ...generateDashboardConfig(shopInfo, options.config),\n locale,\n };\n\n this.updateState({\n initialized: true,\n locale,\n shopInfo,\n translations,\n config,\n loading: false,\n error: undefined,\n });\n\n // Automatically fetch dashboard data after initialization\n await this.refreshDashboardData(locale);\n\n // console.log(\"SDK initialized successfully with dashboard data\", {\n // locale,\n // shopInfo,\n // });\n } catch (error) {\n this.updateState({\n loading: false,\n error: error as Error,\n });\n console.error(\"SDK initialization failed:\", error);\n throw error;\n }\n }\n\n /**\n * Update SDK state and notify listeners\n */\n private updateState(updates: Partial<SDKState>): void {\n this.state = { ...this.state, ...updates };\n this.notifyListeners();\n }\n\n /**\n * Update configuration (called when components pass new props)\n */\n async updateConfig(options: SDKOptions): Promise<void> {\n const hasChanges =\n options.locale !== this.state.locale ||\n JSON.stringify(options.shopInfo) !== JSON.stringify(this.state.shopInfo);\n\n if (hasChanges) {\n this.initPromise = undefined; // Reset init promise to allow re-initialization\n await this.initialize(options);\n }\n }\n\n /**\n * Get current state\n */\n getState(): SDKState {\n return this.state;\n }\n\n /**\n * Subscribe to state changes\n */\n subscribe(listener: () => void): () => void {\n this.listeners.add(listener);\n return () => this.listeners.delete(listener);\n }\n\n private notifyListeners(): void {\n this.listeners.forEach((listener) => listener());\n }\n\n /**\n * Get component defaults\n */\n getDefaults() {\n return COMPONENT_DEFAULTS;\n }\n\n /**\n * Get dashboard engine instance\n */\n getDashboardEngine(): DashboardEngine | undefined {\n return this.dashboardEngine;\n }\n\n /**\n * Get dashboard data\n */\n getDashboardData(): DashboardData | null | undefined {\n return this.state.dashboardData;\n }\n\n /**\n * Get campaigns data\n */\n getCampaignsData(): any[] | null | undefined {\n return this.state.campaignsData;\n }\n\n /**\n * Check if SDK is ready for use\n */\n isReady(): boolean {\n return (\n this.state.initialized &&\n !this.state.loading &&\n !this.state.error &&\n !this.state.dashboardLoading\n );\n }\n\n /**\n * Cleanup observers and listeners\n */\n destroy(): void {\n if (this.localeObserver) {\n this.localeObserver.disconnect();\n }\n\n if (typeof window !== \"undefined\") {\n window.removeEventListener(\n \"trustshop-locale-change\",\n this.handleCustomLocaleChange,\n );\n window.removeEventListener(\n \"shopify-locale-change\",\n this.handleCustomLocaleChange,\n );\n }\n\n this.listeners.clear();\n // console.log(\"SDK Manager cleaned up\");\n }\n}\n\n// ============================================\n// Export Singleton Instance\n// ============================================\n\nexport const SDKManager = new SDKManagerClass();\n\n// ============================================\n// React Hook for Components\n// ============================================\n\nimport { useState, useEffect } from \"react\";\n\nexport interface UseSDKOptions {\n shopInfo?: ShopInfo;\n locale?: SupportedLocale;\n translations?: Partial<SDKTranslations>;\n config?: Partial<SDKInternalConfig>;\n}\n\n/**\n * Hook for components to connect to SDK Manager\n * Automatically initializes SDK on first use\n */\nexport function useSDK(options: UseSDKOptions = {}) {\n const [state, setState] = useState(() => SDKManager.getState());\n const [isInitializing, setIsInitializing] = useState(false);\n\n // Subscribe to state changes\n useEffect(() => {\n const unsubscribe = SDKManager.subscribe(() => {\n setState(SDKManager.getState());\n });\n return unsubscribe;\n }, []);\n\n // Auto-initialize SDK when component mounts\n useEffect(() => {\n if (!state.initialized && !isInitializing) {\n setIsInitializing(true);\n SDKManager.initialize(options).finally(() => {\n setIsInitializing(false);\n });\n }\n }, [state.initialized, isInitializing]);\n\n // Update config if options change\n useEffect(() => {\n if (state.initialized) {\n SDKManager.updateConfig(options);\n }\n }, [state.initialized, JSON.stringify(options)]);\n\n return {\n ...state,\n isInitializing,\n defaults: SDKManager.getDefaults(),\n isReady: SDKManager.isReady(),\n dashboardEngine: SDKManager.getDashboardEngine(),\n };\n}\n\nexport default SDKManager;\n"]}
@@ -4,3 +4,4 @@ export declare function adaptBanner(apiData: any): BannerItem;
4
4
  export declare function adaptApp(apiData: any, defaultGroup?: AppGroup): AppItem;
5
5
  export declare function adaptArticle(apiData: any): ArticleItem;
6
6
  export declare function adaptProductUpdate(apiData: any): ProductUpdateItem;
7
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../src/core/adapter.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,UAAU,EACV,OAAO,EACP,WAAW,EACX,iBAAiB,EAEjB,QAAQ,EACT,MAAM,UAAU,CAAC;AAElB,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,GAAG,GAAG,aAAa,CAoC9D;AAQD,wBAAgB,WAAW,CAAC,OAAO,EAAE,GAAG,GAAG,UAAU,CAwCpD;AAoFD,wBAAgB,QAAQ,CAAC,OAAO,EAAE,GAAG,EAAE,YAAY,CAAC,EAAE,QAAQ,GAAG,OAAO,CAyBvE;AAQD,wBAAgB,YAAY,CAAC,OAAO,EAAE,GAAG,GAAG,WAAW,CAkCtD;AAgBD,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,GAAG,GAAG,iBAAiB,CAiElE"}
@@ -303,3 +303,4 @@ function generateId() {
303
303
  function generateKey() {
304
304
  return `item-${Math.random().toString(36).substr(2, 9)}`;
305
305
  }
306
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../src/core/adapter.ts"],"names":[],"mappings":"AAUA,MAAM,UAAU,kBAAkB,CAAC,OAAY;IAC7C,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,IAAI,OAAO,CAAC;IAErC,MAAM,OAAO,GAAG,EAAE,CAAC;IACnB,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;QAChB,OAAO,CAAC,IAAI,CAAC;YACX,GAAG,IAAI,CAAC,MAAM;YACd,IAAI,EAAE,YAAY;SACnB,CAAC,CAAC;IACL,CAAC;IAED,MAAM,OAAO,GAAG;QACd,GAAG,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC;QAC5B,GAAG,CAAC,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAC;QACxB,GAAG,CAAC,IAAI,CAAC,YAAY,IAAI,EAAE,CAAC;KAC7B,CAAC;IAEF,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,EAAE,QAAQ,IAAI,EAAE,CAAC;IAEhD,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,EAAE,cAAc,IAAI,EAAE,CAAC;IAEtD,MAAM,QAAQ,GAAG,IAAI,CAAC,SAAS,IAAI,EAAE,CAAC;IACtC,MAAM,oBAAoB,GAAG,IAAI,CAAC,uBAAuB,CAAC;IAE1D,+DAA+D;IAC/D,MAAM,YAAY,GAAG,IAAI,CAAC,YAAY,IAAI,EAAE,CAA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ACZ,CAAC;AAED,SAAS,UAAU;IACjB,OAAO,GAAG,IAAI,CAAC,GAAG,EAAE,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;AACpE,CAAC;AAED,SAAS,WAAW;IAClB,OAAO,QAAQ,IAAI,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC;AAC3D,CAAC","sourcesContent":["import {\n DashboardData,\n BannerItem,\n AppItem,\n ArticleItem,\n ProductUpdateItem,\n BannerType,\n AppGroup,\n} from \"../types\";\n\nexport function adaptDashboardData(rawData: any): DashboardData {\n const data = rawData.data || rawData;\n\n const banners = [];\n if (data.banner) {\n banners.push({\n ...data.banner,\n type: \"top_banner\",\n });\n }\n\n const allApps = [\n ...(data.partner_list || []),\n ...(data.seo_apps || []),\n ...(data.integrations || []),\n ];\n\n const articles = data.whats_new?.articles || [];\n\n const whatsNew = data.whats_new?.product_update || [];\n\n const growApps = data.grow_apps || [];\n const growAppsDisplayLimit = data.grow_apps_display_limit;\n \n // Keep the raw integrations data for the Integration component\n const integrations = data.integrations || [];\n\n return {\n banners: adaptBanners(banners),\n apps: adaptApps(allApps),\n articles: adaptArticles(articles),\n whatsNew: adaptProductUpdates(whatsNew),\n grow_apps: growApps,\n grow_apps_display_limit: growAppsDisplayLimit,\n integrations: integrations, // Add raw integrations\n };\n}\n\nfunction adaptBanners(banners: any[]): BannerItem[] {\n if (!Array.isArray(banners)) return [];\n\n return banners.map((banner) => adaptBanner(banner)).filter(Boolean);\n}\n\nexport function adaptBanner(apiData: any): BannerItem {\n const type = determineBannerType(apiData);\n\n return {\n id: apiData.id || generateId(),\n type,\n title: apiData.title || \"\",\n description:\n apiData.description || apiData.content || apiData.subtitle || \"\",\n image: apiData.image || apiData.image_url || apiData.imageUrl,\n icon: apiData.icon || apiData.icon_url || apiData.iconUrl,\n link:\n apiData.link ||\n apiData.button_url ||\n apiData.buttonUrl ||\n apiData.url ||\n \"#\",\n linkText:\n apiData.linkText ||\n apiData.button_text ||\n apiData.buttonText ||\n \"Learn More\",\n openType: apiData.openType || apiData.open_type || \"new_tab\",\n style: {\n backgroundColor:\n apiData.background_color || apiData.backgroundColor || apiData.bgColor,\n textColor: apiData.text_color || apiData.textColor,\n buttonColor: apiData.button_color || apiData.buttonColor,\n buttonTextColor: apiData.button_text_color || apiData.buttonTextColor,\n },\n priority: apiData.priority || apiData.order || 0,\n isActive:\n apiData.isActive !== undefined\n ? apiData.isActive\n : apiData.active !== undefined\n ? apiData.active\n : apiData.enabled !== undefined\n ? apiData.enabled\n : true,\n };\n}\n\nfunction determineBannerType(apiData: any): BannerType {\n if (apiData.type) {\n const typeMap: Record<string, BannerType> = {\n popup: \"popup\",\n pop_up: \"popup\",\n modal: \"popup\",\n top: \"top_banner\",\n top_banner: \"top_banner\",\n header: \"top_banner\",\n footer: \"footer_banner\",\n footer_banner: \"footer_banner\",\n bottom: \"footer_banner\",\n };\n\n const normalizedType = apiData.type.toLowerCase().replace(/-/g, \"_\");\n return typeMap[normalizedType] || \"top_banner\";\n }\n\n if (apiData.position) {\n const positionMap: Record<string, BannerType> = {\n top: \"top_banner\",\n header: \"top_banner\",\n bottom: \"footer_banner\",\n footer: \"footer_banner\",\n center: \"popup\",\n modal: \"popup\",\n };\n\n const normalizedPosition = apiData.position.toLowerCase();\n return positionMap[normalizedPosition] || \"top_banner\";\n }\n\n return \"top_banner\";\n}\n\nfunction adaptApps(apps: any): Record<AppGroup, AppItem[]> {\n const result: Record<AppGroup, AppItem[]> = {\n grow_faster: [],\n integration: [],\n marketing: [],\n analytics: [],\n other: [],\n };\n\n if (Array.isArray(apps)) {\n const adaptedApps = apps.map((app) => adaptApp(app)).filter(Boolean);\n adaptedApps.forEach((app) => {\n const group = app.group || \"other\";\n if (result[group]) {\n result[group].push(app);\n }\n });\n } else if (typeof apps === \"object\") {\n Object.entries(apps).forEach(([key, value]) => {\n const group = normalizeAppGroup(key);\n if (Array.isArray(value)) {\n result[group] = value\n .map((app) => adaptApp(app, group))\n .filter(Boolean);\n }\n });\n }\n\n return result;\n}\n\nfunction normalizeAppGroup(group: string): AppGroup {\n const groupMap: Record<string, AppGroup> = {\n grow_faster: \"grow_faster\",\n growfaster: \"grow_faster\",\n \"grow-faster\": \"grow_faster\",\n integration: \"integration\",\n integrations: \"integration\",\n marketing: \"marketing\",\n analytics: \"analytics\",\n analysis: \"analytics\",\n };\n\n const normalized = group.toLowerCase().replace(/[\\s_-]/g, \"\");\n return groupMap[normalized] || \"other\";\n}\n\nexport function adaptApp(apiData: any, defaultGroup?: AppGroup): AppItem {\n const group =\n defaultGroup ||\n normalizeAppGroup(apiData.group || apiData.category || \"other\");\n\n return {\n id: apiData.id || generateId(),\n key:\n apiData.key ||\n apiData.slug ||\n apiData.name?.toLowerCase().replace(/\\s+/g, \"-\") ||\n generateKey(),\n title: apiData.title || apiData.name || \"\",\n description: apiData.description || apiData.subtitle || \"\",\n icon:\n apiData.icon || apiData.icon_url || apiData.iconUrl || apiData.logo || \"\",\n link:\n apiData.link || apiData.url || apiData.app_url || apiData.appUrl || \"#\",\n group,\n rating: apiData.rating || apiData.score,\n installs:\n apiData.installs || apiData.installations || apiData.install_count,\n price: apiData.price || apiData.pricing,\n featured: apiData.featured || apiData.is_featured || false,\n };\n}\n\nfunction adaptArticles(articles: any[]): ArticleItem[] {\n if (!Array.isArray(articles)) return [];\n\n return articles.map((article) => adaptArticle(article)).filter(Boolean);\n}\n\nexport function adaptArticle(apiData: any): ArticleItem {\n return {\n id: apiData.id || generateId(),\n title: apiData.title || apiData.headline || \"\",\n description:\n apiData.description || apiData.summary || apiData.excerpt || \"\",\n content: apiData.content || apiData.body || apiData.text,\n thumbnail:\n apiData.thumbnail ||\n apiData.image ||\n apiData.cover_image ||\n apiData.coverImage,\n imageUrl:\n apiData.imageUrl ||\n apiData.image_url ||\n apiData.image ||\n apiData.thumbnail,\n link:\n apiData.link ||\n apiData.url ||\n apiData.article_url ||\n apiData.button_url ||\n \"#\",\n author: apiData.author || apiData.author_name || apiData.authorName,\n publishedDate:\n apiData.published_date ||\n apiData.publishedDate ||\n apiData.date ||\n apiData.created_at,\n category: apiData.category || apiData.section || apiData.label,\n readTime: apiData.read_time || apiData.readTime || apiData.reading_time,\n tags: apiData.tags || apiData.keywords || [],\n buttonText: apiData.button_text || apiData.buttonText,\n };\n}\n\nfunction adaptProductUpdates(updates: any[]): ProductUpdateItem[] {\n if (!Array.isArray(updates)) return [];\n\n const mappedUpdates = updates\n .map((update) => adaptProductUpdate(update))\n .filter(Boolean);\n\n return mappedUpdates.sort((a, b) => {\n const posA = a.position ?? Number.MAX_VALUE;\n const posB = b.position ?? Number.MAX_VALUE;\n return posA - posB;\n });\n}\n\nexport function adaptProductUpdate(apiData: any): ProductUpdateItem {\n const description =\n apiData.description ||\n apiData.content?.text ||\n apiData.content ||\n apiData.summary ||\n \"\";\n\n const features =\n apiData.features || apiData.content?.list || apiData.new_features;\n\n // Handle new nested buttons structure\n const tryButton = apiData.buttons?.try;\n const learnButton = apiData.buttons?.learn;\n\n // Fallback to old format if new format not available\n const link =\n tryButton?.url ||\n learnButton?.url ||\n apiData.link ||\n apiData.button_try_url ||\n apiData.button_learn_url ||\n apiData.url ||\n apiData.release_notes_url;\n\n return {\n id: apiData.id || generateId(),\n title: apiData.title || apiData.name || \"\",\n description,\n version: apiData.version || apiData.release_version,\n releaseDate:\n apiData.version || // New: use version field for date display\n apiData.date_time ||\n apiData.release_date ||\n apiData.releaseDate ||\n apiData.date ||\n new Date().toISOString(),\n date_time: apiData.version || apiData.date_time, // New: prioritize version field\n features: adaptStringArray(features),\n improvements: adaptStringArray(\n apiData.improvements || apiData.enhancements,\n ),\n fixes: adaptStringArray(\n apiData.fixes || apiData.bug_fixes || apiData.bugFixes,\n ),\n link,\n imageUrl:\n apiData.image_url ||\n apiData.imageUrl ||\n apiData.image ||\n apiData.thumbnail,\n image_url: apiData.image_url,\n type: determineUpdateType(apiData),\n position: apiData.position || apiData.order || apiData.priority,\n // Handle new button structure with fallbacks\n button_try_it_now: tryButton?.text || apiData.button_try_it_now || \"Try it now\",\n button_try_url: tryButton?.url || apiData.button_try_url,\n button_learn_more: learnButton?.text || apiData.button_learn_more || \"Learn more\", \n button_learn_url: learnButton?.url || apiData.button_learn_url,\n content: apiData.content\n ? {\n text: apiData.content.text || apiData.content,\n }\n : undefined,\n };\n}\n\nfunction determineUpdateType(apiData: any): \"major\" | \"minor\" | \"patch\" {\n if (apiData.type) {\n const type = apiData.type.toLowerCase();\n if (type.includes(\"major\")) return \"major\";\n if (type.includes(\"minor\")) return \"minor\";\n if (type.includes(\"patch\")) return \"patch\";\n }\n\n if (apiData.version) {\n const version = apiData.version.toString();\n const parts = version.split(\".\");\n if (parts.length >= 3) {\n const [, minor, patch] = parts;\n if (patch !== \"0\") return \"patch\";\n if (minor !== \"0\") return \"minor\";\n return \"major\";\n }\n }\n\n return \"minor\";\n}\n\nfunction adaptStringArray(data: any): string[] {\n if (Array.isArray(data)) {\n return data.filter((item) => typeof item === \"string\");\n }\n\n if (typeof data === \"string\") {\n return data\n .split(/[,;|\\n]/)\n .map((s) => s.trim())\n .filter(Boolean);\n }\n\n return [];\n}\n\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nfunction generateKey(): string {\n return `item-${Math.random().toString(36).substr(2, 9)}`;\n}\n"]}