@szymonpiatek/nextwordpress 0.0.9 → 0.0.11

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,1348 @@
1
+ import { createContext, useState, useCallback, useEffect, useContext, useReducer } from 'react';
2
+ import { jsx } from 'react/jsx-runtime';
3
+ import useSWR2 from 'swr';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
7
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
8
+
9
+ // src/shared/url.ts
10
+ function resolveBaseUrl(config) {
11
+ return typeof window === "undefined" ? config.serverURL : config.clientURL;
12
+ }
13
+
14
+ // src/shared/errors/codes.ts
15
+ var ErrorCode = {
16
+ // WordPress REST API
17
+ WP_REQUEST_FAILED: "WP_REQUEST_FAILED",
18
+ WP_NOT_FOUND: "WP_NOT_FOUND",
19
+ WP_UNAUTHORIZED: "WP_UNAUTHORIZED",
20
+ WP_FORBIDDEN: "WP_FORBIDDEN",
21
+ // WPGraphQL
22
+ GQL_REQUEST_FAILED: "GQL_REQUEST_FAILED",
23
+ GQL_NO_DATA: "GQL_NO_DATA",
24
+ GQL_ERRORS_IN_RESPONSE: "GQL_ERRORS_IN_RESPONSE",
25
+ // WooCommerce — generic
26
+ WOO_REQUEST_FAILED: "WOO_REQUEST_FAILED",
27
+ WOO_NOT_FOUND: "WOO_NOT_FOUND",
28
+ WOO_UNAUTHORIZED: "WOO_UNAUTHORIZED",
29
+ WOO_FORBIDDEN: "WOO_FORBIDDEN",
30
+ // WooCommerce — resource-specific
31
+ WOO_COUPON_NOT_FOUND: "WOO_COUPON_NOT_FOUND",
32
+ WOO_PRODUCT_NOT_FOUND: "WOO_PRODUCT_NOT_FOUND",
33
+ WOO_ORDER_NOT_FOUND: "WOO_ORDER_NOT_FOUND",
34
+ WOO_CUSTOMER_NOT_FOUND: "WOO_CUSTOMER_NOT_FOUND",
35
+ WOO_CATEGORY_NOT_FOUND: "WOO_CATEGORY_NOT_FOUND",
36
+ WOO_REVIEW_NOT_FOUND: "WOO_REVIEW_NOT_FOUND",
37
+ WOO_WEBHOOK_NOT_FOUND: "WOO_WEBHOOK_NOT_FOUND",
38
+ WOO_SHIPPING_ZONE_NOT_FOUND: "WOO_SHIPPING_ZONE_NOT_FOUND",
39
+ // Auth
40
+ AUTH_JWT_FAILED: "AUTH_JWT_FAILED",
41
+ AUTH_CREDENTIALS_INVALID: "AUTH_CREDENTIALS_INVALID",
42
+ AUTH_TOKEN_INVALID: "AUTH_TOKEN_INVALID"
43
+ };
44
+ var defaultMessages = {
45
+ WP_REQUEST_FAILED: "WordPress API request failed",
46
+ WP_NOT_FOUND: "WordPress resource not found",
47
+ WP_UNAUTHORIZED: "WordPress authentication required",
48
+ WP_FORBIDDEN: "WordPress access denied",
49
+ GQL_REQUEST_FAILED: "WPGraphQL request failed",
50
+ GQL_NO_DATA: "No data returned from WPGraphQL",
51
+ GQL_ERRORS_IN_RESPONSE: "WPGraphQL returned errors",
52
+ WOO_REQUEST_FAILED: "WooCommerce API request failed",
53
+ WOO_NOT_FOUND: "WooCommerce resource not found",
54
+ WOO_UNAUTHORIZED: "WooCommerce authentication required",
55
+ WOO_FORBIDDEN: "WooCommerce access denied",
56
+ WOO_COUPON_NOT_FOUND: "Coupon not found",
57
+ WOO_PRODUCT_NOT_FOUND: "Product not found",
58
+ WOO_ORDER_NOT_FOUND: "Order not found",
59
+ WOO_CUSTOMER_NOT_FOUND: "Customer not found",
60
+ WOO_CATEGORY_NOT_FOUND: "Category not found",
61
+ WOO_TAG_NOT_FOUND: "Tag not found",
62
+ WOO_REVIEW_NOT_FOUND: "Product review not found",
63
+ WOO_WEBHOOK_NOT_FOUND: "Webhook not found",
64
+ WOO_SHIPPING_ZONE_NOT_FOUND: "Shipping zone not found",
65
+ AUTH_JWT_FAILED: "JWT authentication failed",
66
+ AUTH_CREDENTIALS_INVALID: "Invalid credentials",
67
+ AUTH_TOKEN_INVALID: "JWT token is invalid or expired"
68
+ };
69
+ function resolveMessage(code, overrides) {
70
+ return overrides?.[code] ?? defaultMessages[code];
71
+ }
72
+
73
+ // src/auth/types.ts
74
+ var AuthenticationError = class extends Error {
75
+ constructor(code, status, message, detail) {
76
+ super(detail ? `${message}: ${detail}` : message);
77
+ __publicField(this, "code", code);
78
+ __publicField(this, "status", status);
79
+ this.name = "AuthenticationError";
80
+ }
81
+ };
82
+
83
+ // src/auth/jwt.ts
84
+ function resolveAuthErrorCode(status) {
85
+ if (status === 401) return ErrorCode.AUTH_CREDENTIALS_INVALID;
86
+ if (status === 403) return ErrorCode.AUTH_TOKEN_INVALID;
87
+ return ErrorCode.AUTH_JWT_FAILED;
88
+ }
89
+ async function authenticateJwt(config, credentials) {
90
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token`;
91
+ const response = await fetch(url, {
92
+ method: "POST",
93
+ headers: { "Content-Type": "application/json" },
94
+ body: JSON.stringify(credentials),
95
+ cache: "no-store"
96
+ });
97
+ if (!response.ok) {
98
+ const code = resolveAuthErrorCode(response.status);
99
+ throw new AuthenticationError(
100
+ code,
101
+ response.status,
102
+ resolveMessage(code, config.errorMessages),
103
+ response.statusText
104
+ );
105
+ }
106
+ return response.json();
107
+ }
108
+ async function validateJwtToken(config, token) {
109
+ const url = `${resolveBaseUrl(config)}/wp-json/jwt-auth/v1/token/validate`;
110
+ const response = await fetch(url, {
111
+ method: "POST",
112
+ headers: { Authorization: `Bearer ${token}` },
113
+ cache: "no-store"
114
+ });
115
+ return response.ok;
116
+ }
117
+ var AuthContext = createContext(null);
118
+ var TOKEN_KEY = "nw_auth_token";
119
+ var USER_KEY = "nw_auth_user";
120
+ function AuthProvider({
121
+ config,
122
+ children
123
+ }) {
124
+ const [user, setUser] = useState(null);
125
+ const [isLoading, setIsLoading] = useState(true);
126
+ const [error, setError] = useState(null);
127
+ const clearStorage = useCallback(() => {
128
+ localStorage.removeItem(TOKEN_KEY);
129
+ localStorage.removeItem(USER_KEY);
130
+ }, []);
131
+ useEffect(() => {
132
+ const token = localStorage.getItem(TOKEN_KEY);
133
+ const storedUser = localStorage.getItem(USER_KEY);
134
+ if (!token || !storedUser) {
135
+ setIsLoading(false);
136
+ return;
137
+ }
138
+ validateJwtToken(config, token).then((valid) => {
139
+ if (valid) {
140
+ setUser(JSON.parse(storedUser));
141
+ } else {
142
+ clearStorage();
143
+ }
144
+ }).catch(() => clearStorage()).finally(() => setIsLoading(false));
145
+ }, []);
146
+ const login = async (credentials) => {
147
+ setError(null);
148
+ setIsLoading(true);
149
+ try {
150
+ const response = await authenticateJwt(config, credentials);
151
+ const authUser = {
152
+ token: response.token,
153
+ email: response.user_email,
154
+ nicename: response.user_nicename,
155
+ displayName: response.user_display_name
156
+ };
157
+ localStorage.setItem(TOKEN_KEY, response.token);
158
+ localStorage.setItem(USER_KEY, JSON.stringify(authUser));
159
+ setUser(authUser);
160
+ } catch (err) {
161
+ const message = err instanceof Error ? err.message : "Authentication failed";
162
+ setError(message);
163
+ throw err;
164
+ } finally {
165
+ setIsLoading(false);
166
+ }
167
+ };
168
+ const logout = () => {
169
+ clearStorage();
170
+ setUser(null);
171
+ setError(null);
172
+ };
173
+ return /* @__PURE__ */ jsx(AuthContext.Provider, { value: { user, isLoggedIn: !!user, isLoading, error, login, logout }, children });
174
+ }
175
+ function useAuth() {
176
+ const ctx = useContext(AuthContext);
177
+ if (!ctx) throw new Error("useAuth must be used within an AuthProvider");
178
+ return ctx;
179
+ }
180
+
181
+ // src/integrations/restApi/core/client/types.ts
182
+ var WordPressAPIError = class extends Error {
183
+ constructor(code, status, endpoint, message, detail) {
184
+ super(detail ? `${message}: ${detail}` : message);
185
+ __publicField(this, "code", code);
186
+ __publicField(this, "status", status);
187
+ __publicField(this, "endpoint", endpoint);
188
+ this.name = "WordPressAPIError";
189
+ }
190
+ };
191
+
192
+ // src/integrations/restApi/core/client/url.ts
193
+ function buildUrl(config, path, query) {
194
+ const base = resolveBaseUrl(config);
195
+ if (!query) return `${base}${path}`;
196
+ const params = new URLSearchParams();
197
+ for (const [key, value] of Object.entries(query)) {
198
+ if (value !== void 0 && value !== null) {
199
+ params.set(key, String(value));
200
+ }
201
+ }
202
+ const qs = params.toString();
203
+ return qs ? `${base}${path}?${qs}` : `${base}${path}`;
204
+ }
205
+
206
+ // src/integrations/restApi/core/client/fetcher.ts
207
+ var USER_AGENT = "NextWordpress Client";
208
+ function resolveWpErrorCode(status) {
209
+ if (status === 401) return ErrorCode.WP_UNAUTHORIZED;
210
+ if (status === 403) return ErrorCode.WP_FORBIDDEN;
211
+ if (status === 404) return ErrorCode.WP_NOT_FOUND;
212
+ return ErrorCode.WP_REQUEST_FAILED;
213
+ }
214
+ function createFetcher(config) {
215
+ const cacheTtl = config.cacheTTL ?? 300;
216
+ async function doFetch(url, init = {}) {
217
+ const response = await fetch(url, init);
218
+ if (!response.ok) {
219
+ const code = resolveWpErrorCode(response.status);
220
+ throw new WordPressAPIError(
221
+ code,
222
+ response.status,
223
+ url,
224
+ resolveMessage(code, config.errorMessages),
225
+ response.statusText
226
+ );
227
+ }
228
+ return response;
229
+ }
230
+ async function wpFetch(path, query, tags = ["wordpress"]) {
231
+ const url = buildUrl(config, path, query);
232
+ const res = await doFetch(url, {
233
+ headers: { "User-Agent": USER_AGENT },
234
+ next: { tags, revalidate: cacheTtl }
235
+ });
236
+ return await res.json();
237
+ }
238
+ async function wpFetchGraceful(path, fallback, query, tags = ["wordpress"]) {
239
+ try {
240
+ return await wpFetch(path, query, tags);
241
+ } catch {
242
+ console.warn(`WordPress fetch failed for ${path}`);
243
+ return fallback;
244
+ }
245
+ }
246
+ async function wpFetchPaginated(path, query, tags = ["wordpress"]) {
247
+ const url = buildUrl(config, path, query);
248
+ const res = await doFetch(url, {
249
+ headers: { "User-Agent": USER_AGENT },
250
+ next: { tags, revalidate: cacheTtl }
251
+ });
252
+ return {
253
+ data: await res.json(),
254
+ headers: {
255
+ total: parseInt(res.headers.get("X-WP-Total") ?? "0", 10),
256
+ totalPages: parseInt(res.headers.get("X-WP-TotalPages") ?? "0", 10)
257
+ }
258
+ };
259
+ }
260
+ async function wpFetchPaginatedGraceful(path, query, tags = ["wordpress"]) {
261
+ const empty = { data: [], headers: { total: 0, totalPages: 0 } };
262
+ try {
263
+ return await wpFetchPaginated(path, query, tags);
264
+ } catch {
265
+ console.warn(`WordPress paginated fetch failed for ${path}`);
266
+ return empty;
267
+ }
268
+ }
269
+ async function wpMutate(path, body, method = "POST", authToken) {
270
+ const url = buildUrl(config, path);
271
+ const headers = {
272
+ "Content-Type": "application/json",
273
+ "User-Agent": USER_AGENT
274
+ };
275
+ if (authToken) {
276
+ headers["Authorization"] = authToken.startsWith("Basic ") || authToken.startsWith("Bearer ") ? authToken : `Bearer ${authToken}`;
277
+ }
278
+ const res = await doFetch(url, {
279
+ method,
280
+ headers,
281
+ body: JSON.stringify(body),
282
+ cache: "no-store"
283
+ });
284
+ return await res.json();
285
+ }
286
+ async function wpUpload(path, file, filename, mimeType, authToken) {
287
+ const url = buildUrl(config, path);
288
+ const res = await doFetch(url, {
289
+ method: "POST",
290
+ headers: {
291
+ "Content-Disposition": `attachment; filename="${filename}"`,
292
+ "Content-Type": mimeType,
293
+ "User-Agent": USER_AGENT,
294
+ "Authorization": authToken.startsWith("Basic ") || authToken.startsWith("Bearer ") ? authToken : `Bearer ${authToken}`
295
+ },
296
+ body: file,
297
+ cache: "no-store"
298
+ });
299
+ return await res.json();
300
+ }
301
+ return { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful, wpMutate, wpUpload };
302
+ }
303
+
304
+ // src/integrations/restApi/core/posts/queries.ts
305
+ function createPostsQueries(fetcher) {
306
+ const { wpFetch, wpFetchGraceful, wpFetchPaginated, wpFetchPaginatedGraceful } = fetcher;
307
+ async function getPostsPaginated(page = 1, perPage = 9, filterParams) {
308
+ const query = { _embed: true, per_page: perPage, page };
309
+ const cacheTags = ["wordpress", "posts", `posts-page-${page}`];
310
+ if (filterParams?.search) {
311
+ query.search = filterParams.search;
312
+ cacheTags.push("posts-search");
313
+ }
314
+ if (filterParams?.author) {
315
+ query.author = filterParams.author;
316
+ cacheTags.push(`posts-author-${filterParams.author}`);
317
+ }
318
+ if (filterParams?.tag) {
319
+ query.tags = filterParams.tag;
320
+ cacheTags.push(`posts-tag-${filterParams.tag}`);
321
+ }
322
+ if (filterParams?.category) {
323
+ query.categories = filterParams.category;
324
+ cacheTags.push(`posts-category-${filterParams.category}`);
325
+ }
326
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", query, cacheTags);
327
+ }
328
+ async function getRecentPosts(filterParams) {
329
+ const query = { _embed: true, per_page: 100 };
330
+ if (filterParams?.search) query.search = filterParams.search;
331
+ if (filterParams?.author) query.author = filterParams.author;
332
+ if (filterParams?.tag) query.tags = filterParams.tag;
333
+ if (filterParams?.category) query.categories = filterParams.category;
334
+ return wpFetchGraceful("/wp-json/wp/v2/posts", [], query, ["wordpress", "posts"]);
335
+ }
336
+ async function getPostById(id) {
337
+ return wpFetch(`/wp-json/wp/v2/posts/${id}`);
338
+ }
339
+ async function getPostBySlug(slug) {
340
+ const posts = await wpFetchGraceful("/wp-json/wp/v2/posts", [], { slug, _embed: true });
341
+ return posts[0];
342
+ }
343
+ async function getPostsByCategory(categoryId) {
344
+ return wpFetch("/wp-json/wp/v2/posts", { categories: categoryId });
345
+ }
346
+ async function getPostsByTag(tagId) {
347
+ return wpFetch("/wp-json/wp/v2/posts", { tags: tagId });
348
+ }
349
+ async function getPostsByAuthor(authorId) {
350
+ return wpFetch("/wp-json/wp/v2/posts", { author: authorId });
351
+ }
352
+ async function getPostsByCategoryPaginated(categoryId, page = 1, perPage = 9) {
353
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
354
+ _embed: true,
355
+ per_page: perPage,
356
+ page,
357
+ categories: categoryId
358
+ });
359
+ }
360
+ async function getPostsByTagPaginated(tagId, page = 1, perPage = 9) {
361
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
362
+ _embed: true,
363
+ per_page: perPage,
364
+ page,
365
+ tags: tagId
366
+ });
367
+ }
368
+ async function getPostsByAuthorPaginated(authorId, page = 1, perPage = 9) {
369
+ return wpFetchPaginatedGraceful("/wp-json/wp/v2/posts", {
370
+ _embed: true,
371
+ per_page: perPage,
372
+ page,
373
+ author: authorId
374
+ });
375
+ }
376
+ async function getAllPostSlugs() {
377
+ try {
378
+ const allSlugs = [];
379
+ let page = 1;
380
+ let hasMore = true;
381
+ while (hasMore) {
382
+ const response = await wpFetchPaginated(
383
+ "/wp-json/wp/v2/posts",
384
+ { per_page: 100, page, _fields: "slug" }
385
+ );
386
+ allSlugs.push(...response.data.map((post) => ({ slug: post.slug })));
387
+ hasMore = page < response.headers.totalPages;
388
+ page++;
389
+ }
390
+ return allSlugs;
391
+ } catch {
392
+ console.warn("WordPress unavailable, skipping static generation for posts");
393
+ return [];
394
+ }
395
+ }
396
+ async function getAllPostsForSitemap() {
397
+ try {
398
+ const allPosts = [];
399
+ let page = 1;
400
+ let hasMore = true;
401
+ while (hasMore) {
402
+ const response = await wpFetchPaginated(
403
+ "/wp-json/wp/v2/posts",
404
+ { per_page: 100, page, _fields: "slug,modified" }
405
+ );
406
+ allPosts.push(...response.data.map((post) => ({ slug: post.slug, modified: post.modified })));
407
+ hasMore = page < response.headers.totalPages;
408
+ page++;
409
+ }
410
+ return allPosts;
411
+ } catch {
412
+ console.warn("WordPress unavailable, skipping sitemap generation");
413
+ return [];
414
+ }
415
+ }
416
+ return {
417
+ getPostsPaginated,
418
+ getRecentPosts,
419
+ getPostById,
420
+ getPostBySlug,
421
+ getPostsByCategory,
422
+ getPostsByTag,
423
+ getPostsByAuthor,
424
+ getPostsByCategoryPaginated,
425
+ getPostsByTagPaginated,
426
+ getPostsByAuthorPaginated,
427
+ getAllPostSlugs,
428
+ getAllPostsForSitemap
429
+ };
430
+ }
431
+
432
+ // src/hooks/core/usePosts.ts
433
+ function usePosts(config, filter, swrOptions) {
434
+ const key = ["wp-posts", config.clientURL, JSON.stringify(filter ?? null)];
435
+ return useSWR2(
436
+ key,
437
+ () => {
438
+ const fetcher = createFetcher(config);
439
+ return createPostsQueries(fetcher).getRecentPosts(filter);
440
+ },
441
+ swrOptions
442
+ );
443
+ }
444
+ function usePost(config, id, swrOptions) {
445
+ const key = id != null ? ["wp-post", config.clientURL, id] : null;
446
+ return useSWR2(
447
+ key,
448
+ () => {
449
+ const fetcher = createFetcher(config);
450
+ return createPostsQueries(fetcher).getPostById(id);
451
+ },
452
+ swrOptions
453
+ );
454
+ }
455
+ function usePostBySlug(config, slug, swrOptions) {
456
+ const key = slug ? ["wp-post-slug", config.clientURL, slug] : null;
457
+ return useSWR2(
458
+ key,
459
+ () => {
460
+ const fetcher = createFetcher(config);
461
+ return createPostsQueries(fetcher).getPostBySlug(slug);
462
+ },
463
+ swrOptions
464
+ );
465
+ }
466
+ function usePostsPaginated(config, page = 1, perPage = 9, filter, swrOptions) {
467
+ const key = ["wp-posts-paginated", config.clientURL, page, perPage, JSON.stringify(filter ?? null)];
468
+ return useSWR2(
469
+ key,
470
+ () => {
471
+ const fetcher = createFetcher(config);
472
+ return createPostsQueries(fetcher).getPostsPaginated(page, perPage, filter);
473
+ },
474
+ swrOptions
475
+ );
476
+ }
477
+
478
+ // src/integrations/restApi/woocommerce/client/types.ts
479
+ var WooCommerceError = class extends Error {
480
+ constructor(code, status, endpoint, message, upstreamCode, detail) {
481
+ super(detail ? `${message}: ${detail}` : message);
482
+ __publicField(this, "code", code);
483
+ __publicField(this, "status", status);
484
+ __publicField(this, "endpoint", endpoint);
485
+ __publicField(this, "upstreamCode", upstreamCode);
486
+ this.name = "WooCommerceError";
487
+ }
488
+ };
489
+
490
+ // src/integrations/restApi/woocommerce/client/errorMap.ts
491
+ var upstreamToErrorCode = {
492
+ woocommerce_rest_coupon_invalid_id: ErrorCode.WOO_COUPON_NOT_FOUND,
493
+ woocommerce_rest_product_invalid_id: ErrorCode.WOO_PRODUCT_NOT_FOUND,
494
+ woocommerce_rest_order_invalid_id: ErrorCode.WOO_ORDER_NOT_FOUND,
495
+ woocommerce_rest_customer_invalid_id: ErrorCode.WOO_CUSTOMER_NOT_FOUND,
496
+ woocommerce_rest_term_invalid: ErrorCode.WOO_CATEGORY_NOT_FOUND,
497
+ woocommerce_rest_review_invalid_id: ErrorCode.WOO_REVIEW_NOT_FOUND,
498
+ woocommerce_rest_webhook_invalid_id: ErrorCode.WOO_WEBHOOK_NOT_FOUND,
499
+ woocommerce_rest_shipping_zone_invalid_id: ErrorCode.WOO_SHIPPING_ZONE_NOT_FOUND
500
+ };
501
+ function resolveWooErrorCode(status, upstreamCode) {
502
+ if (status === 401) return ErrorCode.WOO_UNAUTHORIZED;
503
+ if (status === 403) return ErrorCode.WOO_FORBIDDEN;
504
+ if (status === 404) {
505
+ if (upstreamCode) {
506
+ const mapped = upstreamToErrorCode[upstreamCode];
507
+ if (mapped) return mapped;
508
+ }
509
+ return ErrorCode.WOO_NOT_FOUND;
510
+ }
511
+ return ErrorCode.WOO_REQUEST_FAILED;
512
+ }
513
+
514
+ // src/integrations/restApi/woocommerce/client/fetcher.ts
515
+ var USER_AGENT2 = "NextWordpress WooCommerce Client";
516
+ var DEFAULT_CACHE_TTL = 3600;
517
+ function toQueryString(params) {
518
+ const pairs = [];
519
+ for (const [key, value] of Object.entries(params)) {
520
+ if (value === void 0 || value === null) continue;
521
+ pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`);
522
+ }
523
+ return pairs.join("&");
524
+ }
525
+ function createWooCommerceFetcher(config) {
526
+ const cacheTTL = config.cacheTTL ?? DEFAULT_CACHE_TTL;
527
+ function withAuth(query) {
528
+ return { ...query, consumer_key: config.consumerKey, consumer_secret: config.consumerSecret };
529
+ }
530
+ function buildUrl2(path, query) {
531
+ const base = typeof window !== "undefined" && config.clientURL ? config.clientURL : config.serverURL;
532
+ return `${base}${path}?${toQueryString(withAuth(query))}`;
533
+ }
534
+ async function throwWooError(response, url) {
535
+ const body = await response.json().catch(() => ({}));
536
+ const errorCode = resolveWooErrorCode(response.status, body.code);
537
+ throw new WooCommerceError(
538
+ errorCode,
539
+ response.status,
540
+ url,
541
+ resolveMessage(errorCode, config.errorMessages),
542
+ body.code,
543
+ body.message
544
+ );
545
+ }
546
+ async function wcFetch(path, query, tags = ["woocommerce"], options) {
547
+ const url = buildUrl2(path, query);
548
+ const isMutation = options?.method && options.method !== "GET";
549
+ const noStore = options?.cache === "no-store";
550
+ const response = await fetch(url, {
551
+ ...options,
552
+ headers: {
553
+ "User-Agent": USER_AGENT2,
554
+ "Content-Type": "application/json",
555
+ ...options?.headers
556
+ },
557
+ next: isMutation || noStore ? void 0 : { tags, revalidate: cacheTTL }
558
+ });
559
+ if (!response.ok) {
560
+ await throwWooError(response, url);
561
+ }
562
+ return response.json();
563
+ }
564
+ async function wcFetchGraceful(path, fallback, query, tags = ["woocommerce"]) {
565
+ try {
566
+ return await wcFetch(path, query, tags);
567
+ } catch (err) {
568
+ console.warn(`WooCommerce fetch failed for ${path}`, err);
569
+ return fallback;
570
+ }
571
+ }
572
+ async function wcFetchPaginated(path, query, tags = ["woocommerce"]) {
573
+ const url = buildUrl2(path, query);
574
+ const response = await fetch(url, {
575
+ headers: { "User-Agent": USER_AGENT2 },
576
+ next: { tags, revalidate: cacheTTL }
577
+ });
578
+ if (!response.ok) {
579
+ await throwWooError(response, url);
580
+ }
581
+ return {
582
+ data: await response.json(),
583
+ headers: {
584
+ total: parseInt(response.headers.get("X-WP-Total") ?? "0", 10),
585
+ totalPages: parseInt(response.headers.get("X-WP-TotalPages") ?? "0", 10)
586
+ }
587
+ };
588
+ }
589
+ async function wcFetchPaginatedGraceful(path, query, tags = ["woocommerce"]) {
590
+ const empty = { data: [], headers: { total: 0, totalPages: 0 } };
591
+ try {
592
+ return await wcFetchPaginated(path, query, tags);
593
+ } catch (err) {
594
+ console.warn(`WooCommerce paginated fetch failed for ${path}`, err);
595
+ return empty;
596
+ }
597
+ }
598
+ async function wcMutate(path, body, method = "POST") {
599
+ return wcFetch(path, void 0, ["woocommerce"], {
600
+ method,
601
+ body: JSON.stringify(body)
602
+ });
603
+ }
604
+ return { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful, wcMutate };
605
+ }
606
+
607
+ // src/integrations/restApi/woocommerce/products/queries.ts
608
+ function buildProductQuery(base, filterParams) {
609
+ const query = { ...base };
610
+ if (!filterParams) return query;
611
+ if (filterParams.category !== void 0) query.category = filterParams.category;
612
+ if (filterParams.tag !== void 0) query.tag = filterParams.tag;
613
+ if (filterParams.featured !== void 0) query.featured = filterParams.featured;
614
+ if (filterParams.on_sale !== void 0) query.on_sale = filterParams.on_sale;
615
+ if (filterParams.min_price !== void 0) query.min_price = filterParams.min_price;
616
+ if (filterParams.max_price !== void 0) query.max_price = filterParams.max_price;
617
+ if (filterParams.search !== void 0) query.search = filterParams.search;
618
+ if (filterParams.orderby !== void 0) query.orderby = filterParams.orderby;
619
+ if (filterParams.order !== void 0) query.order = filterParams.order;
620
+ if (filterParams.stock_status !== void 0) query.stock_status = filterParams.stock_status;
621
+ if (filterParams.type !== void 0) query.type = filterParams.type;
622
+ return query;
623
+ }
624
+ function createProductsQueries(fetcher) {
625
+ const { wcFetch, wcFetchGraceful, wcFetchPaginated, wcFetchPaginatedGraceful } = fetcher;
626
+ async function getProducts(filterParams) {
627
+ const query = buildProductQuery({ per_page: 100, status: "publish" }, filterParams);
628
+ return wcFetchGraceful("/wp-json/wc/v3/products", [], query, [
629
+ "woocommerce",
630
+ "products"
631
+ ]);
632
+ }
633
+ async function getProductsPaginated(page = 1, perPage = 12, filterParams) {
634
+ const query = buildProductQuery({ per_page: perPage, page, status: "publish" }, filterParams);
635
+ const cacheTags = ["woocommerce", "products", `products-page-${page}`];
636
+ if (filterParams?.category) cacheTags.push(`products-category-${filterParams.category}`);
637
+ if (filterParams?.tag) cacheTags.push(`products-tag-${filterParams.tag}`);
638
+ if (filterParams?.search) cacheTags.push("products-search");
639
+ return wcFetchPaginatedGraceful("/wp-json/wc/v3/products", query, cacheTags);
640
+ }
641
+ async function getProductById(id) {
642
+ return wcFetch(`/wp-json/wc/v3/products/${id}`, void 0, [
643
+ "woocommerce",
644
+ "products",
645
+ `product-${id}`
646
+ ]);
647
+ }
648
+ async function getProductBySlug(slug) {
649
+ const products = await wcFetchGraceful(
650
+ "/wp-json/wc/v3/products",
651
+ [],
652
+ { slug },
653
+ ["woocommerce", "products", `product-slug-${slug}`]
654
+ );
655
+ return products[0];
656
+ }
657
+ async function getFeaturedProducts(limit = 10) {
658
+ return wcFetchGraceful(
659
+ "/wp-json/wc/v3/products",
660
+ [],
661
+ { featured: true, per_page: limit, status: "publish" },
662
+ ["woocommerce", "products", "featured"]
663
+ );
664
+ }
665
+ async function getOnSaleProducts(limit = 10) {
666
+ return wcFetchGraceful(
667
+ "/wp-json/wc/v3/products",
668
+ [],
669
+ { on_sale: true, per_page: limit, status: "publish" },
670
+ ["woocommerce", "products", "on-sale"]
671
+ );
672
+ }
673
+ async function getRelatedProducts(productId) {
674
+ const product = await getProductById(productId);
675
+ if (!product.related_ids.length) return [];
676
+ return wcFetchGraceful(
677
+ "/wp-json/wc/v3/products",
678
+ [],
679
+ { include: product.related_ids.join(","), per_page: 10, status: "publish" },
680
+ ["woocommerce", "products", `related-${productId}`]
681
+ );
682
+ }
683
+ async function getAllProductSlugs() {
684
+ try {
685
+ const allSlugs = [];
686
+ let page = 1;
687
+ let hasMore = true;
688
+ while (hasMore) {
689
+ const response = await wcFetchPaginated("/wp-json/wc/v3/products", {
690
+ per_page: 100,
691
+ page,
692
+ status: "publish",
693
+ _fields: "slug"
694
+ });
695
+ allSlugs.push(...response.data.map((p) => ({ slug: p.slug })));
696
+ hasMore = page < response.headers.totalPages;
697
+ page++;
698
+ }
699
+ return allSlugs;
700
+ } catch {
701
+ console.warn("WooCommerce unavailable, skipping static generation for products");
702
+ return [];
703
+ }
704
+ }
705
+ async function getProductVariations(productId) {
706
+ return wcFetchGraceful(
707
+ `/wp-json/wc/v3/products/${productId}/variations`,
708
+ [],
709
+ { per_page: 100 },
710
+ ["woocommerce", "products", `product-${productId}`, "variations"]
711
+ );
712
+ }
713
+ async function getProductVariationById(productId, variationId) {
714
+ return wcFetch(
715
+ `/wp-json/wc/v3/products/${productId}/variations/${variationId}`,
716
+ void 0,
717
+ ["woocommerce", "products", `product-${productId}`, `variation-${variationId}`]
718
+ );
719
+ }
720
+ return {
721
+ getProducts,
722
+ getProductsPaginated,
723
+ getProductById,
724
+ getProductBySlug,
725
+ getFeaturedProducts,
726
+ getOnSaleProducts,
727
+ getRelatedProducts,
728
+ getAllProductSlugs,
729
+ getProductVariations,
730
+ getProductVariationById
731
+ };
732
+ }
733
+
734
+ // src/hooks/woocommerce/useProducts.ts
735
+ function useProducts(config, filter, swrOptions) {
736
+ const key = ["wc-products", config.serverURL, JSON.stringify(filter ?? null)];
737
+ return useSWR2(
738
+ key,
739
+ () => {
740
+ const fetcher = createWooCommerceFetcher(config);
741
+ return createProductsQueries(fetcher).getProducts(filter);
742
+ },
743
+ swrOptions
744
+ );
745
+ }
746
+ function useProduct(config, id, swrOptions) {
747
+ const key = id != null ? ["wc-product", config.serverURL, id] : null;
748
+ return useSWR2(
749
+ key,
750
+ () => {
751
+ const fetcher = createWooCommerceFetcher(config);
752
+ return createProductsQueries(fetcher).getProductById(id);
753
+ },
754
+ swrOptions
755
+ );
756
+ }
757
+ function useProductBySlug(config, slug, swrOptions) {
758
+ const key = slug ? ["wc-product-slug", config.serverURL, slug] : null;
759
+ return useSWR2(
760
+ key,
761
+ () => {
762
+ const fetcher = createWooCommerceFetcher(config);
763
+ return createProductsQueries(fetcher).getProductBySlug(slug);
764
+ },
765
+ swrOptions
766
+ );
767
+ }
768
+ function useProductsPaginated(config, page = 1, perPage = 12, filter, swrOptions) {
769
+ const key = ["wc-products-paginated", config.serverURL, page, perPage, JSON.stringify(filter ?? null)];
770
+ return useSWR2(
771
+ key,
772
+ () => {
773
+ const fetcher = createWooCommerceFetcher(config);
774
+ return createProductsQueries(fetcher).getProductsPaginated(page, perPage, filter);
775
+ },
776
+ swrOptions
777
+ );
778
+ }
779
+ function useFeaturedProducts(config, limit = 10, swrOptions) {
780
+ const key = ["wc-products-featured", config.serverURL, limit];
781
+ return useSWR2(
782
+ key,
783
+ () => {
784
+ const fetcher = createWooCommerceFetcher(config);
785
+ return createProductsQueries(fetcher).getFeaturedProducts(limit);
786
+ },
787
+ swrOptions
788
+ );
789
+ }
790
+
791
+ // src/integrations/restApi/woocommerce/orders/queries.ts
792
+ function createOrdersQueries(fetcher) {
793
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
794
+ async function createOrder(input) {
795
+ return wcMutate("/wp-json/wc/v3/orders", input, "POST");
796
+ }
797
+ async function getOrderById(id) {
798
+ return wcFetch(`/wp-json/wc/v3/orders/${id}`, void 0, [
799
+ "woocommerce",
800
+ "orders",
801
+ `order-${id}`
802
+ ]);
803
+ }
804
+ async function updateOrder(id, data) {
805
+ return wcMutate(`/wp-json/wc/v3/orders/${id}`, data, "PUT");
806
+ }
807
+ async function getOrdersByCustomer(customerId) {
808
+ return wcFetchGraceful(
809
+ "/wp-json/wc/v3/orders",
810
+ [],
811
+ { customer: customerId, per_page: 100 },
812
+ ["woocommerce", "orders", `orders-customer-${customerId}`]
813
+ );
814
+ }
815
+ async function deleteOrder(id, force = true) {
816
+ return wcMutate(
817
+ `/wp-json/wc/v3/orders/${id}`,
818
+ { force },
819
+ "DELETE"
820
+ );
821
+ }
822
+ return {
823
+ createOrder,
824
+ getOrderById,
825
+ updateOrder,
826
+ getOrdersByCustomer,
827
+ deleteOrder
828
+ };
829
+ }
830
+ var STORAGE_KEY = "nw-cart";
831
+ function isSame(a, b) {
832
+ return a.productId === b.productId && (a.variationId ?? 0) === (b.variationId ?? 0);
833
+ }
834
+ function cartReducer(state, action) {
835
+ switch (action.type) {
836
+ case "LOAD":
837
+ return { items: action.items };
838
+ case "ADD": {
839
+ const existing = state.items.find((i) => isSame(i, action.item));
840
+ if (existing) {
841
+ return {
842
+ items: state.items.map(
843
+ (i) => isSame(i, action.item) ? { ...i, quantity: i.quantity + action.item.quantity } : i
844
+ )
845
+ };
846
+ }
847
+ return { items: [...state.items, action.item] };
848
+ }
849
+ case "REMOVE":
850
+ return { items: state.items.filter((i) => !isSame(i, action)) };
851
+ case "UPDATE":
852
+ if (action.quantity <= 0) {
853
+ return { items: state.items.filter((i) => !isSame(i, action)) };
854
+ }
855
+ return {
856
+ items: state.items.map(
857
+ (i) => isSame(i, action) ? { ...i, quantity: action.quantity } : i
858
+ )
859
+ };
860
+ case "CLEAR":
861
+ return { items: [] };
862
+ }
863
+ }
864
+ var CartContext = createContext(null);
865
+ function CartProvider({ children }) {
866
+ const [state, dispatch] = useReducer(cartReducer, { items: [] });
867
+ useEffect(() => {
868
+ try {
869
+ const stored = localStorage.getItem(STORAGE_KEY);
870
+ if (stored) dispatch({ type: "LOAD", items: JSON.parse(stored) });
871
+ } catch {
872
+ }
873
+ }, []);
874
+ useEffect(() => {
875
+ try {
876
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(state.items));
877
+ } catch {
878
+ }
879
+ }, [state.items]);
880
+ const totalItems = state.items.reduce((sum, i) => sum + i.quantity, 0);
881
+ const subtotal = state.items.reduce((sum, i) => sum + parseFloat(i.price) * i.quantity, 0).toFixed(2);
882
+ function addItem(item, quantity = 1) {
883
+ dispatch({ type: "ADD", item: { ...item, quantity } });
884
+ }
885
+ function removeItem(productId, variationId) {
886
+ dispatch({ type: "REMOVE", productId, variationId });
887
+ }
888
+ function updateQuantity(productId, quantity, variationId) {
889
+ dispatch({ type: "UPDATE", productId, quantity, variationId });
890
+ }
891
+ function clearCart() {
892
+ dispatch({ type: "CLEAR" });
893
+ }
894
+ async function checkout(config, options = {}) {
895
+ if (state.items.length === 0) throw new Error("Cannot checkout with an empty cart");
896
+ const fetcher = createWooCommerceFetcher(config);
897
+ const input = {
898
+ status: "pending",
899
+ line_items: state.items.map((i) => ({
900
+ product_id: i.productId,
901
+ ...i.variationId !== void 0 ? { variation_id: i.variationId } : {},
902
+ quantity: i.quantity
903
+ })),
904
+ ...options.billing ? { billing: options.billing } : {},
905
+ ...options.shipping ? { shipping: options.shipping } : {},
906
+ ...options.paymentMethod ? { payment_method: options.paymentMethod } : {},
907
+ ...options.paymentMethodTitle ? { payment_method_title: options.paymentMethodTitle } : {},
908
+ ...options.customerNote ? { customer_note: options.customerNote } : {},
909
+ ...options.couponCodes ? { coupon_lines: options.couponCodes.map((code) => ({ code })) } : {}
910
+ };
911
+ const order = await createOrdersQueries(fetcher).createOrder(input);
912
+ dispatch({ type: "CLEAR" });
913
+ return order;
914
+ }
915
+ return /* @__PURE__ */ jsx(
916
+ CartContext.Provider,
917
+ {
918
+ value: { items: state.items, totalItems, subtotal, isEmpty: state.items.length === 0, addItem, removeItem, updateQuantity, clearCart, checkout },
919
+ children
920
+ }
921
+ );
922
+ }
923
+ function useCart() {
924
+ const ctx = useContext(CartContext);
925
+ if (!ctx) throw new Error("useCart must be used within a CartProvider");
926
+ return ctx;
927
+ }
928
+
929
+ // src/integrations/restApi/woocommerce/customers/queries.ts
930
+ function createCustomersQueries(fetcher) {
931
+ const { wcFetch, wcFetchGraceful, wcMutate } = fetcher;
932
+ async function getCustomerById(id) {
933
+ return wcFetch(`/wp-json/wc/v3/customers/${id}`, void 0, [
934
+ "woocommerce",
935
+ "customers",
936
+ `customer-${id}`
937
+ ]);
938
+ }
939
+ async function getCustomerByEmail(email) {
940
+ const customers = await wcFetchGraceful(
941
+ "/wp-json/wc/v3/customers",
942
+ [],
943
+ { email },
944
+ ["woocommerce", "customers"]
945
+ );
946
+ return customers[0];
947
+ }
948
+ async function getCustomerByEmailNoCache(email) {
949
+ try {
950
+ const customers = await wcFetch(
951
+ "/wp-json/wc/v3/customers",
952
+ { email },
953
+ ["woocommerce", "customers"],
954
+ { cache: "no-store" }
955
+ );
956
+ return customers[0];
957
+ } catch {
958
+ return void 0;
959
+ }
960
+ }
961
+ async function createCustomer(data) {
962
+ return wcFetch(
963
+ "/wp-json/wc/v3/customers",
964
+ void 0,
965
+ ["woocommerce", "customers"],
966
+ { method: "POST", body: JSON.stringify(data) }
967
+ );
968
+ }
969
+ async function updateCustomer(id, data) {
970
+ return wcMutate(`/wp-json/wc/v3/customers/${id}`, data, "PUT");
971
+ }
972
+ async function deleteCustomer(id, reassign) {
973
+ return wcMutate(
974
+ `/wp-json/wc/v3/customers/${id}`,
975
+ { force: true, ...reassign !== void 0 && { reassign } },
976
+ "DELETE"
977
+ );
978
+ }
979
+ return {
980
+ getCustomerById,
981
+ getCustomerByEmail,
982
+ getCustomerByEmailNoCache,
983
+ createCustomer,
984
+ updateCustomer,
985
+ deleteCustomer
986
+ };
987
+ }
988
+ var CustomerContext = createContext(null);
989
+ function WooCommerceCustomerProvider({
990
+ config,
991
+ children
992
+ }) {
993
+ const { user, isLoggedIn } = useAuth();
994
+ const [customer, setCustomer] = useState(null);
995
+ const [orders, setOrders] = useState([]);
996
+ const [isLoading, setIsLoading] = useState(false);
997
+ const [error, setError] = useState(null);
998
+ const [tick, setTick] = useState(0);
999
+ const fetchData = useCallback(async () => {
1000
+ if (!isLoggedIn || !user?.email) {
1001
+ setCustomer(null);
1002
+ setOrders([]);
1003
+ return;
1004
+ }
1005
+ setIsLoading(true);
1006
+ setError(null);
1007
+ try {
1008
+ const fetcher = createWooCommerceFetcher(config);
1009
+ const foundCustomer = await createCustomersQueries(fetcher).getCustomerByEmailNoCache(user.email);
1010
+ if (!foundCustomer) {
1011
+ setCustomer(null);
1012
+ setOrders([]);
1013
+ return;
1014
+ }
1015
+ const customerOrders = await createOrdersQueries(fetcher).getOrdersByCustomer(foundCustomer.id);
1016
+ setCustomer(foundCustomer);
1017
+ setOrders(customerOrders);
1018
+ } catch (err) {
1019
+ setError(err instanceof Error ? err.message : "Failed to load customer data");
1020
+ } finally {
1021
+ setIsLoading(false);
1022
+ }
1023
+ }, [isLoggedIn, user?.email, config, tick]);
1024
+ useEffect(() => {
1025
+ void fetchData();
1026
+ }, [fetchData]);
1027
+ const updateCustomer = async (data) => {
1028
+ if (!customer) throw new Error("No customer loaded");
1029
+ const fetcher = createWooCommerceFetcher(config);
1030
+ const updated = await createCustomersQueries(fetcher).updateCustomer(customer.id, data);
1031
+ setCustomer(updated);
1032
+ return updated;
1033
+ };
1034
+ const refetch = () => setTick((t) => t + 1);
1035
+ return /* @__PURE__ */ jsx(CustomerContext.Provider, { value: { customer, orders, isLoading, error, updateCustomer, refetch }, children });
1036
+ }
1037
+ function useCustomer() {
1038
+ const ctx = useContext(CustomerContext);
1039
+ if (!ctx) throw new Error("useCustomer must be used within a WooCommerceCustomerProvider");
1040
+ return ctx;
1041
+ }
1042
+
1043
+ // src/integrations/wpGraphQL/client/types.ts
1044
+ var WPGraphQLError = class extends Error {
1045
+ constructor(code, status, endpoint, message, gqlErrors) {
1046
+ super(message);
1047
+ __publicField(this, "code", code);
1048
+ __publicField(this, "status", status);
1049
+ __publicField(this, "endpoint", endpoint);
1050
+ __publicField(this, "gqlErrors", gqlErrors);
1051
+ this.name = "WPGraphQLError";
1052
+ }
1053
+ };
1054
+
1055
+ // src/integrations/wpGraphQL/client/fetcher.ts
1056
+ var USER_AGENT3 = "NextWordpress WPGraphQL Client";
1057
+ function createWPGraphQLFetcher(config) {
1058
+ const url = `${resolveBaseUrl(config)}/graphql`;
1059
+ const cacheTTL = config.cacheTTL ?? 300;
1060
+ async function gqlFetch(document, variables, tags = ["wpgraphql"]) {
1061
+ const response = await fetch(url, {
1062
+ method: "POST",
1063
+ headers: {
1064
+ "Content-Type": "application/json",
1065
+ "User-Agent": USER_AGENT3
1066
+ },
1067
+ body: JSON.stringify({ query: document, variables }),
1068
+ next: { tags, revalidate: cacheTTL }
1069
+ });
1070
+ if (!response.ok) {
1071
+ throw new WPGraphQLError(
1072
+ ErrorCode.GQL_REQUEST_FAILED,
1073
+ response.status,
1074
+ url,
1075
+ resolveMessage(ErrorCode.GQL_REQUEST_FAILED, config.errorMessages)
1076
+ );
1077
+ }
1078
+ const parsed = await response.json();
1079
+ if (parsed.errors && parsed.errors.length > 0) {
1080
+ throw new WPGraphQLError(
1081
+ ErrorCode.GQL_ERRORS_IN_RESPONSE,
1082
+ 200,
1083
+ url,
1084
+ resolveMessage(ErrorCode.GQL_ERRORS_IN_RESPONSE, config.errorMessages),
1085
+ parsed.errors
1086
+ );
1087
+ }
1088
+ if (parsed.data === void 0) {
1089
+ throw new WPGraphQLError(
1090
+ ErrorCode.GQL_NO_DATA,
1091
+ 200,
1092
+ url,
1093
+ resolveMessage(ErrorCode.GQL_NO_DATA, config.errorMessages)
1094
+ );
1095
+ }
1096
+ return parsed.data;
1097
+ }
1098
+ async function gqlFetchGraceful(document, fallback, variables, tags = ["wpgraphql"]) {
1099
+ try {
1100
+ return await gqlFetch(document, variables, tags);
1101
+ } catch {
1102
+ console.warn(`WPGraphQL fetch failed for query`);
1103
+ return fallback;
1104
+ }
1105
+ }
1106
+ async function gqlMutate(document, variables, authToken) {
1107
+ const headers = {
1108
+ "Content-Type": "application/json",
1109
+ "User-Agent": USER_AGENT3
1110
+ };
1111
+ if (authToken) {
1112
+ headers["Authorization"] = authToken;
1113
+ }
1114
+ const response = await fetch(url, {
1115
+ method: "POST",
1116
+ headers,
1117
+ body: JSON.stringify({ query: document, variables }),
1118
+ cache: "no-store"
1119
+ });
1120
+ if (!response.ok) {
1121
+ throw new WPGraphQLError(
1122
+ ErrorCode.GQL_REQUEST_FAILED,
1123
+ response.status,
1124
+ url,
1125
+ resolveMessage(ErrorCode.GQL_REQUEST_FAILED, config.errorMessages)
1126
+ );
1127
+ }
1128
+ const parsed = await response.json();
1129
+ if (parsed.errors && parsed.errors.length > 0) {
1130
+ throw new WPGraphQLError(
1131
+ ErrorCode.GQL_ERRORS_IN_RESPONSE,
1132
+ 200,
1133
+ url,
1134
+ resolveMessage(ErrorCode.GQL_ERRORS_IN_RESPONSE, config.errorMessages),
1135
+ parsed.errors
1136
+ );
1137
+ }
1138
+ if (parsed.data === void 0) {
1139
+ throw new WPGraphQLError(
1140
+ ErrorCode.GQL_NO_DATA,
1141
+ 200,
1142
+ url,
1143
+ resolveMessage(ErrorCode.GQL_NO_DATA, config.errorMessages)
1144
+ );
1145
+ }
1146
+ return parsed.data;
1147
+ }
1148
+ return { gqlFetch, gqlFetchGraceful, gqlMutate };
1149
+ }
1150
+
1151
+ // src/integrations/wpGraphQL/core/posts/queries.ts
1152
+ var DEFAULT_FIRST = 10;
1153
+ var BATCH_FIRST = 100;
1154
+ var POST_FIELDS = `
1155
+ id
1156
+ databaseId
1157
+ slug
1158
+ title
1159
+ excerpt
1160
+ date
1161
+ modified
1162
+ status
1163
+ uri
1164
+ author {
1165
+ node {
1166
+ databaseId
1167
+ name
1168
+ slug
1169
+ avatar { url }
1170
+ }
1171
+ }
1172
+ featuredImage {
1173
+ node {
1174
+ sourceUrl
1175
+ altText
1176
+ mediaDetails { width height }
1177
+ }
1178
+ }
1179
+ categories {
1180
+ nodes { databaseId name slug }
1181
+ }
1182
+ tags {
1183
+ nodes { databaseId name slug }
1184
+ }
1185
+ `;
1186
+ var POST_FIELDS_WITH_CONTENT = `
1187
+ ${POST_FIELDS}
1188
+ content
1189
+ `;
1190
+ var GQL_GET_POSTS = `
1191
+ query GetPosts($first: Int, $after: String, $where: RootQueryToPostConnectionWhereArgs) {
1192
+ posts(first: $first, after: $after, where: $where) {
1193
+ nodes { ${POST_FIELDS} }
1194
+ pageInfo { hasNextPage hasPreviousPage startCursor endCursor }
1195
+ }
1196
+ }
1197
+ `;
1198
+ var GQL_GET_POST_BY_SLUG = `
1199
+ query GetPostBySlug($slug: ID!) {
1200
+ post(id: $slug, idType: SLUG) { ${POST_FIELDS_WITH_CONTENT} }
1201
+ }
1202
+ `;
1203
+ var GQL_GET_POST_BY_DATABASE_ID = `
1204
+ query GetPostByDatabaseId($id: ID!) {
1205
+ post(id: $id, idType: DATABASE_ID) { ${POST_FIELDS_WITH_CONTENT} }
1206
+ }
1207
+ `;
1208
+ var GQL_GET_ALL_POST_SLUGS = `
1209
+ query GetAllPostSlugs($first: Int, $after: String) {
1210
+ posts(first: $first, after: $after) {
1211
+ nodes { slug }
1212
+ pageInfo { hasNextPage endCursor }
1213
+ }
1214
+ }
1215
+ `;
1216
+ var GQL_GET_ALL_POSTS_FOR_SITEMAP = `
1217
+ query GetAllPostsForSitemap($first: Int, $after: String) {
1218
+ posts(first: $first, after: $after) {
1219
+ nodes { slug modified }
1220
+ pageInfo { hasNextPage endCursor }
1221
+ }
1222
+ }
1223
+ `;
1224
+ function createPostsQueries2(fetcher) {
1225
+ const { gqlFetch, gqlFetchGraceful } = fetcher;
1226
+ async function getPosts(first = DEFAULT_FIRST, after, filter) {
1227
+ const where = {};
1228
+ if (filter?.authorName) where["authorName"] = filter.authorName;
1229
+ if (filter?.categoryName) where["categoryName"] = filter.categoryName;
1230
+ if (filter?.tag) where["tag"] = filter.tag;
1231
+ if (filter?.search) where["search"] = filter.search;
1232
+ if (filter?.status) where["status"] = filter.status;
1233
+ const data = await gqlFetchGraceful(
1234
+ GQL_GET_POSTS,
1235
+ { posts: { nodes: [], pageInfo: { hasNextPage: false, hasPreviousPage: false } } },
1236
+ { first, after, where: Object.keys(where).length > 0 ? where : void 0 },
1237
+ ["wpgraphql", "gql-posts"]
1238
+ );
1239
+ return data.posts;
1240
+ }
1241
+ async function getPostBySlug(slug) {
1242
+ const data = await gqlFetchGraceful(
1243
+ GQL_GET_POST_BY_SLUG,
1244
+ { post: null },
1245
+ { slug },
1246
+ ["wpgraphql", "gql-posts", `gql-post-${slug}`]
1247
+ );
1248
+ return data.post;
1249
+ }
1250
+ async function getPostByDatabaseId(id) {
1251
+ const data = await gqlFetchGraceful(
1252
+ GQL_GET_POST_BY_DATABASE_ID,
1253
+ { post: null },
1254
+ { id: String(id) },
1255
+ ["wpgraphql", "gql-posts", `gql-post-id-${id}`]
1256
+ );
1257
+ return data.post;
1258
+ }
1259
+ async function getRecentPosts(first = DEFAULT_FIRST) {
1260
+ const connection = await getPosts(first);
1261
+ return connection.nodes;
1262
+ }
1263
+ async function getAllPostSlugs() {
1264
+ try {
1265
+ const all = [];
1266
+ let after = void 0;
1267
+ let hasNextPage = true;
1268
+ while (hasNextPage) {
1269
+ const data = await gqlFetch(GQL_GET_ALL_POST_SLUGS, { first: BATCH_FIRST, after }, ["wpgraphql"]);
1270
+ all.push(...data.posts.nodes);
1271
+ hasNextPage = data.posts.pageInfo.hasNextPage;
1272
+ after = data.posts.pageInfo.endCursor;
1273
+ }
1274
+ return all;
1275
+ } catch {
1276
+ console.warn("WPGraphQL unavailable, skipping static generation for posts");
1277
+ return [];
1278
+ }
1279
+ }
1280
+ async function getAllPostsForSitemap() {
1281
+ try {
1282
+ const all = [];
1283
+ let after = void 0;
1284
+ let hasNextPage = true;
1285
+ while (hasNextPage) {
1286
+ const data = await gqlFetch(
1287
+ GQL_GET_ALL_POSTS_FOR_SITEMAP,
1288
+ { first: BATCH_FIRST, after },
1289
+ ["wpgraphql"]
1290
+ );
1291
+ all.push(...data.posts.nodes);
1292
+ hasNextPage = data.posts.pageInfo.hasNextPage;
1293
+ after = data.posts.pageInfo.endCursor;
1294
+ }
1295
+ return all;
1296
+ } catch {
1297
+ console.warn("WPGraphQL unavailable, skipping sitemap generation");
1298
+ return [];
1299
+ }
1300
+ }
1301
+ return {
1302
+ getPosts,
1303
+ getPostBySlug,
1304
+ getPostByDatabaseId,
1305
+ getRecentPosts,
1306
+ getAllPostSlugs,
1307
+ getAllPostsForSitemap
1308
+ };
1309
+ }
1310
+
1311
+ // src/hooks/wpgraphql/useWPGraphQL.ts
1312
+ function useWPGraphQL(config, query, variables, tags, swrOptions) {
1313
+ const key = ["wpgraphql", config.clientURL, query, JSON.stringify(variables ?? null)];
1314
+ return useSWR2(
1315
+ key,
1316
+ () => {
1317
+ const fetcher = createWPGraphQLFetcher(config);
1318
+ return fetcher.gqlFetch(query, variables, tags);
1319
+ },
1320
+ swrOptions
1321
+ );
1322
+ }
1323
+ function useGQLPosts(config, first, after, filter, swrOptions) {
1324
+ const key = ["wpgraphql-posts", config.clientURL, first, after, JSON.stringify(filter ?? null)];
1325
+ return useSWR2(
1326
+ key,
1327
+ () => {
1328
+ const fetcher = createWPGraphQLFetcher(config);
1329
+ return createPostsQueries2(fetcher).getPosts(first, after, filter);
1330
+ },
1331
+ swrOptions
1332
+ );
1333
+ }
1334
+ function useGQLPostBySlug(config, slug, swrOptions) {
1335
+ const key = slug ? ["wpgraphql-post-slug", config.clientURL, slug] : null;
1336
+ return useSWR2(
1337
+ key,
1338
+ () => {
1339
+ const fetcher = createWPGraphQLFetcher(config);
1340
+ return createPostsQueries2(fetcher).getPostBySlug(slug);
1341
+ },
1342
+ swrOptions
1343
+ );
1344
+ }
1345
+
1346
+ export { AuthProvider, CartProvider, WooCommerceCustomerProvider, cartReducer, useAuth, useCart, useCustomer, useFeaturedProducts, useGQLPostBySlug, useGQLPosts, usePost, usePostBySlug, usePosts, usePostsPaginated, useProduct, useProductBySlug, useProducts, useProductsPaginated, useWPGraphQL };
1347
+ //# sourceMappingURL=index.js.map
1348
+ //# sourceMappingURL=index.js.map