@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,5 +1,7 @@
1
1
  'use strict';
2
2
 
3
+ var react = require('react');
4
+ var jsxRuntime = require('react/jsx-runtime');
3
5
  var useSWR2 = require('swr');
4
6
 
5
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
@@ -10,6 +12,110 @@ var __defProp = Object.defineProperty;
10
12
  var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
11
13
  var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
12
14
 
15
+ // src/shared/url.ts
16
+ function resolveBaseUrl(config) {
17
+ return typeof window === "undefined" ? config.serverURL : config.clientURL;
18
+ }
19
+
20
+ // src/auth/types.ts
21
+ var AuthenticationError = class extends Error {
22
+ constructor(message, status) {
23
+ super(message);
24
+ __publicField(this, "status", status);
25
+ this.name = "AuthenticationError";
26
+ }
27
+ };
28
+
29
+ // src/auth/jwt.ts
30
+ async function authenticateJwt(config, credentials) {
31
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token`;
32
+ const response = await fetch(url, {
33
+ method: "POST",
34
+ headers: { "Content-Type": "application/json" },
35
+ body: JSON.stringify(credentials),
36
+ cache: "no-store"
37
+ });
38
+ if (!response.ok) {
39
+ throw new AuthenticationError(
40
+ `JWT authentication failed: ${response.statusText}`,
41
+ response.status
42
+ );
43
+ }
44
+ return response.json();
45
+ }
46
+ async function validateJwtToken(config, token) {
47
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token/validate`;
48
+ const response = await fetch(url, {
49
+ method: "POST",
50
+ headers: { Authorization: `Bearer ${token}` },
51
+ cache: "no-store"
52
+ });
53
+ return response.ok;
54
+ }
55
+ var AuthContext = react.createContext(null);
56
+ var TOKEN_KEY = "nw_auth_token";
57
+ var USER_KEY = "nw_auth_user";
58
+ function AuthProvider({
59
+ config,
60
+ children
61
+ }) {
62
+ const [user, setUser] = react.useState(null);
63
+ const [isLoading, setIsLoading] = react.useState(true);
64
+ const [error, setError] = react.useState(null);
65
+ const clearStorage = react.useCallback(() => {
66
+ localStorage.removeItem(TOKEN_KEY);
67
+ localStorage.removeItem(USER_KEY);
68
+ }, []);
69
+ react.useEffect(() => {
70
+ const token = localStorage.getItem(TOKEN_KEY);
71
+ const storedUser = localStorage.getItem(USER_KEY);
72
+ if (!token || !storedUser) {
73
+ setIsLoading(false);
74
+ return;
75
+ }
76
+ validateJwtToken(config, token).then((valid) => {
77
+ if (valid) {
78
+ setUser(JSON.parse(storedUser));
79
+ } else {
80
+ clearStorage();
81
+ }
82
+ }).catch(() => clearStorage()).finally(() => setIsLoading(false));
83
+ }, []);
84
+ const login = async (credentials) => {
85
+ setError(null);
86
+ setIsLoading(true);
87
+ try {
88
+ const response = await authenticateJwt(config, credentials);
89
+ const authUser = {
90
+ token: response.token,
91
+ email: response.user_email,
92
+ nicename: response.user_nicename,
93
+ displayName: response.user_display_name
94
+ };
95
+ localStorage.setItem(TOKEN_KEY, response.token);
96
+ localStorage.setItem(USER_KEY, JSON.stringify(authUser));
97
+ setUser(authUser);
98
+ } catch (err) {
99
+ const message = err instanceof Error ? err.message : "Authentication failed";
100
+ setError(message);
101
+ throw err;
102
+ } finally {
103
+ setIsLoading(false);
104
+ }
105
+ };
106
+ const logout = () => {
107
+ clearStorage();
108
+ setUser(null);
109
+ setError(null);
110
+ };
111
+ return /* @__PURE__ */ jsxRuntime.jsx(AuthContext.Provider, { value: { user, isLoggedIn: !!user, isLoading, error, login, logout }, children });
112
+ }
113
+ function useAuth() {
114
+ const ctx = react.useContext(AuthContext);
115
+ if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
116
+ return ctx;
117
+ }
118
+
13
119
  // src/integrations/restApi/core/client/types.ts
14
120
  var WordPressAPIError = class extends Error {
15
121
  constructor(message, status, endpoint) {
@@ -20,11 +126,6 @@ var WordPressAPIError = class extends Error {
20
126
  }
21
127
  };
22
128
 
23
- // src/shared/url.ts
24
- function resolveBaseUrl(config) {
25
- return typeof window === "undefined" ? config.serverURL : config.clientURL;
26
- }
27
-
28
129
  // src/integrations/restApi/core/client/url.ts
29
130
  function buildUrl(config, path, query) {
30
131
  const base = resolveBaseUrl(config);
@@ -53,7 +154,7 @@ async function doFetch(url, init = {}) {
53
154
  return response;
54
155
  }
55
156
  function createFetcher(config) {
56
- const cacheTtl = 300;
157
+ const cacheTtl = config.cacheTTL ?? 300;
57
158
  async function wpFetch(path, query, tags = ["wordpress"]) {
58
159
  const url = buildUrl(config, path, query);
59
160
  const res = await doFetch(url, {
@@ -256,7 +357,7 @@ function createPostsQueries(fetcher) {
256
357
  };
257
358
  }
258
359
 
259
- // src/hooks/usePosts.ts
360
+ // src/hooks/core/usePosts.ts
260
361
  function usePosts(config, filter, swrOptions) {
261
362
  const key = ["wp-posts", config.clientURL, JSON.stringify(filter ?? null)];
262
363
  return useSWR2__default.default(
@@ -511,7 +612,7 @@ function createProductsQueries(fetcher) {
511
612
  };
512
613
  }
513
614
 
514
- // src/hooks/useProducts.ts
615
+ // src/hooks/woocommerce/useProducts.ts
515
616
  function useProducts(config, filter, swrOptions) {
516
617
  const key = ["wc-products", config.serverURL, JSON.stringify(filter ?? null)];
517
618
  return useSWR2__default.default(
@@ -568,6 +669,258 @@ function useFeaturedProducts(config, limit = 10, swrOptions) {
568
669
  );
569
670
  }
570
671
 
672
+ // src/integrations/restApi/woocommerce/orders/queries.ts
673
+ function createOrdersQueries(fetcher) {
674
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
675
+ async function createOrder(input) {
676
+ return wcMutate("/wp-json/wc/v3/orders", input, "POST");
677
+ }
678
+ async function getOrderById(id) {
679
+ return wcFetch(`/wp-json/wc/v3/orders/${id}`, void 0, [
680
+ "woocommerce",
681
+ "orders",
682
+ `order-${id}`
683
+ ]);
684
+ }
685
+ async function updateOrder(id, data) {
686
+ return wcMutate(`/wp-json/wc/v3/orders/${id}`, data, "PUT");
687
+ }
688
+ async function getOrdersByCustomer(customerId) {
689
+ return wcFetchGraceful(
690
+ "/wp-json/wc/v3/orders",
691
+ [],
692
+ { customer: customerId, per_page: 100 },
693
+ ["woocommerce", "orders", `orders-customer-${customerId}`]
694
+ );
695
+ }
696
+ async function deleteOrder(id, force = true) {
697
+ return wcMutate(
698
+ `/wp-json/wc/v3/orders/${id}`,
699
+ { force },
700
+ "DELETE"
701
+ );
702
+ }
703
+ return {
704
+ createOrder,
705
+ getOrderById,
706
+ updateOrder,
707
+ getOrdersByCustomer,
708
+ deleteOrder
709
+ };
710
+ }
711
+ var STORAGE_KEY = "nw-cart";
712
+ function isSame(a, b) {
713
+ return a.productId === b.productId && (a.variationId ?? 0) === (b.variationId ?? 0);
714
+ }
715
+ function cartReducer(state, action) {
716
+ switch (action.type) {
717
+ case "LOAD":
718
+ return { items: action.items };
719
+ case "ADD": {
720
+ const existing = state.items.find((i) => isSame(i, action.item));
721
+ if (existing) {
722
+ return {
723
+ items: state.items.map(
724
+ (i) => isSame(i, action.item) ? { ...i, quantity: i.quantity + action.item.quantity } : i
725
+ )
726
+ };
727
+ }
728
+ return { items: [...state.items, action.item] };
729
+ }
730
+ case "REMOVE":
731
+ return { items: state.items.filter((i) => !isSame(i, action)) };
732
+ case "UPDATE":
733
+ if (action.quantity <= 0) {
734
+ return { items: state.items.filter((i) => !isSame(i, action)) };
735
+ }
736
+ return {
737
+ items: state.items.map(
738
+ (i) => isSame(i, action) ? { ...i, quantity: action.quantity } : i
739
+ )
740
+ };
741
+ case "CLEAR":
742
+ return { items: [] };
743
+ }
744
+ }
745
+ var CartContext = react.createContext(null);
746
+ function CartProvider({ children }) {
747
+ const [state, dispatch] = react.useReducer(cartReducer, { items: [] });
748
+ react.useEffect(() => {
749
+ try {
750
+ const stored = localStorage.getItem(STORAGE_KEY);
751
+ if (stored) dispatch({ type: "LOAD", items: JSON.parse(stored) });
752
+ } catch {
753
+ }
754
+ }, []);
755
+ react.useEffect(() => {
756
+ try {
757
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state.items));
758
+ } catch {
759
+ }
760
+ }, [state.items]);
761
+ const totalItems = state.items.reduce((sum, i) => sum + i.quantity, 0);
762
+ const subtotal = state.items.reduce((sum, i) => sum + parseFloat(i.price) * i.quantity, 0).toFixed(2);
763
+ function addItem(item, quantity = 1) {
764
+ dispatch({ type: "ADD", item: { ...item, quantity } });
765
+ }
766
+ function removeItem(productId, variationId) {
767
+ dispatch({ type: "REMOVE", productId, variationId });
768
+ }
769
+ function updateQuantity(productId, quantity, variationId) {
770
+ dispatch({ type: "UPDATE", productId, quantity, variationId });
771
+ }
772
+ function clearCart() {
773
+ dispatch({ type: "CLEAR" });
774
+ }
775
+ async function checkout(config, options = {}) {
776
+ if (state.items.length === 0) throw new Error("Cannot checkout with an empty cart");
777
+ const fetcher = createWooCommerceFetcher(config);
778
+ const input = {
779
+ status: "pending",
780
+ line_items: state.items.map((i) => ({
781
+ product_id: i.productId,
782
+ ...i.variationId !== void 0 ? { variation_id: i.variationId } : {},
783
+ quantity: i.quantity
784
+ })),
785
+ ...options.billing ? { billing: options.billing } : {},
786
+ ...options.shipping ? { shipping: options.shipping } : {},
787
+ ...options.paymentMethod ? { payment_method: options.paymentMethod } : {},
788
+ ...options.paymentMethodTitle ? { payment_method_title: options.paymentMethodTitle } : {},
789
+ ...options.customerNote ? { customer_note: options.customerNote } : {},
790
+ ...options.couponCodes ? { coupon_lines: options.couponCodes.map((code) => ({ code })) } : {}
791
+ };
792
+ const order = await createOrdersQueries(fetcher).createOrder(input);
793
+ dispatch({ type: "CLEAR" });
794
+ return order;
795
+ }
796
+ return /* @__PURE__ */ jsxRuntime.jsx(
797
+ CartContext.Provider,
798
+ {
799
+ value: { items: state.items, totalItems, subtotal, isEmpty: state.items.length === 0, addItem, removeItem, updateQuantity, clearCart, checkout },
800
+ children
801
+ }
802
+ );
803
+ }
804
+ function useCart() {
805
+ const ctx = react.useContext(CartContext);
806
+ if (!ctx) throw new Error("useCart must be used within a CartProvider");
807
+ return ctx;
808
+ }
809
+
810
+ // src/integrations/restApi/woocommerce/customers/queries.ts
811
+ function createCustomersQueries(fetcher) {
812
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
813
+ async function getCustomerById(id) {
814
+ return wcFetch(`/wp-json/wc/v3/customers/${id}`, void 0, [
815
+ "woocommerce",
816
+ "customers",
817
+ `customer-${id}`
818
+ ]);
819
+ }
820
+ async function getCustomerByEmail(email) {
821
+ const customers = await wcFetchGraceful(
822
+ "/wp-json/wc/v3/customers",
823
+ [],
824
+ { email },
825
+ ["woocommerce", "customers"]
826
+ );
827
+ return customers[0];
828
+ }
829
+ async function getCustomerByEmailNoCache(email) {
830
+ try {
831
+ const customers = await wcFetch(
832
+ "/wp-json/wc/v3/customers",
833
+ { email },
834
+ ["woocommerce", "customers"],
835
+ { cache: "no-store" }
836
+ );
837
+ return customers[0];
838
+ } catch {
839
+ return void 0;
840
+ }
841
+ }
842
+ async function createCustomer(data) {
843
+ return wcFetch(
844
+ "/wp-json/wc/v3/customers",
845
+ void 0,
846
+ ["woocommerce", "customers"],
847
+ { method: "POST", body: JSON.stringify(data) }
848
+ );
849
+ }
850
+ async function updateCustomer(id, data) {
851
+ return wcMutate(`/wp-json/wc/v3/customers/${id}`, data, "PUT");
852
+ }
853
+ async function deleteCustomer(id, reassign) {
854
+ return wcMutate(
855
+ `/wp-json/wc/v3/customers/${id}`,
856
+ { force: true, ...reassign !== void 0 && { reassign } },
857
+ "DELETE"
858
+ );
859
+ }
860
+ return {
861
+ getCustomerById,
862
+ getCustomerByEmail,
863
+ getCustomerByEmailNoCache,
864
+ createCustomer,
865
+ updateCustomer,
866
+ deleteCustomer
867
+ };
868
+ }
869
+ var CustomerContext = react.createContext(null);
870
+ function WooCommerceCustomerProvider({
871
+ config,
872
+ children
873
+ }) {
874
+ const { user, isLoggedIn } = useAuth();
875
+ const [customer, setCustomer] = react.useState(null);
876
+ const [orders, setOrders] = react.useState([]);
877
+ const [isLoading, setIsLoading] = react.useState(false);
878
+ const [error, setError] = react.useState(null);
879
+ const [tick, setTick] = react.useState(0);
880
+ const fetchData = react.useCallback(async () => {
881
+ if (!isLoggedIn || !user?.email) {
882
+ setCustomer(null);
883
+ setOrders([]);
884
+ return;
885
+ }
886
+ setIsLoading(true);
887
+ setError(null);
888
+ try {
889
+ const fetcher = createWooCommerceFetcher(config);
890
+ const foundCustomer = await createCustomersQueries(fetcher).getCustomerByEmailNoCache(user.email);
891
+ if (!foundCustomer) {
892
+ setCustomer(null);
893
+ setOrders([]);
894
+ return;
895
+ }
896
+ const customerOrders = await createOrdersQueries(fetcher).getOrdersByCustomer(foundCustomer.id);
897
+ setCustomer(foundCustomer);
898
+ setOrders(customerOrders);
899
+ } catch (err) {
900
+ setError(err instanceof Error ? err.message : "Failed to load customer data");
901
+ } finally {
902
+ setIsLoading(false);
903
+ }
904
+ }, [isLoggedIn, user?.email, config, tick]);
905
+ react.useEffect(() => {
906
+ void fetchData();
907
+ }, [fetchData]);
908
+ const updateCustomer = async (data) => {
909
+ if (!customer) throw new Error("No customer loaded");
910
+ const fetcher = createWooCommerceFetcher(config);
911
+ const updated = await createCustomersQueries(fetcher).updateCustomer(customer.id, data);
912
+ setCustomer(updated);
913
+ return updated;
914
+ };
915
+ const refetch = () => setTick((t) => t + 1);
916
+ return /* @__PURE__ */ jsxRuntime.jsx(CustomerContext.Provider, { value: { customer, orders, isLoading, error, updateCustomer, refetch }, children });
917
+ }
918
+ function useCustomer() {
919
+ const ctx = react.useContext(CustomerContext);
920
+ if (!ctx) throw new Error("useCustomer must be used within a WooCommerceCustomerProvider");
921
+ return ctx;
922
+ }
923
+
571
924
  // src/integrations/wpGraphQL/client/types.ts
572
925
  var WPGraphQLError = class extends Error {
573
926
  constructor(message, status, endpoint, gqlErrors) {
@@ -581,9 +934,9 @@ var WPGraphQLError = class extends Error {
581
934
 
582
935
  // src/integrations/wpGraphQL/client/fetcher.ts
583
936
  var USER_AGENT3 = "NextWordpress WPGraphQL Client";
584
- var CACHE_TTL = 300;
585
937
  function createWPGraphQLFetcher(config) {
586
938
  const url = `${resolveBaseUrl(config)}/graphql`;
939
+ const cacheTTL = config.cacheTTL ?? 300;
587
940
  async function gqlFetch(document, variables, tags = ["wpgraphql"]) {
588
941
  const response = await fetch(url, {
589
942
  method: "POST",
@@ -592,7 +945,7 @@ function createWPGraphQLFetcher(config) {
592
945
  "User-Agent": USER_AGENT3
593
946
  },
594
947
  body: JSON.stringify({ query: document, variables }),
595
- next: { tags, revalidate: CACHE_TTL }
948
+ next: { tags, revalidate: cacheTTL }
596
949
  });
597
950
  if (!response.ok) {
598
951
  throw new WPGraphQLError(
@@ -821,7 +1174,7 @@ function createPostsQueries2(fetcher) {
821
1174
  };
822
1175
  }
823
1176
 
824
- // src/hooks/useWPGraphQL.ts
1177
+ // src/hooks/wpgraphql/useWPGraphQL.ts
825
1178
  function useWPGraphQL(config, query, variables, tags, swrOptions) {
826
1179
  const key = ["wpgraphql", config.clientURL, query, JSON.stringify(variables ?? null)];
827
1180
  return useSWR2__default.default(
@@ -856,6 +1209,13 @@ function useGQLPostBySlug(config, slug, swrOptions) {
856
1209
  );
857
1210
  }
858
1211
 
1212
+ exports.AuthProvider = AuthProvider;
1213
+ exports.CartProvider = CartProvider;
1214
+ exports.WooCommerceCustomerProvider = WooCommerceCustomerProvider;
1215
+ exports.cartReducer = cartReducer;
1216
+ exports.useAuth = useAuth;
1217
+ exports.useCart = useCart;
1218
+ exports.useCustomer = useCustomer;
859
1219
  exports.useFeaturedProducts = useFeaturedProducts;
860
1220
  exports.useGQLPostBySlug = useGQLPostBySlug;
861
1221
  exports.useGQLPosts = useGQLPosts;