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