@cimplify/sdk 0.6.6 → 0.6.7

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.mjs CHANGED
@@ -38,11 +38,72 @@ var ErrorCode = {
38
38
  OUT_OF_STOCK: "OUT_OF_STOCK",
39
39
  INSUFFICIENT_QUANTITY: "INSUFFICIENT_QUANTITY"
40
40
  };
41
+ var DOCS_ERROR_BASE_URL = "https://docs.cimplify.io/reference/error-codes";
42
+ function docsUrlForCode(code) {
43
+ return `${DOCS_ERROR_BASE_URL}#${code.toLowerCase().replace(/_/g, "-")}`;
44
+ }
45
+ var ERROR_SUGGESTIONS = {
46
+ UNKNOWN_ERROR: "An unexpected error occurred. Capture the request/response payload and retry with exponential backoff.",
47
+ NETWORK_ERROR: "Check the shopper's connection and retry. If this persists, inspect CORS, DNS, and API reachability.",
48
+ TIMEOUT: "The request exceeded the timeout. Retry once, then poll order status before charging again.",
49
+ UNAUTHORIZED: "Authentication is missing or expired. Ensure a valid access token is set and refresh the session if needed.",
50
+ FORBIDDEN: "The key/session lacks permission for this resource. Verify business ownership and API key scope.",
51
+ NOT_FOUND: "The requested resource does not exist or is not visible in this environment.",
52
+ VALIDATION_ERROR: "One or more fields are invalid. Validate required fields and enum values before retrying.",
53
+ CART_EMPTY: "The cart has no items. Redirect back to menu/catalogue and require at least one line item.",
54
+ CART_EXPIRED: "This cart is no longer active. Recreate a new cart and re-add shopper selections.",
55
+ CART_NOT_FOUND: "Cart could not be located. It may have expired or belongs to a different key/location.",
56
+ ITEM_UNAVAILABLE: "The selected item is unavailable at this location/time. Prompt the shopper to pick an alternative.",
57
+ VARIANT_NOT_FOUND: "The requested variant no longer exists. Refresh product data and require re-selection.",
58
+ VARIANT_OUT_OF_STOCK: "The selected variant is out of stock. Show in-stock variants and block checkout for this line.",
59
+ ADDON_REQUIRED: "A required add-on is missing. Ensure required modifier groups are completed before add-to-cart.",
60
+ ADDON_MAX_EXCEEDED: "Too many add-ons were selected. Enforce max selections client-side before submission.",
61
+ CHECKOUT_VALIDATION_FAILED: "Checkout payload failed validation. Verify customer, order type, and address fields are complete.",
62
+ DELIVERY_ADDRESS_REQUIRED: "Delivery orders require an address. Collect and pass address info before processing checkout.",
63
+ CUSTOMER_INFO_REQUIRED: "Customer details are required. Ensure name/email/phone are available before checkout.",
64
+ PAYMENT_FAILED: "Payment provider rejected or failed processing. Show retry/change-method options to the shopper.",
65
+ PAYMENT_CANCELLED: "Payment was cancelled by the shopper or provider flow. Allow a safe retry path.",
66
+ INSUFFICIENT_FUNDS: "Payment method has insufficient funds. Prompt shopper to use another method.",
67
+ CARD_DECLINED: "Card was declined. Ask shopper to retry or switch payment method.",
68
+ INVALID_OTP: "Authorization code is invalid. Let shopper re-enter OTP/PIN and retry.",
69
+ OTP_EXPIRED: "Authorization code expired. Request a new OTP and re-submit authorization.",
70
+ AUTHORIZATION_FAILED: "Additional payment authorization failed. Retry authorization or change payment method.",
71
+ PAYMENT_ACTION_NOT_COMPLETED: "Required payment action was not completed. Resume provider flow and poll for status.",
72
+ SLOT_UNAVAILABLE: "Selected schedule slot is unavailable. Refresh available slots and ask shopper to reselect.",
73
+ BOOKING_CONFLICT: "The requested booking conflicts with an existing reservation. Pick another slot/resource.",
74
+ SERVICE_NOT_FOUND: "Requested service no longer exists. Refresh service catalogue and retry selection.",
75
+ OUT_OF_STOCK: "Inventory is depleted for this item. Remove it or reduce quantity before checkout.",
76
+ INSUFFICIENT_QUANTITY: "Requested quantity exceeds available inventory. Reduce quantity and retry.",
77
+ BUSINESS_ID_REQUIRED: "Business context could not be resolved. Verify the public key and business bootstrap call.",
78
+ INVALID_CART: "Cart is invalid for checkout. Sync cart state, ensure items exist, then retry.",
79
+ ORDER_TYPE_REQUIRED: "Order type is required. Provide one of delivery, pickup, or dine_in before checkout.",
80
+ NO_PAYMENT_ELEMENT: "PaymentElement is required for processCheckout(). Mount it before triggering checkout.",
81
+ PAYMENT_NOT_MOUNTED: "PaymentElement iframe is not mounted. Mount it in the DOM before processCheckout().",
82
+ AUTH_INCOMPLETE: "AuthElement has not completed authentication. Wait for AUTHENTICATED before checkout.",
83
+ AUTH_LOST: "Session was cleared during checkout. Re-authenticate and restart checkout safely.",
84
+ ALREADY_PROCESSING: "Checkout is already in progress. Disable duplicate submits until completion.",
85
+ CHECKOUT_NOT_READY: "Checkout elements are still initializing. Wait for readiness before submit.",
86
+ CANCELLED: "Checkout was cancelled. Preserve cart state and allow shopper to retry.",
87
+ REQUEST_TIMEOUT: "Provider call timed out. Poll payment/order status before issuing another charge attempt.",
88
+ POPUP_BLOCKED: "Browser blocked provider popup. Ask shopper to enable popups and retry.",
89
+ FX_QUOTE_FAILED: "Failed to lock FX quote. Retry currency quote or fallback to base currency."
90
+ };
91
+ var ERROR_HINTS = Object.fromEntries(
92
+ Object.entries(ERROR_SUGGESTIONS).map(([code, suggestion]) => [
93
+ code,
94
+ {
95
+ docs_url: docsUrlForCode(code),
96
+ suggestion
97
+ }
98
+ ])
99
+ );
41
100
  var CimplifyError = class extends Error {
42
- constructor(code, message, retryable = false) {
101
+ constructor(code, message, retryable = false, docs_url, suggestion) {
43
102
  super(message);
44
103
  this.code = code;
45
104
  this.retryable = retryable;
105
+ this.docs_url = docs_url;
106
+ this.suggestion = suggestion;
46
107
  this.name = "CimplifyError";
47
108
  }
48
109
  /** User-friendly message safe to display */
@@ -53,6 +114,28 @@ var CimplifyError = class extends Error {
53
114
  function isCimplifyError(error) {
54
115
  return error instanceof CimplifyError;
55
116
  }
117
+ function getErrorHint(code) {
118
+ return ERROR_HINTS[code];
119
+ }
120
+ function enrichError(error, options = {}) {
121
+ const hint = getErrorHint(error.code);
122
+ if (hint) {
123
+ if (!error.docs_url) {
124
+ error.docs_url = hint.docs_url;
125
+ }
126
+ if (!error.suggestion) {
127
+ error.suggestion = hint.suggestion;
128
+ }
129
+ } else if (!error.docs_url) {
130
+ error.docs_url = docsUrlForCode(error.code || ErrorCode.UNKNOWN_ERROR);
131
+ }
132
+ if (options.isTestMode && !error.message.includes("pk_test_")) {
133
+ error.message = `${error.message}
134
+
135
+ \u2139 Your API key is a test-mode key (pk_test_...). Verify test data/session before retrying.`;
136
+ }
137
+ return error;
138
+ }
56
139
  function isRetryableError(error) {
57
140
  if (isCimplifyError(error)) {
58
141
  return error.retryable;
@@ -136,11 +219,11 @@ function combineObject(results) {
136
219
 
137
220
  // src/catalogue.ts
138
221
  function toCimplifyError(error) {
139
- if (error instanceof CimplifyError) return error;
222
+ if (error instanceof CimplifyError) return enrichError(error);
140
223
  if (error instanceof Error) {
141
- return new CimplifyError("UNKNOWN_ERROR", error.message, false);
224
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
142
225
  }
143
- return new CimplifyError("UNKNOWN_ERROR", String(error), false);
226
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
144
227
  }
145
228
  async function safe(promise) {
146
229
  try {
@@ -435,11 +518,11 @@ var CatalogueQueries = class {
435
518
 
436
519
  // src/cart.ts
437
520
  function toCimplifyError2(error) {
438
- if (error instanceof CimplifyError) return error;
521
+ if (error instanceof CimplifyError) return enrichError(error);
439
522
  if (error instanceof Error) {
440
- return new CimplifyError("UNKNOWN_ERROR", error.message, false);
523
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
441
524
  }
442
- return new CimplifyError("UNKNOWN_ERROR", String(error), false);
525
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
443
526
  }
444
527
  async function safe2(promise) {
445
528
  try {
@@ -1654,11 +1737,11 @@ var CheckoutResolver = class {
1654
1737
 
1655
1738
  // src/checkout.ts
1656
1739
  function toCimplifyError3(error) {
1657
- if (error instanceof CimplifyError) return error;
1740
+ if (error instanceof CimplifyError) return enrichError(error);
1658
1741
  if (error instanceof Error) {
1659
- return new CimplifyError("UNKNOWN_ERROR", error.message, false);
1742
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
1660
1743
  }
1661
- return new CimplifyError("UNKNOWN_ERROR", String(error), false);
1744
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
1662
1745
  }
1663
1746
  async function safe3(promise) {
1664
1747
  try {
@@ -1834,11 +1917,11 @@ var CheckoutService = class {
1834
1917
 
1835
1918
  // src/orders.ts
1836
1919
  function toCimplifyError4(error) {
1837
- if (error instanceof CimplifyError) return error;
1920
+ if (error instanceof CimplifyError) return enrichError(error);
1838
1921
  if (error instanceof Error) {
1839
- return new CimplifyError("UNKNOWN_ERROR", error.message, false);
1922
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
1840
1923
  }
1841
- return new CimplifyError("UNKNOWN_ERROR", String(error), false);
1924
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
1842
1925
  }
1843
1926
  async function safe4(promise) {
1844
1927
  try {
@@ -2095,11 +2178,11 @@ var AuthService = class {
2095
2178
 
2096
2179
  // src/business.ts
2097
2180
  function toCimplifyError7(error) {
2098
- if (error instanceof CimplifyError) return error;
2181
+ if (error instanceof CimplifyError) return enrichError(error);
2099
2182
  if (error instanceof Error) {
2100
- return new CimplifyError("UNKNOWN_ERROR", error.message, false);
2183
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, error.message, false));
2101
2184
  }
2102
- return new CimplifyError("UNKNOWN_ERROR", String(error), false);
2185
+ return enrichError(new CimplifyError(ErrorCode.UNKNOWN_ERROR, String(error), false));
2103
2186
  }
2104
2187
  async function safe7(promise) {
2105
2188
  try {
@@ -2485,12 +2568,15 @@ var EVENT_TYPES = {
2485
2568
 
2486
2569
  // src/elements.ts
2487
2570
  function toCheckoutError(code, message, recoverable) {
2571
+ const hint = getErrorHint(code);
2488
2572
  return {
2489
2573
  success: false,
2490
2574
  error: {
2491
2575
  code,
2492
2576
  message,
2493
- recoverable
2577
+ recoverable,
2578
+ docs_url: hint?.docs_url,
2579
+ suggestion: hint?.suggestion
2494
2580
  }
2495
2581
  };
2496
2582
  }
@@ -2531,6 +2617,7 @@ var CimplifyElements = class {
2531
2617
  this.paymentData = null;
2532
2618
  this.checkoutInProgress = false;
2533
2619
  this.activeCheckoutAbort = null;
2620
+ this.hasWarnedMissingAuthElement = false;
2534
2621
  this.businessIdResolvePromise = null;
2535
2622
  this.client = client;
2536
2623
  this.businessId = businessId ?? null;
@@ -2626,6 +2713,12 @@ var CimplifyElements = class {
2626
2713
  );
2627
2714
  }
2628
2715
  const authElement = this.elements.get(ELEMENT_TYPES.AUTH);
2716
+ if (!authElement && !this.hasWarnedMissingAuthElement) {
2717
+ this.hasWarnedMissingAuthElement = true;
2718
+ console.warn(
2719
+ "[Cimplify] processCheckout() called without AuthElement mounted. For best conversion and Link enrollment, mount <AuthElement> before checkout."
2720
+ );
2721
+ }
2629
2722
  if (authElement && !this.accessToken) {
2630
2723
  return toCheckoutError(
2631
2724
  "AUTH_INCOMPLETE",
@@ -3062,28 +3155,37 @@ function isRetryable(error) {
3062
3155
  }
3063
3156
  return false;
3064
3157
  }
3065
- function toNetworkError(error) {
3158
+ function toNetworkError(error, isTestMode) {
3066
3159
  if (error instanceof DOMException && error.name === "AbortError") {
3067
- return new CimplifyError(
3068
- ErrorCode.TIMEOUT,
3069
- "Request timed out. Please check your connection and try again.",
3070
- true
3160
+ return enrichError(
3161
+ new CimplifyError(
3162
+ ErrorCode.TIMEOUT,
3163
+ "Request timed out. Please check your connection and try again.",
3164
+ true
3165
+ ),
3166
+ { isTestMode }
3071
3167
  );
3072
3168
  }
3073
3169
  if (error instanceof TypeError && error.message.includes("fetch")) {
3074
- return new CimplifyError(
3075
- ErrorCode.NETWORK_ERROR,
3076
- "Network error. Please check your internet connection.",
3077
- true
3170
+ return enrichError(
3171
+ new CimplifyError(
3172
+ ErrorCode.NETWORK_ERROR,
3173
+ "Network error. Please check your internet connection.",
3174
+ true
3175
+ ),
3176
+ { isTestMode }
3078
3177
  );
3079
3178
  }
3080
3179
  if (error instanceof CimplifyError) {
3081
- return error;
3082
- }
3083
- return new CimplifyError(
3084
- ErrorCode.UNKNOWN_ERROR,
3085
- error instanceof Error ? error.message : "An unknown error occurred",
3086
- false
3180
+ return enrichError(error, { isTestMode });
3181
+ }
3182
+ return enrichError(
3183
+ new CimplifyError(
3184
+ ErrorCode.UNKNOWN_ERROR,
3185
+ error instanceof Error ? error.message : "An unknown error occurred",
3186
+ false
3187
+ ),
3188
+ { isTestMode }
3087
3189
  );
3088
3190
  }
3089
3191
  function deriveUrls() {
@@ -3145,6 +3247,9 @@ var CimplifyClient = class {
3145
3247
  getPublicKey() {
3146
3248
  return this.publicKey;
3147
3249
  }
3250
+ isTestMode() {
3251
+ return this.publicKey.trim().startsWith("pk_test_");
3252
+ }
3148
3253
  setAccessToken(token) {
3149
3254
  const previous = this.accessToken;
3150
3255
  this.accessToken = token;
@@ -3294,7 +3399,7 @@ var CimplifyClient = class {
3294
3399
  return response;
3295
3400
  } catch (error) {
3296
3401
  lastError = error;
3297
- const networkError = toNetworkError(error);
3402
+ const networkError = toNetworkError(error, this.isTestMode());
3298
3403
  const errorRetryable = isRetryable(error);
3299
3404
  if (!errorRetryable || attempt >= this.maxRetries) {
3300
3405
  this.hooks.onRequestError?.({
@@ -3317,7 +3422,7 @@ var CimplifyClient = class {
3317
3422
  await sleep(delay);
3318
3423
  }
3319
3424
  }
3320
- const finalError = toNetworkError(lastError);
3425
+ const finalError = toNetworkError(lastError, this.isTestMode());
3321
3426
  this.hooks.onRequestError?.({
3322
3427
  ...context,
3323
3428
  error: finalError,
@@ -3435,22 +3540,40 @@ var CimplifyClient = class {
3435
3540
  async handleRestResponse(response) {
3436
3541
  const json = await response.json();
3437
3542
  if (!response.ok) {
3438
- throw new CimplifyError(
3439
- json.error?.error_code || "API_ERROR",
3440
- json.error?.error_message || "An error occurred",
3441
- false
3543
+ const error = enrichError(
3544
+ new CimplifyError(
3545
+ json.error?.error_code || "API_ERROR",
3546
+ json.error?.error_message || "An error occurred",
3547
+ false
3548
+ ),
3549
+ { isTestMode: this.isTestMode() }
3442
3550
  );
3551
+ if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
3552
+ console.warn(
3553
+ "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
3554
+ );
3555
+ }
3556
+ throw error;
3443
3557
  }
3444
3558
  return json.data;
3445
3559
  }
3446
3560
  async handleResponse(response) {
3447
3561
  const json = await response.json();
3448
3562
  if (!json.success || json.error) {
3449
- throw new CimplifyError(
3450
- json.error?.code || "UNKNOWN_ERROR",
3451
- json.error?.message || "An unknown error occurred",
3452
- json.error?.retryable || false
3563
+ const error = enrichError(
3564
+ new CimplifyError(
3565
+ json.error?.code || "UNKNOWN_ERROR",
3566
+ json.error?.message || "An unknown error occurred",
3567
+ json.error?.retryable || false
3568
+ ),
3569
+ { isTestMode: this.isTestMode() }
3453
3570
  );
3571
+ if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
3572
+ console.warn(
3573
+ "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
3574
+ );
3575
+ }
3576
+ throw error;
3454
3577
  }
3455
3578
  return json.data;
3456
3579
  }
@@ -3610,4 +3733,4 @@ function query(entity) {
3610
3733
  return new QueryBuilder(entity);
3611
3734
  }
3612
3735
 
3613
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyElement, CimplifyElements, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENT_TYPES, EVENT_TYPES, ErrorCode, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, categorizePaymentError, combine, combineObject, createCimplifyClient, createElements, detectMobileMoneyProvider, err, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, query, toNullable, tryCatch, unwrap };
3736
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyElement, CimplifyElements, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENT_TYPES, ERROR_HINTS, EVENT_TYPES, ErrorCode, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, categorizePaymentError, combine, combineObject, createCimplifyClient, createElements, detectMobileMoneyProvider, enrichError, err, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getErrorHint, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, query, toNullable, tryCatch, unwrap };
@@ -56,6 +56,11 @@ interface ApiError {
56
56
  message: string;
57
57
  retryable: boolean;
58
58
  }
59
+ interface ErrorHint {
60
+ docs_url: string;
61
+ suggestion: string;
62
+ }
63
+ declare const ERROR_HINTS: Record<string, ErrorHint>;
59
64
  /**
60
65
  * Custom error class for SDK errors with typed error codes.
61
66
  *
@@ -82,12 +87,18 @@ interface ApiError {
82
87
  declare class CimplifyError extends Error {
83
88
  code: string;
84
89
  retryable: boolean;
85
- constructor(code: string, message: string, retryable?: boolean);
90
+ docs_url?: string | undefined;
91
+ suggestion?: string | undefined;
92
+ constructor(code: string, message: string, retryable?: boolean, docs_url?: string | undefined, suggestion?: string | undefined);
86
93
  /** User-friendly message safe to display */
87
94
  get userMessage(): string;
88
95
  }
89
96
  /** Type guard for CimplifyError */
90
97
  declare function isCimplifyError(error: unknown): error is CimplifyError;
98
+ declare function getErrorHint(code: string): ErrorHint | undefined;
99
+ declare function enrichError(error: CimplifyError, options?: {
100
+ isTestMode?: boolean;
101
+ }): CimplifyError;
91
102
  /** Check if error is retryable */
92
103
  declare function isRetryableError(error: unknown): boolean;
93
104
 
@@ -167,4 +178,4 @@ interface SubmitAuthorizationInput {
167
178
  value: string;
168
179
  }
169
180
 
170
- export { type ApiError as A, type Currency as C, ErrorCode as E, type InitializePaymentResult as I, type Money as M, type PaginationParams as P, type SubmitAuthorizationInput as S, type Pagination as a, type ErrorCodeType as b, CimplifyError as c, isRetryableError as d, type PaymentStatus as e, type PaymentProvider as f, type PaymentMethodType as g, type AuthorizationType as h, isCimplifyError as i, type PaymentProcessingState as j, type PaymentMethod as k, type Payment as l, type PaymentResponse as m, type PaymentStatusResponse as n, type PaymentErrorDetails as o };
181
+ export { type ApiError as A, type Currency as C, ErrorCode as E, type InitializePaymentResult as I, type Money as M, type PaginationParams as P, type SubmitAuthorizationInput as S, type Pagination as a, type ErrorCodeType as b, type ErrorHint as c, ERROR_HINTS as d, CimplifyError as e, enrichError as f, getErrorHint as g, isRetryableError as h, isCimplifyError as i, type PaymentStatus as j, type PaymentProvider as k, type PaymentMethodType as l, type AuthorizationType as m, type PaymentProcessingState as n, type PaymentMethod as o, type Payment as p, type PaymentResponse as q, type PaymentStatusResponse as r, type PaymentErrorDetails as s };
@@ -56,6 +56,11 @@ interface ApiError {
56
56
  message: string;
57
57
  retryable: boolean;
58
58
  }
59
+ interface ErrorHint {
60
+ docs_url: string;
61
+ suggestion: string;
62
+ }
63
+ declare const ERROR_HINTS: Record<string, ErrorHint>;
59
64
  /**
60
65
  * Custom error class for SDK errors with typed error codes.
61
66
  *
@@ -82,12 +87,18 @@ interface ApiError {
82
87
  declare class CimplifyError extends Error {
83
88
  code: string;
84
89
  retryable: boolean;
85
- constructor(code: string, message: string, retryable?: boolean);
90
+ docs_url?: string | undefined;
91
+ suggestion?: string | undefined;
92
+ constructor(code: string, message: string, retryable?: boolean, docs_url?: string | undefined, suggestion?: string | undefined);
86
93
  /** User-friendly message safe to display */
87
94
  get userMessage(): string;
88
95
  }
89
96
  /** Type guard for CimplifyError */
90
97
  declare function isCimplifyError(error: unknown): error is CimplifyError;
98
+ declare function getErrorHint(code: string): ErrorHint | undefined;
99
+ declare function enrichError(error: CimplifyError, options?: {
100
+ isTestMode?: boolean;
101
+ }): CimplifyError;
91
102
  /** Check if error is retryable */
92
103
  declare function isRetryableError(error: unknown): boolean;
93
104
 
@@ -167,4 +178,4 @@ interface SubmitAuthorizationInput {
167
178
  value: string;
168
179
  }
169
180
 
170
- export { type ApiError as A, type Currency as C, ErrorCode as E, type InitializePaymentResult as I, type Money as M, type PaginationParams as P, type SubmitAuthorizationInput as S, type Pagination as a, type ErrorCodeType as b, CimplifyError as c, isRetryableError as d, type PaymentStatus as e, type PaymentProvider as f, type PaymentMethodType as g, type AuthorizationType as h, isCimplifyError as i, type PaymentProcessingState as j, type PaymentMethod as k, type Payment as l, type PaymentResponse as m, type PaymentStatusResponse as n, type PaymentErrorDetails as o };
181
+ export { type ApiError as A, type Currency as C, ErrorCode as E, type InitializePaymentResult as I, type Money as M, type PaginationParams as P, type SubmitAuthorizationInput as S, type Pagination as a, type ErrorCodeType as b, type ErrorHint as c, ERROR_HINTS as d, CimplifyError as e, enrichError as f, getErrorHint as g, isRetryableError as h, isCimplifyError as i, type PaymentStatus as j, type PaymentProvider as k, type PaymentMethodType as l, type AuthorizationType as m, type PaymentProcessingState as n, type PaymentMethod as o, type Payment as p, type PaymentResponse as q, type PaymentStatusResponse as r, type PaymentErrorDetails as s };
package/dist/react.d.mts CHANGED
@@ -1,8 +1,8 @@
1
- import { C as CimplifyClient, _ as ProcessCheckoutResult, a0 as CheckoutStatus, a1 as CheckoutStatusContext, cT as Location, cQ as Business, u as CimplifyElements, y as ElementsOptions, eh as AuthenticatedData, ed as AddressInfo, ee as PaymentMethodInfo, ej as ElementsCheckoutResult, Z as ProcessCheckoutOptions } from './client-CUFdFugo.mjs';
1
+ import { C as CimplifyClient, _ as ProcessCheckoutResult, a0 as CheckoutStatus, a1 as CheckoutStatusContext, cT as Location, cQ as Business, aL as Product, aM as ProductWithDetails, a_ as Category, bH as BundleSelectionInput, bi as ComponentSelectionInput, cj as Order, u as CimplifyElements, y as ElementsOptions, eh as AuthenticatedData, ed as AddressInfo, ee as PaymentMethodInfo, ej as ElementsCheckoutResult, Z as ProcessCheckoutOptions } from './client-B4etj3AD.mjs';
2
2
  import React, { ReactNode } from 'react';
3
3
  import { A as AdSlot, a as AdPosition, e as AdContextValue } from './ads-t3FBTU8p.mjs';
4
4
  export { c as AdConfig } from './ads-t3FBTU8p.mjs';
5
- import './payment-D-u3asA8.mjs';
5
+ import { e as CimplifyError } from './payment-pjpfIKX8.mjs';
6
6
 
7
7
  interface UserIdentity {
8
8
  uid: string;
@@ -94,6 +94,132 @@ interface CimplifyProviderProps {
94
94
  }
95
95
  declare function CimplifyProvider({ client, children, onLocationChange, }: CimplifyProviderProps): React.ReactElement;
96
96
  declare function useCimplify(): CimplifyContextValue;
97
+ declare function useOptionalCimplify(): CimplifyContextValue | null;
98
+
99
+ interface UseProductsOptions {
100
+ category?: string;
101
+ collection?: string;
102
+ search?: string;
103
+ featured?: boolean;
104
+ limit?: number;
105
+ enabled?: boolean;
106
+ client?: CimplifyClient;
107
+ }
108
+ interface UseProductsResult {
109
+ products: Product[];
110
+ isLoading: boolean;
111
+ error: CimplifyError | null;
112
+ refetch: () => Promise<void>;
113
+ }
114
+ declare function useProducts(options?: UseProductsOptions): UseProductsResult;
115
+
116
+ interface UseProductOptions {
117
+ enabled?: boolean;
118
+ client?: CimplifyClient;
119
+ }
120
+ interface UseProductResult {
121
+ product: ProductWithDetails | null;
122
+ isLoading: boolean;
123
+ error: CimplifyError | null;
124
+ refetch: () => Promise<void>;
125
+ }
126
+ declare function useProduct(slugOrId: string | null | undefined, options?: UseProductOptions): UseProductResult;
127
+
128
+ interface UseCategoriesOptions {
129
+ enabled?: boolean;
130
+ client?: CimplifyClient;
131
+ }
132
+ interface UseCategoriesResult {
133
+ categories: Category[];
134
+ isLoading: boolean;
135
+ error: CimplifyError | null;
136
+ refetch: () => Promise<void>;
137
+ }
138
+ declare function useCategories(options?: UseCategoriesOptions): UseCategoriesResult;
139
+
140
+ interface CartVariantSelection {
141
+ id: string;
142
+ name: string;
143
+ price_adjustment?: string;
144
+ }
145
+ interface CartAddOnOptionSelection {
146
+ id: string;
147
+ name: string;
148
+ add_on_id?: string;
149
+ default_price?: string;
150
+ }
151
+ interface UseCartItem {
152
+ id: string;
153
+ product: Product;
154
+ quantity: number;
155
+ locationId?: string;
156
+ variantId?: string;
157
+ variant?: CartVariantSelection;
158
+ quoteId?: string;
159
+ addOnOptionIds?: string[];
160
+ addOnOptions?: CartAddOnOptionSelection[];
161
+ bundleSelections?: BundleSelectionInput[];
162
+ compositeSelections?: ComponentSelectionInput[];
163
+ specialInstructions?: string;
164
+ }
165
+ interface AddToCartOptions {
166
+ locationId?: string;
167
+ variantId?: string;
168
+ variant?: CartVariantSelection;
169
+ quoteId?: string;
170
+ addOnOptionIds?: string[];
171
+ addOnOptions?: CartAddOnOptionSelection[];
172
+ bundleSelections?: BundleSelectionInput[];
173
+ compositeSelections?: ComponentSelectionInput[];
174
+ specialInstructions?: string;
175
+ }
176
+ interface UseCartOptions {
177
+ client?: CimplifyClient;
178
+ demoMode?: boolean;
179
+ locationId?: string;
180
+ currency?: string;
181
+ }
182
+ interface UseCartResult {
183
+ items: UseCartItem[];
184
+ itemCount: number;
185
+ subtotal: number;
186
+ tax: number;
187
+ total: number;
188
+ currency: string;
189
+ isEmpty: boolean;
190
+ isLoading: boolean;
191
+ addItem: (product: Product, quantity?: number, options?: AddToCartOptions) => Promise<void>;
192
+ removeItem: (itemId: string) => Promise<void>;
193
+ updateQuantity: (itemId: string, quantity: number) => Promise<void>;
194
+ clearCart: () => Promise<void>;
195
+ sync: () => Promise<void>;
196
+ }
197
+ declare function useCart(options?: UseCartOptions): UseCartResult;
198
+
199
+ interface UseOrderOptions {
200
+ poll?: boolean;
201
+ pollInterval?: number;
202
+ enabled?: boolean;
203
+ client?: CimplifyClient;
204
+ }
205
+ interface UseOrderResult {
206
+ order: Order | null;
207
+ isLoading: boolean;
208
+ error: CimplifyError | null;
209
+ refetch: () => Promise<void>;
210
+ }
211
+ declare function useOrder(orderId: string | null | undefined, options?: UseOrderOptions): UseOrderResult;
212
+
213
+ interface UseLocationsOptions {
214
+ client?: CimplifyClient;
215
+ }
216
+ interface UseLocationsResult {
217
+ locations: Location[];
218
+ currentLocation: Location | null;
219
+ setCurrentLocation: (location: Location) => void;
220
+ isLoading: boolean;
221
+ }
222
+ declare function useLocations(options?: UseLocationsOptions): UseLocationsResult;
97
223
 
98
224
  declare function useElements(): CimplifyElements | null;
99
225
  declare function useElementsReady(): boolean;
@@ -151,4 +277,4 @@ declare function useCheckout(): {
151
277
  isLoading: boolean;
152
278
  };
153
279
 
154
- export { Ad, AdPosition, type AdProps, AdProvider, AdSlot, AddressElement, AuthElement, CimplifyCheckout, type CimplifyCheckoutProps, type CimplifyContextValue, CimplifyProvider, type CimplifyProviderProps, ElementsProvider, PaymentElement, useAds, useCheckout, useCimplify, useElements, useElementsReady };
280
+ export { Ad, AdPosition, type AdProps, AdProvider, AdSlot, type AddToCartOptions, AddressElement, AuthElement, CimplifyCheckout, type CimplifyCheckoutProps, type CimplifyContextValue, CimplifyProvider, type CimplifyProviderProps, ElementsProvider, PaymentElement, type UseCartItem, type UseCartOptions, type UseCartResult, type UseCategoriesOptions, type UseCategoriesResult, type UseLocationsOptions, type UseLocationsResult, type UseOrderOptions, type UseOrderResult, type UseProductOptions, type UseProductResult, type UseProductsOptions, type UseProductsResult, useAds, useCart, useCategories, useCheckout, useCimplify, useElements, useElementsReady, useLocations, useOptionalCimplify, useOrder, useProduct, useProducts };