@cimplify/sdk 0.6.5 → 0.6.6

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.d.ts CHANGED
@@ -1,348 +1,9 @@
1
- import { P as PaymentErrorDetails, a as PaymentResponse, b as PaymentStatusResponse, A as ApiError } from './ads-CmO7VVPP.js';
2
- export { ah as AUTHORIZATION_TYPE, am as AUTH_MUTATION, a6 as AbortablePromise, eM as AdConfig, eO as AdContextValue, eN as AdCreative, eK as AdPosition, eJ as AdSlot, eL as AdTheme, b6 as AddOn, bR as AddOnDetails, cb as AddOnGroupDetails, b8 as AddOnOption, ca as AddOnOptionDetails, b9 as AddOnOptionPrice, b7 as AddOnWithOptions, cg as AddToCartInput, e7 as AddressData, ez as AddressInfo, bG as AdjustmentType, cu as AmountToPay, bN as AppliedDiscount, ei as AuthResponse, p as AuthService, q as AuthStatus, eB as AuthenticatedCustomer, eD as AuthenticatedData, d2 as AuthorizationType, dX as AvailabilityCheck, dY as AvailabilityResult, dF as AvailableSlot, bM as BenefitType, dI as Booking, dz as BookingRequirementOverride, dH as BookingStatus, dJ as BookingWithDetails, cO as BufferTimes, bh as Bundle, bl as BundleComponentData, bm as BundleComponentInfo, bg as BundlePriceType, bj as BundleProduct, bW as BundleSelectionData, bU as BundleSelectionInput, bV as BundleStoredSelection, bi as BundleSummary, bk as BundleWithDetails, da as Business, dp as BusinessHours, d9 as BusinessPreferences, B as BusinessService, dn as BusinessSettings, d8 as BusinessType, dl as BusinessWithLocations, aa as CHECKOUT_MODE, an as CHECKOUT_MUTATION, ad as CHECKOUT_STEP, aj as CONTACT_TYPE, dN as CancelBookingInput, cI as CancelOrderInput, cQ as CancellationPolicy, b$ as Cart, bS as CartAddOn, bE as CartChannel, c0 as CartItem, cd as CartItemDetails, l as CartOperations, bD as CartStatus, ci as CartSummary, c1 as CartTotals, e as CatalogueQueries, bb as Category, dq as CategoryInfo, bc as CategorySummary, s as ChangePasswordInput, dL as CheckSlotAvailabilityInput, el as CheckoutAddressInfo, en as CheckoutCustomerInfo, $ as CheckoutFormData, cG as CheckoutInput, X as CheckoutMode, m as CheckoutOperations, Y as CheckoutOrderType, Z as CheckoutPaymentMethod, a0 as CheckoutResult, m as CheckoutService, a4 as CheckoutStatus, a5 as CheckoutStatusContext, _ as CheckoutStep, bL as ChosenPrice, C as CimplifyClient, d as CimplifyConfig, z as CimplifyElement, y as CimplifyElements, ay as CimplifyError, bd as Collection, bf as CollectionProduct, be as CollectionSummary, bs as ComponentGroup, bt as ComponentGroupWithComponents, bx as ComponentPriceBreakdown, bv as ComponentSelectionInput, bp as ComponentSourceType, bq as Composite, bu as CompositeComponent, bY as CompositePriceBreakdown, bw as CompositePriceResult, bn as CompositePricingMode, bZ as CompositeSelectionData, bv as CompositeSelectionInput, bX as CompositeStoredSelection, br as CompositeWithDetails, a9 as ContactType, e3 as CreateAddressInput, e5 as CreateMobileMoneyInput, at as Currency, d_ as Customer, d$ as CustomerAddress, e1 as CustomerLinkPreferences, e0 as CustomerMobileMoney, cN as CustomerServicePreferences, ar as DEFAULT_COUNTRY, aq as DEFAULT_CURRENCY, ai as DEVICE_TYPE, dG as DayAvailability, cX as DepositResult, aW as DepositType, a8 as DeviceType, aV as DigitalProductType, bO as DiscountBreakdown, bP as DiscountDetails, c4 as DisplayAddOn, c5 as DisplayAddOnOption, c2 as DisplayCart, c3 as DisplayCartItem, H as ELEMENT_TYPES, E as EVENT_TYPES, ey as ElementAppearance, eI as ElementEventHandler, W as ElementEventType, N as ElementOptions, V as ElementType, eE as ElementsCheckoutData, eF as ElementsCheckoutResult, eC as ElementsCustomerInfo, J as ElementsOptions, e9 as EnrollAndLinkOrderInput, ec as EnrollAndLinkOrderResult, e6 as EnrollmentData, aD as Err, aw as ErrorCode, ax as ErrorCodeType, ct as FeeBearerType, F as FetchQuoteInput, cr as FulfillmentLink, cq as FulfillmentStatus, cp as FulfillmentType, ep as FxQuote, eo as FxQuoteRequest, eq as FxRateResponse, v as FxService, dK as GetAvailableSlotsInput, o as GetOrdersOptions, G as GetProductsOptions, bo as GroupPricingBehavior, eH as IframeToParentMessage, d6 as InitializePaymentResult, I as InventoryService, dZ as InventorySummary, aT as InventoryType, K as KitchenOrderItem, x as KitchenOrderResult, al as LINK_MUTATION, ak as LINK_QUERY, b_ as LineConfiguration, cv as LineItem, cm as LineType, e2 as LinkData, eb as LinkEnrollResult, L as LinkService, ed as LinkSession, ea as LinkStatusResult, w as LiteBootstrap, u as LiteService, dd as Location, c_ as LocationAppointment, bA as LocationProductPrice, dW as LocationStock, db as LocationTaxBehavior, dc as LocationTaxOverrides, dg as LocationTimeProfile, dm as LocationWithDetails, M as MESSAGE_TYPES, ag as MOBILE_MONEY_PROVIDER, e8 as MobileMoneyData, em as MobileMoneyDetails, a7 as MobileMoneyProvider, as as Money, ap as ORDER_MUTATION, ab as ORDER_TYPE, ex as ObservabilityHooks, aC as Ok, cw as Order, cl as OrderChannel, cF as OrderFilter, cs as OrderFulfillmentSummary, cz as OrderGroup, cD as OrderGroupDetails, cA as OrderGroupPayment, cy as OrderGroupPaymentState, cC as OrderGroupPaymentSummary, cx as OrderHistory, cn as OrderLineState, co as OrderLineStatus, cE as OrderPaymentEvent, O as OrderQueries, cB as OrderSplitDetail, cj as OrderStatus, r as OtpResult, ac as PAYMENT_METHOD, ao as PAYMENT_MUTATION, ae as PAYMENT_STATE, af as PICKUP_TIME_TYPE, av as Pagination, au as PaginationParams, eG as ParentToIframeMessage, d5 as Payment, d4 as PaymentMethod, eA as PaymentMethodInfo, d1 as PaymentMethodType, d3 as PaymentProcessingState, d0 as PaymentProvider, ck as PaymentState, c$ as PaymentStatus, ek as PickupTime, ej as PickupTimeType, bz as Price, bH as PriceAdjustment, bK as PriceDecisionPath, by as PriceEntryType, bJ as PricePathTaxInfo, j as PriceQuote, bF as PriceSource, cS as PricingOverrides, a3 as ProcessAndResolveOptions, a1 as ProcessCheckoutOptions, a2 as ProcessCheckoutResult, aY as Product, ba as ProductAddOn, bB as ProductAvailability, dU as ProductStock, bC as ProductTimeProfile, aS as ProductType, a_ as ProductVariant, b3 as ProductVariantValue, aZ as ProductWithDetails, f as QuoteBundleSelectionInput, Q as QuoteCompositeSelectionInput, h as QuoteDynamicBuckets, g as QuoteStatus, i as QuoteUiMessage, R as RefreshQuoteInput, k as RefreshQuoteResult, cJ as RefundOrderInput, cM as ReminderMethod, cP as ReminderSettings, er as RequestContext, eu as RequestErrorEvent, eg as RequestOtpInput, es as RequestStartEvent, et as RequestSuccessEvent, dM as RescheduleBookingInput, cV as ResourceAssignment, dw as ResourceAvailabilityException, dv as ResourceAvailabilityRule, dA as ResourceType, aB as Result, ev as RetryEvent, ef as RevokeAllSessionsResult, ee as RevokeSessionResult, di as Room, aX as SalesChannel, cT as SchedulingMetadata, cW as SchedulingResult, t as SchedulingService, S as SearchOptions, bQ as SelectedAddOnOption, dB as Service, ds as ServiceAvailabilityException, dO as ServiceAvailabilityParams, dP as ServiceAvailabilityResult, dr as ServiceAvailabilityRule, dj as ServiceCharge, cR as ServiceNotes, cY as ServiceScheduleRequest, dy as ServiceStaffRequirement, cK as ServiceStatus, dC as ServiceWithStaff, ew as SessionChangeEvent, dD as Staff, cU as StaffAssignment, du as StaffAvailabilityException, dt as StaffAvailabilityRule, dx as StaffBookingProfile, cL as StaffRole, cZ as StaffScheduleItem, dS as Stock, dT as StockLevel, dQ as StockOwnershipType, dR as StockStatus, dk as StorefrontBootstrap, d7 as SubmitAuthorizationInput, dh as Table, T as TableInfo, bI as TaxPathComponent, de as TimeRange, df as TimeRanges, dE as TimeSlot, ce as UICart, c6 as UICartBusiness, c8 as UICartCustomer, c7 as UICartLocation, c9 as UICartPricing, cf as UICartResponse, e4 as UpdateAddressInput, ch as UpdateCartItemInput, cH as UpdateOrderStatusInput, U as UpdateProfileInput, b0 as VariantAxis, b5 as VariantAxisSelection, b2 as VariantAxisValue, b1 as VariantAxisWithValues, bT as VariantDetails, cc as VariantDetailsDTO, a$ as VariantDisplayAttribute, b4 as VariantLocationAvailability, dV as VariantStock, aU as VariantStrategy, eh as VerifyOtpInput, aQ as combine, aR as combineObject, c as createCimplifyClient, D as createElements, aF as err, aK as flatMap, aO as fromPromise, n as generateIdempotencyKey, aL as getOrElse, az as isCimplifyError, aH as isErr, aG as isOk, aA as isRetryableError, aJ as mapError, aI as mapResult, aE as ok, aN as toNullable, aP as tryCatch, aM as unwrap } from './ads-CmO7VVPP.js';
3
-
4
- type Operator = "==" | "!=" | ">" | "<" | ">=" | "<=" | "contains" | "startsWith";
5
- type SortOrder = "asc" | "desc";
6
- declare class QueryBuilder {
7
- private entity;
8
- private filters;
9
- private modifiers;
10
- private pathSegments;
11
- constructor(entity: string);
12
- path(segment: string): this;
13
- where(field: string, op: Operator, value: unknown): this;
14
- and(field: string, op: Operator, value: unknown): this;
15
- sort(field: string, order?: SortOrder): this;
16
- limit(n: number): this;
17
- offset(n: number): this;
18
- count(): this;
19
- enriched(): this;
20
- build(): string;
21
- toString(): string;
22
- }
23
- declare function query(entity: string): QueryBuilder;
24
-
25
- /**
26
- * Price Types
27
- *
28
- * Types for price parsing, formatting, and display utilities.
29
- */
30
- /**
31
- * Individual tax component (e.g., VAT, NHIL, GETFund)
32
- */
33
- interface TaxComponent {
34
- /** Tax component name */
35
- name: string;
36
- /** Tax rate as percentage (e.g., 15.0 for 15%) */
37
- rate: number;
38
- }
39
- /**
40
- * Complete tax information from a pricing response
41
- */
42
- interface TaxInfo {
43
- /** Total tax rate as percentage */
44
- taxRate: number;
45
- /** Calculated tax amount */
46
- taxAmount: number;
47
- /** Whether tax is included in the displayed price */
48
- isInclusive: boolean;
49
- /** Individual tax components that make up the total */
50
- components: TaxComponent[];
51
- }
52
- /**
53
- * Price information in snake_case format (as returned from backend)
54
- * Used by components that work with raw API responses
55
- */
56
- interface PriceInfo {
57
- /** Original price before markup/discount */
58
- base_price: number;
59
- /** Final price after all adjustments */
60
- final_price: number;
61
- /** Markup percentage if applicable */
62
- markup_percentage?: number;
63
- /** Markup amount if applicable */
64
- markup_amount?: number;
65
- /** Currency code (e.g., "GHS", "USD") */
66
- currency?: string;
67
- /** Tax information */
68
- tax_info?: TaxInfo;
69
- /** Decision path showing pricing adjustments */
70
- decision_path?: string;
71
- }
72
- /**
73
- * Minimal product shape for price utilities.
74
- * Uses quote-aware `price_info` and plain numeric fallback fields.
75
- */
76
- interface ProductWithPrice {
77
- /** Pre-parsed price info from backend */
78
- price_info?: PriceInfo;
79
- /** Final computed price in plain field form (if provided by API) */
80
- final_price?: number | string | null;
81
- /** Base/original price in plain field form */
82
- base_price?: number | string | null;
83
- /** Default/indicative price in plain field form */
84
- default_price?: number | string | null;
85
- /** Currency in plain field form */
86
- currency?: string | null;
87
- }
88
- /**
89
- * Options for price formatting functions
90
- */
91
- interface FormatPriceOptions {
92
- /** Currency code (default: "GHS") */
93
- currency?: string;
94
- /** Locale for Intl.NumberFormat (default: "en-US") */
95
- locale?: string;
96
- /** Minimum fraction digits (default: 2) */
97
- minimumFractionDigits?: number;
98
- /** Maximum fraction digits (default: 2) */
99
- maximumFractionDigits?: number;
100
- }
101
- /**
102
- * Options for compact price formatting
103
- */
104
- interface FormatCompactOptions {
105
- /** Currency code (default: "GHS") */
106
- currency?: string;
107
- /** Number of decimal places for compact notation (default: 1) */
108
- decimals?: number;
109
- }
110
-
111
- /**
112
- * Price Utilities
113
- *
114
- * Comprehensive utilities for parsing, formatting, and displaying prices.
115
- * Handles quote-aware pricing fields, currency formatting, and product price helpers.
116
- *
117
- * @example
118
- * ```typescript
119
- * import {
120
- * formatPrice,
121
- * formatPriceCompact,
122
- * isOnSale,
123
- * getDiscountPercentage
124
- * } from '@cimplify/sdk';
125
- *
126
- * // Format prices
127
- * formatPrice(29.99, 'USD'); // "$29.99"
128
- * formatPrice(29.99, 'GHS'); // "GH₵29.99"
129
- * formatPriceCompact(1500000, 'USD'); // "$1.5M"
130
- *
131
- * // Check for discounts
132
- * if (isOnSale(product)) {
133
- * console.log(`${getDiscountPercentage(product)}% off!`);
134
- * }
135
- * ```
136
- */
137
-
138
- /**
139
- * Currency code to symbol mapping
140
- * Includes major world currencies and African currencies
141
- */
142
- declare const CURRENCY_SYMBOLS: Record<string, string>;
143
- /**
144
- * Get currency symbol for a currency code
145
- * @param currencyCode - ISO 4217 currency code (e.g., "USD", "GHS")
146
- * @returns Currency symbol or the code itself if not found
147
- *
148
- * @example
149
- * getCurrencySymbol('USD') // "$"
150
- * getCurrencySymbol('GHS') // "GH₵"
151
- * getCurrencySymbol('XYZ') // "XYZ"
152
- */
153
- declare function getCurrencySymbol(currencyCode: string): string;
154
- /**
155
- * Format a number compactly with K/M/B suffixes
156
- * @param value - Number to format
157
- * @param decimals - Decimal places (default: 1)
158
- * @returns Compact string representation
159
- *
160
- * @example
161
- * formatNumberCompact(1234) // "1.2K"
162
- * formatNumberCompact(1500000) // "1.5M"
163
- * formatNumberCompact(2500000000) // "2.5B"
164
- */
165
- declare function formatNumberCompact(value: number, decimals?: number): string;
166
- /**
167
- * Format a price with locale-aware currency formatting
168
- * Uses Intl.NumberFormat for proper localization
169
- *
170
- * @param amount - Price amount (number or string)
171
- * @param currency - ISO 4217 currency code (default: "GHS")
172
- * @param locale - BCP 47 locale string (default: "en-US")
173
- * @returns Formatted price string
174
- *
175
- * @example
176
- * formatPrice(29.99, 'USD') // "$29.99"
177
- * formatPrice(29.99, 'GHS') // "GH₵29.99"
178
- * formatPrice('29.99', 'EUR') // "€29.99"
179
- * formatPrice(1234.56, 'USD', 'de-DE') // "1.234,56 $"
180
- */
181
- declare function formatPrice(amount: number | string, currency?: string, locale?: string): string;
182
- /**
183
- * Format a price with +/- sign for adjustments
184
- * Useful for showing price changes, modifiers, or discounts
185
- *
186
- * @param amount - Adjustment amount (positive or negative)
187
- * @param currency - ISO 4217 currency code (default: "GHS")
188
- * @param locale - BCP 47 locale string (default: "en-US")
189
- * @returns Formatted adjustment string with sign
190
- *
191
- * @example
192
- * formatPriceAdjustment(5.00, 'USD') // "+$5.00"
193
- * formatPriceAdjustment(-3.50, 'GHS') // "-GH₵3.50"
194
- * formatPriceAdjustment(0, 'EUR') // "€0.00"
195
- */
196
- declare function formatPriceAdjustment(amount: number, currency?: string, locale?: string): string;
197
- /**
198
- * Format a price compactly for large numbers
199
- * Uses K/M/B suffixes for thousands, millions, billions
200
- *
201
- * @param amount - Price amount (number or string)
202
- * @param currency - ISO 4217 currency code (default: "GHS")
203
- * @param decimals - Decimal places for compact notation (default: 1)
204
- * @returns Compact formatted price
205
- *
206
- * @example
207
- * formatPriceCompact(999, 'USD') // "$999.00"
208
- * formatPriceCompact(1500, 'GHS') // "GH₵1.5K"
209
- * formatPriceCompact(2500000, 'USD') // "$2.5M"
210
- * formatPriceCompact(1200000000, 'EUR') // "€1.2B"
211
- */
212
- declare function formatPriceCompact(amount: number | string, currency?: string, decimals?: number): string;
213
- /**
214
- * Simple currency symbol + amount format
215
- * Lighter alternative to formatPrice without Intl
216
- *
217
- * @param amount - Price amount (number or string)
218
- * @param currency - ISO 4217 currency code (default: "GHS")
219
- * @returns Simple formatted price
220
- *
221
- * @example
222
- * formatMoney(29.99, 'USD') // "$29.99"
223
- * formatMoney('15.00', 'GHS') // "GH₵15.00"
224
- */
225
- declare function formatMoney(amount: string | number, currency?: string): string;
226
- /**
227
- * Parse a price string or number to a numeric value
228
- * Handles various input formats gracefully
229
- *
230
- * @param value - Value to parse (string, number, or undefined)
231
- * @returns Parsed numeric value, or 0 if invalid
232
- *
233
- * @example
234
- * parsePrice('29.99') // 29.99
235
- * parsePrice(29.99) // 29.99
236
- * parsePrice('$29.99') // 29.99 (strips non-numeric prefix)
237
- * parsePrice(undefined) // 0
238
- * parsePrice('invalid') // 0
239
- */
240
- declare function parsePrice(value: string | number | undefined | null): number;
241
- /**
242
- * Get the display price from a product.
243
- * Prefers quote-aware price_info, then plain price fields.
244
- *
245
- * @param product - Product with price data
246
- * @returns The final price to display
247
- *
248
- * @example
249
- * const price = getDisplayPrice(product);
250
- * console.log(formatPrice(price, 'GHS')); // "GH₵29.99"
251
- */
252
- declare function getDisplayPrice(product: ProductWithPrice): number;
253
- /**
254
- * Get the base price from a product (before markup/discount)
255
- *
256
- * @param product - Product with price data
257
- * @returns The base price before adjustments
258
- */
259
- declare function getBasePrice(product: ProductWithPrice): number;
260
- /**
261
- * Check if a product is on sale (discounted)
262
- *
263
- * @param product - Product with price data
264
- * @returns True if the final price is less than the base price
265
- *
266
- * @example
267
- * if (isOnSale(product)) {
268
- * return <Badge>Sale!</Badge>;
269
- * }
270
- */
271
- declare function isOnSale(product: ProductWithPrice): boolean;
272
- /**
273
- * Get the discount percentage for a product on sale
274
- *
275
- * @param product - Product with price data
276
- * @returns Discount percentage (0-100), or 0 if not on sale
277
- *
278
- * @example
279
- * const discount = getDiscountPercentage(product);
280
- * if (discount > 0) {
281
- * return <Badge>{discount}% OFF</Badge>;
282
- * }
283
- */
284
- declare function getDiscountPercentage(product: ProductWithPrice): number;
285
- /**
286
- * Get the markup percentage for a product
287
- *
288
- * @param product - Product with price data
289
- * @returns Markup percentage, or 0 if no markup
290
- */
291
- declare function getMarkupPercentage(product: ProductWithPrice): number;
292
- /**
293
- * Get the currency for a product
294
- *
295
- * @param product - Product with price data
296
- * @returns Currency code (default: "GHS")
297
- */
298
- declare function getProductCurrency(product: ProductWithPrice): string;
299
- /**
300
- * Format a product's display price
301
- * Convenience function combining getDisplayPrice and formatPrice
302
- *
303
- * @param product - Product with price data
304
- * @param locale - BCP 47 locale string (default: "en-US")
305
- * @returns Formatted price string
306
- *
307
- * @example
308
- * <span>{formatProductPrice(product)}</span> // "GH₵29.99"
309
- */
310
- declare function formatProductPrice(product: ProductWithPrice, locale?: string): string;
311
-
312
- /**
313
- * Categorize payment errors into user-friendly messages
314
- */
315
- declare function categorizePaymentError(error: Error, errorCode?: string): PaymentErrorDetails;
316
- /**
317
- * Normalize payment response from different formats into a standard PaymentResponse
318
- */
319
- declare function normalizePaymentResponse(response: unknown): PaymentResponse;
320
- declare function isPaymentStatusSuccess(status: string | undefined): boolean;
321
- declare function isPaymentStatusFailure(status: string | undefined): boolean;
322
- declare function isPaymentStatusRequiresAction(status: string | undefined): boolean;
323
- /**
324
- * Normalize payment status response into a standard format
325
- */
326
- declare function normalizeStatusResponse(response: unknown): PaymentStatusResponse;
327
- /** Mobile money provider display names */
328
- declare const MOBILE_MONEY_PROVIDERS: {
329
- readonly mtn: {
330
- readonly name: "MTN Mobile Money";
331
- readonly prefix: readonly ["024", "054", "055", "059"];
332
- };
333
- readonly vodafone: {
334
- readonly name: "Vodafone Cash";
335
- readonly prefix: readonly ["020", "050"];
336
- };
337
- readonly airtel: {
338
- readonly name: "AirtelTigo Money";
339
- readonly prefix: readonly ["027", "057", "026", "056"];
340
- };
341
- };
342
- /**
343
- * Detect mobile money provider from phone number
344
- */
345
- declare function detectMobileMoneyProvider(phoneNumber: string): "mtn" | "vodafone" | "airtel" | null;
1
+ export { ad as AUTHORIZATION_TYPE, ai as AUTH_MUTATION, a2 as AbortablePromise, aV as AddOn, bE as AddOnDetails, b_ as AddOnGroupDetails, aX as AddOnOption, bZ as AddOnOptionDetails, aY as AddOnOptionPrice, aW as AddOnWithOptions, c3 as AddToCartInput, dN as AddressData, ed as AddressInfo, bt as AdjustmentType, ch as AmountToPay, bA as AppliedDiscount, dY as AuthResponse, A as AuthService, m as AuthStatus, ef as AuthenticatedCustomer, eh as AuthenticatedData, dB as AvailabilityCheck, dC as AvailabilityResult, di as AvailableSlot, bz as BenefitType, dl as Booking, dc as BookingRequirementOverride, dk as BookingStatus, dm as BookingWithDetails, cB as BufferTimes, b4 as Bundle, b8 as BundleComponentData, b9 as BundleComponentInfo, b3 as BundlePriceType, b6 as BundleProduct, bJ as BundleSelectionData, bH as BundleSelectionInput, bI as BundleStoredSelection, b5 as BundleSummary, b7 as BundleWithDetails, cQ as Business, d2 as BusinessHours, cP as BusinessPreferences, B as BusinessService, d1 as BusinessSettings, cO as BusinessType, c$ as BusinessWithLocations, a6 as CHECKOUT_MODE, aj as CHECKOUT_MUTATION, a9 as CHECKOUT_STEP, af as CONTACT_TYPE, dr as CancelBookingInput, cv as CancelOrderInput, cD as CancellationPolicy, bO as Cart, bF as CartAddOn, br as CartChannel, bP as CartItem, c0 as CartItemDetails, i as CartOperations, bq as CartStatus, c5 as CartSummary, bQ as CartTotals, b as CatalogueQueries, a_ as Category, d3 as CategoryInfo, a$ as CategorySummary, o as ChangePasswordInput, dp as CheckSlotAvailabilityInput, d$ as CheckoutAddressInfo, e1 as CheckoutCustomerInfo, X as CheckoutFormData, ct as CheckoutInput, J as CheckoutMode, j as CheckoutOperations, N as CheckoutOrderType, V as CheckoutPaymentMethod, Y as CheckoutResult, j as CheckoutService, a0 as CheckoutStatus, a1 as CheckoutStatusContext, W as CheckoutStep, by as ChosenPrice, C as CimplifyClient, a as CimplifyConfig, v as CimplifyElement, u as CimplifyElements, b0 as Collection, b2 as CollectionProduct, b1 as CollectionSummary, bf as ComponentGroup, bg as ComponentGroupWithComponents, bk as ComponentPriceBreakdown, bi as ComponentSelectionInput, bc as ComponentSourceType, bd as Composite, bh as CompositeComponent, bL as CompositePriceBreakdown, bj as CompositePriceResult, ba as CompositePricingMode, bM as CompositeSelectionData, bi as CompositeSelectionInput, bK as CompositeStoredSelection, be as CompositeWithDetails, a5 as ContactType, dJ as CreateAddressInput, dL as CreateMobileMoneyInput, dE as Customer, dF as CustomerAddress, dH as CustomerLinkPreferences, dG as CustomerMobileMoney, cA as CustomerServicePreferences, an as DEFAULT_COUNTRY, am as DEFAULT_CURRENCY, ae as DEVICE_TYPE, dj as DayAvailability, cK as DepositResult, aJ as DepositType, a4 as DeviceType, aI as DigitalProductType, bB as DiscountBreakdown, bC as DiscountDetails, bT as DisplayAddOn, bU as DisplayAddOnOption, bR as DisplayCart, bS as DisplayCartItem, x as ELEMENT_TYPES, E as EVENT_TYPES, ec as ElementAppearance, em as ElementEventHandler, H as ElementEventType, z as ElementOptions, D as ElementType, ei as ElementsCheckoutData, ej as ElementsCheckoutResult, eg as ElementsCustomerInfo, y as ElementsOptions, dP as EnrollAndLinkOrderInput, dS as EnrollAndLinkOrderResult, dM as EnrollmentData, aq as Err, cg as FeeBearerType, F as FetchQuoteInput, ce as FulfillmentLink, cd as FulfillmentStatus, cc as FulfillmentType, e3 as FxQuote, e2 as FxQuoteRequest, e4 as FxRateResponse, r as FxService, dn as GetAvailableSlotsInput, l as GetOrdersOptions, G as GetProductsOptions, bb as GroupPricingBehavior, el as IframeToParentMessage, I as InventoryService, dD as InventorySummary, aG as InventoryType, K as KitchenOrderItem, t as KitchenOrderResult, ah as LINK_MUTATION, ag as LINK_QUERY, bN as LineConfiguration, ci as LineItem, c9 as LineType, dI as LinkData, dR as LinkEnrollResult, L as LinkService, dT as LinkSession, dQ as LinkStatusResult, s as LiteBootstrap, q as LiteService, cT as Location, cN as LocationAppointment, bn as LocationProductPrice, dA as LocationStock, cR as LocationTaxBehavior, cS as LocationTaxOverrides, cW as LocationTimeProfile, d0 as LocationWithDetails, M as MESSAGE_TYPES, ac as MOBILE_MONEY_PROVIDER, dO as MobileMoneyData, e0 as MobileMoneyDetails, a3 as MobileMoneyProvider, al as ORDER_MUTATION, a7 as ORDER_TYPE, eb as ObservabilityHooks, ap as Ok, cj as Order, c8 as OrderChannel, cs as OrderFilter, cf as OrderFulfillmentSummary, cm as OrderGroup, cq as OrderGroupDetails, cn as OrderGroupPayment, cl as OrderGroupPaymentState, cp as OrderGroupPaymentSummary, ck as OrderHistory, ca as OrderLineState, cb as OrderLineStatus, cr as OrderPaymentEvent, O as OrderQueries, co as OrderSplitDetail, c6 as OrderStatus, n as OtpResult, a8 as PAYMENT_METHOD, ak as PAYMENT_MUTATION, aa as PAYMENT_STATE, ab as PICKUP_TIME_TYPE, ek as ParentToIframeMessage, ee as PaymentMethodInfo, c7 as PaymentState, d_ as PickupTime, dZ as PickupTimeType, bm as Price, bu as PriceAdjustment, bx as PriceDecisionPath, bl as PriceEntryType, bw as PricePathTaxInfo, P as PriceQuote, bs as PriceSource, cF as PricingOverrides, $ as ProcessAndResolveOptions, Z as ProcessCheckoutOptions, _ as ProcessCheckoutResult, aL as Product, aZ as ProductAddOn, bo as ProductAvailability, dy as ProductStock, bp as ProductTimeProfile, aF as ProductType, aN as ProductVariant, aS as ProductVariantValue, aM as ProductWithDetails, d as QuoteBundleSelectionInput, Q as QuoteCompositeSelectionInput, f as QuoteDynamicBuckets, e as QuoteStatus, g as QuoteUiMessage, R as RefreshQuoteInput, h as RefreshQuoteResult, cw as RefundOrderInput, cz as ReminderMethod, cC as ReminderSettings, e5 as RequestContext, e8 as RequestErrorEvent, dW as RequestOtpInput, e6 as RequestStartEvent, e7 as RequestSuccessEvent, dq as RescheduleBookingInput, cI as ResourceAssignment, d9 as ResourceAvailabilityException, d8 as ResourceAvailabilityRule, dd as ResourceType, ao as Result, e9 as RetryEvent, dV as RevokeAllSessionsResult, dU as RevokeSessionResult, cY as Room, aK as SalesChannel, cG as SchedulingMetadata, cJ as SchedulingResult, p as SchedulingService, S as SearchOptions, bD as SelectedAddOnOption, de as Service, d5 as ServiceAvailabilityException, ds as ServiceAvailabilityParams, dt as ServiceAvailabilityResult, d4 as ServiceAvailabilityRule, cZ as ServiceCharge, cE as ServiceNotes, cL as ServiceScheduleRequest, db as ServiceStaffRequirement, cx as ServiceStatus, df as ServiceWithStaff, ea as SessionChangeEvent, dg as Staff, cH as StaffAssignment, d7 as StaffAvailabilityException, d6 as StaffAvailabilityRule, da as StaffBookingProfile, cy as StaffRole, cM as StaffScheduleItem, dw as Stock, dx as StockLevel, du as StockOwnershipType, dv as StockStatus, c_ as StorefrontBootstrap, cX as Table, T as TableInfo, bv as TaxPathComponent, cU as TimeRange, cV as TimeRanges, dh as TimeSlot, c1 as UICart, bV as UICartBusiness, bX as UICartCustomer, bW as UICartLocation, bY as UICartPricing, c2 as UICartResponse, dK as UpdateAddressInput, c4 as UpdateCartItemInput, cu as UpdateOrderStatusInput, U as UpdateProfileInput, aP as VariantAxis, aU as VariantAxisSelection, aR as VariantAxisValue, aQ as VariantAxisWithValues, bG as VariantDetails, b$ as VariantDetailsDTO, aO as VariantDisplayAttribute, aT as VariantLocationAvailability, dz as VariantStock, aH as VariantStrategy, dX as VerifyOtpInput, aD as combine, aE as combineObject, c as createCimplifyClient, w as createElements, as as err, ax as flatMap, aB as fromPromise, k as generateIdempotencyKey, ay as getOrElse, au as isErr, at as isOk, aw as mapError, av as mapResult, ar as ok, aA as toNullable, aC as tryCatch, az as unwrap } from './client-CjqNbEM6.js';
2
+ export { QueryBuilder, query } from './advanced.js';
3
+ export { C as CURRENCY_SYMBOLS, x as FormatCompactOptions, F as FormatPriceOptions, M as MOBILE_MONEY_PROVIDERS, P as PriceInfo, w as ProductWithPrice, T as TaxComponent, v as TaxInfo, n as categorizePaymentError, u as detectMobileMoneyProvider, c as formatMoney, d as formatNumberCompact, f as formatPrice, a as formatPriceAdjustment, b as formatPriceCompact, e as formatProductPrice, i as getBasePrice, g as getCurrencySymbol, k as getDiscountPercentage, h as getDisplayPrice, l as getMarkupPercentage, m as getProductCurrency, j as isOnSale, r as isPaymentStatusFailure, s as isPaymentStatusRequiresAction, t as isPaymentStatusSuccess, o as normalizePaymentResponse, q as normalizeStatusResponse, p as parsePrice } from './index-B5Bj-Ikg.js';
4
+ import { A as ApiError } from './payment-D-u3asA8.js';
5
+ export { h as AuthorizationType, c as CimplifyError, C as Currency, E as ErrorCode, b as ErrorCodeType, I as InitializePaymentResult, M as Money, a as Pagination, P as PaginationParams, l as Payment, o as PaymentErrorDetails, k as PaymentMethod, g as PaymentMethodType, j as PaymentProcessingState, f as PaymentProvider, m as PaymentResponse, e as PaymentStatus, n as PaymentStatusResponse, S as SubmitAuthorizationInput, i as isCimplifyError, d as isRetryableError } from './payment-D-u3asA8.js';
6
+ export { c as AdConfig, e as AdContextValue, d as AdCreative, a as AdPosition, A as AdSlot, b as AdTheme } from './ads-t3FBTU8p.js';
346
7
 
347
8
  /** Context sent with every request to scope operations to a specific location/branch */
348
9
  interface FrontendContext {
@@ -374,4 +35,4 @@ interface ApiResponse<T> {
374
35
  metadata?: ResponseMetadata;
375
36
  }
376
37
 
377
- export { ApiError, type ApiResponse, CURRENCY_SYMBOLS, type FormatCompactOptions, type FormatPriceOptions, type FrontendContext, MOBILE_MONEY_PROVIDERS, type MutationRequest, PaymentErrorDetails, PaymentResponse, PaymentStatusResponse, type PriceInfo, type ProductWithPrice, QueryBuilder, type QueryRequest, type ResponseMetadata, type TaxComponent, type TaxInfo, categorizePaymentError, detectMobileMoneyProvider, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getProductCurrency, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, normalizePaymentResponse, normalizeStatusResponse, parsePrice, query };
38
+ export { ApiError, type ApiResponse, type FrontendContext, type MutationRequest, type QueryRequest, type ResponseMetadata };
package/dist/index.js CHANGED
@@ -2533,8 +2533,9 @@ var CimplifyElements = class {
2533
2533
  this.paymentData = null;
2534
2534
  this.checkoutInProgress = false;
2535
2535
  this.activeCheckoutAbort = null;
2536
+ this.businessIdResolvePromise = null;
2536
2537
  this.client = client;
2537
- this.businessId = businessId;
2538
+ this.businessId = businessId ?? null;
2538
2539
  this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2539
2540
  this.options = options;
2540
2541
  this.boundHandleMessage = this.handleMessage.bind(this);
@@ -2757,6 +2758,24 @@ var CimplifyElements = class {
2757
2758
  getPublicKey() {
2758
2759
  return this.client.getPublicKey();
2759
2760
  }
2761
+ getBusinessId() {
2762
+ return this.businessId;
2763
+ }
2764
+ async resolveBusinessId() {
2765
+ if (this.businessId) {
2766
+ return this.businessId;
2767
+ }
2768
+ if (this.businessIdResolvePromise) {
2769
+ return this.businessIdResolvePromise;
2770
+ }
2771
+ this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
2772
+ this.businessId = resolvedBusinessId;
2773
+ return resolvedBusinessId;
2774
+ }).catch(() => null).finally(() => {
2775
+ this.businessIdResolvePromise = null;
2776
+ });
2777
+ return this.businessIdResolvePromise;
2778
+ }
2760
2779
  getAppearance() {
2761
2780
  return this.options.appearance;
2762
2781
  }
@@ -2861,8 +2880,8 @@ var CimplifyElement = class {
2861
2880
  return;
2862
2881
  }
2863
2882
  this.container = target;
2864
- this.createIframe();
2865
2883
  this.mounted = true;
2884
+ void this.createIframe();
2866
2885
  }
2867
2886
  destroy() {
2868
2887
  if (this.iframe) {
@@ -2916,11 +2935,21 @@ var CimplifyElement = class {
2916
2935
  isMounted() {
2917
2936
  return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
2918
2937
  }
2919
- createIframe() {
2938
+ async createIframe() {
2920
2939
  if (!this.container) return;
2940
+ const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
2941
+ if (!resolvedBusinessId || !this.container || !this.mounted) {
2942
+ console.error("Unable to mount element without a resolved business ID");
2943
+ this.emit(EVENT_TYPES.ERROR, {
2944
+ code: "BUSINESS_ID_REQUIRED",
2945
+ message: "Unable to initialize checkout without a business ID."
2946
+ });
2947
+ return;
2948
+ }
2949
+ this.businessId = resolvedBusinessId;
2921
2950
  const iframe = document.createElement("iframe");
2922
2951
  const url = new URL(`${this.linkUrl}/elements/${this.type}`);
2923
- url.searchParams.set("businessId", this.businessId);
2952
+ url.searchParams.set("businessId", resolvedBusinessId);
2924
2953
  if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
2925
2954
  if (this.options.mode) url.searchParams.set("mode", this.options.mode);
2926
2955
  iframe.src = url.toString();
@@ -2940,7 +2969,7 @@ var CimplifyElement = class {
2940
2969
  const publicKey = this.parent.getPublicKey();
2941
2970
  this.sendMessage({
2942
2971
  type: MESSAGE_TYPES.INIT,
2943
- businessId: this.businessId,
2972
+ businessId: resolvedBusinessId,
2944
2973
  publicKey,
2945
2974
  demoMode: publicKey.length === 0,
2946
2975
  prefillEmail: this.options.prefillEmail,
@@ -3085,6 +3114,8 @@ var CimplifyClient = class {
3085
3114
  constructor(config = {}) {
3086
3115
  this.accessToken = null;
3087
3116
  this.context = {};
3117
+ this.businessId = null;
3118
+ this.businessIdResolvePromise = null;
3088
3119
  this.inflightRequests = /* @__PURE__ */ new Map();
3089
3120
  this.publicKey = config.publicKey || getEnvPublicKey() || "";
3090
3121
  const urls = deriveUrls();
@@ -3148,6 +3179,47 @@ var CimplifyClient = class {
3148
3179
  getLocationId() {
3149
3180
  return this.context.location_id ?? null;
3150
3181
  }
3182
+ /** Cache a resolved business ID for future element/checkouts initialization. */
3183
+ setBusinessId(businessId) {
3184
+ const normalized = businessId.trim();
3185
+ if (!normalized) {
3186
+ return;
3187
+ }
3188
+ this.businessId = normalized;
3189
+ }
3190
+ /** Get cached business ID if available. */
3191
+ getBusinessId() {
3192
+ return this.businessId;
3193
+ }
3194
+ /**
3195
+ * Resolve business ID from public key once and cache it.
3196
+ * Subsequent calls return the cached value (or shared in-flight promise).
3197
+ */
3198
+ async resolveBusinessId() {
3199
+ if (this.businessId) {
3200
+ return this.businessId;
3201
+ }
3202
+ if (this.businessIdResolvePromise) {
3203
+ return this.businessIdResolvePromise;
3204
+ }
3205
+ this.businessIdResolvePromise = (async () => {
3206
+ const result = await this.business.getInfo();
3207
+ if (!result.ok || !result.value?.id) {
3208
+ throw new CimplifyError(
3209
+ ErrorCode.NOT_FOUND,
3210
+ "Unable to resolve business ID from the current public key.",
3211
+ true
3212
+ );
3213
+ }
3214
+ this.businessId = result.value.id;
3215
+ return result.value.id;
3216
+ })();
3217
+ try {
3218
+ return await this.businessIdResolvePromise;
3219
+ } finally {
3220
+ this.businessIdResolvePromise = null;
3221
+ }
3222
+ }
3151
3223
  loadAccessToken() {
3152
3224
  if (typeof window !== "undefined" && window.localStorage) {
3153
3225
  return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
@@ -3465,7 +3537,10 @@ var CimplifyClient = class {
3465
3537
  * ```
3466
3538
  */
3467
3539
  elements(businessId, options) {
3468
- return createElements(this, businessId, options);
3540
+ if (businessId) {
3541
+ this.setBusinessId(businessId);
3542
+ }
3543
+ return createElements(this, businessId ?? this.businessId ?? void 0, options);
3469
3544
  }
3470
3545
  };
3471
3546
  function createCimplifyClient(config = {}) {
package/dist/index.mjs CHANGED
@@ -2531,8 +2531,9 @@ var CimplifyElements = class {
2531
2531
  this.paymentData = null;
2532
2532
  this.checkoutInProgress = false;
2533
2533
  this.activeCheckoutAbort = null;
2534
+ this.businessIdResolvePromise = null;
2534
2535
  this.client = client;
2535
- this.businessId = businessId;
2536
+ this.businessId = businessId ?? null;
2536
2537
  this.linkUrl = options.linkUrl || DEFAULT_LINK_URL;
2537
2538
  this.options = options;
2538
2539
  this.boundHandleMessage = this.handleMessage.bind(this);
@@ -2755,6 +2756,24 @@ var CimplifyElements = class {
2755
2756
  getPublicKey() {
2756
2757
  return this.client.getPublicKey();
2757
2758
  }
2759
+ getBusinessId() {
2760
+ return this.businessId;
2761
+ }
2762
+ async resolveBusinessId() {
2763
+ if (this.businessId) {
2764
+ return this.businessId;
2765
+ }
2766
+ if (this.businessIdResolvePromise) {
2767
+ return this.businessIdResolvePromise;
2768
+ }
2769
+ this.businessIdResolvePromise = this.client.resolveBusinessId().then((resolvedBusinessId) => {
2770
+ this.businessId = resolvedBusinessId;
2771
+ return resolvedBusinessId;
2772
+ }).catch(() => null).finally(() => {
2773
+ this.businessIdResolvePromise = null;
2774
+ });
2775
+ return this.businessIdResolvePromise;
2776
+ }
2758
2777
  getAppearance() {
2759
2778
  return this.options.appearance;
2760
2779
  }
@@ -2859,8 +2878,8 @@ var CimplifyElement = class {
2859
2878
  return;
2860
2879
  }
2861
2880
  this.container = target;
2862
- this.createIframe();
2863
2881
  this.mounted = true;
2882
+ void this.createIframe();
2864
2883
  }
2865
2884
  destroy() {
2866
2885
  if (this.iframe) {
@@ -2914,11 +2933,21 @@ var CimplifyElement = class {
2914
2933
  isMounted() {
2915
2934
  return this.mounted && Boolean(this.iframe) && this.iframe?.isConnected === true;
2916
2935
  }
2917
- createIframe() {
2936
+ async createIframe() {
2918
2937
  if (!this.container) return;
2938
+ const resolvedBusinessId = this.businessId ?? await this.parent.resolveBusinessId();
2939
+ if (!resolvedBusinessId || !this.container || !this.mounted) {
2940
+ console.error("Unable to mount element without a resolved business ID");
2941
+ this.emit(EVENT_TYPES.ERROR, {
2942
+ code: "BUSINESS_ID_REQUIRED",
2943
+ message: "Unable to initialize checkout without a business ID."
2944
+ });
2945
+ return;
2946
+ }
2947
+ this.businessId = resolvedBusinessId;
2919
2948
  const iframe = document.createElement("iframe");
2920
2949
  const url = new URL(`${this.linkUrl}/elements/${this.type}`);
2921
- url.searchParams.set("businessId", this.businessId);
2950
+ url.searchParams.set("businessId", resolvedBusinessId);
2922
2951
  if (this.options.prefillEmail) url.searchParams.set("email", this.options.prefillEmail);
2923
2952
  if (this.options.mode) url.searchParams.set("mode", this.options.mode);
2924
2953
  iframe.src = url.toString();
@@ -2938,7 +2967,7 @@ var CimplifyElement = class {
2938
2967
  const publicKey = this.parent.getPublicKey();
2939
2968
  this.sendMessage({
2940
2969
  type: MESSAGE_TYPES.INIT,
2941
- businessId: this.businessId,
2970
+ businessId: resolvedBusinessId,
2942
2971
  publicKey,
2943
2972
  demoMode: publicKey.length === 0,
2944
2973
  prefillEmail: this.options.prefillEmail,
@@ -3083,6 +3112,8 @@ var CimplifyClient = class {
3083
3112
  constructor(config = {}) {
3084
3113
  this.accessToken = null;
3085
3114
  this.context = {};
3115
+ this.businessId = null;
3116
+ this.businessIdResolvePromise = null;
3086
3117
  this.inflightRequests = /* @__PURE__ */ new Map();
3087
3118
  this.publicKey = config.publicKey || getEnvPublicKey() || "";
3088
3119
  const urls = deriveUrls();
@@ -3146,6 +3177,47 @@ var CimplifyClient = class {
3146
3177
  getLocationId() {
3147
3178
  return this.context.location_id ?? null;
3148
3179
  }
3180
+ /** Cache a resolved business ID for future element/checkouts initialization. */
3181
+ setBusinessId(businessId) {
3182
+ const normalized = businessId.trim();
3183
+ if (!normalized) {
3184
+ return;
3185
+ }
3186
+ this.businessId = normalized;
3187
+ }
3188
+ /** Get cached business ID if available. */
3189
+ getBusinessId() {
3190
+ return this.businessId;
3191
+ }
3192
+ /**
3193
+ * Resolve business ID from public key once and cache it.
3194
+ * Subsequent calls return the cached value (or shared in-flight promise).
3195
+ */
3196
+ async resolveBusinessId() {
3197
+ if (this.businessId) {
3198
+ return this.businessId;
3199
+ }
3200
+ if (this.businessIdResolvePromise) {
3201
+ return this.businessIdResolvePromise;
3202
+ }
3203
+ this.businessIdResolvePromise = (async () => {
3204
+ const result = await this.business.getInfo();
3205
+ if (!result.ok || !result.value?.id) {
3206
+ throw new CimplifyError(
3207
+ ErrorCode.NOT_FOUND,
3208
+ "Unable to resolve business ID from the current public key.",
3209
+ true
3210
+ );
3211
+ }
3212
+ this.businessId = result.value.id;
3213
+ return result.value.id;
3214
+ })();
3215
+ try {
3216
+ return await this.businessIdResolvePromise;
3217
+ } finally {
3218
+ this.businessIdResolvePromise = null;
3219
+ }
3220
+ }
3149
3221
  loadAccessToken() {
3150
3222
  if (typeof window !== "undefined" && window.localStorage) {
3151
3223
  return localStorage.getItem(ACCESS_TOKEN_STORAGE_KEY);
@@ -3463,7 +3535,10 @@ var CimplifyClient = class {
3463
3535
  * ```
3464
3536
  */
3465
3537
  elements(businessId, options) {
3466
- return createElements(this, businessId, options);
3538
+ if (businessId) {
3539
+ this.setBusinessId(businessId);
3540
+ }
3541
+ return createElements(this, businessId ?? this.businessId ?? void 0, options);
3467
3542
  }
3468
3543
  };
3469
3544
  function createCimplifyClient(config = {}) {