@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.
@@ -0,0 +1,1132 @@
1
+ import { createContext, useContext, useMemo, useCallback, useState } from 'react';
2
+ import { useQuery, useQueryClient, useMutation, useInfiniteQuery } from '@tanstack/react-query';
3
+ import { WooCommerceApiError } from '@atomic-solutions/woocommerce-utils';
4
+
5
+ // src/hooks/useWooCommerceClient.ts
6
+ var WooCommerceContext = createContext(null);
7
+
8
+ // src/hooks/useWooCommerceClient.ts
9
+ var useWooCommerceClient = () => {
10
+ const context = useContext(WooCommerceContext);
11
+ if (!context) {
12
+ throw new Error(
13
+ "useWooCommerceClient must be used within WooCommerceProvider. Wrap your app with <WooCommerceProvider client={client} queryKeys={queryKeys}>."
14
+ );
15
+ }
16
+ return context.client;
17
+ };
18
+ var useWooCommerceQueryKeys = () => {
19
+ const context = useContext(WooCommerceContext);
20
+ if (!context) {
21
+ throw new Error(
22
+ "useWooCommerceQueryKeys must be used within WooCommerceProvider. Wrap your app with <WooCommerceProvider client={client} queryKeys={queryKeys}>."
23
+ );
24
+ }
25
+ return context.queryKeys;
26
+ };
27
+
28
+ // src/constants/stale-times.ts
29
+ var STALE_TIME_SHORT = 60 * 1e3;
30
+ var STALE_TIME_LONG = 60 * 60 * 1e3;
31
+ var STALE_TIME_NONE = 0;
32
+ var StaleTimes = {
33
+ /** Cart data - always fresh */
34
+ cart: STALE_TIME_NONE,
35
+ /** Checkout data - always fresh */
36
+ checkout: STALE_TIME_NONE,
37
+ /** Product list - 1 minute */
38
+ products: STALE_TIME_SHORT,
39
+ /** Product detail - 1 minute */
40
+ product: STALE_TIME_SHORT,
41
+ /** Product categories - always fresh */
42
+ categories: STALE_TIME_NONE,
43
+ /** Orders - always fresh */
44
+ orders: STALE_TIME_NONE,
45
+ /** Default for infinite queries - 1 hour */
46
+ infinite: STALE_TIME_LONG
47
+ };
48
+ var useInfiniteWooQuery = ({
49
+ queryKey,
50
+ queryFn,
51
+ params,
52
+ perPage = 10,
53
+ staleTime = StaleTimes.infinite,
54
+ enabled
55
+ }) => {
56
+ const query = useInfiniteQuery({
57
+ queryKey,
58
+ queryFn: ({ pageParam }) => queryFn({
59
+ per_page: perPage,
60
+ ...params,
61
+ page: pageParam
62
+ }),
63
+ initialPageParam: 1,
64
+ getNextPageParam: (lastPage) => lastPage.pagination.nextPage,
65
+ getPreviousPageParam: (firstPage) => firstPage.pagination.prevPage,
66
+ staleTime,
67
+ enabled
68
+ });
69
+ const flatData = query.data?.pages.flatMap((page) => page.data) ?? [];
70
+ return {
71
+ ...query,
72
+ data: flatData
73
+ // Override data with flattened array
74
+ };
75
+ };
76
+
77
+ // src/hooks/products.ts
78
+ var useProducts = (params) => {
79
+ const client = useWooCommerceClient();
80
+ const queryKeys = useWooCommerceQueryKeys();
81
+ return useQuery({
82
+ queryKey: queryKeys.products.list(params),
83
+ queryFn: () => client.products.list(params),
84
+ staleTime: StaleTimes.products
85
+ });
86
+ };
87
+ var useInfiniteProducts = (params) => {
88
+ const client = useWooCommerceClient();
89
+ const queryKeys = useWooCommerceQueryKeys();
90
+ return useInfiniteWooQuery({
91
+ queryKey: queryKeys.products.list(params),
92
+ queryFn: (p) => client.products.list({ ...p, page: p.page ?? 1 }),
93
+ params,
94
+ perPage: params?.per_page ?? 10
95
+ });
96
+ };
97
+ var useProduct = (id) => {
98
+ const client = useWooCommerceClient();
99
+ const queryKeys = useWooCommerceQueryKeys();
100
+ return useQuery({
101
+ queryKey: queryKeys.products.detail(id),
102
+ queryFn: () => client.products.get(id),
103
+ staleTime: StaleTimes.product
104
+ });
105
+ };
106
+ var useProductCategories = () => {
107
+ const client = useWooCommerceClient();
108
+ const queryKeys = useWooCommerceQueryKeys();
109
+ return useQuery({
110
+ queryKey: queryKeys.products.categories(),
111
+ queryFn: () => client.products.categories(),
112
+ staleTime: StaleTimes.categories
113
+ });
114
+ };
115
+ var groupBy = (fn, list) => {
116
+ return list.reduce(
117
+ (acc, item) => {
118
+ const key = fn(item);
119
+ if (!acc[key]) {
120
+ acc[key] = [];
121
+ }
122
+ acc[key].push(item);
123
+ return acc;
124
+ },
125
+ {}
126
+ );
127
+ };
128
+ var processCategoriesToTree = (data) => {
129
+ const rootCategories = data?.filter((item) => item.parent === 0);
130
+ const indexedData = groupBy((item) => String(item.parent), data ?? []);
131
+ const processCategory = (item) => ({
132
+ ...item,
133
+ subCategories: indexedData[item.id]?.map(processCategory)
134
+ });
135
+ return rootCategories?.map(processCategory) ?? [];
136
+ };
137
+ var useProductCategoryTree = () => {
138
+ const query = useProductCategories();
139
+ const flatData = query.data ?? [];
140
+ const treeData = processCategoriesToTree(flatData);
141
+ const findById = (id) => {
142
+ if (!id) return;
143
+ const numId = typeof id === "string" ? parseInt(id, 10) : id;
144
+ return flatData.find((item) => item.id === numId);
145
+ };
146
+ return {
147
+ ...query,
148
+ data: flatData,
149
+ treeData,
150
+ findById
151
+ };
152
+ };
153
+ var EventContext = createContext(null);
154
+ var useEventEmitter = () => {
155
+ return useContext(EventContext);
156
+ };
157
+
158
+ // src/events/types.ts
159
+ function createSuccessEvent(type, data) {
160
+ return { type, status: "success", data };
161
+ }
162
+ function createErrorEvent(type, error) {
163
+ return { type, status: "error", error };
164
+ }
165
+
166
+ // src/hooks/cart.ts
167
+ var useCart = () => {
168
+ const client = useWooCommerceClient();
169
+ const queryKeys = useWooCommerceQueryKeys();
170
+ const query = useQuery({
171
+ queryKey: queryKeys.cart.details(),
172
+ queryFn: () => client.cart.get(),
173
+ staleTime: StaleTimes.cart
174
+ });
175
+ const cart = query.data;
176
+ const isInCart = (productId) => {
177
+ return cart?.items.some((item) => item.id === productId) ?? false;
178
+ };
179
+ const getCartItem = (productId) => {
180
+ return cart?.items.find((item) => item.id === productId);
181
+ };
182
+ const getQuantity = (productId) => {
183
+ return getCartItem(productId)?.quantity ?? 0;
184
+ };
185
+ return {
186
+ ...query,
187
+ isInCart,
188
+ getCartItem,
189
+ getQuantity
190
+ };
191
+ };
192
+ var useAddToCart = () => {
193
+ const client = useWooCommerceClient();
194
+ const queryKeys = useWooCommerceQueryKeys();
195
+ const queryClient = useQueryClient();
196
+ const emitEvent = useEventEmitter();
197
+ return useMutation({
198
+ mutationKey: queryKeys.cart.mutations.addItem(),
199
+ mutationFn: (input) => client.cart.addItem(input),
200
+ onSuccess: (cart, input) => {
201
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
202
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
203
+ const addedItem = cart.items.find((item) => item.id === input.id);
204
+ if (emitEvent && addedItem) {
205
+ emitEvent(createSuccessEvent("cart:item_added", { item: addedItem, cart }));
206
+ }
207
+ },
208
+ onError: (error) => {
209
+ if (emitEvent) {
210
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
211
+ code: "unknown_error",
212
+ message: error instanceof Error ? error.message : "Unknown error",
213
+ statusCode: 500,
214
+ url: "",
215
+ method: "POST",
216
+ originalCode: "unknown_error"
217
+ });
218
+ emitEvent(createErrorEvent("cart:item_added", wooError));
219
+ }
220
+ }
221
+ });
222
+ };
223
+ var useUpdateCartItem = () => {
224
+ const client = useWooCommerceClient();
225
+ const queryKeys = useWooCommerceQueryKeys();
226
+ const queryClient = useQueryClient();
227
+ const emitEvent = useEventEmitter();
228
+ return useMutation({
229
+ mutationKey: queryKeys.cart.mutations.updateItem(),
230
+ mutationFn: (input) => client.cart.updateItem(input),
231
+ onSuccess: (cart, input) => {
232
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
233
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
234
+ const updatedItem = cart.items.find((item) => item.key === input.key);
235
+ if (emitEvent && updatedItem) {
236
+ emitEvent(createSuccessEvent("cart:item_updated", { item: updatedItem, cart }));
237
+ }
238
+ },
239
+ onError: (error) => {
240
+ if (emitEvent) {
241
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
242
+ code: "unknown_error",
243
+ message: error instanceof Error ? error.message : "Unknown error",
244
+ statusCode: 500,
245
+ url: "",
246
+ method: "POST",
247
+ originalCode: "unknown_error"
248
+ });
249
+ emitEvent(createErrorEvent("cart:item_updated", wooError));
250
+ }
251
+ }
252
+ });
253
+ };
254
+ var useRemoveFromCart = () => {
255
+ const client = useWooCommerceClient();
256
+ const queryKeys = useWooCommerceQueryKeys();
257
+ const queryClient = useQueryClient();
258
+ const emitEvent = useEventEmitter();
259
+ return useMutation({
260
+ mutationKey: queryKeys.cart.mutations.removeItem(),
261
+ mutationFn: (input) => client.cart.removeItem(input),
262
+ onSuccess: (cart, input) => {
263
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
264
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
265
+ if (emitEvent) {
266
+ emitEvent(createSuccessEvent("cart:item_removed", { itemKey: input.key, cart }));
267
+ }
268
+ },
269
+ onError: (error) => {
270
+ if (emitEvent) {
271
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
272
+ code: "unknown_error",
273
+ message: error instanceof Error ? error.message : "Unknown error",
274
+ statusCode: 500,
275
+ url: "",
276
+ method: "POST",
277
+ originalCode: "unknown_error"
278
+ });
279
+ emitEvent(createErrorEvent("cart:item_removed", wooError));
280
+ }
281
+ }
282
+ });
283
+ };
284
+ var useApplyCoupon = () => {
285
+ const client = useWooCommerceClient();
286
+ const queryKeys = useWooCommerceQueryKeys();
287
+ const queryClient = useQueryClient();
288
+ const emitEvent = useEventEmitter();
289
+ return useMutation({
290
+ mutationKey: queryKeys.cart.mutations.applyCoupon(),
291
+ mutationFn: (input) => client.cart.applyCoupon(input),
292
+ onSuccess: (cart, input) => {
293
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
294
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
295
+ if (emitEvent) {
296
+ emitEvent(createSuccessEvent("cart:coupon_applied", { code: input.code, cart }));
297
+ }
298
+ },
299
+ onError: (error) => {
300
+ if (emitEvent) {
301
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
302
+ code: "unknown_error",
303
+ message: error instanceof Error ? error.message : "Unknown error",
304
+ statusCode: 500,
305
+ url: "",
306
+ method: "POST",
307
+ originalCode: "unknown_error"
308
+ });
309
+ emitEvent(createErrorEvent("cart:coupon_applied", wooError));
310
+ }
311
+ }
312
+ });
313
+ };
314
+ var useRemoveCoupon = () => {
315
+ const client = useWooCommerceClient();
316
+ const queryKeys = useWooCommerceQueryKeys();
317
+ const queryClient = useQueryClient();
318
+ const emitEvent = useEventEmitter();
319
+ return useMutation({
320
+ mutationKey: queryKeys.cart.mutations.removeCoupon(),
321
+ mutationFn: (input) => client.cart.removeCoupon(input),
322
+ onSuccess: (cart, input) => {
323
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
324
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
325
+ if (emitEvent) {
326
+ emitEvent(createSuccessEvent("cart:coupon_removed", { code: input.code, cart }));
327
+ }
328
+ },
329
+ onError: (error) => {
330
+ if (emitEvent) {
331
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
332
+ code: "unknown_error",
333
+ message: error instanceof Error ? error.message : "Unknown error",
334
+ statusCode: 500,
335
+ url: "",
336
+ method: "POST",
337
+ originalCode: "unknown_error"
338
+ });
339
+ emitEvent(createErrorEvent("cart:coupon_removed", wooError));
340
+ }
341
+ }
342
+ });
343
+ };
344
+ var useUpdateCustomer = () => {
345
+ const client = useWooCommerceClient();
346
+ const queryKeys = useWooCommerceQueryKeys();
347
+ const queryClient = useQueryClient();
348
+ const emitEvent = useEventEmitter();
349
+ return useMutation({
350
+ mutationKey: queryKeys.cart.mutations.updateCustomer(),
351
+ mutationFn: (input) => client.cart.updateCustomer(input),
352
+ onSuccess: (cart) => {
353
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
354
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
355
+ if (emitEvent) {
356
+ emitEvent(createSuccessEvent("cart:customer_updated", { cart }));
357
+ }
358
+ },
359
+ onError: (error) => {
360
+ if (emitEvent) {
361
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
362
+ code: "unknown_error",
363
+ message: error instanceof Error ? error.message : "Unknown error",
364
+ statusCode: 500,
365
+ url: "",
366
+ method: "POST",
367
+ originalCode: "unknown_error"
368
+ });
369
+ emitEvent(createErrorEvent("cart:customer_updated", wooError));
370
+ }
371
+ }
372
+ });
373
+ };
374
+ var useSelectShippingRate = () => {
375
+ const client = useWooCommerceClient();
376
+ const queryKeys = useWooCommerceQueryKeys();
377
+ const queryClient = useQueryClient();
378
+ const emitEvent = useEventEmitter();
379
+ return useMutation({
380
+ mutationKey: queryKeys.cart.mutations.selectShippingRate(),
381
+ mutationFn: (input) => client.cart.selectShippingRate(input),
382
+ onSuccess: (cart) => {
383
+ queryClient.setQueryData(queryKeys.cart.details(), cart);
384
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
385
+ if (emitEvent) {
386
+ emitEvent(createSuccessEvent("cart:shipping_selected", { cart }));
387
+ }
388
+ },
389
+ onError: (error) => {
390
+ if (emitEvent) {
391
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
392
+ code: "unknown_error",
393
+ message: error instanceof Error ? error.message : "Unknown error",
394
+ statusCode: 500,
395
+ url: "",
396
+ method: "POST",
397
+ originalCode: "unknown_error"
398
+ });
399
+ emitEvent(createErrorEvent("cart:shipping_selected", wooError));
400
+ }
401
+ }
402
+ });
403
+ };
404
+ var useCheckout = () => {
405
+ const client = useWooCommerceClient();
406
+ const queryKeys = useWooCommerceQueryKeys();
407
+ return useQuery({
408
+ queryKey: queryKeys.checkout.details(),
409
+ queryFn: () => client.checkout.get(),
410
+ staleTime: StaleTimes.checkout
411
+ });
412
+ };
413
+ var useProcessCheckout = () => {
414
+ const client = useWooCommerceClient();
415
+ const queryKeys = useWooCommerceQueryKeys();
416
+ const queryClient = useQueryClient();
417
+ const emitEvent = useEventEmitter();
418
+ return useMutation({
419
+ mutationKey: queryKeys.checkout.mutations.process(),
420
+ mutationFn: (input) => client.checkout.process(input),
421
+ onSuccess: (checkout) => {
422
+ queryClient.invalidateQueries({ queryKey: queryKeys.cart.all });
423
+ queryClient.invalidateQueries({ queryKey: queryKeys.checkout.all });
424
+ if (emitEvent) {
425
+ emitEvent(createSuccessEvent("checkout:processed", { checkout }));
426
+ }
427
+ },
428
+ onError: (error) => {
429
+ if (emitEvent) {
430
+ const wooError = error instanceof WooCommerceApiError ? error : new WooCommerceApiError({
431
+ code: "unknown_error",
432
+ message: error instanceof Error ? error.message : "Unknown error",
433
+ statusCode: 500,
434
+ url: "",
435
+ method: "POST",
436
+ originalCode: "unknown_error"
437
+ });
438
+ emitEvent(createErrorEvent("checkout:processed", wooError));
439
+ }
440
+ }
441
+ });
442
+ };
443
+ var useOrder = (input) => {
444
+ const client = useWooCommerceClient();
445
+ const queryKeys = useWooCommerceQueryKeys();
446
+ return useQuery({
447
+ queryKey: queryKeys.orders.detail(input.id, input.billing_email, input.key),
448
+ queryFn: () => client.orders.get(input),
449
+ staleTime: StaleTimes.orders
450
+ });
451
+ };
452
+
453
+ // src/hooks/queryKeys.ts
454
+ var createQueryKeys = (prefix = ["woocommerce"]) => ({
455
+ // All keys start with prefix
456
+ all: prefix,
457
+ // Products
458
+ products: {
459
+ all: [...prefix, "products"],
460
+ lists: () => [...prefix, "products", "list"],
461
+ list: (params) => [...prefix, "products", "list", params],
462
+ details: () => [...prefix, "products", "detail"],
463
+ detail: (id) => [...prefix, "products", "detail", id],
464
+ categories: () => [...prefix, "products", "categories"]
465
+ },
466
+ // Cart
467
+ cart: {
468
+ all: [...prefix, "cart"],
469
+ details: () => [...prefix, "cart", "details"],
470
+ // Mutation keys
471
+ mutations: {
472
+ addItem: () => [...prefix, "cart", "mutation", "addItem"],
473
+ updateItem: () => [...prefix, "cart", "mutation", "updateItem"],
474
+ removeItem: () => [...prefix, "cart", "mutation", "removeItem"],
475
+ applyCoupon: () => [...prefix, "cart", "mutation", "applyCoupon"],
476
+ removeCoupon: () => [...prefix, "cart", "mutation", "removeCoupon"],
477
+ updateCustomer: () => [...prefix, "cart", "mutation", "updateCustomer"],
478
+ selectShippingRate: () => [...prefix, "cart", "mutation", "selectShippingRate"]
479
+ }
480
+ },
481
+ // Checkout
482
+ checkout: {
483
+ all: [...prefix, "checkout"],
484
+ details: () => [...prefix, "checkout", "details"],
485
+ // Mutation keys
486
+ mutations: {
487
+ process: () => [...prefix, "checkout", "mutation", "process"]
488
+ }
489
+ },
490
+ // Orders
491
+ orders: {
492
+ all: [...prefix, "orders"],
493
+ lists: () => [...prefix, "orders", "list"],
494
+ list: (params) => [...prefix, "orders", "list", params],
495
+ details: () => [...prefix, "orders", "detail"],
496
+ detail: (id, billing_email, key) => [...prefix, "orders", "detail", id, billing_email, key].filter(Boolean)
497
+ }
498
+ });
499
+ var WooCommerceStoreContext = createContext(null);
500
+ WooCommerceStoreContext.displayName = "WooCommerceStoreContext";
501
+
502
+ // src/hooks/useStore.ts
503
+ function useStore() {
504
+ const context = useContext(WooCommerceStoreContext);
505
+ if (!context) {
506
+ throw new Error("useStore must be used within a WooCommerceStoreProvider");
507
+ }
508
+ return context;
509
+ }
510
+ function useStoreFeatures() {
511
+ const { config } = useStore();
512
+ return config.features;
513
+ }
514
+ function useStoreLocale() {
515
+ const { config } = useStore();
516
+ return config.locale;
517
+ }
518
+ var DEFAULT_THEME = {
519
+ primary: "#007AFF",
520
+ // iOS blue
521
+ secondary: "#5856D6",
522
+ // iOS purple
523
+ mode: "auto",
524
+ fonts: {
525
+ heading: void 0,
526
+ body: void 0
527
+ }
528
+ };
529
+ function useStoreTheme(options = {}) {
530
+ const { externalTheme } = options;
531
+ const storeContext = useContext(WooCommerceStoreContext);
532
+ const storeTheme = storeContext?.config?.theme;
533
+ const theme = useMemo(() => {
534
+ return {
535
+ primary: externalTheme?.primary ?? storeTheme?.primary ?? DEFAULT_THEME.primary,
536
+ secondary: externalTheme?.secondary ?? storeTheme?.secondary ?? DEFAULT_THEME.secondary,
537
+ mode: externalTheme?.mode ?? storeTheme?.mode ?? DEFAULT_THEME.mode,
538
+ fonts: {
539
+ heading: externalTheme?.fonts?.heading ?? storeTheme?.fonts?.heading ?? DEFAULT_THEME.fonts.heading,
540
+ body: externalTheme?.fonts?.body ?? storeTheme?.fonts?.body ?? DEFAULT_THEME.fonts.body
541
+ }
542
+ };
543
+ }, [externalTheme, storeTheme]);
544
+ return {
545
+ theme,
546
+ storeTheme,
547
+ hasExternalTheme: !!externalTheme
548
+ };
549
+ }
550
+
551
+ // src/provider/types.ts
552
+ var DEFAULT_STORE_CONFIG = {
553
+ locale: {
554
+ localeTag: "en-US"},
555
+ debug: process.env.NODE_ENV !== "production"
556
+ };
557
+
558
+ // src/utils/price.ts
559
+ var DEFAULT_LOCALE = {
560
+ localeTag: "en-US",
561
+ currency: "USD",
562
+ currencyPosition: "before",
563
+ thousandsSeparator: ",",
564
+ decimalSeparator: ".",
565
+ decimals: 2
566
+ };
567
+ var CURRENCY_SYMBOLS = {
568
+ USD: "$",
569
+ EUR: "\u20AC",
570
+ GBP: "\xA3",
571
+ CAD: "CA$",
572
+ AUD: "A$",
573
+ JPY: "\xA5",
574
+ CNY: "\xA5",
575
+ INR: "\u20B9",
576
+ BRL: "R$",
577
+ MXN: "MX$",
578
+ RUB: "\u20BD",
579
+ KRW: "\u20A9",
580
+ CHF: "CHF",
581
+ SEK: "kr",
582
+ NOK: "kr",
583
+ DKK: "kr",
584
+ PLN: "z\u0142",
585
+ TRY: "\u20BA",
586
+ ZAR: "R",
587
+ NZD: "NZ$",
588
+ SGD: "S$",
589
+ HKD: "HK$",
590
+ THB: "\u0E3F",
591
+ PHP: "\u20B1",
592
+ // Balkans
593
+ BAM: "KM",
594
+ RSD: "din",
595
+ HRK: "kn",
596
+ MKD: "\u0434\u0435\u043D",
597
+ BGN: "\u043B\u0432",
598
+ RON: "lei"
599
+ };
600
+ function getCurrencySymbol(currencyCode) {
601
+ return CURRENCY_SYMBOLS[currencyCode.toUpperCase()] ?? currencyCode;
602
+ }
603
+ function formatNumber(value, locale) {
604
+ const fixed = value.toFixed(locale.decimals);
605
+ const [integerPart, decimalPart] = fixed.split(".");
606
+ const formattedInteger = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, locale.thousandsSeparator);
607
+ if (locale.decimals > 0 && decimalPart) {
608
+ return `${formattedInteger}${locale.decimalSeparator}${decimalPart}`;
609
+ }
610
+ return formattedInteger;
611
+ }
612
+ function formatPrice(price, locale = {}) {
613
+ const mergedLocale = { ...DEFAULT_LOCALE, ...locale };
614
+ const numericPrice = typeof price === "string" ? parseFloat(price) : price;
615
+ if (isNaN(numericPrice)) {
616
+ return "";
617
+ }
618
+ const symbol = getCurrencySymbol(mergedLocale.currency);
619
+ const formattedNumber = formatNumber(numericPrice, mergedLocale);
620
+ if (mergedLocale.currencyPosition === "after") {
621
+ return `${formattedNumber}${symbol}`;
622
+ }
623
+ return `${symbol}${formattedNumber}`;
624
+ }
625
+ function calculateDiscount(regularPrice, salePrice) {
626
+ const regular = typeof regularPrice === "string" ? parseFloat(regularPrice) : regularPrice;
627
+ const sale = typeof salePrice === "string" ? parseFloat(salePrice) : salePrice;
628
+ if (isNaN(regular) || isNaN(sale) || regular <= 0 || sale >= regular) {
629
+ return null;
630
+ }
631
+ return Math.round((regular - sale) / regular * 100);
632
+ }
633
+ function formatStoreApiPriceIntl(priceInMinorUnits, currencyCode, localeTag = "en-US") {
634
+ if (!priceInMinorUnits || !currencyCode) {
635
+ return "-";
636
+ }
637
+ const cents = parseInt(priceInMinorUnits, 10);
638
+ if (isNaN(cents)) {
639
+ return "-";
640
+ }
641
+ const decimalPrice = cents / 100;
642
+ try {
643
+ const formatter = new Intl.NumberFormat(localeTag, {
644
+ style: "currency",
645
+ currency: currencyCode
646
+ });
647
+ return formatter.format(decimalPrice);
648
+ } catch {
649
+ return formatPrice(decimalPrice, { currency: currencyCode });
650
+ }
651
+ }
652
+
653
+ // src/utils/stock.ts
654
+ var DEFAULT_CONFIG = {
655
+ inStockText: "In Stock",
656
+ outOfStockText: "Out of Stock",
657
+ backorderText: "Available on Backorder",
658
+ showQuantity: false,
659
+ lowStockThreshold: 5,
660
+ lowStockText: "Only {quantity} left"
661
+ };
662
+ function getStockStatusText(status, quantity, config = {}) {
663
+ const mergedConfig = { ...DEFAULT_CONFIG, ...config };
664
+ switch (status) {
665
+ case "instock":
666
+ if (quantity !== null && quantity !== void 0 && quantity <= mergedConfig.lowStockThreshold && quantity > 0) {
667
+ return mergedConfig.lowStockText.replace("{quantity}", quantity.toString());
668
+ }
669
+ if (mergedConfig.showQuantity && quantity !== null && quantity !== void 0) {
670
+ return `${mergedConfig.inStockText} (${quantity})`;
671
+ }
672
+ return mergedConfig.inStockText;
673
+ case "outofstock":
674
+ return mergedConfig.outOfStockText;
675
+ case "onbackorder":
676
+ return mergedConfig.backorderText;
677
+ default:
678
+ return mergedConfig.inStockText;
679
+ }
680
+ }
681
+ function isPurchasable(status, quantity, manageStock = true) {
682
+ if (status === "outofstock") {
683
+ return false;
684
+ }
685
+ if (status === "onbackorder") {
686
+ return true;
687
+ }
688
+ if (manageStock && quantity !== null && quantity !== void 0) {
689
+ return quantity > 0;
690
+ }
691
+ return true;
692
+ }
693
+ function isLowStock(status, quantity, threshold = 5) {
694
+ return status === "instock" && quantity !== null && quantity !== void 0 && quantity <= threshold && quantity > 0;
695
+ }
696
+
697
+ // src/utils/image.ts
698
+ var SIZE_SUFFIXES = {
699
+ thumbnail: "-150x150",
700
+ medium: "-300x300",
701
+ large: "-1024x1024",
702
+ full: ""
703
+ };
704
+ function getPrimaryImage(images) {
705
+ if (!images || images.length === 0) {
706
+ return void 0;
707
+ }
708
+ return images[0];
709
+ }
710
+ function getImageUrl(images, size = "full", fallback) {
711
+ const primary = getPrimaryImage(images);
712
+ if (!primary) {
713
+ return fallback;
714
+ }
715
+ return getSizedImageUrl(primary.src, size);
716
+ }
717
+ function getSizedImageUrl(url, size = "full") {
718
+ if (!url || size === "full") {
719
+ return url;
720
+ }
721
+ const hasSize = Object.values(SIZE_SUFFIXES).some((suffix2) => suffix2 && url.includes(suffix2));
722
+ if (hasSize) {
723
+ let result = url;
724
+ Object.values(SIZE_SUFFIXES).forEach((suffix2) => {
725
+ if (suffix2) {
726
+ result = result.replace(suffix2, SIZE_SUFFIXES[size]);
727
+ }
728
+ });
729
+ return result;
730
+ }
731
+ const suffix = SIZE_SUFFIXES[size];
732
+ const lastDot = url.lastIndexOf(".");
733
+ if (lastDot === -1) {
734
+ return url;
735
+ }
736
+ return `${url.slice(0, lastDot)}${suffix}${url.slice(lastDot)}`;
737
+ }
738
+ function getAllImageUrls(images, size = "full") {
739
+ if (!images || images.length === 0) {
740
+ return [];
741
+ }
742
+ return images.map((img) => getSizedImageUrl(img.src, size));
743
+ }
744
+
745
+ // src/hooks/useProductsFeed.ts
746
+ function useProductsFeed(options = {}) {
747
+ const { params, imageSize = "medium" } = options;
748
+ const storeContext = useContext(WooCommerceStoreContext);
749
+ const storeConfig = storeContext?.config;
750
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
751
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
752
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
753
+ const {
754
+ data: productsData,
755
+ isLoading,
756
+ isFetchingNextPage,
757
+ error,
758
+ hasNextPage = false,
759
+ fetchNextPage,
760
+ refetch,
761
+ isRefetching
762
+ } = useInfiniteProducts(params);
763
+ const { treeData: categoryTree = [], findById } = useProductCategoryTree();
764
+ const getProcessedImageUrl = useCallback(
765
+ (images) => {
766
+ const baseUrl = getImageUrl(images, imageSize, fallbackImageUrl);
767
+ if (baseUrl && imageUrlTransformer) {
768
+ return imageUrlTransformer(baseUrl, imageSize);
769
+ }
770
+ return baseUrl;
771
+ },
772
+ [imageSize, fallbackImageUrl, imageUrlTransformer]
773
+ );
774
+ const products = useMemo(() => {
775
+ if (!productsData) return [];
776
+ const productList = Array.isArray(productsData) ? productsData : [];
777
+ return productList.map((product) => {
778
+ const currencyCode = product.prices?.currency_code;
779
+ return {
780
+ id: product.id,
781
+ name: product.name,
782
+ slug: product.slug,
783
+ permalink: product.permalink,
784
+ imageUrl: getProcessedImageUrl(product.images),
785
+ price: formatStoreApiPriceIntl(product.prices?.price, currencyCode, localeTag),
786
+ regularPrice: formatStoreApiPriceIntl(
787
+ product.prices?.regular_price,
788
+ currencyCode,
789
+ localeTag
790
+ ),
791
+ isOnSale: product.on_sale,
792
+ canAddToCart: product.is_purchasable && product.is_in_stock,
793
+ raw: product
794
+ };
795
+ });
796
+ }, [productsData, localeTag, getProcessedImageUrl]);
797
+ const activeCategory = useMemo(() => {
798
+ if (!params?.category) return void 0;
799
+ return findById(params.category);
800
+ }, [params, findById]);
801
+ const refresh = useCallback(async () => {
802
+ await refetch();
803
+ }, [refetch]);
804
+ const totalCount = products.length;
805
+ return {
806
+ products,
807
+ isLoading,
808
+ isFetchingNextPage,
809
+ error,
810
+ hasNextPage,
811
+ fetchNextPage,
812
+ refresh,
813
+ isRefreshing: isRefetching,
814
+ activeCategory,
815
+ categoryTree,
816
+ findCategoryById: findById,
817
+ totalCount
818
+ };
819
+ }
820
+ function useProductView(options) {
821
+ const { productId, imageSize = "large", lowStockThreshold = 5 } = options;
822
+ const storeContext = useContext(WooCommerceStoreContext);
823
+ const storeConfig = storeContext?.config;
824
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
825
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
826
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
827
+ const [draftQuantity, setDraftQuantity] = useState(1);
828
+ const { data: productData, isLoading, error, refetch } = useProduct(productId);
829
+ const { data: cartData } = useCart();
830
+ const addToCartMutation = useAddToCart();
831
+ const removeFromCartMutation = useRemoveFromCart();
832
+ const updateCartMutation = useUpdateCartItem();
833
+ const processImageUrl = useCallback(
834
+ (url) => {
835
+ if (!url) return url;
836
+ if (imageUrlTransformer) {
837
+ return imageUrlTransformer(url, imageSize);
838
+ }
839
+ return url;
840
+ },
841
+ [imageUrlTransformer, imageSize]
842
+ );
843
+ const product = useMemo(() => {
844
+ if (!productData) return null;
845
+ const currencyCode = productData.prices?.currency_code;
846
+ const stockStatus = productData.is_on_backorder ? "onbackorder" : productData.is_in_stock ? "instock" : "outofstock";
847
+ const lowStockRemaining = productData.low_stock_remaining;
848
+ const baseImageUrl = getImageUrl(productData.images, imageSize, fallbackImageUrl);
849
+ const baseImageUrls = getAllImageUrls(productData.images, imageSize);
850
+ return {
851
+ id: productData.id,
852
+ name: productData.name,
853
+ slug: productData.slug,
854
+ permalink: productData.permalink,
855
+ description: productData.description,
856
+ shortDescription: productData.short_description,
857
+ sku: productData.sku,
858
+ imageUrl: processImageUrl(baseImageUrl),
859
+ imageUrls: baseImageUrls.map((url) => processImageUrl(url) ?? url),
860
+ price: formatStoreApiPriceIntl(productData.prices?.price, currencyCode, localeTag),
861
+ regularPrice: formatStoreApiPriceIntl(
862
+ productData.prices?.regular_price,
863
+ currencyCode,
864
+ localeTag
865
+ ),
866
+ isOnSale: productData.on_sale,
867
+ discountPercent: calculateDiscount(
868
+ productData.prices?.regular_price ?? "0",
869
+ productData.prices?.price ?? "0"
870
+ ),
871
+ discountBadge: productData.on_sale ? `-${calculateDiscount(
872
+ productData.prices?.regular_price ?? "0",
873
+ productData.prices?.price ?? "0"
874
+ )}%` : null,
875
+ stockStatusText: getStockStatusText(stockStatus, lowStockRemaining ?? void 0, {
876
+ lowStockThreshold
877
+ }),
878
+ isPurchasable: isPurchasable(
879
+ stockStatus,
880
+ lowStockRemaining ?? void 0,
881
+ productData.sold_individually
882
+ ),
883
+ isLowStock: isLowStock(stockStatus, lowStockRemaining ?? void 0, lowStockThreshold),
884
+ maxQuantity: productData.add_to_cart?.maximum ?? 999,
885
+ minQuantity: productData.add_to_cart?.minimum ?? 1,
886
+ raw: productData
887
+ };
888
+ }, [productData, localeTag, fallbackImageUrl, imageSize, lowStockThreshold, processImageUrl]);
889
+ const cartItem = useMemo(() => {
890
+ return cartData?.items.find((item) => item.id === productId);
891
+ }, [cartData?.items, productId]);
892
+ const cartState = useMemo(
893
+ () => ({
894
+ isInCart: !!cartItem,
895
+ quantityInCart: cartItem?.quantity ?? 0,
896
+ cartItemKey: cartItem?.key ?? null,
897
+ cartQuantityLimits: cartItem ? {
898
+ minimum: cartItem.quantity_limits.minimum,
899
+ maximum: cartItem.quantity_limits.maximum
900
+ } : null
901
+ }),
902
+ [cartItem]
903
+ );
904
+ const addToCart = useCallback(async () => {
905
+ await addToCartMutation.mutateAsync({
906
+ id: productId,
907
+ quantity: draftQuantity
908
+ });
909
+ setDraftQuantity(1);
910
+ }, [addToCartMutation, productId, draftQuantity]);
911
+ const removeFromCart = useCallback(async () => {
912
+ if (!cartState.cartItemKey) return;
913
+ await removeFromCartMutation.mutateAsync({
914
+ key: cartState.cartItemKey
915
+ });
916
+ }, [removeFromCartMutation, cartState.cartItemKey]);
917
+ const updateCartQuantity = useCallback(
918
+ async (quantity) => {
919
+ if (!cartState.cartItemKey) return;
920
+ await updateCartMutation.mutateAsync({
921
+ key: cartState.cartItemKey,
922
+ quantity
923
+ });
924
+ },
925
+ [updateCartMutation, cartState.cartItemKey]
926
+ );
927
+ const refresh = useCallback(async () => {
928
+ await refetch();
929
+ }, [refetch]);
930
+ const isAddingToCart = addToCartMutation.isPending;
931
+ const isRemovingFromCart = removeFromCartMutation.isPending;
932
+ const isUpdatingCart = updateCartMutation.isPending;
933
+ const isCartBusy = isAddingToCart || isRemovingFromCart || isUpdatingCart;
934
+ return {
935
+ product,
936
+ isLoading,
937
+ error,
938
+ refresh,
939
+ cartState,
940
+ draftQuantity,
941
+ setDraftQuantity,
942
+ addToCart,
943
+ removeFromCart,
944
+ updateCartQuantity,
945
+ isAddingToCart,
946
+ isRemovingFromCart,
947
+ isUpdatingCart,
948
+ isCartBusy
949
+ };
950
+ }
951
+ var PAYMENT_METHOD_TITLES = {
952
+ cod: "Cash on Delivery",
953
+ monri: "Monri",
954
+ bacs: "Bank Transfer",
955
+ cheque: "Check Payment",
956
+ paypal: "PayPal",
957
+ stripe: "Credit Card"
958
+ };
959
+ function formatPaymentMethodTitle(methodId) {
960
+ const knownTitle = PAYMENT_METHOD_TITLES[methodId];
961
+ if (knownTitle) {
962
+ return knownTitle;
963
+ }
964
+ return methodId.replace(/[_-]/g, " ").replace(/\b\w/g, (char) => char.toUpperCase());
965
+ }
966
+ function useCartView(options = {}) {
967
+ const { imageSize = "thumbnail" } = options;
968
+ const storeContext = useContext(WooCommerceStoreContext);
969
+ const storeConfig = storeContext?.config;
970
+ const localeTag = options.localeTag ?? storeConfig?.locale?.localeTag ?? DEFAULT_STORE_CONFIG.locale.localeTag;
971
+ const fallbackImageUrl = options.fallbackImageUrl ?? storeConfig?.fallbackImageUrl;
972
+ const imageUrlTransformer = storeConfig?.imageUrlTransformer;
973
+ const { data: cartData, isLoading, error, refetch } = useCart();
974
+ const updateItemMutation = useUpdateCartItem();
975
+ const removeItemMutation = useRemoveFromCart();
976
+ const applyCouponMutation = useApplyCoupon();
977
+ const removeCouponMutation = useRemoveCoupon();
978
+ const selectShippingMutation = useSelectShippingRate();
979
+ const getProcessedImageUrl = useCallback(
980
+ (images) => {
981
+ const baseUrl = getImageUrl(images, imageSize, fallbackImageUrl);
982
+ if (baseUrl && imageUrlTransformer) {
983
+ return imageUrlTransformer(baseUrl, imageSize);
984
+ }
985
+ return baseUrl;
986
+ },
987
+ [imageSize, fallbackImageUrl, imageUrlTransformer]
988
+ );
989
+ const items = useMemo(() => {
990
+ if (!cartData?.items) return [];
991
+ const currencyCode = cartData.totals.currency_code;
992
+ return cartData.items.map(
993
+ (item) => ({
994
+ key: item.key,
995
+ id: item.id,
996
+ name: item.name,
997
+ imageUrl: getProcessedImageUrl(item.images),
998
+ quantity: item.quantity,
999
+ minQuantity: item.quantity_limits.minimum,
1000
+ maxQuantity: item.quantity_limits.maximum,
1001
+ lineTotal: formatStoreApiPriceIntl(item.totals.line_total, currencyCode, localeTag),
1002
+ unitPrice: formatStoreApiPriceIntl(item.prices.price, currencyCode, localeTag),
1003
+ raw: item
1004
+ })
1005
+ );
1006
+ }, [cartData?.items, cartData?.totals.currency_code, localeTag, getProcessedImageUrl]);
1007
+ const totals = useMemo(() => {
1008
+ if (!cartData?.totals) {
1009
+ return {
1010
+ subtotal: "-",
1011
+ shipping: "-",
1012
+ tax: "-",
1013
+ discount: "-",
1014
+ total: "-",
1015
+ itemCount: 0,
1016
+ currencyCode: "USD"
1017
+ };
1018
+ }
1019
+ const { totals: t } = cartData;
1020
+ const currencyCode = t.currency_code;
1021
+ return {
1022
+ subtotal: formatStoreApiPriceIntl(t.total_items, currencyCode, localeTag),
1023
+ shipping: formatStoreApiPriceIntl(t.total_shipping, currencyCode, localeTag),
1024
+ tax: formatStoreApiPriceIntl(t.total_tax, currencyCode, localeTag),
1025
+ discount: formatStoreApiPriceIntl(t.total_discount, currencyCode, localeTag),
1026
+ total: formatStoreApiPriceIntl(t.total_price, currencyCode, localeTag),
1027
+ itemCount: cartData.items_count,
1028
+ currencyCode
1029
+ };
1030
+ }, [localeTag, cartData]);
1031
+ const coupons = useMemo(() => {
1032
+ if (!cartData?.coupons) return [];
1033
+ return cartData.coupons.map((coupon) => ({
1034
+ code: coupon.code,
1035
+ discount: formatStoreApiPriceIntl(
1036
+ coupon.totals.total_discount,
1037
+ coupon.totals.currency_code,
1038
+ localeTag
1039
+ )
1040
+ }));
1041
+ }, [cartData?.coupons, localeTag]);
1042
+ const shippingRates = useMemo(() => {
1043
+ if (!cartData?.shipping_rates?.[0]?.shipping_rates) return [];
1044
+ const currencyCode = cartData.totals.currency_code;
1045
+ return cartData.shipping_rates[0].shipping_rates.map((rate) => ({
1046
+ rateId: rate.rate_id,
1047
+ name: rate.name,
1048
+ price: formatStoreApiPriceIntl(rate.price, currencyCode, localeTag),
1049
+ isSelected: rate.selected
1050
+ }));
1051
+ }, [cartData?.shipping_rates, cartData?.totals.currency_code, localeTag]);
1052
+ const paymentMethods = useMemo(() => {
1053
+ if (!cartData?.payment_methods) return [];
1054
+ return cartData.payment_methods.map((methodId) => {
1055
+ const title = formatPaymentMethodTitle(methodId);
1056
+ return {
1057
+ id: methodId,
1058
+ title
1059
+ };
1060
+ });
1061
+ }, [cartData?.payment_methods]);
1062
+ const updateItemQuantity = useCallback(
1063
+ async (key, quantity) => {
1064
+ await updateItemMutation.mutateAsync({ key, quantity });
1065
+ },
1066
+ [updateItemMutation]
1067
+ );
1068
+ const removeItem = useCallback(
1069
+ async (key) => {
1070
+ await removeItemMutation.mutateAsync({ key });
1071
+ },
1072
+ [removeItemMutation]
1073
+ );
1074
+ const applyCoupon = useCallback(
1075
+ async (code) => {
1076
+ await applyCouponMutation.mutateAsync({ code });
1077
+ },
1078
+ [applyCouponMutation]
1079
+ );
1080
+ const removeCoupon = useCallback(
1081
+ async (code) => {
1082
+ await removeCouponMutation.mutateAsync({ code });
1083
+ },
1084
+ [removeCouponMutation]
1085
+ );
1086
+ const selectShippingRate = useCallback(
1087
+ async (rateId, packageId = 0) => {
1088
+ await selectShippingMutation.mutateAsync({
1089
+ rate_id: rateId,
1090
+ package_id: packageId
1091
+ });
1092
+ },
1093
+ [selectShippingMutation]
1094
+ );
1095
+ const refresh = useCallback(async () => {
1096
+ await refetch();
1097
+ }, [refetch]);
1098
+ const isUpdatingItem = updateItemMutation.isPending;
1099
+ const isRemovingItem = removeItemMutation.isPending;
1100
+ const isApplyingCoupon = applyCouponMutation.isPending;
1101
+ const isRemovingCoupon = removeCouponMutation.isPending;
1102
+ const isUpdatingShipping = selectShippingMutation.isPending;
1103
+ const isBusy = isUpdatingItem || isRemovingItem || isApplyingCoupon || isRemovingCoupon || isUpdatingShipping;
1104
+ return {
1105
+ items,
1106
+ totals,
1107
+ coupons,
1108
+ shippingRates,
1109
+ paymentMethods,
1110
+ isEmpty: items.length === 0,
1111
+ needsShipping: cartData?.needs_shipping ?? false,
1112
+ raw: cartData,
1113
+ isLoading,
1114
+ error,
1115
+ updateItemQuantity,
1116
+ removeItem,
1117
+ isUpdatingItem,
1118
+ isRemovingItem,
1119
+ applyCoupon,
1120
+ removeCoupon,
1121
+ isApplyingCoupon,
1122
+ isRemovingCoupon,
1123
+ selectShippingRate,
1124
+ isUpdatingShipping,
1125
+ refresh,
1126
+ isBusy
1127
+ };
1128
+ }
1129
+
1130
+ export { createQueryKeys, useAddToCart, useApplyCoupon, useCart, useCartView, useCheckout, useInfiniteProducts, useOrder, useProcessCheckout, useProduct, useProductCategories, useProductCategoryTree, useProductView, useProducts, useProductsFeed, useRemoveCoupon, useRemoveFromCart, useSelectShippingRate, useStore, useStoreFeatures, useStoreLocale, useStoreTheme, useUpdateCartItem, useUpdateCustomer, useWooCommerceClient, useWooCommerceQueryKeys };
1131
+ //# sourceMappingURL=index.js.map
1132
+ //# sourceMappingURL=index.js.map