@01.software/sdk 0.1.0-dev.260210.4ecca43 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -162,7 +162,7 @@ var CollectionQueryBuilder = class {
162
162
  }
163
163
  };
164
164
 
165
- // src/core/collection/base.ts
165
+ // src/core/collection/http-client.ts
166
166
  import { stringify } from "qs-esm";
167
167
 
168
168
  // src/core/internal/errors/index.ts
@@ -219,11 +219,23 @@ var ConfigError = class extends SDKError {
219
219
  }
220
220
  };
221
221
  var TimeoutError = class extends SDKError {
222
- constructor(message = "\uC694\uCCAD\uC774 \uC2DC\uAC04 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.", details, userMessage, suggestion) {
222
+ constructor(message = "Request timed out.", details, userMessage, suggestion) {
223
223
  super("TIMEOUT_ERROR", message, 408, details, userMessage, suggestion);
224
224
  this.name = "TimeoutError";
225
225
  }
226
226
  };
227
+ var UsageLimitError = class extends SDKError {
228
+ constructor(message, usage, details, userMessage, suggestion) {
229
+ super("USAGE_LIMIT_ERROR", message, 429, details, userMessage, suggestion);
230
+ this.name = "UsageLimitError";
231
+ this.usage = usage;
232
+ }
233
+ toJSON() {
234
+ return __spreadProps(__spreadValues({}, super.toJSON()), {
235
+ usage: this.usage
236
+ });
237
+ }
238
+ };
227
239
  function isSDKError(error) {
228
240
  return error instanceof SDKError;
229
241
  }
@@ -242,15 +254,20 @@ function isConfigError(error) {
242
254
  function isTimeoutError(error) {
243
255
  return error instanceof TimeoutError;
244
256
  }
257
+ function isUsageLimitError(error) {
258
+ return error instanceof UsageLimitError;
259
+ }
245
260
  var createNetworkError = (message, status, details, userMessage, suggestion) => new NetworkError(message, status, details, userMessage, suggestion);
246
261
  var createValidationError = (message, details, userMessage, suggestion) => new ValidationError(message, details, userMessage, suggestion);
247
262
  var createApiError = (message, status, details, userMessage, suggestion) => new ApiError(message, status, details, userMessage, suggestion);
263
+ var createTimeoutError = (message, details, userMessage, suggestion) => new TimeoutError(message, details, userMessage, suggestion);
264
+ var createUsageLimitError = (message, usage, details, userMessage, suggestion) => new UsageLimitError(message, usage, details, userMessage, suggestion);
248
265
 
249
- // src/core/collection/base.ts
250
- var BaseApiClient = class {
266
+ // src/core/collection/http-client.ts
267
+ var HttpClient = class {
251
268
  constructor(clientKey, secretKey, baseUrl) {
252
269
  if (!clientKey) {
253
- throw createValidationError("clientKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
270
+ throw createValidationError("clientKey is required.");
254
271
  }
255
272
  this.clientKey = clientKey;
256
273
  this.secretKey = secretKey;
@@ -262,6 +279,12 @@ var BaseApiClient = class {
262
279
  const queryString = stringify(options, { addQueryPrefix: true });
263
280
  return queryString ? `${endpoint}${queryString}` : endpoint;
264
281
  }
282
+ assertJsonResponse(response) {
283
+ const contentType = response.headers.get("content-type");
284
+ if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
285
+ throw createApiError("Response is not in JSON format.", response.status, { contentType });
286
+ }
287
+ }
265
288
  /**
266
289
  * Parse Payload CMS find response (list query)
267
290
  * Returns native Payload response structure
@@ -271,12 +294,10 @@ var BaseApiClient = class {
271
294
  var _a, _b;
272
295
  const contentType = response.headers.get("content-type");
273
296
  try {
274
- if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
275
- throw createApiError("\uC751\uB2F5\uC774 JSON \uD615\uC2DD\uC774 \uC544\uB2D9\uB2C8\uB2E4.", response.status, { contentType });
276
- }
297
+ this.assertJsonResponse(response);
277
298
  const jsonData = yield response.json();
278
299
  if (jsonData.docs === void 0) {
279
- throw createApiError("\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 find \uC751\uB2F5\uC785\uB2C8\uB2E4.", response.status, { jsonData });
300
+ throw createApiError("Invalid find response.", response.status, { jsonData });
280
301
  }
281
302
  return {
282
303
  docs: jsonData.docs,
@@ -291,7 +312,7 @@ var BaseApiClient = class {
291
312
  nextPage: (_b = jsonData.nextPage) != null ? _b : null
292
313
  };
293
314
  } catch (error) {
294
- throw createApiError("\uC751\uB2F5 \uD30C\uC2F1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", response.status, {
315
+ throw createApiError("Failed to parse response.", response.status, {
295
316
  contentType,
296
317
  error: error instanceof Error ? error.message : error
297
318
  });
@@ -306,12 +327,10 @@ var BaseApiClient = class {
306
327
  return __async(this, null, function* () {
307
328
  const contentType = response.headers.get("content-type");
308
329
  try {
309
- if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
310
- throw createApiError("\uC751\uB2F5\uC774 JSON \uD615\uC2DD\uC774 \uC544\uB2D9\uB2C8\uB2E4.", response.status, { contentType });
311
- }
330
+ this.assertJsonResponse(response);
312
331
  const jsonData = yield response.json();
313
332
  if (jsonData.doc === void 0) {
314
- throw createApiError("\uC720\uD6A8\uD558\uC9C0 \uC54A\uC740 mutation \uC751\uB2F5\uC785\uB2C8\uB2E4.", response.status, { jsonData });
333
+ throw createApiError("Invalid mutation response.", response.status, { jsonData });
315
334
  }
316
335
  return {
317
336
  message: jsonData.message || "",
@@ -319,7 +338,7 @@ var BaseApiClient = class {
319
338
  errors: jsonData.errors
320
339
  };
321
340
  } catch (error) {
322
- throw createApiError("\uC751\uB2F5 \uD30C\uC2F1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", response.status, {
341
+ throw createApiError("Failed to parse response.", response.status, {
323
342
  contentType,
324
343
  error: error instanceof Error ? error.message : error
325
344
  });
@@ -334,13 +353,11 @@ var BaseApiClient = class {
334
353
  return __async(this, null, function* () {
335
354
  const contentType = response.headers.get("content-type");
336
355
  try {
337
- if (!(contentType == null ? void 0 : contentType.includes("application/json"))) {
338
- throw createApiError("\uC751\uB2F5\uC774 JSON \uD615\uC2DD\uC774 \uC544\uB2D9\uB2C8\uB2E4.", response.status, { contentType });
339
- }
356
+ this.assertJsonResponse(response);
340
357
  const jsonData = yield response.json();
341
358
  return jsonData;
342
359
  } catch (error) {
343
- throw createApiError("\uC751\uB2F5 \uD30C\uC2F1\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.", response.status, {
360
+ throw createApiError("Failed to parse response.", response.status, {
344
361
  contentType,
345
362
  error: error instanceof Error ? error.message : error
346
363
  });
@@ -376,10 +393,11 @@ function resolveApiUrl(config) {
376
393
  // src/core/internal/utils/index.ts
377
394
  var DEFAULT_TIMEOUT = 3e4;
378
395
  var DEFAULT_RETRYABLE_STATUSES = [408, 429, 500, 502, 503, 504];
396
+ var NON_RETRYABLE_STATUSES = [401, 403, 404, 422];
379
397
  function createServerToken(clientKey, secretKey, expiresIn = "1h") {
380
398
  return __async(this, null, function* () {
381
399
  if (!clientKey || !secretKey) {
382
- throw new Error("clientKey\uC640 secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
400
+ throw new Error("clientKey and secretKey are required.");
383
401
  }
384
402
  const secret = new TextEncoder().encode(secretKey);
385
403
  return new SignJWT({ clientKey }).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(expiresIn).sign(secret);
@@ -388,7 +406,7 @@ function createServerToken(clientKey, secretKey, expiresIn = "1h") {
388
406
  function verifyServerToken(token, secretKey) {
389
407
  return __async(this, null, function* () {
390
408
  if (!token || !secretKey) {
391
- throw new Error("token\uACFC secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
409
+ throw new Error("token and secretKey are required.");
392
410
  }
393
411
  const secret = new TextEncoder().encode(secretKey);
394
412
  const { payload } = yield jwtVerify(token, secret, {
@@ -406,7 +424,7 @@ function verifyServerToken(token, secretKey) {
406
424
  }
407
425
  function decodeServerToken(token) {
408
426
  if (!token) {
409
- throw new Error("token\uC740 \uD544\uC218\uC785\uB2C8\uB2E4.");
427
+ throw new Error("token is required.");
410
428
  }
411
429
  const payload = decodeJwt(token);
412
430
  if (!payload.clientKey || typeof payload.clientKey !== "string") {
@@ -420,7 +438,7 @@ function decodeServerToken(token) {
420
438
  }
421
439
  function createApiKey(clientKey, secretKey) {
422
440
  if (!clientKey || !secretKey) {
423
- throw new Error("clientKey\uC640 secretKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
441
+ throw new Error("clientKey and secretKey are required.");
424
442
  }
425
443
  if (typeof Buffer !== "undefined") {
426
444
  return Buffer.from(`${clientKey}:${secretKey}`).toString("base64");
@@ -429,7 +447,7 @@ function createApiKey(clientKey, secretKey) {
429
447
  }
430
448
  function parseApiKey(apiKey) {
431
449
  if (!apiKey) {
432
- throw new Error("apiKey\uB294 \uD544\uC218\uC785\uB2C8\uB2E4.");
450
+ throw new Error("apiKey is required.");
433
451
  }
434
452
  try {
435
453
  let decoded;
@@ -440,12 +458,12 @@ function parseApiKey(apiKey) {
440
458
  }
441
459
  const colonIndex = decoded.indexOf(":");
442
460
  if (colonIndex === -1) {
443
- throw new Error("Invalid format");
461
+ throw new Error("Invalid format: missing colon separator");
444
462
  }
445
463
  const clientKey = decoded.substring(0, colonIndex);
446
464
  const secretKey = decoded.substring(colonIndex + 1);
447
465
  if (!clientKey || !secretKey) {
448
- throw new Error("Invalid format");
466
+ throw new Error("Invalid format: empty clientKey or secretKey");
449
467
  }
450
468
  return { clientKey, secretKey };
451
469
  } catch (e) {
@@ -462,10 +480,10 @@ function debugLog(debug, type, message, data) {
462
480
  }
463
481
  }
464
482
  function getErrorSuggestion(status) {
465
- if (status === 401) return "\uC778\uC99D \uC815\uBCF4\uB97C \uD655\uC778\uD574\uC8FC\uC138\uC694.";
466
- if (status === 404) return "\uC694\uCCAD\uD55C \uB9AC\uC18C\uC2A4\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.";
483
+ if (status === 401) return "Please check your authentication credentials.";
484
+ if (status === 404) return "The requested resource was not found.";
467
485
  if (status >= 500)
468
- return "\uC11C\uBC84 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4. \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694.";
486
+ return "A server error occurred. Please try again later.";
469
487
  return void 0;
470
488
  }
471
489
  function delay(ms) {
@@ -496,6 +514,10 @@ function _fetch(url, options) {
496
514
  retryableStatuses: (_c = retry == null ? void 0 : retry.retryableStatuses) != null ? _c : DEFAULT_RETRYABLE_STATUSES,
497
515
  retryDelay: (_d = retry == null ? void 0 : retry.retryDelay) != null ? _d : ((attempt) => Math.min(1e3 * __pow(2, attempt), 1e4))
498
516
  };
517
+ let authToken;
518
+ if (secretKey && clientKey) {
519
+ authToken = yield createServerToken(clientKey, secretKey);
520
+ }
499
521
  let lastError;
500
522
  for (let attempt = 0; attempt <= retryConfig.maxRetries; attempt++) {
501
523
  try {
@@ -503,9 +525,8 @@ function _fetch(url, options) {
503
525
  if (clientKey) {
504
526
  headers.set("X-Client-Key", clientKey);
505
527
  }
506
- if (secretKey && clientKey) {
507
- const token = yield createServerToken(clientKey, secretKey);
508
- headers.set("Authorization", `Bearer ${token}`);
528
+ if (authToken) {
529
+ headers.set("Authorization", `Bearer ${authToken}`);
509
530
  }
510
531
  if (!headers.has("Content-Type") && requestInit.body) {
511
532
  headers.set("Content-Type", "application/json");
@@ -528,17 +549,38 @@ function _fetch(url, options) {
528
549
  headers: Object.fromEntries(response.headers.entries())
529
550
  });
530
551
  if (!response.ok) {
552
+ if (response.status === 429 && response.headers.get("X-Usage-Limit")) {
553
+ const limit = parseInt(response.headers.get("X-Usage-Limit") || "0", 10);
554
+ const current = parseInt(response.headers.get("X-Usage-Current") || "0", 10);
555
+ const remaining = parseInt(response.headers.get("X-Usage-Remaining") || "0", 10);
556
+ throw createUsageLimitError(
557
+ `Monthly API usage limit exceeded (${current.toLocaleString()}/${limit.toLocaleString()})`,
558
+ { limit, current, remaining },
559
+ { url, method: requestInit.method || "GET", attempt: attempt + 1 },
560
+ "Monthly API call limit exceeded. Please upgrade your plan.",
561
+ "Upgrade your tenant plan to increase the monthly API call limit."
562
+ );
563
+ }
564
+ if (NON_RETRYABLE_STATUSES.includes(response.status)) {
565
+ throw createNetworkError(
566
+ `HTTP ${response.status}: ${response.statusText}`,
567
+ response.status,
568
+ { url, method: requestInit.method || "GET", attempt: attempt + 1 },
569
+ `Request failed (status: ${response.status})`,
570
+ getErrorSuggestion(response.status)
571
+ );
572
+ }
531
573
  const error = createNetworkError(
532
574
  `HTTP ${response.status}: ${response.statusText}`,
533
575
  response.status,
534
576
  { url, method: requestInit.method || "GET", attempt: attempt + 1 },
535
- `\uC694\uCCAD\uC774 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4 (\uC0C1\uD0DC \uCF54\uB4DC: ${response.status})`,
577
+ `Request failed (status: ${response.status})`,
536
578
  getErrorSuggestion(response.status)
537
579
  );
538
580
  if (attempt < retryConfig.maxRetries && retryConfig.retryableStatuses.includes(response.status)) {
539
581
  lastError = error;
540
582
  const retryDelay = retryConfig.retryDelay(attempt);
541
- debugLog(debug, "error", `\uC7AC\uC2DC\uB3C4 \uB300\uAE30 \uC911... (${retryDelay}ms)`, error);
583
+ debugLog(debug, "error", `Retrying in ${retryDelay}ms...`, error);
542
584
  yield delay(retryDelay);
543
585
  continue;
544
586
  }
@@ -548,11 +590,11 @@ function _fetch(url, options) {
548
590
  } catch (error) {
549
591
  debugLog(debug, "error", url, error);
550
592
  if (error instanceof Error && error.name === "AbortError") {
551
- const timeoutError = new TimeoutError(
552
- `\uC694\uCCAD\uC774 ${timeout}ms \uD6C4 \uD0C0\uC784\uC544\uC6C3\uB418\uC5C8\uC2B5\uB2C8\uB2E4.`,
593
+ const timeoutError = createTimeoutError(
594
+ `Request timed out after ${timeout}ms.`,
553
595
  { url, timeout, attempt: attempt + 1 },
554
- "\uC694\uCCAD \uC2DC\uAC04\uC774 \uCD08\uACFC\uB418\uC5C8\uC2B5\uB2C8\uB2E4.",
555
- "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uAC70\uB098 \uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
596
+ "The request timed out.",
597
+ "Please check your network connection or try again later."
556
598
  );
557
599
  if (attempt < retryConfig.maxRetries) {
558
600
  lastError = timeoutError;
@@ -563,11 +605,11 @@ function _fetch(url, options) {
563
605
  }
564
606
  if (error instanceof TypeError) {
565
607
  const networkError = createNetworkError(
566
- "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
608
+ "Network connection failed.",
567
609
  void 0,
568
610
  { url, originalError: error.message, attempt: attempt + 1 },
569
- "\uB124\uD2B8\uC6CC\uD06C \uC5F0\uACB0\uC5D0 \uC2E4\uD328\uD588\uC2B5\uB2C8\uB2E4.",
570
- "\uC778\uD130\uB137 \uC5F0\uACB0\uC744 \uD655\uC778\uD558\uACE0 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
611
+ "Network connection failed.",
612
+ "Please check your internet connection and try again."
571
613
  );
572
614
  if (attempt < retryConfig.maxRetries) {
573
615
  lastError = networkError;
@@ -577,7 +619,7 @@ function _fetch(url, options) {
577
619
  throw networkError;
578
620
  }
579
621
  if (error instanceof NetworkError || error instanceof TimeoutError) {
580
- if (attempt < retryConfig.maxRetries && error.status && retryConfig.retryableStatuses.includes(error.status)) {
622
+ if (attempt < retryConfig.maxRetries && error.status && !NON_RETRYABLE_STATUSES.includes(error.status) && retryConfig.retryableStatuses.includes(error.status)) {
581
623
  lastError = error;
582
624
  yield delay(retryConfig.retryDelay(attempt));
583
625
  continue;
@@ -585,11 +627,11 @@ function _fetch(url, options) {
585
627
  throw error;
586
628
  }
587
629
  const unknownError = createNetworkError(
588
- error instanceof Error ? error.message : "\uC54C \uC218 \uC5C6\uB294 \uB124\uD2B8\uC6CC\uD06C \uC5D0\uB7EC\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.",
630
+ error instanceof Error ? error.message : "An unknown network error occurred.",
589
631
  void 0,
590
632
  { url, originalError: error, attempt: attempt + 1 },
591
- "\uC54C \uC218 \uC5C6\uB294 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4.",
592
- "\uC7A0\uC2DC \uD6C4 \uB2E4\uC2DC \uC2DC\uB3C4\uD574\uC8FC\uC138\uC694."
633
+ "An unknown error occurred.",
634
+ "Please try again later."
593
635
  );
594
636
  if (attempt < retryConfig.maxRetries) {
595
637
  lastError = unknownError;
@@ -603,8 +645,8 @@ function _fetch(url, options) {
603
645
  });
604
646
  }
605
647
 
606
- // src/core/collection/collections-api.ts
607
- var CollectionsApi = class extends BaseApiClient {
648
+ // src/core/collection/collection-client.ts
649
+ var CollectionClient = class extends HttpClient {
608
650
  constructor(clientKey, secretKey, baseUrl) {
609
651
  super(clientKey, secretKey, baseUrl);
610
652
  }
@@ -612,7 +654,7 @@ var CollectionsApi = class extends BaseApiClient {
612
654
  return new CollectionQueryBuilder(this, collection);
613
655
  }
614
656
  // ============================================================================
615
- // New Payload-native methods
657
+ // Payload-native methods
616
658
  // ============================================================================
617
659
  /**
618
660
  * Find documents (list query)
@@ -776,12 +818,13 @@ function getQueryClient() {
776
818
  return browserQueryClient;
777
819
  }
778
820
 
779
- // src/core/query/UnifiedQuery.ts
821
+ // src/core/query/query-hooks.ts
780
822
  import {
781
823
  useQuery as useQueryOriginal,
782
824
  useSuspenseQuery as useSuspenseQueryOriginal,
783
825
  useInfiniteQuery as useInfiniteQueryOriginal,
784
- useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal
826
+ useSuspenseInfiniteQuery as useSuspenseInfiniteQueryOriginal,
827
+ useMutation as useMutationOriginal
785
828
  } from "@tanstack/react-query";
786
829
  function collectionKeys(collection) {
787
830
  return {
@@ -795,10 +838,10 @@ function collectionKeys(collection) {
795
838
  };
796
839
  }
797
840
  var DEFAULT_PAGE_SIZE = 20;
798
- var UnifiedQueryClient = class {
799
- constructor(queryClient, options) {
841
+ var QueryHooks = class {
842
+ constructor(queryClient, collectionClient) {
800
843
  this.queryClient = queryClient;
801
- this.collectionsApi = new CollectionsApi((options == null ? void 0 : options.clientKey) || "", void 0, options == null ? void 0 : options.baseUrl);
844
+ this.collectionClient = collectionClient;
802
845
  }
803
846
  // ===== useQuery =====
804
847
  useQuery(params, options) {
@@ -807,7 +850,7 @@ var UnifiedQueryClient = class {
807
850
  queryKey: collectionKeys(collection).list(queryOptions),
808
851
  queryFn: () => __async(this, null, function* () {
809
852
  var _a;
810
- const response = yield this.collectionsApi.from(collection).find(queryOptions);
853
+ const response = yield this.collectionClient.from(collection).find(queryOptions);
811
854
  return (_a = response.docs) != null ? _a : [];
812
855
  })
813
856
  }, options));
@@ -819,7 +862,7 @@ var UnifiedQueryClient = class {
819
862
  queryKey: collectionKeys(collection).list(queryOptions),
820
863
  queryFn: () => __async(this, null, function* () {
821
864
  var _a;
822
- const response = yield this.collectionsApi.from(collection).find(queryOptions);
865
+ const response = yield this.collectionClient.from(collection).find(queryOptions);
823
866
  return (_a = response.docs) != null ? _a : [];
824
867
  })
825
868
  }, options));
@@ -830,7 +873,7 @@ var UnifiedQueryClient = class {
830
873
  return useQueryOriginal(__spreadValues({
831
874
  queryKey: collectionKeys(collection).detail(id, queryOptions),
832
875
  queryFn: () => __async(this, null, function* () {
833
- return yield this.collectionsApi.from(collection).findById(id, queryOptions);
876
+ return yield this.collectionClient.from(collection).findById(id, queryOptions);
834
877
  })
835
878
  }, options));
836
879
  }
@@ -840,7 +883,7 @@ var UnifiedQueryClient = class {
840
883
  return useSuspenseQueryOriginal(__spreadValues({
841
884
  queryKey: collectionKeys(collection).detail(id, queryOptions),
842
885
  queryFn: () => __async(this, null, function* () {
843
- return yield this.collectionsApi.from(collection).findById(id, queryOptions);
886
+ return yield this.collectionClient.from(collection).findById(id, queryOptions);
844
887
  })
845
888
  }, options));
846
889
  }
@@ -850,7 +893,7 @@ var UnifiedQueryClient = class {
850
893
  return useInfiniteQueryOriginal(__spreadValues({
851
894
  queryKey: collectionKeys(collection).infinite(queryOptions),
852
895
  queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
853
- const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
896
+ const response = yield this.collectionClient.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
854
897
  return response;
855
898
  }),
856
899
  initialPageParam: 1,
@@ -865,7 +908,7 @@ var UnifiedQueryClient = class {
865
908
  return useSuspenseInfiniteQueryOriginal(__spreadValues({
866
909
  queryKey: collectionKeys(collection).infinite(queryOptions),
867
910
  queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
868
- const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
911
+ const response = yield this.collectionClient.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
869
912
  return response;
870
913
  }),
871
914
  initialPageParam: 1,
@@ -882,7 +925,7 @@ var UnifiedQueryClient = class {
882
925
  queryKey: collectionKeys(collection).list(queryOptions),
883
926
  queryFn: () => __async(this, null, function* () {
884
927
  var _a;
885
- const response = yield this.collectionsApi.from(collection).find(queryOptions);
928
+ const response = yield this.collectionClient.from(collection).find(queryOptions);
886
929
  return (_a = response.docs) != null ? _a : [];
887
930
  })
888
931
  }, options));
@@ -895,7 +938,7 @@ var UnifiedQueryClient = class {
895
938
  return this.queryClient.prefetchQuery(__spreadValues({
896
939
  queryKey: collectionKeys(collection).detail(id, queryOptions),
897
940
  queryFn: () => __async(this, null, function* () {
898
- return yield this.collectionsApi.from(collection).findById(id, queryOptions);
941
+ return yield this.collectionClient.from(collection).findById(id, queryOptions);
899
942
  })
900
943
  }, options));
901
944
  });
@@ -908,7 +951,7 @@ var UnifiedQueryClient = class {
908
951
  return this.queryClient.prefetchInfiniteQuery({
909
952
  queryKey: collectionKeys(collection).infinite(queryOptions),
910
953
  queryFn: (_0) => __async(this, [_0], function* ({ pageParam }) {
911
- const response = yield this.collectionsApi.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
954
+ const response = yield this.collectionClient.from(collection).find(__spreadProps(__spreadValues({}, queryOptions), { page: pageParam, limit: pageSize }));
912
955
  return response;
913
956
  }),
914
957
  initialPageParam: 1,
@@ -920,6 +963,52 @@ var UnifiedQueryClient = class {
920
963
  });
921
964
  });
922
965
  }
966
+ // ===== Mutation Hooks =====
967
+ useCreate(params, options) {
968
+ const { collection } = params;
969
+ return useMutationOriginal({
970
+ mutationFn: (data) => __async(this, null, function* () {
971
+ return yield this.collectionClient.from(collection).create(data);
972
+ }),
973
+ onSuccess: (data) => {
974
+ var _a;
975
+ this.queryClient.invalidateQueries({ queryKey: collectionKeys(collection).lists() });
976
+ (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options, data);
977
+ },
978
+ onError: options == null ? void 0 : options.onError,
979
+ onSettled: options == null ? void 0 : options.onSettled
980
+ });
981
+ }
982
+ useUpdate(params, options) {
983
+ const { collection } = params;
984
+ return useMutationOriginal({
985
+ mutationFn: (variables) => __async(this, null, function* () {
986
+ return yield this.collectionClient.from(collection).update(variables.id, variables.data);
987
+ }),
988
+ onSuccess: (data) => {
989
+ var _a;
990
+ this.queryClient.invalidateQueries({ queryKey: collectionKeys(collection).all });
991
+ (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options, data);
992
+ },
993
+ onError: options == null ? void 0 : options.onError,
994
+ onSettled: options == null ? void 0 : options.onSettled
995
+ });
996
+ }
997
+ useRemove(params, options) {
998
+ const { collection } = params;
999
+ return useMutationOriginal({
1000
+ mutationFn: (id) => __async(this, null, function* () {
1001
+ return yield this.collectionClient.from(collection).remove(id);
1002
+ }),
1003
+ onSuccess: (data) => {
1004
+ var _a;
1005
+ this.queryClient.invalidateQueries({ queryKey: collectionKeys(collection).all });
1006
+ (_a = options == null ? void 0 : options.onSuccess) == null ? void 0 : _a.call(options, data);
1007
+ },
1008
+ onError: options == null ? void 0 : options.onError,
1009
+ onSettled: options == null ? void 0 : options.onSettled
1010
+ });
1011
+ }
923
1012
  // ===== Cache Utilities =====
924
1013
  invalidateQueries(collection, type) {
925
1014
  const queryKey = type ? [collection, type] : [collection];
@@ -961,11 +1050,8 @@ var BrowserClient = class {
961
1050
  };
962
1051
  this.state = { metadata };
963
1052
  this.queryClient = getQueryClient();
964
- this.query = new UnifiedQueryClient(this.queryClient, {
965
- clientKey: this.config.clientKey,
966
- baseUrl: this.baseUrl
967
- });
968
- this.collections = new CollectionsApi(this.config.clientKey, void 0, this.baseUrl);
1053
+ this.collections = new CollectionClient(this.config.clientKey, void 0, this.baseUrl);
1054
+ this.query = new QueryHooks(this.queryClient, this.collections);
969
1055
  }
970
1056
  from(collection) {
971
1057
  return this.collections.from(collection);
@@ -978,8 +1064,8 @@ function createBrowserClient(options) {
978
1064
  return new BrowserClient(options);
979
1065
  }
980
1066
 
981
- // src/core/api/api-client.ts
982
- var ApiClient = class {
1067
+ // src/core/api/order-api.ts
1068
+ var OrderApi = class {
983
1069
  constructor(options) {
984
1070
  if (!options.clientKey) {
985
1071
  throw new Error("clientKey is required.");
@@ -1007,7 +1093,7 @@ var ApiClient = class {
1007
1093
  response.status,
1008
1094
  data,
1009
1095
  data.error,
1010
- "\uC694\uCCAD \uCC98\uB9AC \uC911 \uC624\uB958\uAC00 \uBC1C\uC0DD\uD588\uC2B5\uB2C8\uB2E4."
1096
+ "An error occurred while processing the request."
1011
1097
  );
1012
1098
  }
1013
1099
  return data;
@@ -1041,16 +1127,18 @@ var ServerClient = class {
1041
1127
  userAgent: typeof window !== "undefined" ? (_a = window.navigator) == null ? void 0 : _a.userAgent : "Node.js"
1042
1128
  };
1043
1129
  this.state = { metadata };
1044
- this.api = new ApiClient({
1130
+ this.api = new OrderApi({
1045
1131
  clientKey: this.config.clientKey,
1046
1132
  secretKey: this.config.secretKey,
1047
1133
  baseUrl: this.baseUrl
1048
1134
  });
1049
- this.collections = new CollectionsApi(
1135
+ this.collections = new CollectionClient(
1050
1136
  this.config.clientKey,
1051
1137
  this.config.secretKey,
1052
1138
  this.baseUrl
1053
1139
  );
1140
+ this.queryClient = getQueryClient();
1141
+ this.query = new QueryHooks(this.queryClient, this.collections);
1054
1142
  }
1055
1143
  from(collection) {
1056
1144
  return this.collections.from(collection);
@@ -1073,10 +1161,36 @@ function isValidWebhookEvent(data) {
1073
1161
  const obj = data;
1074
1162
  return typeof obj.collection === "string" && (obj.operation === "create" || obj.operation === "update") && typeof obj.data === "object" && obj.data !== null;
1075
1163
  }
1076
- function handleWebhook(request, handler) {
1164
+ function verifySignature(payload, secret, signature) {
1165
+ return __async(this, null, function* () {
1166
+ const encoder = new TextEncoder();
1167
+ const key = yield crypto.subtle.importKey(
1168
+ "raw",
1169
+ encoder.encode(secret),
1170
+ { name: "HMAC", hash: "SHA-256" },
1171
+ false,
1172
+ ["sign"]
1173
+ );
1174
+ const sig = yield crypto.subtle.sign("HMAC", key, encoder.encode(payload));
1175
+ const expected = Array.from(new Uint8Array(sig)).map((b) => b.toString(16).padStart(2, "0")).join("");
1176
+ return expected === signature;
1177
+ });
1178
+ }
1179
+ function handleWebhook(request, handler, options) {
1077
1180
  return __async(this, null, function* () {
1078
1181
  try {
1079
- const body = yield request.json();
1182
+ const rawBody = yield request.text();
1183
+ if (options == null ? void 0 : options.secret) {
1184
+ const signature = request.headers.get("x-webhook-signature") || "";
1185
+ const valid = yield verifySignature(rawBody, options.secret, signature);
1186
+ if (!valid) {
1187
+ return new Response(
1188
+ JSON.stringify({ error: "Invalid webhook signature" }),
1189
+ { status: 401, headers: { "Content-Type": "application/json" } }
1190
+ );
1191
+ }
1192
+ }
1193
+ const body = JSON.parse(rawBody);
1080
1194
  if (!isValidWebhookEvent(body)) {
1081
1195
  return new Response(
1082
1196
  JSON.stringify({ error: "Invalid webhook event format" }),
@@ -1112,25 +1226,25 @@ function createTypedWebhookHandler(collection, handler) {
1112
1226
  // src/utils/order/generateOrderNumber.ts
1113
1227
  var generateOrderNumber = () => {
1114
1228
  const year = (/* @__PURE__ */ new Date()).getFullYear().toString().slice(-2);
1115
- const month = (/* @__PURE__ */ new Date()).getMonth().toString().padStart(2, "0");
1229
+ const month = ((/* @__PURE__ */ new Date()).getMonth() + 1).toString().padStart(2, "0");
1116
1230
  const day = (/* @__PURE__ */ new Date()).getDate().toString().padStart(2, "0");
1117
1231
  const random = Math.floor(Math.random() * 1e6).toString().padStart(6, "0");
1118
1232
  return `${year}${month}${day}${random}`;
1119
1233
  };
1120
1234
 
1121
1235
  // src/utils/types.ts
1122
- var objectFor = (data) => {
1123
- if (typeof data === "number") {
1124
- return null;
1125
- }
1126
- return data;
1236
+ var resolveRelation = (ref) => {
1237
+ if (typeof ref === "number" || ref === null || ref === void 0) return null;
1238
+ return ref;
1127
1239
  };
1240
+ var objectFor = resolveRelation;
1128
1241
 
1129
1242
  // src/utils/order/formatOrderName.ts
1130
1243
  var formatOrderName = (options) => {
1131
- var _a, _b, _c, _d;
1132
- const optionLength = options.length;
1133
- return optionLength === 1 ? ((_b = objectFor((_a = options == null ? void 0 : options[0]) == null ? void 0 : _a.product)) == null ? void 0 : _b.title) || "" : `${(_d = objectFor((_c = options.at(0)) == null ? void 0 : _c.product)) == null ? void 0 : _d.title} \uC678 ${optionLength - 1}\uAC74`;
1244
+ var _a, _b;
1245
+ if (options.length === 0) return "";
1246
+ const firstTitle = ((_b = resolveRelation((_a = options[0]) == null ? void 0 : _a.product)) == null ? void 0 : _b.title) || "";
1247
+ return options.length === 1 ? firstTitle : `${firstTitle} \uC678 ${options.length - 1}\uAC74`;
1134
1248
  };
1135
1249
 
1136
1250
  // src/components/RichTextContent/index.tsx
@@ -1160,18 +1274,19 @@ function RichTextContent({
1160
1274
  );
1161
1275
  }
1162
1276
  export {
1163
- ApiClient,
1164
1277
  ApiError,
1165
1278
  BrowserClient,
1166
1279
  COLLECTIONS,
1280
+ CollectionClient,
1167
1281
  CollectionQueryBuilder,
1168
- CollectionsApi,
1169
1282
  ConfigError,
1170
1283
  NetworkError,
1284
+ OrderApi,
1285
+ QueryHooks,
1171
1286
  RichTextContent,
1172
1287
  ServerClient,
1173
1288
  TimeoutError,
1174
- UnifiedQueryClient,
1289
+ UsageLimitError,
1175
1290
  ValidationError,
1176
1291
  collectionKeys,
1177
1292
  createApiKey,
@@ -1189,10 +1304,12 @@ export {
1189
1304
  isNetworkError,
1190
1305
  isSDKError,
1191
1306
  isTimeoutError,
1307
+ isUsageLimitError,
1192
1308
  isValidWebhookEvent,
1193
1309
  isValidationError,
1194
1310
  objectFor,
1195
1311
  parseApiKey,
1312
+ resolveRelation,
1196
1313
  verifyServerToken
1197
1314
  };
1198
1315
  //# sourceMappingURL=index.js.map