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