@szymonpiatek/nextwordpress 0.0.5 → 0.0.6

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.
@@ -1,9 +1,115 @@
1
+ import { createContext, useState, useCallback, useEffect, useContext, useReducer } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
1
3
  import useSWR2 from 'swr';
2
4
 
3
5
  var __defProp = Object.defineProperty;
4
6
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
5
7
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
6
8
 
9
+ // src/shared/url.ts
10
+ function resolveBaseUrl(config) {
11
+ return typeof window === "undefined" ? config.serverURL : config.clientURL;
12
+ }
13
+
14
+ // src/auth/types.ts
15
+ var AuthenticationError = class extends Error {
16
+ constructor(message, status) {
17
+ super(message);
18
+ __publicField(this, "status", status);
19
+ this.name = "AuthenticationError";
20
+ }
21
+ };
22
+
23
+ // src/auth/jwt.ts
24
+ async function authenticateJwt(config, credentials) {
25
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token`;
26
+ const response = await fetch(url, {
27
+ method: "POST",
28
+ headers: { "Content-Type": "application/json" },
29
+ body: JSON.stringify(credentials),
30
+ cache: "no-store"
31
+ });
32
+ if (!response.ok) {
33
+ throw new AuthenticationError(
34
+ `JWT authentication failed: ${response.statusText}`,
35
+ response.status
36
+ );
37
+ }
38
+ return response.json();
39
+ }
40
+ async function validateJwtToken(config, token) {
41
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token/validate`;
42
+ const response = await fetch(url, {
43
+ method: "POST",
44
+ headers: { Authorization: `Bearer ${token}` },
45
+ cache: "no-store"
46
+ });
47
+ return response.ok;
48
+ }
49
+ var AuthContext = createContext(null);
50
+ var TOKEN_KEY = "nw_auth_token";
51
+ var USER_KEY = "nw_auth_user";
52
+ function AuthProvider({
53
+ config,
54
+ children
55
+ }) {
56
+ const [user, setUser] = useState(null);
57
+ const [isLoading, setIsLoading] = useState(true);
58
+ const [error, setError] = useState(null);
59
+ const clearStorage = useCallback(() => {
60
+ localStorage.removeItem(TOKEN_KEY);
61
+ localStorage.removeItem(USER_KEY);
62
+ }, []);
63
+ useEffect(() => {
64
+ const token = localStorage.getItem(TOKEN_KEY);
65
+ const storedUser = localStorage.getItem(USER_KEY);
66
+ if (!token || !storedUser) {
67
+ setIsLoading(false);
68
+ return;
69
+ }
70
+ validateJwtToken(config, token).then((valid) => {
71
+ if (valid) {
72
+ setUser(JSON.parse(storedUser));
73
+ } else {
74
+ clearStorage();
75
+ }
76
+ }).catch(() => clearStorage()).finally(() => setIsLoading(false));
77
+ }, []);
78
+ const login = async (credentials) => {
79
+ setError(null);
80
+ setIsLoading(true);
81
+ try {
82
+ const response = await authenticateJwt(config, credentials);
83
+ const authUser = {
84
+ token: response.token,
85
+ email: response.user_email,
86
+ nicename: response.user_nicename,
87
+ displayName: response.user_display_name
88
+ };
89
+ localStorage.setItem(TOKEN_KEY, response.token);
90
+ localStorage.setItem(USER_KEY, JSON.stringify(authUser));
91
+ setUser(authUser);
92
+ } catch (err) {
93
+ const message = err instanceof Error ? err.message : "Authentication failed";
94
+ setError(message);
95
+ throw err;
96
+ } finally {
97
+ setIsLoading(false);
98
+ }
99
+ };
100
+ const logout = () => {
101
+ clearStorage();
102
+ setUser(null);
103
+ setError(null);
104
+ };
105
+ return /* @__PURE__ */ jsx(AuthContext.Provider, { value: { user, isLoggedIn: !!user, isLoading, error, login, logout }, children });
106
+ }
107
+ function useAuth() {
108
+ const ctx = useContext(AuthContext);
109
+ if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
110
+ return ctx;
111
+ }
112
+
7
113
  // src/integrations/restApi/core/client/types.ts
8
114
  var WordPressAPIError = class extends Error {
9
115
  constructor(message, status, endpoint) {
@@ -14,11 +120,6 @@ var WordPressAPIError = class extends Error {
14
120
  }
15
121
  };
16
122
 
17
- // src/shared/url.ts
18
- function resolveBaseUrl(config) {
19
- return typeof window === "undefined" ? config.serverURL : config.clientURL;
20
- }
21
-
22
123
  // src/integrations/restApi/core/client/url.ts
23
124
  function buildUrl(config, path, query) {
24
125
  const base = resolveBaseUrl(config);
@@ -47,7 +148,7 @@ async function doFetch(url, init = {}) {
47
148
  return response;
48
149
  }
49
150
  function createFetcher(config) {
50
- const cacheTtl = 300;
151
+ const cacheTtl = config.cacheTTL ?? 300;
51
152
  async function wpFetch(path, query, tags = ["wordpress"]) {
52
153
  const url = buildUrl(config, path, query);
53
154
  const res = await doFetch(url, {
@@ -250,7 +351,7 @@ function createPostsQueries(fetcher) {
250
351
  };
251
352
  }
252
353
 
253
- // src/hooks/usePosts.ts
354
+ // src/hooks/core/usePosts.ts
254
355
  function usePosts(config, filter, swrOptions) {
255
356
  const key = ["wp-posts", config.clientURL, JSON.stringify(filter ?? null)];
256
357
  return useSWR2(
@@ -505,7 +606,7 @@ function createProductsQueries(fetcher) {
505
606
  };
506
607
  }
507
608
 
508
- // src/hooks/useProducts.ts
609
+ // src/hooks/woocommerce/useProducts.ts
509
610
  function useProducts(config, filter, swrOptions) {
510
611
  const key = ["wc-products", config.serverURL, JSON.stringify(filter ?? null)];
511
612
  return useSWR2(
@@ -562,6 +663,258 @@ function useFeaturedProducts(config, limit = 10, swrOptions) {
562
663
  );
563
664
  }
564
665
 
666
+ // src/integrations/restApi/woocommerce/orders/queries.ts
667
+ function createOrdersQueries(fetcher) {
668
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
669
+ async function createOrder(input) {
670
+ return wcMutate("/wp-json/wc/v3/orders", input, "POST");
671
+ }
672
+ async function getOrderById(id) {
673
+ return wcFetch(`/wp-json/wc/v3/orders/${id}`, void 0, [
674
+ "woocommerce",
675
+ "orders",
676
+ `order-${id}`
677
+ ]);
678
+ }
679
+ async function updateOrder(id, data) {
680
+ return wcMutate(`/wp-json/wc/v3/orders/${id}`, data, "PUT");
681
+ }
682
+ async function getOrdersByCustomer(customerId) {
683
+ return wcFetchGraceful(
684
+ "/wp-json/wc/v3/orders",
685
+ [],
686
+ { customer: customerId, per_page: 100 },
687
+ ["woocommerce", "orders", `orders-customer-${customerId}`]
688
+ );
689
+ }
690
+ async function deleteOrder(id, force = true) {
691
+ return wcMutate(
692
+ `/wp-json/wc/v3/orders/${id}`,
693
+ { force },
694
+ "DELETE"
695
+ );
696
+ }
697
+ return {
698
+ createOrder,
699
+ getOrderById,
700
+ updateOrder,
701
+ getOrdersByCustomer,
702
+ deleteOrder
703
+ };
704
+ }
705
+ var STORAGE_KEY = "nw-cart";
706
+ function isSame(a, b) {
707
+ return a.productId === b.productId && (a.variationId ?? 0) === (b.variationId ?? 0);
708
+ }
709
+ function cartReducer(state, action) {
710
+ switch (action.type) {
711
+ case "LOAD":
712
+ return { items: action.items };
713
+ case "ADD": {
714
+ const existing = state.items.find((i) => isSame(i, action.item));
715
+ if (existing) {
716
+ return {
717
+ items: state.items.map(
718
+ (i) => isSame(i, action.item) ? { ...i, quantity: i.quantity + action.item.quantity } : i
719
+ )
720
+ };
721
+ }
722
+ return { items: [...state.items, action.item] };
723
+ }
724
+ case "REMOVE":
725
+ return { items: state.items.filter((i) => !isSame(i, action)) };
726
+ case "UPDATE":
727
+ if (action.quantity <= 0) {
728
+ return { items: state.items.filter((i) => !isSame(i, action)) };
729
+ }
730
+ return {
731
+ items: state.items.map(
732
+ (i) => isSame(i, action) ? { ...i, quantity: action.quantity } : i
733
+ )
734
+ };
735
+ case "CLEAR":
736
+ return { items: [] };
737
+ }
738
+ }
739
+ var CartContext = createContext(null);
740
+ function CartProvider({ children }) {
741
+ const [state, dispatch] = useReducer(cartReducer, { items: [] });
742
+ useEffect(() => {
743
+ try {
744
+ const stored = localStorage.getItem(STORAGE_KEY);
745
+ if (stored) dispatch({ type: "LOAD", items: JSON.parse(stored) });
746
+ } catch {
747
+ }
748
+ }, []);
749
+ useEffect(() => {
750
+ try {
751
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state.items));
752
+ } catch {
753
+ }
754
+ }, [state.items]);
755
+ const totalItems = state.items.reduce((sum, i) => sum + i.quantity, 0);
756
+ const subtotal = state.items.reduce((sum, i) => sum + parseFloat(i.price) * i.quantity, 0).toFixed(2);
757
+ function addItem(item, quantity = 1) {
758
+ dispatch({ type: "ADD", item: { ...item, quantity } });
759
+ }
760
+ function removeItem(productId, variationId) {
761
+ dispatch({ type: "REMOVE", productId, variationId });
762
+ }
763
+ function updateQuantity(productId, quantity, variationId) {
764
+ dispatch({ type: "UPDATE", productId, quantity, variationId });
765
+ }
766
+ function clearCart() {
767
+ dispatch({ type: "CLEAR" });
768
+ }
769
+ async function checkout(config, options = {}) {
770
+ if (state.items.length === 0) throw new Error("Cannot checkout with an empty cart");
771
+ const fetcher = createWooCommerceFetcher(config);
772
+ const input = {
773
+ status: "pending",
774
+ line_items: state.items.map((i) => ({
775
+ product_id: i.productId,
776
+ ...i.variationId !== void 0 ? { variation_id: i.variationId } : {},
777
+ quantity: i.quantity
778
+ })),
779
+ ...options.billing ? { billing: options.billing } : {},
780
+ ...options.shipping ? { shipping: options.shipping } : {},
781
+ ...options.paymentMethod ? { payment_method: options.paymentMethod } : {},
782
+ ...options.paymentMethodTitle ? { payment_method_title: options.paymentMethodTitle } : {},
783
+ ...options.customerNote ? { customer_note: options.customerNote } : {},
784
+ ...options.couponCodes ? { coupon_lines: options.couponCodes.map((code) => ({ code })) } : {}
785
+ };
786
+ const order = await createOrdersQueries(fetcher).createOrder(input);
787
+ dispatch({ type: "CLEAR" });
788
+ return order;
789
+ }
790
+ return /* @__PURE__ */ jsx(
791
+ CartContext.Provider,
792
+ {
793
+ value: { items: state.items, totalItems, subtotal, isEmpty: state.items.length === 0, addItem, removeItem, updateQuantity, clearCart, checkout },
794
+ children
795
+ }
796
+ );
797
+ }
798
+ function useCart() {
799
+ const ctx = useContext(CartContext);
800
+ if (!ctx) throw new Error("useCart must be used within a CartProvider");
801
+ return ctx;
802
+ }
803
+
804
+ // src/integrations/restApi/woocommerce/customers/queries.ts
805
+ function createCustomersQueries(fetcher) {
806
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
807
+ async function getCustomerById(id) {
808
+ return wcFetch(`/wp-json/wc/v3/customers/${id}`, void 0, [
809
+ "woocommerce",
810
+ "customers",
811
+ `customer-${id}`
812
+ ]);
813
+ }
814
+ async function getCustomerByEmail(email) {
815
+ const customers = await wcFetchGraceful(
816
+ "/wp-json/wc/v3/customers",
817
+ [],
818
+ { email },
819
+ ["woocommerce", "customers"]
820
+ );
821
+ return customers[0];
822
+ }
823
+ async function getCustomerByEmailNoCache(email) {
824
+ try {
825
+ const customers = await wcFetch(
826
+ "/wp-json/wc/v3/customers",
827
+ { email },
828
+ ["woocommerce", "customers"],
829
+ { cache: "no-store" }
830
+ );
831
+ return customers[0];
832
+ } catch {
833
+ return void 0;
834
+ }
835
+ }
836
+ async function createCustomer(data) {
837
+ return wcFetch(
838
+ "/wp-json/wc/v3/customers",
839
+ void 0,
840
+ ["woocommerce", "customers"],
841
+ { method: "POST", body: JSON.stringify(data) }
842
+ );
843
+ }
844
+ async function updateCustomer(id, data) {
845
+ return wcMutate(`/wp-json/wc/v3/customers/${id}`, data, "PUT");
846
+ }
847
+ async function deleteCustomer(id, reassign) {
848
+ return wcMutate(
849
+ `/wp-json/wc/v3/customers/${id}`,
850
+ { force: true, ...reassign !== void 0 && { reassign } },
851
+ "DELETE"
852
+ );
853
+ }
854
+ return {
855
+ getCustomerById,
856
+ getCustomerByEmail,
857
+ getCustomerByEmailNoCache,
858
+ createCustomer,
859
+ updateCustomer,
860
+ deleteCustomer
861
+ };
862
+ }
863
+ var CustomerContext = createContext(null);
864
+ function WooCommerceCustomerProvider({
865
+ config,
866
+ children
867
+ }) {
868
+ const { user, isLoggedIn } = useAuth();
869
+ const [customer, setCustomer] = useState(null);
870
+ const [orders, setOrders] = useState([]);
871
+ const [isLoading, setIsLoading] = useState(false);
872
+ const [error, setError] = useState(null);
873
+ const [tick, setTick] = useState(0);
874
+ const fetchData = useCallback(async () => {
875
+ if (!isLoggedIn || !user?.email) {
876
+ setCustomer(null);
877
+ setOrders([]);
878
+ return;
879
+ }
880
+ setIsLoading(true);
881
+ setError(null);
882
+ try {
883
+ const fetcher = createWooCommerceFetcher(config);
884
+ const foundCustomer = await createCustomersQueries(fetcher).getCustomerByEmailNoCache(user.email);
885
+ if (!foundCustomer) {
886
+ setCustomer(null);
887
+ setOrders([]);
888
+ return;
889
+ }
890
+ const customerOrders = await createOrdersQueries(fetcher).getOrdersByCustomer(foundCustomer.id);
891
+ setCustomer(foundCustomer);
892
+ setOrders(customerOrders);
893
+ } catch (err) {
894
+ setError(err instanceof Error ? err.message : "Failed to load customer data");
895
+ } finally {
896
+ setIsLoading(false);
897
+ }
898
+ }, [isLoggedIn, user?.email, config, tick]);
899
+ useEffect(() => {
900
+ void fetchData();
901
+ }, [fetchData]);
902
+ const updateCustomer = async (data) => {
903
+ if (!customer) throw new Error("No customer loaded");
904
+ const fetcher = createWooCommerceFetcher(config);
905
+ const updated = await createCustomersQueries(fetcher).updateCustomer(customer.id, data);
906
+ setCustomer(updated);
907
+ return updated;
908
+ };
909
+ const refetch = () => setTick((t) => t + 1);
910
+ return /* @__PURE__ */ jsx(CustomerContext.Provider, { value: { customer, orders, isLoading, error, updateCustomer, refetch }, children });
911
+ }
912
+ function useCustomer() {
913
+ const ctx = useContext(CustomerContext);
914
+ if (!ctx) throw new Error("useCustomer must be used within a WooCommerceCustomerProvider");
915
+ return ctx;
916
+ }
917
+
565
918
  // src/integrations/wpGraphQL/client/types.ts
566
919
  var WPGraphQLError = class extends Error {
567
920
  constructor(message, status, endpoint, gqlErrors) {
@@ -575,9 +928,9 @@ var WPGraphQLError = class extends Error {
575
928
 
576
929
  // src/integrations/wpGraphQL/client/fetcher.ts
577
930
  var USER_AGENT3 = "NextWordpress WPGraphQL Client";
578
- var CACHE_TTL = 300;
579
931
  function createWPGraphQLFetcher(config) {
580
932
  const url = `${resolveBaseUrl(config)}/graphql`;
933
+ const cacheTTL = config.cacheTTL ?? 300;
581
934
  async function gqlFetch(document, variables, tags = ["wpgraphql"]) {
582
935
  const response = await fetch(url, {
583
936
  method: "POST",
@@ -586,7 +939,7 @@ function createWPGraphQLFetcher(config) {
586
939
  "User-Agent": USER_AGENT3
587
940
  },
588
941
  body: JSON.stringify({ query: document, variables }),
589
- next: { tags, revalidate: CACHE_TTL }
942
+ next: { tags, revalidate: cacheTTL }
590
943
  });
591
944
  if (!response.ok) {
592
945
  throw new WPGraphQLError(
@@ -815,7 +1168,7 @@ function createPostsQueries2(fetcher) {
815
1168
  };
816
1169
  }
817
1170
 
818
- // src/hooks/useWPGraphQL.ts
1171
+ // src/hooks/wpgraphql/useWPGraphQL.ts
819
1172
  function useWPGraphQL(config, query, variables, tags, swrOptions) {
820
1173
  const key = ["wpgraphql", config.clientURL, query, JSON.stringify(variables ?? null)];
821
1174
  return useSWR2(
@@ -850,6 +1203,6 @@ function useGQLPostBySlug(config, slug, swrOptions) {
850
1203
  );
851
1204
  }
852
1205
 
853
- export { useFeaturedProducts, useGQLPostBySlug, useGQLPosts, usePost, usePostBySlug, usePosts, usePostsPaginated, useProduct, useProductBySlug, useProducts, useProductsPaginated, useWPGraphQL };
1206
+ export { AuthProvider, CartProvider, WooCommerceCustomerProvider, cartReducer, useAuth, useCart, useCustomer, useFeaturedProducts, useGQLPostBySlug, useGQLPosts, usePost, usePostBySlug, usePosts, usePostsPaginated, useProduct, useProductBySlug, useProducts, useProductsPaginated, useWPGraphQL };
854
1207
  //# sourceMappingURL=index.js.map
855
1208
  //# sourceMappingURL=index.js.map