@01.software/sdk 0.29.0 → 0.30.1

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 (78) hide show
  1. package/README.md +273 -73
  2. package/dist/analytics/react.cjs +4 -1
  3. package/dist/analytics/react.cjs.map +1 -1
  4. package/dist/analytics/react.js +4 -1
  5. package/dist/analytics/react.js.map +1 -1
  6. package/dist/analytics.cjs +4 -1
  7. package/dist/analytics.cjs.map +1 -1
  8. package/dist/analytics.js +4 -1
  9. package/dist/analytics.js.map +1 -1
  10. package/dist/client.cjs +1476 -0
  11. package/dist/client.cjs.map +1 -0
  12. package/dist/client.d.cts +28 -0
  13. package/dist/client.d.ts +28 -0
  14. package/dist/client.js +1453 -0
  15. package/dist/client.js.map +1 -0
  16. package/dist/collection-client-B9d9kr1d.d.ts +218 -0
  17. package/dist/collection-client-QPbwimkU.d.cts +218 -0
  18. package/dist/{const-DAjQYNuM.d.ts → const-B75IFDRi.d.ts} +2 -4
  19. package/dist/{const-Dsixdi6z.d.cts → const-VZuk2tWc.d.cts} +2 -4
  20. package/dist/index-B2WbhEgT.d.cts +106 -0
  21. package/dist/index-B2WbhEgT.d.ts +106 -0
  22. package/dist/index.cjs +784 -1530
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +11 -115
  25. package/dist/index.d.ts +11 -115
  26. package/dist/index.js +784 -1548
  27. package/dist/index.js.map +1 -1
  28. package/dist/metadata.cjs +91 -0
  29. package/dist/metadata.cjs.map +1 -0
  30. package/dist/metadata.d.cts +58 -0
  31. package/dist/metadata.d.ts +58 -0
  32. package/dist/metadata.js +68 -0
  33. package/dist/metadata.js.map +1 -0
  34. package/dist/{payload-types-Ci-ZA7aM.d.cts → payload-types-DPjO_IbQ.d.cts} +9 -3
  35. package/dist/{payload-types-Ci-ZA7aM.d.ts → payload-types-DPjO_IbQ.d.ts} +9 -3
  36. package/dist/query.cjs +1791 -0
  37. package/dist/query.cjs.map +1 -0
  38. package/dist/query.d.cts +244 -0
  39. package/dist/query.d.ts +244 -0
  40. package/dist/query.js +1786 -0
  41. package/dist/query.js.map +1 -0
  42. package/dist/realtime.cjs +4 -1
  43. package/dist/realtime.cjs.map +1 -1
  44. package/dist/realtime.d.cts +2 -2
  45. package/dist/realtime.d.ts +2 -2
  46. package/dist/realtime.js +4 -1
  47. package/dist/realtime.js.map +1 -1
  48. package/dist/{server-BINWywT8.d.cts → server-CrsPyqEc.d.cts} +14 -31
  49. package/dist/{server-BINWywT8.d.ts → server-CrsPyqEc.d.ts} +14 -31
  50. package/dist/server.cjs +299 -840
  51. package/dist/server.cjs.map +1 -1
  52. package/dist/server.d.cts +112 -7
  53. package/dist/server.d.ts +112 -7
  54. package/dist/server.js +299 -858
  55. package/dist/server.js.map +1 -1
  56. package/dist/{types-BWq_WlbB.d.ts → types-1fBLrYU7.d.ts} +1 -1
  57. package/dist/{types-zKjATmDK.d.cts → types-BwT0eeaz.d.cts} +1 -1
  58. package/dist/{server-Cv0Q4dPQ.d.ts → types-Dlb2mwpX.d.cts} +228 -741
  59. package/dist/{server-C0C8dtms.d.cts → types-DuSKPiY5.d.ts} +228 -741
  60. package/dist/ui/canvas/server.cjs +7 -6
  61. package/dist/ui/canvas/server.cjs.map +1 -1
  62. package/dist/ui/canvas/server.d.cts +1 -3
  63. package/dist/ui/canvas/server.d.ts +1 -3
  64. package/dist/ui/canvas/server.js +7 -6
  65. package/dist/ui/canvas/server.js.map +1 -1
  66. package/dist/ui/canvas.cjs +11 -10
  67. package/dist/ui/canvas.cjs.map +1 -1
  68. package/dist/ui/canvas.d.cts +29 -6
  69. package/dist/ui/canvas.d.ts +29 -6
  70. package/dist/ui/canvas.js +11 -10
  71. package/dist/ui/canvas.js.map +1 -1
  72. package/dist/ui/form.d.cts +1 -1
  73. package/dist/ui/form.d.ts +1 -1
  74. package/dist/ui/video.d.cts +1 -1
  75. package/dist/ui/video.d.ts +1 -1
  76. package/dist/webhook.d.cts +3 -3
  77. package/dist/webhook.d.ts +3 -3
  78. package/package.json +84 -15
package/dist/query.js ADDED
@@ -0,0 +1,1786 @@
1
+ // src/core/query/get-query-client.ts
2
+ import {
3
+ isServer,
4
+ QueryClient,
5
+ defaultShouldDehydrateQuery
6
+ } from "@tanstack/react-query";
7
+ function makeQueryClient() {
8
+ return new QueryClient({
9
+ defaultOptions: {
10
+ queries: {
11
+ // Infinite staleTime: server-fetched data persists until explicitly invalidated.
12
+ // For browser clients needing fresher data, override per-query:
13
+ // useQuery({ ..., staleTime: 5 * 60 * 1000 })
14
+ staleTime: Number.POSITIVE_INFINITY,
15
+ refetchOnWindowFocus: false
16
+ },
17
+ dehydrate: {
18
+ shouldDehydrateQuery: (query) => defaultShouldDehydrateQuery(query) || query.state.status === "pending",
19
+ shouldRedactErrors: () => false
20
+ }
21
+ }
22
+ });
23
+ }
24
+ var browserQueryClient;
25
+ function getQueryClient() {
26
+ if (isServer) {
27
+ return makeQueryClient();
28
+ }
29
+ if (!browserQueryClient) {
30
+ browserQueryClient = makeQueryClient();
31
+ }
32
+ return browserQueryClient;
33
+ }
34
+
35
+ // src/core/query/query-keys.ts
36
+ function collectionKeys(collection) {
37
+ return {
38
+ all: [collection],
39
+ lists: () => [collection, "list"],
40
+ list: (options) => [collection, "list", options],
41
+ details: () => [collection, "detail"],
42
+ detail: (id, options) => [collection, "detail", id, options],
43
+ infinites: () => [collection, "infinite"],
44
+ infinite: (options) => [collection, "infinite", options]
45
+ };
46
+ }
47
+ var customerKeys = {
48
+ all: ["customer"],
49
+ me: () => ["customer", "me"]
50
+ };
51
+ var productKeys = {
52
+ listingGroups: (options) => ["products", "listing-groups", "list", options],
53
+ listingGroupsInfinite: (options) => ["products", "listing-groups", "infinite", options],
54
+ detail: (params) => ["products", "detail", params],
55
+ detailAll: () => ["products", "detail"]
56
+ };
57
+
58
+ // src/core/query/collection-hooks.ts
59
+ import {
60
+ useQuery as useQueryOriginal,
61
+ useSuspenseQuery as useSuspenseQueryOriginal,
62
+ useInfiniteQuery as useInfiniteQueryOriginal,
63
+ useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,
64
+ useMutation as useMutationOriginal
65
+ } from "@tanstack/react-query";
66
+ var PRODUCT_DETAIL_INVALIDATING_COLLECTIONS = /* @__PURE__ */ new Set([
67
+ "products",
68
+ "product-variants",
69
+ "product-options",
70
+ "product-option-values",
71
+ "product-categories",
72
+ "product-tags",
73
+ "product-collections",
74
+ "brands",
75
+ "brand-logos",
76
+ "images"
77
+ ]);
78
+ var DEFAULT_PAGE_SIZE = 20;
79
+ var CollectionHooks = class {
80
+ constructor(queryClient, collectionClient) {
81
+ this.queryClient = queryClient;
82
+ this.collectionClient = collectionClient;
83
+ }
84
+ // ===== useQuery =====
85
+ useQuery(params, options) {
86
+ const { collection, options: queryOptions } = params;
87
+ const { placeholderData, ...restOptions } = options ?? {};
88
+ return useQueryOriginal({
89
+ queryKey: collectionKeys(collection).list(queryOptions),
90
+ queryFn: async () => {
91
+ return await this.collectionClient.from(collection).find(queryOptions);
92
+ },
93
+ ...restOptions,
94
+ // NonFunctionGuard<T> incompatible with generic union types — safe cast
95
+ ...placeholderData !== void 0 && {
96
+ placeholderData
97
+ }
98
+ });
99
+ }
100
+ // ===== useSuspenseQuery =====
101
+ useSuspenseQuery(params, options) {
102
+ const { collection, options: queryOptions } = params;
103
+ return useSuspenseQueryOriginal({
104
+ queryKey: collectionKeys(collection).list(queryOptions),
105
+ queryFn: async () => {
106
+ return await this.collectionClient.from(collection).find(queryOptions);
107
+ },
108
+ ...options
109
+ });
110
+ }
111
+ // ===== useQueryById =====
112
+ useQueryById(params, options) {
113
+ const { collection, id, options: queryOptions } = params;
114
+ const { placeholderData, ...restOptions } = options ?? {};
115
+ return useQueryOriginal({
116
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
117
+ queryFn: async () => {
118
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
119
+ },
120
+ ...restOptions,
121
+ // NonFunctionGuard<T> incompatible with generic union types — safe cast
122
+ ...placeholderData !== void 0 && {
123
+ placeholderData
124
+ }
125
+ });
126
+ }
127
+ // ===== useSuspenseQueryById =====
128
+ useSuspenseQueryById(params, options) {
129
+ const { collection, id, options: queryOptions } = params;
130
+ return useSuspenseQueryOriginal({
131
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
132
+ queryFn: async () => {
133
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
134
+ },
135
+ ...options
136
+ });
137
+ }
138
+ // ===== useInfiniteQuery =====
139
+ useInfiniteQuery(params, options) {
140
+ const {
141
+ collection,
142
+ options: queryOptions,
143
+ pageSize = DEFAULT_PAGE_SIZE
144
+ } = params;
145
+ return useInfiniteQueryOriginal({
146
+ queryKey: collectionKeys(collection).infinite(queryOptions),
147
+ queryFn: async ({ pageParam }) => {
148
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
149
+ return response;
150
+ },
151
+ initialPageParam: 1,
152
+ getNextPageParam: (lastPage) => {
153
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
154
+ },
155
+ ...options
156
+ });
157
+ }
158
+ // ===== useSuspenseInfiniteQuery =====
159
+ useSuspenseInfiniteQuery(params, options) {
160
+ const {
161
+ collection,
162
+ options: queryOptions,
163
+ pageSize = DEFAULT_PAGE_SIZE
164
+ } = params;
165
+ return useSuspenseInfiniteQueryOriginal({
166
+ queryKey: collectionKeys(collection).infinite(queryOptions),
167
+ queryFn: async ({ pageParam }) => {
168
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
169
+ return response;
170
+ },
171
+ initialPageParam: 1,
172
+ getNextPageParam: (lastPage) => {
173
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
174
+ },
175
+ ...options
176
+ });
177
+ }
178
+ // ===== prefetchQuery =====
179
+ async prefetchQuery(params, options) {
180
+ const { collection, options: queryOptions } = params;
181
+ return this.queryClient.prefetchQuery({
182
+ queryKey: collectionKeys(collection).list(queryOptions),
183
+ queryFn: async () => {
184
+ return await this.collectionClient.from(collection).find(queryOptions);
185
+ },
186
+ ...options
187
+ });
188
+ }
189
+ // ===== prefetchQueryById =====
190
+ async prefetchQueryById(params, options) {
191
+ const { collection, id, options: queryOptions } = params;
192
+ return this.queryClient.prefetchQuery({
193
+ queryKey: collectionKeys(collection).detail(id, queryOptions),
194
+ queryFn: async () => {
195
+ return await this.collectionClient.from(collection).findById(id, queryOptions);
196
+ },
197
+ ...options
198
+ });
199
+ }
200
+ // ===== prefetchInfiniteQuery =====
201
+ async prefetchInfiniteQuery(params, options) {
202
+ const {
203
+ collection,
204
+ options: queryOptions,
205
+ pageSize = DEFAULT_PAGE_SIZE
206
+ } = params;
207
+ return this.queryClient.prefetchInfiniteQuery({
208
+ queryKey: collectionKeys(collection).infinite(queryOptions),
209
+ queryFn: async ({ pageParam }) => {
210
+ const response = await this.collectionClient.from(collection).find({ ...queryOptions, page: pageParam, limit: pageSize });
211
+ return response;
212
+ },
213
+ initialPageParam: 1,
214
+ getNextPageParam: (lastPage) => {
215
+ return lastPage.hasNextPage ? lastPage.nextPage : void 0;
216
+ },
217
+ pages: options?.pages ?? 1,
218
+ staleTime: options?.staleTime
219
+ });
220
+ }
221
+ // ===== Mutation Hooks =====
222
+ useCreate(params, options) {
223
+ const { collection } = params;
224
+ return useMutationOriginal({
225
+ mutationFn: async (variables) => {
226
+ return await this.collectionClient.from(collection).create(
227
+ variables.data,
228
+ variables.file ? { file: variables.file, filename: variables.filename } : void 0
229
+ );
230
+ },
231
+ onSuccess: (data) => {
232
+ this.queryClient.invalidateQueries({
233
+ queryKey: collectionKeys(collection).all
234
+ });
235
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
236
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
237
+ }
238
+ options?.onSuccess?.(data);
239
+ },
240
+ onError: options?.onError,
241
+ onSettled: options?.onSettled
242
+ });
243
+ }
244
+ useUpdate(params, options) {
245
+ const { collection } = params;
246
+ return useMutationOriginal({
247
+ mutationFn: async (variables) => {
248
+ return await this.collectionClient.from(collection).update(
249
+ variables.id,
250
+ variables.data,
251
+ variables.file ? { file: variables.file, filename: variables.filename } : void 0
252
+ );
253
+ },
254
+ onSuccess: (data) => {
255
+ this.queryClient.invalidateQueries({
256
+ queryKey: collectionKeys(collection).all
257
+ });
258
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
259
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
260
+ }
261
+ options?.onSuccess?.(data);
262
+ },
263
+ onError: options?.onError,
264
+ onSettled: options?.onSettled
265
+ });
266
+ }
267
+ useRemove(params, options) {
268
+ const { collection } = params;
269
+ return useMutationOriginal({
270
+ mutationFn: async (id) => {
271
+ return await this.collectionClient.from(collection).remove(id);
272
+ },
273
+ onSuccess: (data) => {
274
+ this.queryClient.invalidateQueries({
275
+ queryKey: collectionKeys(collection).all
276
+ });
277
+ if (PRODUCT_DETAIL_INVALIDATING_COLLECTIONS.has(collection)) {
278
+ this.queryClient.invalidateQueries({ queryKey: ["products", "detail"] });
279
+ }
280
+ options?.onSuccess?.(data);
281
+ },
282
+ onError: options?.onError,
283
+ onSettled: options?.onSettled
284
+ });
285
+ }
286
+ // ===== Cache Utilities =====
287
+ invalidateQueries(collection, type) {
288
+ const queryKey = type ? [collection, type] : [collection];
289
+ return this.queryClient.invalidateQueries({ queryKey });
290
+ }
291
+ getQueryData(collection, type, idOrOptions, options) {
292
+ if (type === "list") {
293
+ return this.queryClient.getQueryData(
294
+ collectionKeys(collection).list(idOrOptions)
295
+ );
296
+ }
297
+ return this.queryClient.getQueryData(
298
+ collectionKeys(collection).detail(idOrOptions, options)
299
+ );
300
+ }
301
+ setQueryData(collection, type, dataOrId, dataOrOptions, options) {
302
+ if (type === "list") {
303
+ this.queryClient.setQueryData(
304
+ collectionKeys(collection).list(dataOrOptions),
305
+ dataOrId
306
+ );
307
+ } else {
308
+ this.queryClient.setQueryData(
309
+ collectionKeys(collection).detail(dataOrId, options),
310
+ dataOrOptions
311
+ );
312
+ }
313
+ }
314
+ };
315
+
316
+ // src/core/query/customer-hooks.ts
317
+ import {
318
+ useQuery as useQueryOriginal2,
319
+ useMutation as useMutationOriginal2
320
+ } from "@tanstack/react-query";
321
+
322
+ // src/core/internal/errors/index.ts
323
+ var SDKError = class extends Error {
324
+ constructor(code, message, status, details, userMessage, suggestion, requestId) {
325
+ super(message);
326
+ this.name = "SDKError";
327
+ this.code = code;
328
+ this.status = status;
329
+ this.details = details;
330
+ this.userMessage = userMessage;
331
+ this.suggestion = suggestion;
332
+ this.requestId = requestId;
333
+ if (Error.captureStackTrace) {
334
+ Error.captureStackTrace(this, new.target);
335
+ }
336
+ }
337
+ getUserMessage() {
338
+ return this.userMessage || this.message;
339
+ }
340
+ toJSON() {
341
+ return {
342
+ name: this.name,
343
+ code: this.code,
344
+ message: this.message,
345
+ status: this.status,
346
+ details: this.details,
347
+ userMessage: this.userMessage,
348
+ suggestion: this.suggestion,
349
+ ...this.requestId !== void 0 && { requestId: this.requestId }
350
+ };
351
+ }
352
+ };
353
+ var NetworkError = class extends SDKError {
354
+ constructor(message, status, details, userMessage, suggestion) {
355
+ super("NETWORK_ERROR", message, status, details, userMessage, suggestion);
356
+ this.name = "NetworkError";
357
+ }
358
+ };
359
+ var ValidationError = class extends SDKError {
360
+ constructor(message, details, userMessage, suggestion, status = 400) {
361
+ super("VALIDATION_ERROR", message, status, details, userMessage, suggestion);
362
+ this.name = "ValidationError";
363
+ }
364
+ };
365
+ var ApiError = class extends SDKError {
366
+ constructor(message, status, details, userMessage, suggestion) {
367
+ super("API_ERROR", message, status, details, userMessage, suggestion);
368
+ this.name = "ApiError";
369
+ }
370
+ };
371
+ var ConfigError = class extends SDKError {
372
+ constructor(message, details, userMessage, suggestion) {
373
+ super("CONFIG_ERROR", message, void 0, details, userMessage, suggestion);
374
+ this.name = "ConfigError";
375
+ }
376
+ };
377
+ var TimeoutError = class extends SDKError {
378
+ constructor(message = "Request timed out.", details, userMessage, suggestion) {
379
+ super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
380
+ this.name = "TimeoutError";
381
+ }
382
+ };
383
+ var UsageLimitError = class extends SDKError {
384
+ constructor(message, usage, details, userMessage, suggestion) {
385
+ super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
386
+ this.name = "UsageLimitError";
387
+ this.usage = usage;
388
+ }
389
+ toJSON() {
390
+ return {
391
+ ...super.toJSON(),
392
+ usage: this.usage
393
+ };
394
+ }
395
+ };
396
+ var AuthError = class extends SDKError {
397
+ constructor(message, details, userMessage, suggestion, requestId) {
398
+ super("auth_error", message, 401, details, userMessage, suggestion, requestId);
399
+ this.name = "AuthError";
400
+ }
401
+ };
402
+ var PermissionError = class extends SDKError {
403
+ constructor(message, details, userMessage, suggestion, requestId) {
404
+ super("permission_error", message, 403, details, userMessage, suggestion, requestId);
405
+ this.name = "PermissionError";
406
+ }
407
+ };
408
+ var NotFoundError = class extends SDKError {
409
+ constructor(message, details, userMessage, suggestion, requestId) {
410
+ super("not_found", message, 404, details, userMessage, suggestion, requestId);
411
+ this.name = "NotFoundError";
412
+ }
413
+ };
414
+ var ConflictError = class extends SDKError {
415
+ constructor(message, details, userMessage, suggestion, requestId) {
416
+ super("conflict", message, 409, details, userMessage, suggestion, requestId);
417
+ this.name = "ConflictError";
418
+ }
419
+ };
420
+ var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
421
+ var createValidationError = (message, details, userMessage, suggestion, status) => new ValidationError(message, details, userMessage, suggestion, status);
422
+ var createApiError = (message, status, details, userMessage, suggestion) => new ApiError(message, status, details, userMessage, suggestion);
423
+ var createConfigError = (message, details, userMessage, suggestion) => new ConfigError(message, details, userMessage, suggestion);
424
+ var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
425
+ var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
426
+ var createAuthError = (message, details, userMessage, suggestion, requestId) => new AuthError(message, details, userMessage, suggestion, requestId);
427
+ var createPermissionError = (message, details, userMessage, suggestion, requestId) => new PermissionError(message, details, userMessage, suggestion, requestId);
428
+ var createNotFoundError = (message, details, userMessage, suggestion, requestId) => new NotFoundError(message, details, userMessage, suggestion, requestId);
429
+ var createConflictError = (message, details, userMessage, suggestion, requestId) => new ConflictError(message, details, userMessage, suggestion, requestId);
430
+
431
+ // src/core/query/customer-hooks.ts
432
+ function createMutation(mutationFn, callbacks, onSuccessExtra) {
433
+ return useMutationOriginal2({
434
+ mutationFn,
435
+ onSuccess: (data) => {
436
+ onSuccessExtra?.(data);
437
+ callbacks?.onSuccess?.(data);
438
+ },
439
+ onError: callbacks?.onError,
440
+ onSettled: callbacks?.onSettled
441
+ });
442
+ }
443
+ var CustomerHooks = class {
444
+ constructor(queryClient, customerAuth) {
445
+ this.invalidateMe = () => {
446
+ this.queryClient.invalidateQueries({ queryKey: customerKeys.me() });
447
+ };
448
+ this.queryClient = queryClient;
449
+ this.customerAuth = customerAuth;
450
+ }
451
+ ensureCustomerAuth() {
452
+ if (!this.customerAuth) {
453
+ throw createConfigError(
454
+ "Customer hooks require Client. Use createClient() instead of createServerClient()."
455
+ );
456
+ }
457
+ return this.customerAuth;
458
+ }
459
+ // ===== useCustomerMe =====
460
+ useCustomerMe(options) {
461
+ return useQueryOriginal2({
462
+ queryKey: customerKeys.me(),
463
+ queryFn: async () => {
464
+ return await this.ensureCustomerAuth().me();
465
+ },
466
+ ...options,
467
+ enabled: (options?.enabled ?? true) && !!this.customerAuth?.isAuthenticated()
468
+ });
469
+ }
470
+ // ===== Mutations =====
471
+ useCustomerLogin(options) {
472
+ return createMutation(
473
+ (data) => this.ensureCustomerAuth().login(data),
474
+ options,
475
+ this.invalidateMe
476
+ );
477
+ }
478
+ useCustomerRegister(options) {
479
+ return createMutation(
480
+ (data) => this.ensureCustomerAuth().register(data),
481
+ options
482
+ );
483
+ }
484
+ useCustomerLogout(options) {
485
+ return useMutationOriginal2({
486
+ mutationFn: async () => {
487
+ this.ensureCustomerAuth().logout();
488
+ },
489
+ onSuccess: () => {
490
+ this.queryClient.removeQueries({ queryKey: customerKeys.all });
491
+ options?.onSuccess?.();
492
+ },
493
+ onError: options?.onError,
494
+ onSettled: options?.onSettled
495
+ });
496
+ }
497
+ useCustomerForgotPassword(options) {
498
+ return createMutation(
499
+ (email) => this.ensureCustomerAuth().forgotPassword(email).then(() => {
500
+ }),
501
+ options
502
+ );
503
+ }
504
+ useCustomerResetPassword(options) {
505
+ return createMutation(
506
+ (data) => this.ensureCustomerAuth().resetPassword(data.token, data.password).then(() => {
507
+ }),
508
+ options
509
+ );
510
+ }
511
+ useCustomerRefreshToken(options) {
512
+ return createMutation(
513
+ () => this.ensureCustomerAuth().refreshToken(),
514
+ options,
515
+ this.invalidateMe
516
+ );
517
+ }
518
+ useCustomerUpdateProfile(options) {
519
+ return createMutation(
520
+ (data) => this.ensureCustomerAuth().updateProfile(data),
521
+ options,
522
+ this.invalidateMe
523
+ );
524
+ }
525
+ useCustomerChangePassword(options) {
526
+ return createMutation(
527
+ (data) => this.ensureCustomerAuth().changePassword(data.currentPassword, data.newPassword).then(() => {
528
+ }),
529
+ options
530
+ );
531
+ }
532
+ // ===== Customer Cache Utilities =====
533
+ invalidateCustomerQueries() {
534
+ return this.queryClient.invalidateQueries({ queryKey: customerKeys.all });
535
+ }
536
+ getCustomerData() {
537
+ return this.queryClient.getQueryData(customerKeys.me());
538
+ }
539
+ setCustomerData(data) {
540
+ this.queryClient.setQueryData(customerKeys.me(), data);
541
+ }
542
+ };
543
+
544
+ // src/core/query/query-hooks.ts
545
+ import {
546
+ useInfiniteQuery as useInfiniteQueryOriginal2,
547
+ useQuery as useQueryOriginal3,
548
+ useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal2,
549
+ useSuspenseQuery as useSuspenseQueryOriginal2
550
+ } from "@tanstack/react-query";
551
+ var QueryHooks = class extends CollectionHooks {
552
+ constructor(queryClient, collectionClient, customerAuth, commerceClient) {
553
+ super(queryClient, collectionClient);
554
+ // --- Customer hooks delegation ---
555
+ this.useCustomerMe = (...args) => this._customer.useCustomerMe(...args);
556
+ this.useCustomerLogin = (...args) => this._customer.useCustomerLogin(...args);
557
+ this.useCustomerRegister = (...args) => this._customer.useCustomerRegister(...args);
558
+ this.useCustomerLogout = (...args) => this._customer.useCustomerLogout(...args);
559
+ this.useCustomerForgotPassword = (...args) => this._customer.useCustomerForgotPassword(...args);
560
+ this.useCustomerResetPassword = (...args) => this._customer.useCustomerResetPassword(...args);
561
+ this.useCustomerRefreshToken = (...args) => this._customer.useCustomerRefreshToken(...args);
562
+ this.useCustomerUpdateProfile = (...args) => this._customer.useCustomerUpdateProfile(...args);
563
+ this.useCustomerChangePassword = (...args) => this._customer.useCustomerChangePassword(...args);
564
+ // --- Customer cache delegation ---
565
+ this.invalidateCustomerQueries = () => this._customer.invalidateCustomerQueries();
566
+ this.getCustomerData = () => this._customer.getCustomerData();
567
+ this.setCustomerData = (data) => this._customer.setCustomerData(data);
568
+ this._customer = new CustomerHooks(queryClient, customerAuth);
569
+ this._commerce = commerceClient;
570
+ }
571
+ useProductListingGroupsQuery(params, options) {
572
+ const queryOptions = params.options;
573
+ const { placeholderData, ...restOptions } = options ?? {};
574
+ return useQueryOriginal3({
575
+ queryKey: productKeys.listingGroups(queryOptions),
576
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
577
+ "/api/products/listing-groups/query",
578
+ { options: queryOptions }
579
+ ),
580
+ ...restOptions,
581
+ ...placeholderData !== void 0 && {
582
+ placeholderData
583
+ }
584
+ });
585
+ }
586
+ useSuspenseProductListingGroupsQuery(params, options) {
587
+ const queryOptions = params.options;
588
+ return useSuspenseQueryOriginal2({
589
+ queryKey: productKeys.listingGroups(queryOptions),
590
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
591
+ "/api/products/listing-groups/query",
592
+ { options: queryOptions }
593
+ ),
594
+ ...options
595
+ });
596
+ }
597
+ useInfiniteProductListingGroupsQuery(params, options) {
598
+ const {
599
+ options: queryOptions,
600
+ pageSize = 20
601
+ } = params;
602
+ return useInfiniteQueryOriginal2({
603
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
604
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
605
+ "/api/products/listing-groups/query",
606
+ {
607
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
608
+ }
609
+ ),
610
+ initialPageParam: 1,
611
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
612
+ ...options
613
+ });
614
+ }
615
+ useSuspenseInfiniteProductListingGroupsQuery(params, options) {
616
+ const {
617
+ options: queryOptions,
618
+ pageSize = 20
619
+ } = params;
620
+ return useSuspenseInfiniteQueryOriginal2({
621
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
622
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
623
+ "/api/products/listing-groups/query",
624
+ {
625
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
626
+ }
627
+ ),
628
+ initialPageParam: 1,
629
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
630
+ ...options
631
+ });
632
+ }
633
+ async prefetchProductListingGroupsQuery(params, options) {
634
+ const queryOptions = params.options;
635
+ return this.queryClient.prefetchQuery({
636
+ queryKey: productKeys.listingGroups(queryOptions),
637
+ queryFn: async () => this.collectionClient.requestFindEndpoint(
638
+ "/api/products/listing-groups/query",
639
+ { options: queryOptions }
640
+ ),
641
+ ...options
642
+ });
643
+ }
644
+ async prefetchInfiniteProductListingGroupsQuery(params, options) {
645
+ const {
646
+ options: queryOptions,
647
+ pageSize = 20
648
+ } = params;
649
+ return this.queryClient.prefetchInfiniteQuery({
650
+ queryKey: productKeys.listingGroupsInfinite(queryOptions),
651
+ queryFn: async ({ pageParam }) => this.collectionClient.requestFindEndpoint(
652
+ "/api/products/listing-groups/query",
653
+ {
654
+ options: { ...queryOptions, page: pageParam, limit: pageSize }
655
+ }
656
+ ),
657
+ initialPageParam: 1,
658
+ getNextPageParam: (lastPage) => lastPage.hasNextPage ? lastPage.nextPage : void 0,
659
+ pages: options?.pages ?? 1,
660
+ staleTime: options?.staleTime
661
+ });
662
+ }
663
+ useProductDetail(params, options) {
664
+ const discriminator = "slug" in params ? params.slug : params.id;
665
+ const enabled = options?.enabled !== false && Boolean(discriminator);
666
+ return useQueryOriginal3({
667
+ queryKey: productKeys.detail(params),
668
+ queryFn: () => this._commerce.product.detail(params),
669
+ enabled
670
+ });
671
+ }
672
+ useProductDetailBySlug(slug, options) {
673
+ return this.useProductDetail({ slug }, options);
674
+ }
675
+ useProductDetailById(id, options) {
676
+ return this.useProductDetail({ id }, options);
677
+ }
678
+ };
679
+
680
+ // src/core/query/realtime.ts
681
+ var INITIAL_RECONNECT_DELAY = 1e3;
682
+ var MAX_RECONNECT_DELAY = 3e4;
683
+ var RECONNECT_BACKOFF_FACTOR = 2;
684
+ var MAX_NO_TOKEN_RETRIES = 5;
685
+ var RealtimeConnection = class {
686
+ constructor(baseUrl, publishableKey, getToken, collections) {
687
+ this.baseUrl = baseUrl;
688
+ this.publishableKey = publishableKey;
689
+ this.getToken = getToken;
690
+ this.collections = collections;
691
+ this.abortController = null;
692
+ this.reconnectAttempt = 0;
693
+ this.noTokenAttempts = 0;
694
+ this.reconnectTimer = null;
695
+ this.listeners = /* @__PURE__ */ new Set();
696
+ this._connected = false;
697
+ }
698
+ get connected() {
699
+ return this._connected;
700
+ }
701
+ addListener(fn) {
702
+ this.listeners.add(fn);
703
+ return () => this.listeners.delete(fn);
704
+ }
705
+ connect() {
706
+ if (this.abortController) return;
707
+ this.abortController = new AbortController();
708
+ this.startStream(this.abortController.signal);
709
+ }
710
+ disconnect() {
711
+ this._connected = false;
712
+ if (this.reconnectTimer) {
713
+ clearTimeout(this.reconnectTimer);
714
+ this.reconnectTimer = null;
715
+ }
716
+ if (this.abortController) {
717
+ this.abortController.abort();
718
+ this.abortController = null;
719
+ }
720
+ this.reconnectAttempt = 0;
721
+ this.noTokenAttempts = 0;
722
+ }
723
+ async startStream(signal) {
724
+ const token = this.getToken();
725
+ if (!token) {
726
+ this.noTokenAttempts++;
727
+ if (this.noTokenAttempts >= MAX_NO_TOKEN_RETRIES) {
728
+ this._connected = false;
729
+ this.abortController = null;
730
+ return;
731
+ }
732
+ this.scheduleReconnect();
733
+ return;
734
+ }
735
+ this.noTokenAttempts = 0;
736
+ const params = this.collections?.length ? `?collections=${this.collections.join(",")}` : "";
737
+ const url = `${this.baseUrl}/api/events/stream${params}`;
738
+ try {
739
+ const response = await fetch(url, {
740
+ headers: {
741
+ "X-Publishable-Key": this.publishableKey,
742
+ Authorization: `Bearer ${token}`
743
+ },
744
+ signal
745
+ });
746
+ if (!response.ok) {
747
+ if (response.status === 401) {
748
+ this.scheduleReconnect();
749
+ return;
750
+ }
751
+ throw new Error(`SSE connection failed: ${response.status}`);
752
+ }
753
+ if (!response.body) {
754
+ throw new Error("SSE response has no body");
755
+ }
756
+ this._connected = true;
757
+ this.reconnectAttempt = 0;
758
+ await this.readStream(response.body, signal);
759
+ } catch {
760
+ if (signal.aborted) return;
761
+ this._connected = false;
762
+ this.scheduleReconnect();
763
+ }
764
+ }
765
+ async readStream(body, signal) {
766
+ const reader = body.getReader();
767
+ const decoder = new TextDecoder();
768
+ let buffer = "";
769
+ let currentEvent = "";
770
+ let currentData = "";
771
+ try {
772
+ while (true) {
773
+ const { done, value } = await reader.read();
774
+ if (done || signal.aborted) break;
775
+ buffer += decoder.decode(value, { stream: true });
776
+ const lines = buffer.split("\n");
777
+ buffer = lines.pop() ?? "";
778
+ for (const line of lines) {
779
+ if (line.startsWith("event: ")) {
780
+ currentEvent = line.slice(7);
781
+ } else if (line.startsWith("data: ")) {
782
+ currentData += (currentData ? "\n" : "") + line.slice(6);
783
+ } else if (line === "") {
784
+ if (currentEvent === "collection:change" && currentData) {
785
+ try {
786
+ const event = JSON.parse(currentData);
787
+ for (const listener of this.listeners) {
788
+ try {
789
+ listener(event);
790
+ } catch {
791
+ }
792
+ }
793
+ } catch {
794
+ }
795
+ }
796
+ currentEvent = "";
797
+ currentData = "";
798
+ }
799
+ }
800
+ }
801
+ } catch {
802
+ } finally {
803
+ reader.releaseLock();
804
+ this._connected = false;
805
+ if (!signal.aborted) {
806
+ this.scheduleReconnect();
807
+ }
808
+ }
809
+ }
810
+ scheduleReconnect() {
811
+ if (this.reconnectTimer) return;
812
+ const delay2 = Math.min(
813
+ INITIAL_RECONNECT_DELAY * Math.pow(RECONNECT_BACKOFF_FACTOR, this.reconnectAttempt),
814
+ MAX_RECONNECT_DELAY
815
+ );
816
+ this.reconnectAttempt++;
817
+ this.reconnectTimer = setTimeout(() => {
818
+ this.reconnectTimer = null;
819
+ this.abortController = new AbortController();
820
+ this.startStream(this.abortController.signal);
821
+ }, delay2);
822
+ }
823
+ };
824
+
825
+ // src/utils/types.ts
826
+ var resolveRelation = (ref) => {
827
+ if (typeof ref === "string" || typeof ref === "number" || ref === null || ref === void 0)
828
+ return null;
829
+ return ref;
830
+ };
831
+
832
+ // src/core/metadata/index.ts
833
+ function extractSeo(doc) {
834
+ const seo = doc.seo ?? {};
835
+ const og = seo.openGraph ?? {};
836
+ return {
837
+ title: seo.title ?? doc.title ?? null,
838
+ description: seo.description ?? null,
839
+ noIndex: seo.noIndex ?? null,
840
+ canonical: seo.canonical ?? null,
841
+ openGraph: {
842
+ title: og.title ?? null,
843
+ description: og.description ?? null,
844
+ image: og.image ?? null
845
+ }
846
+ };
847
+ }
848
+ function generateMetadata(input, options) {
849
+ const title = input.title ?? void 0;
850
+ const description = input.description ?? void 0;
851
+ const ogTitle = input.openGraph?.title ?? title;
852
+ const ogDescription = input.openGraph?.description ?? description;
853
+ const image = resolveMetaImage(input.openGraph?.image);
854
+ return {
855
+ title,
856
+ description,
857
+ ...input.noIndex && { robots: { index: false, follow: false } },
858
+ ...input.canonical && { alternates: { canonical: input.canonical } },
859
+ openGraph: {
860
+ ...ogTitle && { title: ogTitle },
861
+ ...ogDescription && { description: ogDescription },
862
+ ...options?.siteName && { siteName: options.siteName },
863
+ ...image && { images: [image] }
864
+ },
865
+ twitter: {
866
+ card: image ? "summary_large_image" : "summary",
867
+ ...ogTitle && { title: ogTitle },
868
+ ...ogDescription && { description: ogDescription },
869
+ ...image && { images: [image.url] }
870
+ }
871
+ };
872
+ }
873
+ function resolveMetaImage(ref) {
874
+ const image = resolveRelation(ref);
875
+ if (!image) return null;
876
+ const sized = image.sizes?.["1536"];
877
+ const url = sized?.url || image.url;
878
+ if (!url) return null;
879
+ const width = sized?.url ? sized.width : image.width;
880
+ const height = sized?.url ? sized.height : image.height;
881
+ return {
882
+ url,
883
+ ...width && { width },
884
+ ...height && { height },
885
+ ...image.alt && { alt: image.alt }
886
+ };
887
+ }
888
+
889
+ // src/core/collection/query-builder.ts
890
+ var CollectionQueryBuilder = class {
891
+ constructor(api, collection) {
892
+ this.api = api;
893
+ this.collection = collection;
894
+ }
895
+ /**
896
+ * Find documents (list query)
897
+ * GET /api/{collection}
898
+ * @returns Payload CMS find response with docs array and pagination
899
+ */
900
+ async find(options) {
901
+ return this.api.requestFind(
902
+ `/api/${String(this.collection)}`,
903
+ options
904
+ );
905
+ }
906
+ /**
907
+ * Find document by ID
908
+ * GET /api/{collection}/{id}
909
+ * @returns Document object directly (no wrapper)
910
+ */
911
+ async findById(id, options) {
912
+ return this.api.requestFindById(
913
+ `/api/${String(this.collection)}/${String(id)}`,
914
+ options
915
+ );
916
+ }
917
+ /**
918
+ * Create a new document
919
+ * POST /api/{collection}
920
+ * @returns Payload CMS mutation response with doc and message
921
+ */
922
+ async create(data, options) {
923
+ const endpoint = `/api/${String(this.collection)}`;
924
+ if (options?.file) {
925
+ return this.api.requestCreateWithFile(
926
+ endpoint,
927
+ data,
928
+ options.file,
929
+ options.filename
930
+ );
931
+ }
932
+ return this.api.requestCreate(endpoint, data);
933
+ }
934
+ /**
935
+ * Update a document by ID
936
+ * PATCH /api/{collection}/{id}
937
+ * @returns Payload CMS mutation response with doc and message
938
+ */
939
+ async update(id, data, options) {
940
+ const endpoint = `/api/${String(this.collection)}/${String(id)}`;
941
+ if (options?.file) {
942
+ return this.api.requestUpdateWithFile(
943
+ endpoint,
944
+ data,
945
+ options.file,
946
+ options.filename
947
+ );
948
+ }
949
+ return this.api.requestUpdate(endpoint, data);
950
+ }
951
+ /**
952
+ * Count documents
953
+ * GET /api/{collection}/count
954
+ * @returns Count response with totalDocs
955
+ */
956
+ async count(options) {
957
+ return this.api.requestCount(
958
+ `/api/${String(this.collection)}/count`,
959
+ options
960
+ );
961
+ }
962
+ /**
963
+ * Find first matching document and return its Next.js Metadata.
964
+ * Applies depth: 1 (SEO image populate) and limit: 1 automatically.
965
+ * @returns Metadata or null if no document matches
966
+ */
967
+ async findMetadata(options, metadataOptions) {
968
+ const { docs } = await this.find({ ...options, limit: 1, depth: 1 });
969
+ const doc = docs[0];
970
+ if (!doc) return null;
971
+ return generateMetadata(
972
+ extractSeo(doc),
973
+ metadataOptions
974
+ );
975
+ }
976
+ /**
977
+ * Find document by ID and return its Next.js Metadata.
978
+ * Applies depth: 1 (SEO image populate) automatically.
979
+ * @returns Metadata (throws on 404)
980
+ */
981
+ async findMetadataById(id, metadataOptions) {
982
+ const doc = await this.findById(id, { depth: 1 });
983
+ return generateMetadata(
984
+ extractSeo(doc),
985
+ metadataOptions
986
+ );
987
+ }
988
+ /**
989
+ * Update multiple documents (bulk update)
990
+ * PATCH /api/{collection}
991
+ * @returns Payload CMS find response with updated docs
992
+ */
993
+ async updateMany(where, data) {
994
+ return this.api.requestUpdateMany(
995
+ `/api/${String(this.collection)}`,
996
+ { where, data }
997
+ );
998
+ }
999
+ /**
1000
+ * Delete a document by ID
1001
+ * DELETE /api/{collection}/{id}
1002
+ * @returns Deleted document object directly (no wrapper)
1003
+ */
1004
+ async remove(id) {
1005
+ return this.api.requestDelete(
1006
+ `/api/${String(this.collection)}/${String(id)}`
1007
+ );
1008
+ }
1009
+ /**
1010
+ * Delete multiple documents (bulk delete)
1011
+ * DELETE /api/{collection}
1012
+ * @returns Payload CMS find response with deleted docs
1013
+ */
1014
+ async removeMany(where) {
1015
+ return this.api.requestDeleteMany(
1016
+ `/api/${String(this.collection)}`,
1017
+ { where }
1018
+ );
1019
+ }
1020
+ };
1021
+
1022
+ // src/core/collection/http-client.ts
1023
+ import { stringify } from "qs-esm";
1024
+
1025
+ // src/core/internal/utils/credentials.ts
1026
+ function requirePublishableKeyForSecret(apiName, publishableKey, secretKey) {
1027
+ if (secretKey && !publishableKey) {
1028
+ throw createConfigError(
1029
+ `publishableKey is required for ${apiName} when secretKey is used. It is sent as X-Publishable-Key for tenant routing, rate limiting, and quota enforcement.`
1030
+ );
1031
+ }
1032
+ return publishableKey ?? "";
1033
+ }
1034
+
1035
+ // src/core/client/types.ts
1036
+ function resolveApiUrl(apiUrl) {
1037
+ if (apiUrl) {
1038
+ return apiUrl.replace(/\/$/, "");
1039
+ }
1040
+ if (typeof process !== "undefined" && process.env) {
1041
+ const envUrl = process.env.SOFTWARE_API_URL || process.env.NEXT_PUBLIC_SOFTWARE_API_URL;
1042
+ if (envUrl) {
1043
+ return envUrl.replace(/\/$/, "");
1044
+ }
1045
+ }
1046
+ return "https://api.01.software";
1047
+ }
1048
+
1049
+ // src/core/internal/utils/http.ts
1050
+ var DEFAULT_TIMEOUT = 3e4;
1051
+ var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
1052
+ var NON_RETRYABLE_STATUSES = [400, 401, 403, 404, 409, 422];
1053
+ var SAFE_METHODS = ["GET", "HEAD", "OPTIONS"];
1054
+ function debugLog(debug, type, message, data) {
1055
+ if (!debug) return;
1056
+ const shouldLog = debug === true || type === "request" && debug.logRequests || type === "response" && debug.logResponses || type === "error" && debug.logErrors;
1057
+ if (shouldLog) {
1058
+ console.group(`[SDK ${type.toUpperCase()}] ${message}`);
1059
+ if (data) console.log(data);
1060
+ console.groupEnd();
1061
+ }
1062
+ }
1063
+ function getErrorSuggestion(status) {
1064
+ if (status === 400)
1065
+ return "The request data failed validation. Check field values and types.";
1066
+ if (status === 401) return "Please check your authentication credentials.";
1067
+ if (status === 403)
1068
+ return "Access denied. Check your credentials or permissions.";
1069
+ if (status === 404) return "The requested resource was not found.";
1070
+ if (status === 422) return "The request data failed validation.";
1071
+ if (status >= 500) return "A server error occurred. Please try again later.";
1072
+ return void 0;
1073
+ }
1074
+ function isUsageLimitExceededResponse(response) {
1075
+ if (response.status !== 429) return false;
1076
+ const limit = parseInt(response.headers.get("X-Usage-Limit") || "", 10);
1077
+ const current = parseInt(response.headers.get("X-Usage-Current") || "", 10);
1078
+ if (!Number.isFinite(limit) || !Number.isFinite(current)) return false;
1079
+ return response.headers.get("X-Usage-Exceeded") === "true" || current > limit;
1080
+ }
1081
+ async function parseErrorBody(response) {
1082
+ const fallback = {
1083
+ errorMessage: `HTTP ${response.status}: ${response.statusText}`,
1084
+ userMessage: `Request failed (status: ${response.status})`
1085
+ };
1086
+ try {
1087
+ const body = await response.json();
1088
+ const reason = typeof body.reason === "string" ? body.reason : typeof body.code === "string" ? body.code : void 0;
1089
+ if (body.errors && Array.isArray(body.errors)) {
1090
+ const fieldErrors = [];
1091
+ for (const e of body.errors) {
1092
+ if (e.data?.errors && Array.isArray(e.data.errors) && e.data.errors.length > 0) {
1093
+ for (const fe of e.data.errors) {
1094
+ fieldErrors.push({
1095
+ field: fe.path || fe.field,
1096
+ message: fe.message
1097
+ });
1098
+ }
1099
+ } else if (e.field || e.message) {
1100
+ fieldErrors.push({ field: e.field, message: e.message });
1101
+ }
1102
+ }
1103
+ const details = (fieldErrors.length > 0 ? fieldErrors : body.errors).map(
1104
+ (e) => e.field ? `${e.field}: ${e.message}` : e.message
1105
+ ).filter(Boolean).join("; ");
1106
+ if (details) {
1107
+ return {
1108
+ errorMessage: `HTTP ${response.status}: ${details}`,
1109
+ userMessage: details,
1110
+ reason,
1111
+ body,
1112
+ errors: fieldErrors.length > 0 ? fieldErrors : body.errors
1113
+ };
1114
+ }
1115
+ }
1116
+ if (typeof body.error === "string") {
1117
+ return {
1118
+ errorMessage: `HTTP ${response.status}: ${body.error}`,
1119
+ userMessage: body.error,
1120
+ reason,
1121
+ body
1122
+ };
1123
+ }
1124
+ if (body.message) {
1125
+ return {
1126
+ errorMessage: `HTTP ${response.status}: ${body.message}`,
1127
+ userMessage: body.message,
1128
+ reason,
1129
+ body
1130
+ };
1131
+ }
1132
+ return { ...fallback, reason, body };
1133
+ } catch {
1134
+ return fallback;
1135
+ }
1136
+ }
1137
+ async function delay(ms) {
1138
+ return new Promise((resolve) => setTimeout(resolve, ms));
1139
+ }
1140
+ function attachRequestId(err, id) {
1141
+ if (id) err.requestId = id;
1142
+ return err;
1143
+ }
1144
+ function createHttpStatusError(status, parsed, details, requestId) {
1145
+ const errorDetails = {
1146
+ ...details,
1147
+ ...parsed.errors && { errors: parsed.errors },
1148
+ ...parsed.body && { body: parsed.body }
1149
+ };
1150
+ const suggestion = getErrorSuggestion(status);
1151
+ if (status === 400 || status === 422) {
1152
+ return attachRequestId(
1153
+ createValidationError(
1154
+ parsed.errorMessage,
1155
+ errorDetails,
1156
+ parsed.userMessage,
1157
+ suggestion,
1158
+ status
1159
+ ),
1160
+ requestId
1161
+ );
1162
+ }
1163
+ if (status === 401) {
1164
+ return attachRequestId(
1165
+ createAuthError(
1166
+ parsed.errorMessage,
1167
+ errorDetails,
1168
+ parsed.userMessage,
1169
+ suggestion
1170
+ ),
1171
+ requestId
1172
+ );
1173
+ }
1174
+ if (status === 403) {
1175
+ return attachRequestId(
1176
+ createPermissionError(
1177
+ parsed.errorMessage,
1178
+ errorDetails,
1179
+ parsed.userMessage,
1180
+ suggestion
1181
+ ),
1182
+ requestId
1183
+ );
1184
+ }
1185
+ if (status === 404) {
1186
+ return attachRequestId(
1187
+ createNotFoundError(
1188
+ parsed.errorMessage,
1189
+ errorDetails,
1190
+ parsed.userMessage,
1191
+ suggestion
1192
+ ),
1193
+ requestId
1194
+ );
1195
+ }
1196
+ if (status === 409) {
1197
+ return attachRequestId(
1198
+ createConflictError(
1199
+ parsed.errorMessage,
1200
+ errorDetails,
1201
+ parsed.userMessage,
1202
+ suggestion
1203
+ ),
1204
+ requestId
1205
+ );
1206
+ }
1207
+ return attachRequestId(
1208
+ createNetworkError(
1209
+ parsed.errorMessage,
1210
+ status,
1211
+ errorDetails,
1212
+ parsed.userMessage,
1213
+ suggestion
1214
+ ),
1215
+ requestId
1216
+ );
1217
+ }
1218
+ async function httpFetch(url, options) {
1219
+ const {
1220
+ apiUrl,
1221
+ publishableKey,
1222
+ secretKey,
1223
+ customerToken,
1224
+ timeout = DEFAULT_TIMEOUT,
1225
+ debug,
1226
+ retry,
1227
+ onUnauthorized,
1228
+ ...requestInit
1229
+ } = options || {};
1230
+ const baseUrl = resolveApiUrl(apiUrl);
1231
+ const retryConfig = {
1232
+ maxRetries: retry?.maxRetries ?? 3,
1233
+ retryableStatuses: retry?.retryableStatuses ?? DEFAULT_RETRYABLE_STATUSES,
1234
+ retryDelay: retry?.retryDelay ?? ((attempt) => Math.min(1e3 * 2 ** attempt, 1e4))
1235
+ };
1236
+ let authToken;
1237
+ if (secretKey) {
1238
+ authToken = secretKey;
1239
+ } else if (customerToken) {
1240
+ authToken = customerToken;
1241
+ }
1242
+ let lastError;
1243
+ let hasRetried401 = false;
1244
+ for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
1245
+ try {
1246
+ const headers = new Headers(requestInit.headers);
1247
+ if (publishableKey) {
1248
+ headers.set("X-Publishable-Key", publishableKey);
1249
+ }
1250
+ if (authToken) {
1251
+ headers.set("Authorization", `Bearer ${authToken}`);
1252
+ }
1253
+ if (!headers.has("Content-Type") && requestInit.body && !(requestInit.body instanceof FormData)) {
1254
+ headers.set("Content-Type", "application/json");
1255
+ }
1256
+ const redactedHeaders = Object.fromEntries(headers.entries());
1257
+ if (redactedHeaders["authorization"]) {
1258
+ const token = redactedHeaders["authorization"];
1259
+ redactedHeaders["authorization"] = token.length > 20 ? `Bearer ...****${token.slice(-8)}` : "****";
1260
+ }
1261
+ debugLog(debug, "request", url, {
1262
+ method: requestInit.method || "GET",
1263
+ headers: redactedHeaders,
1264
+ attempt: attempt + 1
1265
+ });
1266
+ const controller = new AbortController();
1267
+ const timeoutId = setTimeout(() => controller.abort(), timeout);
1268
+ const response = await fetch(`${baseUrl}${url}`, {
1269
+ ...requestInit,
1270
+ headers,
1271
+ signal: controller.signal
1272
+ });
1273
+ clearTimeout(timeoutId);
1274
+ const requestId = response.headers.get("x-request-id") ?? void 0;
1275
+ debugLog(debug, "response", url, {
1276
+ status: response.status,
1277
+ statusText: response.statusText,
1278
+ headers: Object.fromEntries(response.headers.entries())
1279
+ });
1280
+ if (!response.ok) {
1281
+ if (isUsageLimitExceededResponse(response)) {
1282
+ const limit = parseInt(
1283
+ response.headers.get("X-Usage-Limit") || "0",
1284
+ 10
1285
+ );
1286
+ const current = parseInt(
1287
+ response.headers.get("X-Usage-Current") || "0",
1288
+ 10
1289
+ );
1290
+ const remaining = parseInt(
1291
+ response.headers.get("X-Usage-Remaining") || "0",
1292
+ 10
1293
+ );
1294
+ throw attachRequestId(
1295
+ createUsageLimitError(
1296
+ `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
1297
+ { limit, current, remaining },
1298
+ {
1299
+ url,
1300
+ method: requestInit.method || "GET",
1301
+ attempt: attempt + 1
1302
+ },
1303
+ "Monthly API call limit exceeded. Please upgrade your plan.",
1304
+ "Upgrade your tenant plan to increase the monthly API call limit."
1305
+ ),
1306
+ requestId
1307
+ );
1308
+ }
1309
+ const parsed = await parseErrorBody(response);
1310
+ if (response.status === 401 && onUnauthorized && customerToken && !hasRetried401 && parsed.reason === "token_expired") {
1311
+ hasRetried401 = true;
1312
+ try {
1313
+ const newToken = await onUnauthorized();
1314
+ if (newToken) {
1315
+ authToken = newToken;
1316
+ continue;
1317
+ }
1318
+ } catch {
1319
+ }
1320
+ }
1321
+ const details = {
1322
+ url,
1323
+ method: requestInit.method || "GET",
1324
+ attempt: attempt + 1
1325
+ };
1326
+ if (NON_RETRYABLE_STATUSES.includes(response.status)) {
1327
+ throw createHttpStatusError(
1328
+ response.status,
1329
+ parsed,
1330
+ details,
1331
+ requestId
1332
+ );
1333
+ }
1334
+ const error = attachRequestId(
1335
+ createNetworkError(
1336
+ parsed.errorMessage,
1337
+ response.status,
1338
+ details,
1339
+ parsed.userMessage,
1340
+ getErrorSuggestion(response.status)
1341
+ ),
1342
+ requestId
1343
+ );
1344
+ const method = (requestInit.method || "GET").toUpperCase();
1345
+ if (attempt < retryConfig.maxRetries && SAFE_METHODS.includes(method) && retryConfig.retryableStatuses.includes(response.status)) {
1346
+ lastError = error;
1347
+ const retryDelay = retryConfig.retryDelay(attempt);
1348
+ debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
1349
+ await delay(retryDelay);
1350
+ continue;
1351
+ }
1352
+ throw error;
1353
+ }
1354
+ return response;
1355
+ } catch (error) {
1356
+ debugLog(debug, "error", url, error);
1357
+ const method = (requestInit.method || "GET").toUpperCase();
1358
+ const isSafe = SAFE_METHODS.includes(method);
1359
+ if (error instanceof Error && error.name === "AbortError") {
1360
+ const timeoutError = createTimeoutError(
1361
+ `Request timed out after ${timeout}ms.`,
1362
+ { url, timeout, attempt: attempt + 1 },
1363
+ "The request timed out.",
1364
+ "Please check your network connection or try again later."
1365
+ );
1366
+ if (isSafe && attempt < retryConfig.maxRetries) {
1367
+ lastError = timeoutError;
1368
+ await delay(retryConfig.retryDelay(attempt));
1369
+ continue;
1370
+ }
1371
+ throw timeoutError;
1372
+ }
1373
+ if (error instanceof TypeError) {
1374
+ const networkError = createNetworkError(
1375
+ "Network connection failed.",
1376
+ void 0,
1377
+ { url, originalError: error.message, attempt: attempt + 1 },
1378
+ "Network connection failed.",
1379
+ "Please check your internet connection and try again."
1380
+ );
1381
+ if (isSafe && attempt < retryConfig.maxRetries) {
1382
+ lastError = networkError;
1383
+ await delay(retryConfig.retryDelay(attempt));
1384
+ continue;
1385
+ }
1386
+ throw networkError;
1387
+ }
1388
+ if (error instanceof NetworkError || error instanceof TimeoutError) {
1389
+ if (isSafe && attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
1390
+ lastError = error;
1391
+ await delay(retryConfig.retryDelay(attempt));
1392
+ continue;
1393
+ }
1394
+ throw error;
1395
+ }
1396
+ if (error instanceof SDKError) {
1397
+ throw error;
1398
+ }
1399
+ const unknownError = createNetworkError(
1400
+ error instanceof Error ? error.message : "An unknown network error occurred.",
1401
+ void 0,
1402
+ { url, originalError: error, attempt: attempt + 1 },
1403
+ "An unknown error occurred.",
1404
+ "Please try again later."
1405
+ );
1406
+ if (isSafe && attempt < retryConfig.maxRetries) {
1407
+ lastError = unknownError;
1408
+ await delay(retryConfig.retryDelay(attempt));
1409
+ continue;
1410
+ }
1411
+ throw unknownError;
1412
+ }
1413
+ }
1414
+ throw lastError ?? new NetworkError("Request failed after retries");
1415
+ }
1416
+
1417
+ // src/core/collection/http-client.ts
1418
+ var HttpClient = class {
1419
+ constructor(publishableKey, secretKey, getCustomerToken, onUnauthorized, onRequestId, apiUrl) {
1420
+ this.publishableKey = requirePublishableKeyForSecret(
1421
+ "CollectionClient",
1422
+ publishableKey,
1423
+ secretKey
1424
+ );
1425
+ this.secretKey = secretKey;
1426
+ this.getCustomerToken = getCustomerToken;
1427
+ this.onUnauthorized = onUnauthorized;
1428
+ this.onRequestId = onRequestId;
1429
+ this.apiUrl = apiUrl;
1430
+ }
1431
+ get defaultOptions() {
1432
+ const opts = {
1433
+ apiUrl: this.apiUrl,
1434
+ publishableKey: this.publishableKey,
1435
+ secretKey: this.secretKey
1436
+ };
1437
+ const token = this.getCustomerToken?.();
1438
+ if (token) {
1439
+ opts.customerToken = token;
1440
+ if (this.onUnauthorized) {
1441
+ opts.onUnauthorized = this.onUnauthorized;
1442
+ }
1443
+ }
1444
+ return opts;
1445
+ }
1446
+ async fetchWithTracking(url, opts) {
1447
+ try {
1448
+ const response = await httpFetch(url, opts);
1449
+ this.onRequestId?.(response.headers.get("x-request-id") ?? null);
1450
+ return response;
1451
+ } catch (err) {
1452
+ const id = err instanceof SDKError ? err.requestId ?? null : null;
1453
+ this.onRequestId?.(id);
1454
+ throw err;
1455
+ }
1456
+ }
1457
+ buildUrl(endpoint, options) {
1458
+ if (!options) return endpoint;
1459
+ const queryString = stringify(options, { addQueryPrefix: true });
1460
+ return queryString ? `${endpoint}${queryString}` : endpoint;
1461
+ }
1462
+ assertJsonResponse(response) {
1463
+ const contentType = response.headers.get("content-type");
1464
+ if (!contentType?.includes("application/json")) {
1465
+ throw createApiError("Response is not in JSON format.", response.status, {
1466
+ contentType
1467
+ });
1468
+ }
1469
+ }
1470
+ /**
1471
+ * Parse Payload CMS find response (list query)
1472
+ * Returns native Payload response structure
1473
+ */
1474
+ async parseFindResponse(response) {
1475
+ const contentType = response.headers.get("content-type");
1476
+ try {
1477
+ this.assertJsonResponse(response);
1478
+ const jsonData = await response.json();
1479
+ if (jsonData.docs === void 0) {
1480
+ throw createApiError("Invalid find response.", response.status, {
1481
+ jsonData
1482
+ });
1483
+ }
1484
+ return {
1485
+ docs: jsonData.docs,
1486
+ totalDocs: jsonData.totalDocs ?? 0,
1487
+ limit: jsonData.limit || 20,
1488
+ totalPages: jsonData.totalPages ?? 0,
1489
+ page: jsonData.page || 1,
1490
+ pagingCounter: jsonData.pagingCounter || 1,
1491
+ hasPrevPage: jsonData.hasPrevPage ?? false,
1492
+ hasNextPage: jsonData.hasNextPage ?? false,
1493
+ prevPage: jsonData.prevPage ?? null,
1494
+ nextPage: jsonData.nextPage ?? null
1495
+ };
1496
+ } catch (error) {
1497
+ if (error instanceof SDKError) throw error;
1498
+ throw createApiError("Failed to parse response.", response.status, {
1499
+ contentType,
1500
+ error: error instanceof Error ? error.message : error
1501
+ });
1502
+ }
1503
+ }
1504
+ /**
1505
+ * Parse Payload CMS mutation response (create/update)
1506
+ * Returns native Payload response structure
1507
+ */
1508
+ async parseMutationResponse(response) {
1509
+ const contentType = response.headers.get("content-type");
1510
+ try {
1511
+ this.assertJsonResponse(response);
1512
+ const jsonData = await response.json();
1513
+ if (jsonData.doc === void 0) {
1514
+ throw createApiError("Invalid mutation response.", response.status, {
1515
+ jsonData
1516
+ });
1517
+ }
1518
+ return {
1519
+ message: jsonData.message || "",
1520
+ doc: jsonData.doc,
1521
+ errors: jsonData.errors
1522
+ };
1523
+ } catch (error) {
1524
+ if (error instanceof SDKError) throw error;
1525
+ throw createApiError("Failed to parse response.", response.status, {
1526
+ contentType,
1527
+ error: error instanceof Error ? error.message : error
1528
+ });
1529
+ }
1530
+ }
1531
+ /**
1532
+ * Parse Payload CMS document response (findById/delete)
1533
+ * Returns document directly without wrapper
1534
+ */
1535
+ async parseDocumentResponse(response) {
1536
+ const contentType = response.headers.get("content-type");
1537
+ try {
1538
+ this.assertJsonResponse(response);
1539
+ const jsonData = await response.json();
1540
+ return jsonData;
1541
+ } catch (error) {
1542
+ if (error instanceof SDKError) throw error;
1543
+ throw createApiError("Failed to parse response.", response.status, {
1544
+ contentType,
1545
+ error: error instanceof Error ? error.message : error
1546
+ });
1547
+ }
1548
+ }
1549
+ };
1550
+
1551
+ // src/core/collection/collection-client.ts
1552
+ function buildPayloadFormData(data, file, filename) {
1553
+ const formData = new FormData();
1554
+ formData.append("file", file, filename);
1555
+ if (data != null) {
1556
+ formData.append("_payload", JSON.stringify(data));
1557
+ }
1558
+ return formData;
1559
+ }
1560
+ var CollectionClient = class extends HttpClient {
1561
+ from(collection) {
1562
+ return new CollectionQueryBuilder(this, collection);
1563
+ }
1564
+ // ============================================================================
1565
+ // Payload-native methods
1566
+ // ============================================================================
1567
+ /**
1568
+ * Find documents (list query)
1569
+ * GET /api/{collection}
1570
+ */
1571
+ async requestFind(endpoint, options) {
1572
+ const url = this.buildUrl(endpoint, options);
1573
+ const response = await this.fetchWithTracking(url, {
1574
+ ...this.defaultOptions,
1575
+ method: "GET"
1576
+ });
1577
+ return this.parseFindResponse(response);
1578
+ }
1579
+ /**
1580
+ * Find-like response from a custom endpoint
1581
+ * POST /api/...custom-endpoint
1582
+ */
1583
+ async requestFindEndpoint(endpoint, data) {
1584
+ const response = await this.fetchWithTracking(endpoint, {
1585
+ ...this.defaultOptions,
1586
+ method: "POST",
1587
+ body: data ? JSON.stringify(data) : void 0
1588
+ });
1589
+ return this.parseFindResponse(response);
1590
+ }
1591
+ /**
1592
+ * Find document by ID
1593
+ * GET /api/{collection}/{id}
1594
+ */
1595
+ async requestFindById(endpoint, options) {
1596
+ const url = this.buildUrl(endpoint, options);
1597
+ const response = await this.fetchWithTracking(url, {
1598
+ ...this.defaultOptions,
1599
+ method: "GET"
1600
+ });
1601
+ return this.parseDocumentResponse(response);
1602
+ }
1603
+ /**
1604
+ * Create document
1605
+ * POST /api/{collection}
1606
+ */
1607
+ async requestCreate(endpoint, data) {
1608
+ const response = await this.fetchWithTracking(endpoint, {
1609
+ ...this.defaultOptions,
1610
+ method: "POST",
1611
+ body: data ? JSON.stringify(data) : void 0
1612
+ });
1613
+ return this.parseMutationResponse(response);
1614
+ }
1615
+ /**
1616
+ * Update document
1617
+ * PATCH /api/{collection}/{id}
1618
+ */
1619
+ async requestUpdate(endpoint, data) {
1620
+ const response = await this.fetchWithTracking(endpoint, {
1621
+ ...this.defaultOptions,
1622
+ method: "PATCH",
1623
+ body: data ? JSON.stringify(data) : void 0
1624
+ });
1625
+ return this.parseMutationResponse(response);
1626
+ }
1627
+ /**
1628
+ * Count documents
1629
+ * GET /api/{collection}/count
1630
+ */
1631
+ async requestCount(endpoint, options) {
1632
+ const url = this.buildUrl(endpoint, options);
1633
+ const response = await this.fetchWithTracking(url, {
1634
+ ...this.defaultOptions,
1635
+ method: "GET"
1636
+ });
1637
+ return this.parseDocumentResponse(response);
1638
+ }
1639
+ /**
1640
+ * Update multiple documents (bulk update)
1641
+ * PATCH /api/{collection}
1642
+ */
1643
+ async requestUpdateMany(endpoint, data) {
1644
+ const response = await this.fetchWithTracking(endpoint, {
1645
+ ...this.defaultOptions,
1646
+ method: "PATCH",
1647
+ body: JSON.stringify(data)
1648
+ });
1649
+ return this.parseFindResponse(response);
1650
+ }
1651
+ /**
1652
+ * Delete document
1653
+ * DELETE /api/{collection}/{id}
1654
+ */
1655
+ async requestDelete(endpoint) {
1656
+ const response = await this.fetchWithTracking(endpoint, {
1657
+ ...this.defaultOptions,
1658
+ method: "DELETE"
1659
+ });
1660
+ return this.parseDocumentResponse(response);
1661
+ }
1662
+ /**
1663
+ * Delete multiple documents (bulk delete)
1664
+ * DELETE /api/{collection}
1665
+ */
1666
+ async requestDeleteMany(endpoint, data) {
1667
+ const response = await this.fetchWithTracking(endpoint, {
1668
+ ...this.defaultOptions,
1669
+ method: "DELETE",
1670
+ body: JSON.stringify(data)
1671
+ });
1672
+ return this.parseFindResponse(response);
1673
+ }
1674
+ /**
1675
+ * Create document with file upload
1676
+ * POST /api/{collection} (multipart/form-data)
1677
+ */
1678
+ async requestCreateWithFile(endpoint, data, file, filename) {
1679
+ const response = await this.fetchWithTracking(endpoint, {
1680
+ ...this.defaultOptions,
1681
+ method: "POST",
1682
+ body: buildPayloadFormData(data, file, filename)
1683
+ });
1684
+ return this.parseMutationResponse(response);
1685
+ }
1686
+ /**
1687
+ * Update document with file upload
1688
+ * PATCH /api/{collection}/{id} (multipart/form-data)
1689
+ */
1690
+ async requestUpdateWithFile(endpoint, data, file, filename) {
1691
+ const response = await this.fetchWithTracking(endpoint, {
1692
+ ...this.defaultOptions,
1693
+ method: "PATCH",
1694
+ body: buildPayloadFormData(data, file, filename)
1695
+ });
1696
+ return this.parseMutationResponse(response);
1697
+ }
1698
+ };
1699
+
1700
+ // src/core/query/query-client.ts
1701
+ function createReadOnlyQueryHooksFacade(hooks) {
1702
+ return {
1703
+ useQuery: hooks.useQuery.bind(hooks),
1704
+ useSuspenseQuery: hooks.useSuspenseQuery.bind(hooks),
1705
+ useQueryById: hooks.useQueryById.bind(hooks),
1706
+ useSuspenseQueryById: hooks.useSuspenseQueryById.bind(hooks),
1707
+ useInfiniteQuery: hooks.useInfiniteQuery.bind(hooks),
1708
+ useSuspenseInfiniteQuery: hooks.useSuspenseInfiniteQuery.bind(hooks),
1709
+ prefetchQuery: hooks.prefetchQuery.bind(hooks),
1710
+ prefetchQueryById: hooks.prefetchQueryById.bind(hooks),
1711
+ prefetchInfiniteQuery: hooks.prefetchInfiniteQuery.bind(hooks),
1712
+ invalidateQueries: hooks.invalidateQueries.bind(hooks),
1713
+ getQueryData: hooks.getQueryData.bind(hooks),
1714
+ setQueryData: hooks.setQueryData.bind(hooks),
1715
+ useCustomerMe: hooks.useCustomerMe.bind(hooks),
1716
+ useCustomerLogin: hooks.useCustomerLogin.bind(hooks),
1717
+ useCustomerRegister: hooks.useCustomerRegister.bind(hooks),
1718
+ useCustomerLogout: hooks.useCustomerLogout.bind(hooks),
1719
+ useCustomerForgotPassword: hooks.useCustomerForgotPassword.bind(hooks),
1720
+ useCustomerResetPassword: hooks.useCustomerResetPassword.bind(hooks),
1721
+ useCustomerRefreshToken: hooks.useCustomerRefreshToken.bind(hooks),
1722
+ useCustomerUpdateProfile: hooks.useCustomerUpdateProfile.bind(hooks),
1723
+ useCustomerChangePassword: hooks.useCustomerChangePassword.bind(hooks),
1724
+ invalidateCustomerQueries: hooks.invalidateCustomerQueries.bind(hooks),
1725
+ getCustomerData: hooks.getCustomerData.bind(hooks),
1726
+ setCustomerData: hooks.setCustomerData.bind(hooks),
1727
+ useProductListingGroupsQuery: hooks.useProductListingGroupsQuery.bind(hooks),
1728
+ useSuspenseProductListingGroupsQuery: hooks.useSuspenseProductListingGroupsQuery.bind(hooks),
1729
+ useInfiniteProductListingGroupsQuery: hooks.useInfiniteProductListingGroupsQuery.bind(hooks),
1730
+ useSuspenseInfiniteProductListingGroupsQuery: hooks.useSuspenseInfiniteProductListingGroupsQuery.bind(hooks),
1731
+ prefetchProductListingGroupsQuery: hooks.prefetchProductListingGroupsQuery.bind(hooks),
1732
+ prefetchInfiniteProductListingGroupsQuery: hooks.prefetchInfiniteProductListingGroupsQuery.bind(hooks),
1733
+ useProductDetail: hooks.useProductDetail.bind(hooks),
1734
+ useProductDetailBySlug: hooks.useProductDetailBySlug.bind(hooks),
1735
+ useProductDetailById: hooks.useProductDetailById.bind(hooks)
1736
+ };
1737
+ }
1738
+ function createQueryHooks(client, queryClient = getQueryClient()) {
1739
+ const config = client.getConfig();
1740
+ const onUnauthorized = async () => {
1741
+ try {
1742
+ const result = await client.customer.auth.refreshToken();
1743
+ return result.token ?? null;
1744
+ } catch {
1745
+ return null;
1746
+ }
1747
+ };
1748
+ const collectionClient = new CollectionClient(
1749
+ config.publishableKey,
1750
+ void 0,
1751
+ () => client.customer.auth.getToken(),
1752
+ onUnauthorized,
1753
+ (id) => {
1754
+ client.lastRequestId = id;
1755
+ },
1756
+ config.apiUrl
1757
+ );
1758
+ const hooks = new QueryHooks(
1759
+ queryClient,
1760
+ collectionClient,
1761
+ client.customer.auth,
1762
+ client.commerce
1763
+ );
1764
+ return createReadOnlyQueryHooksFacade(hooks);
1765
+ }
1766
+ function createServerQueryHooks(client, queryClient = getQueryClient()) {
1767
+ return new QueryHooks(
1768
+ queryClient,
1769
+ client.collections,
1770
+ void 0,
1771
+ client.commerce
1772
+ );
1773
+ }
1774
+ export {
1775
+ CollectionHooks,
1776
+ CustomerHooks,
1777
+ QueryHooks,
1778
+ RealtimeConnection,
1779
+ collectionKeys,
1780
+ createQueryHooks,
1781
+ createServerQueryHooks,
1782
+ customerKeys,
1783
+ getQueryClient,
1784
+ productKeys
1785
+ };
1786
+ //# sourceMappingURL=query.js.map