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