@01.software/sdk 0.37.0 → 0.39.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.
Files changed (74) hide show
  1. package/README.md +189 -84
  2. package/dist/analytics/react.cjs.map +1 -1
  3. package/dist/analytics/react.js.map +1 -1
  4. package/dist/analytics.cjs.map +1 -1
  5. package/dist/analytics.js.map +1 -1
  6. package/dist/client.cjs +1286 -109
  7. package/dist/client.cjs.map +1 -1
  8. package/dist/client.d.cts +8 -7
  9. package/dist/client.d.ts +8 -7
  10. package/dist/client.js +1286 -109
  11. package/dist/client.js.map +1 -1
  12. package/dist/{collection-client-DyELGUcL.d.ts → collection-client-CaMgs5KE.d.ts} +18 -12
  13. package/dist/{collection-client-zOmnxwdA.d.cts → collection-client-DVfB0Em1.d.cts} +18 -12
  14. package/dist/const-6XHz_jej.d.ts +32 -0
  15. package/dist/const-B5KT72c7.d.cts +32 -0
  16. package/dist/errors.cjs +4 -1
  17. package/dist/errors.cjs.map +1 -1
  18. package/dist/errors.js +4 -1
  19. package/dist/errors.js.map +1 -1
  20. package/dist/{index-DRJs7QIh.d.cts → index-BOLQxveo.d.cts} +3 -3
  21. package/dist/{index-DTqoUZk_.d.ts → index-CSwR2HSg.d.ts} +3 -3
  22. package/dist/index.cjs +2861 -2714
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +9 -9
  25. package/dist/index.d.ts +9 -9
  26. package/dist/index.js +2861 -2714
  27. package/dist/index.js.map +1 -1
  28. package/dist/{payload-types-CREOjFNT.d.cts → payload-types-m3jjhxk9.d.cts} +418 -106
  29. package/dist/{payload-types-CREOjFNT.d.ts → payload-types-m3jjhxk9.d.ts} +418 -106
  30. package/dist/query.cjs +244 -1093
  31. package/dist/query.cjs.map +1 -1
  32. package/dist/query.d.cts +159 -34
  33. package/dist/query.d.ts +159 -34
  34. package/dist/query.js +244 -1093
  35. package/dist/query.js.map +1 -1
  36. package/dist/realtime.cjs +5 -1
  37. package/dist/realtime.cjs.map +1 -1
  38. package/dist/realtime.d.cts +2 -2
  39. package/dist/realtime.d.ts +2 -2
  40. package/dist/realtime.js +5 -1
  41. package/dist/realtime.js.map +1 -1
  42. package/dist/server.cjs +1191 -22
  43. package/dist/server.cjs.map +1 -1
  44. package/dist/server.d.cts +7 -7
  45. package/dist/server.d.ts +7 -7
  46. package/dist/server.js +1191 -22
  47. package/dist/server.js.map +1 -1
  48. package/dist/storefront-cache.cjs +144 -0
  49. package/dist/storefront-cache.cjs.map +1 -0
  50. package/dist/storefront-cache.d.cts +24 -0
  51. package/dist/storefront-cache.d.ts +24 -0
  52. package/dist/storefront-cache.js +121 -0
  53. package/dist/storefront-cache.js.map +1 -0
  54. package/dist/{types-DMvVHdb1.d.ts → types-BQo7UdI9.d.cts} +1608 -1215
  55. package/dist/{types-BWMUr3Zw.d.cts → types-CVf8sCZ-.d.ts} +1608 -1215
  56. package/dist/{types-CxzWHspI.d.ts → types-Cmrd1ezc.d.ts} +1 -15
  57. package/dist/{types-BkZNhuBh.d.cts → types-D0ubzQw0.d.cts} +1 -15
  58. package/dist/ui/canvas/server.cjs +5 -1
  59. package/dist/ui/canvas/server.cjs.map +1 -1
  60. package/dist/ui/canvas/server.js +5 -1
  61. package/dist/ui/canvas/server.js.map +1 -1
  62. package/dist/ui/canvas.cjs +5 -1
  63. package/dist/ui/canvas.cjs.map +1 -1
  64. package/dist/ui/canvas.js +5 -1
  65. package/dist/ui/canvas.js.map +1 -1
  66. package/dist/ui/form.d.cts +1 -1
  67. package/dist/ui/form.d.ts +1 -1
  68. package/dist/ui/video.d.cts +1 -1
  69. package/dist/ui/video.d.ts +1 -1
  70. package/dist/webhook.d.cts +4 -4
  71. package/dist/webhook.d.ts +4 -4
  72. package/package.json +11 -1
  73. package/dist/const-CK_FPaIn.d.cts +0 -32
  74. package/dist/const-Dqz05oaG.d.ts +0 -32
package/dist/query.cjs CHANGED
@@ -30,7 +30,11 @@ __export(query_exports, {
30
30
  customerKeys: () => customerKeys,
31
31
  getQueryClient: () => getQueryClient,
32
32
  getStorefrontQueryClient: () => getStorefrontQueryClient,
33
- productKeys: () => productKeys
33
+ prefetchInfiniteProductListingPage: () => prefetchInfiniteProductListingPage,
34
+ prefetchProductListingPage: () => prefetchProductListingPage,
35
+ productKeys: () => productKeys,
36
+ productListingPageInfiniteQueryOptions: () => productListingPageInfiniteQueryOptions,
37
+ productListingPageQueryOptions: () => productListingPageQueryOptions
34
38
  });
35
39
  module.exports = __toCommonJS(query_exports);
36
40
 
@@ -90,6 +94,49 @@ function getStorefrontQueryClient() {
90
94
  }
91
95
 
92
96
  // src/core/query/query-keys.ts
97
+ function nonEmpty(values) {
98
+ return values?.length ? values : void 0;
99
+ }
100
+ function canonicalProductListingPageParams(params = {}, limit) {
101
+ const filters = params.filters;
102
+ const canonicalFilters = {};
103
+ const ids = nonEmpty(filters?.ids);
104
+ if (ids) canonicalFilters.ids = ids;
105
+ const slugs = nonEmpty(filters?.slugs);
106
+ if (slugs) canonicalFilters.slugs = slugs;
107
+ const handles = nonEmpty(filters?.handles);
108
+ if (handles) canonicalFilters.handles = handles;
109
+ const categoryIds = nonEmpty(filters?.categoryIds);
110
+ if (categoryIds) canonicalFilters.categoryIds = categoryIds;
111
+ const tagIds = nonEmpty(filters?.tagIds);
112
+ if (tagIds) canonicalFilters.tagIds = tagIds;
113
+ if (filters?.price?.min != null || filters?.price?.max != null) {
114
+ canonicalFilters.price = {
115
+ ...filters.price.min != null && { min: filters.price.min },
116
+ ...filters.price.max != null && { max: filters.price.max }
117
+ };
118
+ }
119
+ if (filters?.availableForSale != null) {
120
+ canonicalFilters.availableForSale = filters.availableForSale;
121
+ }
122
+ const search = params.search?.trim();
123
+ return {
124
+ mode: params.mode ?? "catalog",
125
+ ...params.page != null && { page: params.page },
126
+ ...limit != null ? { limit } : params.limit != null ? { limit: params.limit } : {},
127
+ ...search && { search },
128
+ ...params.sort != null && { sort: params.sort },
129
+ ...Object.keys(canonicalFilters).length > 0 && {
130
+ filters: canonicalFilters
131
+ },
132
+ ...params.basePath != null && { basePath: params.basePath },
133
+ ...params.trailingSlash != null && { trailingSlash: params.trailingSlash },
134
+ ...params.emit != null && { emit: params.emit },
135
+ ...params.preferCompleteVariantFromHint != null && {
136
+ preferCompleteVariantFromHint: params.preferCompleteVariantFromHint
137
+ }
138
+ };
139
+ }
93
140
  function collectionKeys(collection) {
94
141
  return {
95
142
  all: [collection],
@@ -98,7 +145,11 @@ function collectionKeys(collection) {
98
145
  details: () => [collection, "detail"],
99
146
  detail: (id, options) => [collection, "detail", id, options],
100
147
  infinites: () => [collection, "infinite"],
101
- infinite: (options) => [collection, "infinite", options]
148
+ infinite: (options, pageSize) => [
149
+ collection,
150
+ "infinite",
151
+ pageSize === void 0 ? options : { ...options, limit: pageSize }
152
+ ]
102
153
  };
103
154
  }
104
155
  var customerKeys = {
@@ -108,8 +159,29 @@ var customerKeys = {
108
159
  var productKeys = {
109
160
  listingGroups: (options) => ["products", "listing-groups", "list", options],
110
161
  listingGroupsCatalog: (options) => ["products", "listing-groups", "catalog", options],
111
- listingGroupsInfinite: (options) => ["products", "listing-groups", "infinite", options],
112
- listingGroupsCatalogInfinite: (options) => ["products", "listing-groups", "catalog", "infinite", options],
162
+ listingGroupsInfinite: (options, pageSize) => [
163
+ "products",
164
+ "listing-groups",
165
+ "infinite",
166
+ pageSize === void 0 ? options : { ...options, limit: pageSize }
167
+ ],
168
+ listingGroupsCatalogInfinite: (options, pageSize) => [
169
+ "products",
170
+ "listing-groups",
171
+ "catalog",
172
+ "infinite",
173
+ pageSize === void 0 ? options : { ...options, limit: pageSize }
174
+ ],
175
+ listingPage: (params) => ["products", "listing-page", canonicalProductListingPageParams(params)],
176
+ listingPageInfinite: (params, pageSize) => [
177
+ "products",
178
+ "listing-page",
179
+ "infinite",
180
+ canonicalProductListingPageParams(
181
+ params,
182
+ pageSize
183
+ )
184
+ ],
113
185
  detail: (params) => ["products", "detail", params],
114
186
  detailAll: () => ["products", "detail"]
115
187
  };
@@ -190,13 +262,14 @@ var CollectionHooks = class {
190
262
  }
191
263
  // ===== useInfiniteQuery =====
192
264
  useInfiniteQuery(params, options) {
193
- const {
194
- collection,
195
- options: queryOptions,
196
- pageSize = DEFAULT_PAGE_SIZE
197
- } = params;
265
+ const { collection, options: queryOptions } = params;
266
+ const explicitPageSize = params.pageSize;
267
+ const pageSize = explicitPageSize ?? DEFAULT_PAGE_SIZE;
198
268
  return (0, import_react_query2.useInfiniteQuery)({
199
- queryKey: collectionKeys(collection).infinite(queryOptions),
269
+ queryKey: collectionKeys(collection).infinite(
270
+ queryOptions,
271
+ explicitPageSize
272
+ ),
200
273
  queryFn: async ({ pageParam }) => {
201
274
  const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
202
275
  return response;
@@ -210,13 +283,14 @@ var CollectionHooks = class {
210
283
  }
211
284
  // ===== useSuspenseInfiniteQuery =====
212
285
  useSuspenseInfiniteQuery(params, options) {
213
- const {
214
- collection,
215
- options: queryOptions,
216
- pageSize = DEFAULT_PAGE_SIZE
217
- } = params;
286
+ const { collection, options: queryOptions } = params;
287
+ const explicitPageSize = params.pageSize;
288
+ const pageSize = explicitPageSize ?? DEFAULT_PAGE_SIZE;
218
289
  return (0, import_react_query2.useSuspenseInfiniteQuery)({
219
- queryKey: collectionKeys(collection).infinite(queryOptions),
290
+ queryKey: collectionKeys(collection).infinite(
291
+ queryOptions,
292
+ explicitPageSize
293
+ ),
220
294
  queryFn: async ({ pageParam }) => {
221
295
  const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
222
296
  return response;
@@ -252,13 +326,14 @@ var CollectionHooks = class {
252
326
  }
253
327
  // ===== prefetchInfiniteQuery =====
254
328
  async prefetchInfiniteQuery(params, options) {
255
- const {
256
- collection,
257
- options: queryOptions,
258
- pageSize = DEFAULT_PAGE_SIZE
259
- } = params;
329
+ const { collection, options: queryOptions } = params;
330
+ const explicitPageSize = params.pageSize;
331
+ const pageSize = explicitPageSize ?? DEFAULT_PAGE_SIZE;
260
332
  return this.queryClient.prefetchInfiniteQuery({
261
- queryKey: collectionKeys(collection).infinite(queryOptions),
333
+ queryKey: collectionKeys(collection).infinite(
334
+ queryOptions,
335
+ explicitPageSize
336
+ ),
262
337
  queryFn: async ({ pageParam }) => {
263
338
  const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
264
339
  return response;
@@ -400,115 +475,13 @@ var SDKError = class extends Error {
400
475
  };
401
476
  }
402
477
  };
403
- var NetworkError = class extends SDKError {
404
- constructor(message, status, details, userMessage, suggestion) {
405
- super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
406
- this.name = "NetworkError";
407
- }
408
- };
409
- var ValidationError = class extends SDKError {
410
- constructor(message, details, userMessage, suggestion, status = 400) {
411
- super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
412
- this.name = "ValidationError";
413
- }
414
- };
415
- var ApiError = class extends SDKError {
416
- constructor(message, status, details, userMessage, suggestion, requestId) {
417
- super(
418
- "API_ERROR",
419
- message,
420
- status,
421
- details,
422
- userMessage,
423
- suggestion,
424
- requestId
425
- );
426
- this.name = "ApiError";
427
- }
428
- };
429
478
  var ConfigError = class extends SDKError {
430
479
  constructor(message, details, userMessage, suggestion) {
431
480
  super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
432
481
  this.name = "ConfigError";
433
482
  }
434
483
  };
435
- var TimeoutError = class extends SDKError {
436
- constructor(message = "Request timed out.", details, userMessage, suggestion) {
437
- super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
438
- this.name = "TimeoutError";
439
- }
440
- };
441
- var UsageLimitError = class extends SDKError {
442
- constructor(message, usage, details, userMessage, suggestion) {
443
- super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
444
- this.name = "UsageLimitError";
445
- this.usage = usage;
446
- }
447
- toJSON() {
448
- return {
449
- ...super.toJSON(),
450
- usage: this.usage
451
- };
452
- }
453
- };
454
- var AuthError = class extends SDKError {
455
- constructor(message, details, userMessage, suggestion, requestId) {
456
- super(
457
- "auth_error",
458
- message,
459
- 401,
460
- details,
461
- userMessage,
462
- suggestion,
463
- requestId
464
- );
465
- this.name = "AuthError";
466
- }
467
- };
468
- var PermissionError = class extends SDKError {
469
- constructor(message, details, userMessage, suggestion, requestId) {
470
- super(
471
- "permission_error",
472
- message,
473
- 403,
474
- details,
475
- userMessage,
476
- suggestion,
477
- requestId
478
- );
479
- this.name = "PermissionError";
480
- }
481
- };
482
- var NotFoundError = class extends SDKError {
483
- constructor(message, details, userMessage, suggestion, requestId) {
484
- super(
485
- "not_found",
486
- message,
487
- 404,
488
- details,
489
- userMessage,
490
- suggestion,
491
- requestId
492
- );
493
- this.name = "NotFoundError";
494
- }
495
- };
496
- var ConflictError = class extends SDKError {
497
- constructor(message, details, userMessage, suggestion, requestId) {
498
- super("conflict", message, 409, details, userMessage, suggestion, requestId);
499
- this.name = "ConflictError";
500
- }
501
- };
502
- var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
503
- var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
504
- var createApiError = (message, status, details, userMessage, suggestion, requestId) => new ApiError(message, status, details, userMessage, suggestion, requestId);
505
484
  var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
506
- var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
507
- var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
508
- var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
509
- var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
510
- var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
511
- var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
512
485
 
513
486
  // src/core/query/customer-hooks.ts
514
487
  function createMutation(mutationFn, callbacks, onSuccessExtra) {
@@ -661,6 +634,50 @@ function fetchProductListingGroupsCatalogQuery(collectionClient, queryOptions) {
661
634
  listingGroupsQueryCatalogUrl(queryOptions)
662
635
  );
663
636
  }
637
+ function productListingPageQueryOptions(commerceClient, params = {}) {
638
+ return {
639
+ queryKey: productKeys.listingPage(params),
640
+ queryFn: () => commerceClient.product.listingPage(params)
641
+ };
642
+ }
643
+ function productListingPageInfiniteQueryOptions(commerceClient, params = {}) {
644
+ const {
645
+ pageSize: explicitPageSize,
646
+ page: _page,
647
+ limit: _limit,
648
+ ...pageParams
649
+ } = params;
650
+ const pageSize = explicitPageSize ?? 20;
651
+ return {
652
+ queryKey: productKeys.listingPageInfinite(pageParams, explicitPageSize),
653
+ queryFn: ({ pageParam }) => commerceClient.product.listingPage({
654
+ ...pageParams,
655
+ page: pageParam,
656
+ limit: pageSize
657
+ }),
658
+ initialPageParam: 1,
659
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0
660
+ };
661
+ }
662
+ function prefetchProductListingPage(queryClient, commerceClient, params = {}, options) {
663
+ return queryClient.prefetchQuery({
664
+ ...productListingPageQueryOptions(
665
+ commerceClient,
666
+ params
667
+ ),
668
+ ...options
669
+ });
670
+ }
671
+ function prefetchInfiniteProductListingPage(queryClient, commerceClient, params = {}, options) {
672
+ return queryClient.prefetchInfiniteQuery({
673
+ ...productListingPageInfiniteQueryOptions(
674
+ commerceClient,
675
+ params
676
+ ),
677
+ pages: options?.pages ?? 1,
678
+ staleTime: options?.staleTime
679
+ });
680
+ }
664
681
  var QueryHooks = class extends CollectionHooks {
665
682
  constructor(queryClient, collectionClient, customerAuth, commerceClient) {
666
683
  super(queryClient, collectionClient);
@@ -681,6 +698,14 @@ var QueryHooks = class extends CollectionHooks {
681
698
  this._customer = new CustomerHooks(queryClient, customerAuth);
682
699
  this._commerce = commerceClient;
683
700
  }
701
+ ensureCommerce() {
702
+ if (!this._commerce) {
703
+ throw createConfigError(
704
+ "Product listing page hooks require Client or ServerClient. Use createQueryHooks(client) or createServerQueryHooks(server) instead of constructing QueryHooks directly."
705
+ );
706
+ }
707
+ return this._commerce;
708
+ }
684
709
  useProductListingGroupsQuery(params, options) {
685
710
  const queryOptions = params.options;
686
711
  const { placeholderData, ...restOptions } = options ?? {};
@@ -728,12 +753,14 @@ var QueryHooks = class extends CollectionHooks {
728
753
  });
729
754
  }
730
755
  useInfiniteProductListingGroupsQuery(params, options) {
731
- const {
732
- options: queryOptions,
733
- pageSize = 20
734
- } = params;
756
+ const { options: queryOptions } = params;
757
+ const explicitPageSize = params.pageSize;
758
+ const pageSize = explicitPageSize ?? 20;
735
759
  return (0, import_react_query4.useInfiniteQuery)({
736
- queryKey: productKeys.listingGroupsInfinite(queryOptions),
760
+ queryKey: productKeys.listingGroupsInfinite(
761
+ queryOptions,
762
+ explicitPageSize
763
+ ),
737
764
  queryFn: async ({ pageParam }) => fetchProductListingGroupsQuery(this.collectionClient, {
738
765
  ...queryOptions,
739
766
  page: pageParam,
@@ -745,12 +772,14 @@ var QueryHooks = class extends CollectionHooks {
745
772
  });
746
773
  }
747
774
  useInfiniteProductListingGroupsCatalogQuery(params, options) {
748
- const {
749
- options: queryOptions,
750
- pageSize = 20
751
- } = params;
775
+ const { options: queryOptions } = params;
776
+ const explicitPageSize = params.pageSize;
777
+ const pageSize = explicitPageSize ?? 20;
752
778
  return (0, import_react_query4.useInfiniteQuery)({
753
- queryKey: productKeys.listingGroupsCatalogInfinite(queryOptions),
779
+ queryKey: productKeys.listingGroupsCatalogInfinite(
780
+ queryOptions,
781
+ explicitPageSize
782
+ ),
754
783
  queryFn: async ({ pageParam }) => fetchProductListingGroupsCatalogQuery(this.collectionClient, {
755
784
  ...queryOptions,
756
785
  page: pageParam,
@@ -762,12 +791,14 @@ var QueryHooks = class extends CollectionHooks {
762
791
  });
763
792
  }
764
793
  useSuspenseInfiniteProductListingGroupsQuery(params, options) {
765
- const {
766
- options: queryOptions,
767
- pageSize = 20
768
- } = params;
794
+ const { options: queryOptions } = params;
795
+ const explicitPageSize = params.pageSize;
796
+ const pageSize = explicitPageSize ?? 20;
769
797
  return (0, import_react_query4.useSuspenseInfiniteQuery)({
770
- queryKey: productKeys.listingGroupsInfinite(queryOptions),
798
+ queryKey: productKeys.listingGroupsInfinite(
799
+ queryOptions,
800
+ explicitPageSize
801
+ ),
771
802
  queryFn: async ({ pageParam }) => fetchProductListingGroupsQuery(this.collectionClient, {
772
803
  ...queryOptions,
773
804
  page: pageParam,
@@ -779,12 +810,14 @@ var QueryHooks = class extends CollectionHooks {
779
810
  });
780
811
  }
781
812
  useSuspenseInfiniteProductListingGroupsCatalogQuery(params, options) {
782
- const {
783
- options: queryOptions,
784
- pageSize = 20
785
- } = params;
813
+ const { options: queryOptions } = params;
814
+ const explicitPageSize = params.pageSize;
815
+ const pageSize = explicitPageSize ?? 20;
786
816
  return (0, import_react_query4.useSuspenseInfiniteQuery)({
787
- queryKey: productKeys.listingGroupsCatalogInfinite(queryOptions),
817
+ queryKey: productKeys.listingGroupsCatalogInfinite(
818
+ queryOptions,
819
+ explicitPageSize
820
+ ),
788
821
  queryFn: async ({ pageParam }) => fetchProductListingGroupsCatalogQuery(this.collectionClient, {
789
822
  ...queryOptions,
790
823
  page: pageParam,
@@ -815,12 +848,14 @@ var QueryHooks = class extends CollectionHooks {
815
848
  });
816
849
  }
817
850
  async prefetchInfiniteProductListingGroupsQuery(params, options) {
818
- const {
819
- options: queryOptions,
820
- pageSize = 20
821
- } = params;
851
+ const { options: queryOptions } = params;
852
+ const explicitPageSize = params.pageSize;
853
+ const pageSize = explicitPageSize ?? 20;
822
854
  return this.queryClient.prefetchInfiniteQuery({
823
- queryKey: productKeys.listingGroupsInfinite(queryOptions),
855
+ queryKey: productKeys.listingGroupsInfinite(
856
+ queryOptions,
857
+ explicitPageSize
858
+ ),
824
859
  queryFn: async ({ pageParam }) => fetchProductListingGroupsQuery(this.collectionClient, {
825
860
  ...queryOptions,
826
861
  page: pageParam,
@@ -833,12 +868,14 @@ var QueryHooks = class extends CollectionHooks {
833
868
  });
834
869
  }
835
870
  async prefetchInfiniteProductListingGroupsCatalogQuery(params, options) {
836
- const {
837
- options: queryOptions,
838
- pageSize = 20
839
- } = params;
871
+ const { options: queryOptions } = params;
872
+ const explicitPageSize = params.pageSize;
873
+ const pageSize = explicitPageSize ?? 20;
840
874
  return this.queryClient.prefetchInfiniteQuery({
841
- queryKey: productKeys.listingGroupsCatalogInfinite(queryOptions),
875
+ queryKey: productKeys.listingGroupsCatalogInfinite(
876
+ queryOptions,
877
+ explicitPageSize
878
+ ),
842
879
  queryFn: async ({ pageParam }) => fetchProductListingGroupsCatalogQuery(this.collectionClient, {
843
880
  ...queryOptions,
844
881
  page: pageParam,
@@ -850,6 +887,45 @@ var QueryHooks = class extends CollectionHooks {
850
887
  staleTime: options?.staleTime
851
888
  });
852
889
  }
890
+ useProductListingPage(params = {}, options) {
891
+ const { placeholderData, ...restOptions } = options ?? {};
892
+ return (0, import_react_query4.useQuery)({
893
+ ...productListingPageQueryOptions(this.ensureCommerce(), params),
894
+ ...restOptions,
895
+ ...placeholderData !== void 0 && {
896
+ placeholderData
897
+ }
898
+ });
899
+ }
900
+ useSuspenseProductListingPage(params = {}, options) {
901
+ const suspenseOptions = options;
902
+ return (0, import_react_query4.useSuspenseQuery)({
903
+ ...productListingPageQueryOptions(this.ensureCommerce(), params),
904
+ ...suspenseOptions
905
+ });
906
+ }
907
+ useInfiniteProductListingPage(params = {}, options) {
908
+ return (0, import_react_query4.useInfiniteQuery)({
909
+ ...productListingPageInfiniteQueryOptions(this.ensureCommerce(), params),
910
+ ...options
911
+ });
912
+ }
913
+ async prefetchProductListingPage(params = {}, options) {
914
+ return prefetchProductListingPage(
915
+ this.queryClient,
916
+ this.ensureCommerce(),
917
+ params,
918
+ options
919
+ );
920
+ }
921
+ async prefetchInfiniteProductListingPage(params = {}, options) {
922
+ return prefetchInfiniteProductListingPage(
923
+ this.queryClient,
924
+ this.ensureCommerce(),
925
+ params,
926
+ options
927
+ );
928
+ }
853
929
  useProductDetail(params, options) {
854
930
  const discriminator = "slug" in params ? params.slug : params.id;
855
931
  const { enabled, ...restOptions } = options ?? {};
@@ -1001,7 +1077,7 @@ var RealtimeConnection = class {
1001
1077
  }
1002
1078
  scheduleReconnect() {
1003
1079
  if (this.reconnectTimer) return;
1004
- const delay2 = Math.min(
1080
+ const delay = Math.min(
1005
1081
  INITIAL_RECONNECT_DELAY * Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),
1006
1082
  MAX_RECONNECT_DELAY
1007
1083
  );
@@ -1010,918 +1086,7 @@ var RealtimeConnection = class {
1010
1086
  this.reconnectTimer = null;
1011
1087
  this.abortController = new AbortController();
1012
1088
  this.startStream(this.abortController.signal);
1013
- }, delay2);
1014
- }
1015
- };
1016
-
1017
- // src/utils/types.ts
1018
- function resolveRelation(ref) {
1019
- if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
1020
- return null;
1021
- return ref;
1022
- }
1023
-
1024
- // src/core/metadata/index.ts
1025
- var OPEN_GRAPH_IMAGE_SIZE = "1200";
1026
- var LEGACY_OPEN_GRAPH_IMAGE_SIZE = "1536";
1027
- function extractSeo(doc) {
1028
- const seo = doc.seo ?? {};
1029
- const og = seo.openGraph ?? {};
1030
- return {
1031
- title: seo.title ?? doc.title ?? null,
1032
- description: seo.description ?? null,
1033
- noIndex: seo.noIndex ?? null,
1034
- canonical: seo.canonical ?? null,
1035
- openGraph: {
1036
- title: og.title ?? null,
1037
- description: og.description ?? null,
1038
- image: og.image ?? null
1039
- }
1040
- };
1041
- }
1042
- function generateMetadata(input, options) {
1043
- const title = input.title ?? void 0;
1044
- const description = input.description ?? void 0;
1045
- const ogTitle = input.openGraph?.title ?? title;
1046
- const ogDescription = input.openGraph?.description ?? description;
1047
- const image = resolveMetaImage(input.openGraph?.image);
1048
- return {
1049
- title,
1050
- description,
1051
- ...input.noIndex && { robots: { index: false, follow: false } },
1052
- ...input.canonical && { alternates: { canonical: input.canonical } },
1053
- openGraph: {
1054
- ...ogTitle && { title: ogTitle },
1055
- ...ogDescription && { description: ogDescription },
1056
- ...options?.siteName && { siteName: options.siteName },
1057
- ...image && { images: [image] }
1058
- },
1059
- twitter: {
1060
- card: image ? "summary_large_image" : "summary",
1061
- ...ogTitle && { title: ogTitle },
1062
- ...ogDescription && { description: ogDescription },
1063
- ...image && { images: [image.url] }
1064
- }
1065
- };
1066
- }
1067
- function resolveMetaImage(ref) {
1068
- const image = resolveRelation(ref);
1069
- if (!image) return null;
1070
- const sized = image.sizes?.[OPEN_GRAPH_IMAGE_SIZE] ?? image.sizes?.[LEGACY_OPEN_GRAPH_IMAGE_SIZE];
1071
- const url = sized?.url || image.url;
1072
- if (!url) return null;
1073
- const width = sized?.url ? sized.width : image.width;
1074
- const height = sized?.url ? sized.height : image.height;
1075
- return {
1076
- url,
1077
- ...width && { width },
1078
- ...height && { height },
1079
- ...image.alt && { alt: image.alt }
1080
- };
1081
- }
1082
-
1083
- // src/core/collection/query-builder.ts
1084
- var CollectionQueryBuilder = class {
1085
- constructor(api, collection) {
1086
- this.api = api;
1087
- this.collection = collection;
1088
- }
1089
- /**
1090
- * Find documents (list query)
1091
- * GET /api/{collection}
1092
- * @returns Payload CMS find response with docs array and pagination
1093
- */
1094
- async find(options) {
1095
- return this.api.requestFind(
1096
- `/api/${String(this.collection)}`,
1097
- options
1098
- );
1099
- }
1100
- /**
1101
- * Find document by ID
1102
- * GET /api/{collection}/{id}
1103
- * @returns Document object directly (no wrapper)
1104
- */
1105
- async findById(id, options) {
1106
- return this.api.requestFindById(
1107
- `/api/${String(this.collection)}/${String(id)}`,
1108
- options
1109
- );
1110
- }
1111
- /**
1112
- * Create a new document
1113
- * POST /api/{collection}
1114
- * @returns Payload CMS mutation response with doc and message
1115
- */
1116
- async create(data, options) {
1117
- const endpoint = `/api/${String(this.collection)}`;
1118
- if (options?.file) {
1119
- return this.api.requestCreateWithFile(
1120
- endpoint,
1121
- data,
1122
- options.file,
1123
- options.filename
1124
- );
1125
- }
1126
- return this.api.requestCreate(endpoint, data);
1127
- }
1128
- /**
1129
- * Update a document by ID
1130
- * PATCH /api/{collection}/{id}
1131
- * @returns Payload CMS mutation response with doc and message
1132
- */
1133
- async update(id, data, options) {
1134
- const endpoint = `/api/${String(this.collection)}/${String(id)}`;
1135
- if (options?.file) {
1136
- return this.api.requestUpdateWithFile(
1137
- endpoint,
1138
- data,
1139
- options.file,
1140
- options.filename
1141
- );
1142
- }
1143
- return this.api.requestUpdate(endpoint, data);
1144
- }
1145
- /**
1146
- * Count documents
1147
- * GET /api/{collection}/count
1148
- * @returns Count response with totalDocs
1149
- */
1150
- async count(options) {
1151
- return this.api.requestCount(
1152
- `/api/${String(this.collection)}/count`,
1153
- options
1154
- );
1155
- }
1156
- /**
1157
- * Find first matching document and return its Next.js Metadata.
1158
- * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
1159
- * @returns Metadata or null if no document matches
1160
- */
1161
- async findMetadata(options, metadataOptions) {
1162
- const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
1163
- const doc = docs[0];
1164
- if (!doc) return null;
1165
- return generateMetadata(
1166
- extractSeo(doc),
1167
- metadataOptions
1168
- );
1169
- }
1170
- /**
1171
- * Find document by ID and return its Next.js Metadata.
1172
- * Applies depth: 1 (SEO image populate) automatically.
1173
- * @returns Metadata (throws on 404)
1174
- */
1175
- async findMetadataById(id, metadataOptions) {
1176
- const doc = await this.findById(id, { depth: 1 });
1177
- return generateMetadata(
1178
- extractSeo(doc),
1179
- metadataOptions
1180
- );
1181
- }
1182
- /**
1183
- * Update multiple documents (bulk update)
1184
- * PATCH /api/{collection}
1185
- * @returns Payload CMS find response with updated docs
1186
- */
1187
- async updateMany(where, data) {
1188
- return this.api.requestUpdateMany(
1189
- `/api/${String(this.collection)}`,
1190
- { where, data }
1191
- );
1192
- }
1193
- /**
1194
- * Delete a document by ID
1195
- * DELETE /api/{collection}/{id}
1196
- * @returns Deleted document object directly (no wrapper)
1197
- */
1198
- async remove(id) {
1199
- return this.api.requestDelete(
1200
- `/api/${String(this.collection)}/${String(id)}`
1201
- );
1202
- }
1203
- /**
1204
- * Delete multiple documents (bulk delete)
1205
- * DELETE /api/{collection}
1206
- * @returns Payload CMS find response with deleted docs
1207
- */
1208
- async removeMany(where) {
1209
- return this.api.requestDeleteMany(
1210
- `/api/${String(this.collection)}`,
1211
- { where }
1212
- );
1213
- }
1214
- };
1215
-
1216
- // src/core/collection/http-client.ts
1217
- var import_qs_esm = require("qs-esm");
1218
-
1219
- // src/core/internal/utils/credentials.ts
1220
- function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
1221
- if (secretKey && !publishableKey) {
1222
- throw createConfigError(
1223
- `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
1224
- );
1225
- }
1226
- return publishableKey ?? "";
1227
- }
1228
-
1229
- // src/core/client/types.ts
1230
- function resolveApiUrl(apiUrl) {
1231
- if (apiUrl) {
1232
- return apiUrl.replace(/\/$/, "");
1233
- }
1234
- if (typeof process !== "undefined" && process.env) {
1235
- const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
1236
- if (envUrl) {
1237
- return envUrl.replace(/\/$/, "");
1238
- }
1239
- }
1240
- return "https://api.01.software";
1241
- }
1242
-
1243
- // src/core/internal/utils/http.ts
1244
- var DEFAULT_TIMEOUT = 3e4;
1245
- var STOREFRONT_BROWSER_TIMEOUT = 15e3;
1246
- var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
1247
- var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
1248
- var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
1249
- var DEFAULT_MAX_RETRIES = 3;
1250
- var STOREFRONT_BROWSER_MAX_RETRIES = 1;
1251
- function debugLog(debug, type, message, data) {
1252
- if (!debug) return;
1253
- const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
1254
- if (shouldLog) {
1255
- console.group(`[SDK ${type.toUpperCase()}] ${message}`);
1256
- if (data) console.log(data);
1257
- console.groupEnd();
1258
- }
1259
- }
1260
- function redactSensitiveHeader(value) {
1261
- const prefix = value.toLowerCase().startsWith("bearer ") ? "Bearer " : "";
1262
- return value.length > 20 ? `${prefix}...****${value.slice(-8)}` : "****";
1263
- }
1264
- function redactSensitiveHeaders(headers) {
1265
- const redacted = Object.fromEntries(headers.entries());
1266
- if (redacted.authorization) {
1267
- redacted.authorization = redactSensitiveHeader(redacted.authorization);
1268
- }
1269
- if (redacted["x-preview-token"]) {
1270
- redacted["x-preview-token"] = redactSensitiveHeader(
1271
- redacted["x-preview-token"]
1272
- );
1273
- }
1274
- return redacted;
1275
- }
1276
- function getErrorSuggestion(status) {
1277
- if (status === 400)
1278
- return "The request data failed validation. Check field values and types.";
1279
- if (status === 401) return "Please check your authentication credentials.";
1280
- if (status === 403)
1281
- return "Access denied. Check your credentials or permissions.";
1282
- if (status === 404) return "The requested resource was not found.";
1283
- if (status === 422) return "The request data failed validation.";
1284
- if (status >= 500) return "A server error occurred. Please try again later.";
1285
- return void 0;
1286
- }
1287
- function isUsageLimitExceededResponse(response) {
1288
- if (response.status !== 429) return false;
1289
- const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
1290
- const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
1291
- if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
1292
- return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
1293
- }
1294
- async function parseErrorBody(response) {
1295
- const fallback = {
1296
- errorMessage: `HTTP ${response.status}: ${response.statusText}`,
1297
- userMessage: `Request failed (status: ${response.status})`
1298
- };
1299
- try {
1300
- const body = await response.json();
1301
- const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
1302
- if (body.errors && Array.isArray(body.errors)) {
1303
- const fieldErrors = [];
1304
- for (const e of body.errors) {
1305
- if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
1306
- for (const fe of e.data.errors) {
1307
- fieldErrors.push({
1308
- field: fe.path || fe.field,
1309
- message: fe.message
1310
- });
1311
- }
1312
- } else if (e.field || e.message) {
1313
- fieldErrors.push({ field: e.field, message: e.message });
1314
- }
1315
- }
1316
- const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
1317
- (e) => e.field ? `${e.field}: ${e.message}` : e.message
1318
- ).filter(Boolean).join("; ");
1319
- if (details) {
1320
- return {
1321
- errorMessage: `HTTP ${response.status}: ${details}`,
1322
- userMessage: details,
1323
- reason,
1324
- body,
1325
- errors: fieldErrors.length > 0 ? fieldErrors : body.errors
1326
- };
1327
- }
1328
- }
1329
- if (typeof body.error === "string") {
1330
- return {
1331
- errorMessage: `HTTP ${response.status}: ${body.error}`,
1332
- userMessage: body.error,
1333
- reason,
1334
- body
1335
- };
1336
- }
1337
- if (body.message) {
1338
- return {
1339
- errorMessage: `HTTP ${response.status}: ${body.message}`,
1340
- userMessage: body.message,
1341
- reason,
1342
- body
1343
- };
1344
- }
1345
- return { ...fallback, reason, body };
1346
- } catch {
1347
- return fallback;
1348
- }
1349
- }
1350
- function getParsedErrorSuggestion(status, parsed) {
1351
- if (status === 403 && parsed.reason === "origin_not_allowed") {
1352
- return "Add the request origin to the tenant Browser API origins, then retry the browser request.";
1353
- }
1354
- return getErrorSuggestion(status);
1355
- }
1356
- async function delay(ms) {
1357
- return new Promise((resolve) => setTimeout(resolve, ms));
1358
- }
1359
- function attachRequestId(err, id) {
1360
- if (id) err.requestId = id;
1361
- return err;
1362
- }
1363
- function createHttpStatusError(status, parsed, details, requestId) {
1364
- const errorDetails = {
1365
- ...details,
1366
- ...parsed.errors && { errors: parsed.errors },
1367
- ...parsed.body && { body: parsed.body }
1368
- };
1369
- const suggestion = getParsedErrorSuggestion(status, parsed);
1370
- if (status === 400 || status === 422) {
1371
- return attachRequestId(
1372
- createValidationError(
1373
- parsed.errorMessage,
1374
- errorDetails,
1375
- parsed.userMessage,
1376
- suggestion,
1377
- status
1378
- ),
1379
- requestId
1380
- );
1381
- }
1382
- if (status === 401) {
1383
- return attachRequestId(
1384
- createAuthError(
1385
- parsed.errorMessage,
1386
- errorDetails,
1387
- parsed.userMessage,
1388
- suggestion
1389
- ),
1390
- requestId
1391
- );
1392
- }
1393
- if (status === 403) {
1394
- return attachRequestId(
1395
- createPermissionError(
1396
- parsed.errorMessage,
1397
- errorDetails,
1398
- parsed.userMessage,
1399
- suggestion
1400
- ),
1401
- requestId
1402
- );
1403
- }
1404
- if (status === 404) {
1405
- return attachRequestId(
1406
- createNotFoundError(
1407
- parsed.errorMessage,
1408
- errorDetails,
1409
- parsed.userMessage,
1410
- suggestion
1411
- ),
1412
- requestId
1413
- );
1414
- }
1415
- if (status === 409) {
1416
- return attachRequestId(
1417
- createConflictError(
1418
- parsed.errorMessage,
1419
- errorDetails,
1420
- parsed.userMessage,
1421
- suggestion
1422
- ),
1423
- requestId
1424
- );
1425
- }
1426
- return attachRequestId(
1427
- createNetworkError(
1428
- parsed.errorMessage,
1429
- status,
1430
- errorDetails,
1431
- parsed.userMessage,
1432
- suggestion
1433
- ),
1434
- requestId
1435
- );
1436
- }
1437
- async function httpFetch(url, options) {
1438
- const {
1439
- apiUrl,
1440
- publishableKey,
1441
- secretKey,
1442
- customerToken,
1443
- timeout: timeoutOption = DEFAULT_TIMEOUT,
1444
- debug,
1445
- retry,
1446
- onUnauthorized,
1447
- ...requestInit
1448
- } = options || {};
1449
- const baseUrl = resolveApiUrl(apiUrl);
1450
- const method = (requestInit.method || "GET").toUpperCase();
1451
- const isPublishableKeyBrowserGet = typeof window !== "undefined" && !secretKey && !customerToken && Boolean(publishableKey) && SAFE_METHODS.includes(method);
1452
- const timeout = timeoutOption === DEFAULT_TIMEOUT && isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_TIMEOUT : timeoutOption;
1453
- const retryConfig = {
1454
- maxRetries: retry?.maxRetries ?? (isPublishableKeyBrowserGet ? STOREFRONT_BROWSER_MAX_RETRIES : DEFAULT_MAX_RETRIES),
1455
- retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
1456
- retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
1457
- };
1458
- let authToken;
1459
- if (secretKey) {
1460
- authToken = secretKey;
1461
- } else if (customerToken) {
1462
- authToken = customerToken;
1463
- }
1464
- let lastError;
1465
- let hasRetried401 = false;
1466
- for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
1467
- try {
1468
- const headers = new Headers(requestInit.headers);
1469
- if (publishableKey) {
1470
- headers.set("X-Publishable-Key", publishableKey);
1471
- }
1472
- if (authToken) {
1473
- headers.set("Authorization", `Bearer ${authToken}`);
1474
- }
1475
- if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
1476
- headers.set("Content-Type", "application/json");
1477
- }
1478
- const redactedHeaders = redactSensitiveHeaders(headers);
1479
- debugLog(debug, "request", url, {
1480
- method: requestInit.method || "GET",
1481
- headers: redactedHeaders,
1482
- attempt: attempt + 1
1483
- });
1484
- const controller = new AbortController();
1485
- const timeoutId = setTimeout(() => controller.abort(), timeout);
1486
- const response = await fetch(`${baseUrl}${url}`, {
1487
- ...requestInit,
1488
- headers,
1489
- signal: controller.signal
1490
- });
1491
- clearTimeout(timeoutId);
1492
- const requestId = response.headers.get("x-request-id") ?? void 0;
1493
- debugLog(debug, "response", url, {
1494
- status: response.status,
1495
- statusText: response.statusText,
1496
- headers: redactSensitiveHeaders(response.headers)
1497
- });
1498
- if (!response.ok) {
1499
- if (isUsageLimitExceededResponse(response)) {
1500
- const limit = parseInt(
1501
- response.headers.get("X-Usage-Limit") || "0",
1502
- 10
1503
- );
1504
- const current = parseInt(
1505
- response.headers.get("X-Usage-Current") || "0",
1506
- 10
1507
- );
1508
- const remaining = parseInt(
1509
- response.headers.get("X-Usage-Remaining") || "0",
1510
- 10
1511
- );
1512
- throw attachRequestId(
1513
- createUsageLimitError(
1514
- `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
1515
- { limit, current, remaining },
1516
- {
1517
- url,
1518
- method: requestInit.method || "GET",
1519
- attempt: attempt + 1
1520
- },
1521
- "Monthly API call limit exceeded. Please upgrade your plan.",
1522
- "Upgrade your tenant plan to increase the monthly API call limit."
1523
- ),
1524
- requestId
1525
- );
1526
- }
1527
- const parsed = await parseErrorBody(response);
1528
- if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
1529
- hasRetried401 = true;
1530
- try {
1531
- const newToken = await onUnauthorized();
1532
- if (newToken) {
1533
- authToken = newToken;
1534
- continue;
1535
- }
1536
- } catch {
1537
- }
1538
- }
1539
- const details = {
1540
- url,
1541
- method: requestInit.method || "GET",
1542
- attempt: attempt + 1
1543
- };
1544
- if (NON_RETRYABLE_STATUSES.includes(response.status)) {
1545
- throw createHttpStatusError(
1546
- response.status,
1547
- parsed,
1548
- details,
1549
- requestId
1550
- );
1551
- }
1552
- const error = attachRequestId(
1553
- createNetworkError(
1554
- parsed.errorMessage,
1555
- response.status,
1556
- details,
1557
- parsed.userMessage,
1558
- getErrorSuggestion(response.status)
1559
- ),
1560
- requestId
1561
- );
1562
- const method2 = (requestInit.method || "GET").toUpperCase();
1563
- if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method2) && retryConfig.retryableStatuses.includes(response.status)) {
1564
- lastError = error;
1565
- const retryDelay = retryConfig.retryDelay(attempt);
1566
- debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
1567
- await delay(retryDelay);
1568
- continue;
1569
- }
1570
- throw error;
1571
- }
1572
- return response;
1573
- } catch (error) {
1574
- debugLog(debug, "error", url, error);
1575
- const method2 = (requestInit.method || "GET").toUpperCase();
1576
- const isSafe = SAFE_METHODS.includes(method2);
1577
- if (error instanceof Error && error.name === "AbortError") {
1578
- const timeoutError = createTimeoutError(
1579
- `Request timed out after ${timeout}ms.`,
1580
- { url, timeout, attempt: attempt + 1 },
1581
- "The request timed out.",
1582
- "Please check your network connection or try again later."
1583
- );
1584
- if (isSafe && attempt < retryConfig.maxRetries) {
1585
- lastError = timeoutError;
1586
- await delay(retryConfig.retryDelay(attempt));
1587
- continue;
1588
- }
1589
- throw timeoutError;
1590
- }
1591
- if (error instanceof TypeError) {
1592
- const networkError = createNetworkError(
1593
- "Network connection failed.",
1594
- void 0,
1595
- { url, originalError: error.message, attempt: attempt + 1 },
1596
- "Network connection failed.",
1597
- "Please check your internet connection and try again."
1598
- );
1599
- if (isSafe && attempt < retryConfig.maxRetries) {
1600
- lastError = networkError;
1601
- await delay(retryConfig.retryDelay(attempt));
1602
- continue;
1603
- }
1604
- throw networkError;
1605
- }
1606
- if (error instanceof NetworkError || error instanceof TimeoutError) {
1607
- if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
1608
- lastError = error;
1609
- await delay(retryConfig.retryDelay(attempt));
1610
- continue;
1611
- }
1612
- throw error;
1613
- }
1614
- if (error instanceof SDKError) {
1615
- throw error;
1616
- }
1617
- const unknownError = createNetworkError(
1618
- error instanceof Error ? error.message : "An unknown network error occurred.",
1619
- void 0,
1620
- { url, originalError: error, attempt: attempt + 1 },
1621
- "An unknown error occurred.",
1622
- "Please try again later."
1623
- );
1624
- if (isSafe && attempt < retryConfig.maxRetries) {
1625
- lastError = unknownError;
1626
- await delay(retryConfig.retryDelay(attempt));
1627
- continue;
1628
- }
1629
- throw unknownError;
1630
- }
1631
- }
1632
- throw lastError ?? new NetworkError("Request failed after retries");
1633
- }
1634
-
1635
- // src/core/collection/http-client.ts
1636
- var HttpClient = class {
1637
- constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1638
- this.publishableKey = requirePublishableKeyForSecret(
1639
- "CollectionClient",
1640
- publishableKey,
1641
- secretKey
1642
- );
1643
- this.secretKey = secretKey;
1644
- this.getCustomerToken = getCustomerToken;
1645
- this.onUnauthorized = onUnauthorized;
1646
- this.onRequestId = onRequestId;
1647
- this.apiUrl = apiUrl;
1648
- }
1649
- get defaultOptions() {
1650
- const opts = {
1651
- apiUrl: this.apiUrl,
1652
- publishableKey: this.publishableKey,
1653
- secretKey: this.secretKey
1654
- };
1655
- const token = this.getCustomerToken?.();
1656
- if (token) {
1657
- opts.customerToken = token;
1658
- if (this.onUnauthorized) {
1659
- opts.onUnauthorized = this.onUnauthorized;
1660
- }
1661
- }
1662
- return opts;
1663
- }
1664
- async fetchWithTracking(url, opts) {
1665
- try {
1666
- const response = await httpFetch(url, opts);
1667
- this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1668
- return response;
1669
- } catch (err) {
1670
- const id = err instanceof SDKError ? err.requestId ?? null : null;
1671
- this.onRequestId?.(id);
1672
- throw err;
1673
- }
1674
- }
1675
- buildUrl(endpoint, options) {
1676
- if (!options) return endpoint;
1677
- const queryString = (0, import_qs_esm.stringify)(options, { addQueryPrefix: true });
1678
- return queryString ? `${endpoint}${queryString}` : endpoint;
1679
- }
1680
- assertJsonResponse(response) {
1681
- const contentType = response.headers.get("content-type");
1682
- if (!contentType?.includes("application/json")) {
1683
- throw createApiError("Response is not in JSON format.", response.status, {
1684
- contentType
1685
- });
1686
- }
1687
- }
1688
- /**
1689
- * Parse Payload CMS find response (list query)
1690
- * Returns native Payload response structure
1691
- */
1692
- async parseFindResponse(response) {
1693
- const contentType = response.headers.get("content-type");
1694
- try {
1695
- this.assertJsonResponse(response);
1696
- const jsonData = await response.json();
1697
- if (jsonData.docs === void 0) {
1698
- throw createApiError("Invalid find response.", response.status, {
1699
- jsonData
1700
- });
1701
- }
1702
- return {
1703
- docs: jsonData.docs,
1704
- totalDocs: jsonData.totalDocs ?? 0,
1705
- limit: jsonData.limit || 20,
1706
- totalPages: jsonData.totalPages ?? 0,
1707
- page: jsonData.page || 1,
1708
- pagingCounter: jsonData.pagingCounter || 1,
1709
- hasPrevPage: jsonData.hasPrevPage ?? false,
1710
- hasNextPage: jsonData.hasNextPage ?? false,
1711
- prevPage: jsonData.prevPage ?? null,
1712
- nextPage: jsonData.nextPage ?? null
1713
- };
1714
- } catch (error) {
1715
- if (error instanceof SDKError) throw error;
1716
- throw createApiError("Failed to parse response.", response.status, {
1717
- contentType,
1718
- error: error instanceof Error ? error.message : error
1719
- });
1720
- }
1721
- }
1722
- /**
1723
- * Parse Payload CMS mutation response (create/update)
1724
- * Returns native Payload response structure
1725
- */
1726
- async parseMutationResponse(response) {
1727
- const contentType = response.headers.get("content-type");
1728
- try {
1729
- this.assertJsonResponse(response);
1730
- const jsonData = await response.json();
1731
- if (jsonData.doc === void 0) {
1732
- throw createApiError("Invalid mutation response.", response.status, {
1733
- jsonData
1734
- });
1735
- }
1736
- return {
1737
- message: jsonData.message || "",
1738
- doc: jsonData.doc,
1739
- errors: jsonData.errors
1740
- };
1741
- } catch (error) {
1742
- if (error instanceof SDKError) throw error;
1743
- throw createApiError("Failed to parse response.", response.status, {
1744
- contentType,
1745
- error: error instanceof Error ? error.message : error
1746
- });
1747
- }
1748
- }
1749
- /**
1750
- * Parse Payload CMS document response (findById/delete)
1751
- * Returns document directly without wrapper
1752
- */
1753
- async parseDocumentResponse(response) {
1754
- const contentType = response.headers.get("content-type");
1755
- try {
1756
- this.assertJsonResponse(response);
1757
- const jsonData = await response.json();
1758
- return jsonData;
1759
- } catch (error) {
1760
- if (error instanceof SDKError) throw error;
1761
- throw createApiError("Failed to parse response.", response.status, {
1762
- contentType,
1763
- error: error instanceof Error ? error.message : error
1764
- });
1765
- }
1766
- }
1767
- };
1768
-
1769
- // src/core/collection/collection-client.ts
1770
- function buildPayloadFormData(data, file, filename) {
1771
- const formData = new FormData();
1772
- formData.append("file", file, filename);
1773
- if (data != null) {
1774
- formData.append("_payload", JSON.stringify(data));
1775
- }
1776
- return formData;
1777
- }
1778
- var CollectionClient = class extends HttpClient {
1779
- from(collection) {
1780
- return new CollectionQueryBuilder(this, collection);
1781
- }
1782
- // ============================================================================
1783
- // Payload-native methods
1784
- // ============================================================================
1785
- /**
1786
- * Find documents (list query)
1787
- * GET /api/{collection}
1788
- */
1789
- async requestFind(endpoint, options) {
1790
- const url = this.buildUrl(endpoint, options);
1791
- const response = await this.fetchWithTracking(url, {
1792
- ...this.defaultOptions,
1793
- method: "GET"
1794
- });
1795
- return this.parseFindResponse(response);
1796
- }
1797
- /**
1798
- * Find-like response from a custom endpoint
1799
- * POST /api/...custom-endpoint
1800
- */
1801
- async requestFindEndpoint(endpoint, data) {
1802
- const response = await this.fetchWithTracking(endpoint, {
1803
- ...this.defaultOptions,
1804
- method: "POST",
1805
- body: data ? JSON.stringify(data) : void 0
1806
- });
1807
- return this.parseFindResponse(response);
1808
- }
1809
- /**
1810
- * Find-like response from a cacheable GET custom endpoint.
1811
- */
1812
- async requestFindEndpointGet(endpoint) {
1813
- const response = await this.fetchWithTracking(endpoint, {
1814
- ...this.defaultOptions,
1815
- method: "GET"
1816
- });
1817
- return this.parseFindResponse(response);
1818
- }
1819
- /**
1820
- * Find document by ID
1821
- * GET /api/{collection}/{id}
1822
- */
1823
- async requestFindById(endpoint, options) {
1824
- const url = this.buildUrl(endpoint, options);
1825
- const response = await this.fetchWithTracking(url, {
1826
- ...this.defaultOptions,
1827
- method: "GET"
1828
- });
1829
- return this.parseDocumentResponse(response);
1830
- }
1831
- /**
1832
- * Create document
1833
- * POST /api/{collection}
1834
- */
1835
- async requestCreate(endpoint, data) {
1836
- const response = await this.fetchWithTracking(endpoint, {
1837
- ...this.defaultOptions,
1838
- method: "POST",
1839
- body: data ? JSON.stringify(data) : void 0
1840
- });
1841
- return this.parseMutationResponse(response);
1842
- }
1843
- /**
1844
- * Update document
1845
- * PATCH /api/{collection}/{id}
1846
- */
1847
- async requestUpdate(endpoint, data) {
1848
- const response = await this.fetchWithTracking(endpoint, {
1849
- ...this.defaultOptions,
1850
- method: "PATCH",
1851
- body: data ? JSON.stringify(data) : void 0
1852
- });
1853
- return this.parseMutationResponse(response);
1854
- }
1855
- /**
1856
- * Count documents
1857
- * GET /api/{collection}/count
1858
- */
1859
- async requestCount(endpoint, options) {
1860
- const url = this.buildUrl(endpoint, options);
1861
- const response = await this.fetchWithTracking(url, {
1862
- ...this.defaultOptions,
1863
- method: "GET"
1864
- });
1865
- return this.parseDocumentResponse(response);
1866
- }
1867
- /**
1868
- * Update multiple documents (bulk update)
1869
- * PATCH /api/{collection}
1870
- */
1871
- async requestUpdateMany(endpoint, data) {
1872
- const response = await this.fetchWithTracking(endpoint, {
1873
- ...this.defaultOptions,
1874
- method: "PATCH",
1875
- body: JSON.stringify(data)
1876
- });
1877
- return this.parseFindResponse(response);
1878
- }
1879
- /**
1880
- * Delete document
1881
- * DELETE /api/{collection}/{id}
1882
- */
1883
- async requestDelete(endpoint) {
1884
- const response = await this.fetchWithTracking(endpoint, {
1885
- ...this.defaultOptions,
1886
- method: "DELETE"
1887
- });
1888
- return this.parseDocumentResponse(response);
1889
- }
1890
- /**
1891
- * Delete multiple documents (bulk delete)
1892
- * DELETE /api/{collection}
1893
- */
1894
- async requestDeleteMany(endpoint, data) {
1895
- const response = await this.fetchWithTracking(endpoint, {
1896
- ...this.defaultOptions,
1897
- method: "DELETE",
1898
- body: JSON.stringify(data)
1899
- });
1900
- return this.parseFindResponse(response);
1901
- }
1902
- /**
1903
- * Create document with file upload
1904
- * POST /api/{collection} (multipart/form-data)
1905
- */
1906
- async requestCreateWithFile(endpoint, data, file, filename) {
1907
- const response = await this.fetchWithTracking(endpoint, {
1908
- ...this.defaultOptions,
1909
- method: "POST",
1910
- body: buildPayloadFormData(data, file, filename)
1911
- });
1912
- return this.parseMutationResponse(response);
1913
- }
1914
- /**
1915
- * Update document with file upload
1916
- * PATCH /api/{collection}/{id} (multipart/form-data)
1917
- */
1918
- async requestUpdateWithFile(endpoint, data, file, filename) {
1919
- const response = await this.fetchWithTracking(endpoint, {
1920
- ...this.defaultOptions,
1921
- method: "PATCH",
1922
- body: buildPayloadFormData(data, file, filename)
1923
- });
1924
- return this.parseMutationResponse(response);
1089
+ }, delay);
1925
1090
  }
1926
1091
  };
1927
1092
 
@@ -1952,40 +1117,26 @@ function createReadOnlyQueryHooksFacade(hooks) {
1952
1117
  invalidateCustomerQueries: hooks.invalidateCustomerQueries.bind(hooks),
1953
1118
  getCustomerData: hooks.getCustomerData.bind(hooks),
1954
1119
  setCustomerData: hooks.setCustomerData.bind(hooks),
1955
- useProductListingGroupsQuery: hooks.useProductListingGroupsQuery.bind(hooks),
1956
- useSuspenseProductListingGroupsQuery: hooks.useSuspenseProductListingGroupsQuery.bind(hooks),
1957
- useInfiniteProductListingGroupsQuery: hooks.useInfiniteProductListingGroupsQuery.bind(hooks),
1958
- useSuspenseInfiniteProductListingGroupsQuery: hooks.useSuspenseInfiniteProductListingGroupsQuery.bind(hooks),
1959
- prefetchProductListingGroupsQuery: hooks.prefetchProductListingGroupsQuery.bind(hooks),
1960
- prefetchInfiniteProductListingGroupsQuery: hooks.prefetchInfiniteProductListingGroupsQuery.bind(hooks),
1120
+ useProductListingGroupsCatalogQuery: hooks.useProductListingGroupsCatalogQuery.bind(hooks),
1121
+ useSuspenseProductListingGroupsCatalogQuery: hooks.useSuspenseProductListingGroupsCatalogQuery.bind(hooks),
1122
+ useInfiniteProductListingGroupsCatalogQuery: hooks.useInfiniteProductListingGroupsCatalogQuery.bind(hooks),
1123
+ useSuspenseInfiniteProductListingGroupsCatalogQuery: hooks.useSuspenseInfiniteProductListingGroupsCatalogQuery.bind(hooks),
1124
+ prefetchProductListingGroupsCatalogQuery: hooks.prefetchProductListingGroupsCatalogQuery.bind(hooks),
1125
+ prefetchInfiniteProductListingGroupsCatalogQuery: hooks.prefetchInfiniteProductListingGroupsCatalogQuery.bind(hooks),
1126
+ useProductListingPage: hooks.useProductListingPage.bind(hooks),
1127
+ useSuspenseProductListingPage: hooks.useSuspenseProductListingPage.bind(hooks),
1128
+ useInfiniteProductListingPage: hooks.useInfiniteProductListingPage.bind(hooks),
1129
+ prefetchProductListingPage: hooks.prefetchProductListingPage.bind(hooks),
1130
+ prefetchInfiniteProductListingPage: hooks.prefetchInfiniteProductListingPage.bind(hooks),
1961
1131
  useProductDetail: hooks.useProductDetail.bind(hooks),
1962
1132
  useProductDetailBySlug: hooks.useProductDetailBySlug.bind(hooks),
1963
1133
  useProductDetailById: hooks.useProductDetailById.bind(hooks)
1964
1134
  };
1965
1135
  }
1966
1136
  function createQueryHooks(client, queryClient = getQueryClient()) {
1967
- const config = client.getConfig();
1968
- const onUnauthorized = async () => {
1969
- try {
1970
- const result = await client.customer.auth.refreshToken();
1971
- return result.token ?? null;
1972
- } catch {
1973
- return null;
1974
- }
1975
- };
1976
- const collectionClient = new CollectionClient(
1977
- config.publishableKey,
1978
- void 0,
1979
- () => client.customer.auth.getToken(),
1980
- onUnauthorized,
1981
- (id) => {
1982
- client.lastRequestId = id;
1983
- },
1984
- config.apiUrl
1985
- );
1986
1137
  const hooks = new QueryHooks(
1987
1138
  queryClient,
1988
- collectionClient,
1139
+ client.collections,
1989
1140
  client.customer.auth,
1990
1141
  client.commerce
1991
1142
  );