@atomic-solutions/woocommerce-react 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,1712 @@
1
+ 'use strict';
2
+
3
+ var react = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
5
+ var woocommerceUtils = require('@atomic-solutions/woocommerce-utils');
6
+ var reactQuery = require('@tanstack/react-query');
7
+
8
+ // src/provider/WooCommerceProvider.tsx
9
+ var EventContext = react.createContext(null);
10
+ var useEventEmitter = () => {
11
+ return react.useContext(EventContext);
12
+ };
13
+ var WooCommerceContext = react.createContext(null);
14
+ var WooCommerceProvider = ({
15
+ client,
16
+ queryKeys,
17
+ onEvent,
18
+ children
19
+ }) => {
20
+ const contextValue = react.useMemo(() => ({ client, queryKeys }), [client, queryKeys]);
21
+ return /* @__PURE__ */ jsxRuntime.jsx(WooCommerceContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsx(EventContext.Provider, { value: onEvent ?? null, children }) });
22
+ };
23
+
24
+ // src/guardrails/storeValidator.ts
25
+ function normalizeStoreUrl(url) {
26
+ let normalized = url.trim();
27
+ if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) {
28
+ normalized = `https://${normalized}`;
29
+ }
30
+ normalized = normalized.replace(/\/+$/, "");
31
+ normalized = normalized.replace(/\/wp-json\/?$/, "");
32
+ return `${normalized}/wp-json`;
33
+ }
34
+ function getBaseUrl(normalizedUrl) {
35
+ return normalizedUrl.replace(/\/wp-json\/?$/, "");
36
+ }
37
+ async function validateWooCommerceStore(url, options = {}) {
38
+ const { timeout = 1e4, allowLocalhost = process.env.NODE_ENV !== "production" } = options;
39
+ try {
40
+ const normalizedUrl = normalizeStoreUrl(url);
41
+ const baseUrl = getBaseUrl(normalizedUrl);
42
+ const isLocalhost = baseUrl.includes("localhost") || baseUrl.includes("127.0.0.1");
43
+ if (isLocalhost && !allowLocalhost) {
44
+ return {
45
+ valid: false,
46
+ error: "Localhost URLs are not allowed in production"
47
+ };
48
+ }
49
+ const storeApiUrl = `${normalizedUrl}/wc/store/v1`;
50
+ const controller = new AbortController();
51
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
52
+ let response;
53
+ try {
54
+ response = await fetch(storeApiUrl, {
55
+ method: "GET",
56
+ headers: {
57
+ "User-Agent": "@atomic-solutions/react-native-woocommerce",
58
+ Accept: "application/json"
59
+ },
60
+ signal: controller.signal
61
+ });
62
+ } finally {
63
+ clearTimeout(timeoutId);
64
+ }
65
+ if (response.status === 404) {
66
+ return {
67
+ valid: false,
68
+ error: "WooCommerce Store API not found. Ensure WooCommerce is installed and REST API is enabled."
69
+ };
70
+ }
71
+ if (response.status === 401 || response.status === 403) {
72
+ return {
73
+ valid: false,
74
+ error: "Access denied. Check that the REST API is publicly accessible for the Store API."
75
+ };
76
+ }
77
+ if (!response.ok) {
78
+ return {
79
+ valid: false,
80
+ error: `Unexpected response: ${response.status} ${response.statusText}`
81
+ };
82
+ }
83
+ let storeName;
84
+ let wcVersion;
85
+ try {
86
+ const rootResponse = await fetch(normalizedUrl, {
87
+ method: "GET",
88
+ headers: {
89
+ Accept: "application/json"
90
+ }
91
+ });
92
+ if (rootResponse.ok) {
93
+ const rootData = await rootResponse.json();
94
+ storeName = rootData.name;
95
+ if (rootData.namespaces) {
96
+ const hasWcNamespace = rootData.namespaces.some(
97
+ (ns) => ns.startsWith("wc/") || ns === "wc"
98
+ );
99
+ if (!hasWcNamespace) {
100
+ return {
101
+ valid: false,
102
+ error: "WooCommerce REST API namespace not found. Is WooCommerce installed?"
103
+ };
104
+ }
105
+ }
106
+ }
107
+ } catch {
108
+ }
109
+ return {
110
+ valid: true,
111
+ storeName: storeName || "WooCommerce Store",
112
+ storeUrl: normalizedUrl,
113
+ wcVersion
114
+ };
115
+ } catch (error) {
116
+ if (error instanceof Error) {
117
+ if (error.name === "AbortError") {
118
+ return {
119
+ valid: false,
120
+ error: `Connection timed out after ${timeout}ms`
121
+ };
122
+ }
123
+ if (error.message.includes("Network request failed")) {
124
+ return {
125
+ valid: false,
126
+ error: "Unable to connect to the store. Check the URL and your internet connection."
127
+ };
128
+ }
129
+ return {
130
+ valid: false,
131
+ error: error.message
132
+ };
133
+ }
134
+ return {
135
+ valid: false,
136
+ error: "An unexpected error occurred while validating the store"
137
+ };
138
+ }
139
+ }
140
+ function isValidStoreUrlFormat(url) {
141
+ if (!url || typeof url !== "string") {
142
+ return false;
143
+ }
144
+ const trimmed = url.trim();
145
+ if (trimmed.length === 0) {
146
+ return false;
147
+ }
148
+ try {
149
+ const normalized = normalizeStoreUrl(trimmed);
150
+ new URL(normalized);
151
+ return true;
152
+ } catch {
153
+ return false;
154
+ }
155
+ }
156
+
157
+ // src/guardrails/rateLimiter.ts
158
+ var DEFAULT_CONFIG = {
159
+ requestsPerSecond: 10,
160
+ requestsPerMinute: 60,
161
+ burstLimit: 20
162
+ };
163
+ var RateLimiter = class {
164
+ constructor(config = {}) {
165
+ // tokens per millisecond
166
+ this.queue = [];
167
+ this.isProcessing = false;
168
+ const mergedConfig = { ...DEFAULT_CONFIG, ...config };
169
+ this.maxTokens = mergedConfig.burstLimit;
170
+ this.tokens = this.maxTokens;
171
+ this.refillRate = mergedConfig.requestsPerSecond / 1e3;
172
+ this.lastRefill = Date.now();
173
+ }
174
+ /**
175
+ * Refills tokens based on elapsed time
176
+ */
177
+ refill() {
178
+ const now = Date.now();
179
+ const elapsed = now - this.lastRefill;
180
+ const tokensToAdd = elapsed * this.refillRate;
181
+ this.tokens = Math.min(this.maxTokens, this.tokens + tokensToAdd);
182
+ this.lastRefill = now;
183
+ }
184
+ /**
185
+ * Process queued requests
186
+ */
187
+ async processQueue() {
188
+ if (this.isProcessing) {
189
+ return;
190
+ }
191
+ this.isProcessing = true;
192
+ while (this.queue.length > 0) {
193
+ this.refill();
194
+ if (this.tokens >= 1) {
195
+ this.tokens -= 1;
196
+ const request = this.queue.shift();
197
+ request?.resolve();
198
+ } else {
199
+ const waitTime = Math.ceil((1 - this.tokens) / this.refillRate);
200
+ await this.sleep(waitTime);
201
+ }
202
+ }
203
+ this.isProcessing = false;
204
+ }
205
+ /**
206
+ * Sleep for specified milliseconds
207
+ */
208
+ sleep(ms) {
209
+ return new Promise((resolve) => setTimeout(resolve, ms));
210
+ }
211
+ /**
212
+ * Acquire a token before making a request
213
+ * Returns immediately if tokens available, otherwise queues the request
214
+ *
215
+ * @returns Promise that resolves when request can proceed
216
+ */
217
+ acquire() {
218
+ return new Promise((resolve, reject) => {
219
+ this.refill();
220
+ if (this.tokens >= 1) {
221
+ this.tokens -= 1;
222
+ resolve();
223
+ } else {
224
+ this.queue.push({ resolve, reject });
225
+ this.processQueue();
226
+ }
227
+ });
228
+ }
229
+ /**
230
+ * Try to acquire a token without waiting
231
+ *
232
+ * @returns true if token was acquired, false if rate limited
233
+ */
234
+ tryAcquire() {
235
+ this.refill();
236
+ if (this.tokens >= 1) {
237
+ this.tokens -= 1;
238
+ return true;
239
+ }
240
+ return false;
241
+ }
242
+ /**
243
+ * Get current number of available tokens
244
+ */
245
+ getAvailableTokens() {
246
+ this.refill();
247
+ return Math.floor(this.tokens);
248
+ }
249
+ /**
250
+ * Get number of queued requests
251
+ */
252
+ getQueueLength() {
253
+ return this.queue.length;
254
+ }
255
+ /**
256
+ * Clear all queued requests (rejects them)
257
+ */
258
+ clearQueue() {
259
+ while (this.queue.length > 0) {
260
+ const request = this.queue.shift();
261
+ request?.reject(new Error("Rate limiter queue cleared"));
262
+ }
263
+ }
264
+ /**
265
+ * Reset the rate limiter to initial state
266
+ */
267
+ reset() {
268
+ this.clearQueue();
269
+ this.tokens = this.maxTokens;
270
+ this.lastRefill = Date.now();
271
+ }
272
+ };
273
+ var globalRateLimiter = null;
274
+ function getGlobalRateLimiter(config) {
275
+ if (!globalRateLimiter) {
276
+ globalRateLimiter = new RateLimiter(config);
277
+ }
278
+ return globalRateLimiter;
279
+ }
280
+ function configureGlobalRateLimiter(config) {
281
+ if (globalRateLimiter) {
282
+ globalRateLimiter.clearQueue();
283
+ }
284
+ globalRateLimiter = new RateLimiter(config);
285
+ }
286
+ function resetGlobalRateLimiter() {
287
+ globalRateLimiter?.clearQueue();
288
+ globalRateLimiter = null;
289
+ }
290
+
291
+ // src/provider/types.ts
292
+ var DEFAULT_STORE_CONFIG = {
293
+ features: {
294
+ auth: false,
295
+ wishlist: false,
296
+ reviews: true,
297
+ search: true,
298
+ categories: true
299
+ },
300
+ locale: {
301
+ localeTag: "en-US",
302
+ currency: "USD",
303
+ currencyPosition: "before",
304
+ thousandsSeparator: ",",
305
+ decimalSeparator: ".",
306
+ decimals: 2
307
+ },
308
+ guardrails: {
309
+ validateStore: true,
310
+ rateLimit: {
311
+ requestsPerMinute: 60,
312
+ requestsPerSecond: 10,
313
+ burstLimit: 20
314
+ }
315
+ },
316
+ debug: process.env.NODE_ENV !== "production"
317
+ };
318
+ var WooCommerceStoreContext = react.createContext(null);
319
+ WooCommerceStoreContext.displayName = "WooCommerceStoreContext";
320
+ var PACKAGE_VERSION = "0.1.0";
321
+ function createCartHeadersAdapter() {
322
+ let headers = {};
323
+ return {
324
+ get: async () => headers,
325
+ save: async (newHeaders) => {
326
+ headers = { ...headers, ...newHeaders };
327
+ },
328
+ clear: async () => {
329
+ headers = {};
330
+ }
331
+ };
332
+ }
333
+ function WooCommerceStoreProvider({
334
+ config,
335
+ queryKeys,
336
+ children,
337
+ skipValidation = false,
338
+ loadingFallback = null,
339
+ errorFallback
340
+ }) {
341
+ const [isValidating, setIsValidating] = react.useState(!skipValidation);
342
+ const [isValidated, setIsValidated] = react.useState(skipValidation);
343
+ const [validationResult, setValidationResult] = react.useState(
344
+ skipValidation ? { valid: true, storeUrl: normalizeStoreUrl(config.storeUrl) } : void 0
345
+ );
346
+ const [validationError, setValidationError] = react.useState();
347
+ const mergedConfig = react.useMemo(
348
+ () => ({
349
+ ...config,
350
+ features: { ...DEFAULT_STORE_CONFIG.features, ...config.features },
351
+ locale: { ...DEFAULT_STORE_CONFIG.locale, ...config.locale },
352
+ guardrails: { ...DEFAULT_STORE_CONFIG.guardrails, ...config.guardrails },
353
+ debug: config.debug ?? DEFAULT_STORE_CONFIG.debug
354
+ }),
355
+ [config]
356
+ );
357
+ react.useEffect(() => {
358
+ if (mergedConfig.guardrails.rateLimit) {
359
+ configureGlobalRateLimiter(mergedConfig.guardrails.rateLimit);
360
+ }
361
+ }, [mergedConfig.guardrails.rateLimit]);
362
+ const cartHeadersAdapter = react.useRef(createCartHeadersAdapter());
363
+ const client = react.useMemo(() => {
364
+ const normalizedUrl = normalizeStoreUrl(config.storeUrl);
365
+ return woocommerceUtils.createClient({
366
+ baseURL: normalizedUrl,
367
+ storeApiVersion: "v1",
368
+ cartHeaders: cartHeadersAdapter.current,
369
+ validationMode: "warn",
370
+ debug: mergedConfig.debug,
371
+ headers: {
372
+ "User-Agent": `@atomic-solutions/react-native-woocommerce/${PACKAGE_VERSION}`,
373
+ "X-WC-Client": "atomic-woocommerce",
374
+ "X-WC-Client-Version": PACKAGE_VERSION
375
+ },
376
+ onRequest: async (requestConfig) => {
377
+ const rateLimiter = getGlobalRateLimiter();
378
+ await rateLimiter.acquire();
379
+ return requestConfig;
380
+ },
381
+ onError: (error) => {
382
+ if (mergedConfig.debug) {
383
+ console.error("[WooCommerceStore] API Error:", error);
384
+ }
385
+ }
386
+ });
387
+ }, [config.storeUrl, mergedConfig.debug]);
388
+ const validateStore = react.useCallback(async () => {
389
+ if (skipValidation) {
390
+ return;
391
+ }
392
+ setIsValidating(true);
393
+ setValidationError(void 0);
394
+ try {
395
+ const result = await validateWooCommerceStore(config.storeUrl, {
396
+ allowLocalhost: process.env.NODE_ENV !== "production"
397
+ });
398
+ setValidationResult(result);
399
+ if (result.valid) {
400
+ setIsValidated(true);
401
+ setValidationError(void 0);
402
+ if (mergedConfig.debug) {
403
+ console.log("[WooCommerceStore] Connected to:", result.storeName);
404
+ }
405
+ } else {
406
+ setIsValidated(false);
407
+ setValidationError(result.error);
408
+ if (mergedConfig.debug) {
409
+ console.warn("[WooCommerceStore] Validation failed:", result.error);
410
+ }
411
+ }
412
+ } catch (error) {
413
+ const errorMessage = error instanceof Error ? error.message : "Unknown error";
414
+ setValidationError(errorMessage);
415
+ setIsValidated(false);
416
+ } finally {
417
+ setIsValidating(false);
418
+ }
419
+ }, [config.storeUrl, skipValidation, mergedConfig.debug]);
420
+ react.useEffect(() => {
421
+ if (mergedConfig.guardrails.validateStore) {
422
+ validateStore();
423
+ } else {
424
+ setIsValidated(true);
425
+ setIsValidating(false);
426
+ }
427
+ }, [validateStore, mergedConfig.guardrails.validateStore]);
428
+ const contextValue = react.useMemo(
429
+ () => ({
430
+ config: mergedConfig,
431
+ isValidated,
432
+ isValidating,
433
+ validationError,
434
+ validationResult,
435
+ revalidate: validateStore
436
+ }),
437
+ [mergedConfig, isValidated, isValidating, validationError, validationResult, validateStore]
438
+ );
439
+ if (isValidating && loadingFallback) {
440
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: loadingFallback });
441
+ }
442
+ if (validationError && errorFallback) {
443
+ return /* @__PURE__ */ jsxRuntime.jsx(jsxRuntime.Fragment, { children: errorFallback(validationError, validateStore) });
444
+ }
445
+ return /* @__PURE__ */ jsxRuntime.jsx(WooCommerceStoreContext.Provider, { value: contextValue, children: /* @__PURE__ */ jsxRuntime.jsx(WooCommerceProvider, { client, queryKeys, onEvent: config.onEvent, children }) });
446
+ }
447
+ var useWooCommerceClient = () => {
448
+ const context = react.useContext(WooCommerceContext);
449
+ if (!context) {
450
+ throw new Error(
451
+ "useWooCommerceClient must be used within WooCommerceProvider. Wrap your app with <WooCommerceProvider client={client} queryKeys={queryKeys}>."
452
+ );
453
+ }
454
+ return context.client;
455
+ };
456
+ var useWooCommerceQueryKeys = () => {
457
+ const context = react.useContext(WooCommerceContext);
458
+ if (!context) {
459
+ throw new Error(
460
+ "useWooCommerceQueryKeys must be used within WooCommerceProvider. Wrap your app with <WooCommerceProvider client={client} queryKeys={queryKeys}>."
461
+ );
462
+ }
463
+ return context.queryKeys;
464
+ };
465
+
466
+ // src/constants/stale-times.ts
467
+ var STALE_TIME_SHORT = 60 * 1e3;
468
+ var STALE_TIME_LONG = 60 * 60 * 1e3;
469
+ var STALE_TIME_NONE = 0;
470
+ var StaleTimes = {
471
+ /** Cart data - always fresh */
472
+ cart: STALE_TIME_NONE,
473
+ /** Checkout data - always fresh */
474
+ checkout: STALE_TIME_NONE,
475
+ /** Product list - 1 minute */
476
+ products: STALE_TIME_SHORT,
477
+ /** Product detail - 1 minute */
478
+ product: STALE_TIME_SHORT,
479
+ /** Product categories - always fresh */
480
+ categories: STALE_TIME_NONE,
481
+ /** Orders - always fresh */
482
+ orders: STALE_TIME_NONE,
483
+ /** Default for infinite queries - 1 hour */
484
+ infinite: STALE_TIME_LONG
485
+ };
486
+ var useInfiniteWooQuery = ({
487
+ queryKey,
488
+ queryFn,
489
+ params,
490
+ perPage = 10,
491
+ staleTime = StaleTimes.infinite,
492
+ enabled
493
+ }) => {
494
+ const query = reactQuery.useInfiniteQuery({
495
+ queryKey,
496
+ queryFn: ({ pageParam }) => queryFn({
497
+ per_page: perPage,
498
+ ...params,
499
+ page: pageParam
500
+ }),
501
+ initialPageParam: 1,
502
+ getNextPageParam: (lastPage) => lastPage.pagination.nextPage,
503
+ getPreviousPageParam: (firstPage) => firstPage.pagination.prevPage,
504
+ staleTime,
505
+ enabled
506
+ });
507
+ const flatData = query.data?.pages.flatMap((page) => page.data) ?? [];
508
+ return {
509
+ ...query,
510
+ data: flatData
511
+ // Override data with flattened array
512
+ };
513
+ };
514
+
515
+ // src/hooks/products.ts
516
+ var useProducts = (params) => {
517
+ const client = useWooCommerceClient();
518
+ const queryKeys = useWooCommerceQueryKeys();
519
+ return reactQuery.useQuery({
520
+ queryKey: queryKeys.products.list(params),
521
+ queryFn: () => client.products.list(params),
522
+ staleTime: StaleTimes.products
523
+ });
524
+ };
525
+ var useInfiniteProducts = (params) => {
526
+ const client = useWooCommerceClient();
527
+ const queryKeys = useWooCommerceQueryKeys();
528
+ return useInfiniteWooQuery({
529
+ queryKey: queryKeys.products.list(params),
530
+ queryFn: (p) => client.products.list({ ...p, page: p.page ?? 1 }),
531
+ params,
532
+ perPage: params?.per_page ?? 10
533
+ });
534
+ };
535
+ var useProduct = (id) => {
536
+ const client = useWooCommerceClient();
537
+ const queryKeys = useWooCommerceQueryKeys();
538
+ return reactQuery.useQuery({
539
+ queryKey: queryKeys.products.detail(id),
540
+ queryFn: () => client.products.get(id),
541
+ staleTime: StaleTimes.product
542
+ });
543
+ };
544
+ var useProductCategories = () => {
545
+ const client = useWooCommerceClient();
546
+ const queryKeys = useWooCommerceQueryKeys();
547
+ return reactQuery.useQuery({
548
+ queryKey: queryKeys.products.categories(),
549
+ queryFn: () => client.products.categories(),
550
+ staleTime: StaleTimes.categories
551
+ });
552
+ };
553
+ var groupBy = (fn, list) => {
554
+ return list.reduce(
555
+ (acc, item) => {
556
+ const key = fn(item);
557
+ if (!acc[key]) {
558
+ acc[key] = [];
559
+ }
560
+ acc[key].push(item);
561
+ return acc;
562
+ },
563
+ {}
564
+ );
565
+ };
566
+ var processCategoriesToTree = (data) => {
567
+ const rootCategories = data?.filter((item) => item.parent === 0);
568
+ const indexedData = groupBy((item) => String(item.parent), data ?? []);
569
+ const processCategory = (item) => ({
570
+ ...item,
571
+ subCategories: indexedData[item.id]?.map(processCategory)
572
+ });
573
+ return rootCategories?.map(processCategory) ?? [];
574
+ };
575
+ var useProductCategoryTree = () => {
576
+ const query = useProductCategories();
577
+ const flatData = query.data ?? [];
578
+ const treeData = processCategoriesToTree(flatData);
579
+ const findById = (id) => {
580
+ if (!id) return;
581
+ const numId = typeof id === "string" ? parseInt(id, 10) : id;
582
+ return flatData.find((item) => item.id === numId);
583
+ };
584
+ return {
585
+ ...query,
586
+ data: flatData,
587
+ treeData,
588
+ findById
589
+ };
590
+ };
591
+
592
+ // src/events/types.ts
593
+ function createSuccessEvent(type, data) {
594
+ return { type, status: "success", data };
595
+ }
596
+ function createErrorEvent(type, error) {
597
+ return { type, status: "error", error };
598
+ }
599
+
600
+ // src/hooks/cart.ts
601
+ var useCart = () => {
602
+ const client = useWooCommerceClient();
603
+ const queryKeys = useWooCommerceQueryKeys();
604
+ const query = reactQuery.useQuery({
605
+ queryKey: queryKeys.cart.details(),
606
+ queryFn: () => client.cart.get(),
607
+ staleTime: StaleTimes.cart
608
+ });
609
+ const cart = query.data;
610
+ const isInCart = (productId) => {
611
+ return cart?.items.some((item) => item.id === productId) ?? false;
612
+ };
613
+ const getCartItem = (productId) => {
614
+ return cart?.items.find((item) => item.id === productId);
615
+ };
616
+ const getQuantity = (productId) => {
617
+ return getCartItem(productId)?.quantity ?? 0;
618
+ };
619
+ return {
620
+ ...query,
621
+ isInCart,
622
+ getCartItem,
623
+ getQuantity
624
+ };
625
+ };
626
+ var useAddToCart = () => {
627
+ const client = useWooCommerceClient();
628
+ const queryKeys = useWooCommerceQueryKeys();
629
+ const queryClient = reactQuery.useQueryClient();
630
+ const emitEvent = useEventEmitter();
631
+ return reactQuery.useMutation({
632
+ mutationKey: queryKeys.cart.mutations.addItem(),
633
+ mutationFn: (input) => client.cart.addItem(input),
634
+ onSuccess: (cart, input) => {
635
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
636
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
637
+ const addedItem = cart.items.find((item) => item.id === input.id);
638
+ if (emitEvent && addedItem) {
639
+ emitEvent(createSuccessEvent("cart:item_added", { item: addedItem, cart }));
640
+ }
641
+ },
642
+ onError: (error) => {
643
+ if (emitEvent) {
644
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
645
+ code: "unknown_error",
646
+ message: error instanceof Error ? error.message : "Unknown error",
647
+ statusCode: 500,
648
+ url: "",
649
+ method: "POST",
650
+ originalCode: "unknown_error"
651
+ });
652
+ emitEvent(createErrorEvent("cart:item_added", wooError));
653
+ }
654
+ }
655
+ });
656
+ };
657
+ var useUpdateCartItem = () => {
658
+ const client = useWooCommerceClient();
659
+ const queryKeys = useWooCommerceQueryKeys();
660
+ const queryClient = reactQuery.useQueryClient();
661
+ const emitEvent = useEventEmitter();
662
+ return reactQuery.useMutation({
663
+ mutationKey: queryKeys.cart.mutations.updateItem(),
664
+ mutationFn: (input) => client.cart.updateItem(input),
665
+ onSuccess: (cart, input) => {
666
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
667
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
668
+ const updatedItem = cart.items.find((item) => item.key === input.key);
669
+ if (emitEvent && updatedItem) {
670
+ emitEvent(createSuccessEvent("cart:item_updated", { item: updatedItem, cart }));
671
+ }
672
+ },
673
+ onError: (error) => {
674
+ if (emitEvent) {
675
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
676
+ code: "unknown_error",
677
+ message: error instanceof Error ? error.message : "Unknown error",
678
+ statusCode: 500,
679
+ url: "",
680
+ method: "POST",
681
+ originalCode: "unknown_error"
682
+ });
683
+ emitEvent(createErrorEvent("cart:item_updated", wooError));
684
+ }
685
+ }
686
+ });
687
+ };
688
+ var useRemoveFromCart = () => {
689
+ const client = useWooCommerceClient();
690
+ const queryKeys = useWooCommerceQueryKeys();
691
+ const queryClient = reactQuery.useQueryClient();
692
+ const emitEvent = useEventEmitter();
693
+ return reactQuery.useMutation({
694
+ mutationKey: queryKeys.cart.mutations.removeItem(),
695
+ mutationFn: (input) => client.cart.removeItem(input),
696
+ onSuccess: (cart, input) => {
697
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
698
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
699
+ if (emitEvent) {
700
+ emitEvent(createSuccessEvent("cart:item_removed", { itemKey: input.key, cart }));
701
+ }
702
+ },
703
+ onError: (error) => {
704
+ if (emitEvent) {
705
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
706
+ code: "unknown_error",
707
+ message: error instanceof Error ? error.message : "Unknown error",
708
+ statusCode: 500,
709
+ url: "",
710
+ method: "POST",
711
+ originalCode: "unknown_error"
712
+ });
713
+ emitEvent(createErrorEvent("cart:item_removed", wooError));
714
+ }
715
+ }
716
+ });
717
+ };
718
+ var useApplyCoupon = () => {
719
+ const client = useWooCommerceClient();
720
+ const queryKeys = useWooCommerceQueryKeys();
721
+ const queryClient = reactQuery.useQueryClient();
722
+ const emitEvent = useEventEmitter();
723
+ return reactQuery.useMutation({
724
+ mutationKey: queryKeys.cart.mutations.applyCoupon(),
725
+ mutationFn: (input) => client.cart.applyCoupon(input),
726
+ onSuccess: (cart, input) => {
727
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
728
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
729
+ if (emitEvent) {
730
+ emitEvent(createSuccessEvent("cart:coupon_applied", { code: input.code, cart }));
731
+ }
732
+ },
733
+ onError: (error) => {
734
+ if (emitEvent) {
735
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
736
+ code: "unknown_error",
737
+ message: error instanceof Error ? error.message : "Unknown error",
738
+ statusCode: 500,
739
+ url: "",
740
+ method: "POST",
741
+ originalCode: "unknown_error"
742
+ });
743
+ emitEvent(createErrorEvent("cart:coupon_applied", wooError));
744
+ }
745
+ }
746
+ });
747
+ };
748
+ var useRemoveCoupon = () => {
749
+ const client = useWooCommerceClient();
750
+ const queryKeys = useWooCommerceQueryKeys();
751
+ const queryClient = reactQuery.useQueryClient();
752
+ const emitEvent = useEventEmitter();
753
+ return reactQuery.useMutation({
754
+ mutationKey: queryKeys.cart.mutations.removeCoupon(),
755
+ mutationFn: (input) => client.cart.removeCoupon(input),
756
+ onSuccess: (cart, input) => {
757
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
758
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
759
+ if (emitEvent) {
760
+ emitEvent(createSuccessEvent("cart:coupon_removed", { code: input.code, cart }));
761
+ }
762
+ },
763
+ onError: (error) => {
764
+ if (emitEvent) {
765
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
766
+ code: "unknown_error",
767
+ message: error instanceof Error ? error.message : "Unknown error",
768
+ statusCode: 500,
769
+ url: "",
770
+ method: "POST",
771
+ originalCode: "unknown_error"
772
+ });
773
+ emitEvent(createErrorEvent("cart:coupon_removed", wooError));
774
+ }
775
+ }
776
+ });
777
+ };
778
+ var useUpdateCustomer = () => {
779
+ const client = useWooCommerceClient();
780
+ const queryKeys = useWooCommerceQueryKeys();
781
+ const queryClient = reactQuery.useQueryClient();
782
+ const emitEvent = useEventEmitter();
783
+ return reactQuery.useMutation({
784
+ mutationKey: queryKeys.cart.mutations.updateCustomer(),
785
+ mutationFn: (input) => client.cart.updateCustomer(input),
786
+ onSuccess: (cart) => {
787
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
788
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
789
+ if (emitEvent) {
790
+ emitEvent(createSuccessEvent("cart:customer_updated", { cart }));
791
+ }
792
+ },
793
+ onError: (error) => {
794
+ if (emitEvent) {
795
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
796
+ code: "unknown_error",
797
+ message: error instanceof Error ? error.message : "Unknown error",
798
+ statusCode: 500,
799
+ url: "",
800
+ method: "POST",
801
+ originalCode: "unknown_error"
802
+ });
803
+ emitEvent(createErrorEvent("cart:customer_updated", wooError));
804
+ }
805
+ }
806
+ });
807
+ };
808
+ var useSelectShippingRate = () => {
809
+ const client = useWooCommerceClient();
810
+ const queryKeys = useWooCommerceQueryKeys();
811
+ const queryClient = reactQuery.useQueryClient();
812
+ const emitEvent = useEventEmitter();
813
+ return reactQuery.useMutation({
814
+ mutationKey: queryKeys.cart.mutations.selectShippingRate(),
815
+ mutationFn: (input) => client.cart.selectShippingRate(input),
816
+ onSuccess: (cart) => {
817
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
818
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
819
+ if (emitEvent) {
820
+ emitEvent(createSuccessEvent("cart:shipping_selected", { cart }));
821
+ }
822
+ },
823
+ onError: (error) => {
824
+ if (emitEvent) {
825
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
826
+ code: "unknown_error",
827
+ message: error instanceof Error ? error.message : "Unknown error",
828
+ statusCode: 500,
829
+ url: "",
830
+ method: "POST",
831
+ originalCode: "unknown_error"
832
+ });
833
+ emitEvent(createErrorEvent("cart:shipping_selected", wooError));
834
+ }
835
+ }
836
+ });
837
+ };
838
+ var useCheckout = () => {
839
+ const client = useWooCommerceClient();
840
+ const queryKeys = useWooCommerceQueryKeys();
841
+ return reactQuery.useQuery({
842
+ queryKey: queryKeys.checkout.details(),
843
+ queryFn: () => client.checkout.get(),
844
+ staleTime: StaleTimes.checkout
845
+ });
846
+ };
847
+ var useProcessCheckout = () => {
848
+ const client = useWooCommerceClient();
849
+ const queryKeys = useWooCommerceQueryKeys();
850
+ const queryClient = reactQuery.useQueryClient();
851
+ const emitEvent = useEventEmitter();
852
+ return reactQuery.useMutation({
853
+ mutationKey: queryKeys.checkout.mutations.process(),
854
+ mutationFn: (input) => client.checkout.process(input),
855
+ onSuccess: (checkout) => {
856
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
857
+ queryClient.invalidateQueries({ queryKey: queryKeys.checkout.all });
858
+ if (emitEvent) {
859
+ emitEvent(createSuccessEvent("checkout:processed", { checkout }));
860
+ }
861
+ },
862
+ onError: (error) => {
863
+ if (emitEvent) {
864
+ const wooError = error instanceof woocommerceUtils.WooCommerceApiError ? error : new woocommerceUtils.WooCommerceApiError({
865
+ code: "unknown_error",
866
+ message: error instanceof Error ? error.message : "Unknown error",
867
+ statusCode: 500,
868
+ url: "",
869
+ method: "POST",
870
+ originalCode: "unknown_error"
871
+ });
872
+ emitEvent(createErrorEvent("checkout:processed", wooError));
873
+ }
874
+ }
875
+ });
876
+ };
877
+ var useOrder = (input) => {
878
+ const client = useWooCommerceClient();
879
+ const queryKeys = useWooCommerceQueryKeys();
880
+ return reactQuery.useQuery({
881
+ queryKey: queryKeys.orders.detail(input.id, input.billing_email, input.key),
882
+ queryFn: () => client.orders.get(input),
883
+ staleTime: StaleTimes.orders
884
+ });
885
+ };
886
+
887
+ // src/hooks/queryKeys.ts
888
+ var createQueryKeys = (prefix = ["woocommerce"]) => ({
889
+ // All keys start with prefix
890
+ all: prefix,
891
+ // Products
892
+ products: {
893
+ all: [...prefix, "products"],
894
+ lists: () => [...prefix, "products", "list"],
895
+ list: (params) => [...prefix, "products", "list", params],
896
+ details: () => [...prefix, "products", "detail"],
897
+ detail: (id) => [...prefix, "products", "detail", id],
898
+ categories: () => [...prefix, "products", "categories"]
899
+ },
900
+ // Cart
901
+ cart: {
902
+ all: [...prefix, "cart"],
903
+ details: () => [...prefix, "cart", "details"],
904
+ // Mutation keys
905
+ mutations: {
906
+ addItem: () => [...prefix, "cart", "mutation", "addItem"],
907
+ updateItem: () => [...prefix, "cart", "mutation", "updateItem"],
908
+ removeItem: () => [...prefix, "cart", "mutation", "removeItem"],
909
+ applyCoupon: () => [...prefix, "cart", "mutation", "applyCoupon"],
910
+ removeCoupon: () => [...prefix, "cart", "mutation", "removeCoupon"],
911
+ updateCustomer: () => [...prefix, "cart", "mutation", "updateCustomer"],
912
+ selectShippingRate: () => [...prefix, "cart", "mutation", "selectShippingRate"]
913
+ }
914
+ },
915
+ // Checkout
916
+ checkout: {
917
+ all: [...prefix, "checkout"],
918
+ details: () => [...prefix, "checkout", "details"],
919
+ // Mutation keys
920
+ mutations: {
921
+ process: () => [...prefix, "checkout", "mutation", "process"]
922
+ }
923
+ },
924
+ // Orders
925
+ orders: {
926
+ all: [...prefix, "orders"],
927
+ lists: () => [...prefix, "orders", "list"],
928
+ list: (params) => [...prefix, "orders", "list", params],
929
+ details: () => [...prefix, "orders", "detail"],
930
+ detail: (id, billing_email, key) => [...prefix, "orders", "detail", id, billing_email, key].filter(Boolean)
931
+ }
932
+ });
933
+ function useStore() {
934
+ const context = react.useContext(WooCommerceStoreContext);
935
+ if (!context) {
936
+ throw new Error("useStore must be used within a WooCommerceStoreProvider");
937
+ }
938
+ return context;
939
+ }
940
+ function useStoreFeatures() {
941
+ const { config } = useStore();
942
+ return config.features;
943
+ }
944
+ function useStoreLocale() {
945
+ const { config } = useStore();
946
+ return config.locale;
947
+ }
948
+ var DEFAULT_THEME = {
949
+ primary: "#007AFF",
950
+ // iOS blue
951
+ secondary: "#5856D6",
952
+ // iOS purple
953
+ mode: "auto",
954
+ fonts: {
955
+ heading: void 0,
956
+ body: void 0
957
+ }
958
+ };
959
+ function useStoreTheme(options = {}) {
960
+ const { externalTheme } = options;
961
+ const storeContext = react.useContext(WooCommerceStoreContext);
962
+ const storeTheme = storeContext?.config?.theme;
963
+ const theme = react.useMemo(() => {
964
+ return {
965
+ primary: externalTheme?.primary ?? storeTheme?.primary ?? DEFAULT_THEME.primary,
966
+ secondary: externalTheme?.secondary ?? storeTheme?.secondary ?? DEFAULT_THEME.secondary,
967
+ mode: externalTheme?.mode ?? storeTheme?.mode ?? DEFAULT_THEME.mode,
968
+ fonts: {
969
+ heading: externalTheme?.fonts?.heading ?? storeTheme?.fonts?.heading ?? DEFAULT_THEME.fonts.heading,
970
+ body: externalTheme?.fonts?.body ?? storeTheme?.fonts?.body ?? DEFAULT_THEME.fonts.body
971
+ }
972
+ };
973
+ }, [externalTheme, storeTheme]);
974
+ return {
975
+ theme,
976
+ storeTheme,
977
+ hasExternalTheme: !!externalTheme
978
+ };
979
+ }
980
+
981
+ // src/utils/image.ts
982
+ var SIZE_SUFFIXES = {
983
+ thumbnail: "-150x150",
984
+ medium: "-300x300",
985
+ large: "-1024x1024",
986
+ full: ""
987
+ };
988
+ function getPrimaryImage(images) {
989
+ if (!images || images.length === 0) {
990
+ return void 0;
991
+ }
992
+ return images[0];
993
+ }
994
+ function getImageUrl(images, size = "full", fallback) {
995
+ const primary = getPrimaryImage(images);
996
+ if (!primary) {
997
+ return fallback;
998
+ }
999
+ return getSizedImageUrl(primary.src, size);
1000
+ }
1001
+ function getSizedImageUrl(url, size = "full") {
1002
+ if (!url || size === "full") {
1003
+ return url;
1004
+ }
1005
+ const hasSize = Object.values(SIZE_SUFFIXES).some((suffix2) => suffix2 && url.includes(suffix2));
1006
+ if (hasSize) {
1007
+ let result = url;
1008
+ Object.values(SIZE_SUFFIXES).forEach((suffix2) => {
1009
+ if (suffix2) {
1010
+ result = result.replace(suffix2, SIZE_SUFFIXES[size]);
1011
+ }
1012
+ });
1013
+ return result;
1014
+ }
1015
+ const suffix = SIZE_SUFFIXES[size];
1016
+ const lastDot = url.lastIndexOf(".");
1017
+ if (lastDot === -1) {
1018
+ return url;
1019
+ }
1020
+ return `${url.slice(0, lastDot)}${suffix}${url.slice(lastDot)}`;
1021
+ }
1022
+ function getAllImageUrls(images, size = "full") {
1023
+ if (!images || images.length === 0) {
1024
+ return [];
1025
+ }
1026
+ return images.map((img) => getSizedImageUrl(img.src, size));
1027
+ }
1028
+ var PLACEHOLDER_IMAGE_URL = "https://via.placeholder.com/300x300.png?text=No+Image";
1029
+ function getImageUrlOrPlaceholder(images, size = "medium") {
1030
+ return getImageUrl(images, size, PLACEHOLDER_IMAGE_URL) ?? PLACEHOLDER_IMAGE_URL;
1031
+ }
1032
+ async function preloadImage(_url) {
1033
+ return Promise.resolve();
1034
+ }
1035
+ async function preloadImages(urls) {
1036
+ await Promise.all(urls.map(preloadImage));
1037
+ }
1038
+
1039
+ // src/utils/price.ts
1040
+ var DEFAULT_LOCALE = {
1041
+ localeTag: "en-US",
1042
+ currency: "USD",
1043
+ currencyPosition: "before",
1044
+ thousandsSeparator: ",",
1045
+ decimalSeparator: ".",
1046
+ decimals: 2
1047
+ };
1048
+ var CURRENCY_SYMBOLS = {
1049
+ USD: "$",
1050
+ EUR: "\u20AC",
1051
+ GBP: "\xA3",
1052
+ CAD: "CA$",
1053
+ AUD: "A$",
1054
+ JPY: "\xA5",
1055
+ CNY: "\xA5",
1056
+ INR: "\u20B9",
1057
+ BRL: "R$",
1058
+ MXN: "MX$",
1059
+ RUB: "\u20BD",
1060
+ KRW: "\u20A9",
1061
+ CHF: "CHF",
1062
+ SEK: "kr",
1063
+ NOK: "kr",
1064
+ DKK: "kr",
1065
+ PLN: "z\u0142",
1066
+ TRY: "\u20BA",
1067
+ ZAR: "R",
1068
+ NZD: "NZ$",
1069
+ SGD: "S$",
1070
+ HKD: "HK$",
1071
+ THB: "\u0E3F",
1072
+ PHP: "\u20B1",
1073
+ // Balkans
1074
+ BAM: "KM",
1075
+ RSD: "din",
1076
+ HRK: "kn",
1077
+ MKD: "\u0434\u0435\u043D",
1078
+ BGN: "\u043B\u0432",
1079
+ RON: "lei"
1080
+ };
1081
+ function getCurrencySymbol(currencyCode) {
1082
+ return CURRENCY_SYMBOLS[currencyCode.toUpperCase()] ?? currencyCode;
1083
+ }
1084
+ function formatNumber(value, locale) {
1085
+ const fixed = value.toFixed(locale.decimals);
1086
+ const [integerPart, decimalPart] = fixed.split(".");
1087
+ const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, locale.thousandsSeparator);
1088
+ if (locale.decimals > 0 && decimalPart) {
1089
+ return `${formattedInteger}${locale.decimalSeparator}${decimalPart}`;
1090
+ }
1091
+ return formattedInteger;
1092
+ }
1093
+ function formatPrice(price, locale = {}) {
1094
+ const mergedLocale = { ...DEFAULT_LOCALE, ...locale };
1095
+ const numericPrice = typeof price === "string" ? parseFloat(price) : price;
1096
+ if (isNaN(numericPrice)) {
1097
+ return "";
1098
+ }
1099
+ const symbol = getCurrencySymbol(mergedLocale.currency);
1100
+ const formattedNumber = formatNumber(numericPrice, mergedLocale);
1101
+ if (mergedLocale.currencyPosition === "after") {
1102
+ return `${formattedNumber}${symbol}`;
1103
+ }
1104
+ return `${symbol}${formattedNumber}`;
1105
+ }
1106
+ function formatPriceRange(minPrice, maxPrice, locale = {}) {
1107
+ const min = typeof minPrice === "string" ? parseFloat(minPrice) : minPrice;
1108
+ const max = typeof maxPrice === "string" ? parseFloat(maxPrice) : maxPrice;
1109
+ if (isNaN(min) || isNaN(max)) {
1110
+ return "";
1111
+ }
1112
+ if (min === max) {
1113
+ return formatPrice(min, locale);
1114
+ }
1115
+ return `${formatPrice(min, locale)} - ${formatPrice(max, locale)}`;
1116
+ }
1117
+ function calculateDiscount(regularPrice, salePrice) {
1118
+ const regular = typeof regularPrice === "string" ? parseFloat(regularPrice) : regularPrice;
1119
+ const sale = typeof salePrice === "string" ? parseFloat(salePrice) : salePrice;
1120
+ if (isNaN(regular) || isNaN(sale) || regular <= 0 || sale >= regular) {
1121
+ return null;
1122
+ }
1123
+ return Math.round((regular - sale) / regular * 100);
1124
+ }
1125
+ function formatStoreApiPrice(priceInMinorUnits, currencyCode, locale = {}) {
1126
+ if (!priceInMinorUnits || !currencyCode) {
1127
+ return "-";
1128
+ }
1129
+ const cents = parseInt(priceInMinorUnits, 10);
1130
+ if (isNaN(cents)) {
1131
+ return "-";
1132
+ }
1133
+ const decimalPrice = cents / 100;
1134
+ return formatPrice(decimalPrice, { ...locale, currency: currencyCode });
1135
+ }
1136
+ function formatDiscountBadge(regularPrice, salePrice) {
1137
+ const discount = calculateDiscount(regularPrice, salePrice);
1138
+ return discount ? `-${discount}%` : null;
1139
+ }
1140
+ function formatStoreApiPriceIntl(priceInMinorUnits, currencyCode, localeTag = "en-US") {
1141
+ if (!priceInMinorUnits || !currencyCode) {
1142
+ return "-";
1143
+ }
1144
+ const cents = parseInt(priceInMinorUnits, 10);
1145
+ if (isNaN(cents)) {
1146
+ return "-";
1147
+ }
1148
+ const decimalPrice = cents / 100;
1149
+ try {
1150
+ const formatter = new Intl.NumberFormat(localeTag, {
1151
+ style: "currency",
1152
+ currency: currencyCode
1153
+ });
1154
+ return formatter.format(decimalPrice);
1155
+ } catch {
1156
+ return formatPrice(decimalPrice, { currency: currencyCode });
1157
+ }
1158
+ }
1159
+ function parseWooCommercePrice(priceString) {
1160
+ if (!priceString || typeof priceString !== "string") {
1161
+ return NaN;
1162
+ }
1163
+ const cleaned = priceString.replace(/[^\d.,-]/g, "").trim();
1164
+ if (cleaned.includes(",") && cleaned.includes(".")) {
1165
+ const lastComma = cleaned.lastIndexOf(",");
1166
+ const lastDot = cleaned.lastIndexOf(".");
1167
+ if (lastComma > lastDot) {
1168
+ return parseFloat(cleaned.replace(/\./g, "").replace(",", "."));
1169
+ } else {
1170
+ return parseFloat(cleaned.replace(/,/g, ""));
1171
+ }
1172
+ }
1173
+ if (cleaned.includes(",") && !cleaned.includes(".")) {
1174
+ const commaPos = cleaned.lastIndexOf(",");
1175
+ const afterComma = cleaned.length - commaPos - 1;
1176
+ if (afterComma <= 2) {
1177
+ return parseFloat(cleaned.replace(",", "."));
1178
+ }
1179
+ return parseFloat(cleaned.replace(/,/g, ""));
1180
+ }
1181
+ return parseFloat(cleaned.replace(/,/g, ""));
1182
+ }
1183
+
1184
+ // src/hooks/useProductsFeed.ts
1185
+ function useProductsFeed(options = {}) {
1186
+ const { params, imageSize = "medium" } = options;
1187
+ const storeContext = react.useContext(WooCommerceStoreContext);
1188
+ const storeConfig = storeContext?.config;
1189
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
1190
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
1191
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
1192
+ const {
1193
+ data: productsData,
1194
+ isLoading,
1195
+ isFetchingNextPage,
1196
+ error,
1197
+ hasNextPage = false,
1198
+ fetchNextPage,
1199
+ refetch,
1200
+ isRefetching
1201
+ } = useInfiniteProducts(params);
1202
+ const { treeData: categoryTree = [], findById } = useProductCategoryTree();
1203
+ const getProcessedImageUrl = react.useCallback(
1204
+ (images) => {
1205
+ const baseUrl = getImageUrl(images, imageSize, fallbackImageUrl);
1206
+ if (baseUrl && imageUrlTransformer) {
1207
+ return imageUrlTransformer(baseUrl, imageSize);
1208
+ }
1209
+ return baseUrl;
1210
+ },
1211
+ [imageSize, fallbackImageUrl, imageUrlTransformer]
1212
+ );
1213
+ const products = react.useMemo(() => {
1214
+ if (!productsData) return [];
1215
+ const productList = Array.isArray(productsData) ? productsData : [];
1216
+ return productList.map((product) => {
1217
+ const currencyCode = product.prices?.currency_code;
1218
+ return {
1219
+ id: product.id,
1220
+ name: product.name,
1221
+ slug: product.slug,
1222
+ permalink: product.permalink,
1223
+ imageUrl: getProcessedImageUrl(product.images),
1224
+ price: formatStoreApiPriceIntl(product.prices?.price, currencyCode, localeTag),
1225
+ regularPrice: formatStoreApiPriceIntl(
1226
+ product.prices?.regular_price,
1227
+ currencyCode,
1228
+ localeTag
1229
+ ),
1230
+ isOnSale: product.on_sale,
1231
+ canAddToCart: product.is_purchasable && product.is_in_stock,
1232
+ raw: product
1233
+ };
1234
+ });
1235
+ }, [productsData, localeTag, getProcessedImageUrl]);
1236
+ const activeCategory = react.useMemo(() => {
1237
+ if (!params?.category) return void 0;
1238
+ return findById(params.category);
1239
+ }, [params, findById]);
1240
+ const refresh = react.useCallback(async () => {
1241
+ await refetch();
1242
+ }, [refetch]);
1243
+ const totalCount = products.length;
1244
+ return {
1245
+ products,
1246
+ isLoading,
1247
+ isFetchingNextPage,
1248
+ error,
1249
+ hasNextPage,
1250
+ fetchNextPage,
1251
+ refresh,
1252
+ isRefreshing: isRefetching,
1253
+ activeCategory,
1254
+ categoryTree,
1255
+ findCategoryById: findById,
1256
+ totalCount
1257
+ };
1258
+ }
1259
+
1260
+ // src/utils/stock.ts
1261
+ var DEFAULT_CONFIG2 = {
1262
+ inStockText: "In Stock",
1263
+ outOfStockText: "Out of Stock",
1264
+ backorderText: "Available on Backorder",
1265
+ showQuantity: false,
1266
+ lowStockThreshold: 5,
1267
+ lowStockText: "Only {quantity} left"
1268
+ };
1269
+ function getStockStatusText(status, quantity, config = {}) {
1270
+ const mergedConfig = { ...DEFAULT_CONFIG2, ...config };
1271
+ switch (status) {
1272
+ case "instock":
1273
+ if (quantity !== null && quantity !== void 0 && quantity <= mergedConfig.lowStockThreshold && quantity > 0) {
1274
+ return mergedConfig.lowStockText.replace("{quantity}", quantity.toString());
1275
+ }
1276
+ if (mergedConfig.showQuantity && quantity !== null && quantity !== void 0) {
1277
+ return `${mergedConfig.inStockText} (${quantity})`;
1278
+ }
1279
+ return mergedConfig.inStockText;
1280
+ case "outofstock":
1281
+ return mergedConfig.outOfStockText;
1282
+ case "onbackorder":
1283
+ return mergedConfig.backorderText;
1284
+ default:
1285
+ return mergedConfig.inStockText;
1286
+ }
1287
+ }
1288
+ function isPurchasable(status, quantity, manageStock = true) {
1289
+ if (status === "outofstock") {
1290
+ return false;
1291
+ }
1292
+ if (status === "onbackorder") {
1293
+ return true;
1294
+ }
1295
+ if (manageStock && quantity !== null && quantity !== void 0) {
1296
+ return quantity > 0;
1297
+ }
1298
+ return true;
1299
+ }
1300
+ function getStockSeverity(status, quantity, lowStockThreshold = 5) {
1301
+ switch (status) {
1302
+ case "outofstock":
1303
+ return "error";
1304
+ case "onbackorder":
1305
+ return "info";
1306
+ case "instock":
1307
+ if (quantity !== null && quantity !== void 0 && quantity <= lowStockThreshold && quantity > 0) {
1308
+ return "warning";
1309
+ }
1310
+ return "success";
1311
+ default:
1312
+ return "info";
1313
+ }
1314
+ }
1315
+ function isLowStock(status, quantity, threshold = 5) {
1316
+ return status === "instock" && quantity !== null && quantity !== void 0 && quantity <= threshold && quantity > 0;
1317
+ }
1318
+ function getMaxAddToCartQuantity(status, stockQuantity, cartQuantity = 0, maxPurchaseQuantity) {
1319
+ if (status === "outofstock") {
1320
+ return 0;
1321
+ }
1322
+ if (status === "onbackorder") {
1323
+ return maxPurchaseQuantity ?? 999;
1324
+ }
1325
+ let maxQty = stockQuantity ?? 999;
1326
+ if (maxPurchaseQuantity && maxPurchaseQuantity < maxQty) {
1327
+ maxQty = maxPurchaseQuantity;
1328
+ }
1329
+ return Math.max(0, maxQty - cartQuantity);
1330
+ }
1331
+
1332
+ // src/hooks/useProductView.ts
1333
+ function useProductView(options) {
1334
+ const { productId, imageSize = "large", lowStockThreshold = 5 } = options;
1335
+ const storeContext = react.useContext(WooCommerceStoreContext);
1336
+ const storeConfig = storeContext?.config;
1337
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
1338
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
1339
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
1340
+ const [draftQuantity, setDraftQuantity] = react.useState(1);
1341
+ const { data: productData, isLoading, error, refetch } = useProduct(productId);
1342
+ const { data: cartData } = useCart();
1343
+ const addToCartMutation = useAddToCart();
1344
+ const removeFromCartMutation = useRemoveFromCart();
1345
+ const updateCartMutation = useUpdateCartItem();
1346
+ const processImageUrl = react.useCallback(
1347
+ (url) => {
1348
+ if (!url) return url;
1349
+ if (imageUrlTransformer) {
1350
+ return imageUrlTransformer(url, imageSize);
1351
+ }
1352
+ return url;
1353
+ },
1354
+ [imageUrlTransformer, imageSize]
1355
+ );
1356
+ const product = react.useMemo(() => {
1357
+ if (!productData) return null;
1358
+ const currencyCode = productData.prices?.currency_code;
1359
+ const stockStatus = productData.is_on_backorder ? "onbackorder" : productData.is_in_stock ? "instock" : "outofstock";
1360
+ const lowStockRemaining = productData.low_stock_remaining;
1361
+ const baseImageUrl = getImageUrl(productData.images, imageSize, fallbackImageUrl);
1362
+ const baseImageUrls = getAllImageUrls(productData.images, imageSize);
1363
+ return {
1364
+ id: productData.id,
1365
+ name: productData.name,
1366
+ slug: productData.slug,
1367
+ permalink: productData.permalink,
1368
+ description: productData.description,
1369
+ shortDescription: productData.short_description,
1370
+ sku: productData.sku,
1371
+ imageUrl: processImageUrl(baseImageUrl),
1372
+ imageUrls: baseImageUrls.map((url) => processImageUrl(url) ?? url),
1373
+ price: formatStoreApiPriceIntl(productData.prices?.price, currencyCode, localeTag),
1374
+ regularPrice: formatStoreApiPriceIntl(
1375
+ productData.prices?.regular_price,
1376
+ currencyCode,
1377
+ localeTag
1378
+ ),
1379
+ isOnSale: productData.on_sale,
1380
+ discountPercent: calculateDiscount(
1381
+ productData.prices?.regular_price ?? "0",
1382
+ productData.prices?.price ?? "0"
1383
+ ),
1384
+ discountBadge: productData.on_sale ? `-${calculateDiscount(
1385
+ productData.prices?.regular_price ?? "0",
1386
+ productData.prices?.price ?? "0"
1387
+ )}%` : null,
1388
+ stockStatusText: getStockStatusText(stockStatus, lowStockRemaining ?? void 0, {
1389
+ lowStockThreshold
1390
+ }),
1391
+ isPurchasable: isPurchasable(
1392
+ stockStatus,
1393
+ lowStockRemaining ?? void 0,
1394
+ productData.sold_individually
1395
+ ),
1396
+ isLowStock: isLowStock(stockStatus, lowStockRemaining ?? void 0, lowStockThreshold),
1397
+ maxQuantity: productData.add_to_cart?.maximum ?? 999,
1398
+ minQuantity: productData.add_to_cart?.minimum ?? 1,
1399
+ raw: productData
1400
+ };
1401
+ }, [productData, localeTag, fallbackImageUrl, imageSize, lowStockThreshold, processImageUrl]);
1402
+ const cartItem = react.useMemo(() => {
1403
+ return cartData?.items.find((item) => item.id === productId);
1404
+ }, [cartData?.items, productId]);
1405
+ const cartState = react.useMemo(
1406
+ () => ({
1407
+ isInCart: !!cartItem,
1408
+ quantityInCart: cartItem?.quantity ?? 0,
1409
+ cartItemKey: cartItem?.key ?? null,
1410
+ cartQuantityLimits: cartItem ? {
1411
+ minimum: cartItem.quantity_limits.minimum,
1412
+ maximum: cartItem.quantity_limits.maximum
1413
+ } : null
1414
+ }),
1415
+ [cartItem]
1416
+ );
1417
+ const addToCart = react.useCallback(async () => {
1418
+ await addToCartMutation.mutateAsync({
1419
+ id: productId,
1420
+ quantity: draftQuantity
1421
+ });
1422
+ setDraftQuantity(1);
1423
+ }, [addToCartMutation, productId, draftQuantity]);
1424
+ const removeFromCart = react.useCallback(async () => {
1425
+ if (!cartState.cartItemKey) return;
1426
+ await removeFromCartMutation.mutateAsync({
1427
+ key: cartState.cartItemKey
1428
+ });
1429
+ }, [removeFromCartMutation, cartState.cartItemKey]);
1430
+ const updateCartQuantity = react.useCallback(
1431
+ async (quantity) => {
1432
+ if (!cartState.cartItemKey) return;
1433
+ await updateCartMutation.mutateAsync({
1434
+ key: cartState.cartItemKey,
1435
+ quantity
1436
+ });
1437
+ },
1438
+ [updateCartMutation, cartState.cartItemKey]
1439
+ );
1440
+ const refresh = react.useCallback(async () => {
1441
+ await refetch();
1442
+ }, [refetch]);
1443
+ const isAddingToCart = addToCartMutation.isPending;
1444
+ const isRemovingFromCart = removeFromCartMutation.isPending;
1445
+ const isUpdatingCart = updateCartMutation.isPending;
1446
+ const isCartBusy = isAddingToCart || isRemovingFromCart || isUpdatingCart;
1447
+ return {
1448
+ product,
1449
+ isLoading,
1450
+ error,
1451
+ refresh,
1452
+ cartState,
1453
+ draftQuantity,
1454
+ setDraftQuantity,
1455
+ addToCart,
1456
+ removeFromCart,
1457
+ updateCartQuantity,
1458
+ isAddingToCart,
1459
+ isRemovingFromCart,
1460
+ isUpdatingCart,
1461
+ isCartBusy
1462
+ };
1463
+ }
1464
+ var PAYMENT_METHOD_TITLES = {
1465
+ cod: "Cash on Delivery",
1466
+ monri: "Monri",
1467
+ bacs: "Bank Transfer",
1468
+ cheque: "Check Payment",
1469
+ paypal: "PayPal",
1470
+ stripe: "Credit Card"
1471
+ };
1472
+ function formatPaymentMethodTitle(methodId) {
1473
+ const knownTitle = PAYMENT_METHOD_TITLES[methodId];
1474
+ if (knownTitle) {
1475
+ return knownTitle;
1476
+ }
1477
+ return methodId.replace(/[_-]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
1478
+ }
1479
+ function useCartView(options = {}) {
1480
+ const { imageSize = "thumbnail" } = options;
1481
+ const storeContext = react.useContext(WooCommerceStoreContext);
1482
+ const storeConfig = storeContext?.config;
1483
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
1484
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
1485
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
1486
+ const { data: cartData, isLoading, error, refetch } = useCart();
1487
+ const updateItemMutation = useUpdateCartItem();
1488
+ const removeItemMutation = useRemoveFromCart();
1489
+ const applyCouponMutation = useApplyCoupon();
1490
+ const removeCouponMutation = useRemoveCoupon();
1491
+ const selectShippingMutation = useSelectShippingRate();
1492
+ const getProcessedImageUrl = react.useCallback(
1493
+ (images) => {
1494
+ const baseUrl = getImageUrl(images, imageSize, fallbackImageUrl);
1495
+ if (baseUrl && imageUrlTransformer) {
1496
+ return imageUrlTransformer(baseUrl, imageSize);
1497
+ }
1498
+ return baseUrl;
1499
+ },
1500
+ [imageSize, fallbackImageUrl, imageUrlTransformer]
1501
+ );
1502
+ const items = react.useMemo(() => {
1503
+ if (!cartData?.items) return [];
1504
+ const currencyCode = cartData.totals.currency_code;
1505
+ return cartData.items.map(
1506
+ (item) => ({
1507
+ key: item.key,
1508
+ id: item.id,
1509
+ name: item.name,
1510
+ imageUrl: getProcessedImageUrl(item.images),
1511
+ quantity: item.quantity,
1512
+ minQuantity: item.quantity_limits.minimum,
1513
+ maxQuantity: item.quantity_limits.maximum,
1514
+ lineTotal: formatStoreApiPriceIntl(item.totals.line_total, currencyCode, localeTag),
1515
+ unitPrice: formatStoreApiPriceIntl(item.prices.price, currencyCode, localeTag),
1516
+ raw: item
1517
+ })
1518
+ );
1519
+ }, [cartData?.items, cartData?.totals.currency_code, localeTag, getProcessedImageUrl]);
1520
+ const totals = react.useMemo(() => {
1521
+ if (!cartData?.totals) {
1522
+ return {
1523
+ subtotal: "-",
1524
+ shipping: "-",
1525
+ tax: "-",
1526
+ discount: "-",
1527
+ total: "-",
1528
+ itemCount: 0,
1529
+ currencyCode: "USD"
1530
+ };
1531
+ }
1532
+ const { totals: t } = cartData;
1533
+ const currencyCode = t.currency_code;
1534
+ return {
1535
+ subtotal: formatStoreApiPriceIntl(t.total_items, currencyCode, localeTag),
1536
+ shipping: formatStoreApiPriceIntl(t.total_shipping, currencyCode, localeTag),
1537
+ tax: formatStoreApiPriceIntl(t.total_tax, currencyCode, localeTag),
1538
+ discount: formatStoreApiPriceIntl(t.total_discount, currencyCode, localeTag),
1539
+ total: formatStoreApiPriceIntl(t.total_price, currencyCode, localeTag),
1540
+ itemCount: cartData.items_count,
1541
+ currencyCode
1542
+ };
1543
+ }, [localeTag, cartData]);
1544
+ const coupons = react.useMemo(() => {
1545
+ if (!cartData?.coupons) return [];
1546
+ return cartData.coupons.map((coupon) => ({
1547
+ code: coupon.code,
1548
+ discount: formatStoreApiPriceIntl(
1549
+ coupon.totals.total_discount,
1550
+ coupon.totals.currency_code,
1551
+ localeTag
1552
+ )
1553
+ }));
1554
+ }, [cartData?.coupons, localeTag]);
1555
+ const shippingRates = react.useMemo(() => {
1556
+ if (!cartData?.shipping_rates?.[0]?.shipping_rates) return [];
1557
+ const currencyCode = cartData.totals.currency_code;
1558
+ return cartData.shipping_rates[0].shipping_rates.map((rate) => ({
1559
+ rateId: rate.rate_id,
1560
+ name: rate.name,
1561
+ price: formatStoreApiPriceIntl(rate.price, currencyCode, localeTag),
1562
+ isSelected: rate.selected
1563
+ }));
1564
+ }, [cartData?.shipping_rates, cartData?.totals.currency_code, localeTag]);
1565
+ const paymentMethods = react.useMemo(() => {
1566
+ if (!cartData?.payment_methods) return [];
1567
+ return cartData.payment_methods.map((methodId) => {
1568
+ const title = formatPaymentMethodTitle(methodId);
1569
+ return {
1570
+ id: methodId,
1571
+ title
1572
+ };
1573
+ });
1574
+ }, [cartData?.payment_methods]);
1575
+ const updateItemQuantity = react.useCallback(
1576
+ async (key, quantity) => {
1577
+ await updateItemMutation.mutateAsync({ key, quantity });
1578
+ },
1579
+ [updateItemMutation]
1580
+ );
1581
+ const removeItem = react.useCallback(
1582
+ async (key) => {
1583
+ await removeItemMutation.mutateAsync({ key });
1584
+ },
1585
+ [removeItemMutation]
1586
+ );
1587
+ const applyCoupon = react.useCallback(
1588
+ async (code) => {
1589
+ await applyCouponMutation.mutateAsync({ code });
1590
+ },
1591
+ [applyCouponMutation]
1592
+ );
1593
+ const removeCoupon = react.useCallback(
1594
+ async (code) => {
1595
+ await removeCouponMutation.mutateAsync({ code });
1596
+ },
1597
+ [removeCouponMutation]
1598
+ );
1599
+ const selectShippingRate = react.useCallback(
1600
+ async (rateId, packageId = 0) => {
1601
+ await selectShippingMutation.mutateAsync({
1602
+ rate_id: rateId,
1603
+ package_id: packageId
1604
+ });
1605
+ },
1606
+ [selectShippingMutation]
1607
+ );
1608
+ const refresh = react.useCallback(async () => {
1609
+ await refetch();
1610
+ }, [refetch]);
1611
+ const isUpdatingItem = updateItemMutation.isPending;
1612
+ const isRemovingItem = removeItemMutation.isPending;
1613
+ const isApplyingCoupon = applyCouponMutation.isPending;
1614
+ const isRemovingCoupon = removeCouponMutation.isPending;
1615
+ const isUpdatingShipping = selectShippingMutation.isPending;
1616
+ const isBusy = isUpdatingItem || isRemovingItem || isApplyingCoupon || isRemovingCoupon || isUpdatingShipping;
1617
+ return {
1618
+ items,
1619
+ totals,
1620
+ coupons,
1621
+ shippingRates,
1622
+ paymentMethods,
1623
+ isEmpty: items.length === 0,
1624
+ needsShipping: cartData?.needs_shipping ?? false,
1625
+ raw: cartData,
1626
+ isLoading,
1627
+ error,
1628
+ updateItemQuantity,
1629
+ removeItem,
1630
+ isUpdatingItem,
1631
+ isRemovingItem,
1632
+ applyCoupon,
1633
+ removeCoupon,
1634
+ isApplyingCoupon,
1635
+ isRemovingCoupon,
1636
+ selectShippingRate,
1637
+ isUpdatingShipping,
1638
+ refresh,
1639
+ isBusy
1640
+ };
1641
+ }
1642
+
1643
+ Object.defineProperty(exports, "addressSchema", {
1644
+ enumerable: true,
1645
+ get: function () { return woocommerceUtils.addressSchema; }
1646
+ });
1647
+ Object.defineProperty(exports, "checkoutSchema", {
1648
+ enumerable: true,
1649
+ get: function () { return woocommerceUtils.checkoutSchema; }
1650
+ });
1651
+ exports.DEFAULT_STORE_CONFIG = DEFAULT_STORE_CONFIG;
1652
+ exports.PLACEHOLDER_IMAGE_URL = PLACEHOLDER_IMAGE_URL;
1653
+ exports.RateLimiter = RateLimiter;
1654
+ exports.WooCommerceContext = WooCommerceContext;
1655
+ exports.WooCommerceProvider = WooCommerceProvider;
1656
+ exports.WooCommerceStoreContext = WooCommerceStoreContext;
1657
+ exports.WooCommerceStoreProvider = WooCommerceStoreProvider;
1658
+ exports.calculateDiscount = calculateDiscount;
1659
+ exports.configureGlobalRateLimiter = configureGlobalRateLimiter;
1660
+ exports.createQueryKeys = createQueryKeys;
1661
+ exports.formatDiscountBadge = formatDiscountBadge;
1662
+ exports.formatPrice = formatPrice;
1663
+ exports.formatPriceRange = formatPriceRange;
1664
+ exports.formatStoreApiPrice = formatStoreApiPrice;
1665
+ exports.formatStoreApiPriceIntl = formatStoreApiPriceIntl;
1666
+ exports.getAllImageUrls = getAllImageUrls;
1667
+ exports.getBaseUrl = getBaseUrl;
1668
+ exports.getCurrencySymbol = getCurrencySymbol;
1669
+ exports.getGlobalRateLimiter = getGlobalRateLimiter;
1670
+ exports.getImageUrl = getImageUrl;
1671
+ exports.getImageUrlOrPlaceholder = getImageUrlOrPlaceholder;
1672
+ exports.getMaxAddToCartQuantity = getMaxAddToCartQuantity;
1673
+ exports.getPrimaryImage = getPrimaryImage;
1674
+ exports.getSizedImageUrl = getSizedImageUrl;
1675
+ exports.getStockSeverity = getStockSeverity;
1676
+ exports.getStockStatusText = getStockStatusText;
1677
+ exports.isLowStock = isLowStock;
1678
+ exports.isPurchasable = isPurchasable;
1679
+ exports.isValidStoreUrlFormat = isValidStoreUrlFormat;
1680
+ exports.normalizeStoreUrl = normalizeStoreUrl;
1681
+ exports.parseWooCommercePrice = parseWooCommercePrice;
1682
+ exports.preloadImage = preloadImage;
1683
+ exports.preloadImages = preloadImages;
1684
+ exports.resetGlobalRateLimiter = resetGlobalRateLimiter;
1685
+ exports.useAddToCart = useAddToCart;
1686
+ exports.useApplyCoupon = useApplyCoupon;
1687
+ exports.useCart = useCart;
1688
+ exports.useCartView = useCartView;
1689
+ exports.useCheckout = useCheckout;
1690
+ exports.useInfiniteProducts = useInfiniteProducts;
1691
+ exports.useOrder = useOrder;
1692
+ exports.useProcessCheckout = useProcessCheckout;
1693
+ exports.useProduct = useProduct;
1694
+ exports.useProductCategories = useProductCategories;
1695
+ exports.useProductCategoryTree = useProductCategoryTree;
1696
+ exports.useProductView = useProductView;
1697
+ exports.useProducts = useProducts;
1698
+ exports.useProductsFeed = useProductsFeed;
1699
+ exports.useRemoveCoupon = useRemoveCoupon;
1700
+ exports.useRemoveFromCart = useRemoveFromCart;
1701
+ exports.useSelectShippingRate = useSelectShippingRate;
1702
+ exports.useStore = useStore;
1703
+ exports.useStoreFeatures = useStoreFeatures;
1704
+ exports.useStoreLocale = useStoreLocale;
1705
+ exports.useStoreTheme = useStoreTheme;
1706
+ exports.useUpdateCartItem = useUpdateCartItem;
1707
+ exports.useUpdateCustomer = useUpdateCustomer;
1708
+ exports.useWooCommerceClient = useWooCommerceClient;
1709
+ exports.useWooCommerceQueryKeys = useWooCommerceQueryKeys;
1710
+ exports.validateWooCommerceStore = validateWooCommerceStore;
1711
+ //# sourceMappingURL=index.cjs.map
1712
+ //# sourceMappingURL=index.cjs.map