omni-sync-sdk 0.16.0 → 0.16.2

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/LICENSE ADDED
File without changes
package/dist/index.d.mts CHANGED
@@ -125,9 +125,12 @@ interface Product {
125
125
  description?: string | null;
126
126
  descriptionFormat?: 'text' | 'html' | 'markdown';
127
127
  sku: string;
128
- basePrice: number;
129
- salePrice?: number | null;
130
- costPrice?: number | null;
128
+ /** Base price as string (e.g., "29.99"). Use parseFloat() for calculations. */
129
+ basePrice: string;
130
+ /** Sale price as string. Use parseFloat() for calculations. */
131
+ salePrice?: string | null;
132
+ /** Cost price as string. Use parseFloat() for calculations. */
133
+ costPrice?: string | null;
131
134
  status: 'active' | 'draft' | 'archived';
132
135
  type: 'SIMPLE' | 'VARIABLE';
133
136
  isDownloadable?: boolean;
@@ -150,9 +153,12 @@ interface ProductVariant {
150
153
  id: string;
151
154
  sku?: string | null;
152
155
  name?: string | null;
153
- price?: number | null;
154
- salePrice?: number | null;
155
- attributes?: Record<string, string>;
156
+ /** Variant price as string. Use parseFloat() for calculations. */
157
+ price?: string | null;
158
+ /** Variant sale price as string. Use parseFloat() for calculations. */
159
+ salePrice?: string | null;
160
+ /** Variant attributes (e.g., { "Color": "Red", "Size": "M" }) */
161
+ attributes?: Record<string, unknown>;
156
162
  inventory?: InventoryInfo | null;
157
163
  }
158
164
  /**
@@ -351,8 +357,10 @@ interface ProductSuggestion {
351
357
  name: string;
352
358
  slug: string | null;
353
359
  image: string | null;
354
- basePrice: number;
355
- salePrice?: number | null;
360
+ /** Base price as string. Use parseFloat() for calculations. */
361
+ basePrice: string;
362
+ /** Sale price as string. Use parseFloat() for calculations. */
363
+ salePrice?: string | null;
356
364
  type: 'SIMPLE' | 'VARIABLE';
357
365
  }
358
366
  /**
@@ -667,6 +675,41 @@ interface CustomerAddress {
667
675
  createdAt: string;
668
676
  updatedAt: string;
669
677
  }
678
+ /**
679
+ * Pre-fill data for checkout forms when customer is logged in.
680
+ * Use getCheckoutPrefillData() to retrieve this data.
681
+ */
682
+ interface CheckoutPrefillData {
683
+ /** Customer profile information */
684
+ customer: {
685
+ id: string;
686
+ email: string;
687
+ firstName?: string;
688
+ lastName?: string;
689
+ phone?: string;
690
+ emailVerified: boolean;
691
+ };
692
+ /** Customer's default address (if any) */
693
+ defaultAddress: CustomerAddress | null;
694
+ /**
695
+ * Pre-formatted address data ready to pass to setShippingAddress().
696
+ * Combines customer email with default address fields.
697
+ * Null if customer has no saved addresses.
698
+ */
699
+ shippingAddress: {
700
+ email: string;
701
+ firstName: string;
702
+ lastName: string;
703
+ company?: string;
704
+ line1: string;
705
+ line2?: string;
706
+ city: string;
707
+ region?: string;
708
+ postalCode: string;
709
+ country: string;
710
+ phone?: string;
711
+ } | null;
712
+ }
670
713
  interface CreateCustomerDto {
671
714
  email: string;
672
715
  phone?: string;
@@ -832,7 +875,7 @@ interface CartItem {
832
875
  id: string;
833
876
  name: string;
834
877
  sku: string;
835
- images?: unknown[];
878
+ images?: ProductImage[];
836
879
  };
837
880
  /**
838
881
  * Nested variant information (null for simple products).
@@ -842,7 +885,7 @@ interface CartItem {
842
885
  id: string;
843
886
  name?: string | null;
844
887
  sku?: string | null;
845
- image?: unknown;
888
+ image?: ProductImage | string | null;
846
889
  } | null;
847
890
  /** ISO timestamp when item was added */
848
891
  createdAt: string;
@@ -1194,7 +1237,7 @@ interface CheckoutLineItem {
1194
1237
  id: string;
1195
1238
  name: string;
1196
1239
  sku: string;
1197
- images?: unknown[];
1240
+ images?: ProductImage[];
1198
1241
  };
1199
1242
  /**
1200
1243
  * Nested variant information (null for simple products).
@@ -1204,6 +1247,7 @@ interface CheckoutLineItem {
1204
1247
  id: string;
1205
1248
  name?: string | null;
1206
1249
  sku?: string | null;
1250
+ image?: ProductImage | string | null;
1207
1251
  } | null;
1208
1252
  }
1209
1253
  /**
@@ -1293,7 +1337,7 @@ interface ShippingRate {
1293
1337
  * console.log(`Total: $${total.toFixed(2)}`);
1294
1338
  *
1295
1339
  * // Access line items (nested structure)
1296
- * checkout.items.forEach(item => {
1340
+ * checkout.lineItems.forEach(item => {
1297
1341
  * console.log(item.product.name, item.quantity);
1298
1342
  * });
1299
1343
  * ```
@@ -1339,7 +1383,7 @@ interface Checkout {
1339
1383
  /** Applied coupon code */
1340
1384
  couponCode?: string | null;
1341
1385
  /** Line items with nested product/variant data */
1342
- items: CheckoutLineItem[];
1386
+ lineItems: CheckoutLineItem[];
1343
1387
  /** Total item count */
1344
1388
  itemCount: number;
1345
1389
  /** Available shipping rates (after address is set) */
@@ -1950,6 +1994,7 @@ declare class OmniSyncClient {
1950
1994
  private readonly baseUrl;
1951
1995
  private readonly timeout;
1952
1996
  private customerToken;
1997
+ private customerCartId;
1953
1998
  private readonly onAuthError?;
1954
1999
  constructor(options: OmniSyncClientOptions);
1955
2000
  /**
@@ -2992,6 +3037,113 @@ declare class OmniSyncClient {
2992
3037
  * ```
2993
3038
  */
2994
3039
  mergeCarts(data: MergeCartsDto): Promise<Cart>;
3040
+ /**
3041
+ * Check if customer is currently authenticated
3042
+ * Used internally by smart cart methods to determine storage strategy
3043
+ *
3044
+ * @example
3045
+ * ```typescript
3046
+ * if (omni.isCustomerLoggedIn()) {
3047
+ * console.log('Cart will be stored on server');
3048
+ * } else {
3049
+ * console.log('Cart will be stored in localStorage');
3050
+ * }
3051
+ * ```
3052
+ */
3053
+ isCustomerLoggedIn(): boolean;
3054
+ /**
3055
+ * Get or create a server cart for the logged-in customer
3056
+ * Caches the cart ID for subsequent calls
3057
+ * @internal
3058
+ */
3059
+ private getOrCreateCustomerCart;
3060
+ /**
3061
+ * Smart add to cart - automatically uses localStorage or server based on auth state
3062
+ *
3063
+ * - **Guest (not logged in)**: Stores in localStorage
3064
+ * - **Logged in**: Stores on server (database)
3065
+ *
3066
+ * @example
3067
+ * ```typescript
3068
+ * // Works the same whether logged in or not
3069
+ * await omni.smartAddToCart({
3070
+ * productId: 'prod_123',
3071
+ * quantity: 2,
3072
+ * name: 'Cool Product', // Optional: for localStorage display
3073
+ * price: '29.99',
3074
+ * });
3075
+ * ```
3076
+ */
3077
+ smartAddToCart(item: Omit<LocalCartItem, 'addedAt'>): Promise<Cart | LocalCart>;
3078
+ /**
3079
+ * Smart get cart - returns server cart if logged in, localStorage if guest
3080
+ *
3081
+ * @example
3082
+ * ```typescript
3083
+ * const cart = await omni.smartGetCart();
3084
+ * console.log('Items:', cart.items.length);
3085
+ * ```
3086
+ */
3087
+ smartGetCart(): Promise<Cart | LocalCart>;
3088
+ /**
3089
+ * Smart update cart item quantity
3090
+ *
3091
+ * @example
3092
+ * ```typescript
3093
+ * await omni.smartUpdateCartItem('prod_123', 3); // Set quantity to 3
3094
+ * await omni.smartUpdateCartItem('prod_123', 0); // Remove item
3095
+ * ```
3096
+ */
3097
+ smartUpdateCartItem(productId: string, quantity: number, variantId?: string): Promise<Cart | LocalCart>;
3098
+ /**
3099
+ * Smart remove from cart
3100
+ *
3101
+ * @example
3102
+ * ```typescript
3103
+ * await omni.smartRemoveFromCart('prod_123');
3104
+ * await omni.smartRemoveFromCart('prod_456', 'variant_789');
3105
+ * ```
3106
+ */
3107
+ smartRemoveFromCart(productId: string, variantId?: string): Promise<Cart | LocalCart>;
3108
+ /**
3109
+ * Sync local cart to server on login
3110
+ *
3111
+ * Call this AFTER setCustomerToken() when a customer logs in.
3112
+ * This will:
3113
+ * 1. Get or create a server cart for the customer
3114
+ * 2. Add all items from localStorage to the server cart (merging with existing)
3115
+ * 3. Clear localStorage
3116
+ *
3117
+ * Items that fail to sync (e.g., out of stock) are silently skipped.
3118
+ *
3119
+ * @example
3120
+ * ```typescript
3121
+ * // Customer logs in
3122
+ * const auth = await omni.login(email, password);
3123
+ * omni.setCustomerToken(auth.token);
3124
+ *
3125
+ * // Sync their local cart to server
3126
+ * const cart = await omni.syncCartOnLogin();
3127
+ * console.log('Cart synced, items:', cart.items.length);
3128
+ * ```
3129
+ */
3130
+ syncCartOnLogin(): Promise<Cart>;
3131
+ /**
3132
+ * Clear cart state on logout
3133
+ *
3134
+ * Call this when a customer logs out to clear the cached cart ID.
3135
+ * The localStorage cart remains available for the next guest session.
3136
+ *
3137
+ * @example
3138
+ * ```typescript
3139
+ * omni.clearCustomerToken();
3140
+ * omni.onLogout();
3141
+ *
3142
+ * // Now back to guest mode - cart uses localStorage
3143
+ * await omni.smartAddToCart({ productId: 'prod_123', quantity: 1 });
3144
+ * ```
3145
+ */
3146
+ onLogout(): void;
2995
3147
  /**
2996
3148
  * Create a checkout from a cart
2997
3149
  * Starts the checkout process and returns checkout with available options
@@ -3486,6 +3638,28 @@ declare class OmniSyncClient {
3486
3638
  * ```
3487
3639
  */
3488
3640
  getMyProfile(): Promise<CustomerProfile>;
3641
+ /**
3642
+ * Get pre-fill data for checkout forms (requires customerToken).
3643
+ * Returns customer profile and default address formatted for checkout.
3644
+ * Use this to pre-populate shipping forms for logged-in customers.
3645
+ *
3646
+ * @example
3647
+ * ```typescript
3648
+ * omni.setCustomerToken(auth.token);
3649
+ *
3650
+ * const prefill = await omni.getCheckoutPrefillData();
3651
+ *
3652
+ * if (prefill.shippingAddress) {
3653
+ * // Pre-fill shipping form with customer's default address
3654
+ * setFormValues(prefill.shippingAddress);
3655
+ * } else {
3656
+ * // Customer has no saved addresses, show empty form
3657
+ * // But still pre-fill email from customer profile
3658
+ * setFormValues({ email: prefill.customer.email });
3659
+ * }
3660
+ * ```
3661
+ */
3662
+ getCheckoutPrefillData(): Promise<CheckoutPrefillData>;
3489
3663
  /**
3490
3664
  * Update the current customer's profile (requires customerToken)
3491
3665
  * Only available in storefront mode
@@ -3749,4 +3923,4 @@ declare function isWebhookEventType(event: WebhookEvent, type: WebhookEventType)
3749
3923
  */
3750
3924
  declare function createWebhookHandler(handlers: Partial<Record<WebhookEventType, (event: WebhookEvent) => Promise<void>>>): (payload: unknown) => Promise<void>;
3751
3925
 
3752
- export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartItem, type CartStatus, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutLineItem, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateGuestOrderDto, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DraftLineItem, type EditInventoryDto, type EmailVerificationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventorySyncStatus, type LocalCart, type LocalCartItem, type MergeCartsDto, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProvidersResponse, type OmniSyncApiError, OmniSyncClient, type OmniSyncClientOptions, OmniSyncError, type Order, type OrderAddress, type OrderCustomer, type OrderItem, type OrderQueryParams, type OrderStatus, type PaginatedResponse, type PaymentConfig, type PaymentIntent, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PlatformCouponCapabilities, type Product, type ProductAttributeInput, type ProductImage, type ProductQueryParams, type ProductSuggestion, type ProductVariant, type PublishProductResponse, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type SearchSuggestions, type SelectShippingMethodDto, type SendInvoiceDto, type SetBillingAddressDto, type SetCheckoutCustomerDto, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingLine, type ShippingRate, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type SyncJob, type UpdateAddressDto, type UpdateCartItemDto, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateInventoryDto, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateVariantDto, type UpdateVariantInventoryDto, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, formatPrice, getDescriptionContent, formatPrice as getPriceDisplay, getStockStatus, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
3926
+ export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartItem, type CartStatus, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateGuestOrderDto, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DraftLineItem, type EditInventoryDto, type EmailVerificationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventorySyncStatus, type LocalCart, type LocalCartItem, type MergeCartsDto, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProvidersResponse, type OmniSyncApiError, OmniSyncClient, type OmniSyncClientOptions, OmniSyncError, type Order, type OrderAddress, type OrderCustomer, type OrderItem, type OrderQueryParams, type OrderStatus, type PaginatedResponse, type PaymentConfig, type PaymentIntent, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PlatformCouponCapabilities, type Product, type ProductAttributeInput, type ProductImage, type ProductQueryParams, type ProductSuggestion, type ProductVariant, type PublishProductResponse, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type SearchSuggestions, type SelectShippingMethodDto, type SendInvoiceDto, type SetBillingAddressDto, type SetCheckoutCustomerDto, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingLine, type ShippingRate, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type SyncJob, type UpdateAddressDto, type UpdateCartItemDto, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateInventoryDto, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateVariantDto, type UpdateVariantInventoryDto, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, formatPrice, getDescriptionContent, formatPrice as getPriceDisplay, getStockStatus, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
package/dist/index.d.ts CHANGED
@@ -125,9 +125,12 @@ interface Product {
125
125
  description?: string | null;
126
126
  descriptionFormat?: 'text' | 'html' | 'markdown';
127
127
  sku: string;
128
- basePrice: number;
129
- salePrice?: number | null;
130
- costPrice?: number | null;
128
+ /** Base price as string (e.g., "29.99"). Use parseFloat() for calculations. */
129
+ basePrice: string;
130
+ /** Sale price as string. Use parseFloat() for calculations. */
131
+ salePrice?: string | null;
132
+ /** Cost price as string. Use parseFloat() for calculations. */
133
+ costPrice?: string | null;
131
134
  status: 'active' | 'draft' | 'archived';
132
135
  type: 'SIMPLE' | 'VARIABLE';
133
136
  isDownloadable?: boolean;
@@ -150,9 +153,12 @@ interface ProductVariant {
150
153
  id: string;
151
154
  sku?: string | null;
152
155
  name?: string | null;
153
- price?: number | null;
154
- salePrice?: number | null;
155
- attributes?: Record<string, string>;
156
+ /** Variant price as string. Use parseFloat() for calculations. */
157
+ price?: string | null;
158
+ /** Variant sale price as string. Use parseFloat() for calculations. */
159
+ salePrice?: string | null;
160
+ /** Variant attributes (e.g., { "Color": "Red", "Size": "M" }) */
161
+ attributes?: Record<string, unknown>;
156
162
  inventory?: InventoryInfo | null;
157
163
  }
158
164
  /**
@@ -351,8 +357,10 @@ interface ProductSuggestion {
351
357
  name: string;
352
358
  slug: string | null;
353
359
  image: string | null;
354
- basePrice: number;
355
- salePrice?: number | null;
360
+ /** Base price as string. Use parseFloat() for calculations. */
361
+ basePrice: string;
362
+ /** Sale price as string. Use parseFloat() for calculations. */
363
+ salePrice?: string | null;
356
364
  type: 'SIMPLE' | 'VARIABLE';
357
365
  }
358
366
  /**
@@ -667,6 +675,41 @@ interface CustomerAddress {
667
675
  createdAt: string;
668
676
  updatedAt: string;
669
677
  }
678
+ /**
679
+ * Pre-fill data for checkout forms when customer is logged in.
680
+ * Use getCheckoutPrefillData() to retrieve this data.
681
+ */
682
+ interface CheckoutPrefillData {
683
+ /** Customer profile information */
684
+ customer: {
685
+ id: string;
686
+ email: string;
687
+ firstName?: string;
688
+ lastName?: string;
689
+ phone?: string;
690
+ emailVerified: boolean;
691
+ };
692
+ /** Customer's default address (if any) */
693
+ defaultAddress: CustomerAddress | null;
694
+ /**
695
+ * Pre-formatted address data ready to pass to setShippingAddress().
696
+ * Combines customer email with default address fields.
697
+ * Null if customer has no saved addresses.
698
+ */
699
+ shippingAddress: {
700
+ email: string;
701
+ firstName: string;
702
+ lastName: string;
703
+ company?: string;
704
+ line1: string;
705
+ line2?: string;
706
+ city: string;
707
+ region?: string;
708
+ postalCode: string;
709
+ country: string;
710
+ phone?: string;
711
+ } | null;
712
+ }
670
713
  interface CreateCustomerDto {
671
714
  email: string;
672
715
  phone?: string;
@@ -832,7 +875,7 @@ interface CartItem {
832
875
  id: string;
833
876
  name: string;
834
877
  sku: string;
835
- images?: unknown[];
878
+ images?: ProductImage[];
836
879
  };
837
880
  /**
838
881
  * Nested variant information (null for simple products).
@@ -842,7 +885,7 @@ interface CartItem {
842
885
  id: string;
843
886
  name?: string | null;
844
887
  sku?: string | null;
845
- image?: unknown;
888
+ image?: ProductImage | string | null;
846
889
  } | null;
847
890
  /** ISO timestamp when item was added */
848
891
  createdAt: string;
@@ -1194,7 +1237,7 @@ interface CheckoutLineItem {
1194
1237
  id: string;
1195
1238
  name: string;
1196
1239
  sku: string;
1197
- images?: unknown[];
1240
+ images?: ProductImage[];
1198
1241
  };
1199
1242
  /**
1200
1243
  * Nested variant information (null for simple products).
@@ -1204,6 +1247,7 @@ interface CheckoutLineItem {
1204
1247
  id: string;
1205
1248
  name?: string | null;
1206
1249
  sku?: string | null;
1250
+ image?: ProductImage | string | null;
1207
1251
  } | null;
1208
1252
  }
1209
1253
  /**
@@ -1293,7 +1337,7 @@ interface ShippingRate {
1293
1337
  * console.log(`Total: $${total.toFixed(2)}`);
1294
1338
  *
1295
1339
  * // Access line items (nested structure)
1296
- * checkout.items.forEach(item => {
1340
+ * checkout.lineItems.forEach(item => {
1297
1341
  * console.log(item.product.name, item.quantity);
1298
1342
  * });
1299
1343
  * ```
@@ -1339,7 +1383,7 @@ interface Checkout {
1339
1383
  /** Applied coupon code */
1340
1384
  couponCode?: string | null;
1341
1385
  /** Line items with nested product/variant data */
1342
- items: CheckoutLineItem[];
1386
+ lineItems: CheckoutLineItem[];
1343
1387
  /** Total item count */
1344
1388
  itemCount: number;
1345
1389
  /** Available shipping rates (after address is set) */
@@ -1950,6 +1994,7 @@ declare class OmniSyncClient {
1950
1994
  private readonly baseUrl;
1951
1995
  private readonly timeout;
1952
1996
  private customerToken;
1997
+ private customerCartId;
1953
1998
  private readonly onAuthError?;
1954
1999
  constructor(options: OmniSyncClientOptions);
1955
2000
  /**
@@ -2992,6 +3037,113 @@ declare class OmniSyncClient {
2992
3037
  * ```
2993
3038
  */
2994
3039
  mergeCarts(data: MergeCartsDto): Promise<Cart>;
3040
+ /**
3041
+ * Check if customer is currently authenticated
3042
+ * Used internally by smart cart methods to determine storage strategy
3043
+ *
3044
+ * @example
3045
+ * ```typescript
3046
+ * if (omni.isCustomerLoggedIn()) {
3047
+ * console.log('Cart will be stored on server');
3048
+ * } else {
3049
+ * console.log('Cart will be stored in localStorage');
3050
+ * }
3051
+ * ```
3052
+ */
3053
+ isCustomerLoggedIn(): boolean;
3054
+ /**
3055
+ * Get or create a server cart for the logged-in customer
3056
+ * Caches the cart ID for subsequent calls
3057
+ * @internal
3058
+ */
3059
+ private getOrCreateCustomerCart;
3060
+ /**
3061
+ * Smart add to cart - automatically uses localStorage or server based on auth state
3062
+ *
3063
+ * - **Guest (not logged in)**: Stores in localStorage
3064
+ * - **Logged in**: Stores on server (database)
3065
+ *
3066
+ * @example
3067
+ * ```typescript
3068
+ * // Works the same whether logged in or not
3069
+ * await omni.smartAddToCart({
3070
+ * productId: 'prod_123',
3071
+ * quantity: 2,
3072
+ * name: 'Cool Product', // Optional: for localStorage display
3073
+ * price: '29.99',
3074
+ * });
3075
+ * ```
3076
+ */
3077
+ smartAddToCart(item: Omit<LocalCartItem, 'addedAt'>): Promise<Cart | LocalCart>;
3078
+ /**
3079
+ * Smart get cart - returns server cart if logged in, localStorage if guest
3080
+ *
3081
+ * @example
3082
+ * ```typescript
3083
+ * const cart = await omni.smartGetCart();
3084
+ * console.log('Items:', cart.items.length);
3085
+ * ```
3086
+ */
3087
+ smartGetCart(): Promise<Cart | LocalCart>;
3088
+ /**
3089
+ * Smart update cart item quantity
3090
+ *
3091
+ * @example
3092
+ * ```typescript
3093
+ * await omni.smartUpdateCartItem('prod_123', 3); // Set quantity to 3
3094
+ * await omni.smartUpdateCartItem('prod_123', 0); // Remove item
3095
+ * ```
3096
+ */
3097
+ smartUpdateCartItem(productId: string, quantity: number, variantId?: string): Promise<Cart | LocalCart>;
3098
+ /**
3099
+ * Smart remove from cart
3100
+ *
3101
+ * @example
3102
+ * ```typescript
3103
+ * await omni.smartRemoveFromCart('prod_123');
3104
+ * await omni.smartRemoveFromCart('prod_456', 'variant_789');
3105
+ * ```
3106
+ */
3107
+ smartRemoveFromCart(productId: string, variantId?: string): Promise<Cart | LocalCart>;
3108
+ /**
3109
+ * Sync local cart to server on login
3110
+ *
3111
+ * Call this AFTER setCustomerToken() when a customer logs in.
3112
+ * This will:
3113
+ * 1. Get or create a server cart for the customer
3114
+ * 2. Add all items from localStorage to the server cart (merging with existing)
3115
+ * 3. Clear localStorage
3116
+ *
3117
+ * Items that fail to sync (e.g., out of stock) are silently skipped.
3118
+ *
3119
+ * @example
3120
+ * ```typescript
3121
+ * // Customer logs in
3122
+ * const auth = await omni.login(email, password);
3123
+ * omni.setCustomerToken(auth.token);
3124
+ *
3125
+ * // Sync their local cart to server
3126
+ * const cart = await omni.syncCartOnLogin();
3127
+ * console.log('Cart synced, items:', cart.items.length);
3128
+ * ```
3129
+ */
3130
+ syncCartOnLogin(): Promise<Cart>;
3131
+ /**
3132
+ * Clear cart state on logout
3133
+ *
3134
+ * Call this when a customer logs out to clear the cached cart ID.
3135
+ * The localStorage cart remains available for the next guest session.
3136
+ *
3137
+ * @example
3138
+ * ```typescript
3139
+ * omni.clearCustomerToken();
3140
+ * omni.onLogout();
3141
+ *
3142
+ * // Now back to guest mode - cart uses localStorage
3143
+ * await omni.smartAddToCart({ productId: 'prod_123', quantity: 1 });
3144
+ * ```
3145
+ */
3146
+ onLogout(): void;
2995
3147
  /**
2996
3148
  * Create a checkout from a cart
2997
3149
  * Starts the checkout process and returns checkout with available options
@@ -3486,6 +3638,28 @@ declare class OmniSyncClient {
3486
3638
  * ```
3487
3639
  */
3488
3640
  getMyProfile(): Promise<CustomerProfile>;
3641
+ /**
3642
+ * Get pre-fill data for checkout forms (requires customerToken).
3643
+ * Returns customer profile and default address formatted for checkout.
3644
+ * Use this to pre-populate shipping forms for logged-in customers.
3645
+ *
3646
+ * @example
3647
+ * ```typescript
3648
+ * omni.setCustomerToken(auth.token);
3649
+ *
3650
+ * const prefill = await omni.getCheckoutPrefillData();
3651
+ *
3652
+ * if (prefill.shippingAddress) {
3653
+ * // Pre-fill shipping form with customer's default address
3654
+ * setFormValues(prefill.shippingAddress);
3655
+ * } else {
3656
+ * // Customer has no saved addresses, show empty form
3657
+ * // But still pre-fill email from customer profile
3658
+ * setFormValues({ email: prefill.customer.email });
3659
+ * }
3660
+ * ```
3661
+ */
3662
+ getCheckoutPrefillData(): Promise<CheckoutPrefillData>;
3489
3663
  /**
3490
3664
  * Update the current customer's profile (requires customerToken)
3491
3665
  * Only available in storefront mode
@@ -3749,4 +3923,4 @@ declare function isWebhookEventType(event: WebhookEvent, type: WebhookEventType)
3749
3923
  */
3750
3924
  declare function createWebhookHandler(handlers: Partial<Record<WebhookEventType, (event: WebhookEvent) => Promise<void>>>): (payload: unknown) => Promise<void>;
3751
3925
 
3752
- export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartItem, type CartStatus, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutLineItem, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateGuestOrderDto, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DraftLineItem, type EditInventoryDto, type EmailVerificationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventorySyncStatus, type LocalCart, type LocalCartItem, type MergeCartsDto, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProvidersResponse, type OmniSyncApiError, OmniSyncClient, type OmniSyncClientOptions, OmniSyncError, type Order, type OrderAddress, type OrderCustomer, type OrderItem, type OrderQueryParams, type OrderStatus, type PaginatedResponse, type PaymentConfig, type PaymentIntent, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PlatformCouponCapabilities, type Product, type ProductAttributeInput, type ProductImage, type ProductQueryParams, type ProductSuggestion, type ProductVariant, type PublishProductResponse, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type SearchSuggestions, type SelectShippingMethodDto, type SendInvoiceDto, type SetBillingAddressDto, type SetCheckoutCustomerDto, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingLine, type ShippingRate, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type SyncJob, type UpdateAddressDto, type UpdateCartItemDto, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateInventoryDto, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateVariantDto, type UpdateVariantInventoryDto, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, formatPrice, getDescriptionContent, formatPrice as getPriceDisplay, getStockStatus, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
3926
+ export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartItem, type CartStatus, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateGuestOrderDto, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateVariantDto, type CustomApiAuthType, type CustomApiConnectionStatus, type CustomApiCredentials, type CustomApiIntegration, type CustomApiSyncConfig, type CustomApiSyncDirection, type CustomApiTestResult, type Customer, type CustomerAddress, type CustomerAuthResponse, type CustomerOAuthProvider, type CustomerProfile, type CustomerQueryParams, type DraftLineItem, type EditInventoryDto, type EmailVerificationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventorySyncStatus, type LocalCart, type LocalCartItem, type MergeCartsDto, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProvidersResponse, type OmniSyncApiError, OmniSyncClient, type OmniSyncClientOptions, OmniSyncError, type Order, type OrderAddress, type OrderCustomer, type OrderItem, type OrderQueryParams, type OrderStatus, type PaginatedResponse, type PaymentConfig, type PaymentIntent, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PlatformCouponCapabilities, type Product, type ProductAttributeInput, type ProductImage, type ProductQueryParams, type ProductSuggestion, type ProductVariant, type PublishProductResponse, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type SearchSuggestions, type SelectShippingMethodDto, type SendInvoiceDto, type SetBillingAddressDto, type SetCheckoutCustomerDto, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingLine, type ShippingRate, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type SyncJob, type UpdateAddressDto, type UpdateCartItemDto, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateInventoryDto, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateVariantDto, type UpdateVariantInventoryDto, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, formatPrice, getDescriptionContent, formatPrice as getPriceDisplay, getStockStatus, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
package/dist/index.js CHANGED
@@ -41,6 +41,7 @@ var DEFAULT_TIMEOUT = 3e4;
41
41
  var OmniSyncClient = class {
42
42
  constructor(options) {
43
43
  this.customerToken = null;
44
+ this.customerCartId = null;
44
45
  // -------------------- Local Cart (Client-Side for Guests) --------------------
45
46
  // These methods store cart data in localStorage - NO API calls!
46
47
  // Use for guest users in vibe-coded sites
@@ -1838,6 +1839,194 @@ var OmniSyncClient = class {
1838
1839
  }
1839
1840
  return this.adminRequest("POST", "/api/v1/cart/merge", data);
1840
1841
  }
1842
+ // -------------------- Smart Cart (Auto-sync) --------------------
1843
+ /**
1844
+ * Check if customer is currently authenticated
1845
+ * Used internally by smart cart methods to determine storage strategy
1846
+ *
1847
+ * @example
1848
+ * ```typescript
1849
+ * if (omni.isCustomerLoggedIn()) {
1850
+ * console.log('Cart will be stored on server');
1851
+ * } else {
1852
+ * console.log('Cart will be stored in localStorage');
1853
+ * }
1854
+ * ```
1855
+ */
1856
+ isCustomerLoggedIn() {
1857
+ return !!this.customerToken;
1858
+ }
1859
+ /**
1860
+ * Get or create a server cart for the logged-in customer
1861
+ * Caches the cart ID for subsequent calls
1862
+ * @internal
1863
+ */
1864
+ async getOrCreateCustomerCart() {
1865
+ if (this.customerCartId) {
1866
+ try {
1867
+ return await this.getCart(this.customerCartId);
1868
+ } catch {
1869
+ this.customerCartId = null;
1870
+ }
1871
+ }
1872
+ const cart = await this.createCart();
1873
+ this.customerCartId = cart.id;
1874
+ if (this.customerToken) {
1875
+ try {
1876
+ await this.linkCart(cart.id);
1877
+ } catch {
1878
+ }
1879
+ }
1880
+ return cart;
1881
+ }
1882
+ /**
1883
+ * Smart add to cart - automatically uses localStorage or server based on auth state
1884
+ *
1885
+ * - **Guest (not logged in)**: Stores in localStorage
1886
+ * - **Logged in**: Stores on server (database)
1887
+ *
1888
+ * @example
1889
+ * ```typescript
1890
+ * // Works the same whether logged in or not
1891
+ * await omni.smartAddToCart({
1892
+ * productId: 'prod_123',
1893
+ * quantity: 2,
1894
+ * name: 'Cool Product', // Optional: for localStorage display
1895
+ * price: '29.99',
1896
+ * });
1897
+ * ```
1898
+ */
1899
+ async smartAddToCart(item) {
1900
+ if (this.isCustomerLoggedIn()) {
1901
+ const cart = await this.getOrCreateCustomerCart();
1902
+ return this.addToCart(cart.id, {
1903
+ productId: item.productId,
1904
+ variantId: item.variantId,
1905
+ quantity: item.quantity
1906
+ });
1907
+ } else {
1908
+ return this.addToLocalCart(item);
1909
+ }
1910
+ }
1911
+ /**
1912
+ * Smart get cart - returns server cart if logged in, localStorage if guest
1913
+ *
1914
+ * @example
1915
+ * ```typescript
1916
+ * const cart = await omni.smartGetCart();
1917
+ * console.log('Items:', cart.items.length);
1918
+ * ```
1919
+ */
1920
+ async smartGetCart() {
1921
+ if (this.isCustomerLoggedIn()) {
1922
+ return this.getOrCreateCustomerCart();
1923
+ } else {
1924
+ return this.getLocalCart();
1925
+ }
1926
+ }
1927
+ /**
1928
+ * Smart update cart item quantity
1929
+ *
1930
+ * @example
1931
+ * ```typescript
1932
+ * await omni.smartUpdateCartItem('prod_123', 3); // Set quantity to 3
1933
+ * await omni.smartUpdateCartItem('prod_123', 0); // Remove item
1934
+ * ```
1935
+ */
1936
+ async smartUpdateCartItem(productId, quantity, variantId) {
1937
+ if (this.isCustomerLoggedIn()) {
1938
+ const cart = await this.getOrCreateCustomerCart();
1939
+ const item = cart.items.find(
1940
+ (i) => i.productId === productId && i.variantId === (variantId ?? null)
1941
+ );
1942
+ if (!item) {
1943
+ return cart;
1944
+ }
1945
+ if (quantity <= 0) {
1946
+ return this.removeCartItem(cart.id, item.id);
1947
+ }
1948
+ return this.updateCartItem(cart.id, item.id, { quantity });
1949
+ } else {
1950
+ return this.updateLocalCartItem(productId, quantity, variantId);
1951
+ }
1952
+ }
1953
+ /**
1954
+ * Smart remove from cart
1955
+ *
1956
+ * @example
1957
+ * ```typescript
1958
+ * await omni.smartRemoveFromCart('prod_123');
1959
+ * await omni.smartRemoveFromCart('prod_456', 'variant_789');
1960
+ * ```
1961
+ */
1962
+ async smartRemoveFromCart(productId, variantId) {
1963
+ return this.smartUpdateCartItem(productId, 0, variantId);
1964
+ }
1965
+ /**
1966
+ * Sync local cart to server on login
1967
+ *
1968
+ * Call this AFTER setCustomerToken() when a customer logs in.
1969
+ * This will:
1970
+ * 1. Get or create a server cart for the customer
1971
+ * 2. Add all items from localStorage to the server cart (merging with existing)
1972
+ * 3. Clear localStorage
1973
+ *
1974
+ * Items that fail to sync (e.g., out of stock) are silently skipped.
1975
+ *
1976
+ * @example
1977
+ * ```typescript
1978
+ * // Customer logs in
1979
+ * const auth = await omni.login(email, password);
1980
+ * omni.setCustomerToken(auth.token);
1981
+ *
1982
+ * // Sync their local cart to server
1983
+ * const cart = await omni.syncCartOnLogin();
1984
+ * console.log('Cart synced, items:', cart.items.length);
1985
+ * ```
1986
+ */
1987
+ async syncCartOnLogin() {
1988
+ if (!this.isCustomerLoggedIn()) {
1989
+ throw new OmniSyncError(
1990
+ "Must be logged in to sync cart. Call setCustomerToken() first.",
1991
+ 401
1992
+ );
1993
+ }
1994
+ const localCart = this.getLocalCart();
1995
+ const serverCart = await this.getOrCreateCustomerCart();
1996
+ if (localCart.items.length === 0) {
1997
+ return serverCart;
1998
+ }
1999
+ for (const item of localCart.items) {
2000
+ try {
2001
+ await this.addToCart(serverCart.id, {
2002
+ productId: item.productId,
2003
+ variantId: item.variantId,
2004
+ quantity: item.quantity
2005
+ });
2006
+ } catch {
2007
+ }
2008
+ }
2009
+ this.clearLocalCart();
2010
+ return this.getCart(serverCart.id);
2011
+ }
2012
+ /**
2013
+ * Clear cart state on logout
2014
+ *
2015
+ * Call this when a customer logs out to clear the cached cart ID.
2016
+ * The localStorage cart remains available for the next guest session.
2017
+ *
2018
+ * @example
2019
+ * ```typescript
2020
+ * omni.clearCustomerToken();
2021
+ * omni.onLogout();
2022
+ *
2023
+ * // Now back to guest mode - cart uses localStorage
2024
+ * await omni.smartAddToCart({ productId: 'prod_123', quantity: 1 });
2025
+ * ```
2026
+ */
2027
+ onLogout() {
2028
+ this.customerCartId = null;
2029
+ }
1841
2030
  // -------------------- Checkout --------------------
1842
2031
  /**
1843
2032
  * Create a checkout from a cart
@@ -2727,6 +2916,42 @@ var OmniSyncClient = class {
2727
2916
  }
2728
2917
  throw new OmniSyncError("getMyProfile is only available in vibe-coded or storefront mode", 400);
2729
2918
  }
2919
+ /**
2920
+ * Get pre-fill data for checkout forms (requires customerToken).
2921
+ * Returns customer profile and default address formatted for checkout.
2922
+ * Use this to pre-populate shipping forms for logged-in customers.
2923
+ *
2924
+ * @example
2925
+ * ```typescript
2926
+ * omni.setCustomerToken(auth.token);
2927
+ *
2928
+ * const prefill = await omni.getCheckoutPrefillData();
2929
+ *
2930
+ * if (prefill.shippingAddress) {
2931
+ * // Pre-fill shipping form with customer's default address
2932
+ * setFormValues(prefill.shippingAddress);
2933
+ * } else {
2934
+ * // Customer has no saved addresses, show empty form
2935
+ * // But still pre-fill email from customer profile
2936
+ * setFormValues({ email: prefill.customer.email });
2937
+ * }
2938
+ * ```
2939
+ */
2940
+ async getCheckoutPrefillData() {
2941
+ if (!this.customerToken) {
2942
+ throw new OmniSyncError("Customer token required. Call setCustomerToken() after login.", 401);
2943
+ }
2944
+ if (this.isVibeCodedMode()) {
2945
+ return this.vibeCodedRequest("GET", "/customers/me/checkout-prefill");
2946
+ }
2947
+ if (this.storeId && !this.apiKey) {
2948
+ return this.storefrontRequest("GET", "/customers/me/checkout-prefill");
2949
+ }
2950
+ throw new OmniSyncError(
2951
+ "getCheckoutPrefillData is only available in vibe-coded or storefront mode",
2952
+ 400
2953
+ );
2954
+ }
2730
2955
  /**
2731
2956
  * Update the current customer's profile (requires customerToken)
2732
2957
  * Only available in storefront mode
package/dist/index.mjs CHANGED
@@ -11,6 +11,7 @@ var DEFAULT_TIMEOUT = 3e4;
11
11
  var OmniSyncClient = class {
12
12
  constructor(options) {
13
13
  this.customerToken = null;
14
+ this.customerCartId = null;
14
15
  // -------------------- Local Cart (Client-Side for Guests) --------------------
15
16
  // These methods store cart data in localStorage - NO API calls!
16
17
  // Use for guest users in vibe-coded sites
@@ -1808,6 +1809,194 @@ var OmniSyncClient = class {
1808
1809
  }
1809
1810
  return this.adminRequest("POST", "/api/v1/cart/merge", data);
1810
1811
  }
1812
+ // -------------------- Smart Cart (Auto-sync) --------------------
1813
+ /**
1814
+ * Check if customer is currently authenticated
1815
+ * Used internally by smart cart methods to determine storage strategy
1816
+ *
1817
+ * @example
1818
+ * ```typescript
1819
+ * if (omni.isCustomerLoggedIn()) {
1820
+ * console.log('Cart will be stored on server');
1821
+ * } else {
1822
+ * console.log('Cart will be stored in localStorage');
1823
+ * }
1824
+ * ```
1825
+ */
1826
+ isCustomerLoggedIn() {
1827
+ return !!this.customerToken;
1828
+ }
1829
+ /**
1830
+ * Get or create a server cart for the logged-in customer
1831
+ * Caches the cart ID for subsequent calls
1832
+ * @internal
1833
+ */
1834
+ async getOrCreateCustomerCart() {
1835
+ if (this.customerCartId) {
1836
+ try {
1837
+ return await this.getCart(this.customerCartId);
1838
+ } catch {
1839
+ this.customerCartId = null;
1840
+ }
1841
+ }
1842
+ const cart = await this.createCart();
1843
+ this.customerCartId = cart.id;
1844
+ if (this.customerToken) {
1845
+ try {
1846
+ await this.linkCart(cart.id);
1847
+ } catch {
1848
+ }
1849
+ }
1850
+ return cart;
1851
+ }
1852
+ /**
1853
+ * Smart add to cart - automatically uses localStorage or server based on auth state
1854
+ *
1855
+ * - **Guest (not logged in)**: Stores in localStorage
1856
+ * - **Logged in**: Stores on server (database)
1857
+ *
1858
+ * @example
1859
+ * ```typescript
1860
+ * // Works the same whether logged in or not
1861
+ * await omni.smartAddToCart({
1862
+ * productId: 'prod_123',
1863
+ * quantity: 2,
1864
+ * name: 'Cool Product', // Optional: for localStorage display
1865
+ * price: '29.99',
1866
+ * });
1867
+ * ```
1868
+ */
1869
+ async smartAddToCart(item) {
1870
+ if (this.isCustomerLoggedIn()) {
1871
+ const cart = await this.getOrCreateCustomerCart();
1872
+ return this.addToCart(cart.id, {
1873
+ productId: item.productId,
1874
+ variantId: item.variantId,
1875
+ quantity: item.quantity
1876
+ });
1877
+ } else {
1878
+ return this.addToLocalCart(item);
1879
+ }
1880
+ }
1881
+ /**
1882
+ * Smart get cart - returns server cart if logged in, localStorage if guest
1883
+ *
1884
+ * @example
1885
+ * ```typescript
1886
+ * const cart = await omni.smartGetCart();
1887
+ * console.log('Items:', cart.items.length);
1888
+ * ```
1889
+ */
1890
+ async smartGetCart() {
1891
+ if (this.isCustomerLoggedIn()) {
1892
+ return this.getOrCreateCustomerCart();
1893
+ } else {
1894
+ return this.getLocalCart();
1895
+ }
1896
+ }
1897
+ /**
1898
+ * Smart update cart item quantity
1899
+ *
1900
+ * @example
1901
+ * ```typescript
1902
+ * await omni.smartUpdateCartItem('prod_123', 3); // Set quantity to 3
1903
+ * await omni.smartUpdateCartItem('prod_123', 0); // Remove item
1904
+ * ```
1905
+ */
1906
+ async smartUpdateCartItem(productId, quantity, variantId) {
1907
+ if (this.isCustomerLoggedIn()) {
1908
+ const cart = await this.getOrCreateCustomerCart();
1909
+ const item = cart.items.find(
1910
+ (i) => i.productId === productId && i.variantId === (variantId ?? null)
1911
+ );
1912
+ if (!item) {
1913
+ return cart;
1914
+ }
1915
+ if (quantity <= 0) {
1916
+ return this.removeCartItem(cart.id, item.id);
1917
+ }
1918
+ return this.updateCartItem(cart.id, item.id, { quantity });
1919
+ } else {
1920
+ return this.updateLocalCartItem(productId, quantity, variantId);
1921
+ }
1922
+ }
1923
+ /**
1924
+ * Smart remove from cart
1925
+ *
1926
+ * @example
1927
+ * ```typescript
1928
+ * await omni.smartRemoveFromCart('prod_123');
1929
+ * await omni.smartRemoveFromCart('prod_456', 'variant_789');
1930
+ * ```
1931
+ */
1932
+ async smartRemoveFromCart(productId, variantId) {
1933
+ return this.smartUpdateCartItem(productId, 0, variantId);
1934
+ }
1935
+ /**
1936
+ * Sync local cart to server on login
1937
+ *
1938
+ * Call this AFTER setCustomerToken() when a customer logs in.
1939
+ * This will:
1940
+ * 1. Get or create a server cart for the customer
1941
+ * 2. Add all items from localStorage to the server cart (merging with existing)
1942
+ * 3. Clear localStorage
1943
+ *
1944
+ * Items that fail to sync (e.g., out of stock) are silently skipped.
1945
+ *
1946
+ * @example
1947
+ * ```typescript
1948
+ * // Customer logs in
1949
+ * const auth = await omni.login(email, password);
1950
+ * omni.setCustomerToken(auth.token);
1951
+ *
1952
+ * // Sync their local cart to server
1953
+ * const cart = await omni.syncCartOnLogin();
1954
+ * console.log('Cart synced, items:', cart.items.length);
1955
+ * ```
1956
+ */
1957
+ async syncCartOnLogin() {
1958
+ if (!this.isCustomerLoggedIn()) {
1959
+ throw new OmniSyncError(
1960
+ "Must be logged in to sync cart. Call setCustomerToken() first.",
1961
+ 401
1962
+ );
1963
+ }
1964
+ const localCart = this.getLocalCart();
1965
+ const serverCart = await this.getOrCreateCustomerCart();
1966
+ if (localCart.items.length === 0) {
1967
+ return serverCart;
1968
+ }
1969
+ for (const item of localCart.items) {
1970
+ try {
1971
+ await this.addToCart(serverCart.id, {
1972
+ productId: item.productId,
1973
+ variantId: item.variantId,
1974
+ quantity: item.quantity
1975
+ });
1976
+ } catch {
1977
+ }
1978
+ }
1979
+ this.clearLocalCart();
1980
+ return this.getCart(serverCart.id);
1981
+ }
1982
+ /**
1983
+ * Clear cart state on logout
1984
+ *
1985
+ * Call this when a customer logs out to clear the cached cart ID.
1986
+ * The localStorage cart remains available for the next guest session.
1987
+ *
1988
+ * @example
1989
+ * ```typescript
1990
+ * omni.clearCustomerToken();
1991
+ * omni.onLogout();
1992
+ *
1993
+ * // Now back to guest mode - cart uses localStorage
1994
+ * await omni.smartAddToCart({ productId: 'prod_123', quantity: 1 });
1995
+ * ```
1996
+ */
1997
+ onLogout() {
1998
+ this.customerCartId = null;
1999
+ }
1811
2000
  // -------------------- Checkout --------------------
1812
2001
  /**
1813
2002
  * Create a checkout from a cart
@@ -2697,6 +2886,42 @@ var OmniSyncClient = class {
2697
2886
  }
2698
2887
  throw new OmniSyncError("getMyProfile is only available in vibe-coded or storefront mode", 400);
2699
2888
  }
2889
+ /**
2890
+ * Get pre-fill data for checkout forms (requires customerToken).
2891
+ * Returns customer profile and default address formatted for checkout.
2892
+ * Use this to pre-populate shipping forms for logged-in customers.
2893
+ *
2894
+ * @example
2895
+ * ```typescript
2896
+ * omni.setCustomerToken(auth.token);
2897
+ *
2898
+ * const prefill = await omni.getCheckoutPrefillData();
2899
+ *
2900
+ * if (prefill.shippingAddress) {
2901
+ * // Pre-fill shipping form with customer's default address
2902
+ * setFormValues(prefill.shippingAddress);
2903
+ * } else {
2904
+ * // Customer has no saved addresses, show empty form
2905
+ * // But still pre-fill email from customer profile
2906
+ * setFormValues({ email: prefill.customer.email });
2907
+ * }
2908
+ * ```
2909
+ */
2910
+ async getCheckoutPrefillData() {
2911
+ if (!this.customerToken) {
2912
+ throw new OmniSyncError("Customer token required. Call setCustomerToken() after login.", 401);
2913
+ }
2914
+ if (this.isVibeCodedMode()) {
2915
+ return this.vibeCodedRequest("GET", "/customers/me/checkout-prefill");
2916
+ }
2917
+ if (this.storeId && !this.apiKey) {
2918
+ return this.storefrontRequest("GET", "/customers/me/checkout-prefill");
2919
+ }
2920
+ throw new OmniSyncError(
2921
+ "getCheckoutPrefillData is only available in vibe-coded or storefront mode",
2922
+ 400
2923
+ );
2924
+ }
2700
2925
  /**
2701
2926
  * Update the current customer's profile (requires customerToken)
2702
2927
  * Only available in storefront mode
package/package.json CHANGED
@@ -1,76 +1,75 @@
1
- {
2
- "name": "omni-sync-sdk",
3
- "version": "0.16.0",
4
- "description": "Official SDK for building e-commerce storefronts with OmniSync Platform. Perfect for vibe-coded sites, AI-built stores (Cursor, Lovable, v0), and custom storefronts.",
5
- "main": "dist/index.js",
6
- "module": "dist/index.mjs",
7
- "types": "dist/index.d.ts",
8
- "exports": {
9
- ".": {
10
- "types": "./dist/index.d.ts",
11
- "require": "./dist/index.js",
12
- "import": "./dist/index.mjs"
13
- }
14
- },
15
- "files": [
16
- "dist",
17
- "README.md"
18
- ],
19
- "scripts": {
20
- "build": "tsup src/index.ts --format cjs,esm --dts",
21
- "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
22
- "lint": "eslint \"src/**/*.ts\"",
23
- "test": "vitest run",
24
- "test:watch": "vitest",
25
- "prepublishOnly": "pnpm build"
26
- },
27
- "keywords": [
28
- "omni-sync",
29
- "e-commerce",
30
- "ecommerce",
31
- "sdk",
32
- "vibe-coding",
33
- "vibe-coded",
34
- "ai-commerce",
35
- "storefront",
36
- "headless-commerce",
37
- "multi-platform",
38
- "shopify",
39
- "tiktok",
40
- "cursor",
41
- "lovable",
42
- "v0",
43
- "cart",
44
- "checkout",
45
- "products",
46
- "sync"
47
- ],
48
- "author": "Omni-Sync Platform",
49
- "license": "MIT",
50
- "repository": {
51
- "type": "git",
52
- "url": "https://github.com/omni-sync/omni-sync-platform.git",
53
- "directory": "packages/sdk"
54
- },
55
- "homepage": "https://omni-sync.com",
56
- "bugs": {
57
- "url": "https://github.com/omni-sync/omni-sync-platform/issues"
58
- },
59
- "devDependencies": {
60
- "@types/node": "^25.0.3",
61
- "@typescript-eslint/eslint-plugin": "^8.50.1",
62
- "@typescript-eslint/parser": "^8.50.1",
63
- "eslint": "^9.39.2",
64
- "tsup": "^8.0.0",
65
- "typescript": "^5.3.0",
66
- "vitest": "^1.0.0"
67
- },
68
- "peerDependencies": {
69
- "typescript": ">=4.7.0"
70
- },
71
- "peerDependenciesMeta": {
72
- "typescript": {
73
- "optional": true
74
- }
75
- }
76
- }
1
+ {
2
+ "name": "omni-sync-sdk",
3
+ "version": "0.16.2",
4
+ "description": "Official SDK for building e-commerce storefronts with OmniSync Platform. Perfect for vibe-coded sites, AI-built stores (Cursor, Lovable, v0), and custom storefronts.",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "require": "./dist/index.js",
12
+ "import": "./dist/index.mjs"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "keywords": [
20
+ "omni-sync",
21
+ "e-commerce",
22
+ "ecommerce",
23
+ "sdk",
24
+ "vibe-coding",
25
+ "vibe-coded",
26
+ "ai-commerce",
27
+ "storefront",
28
+ "headless-commerce",
29
+ "multi-platform",
30
+ "shopify",
31
+ "tiktok",
32
+ "cursor",
33
+ "lovable",
34
+ "v0",
35
+ "cart",
36
+ "checkout",
37
+ "products",
38
+ "sync"
39
+ ],
40
+ "author": "Omni-Sync Platform",
41
+ "license": "MIT",
42
+ "repository": {
43
+ "type": "git",
44
+ "url": "https://github.com/omni-sync/omni-sync-platform.git",
45
+ "directory": "packages/sdk"
46
+ },
47
+ "homepage": "https://omni-sync.com",
48
+ "bugs": {
49
+ "url": "https://github.com/omni-sync/omni-sync-platform/issues"
50
+ },
51
+ "devDependencies": {
52
+ "@types/node": "^25.0.3",
53
+ "@typescript-eslint/eslint-plugin": "^8.50.1",
54
+ "@typescript-eslint/parser": "^8.50.1",
55
+ "eslint": "^9.39.2",
56
+ "tsup": "^8.0.0",
57
+ "typescript": "^5.3.0",
58
+ "vitest": "^1.0.0"
59
+ },
60
+ "peerDependencies": {
61
+ "typescript": ">=4.7.0"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "typescript": {
65
+ "optional": true
66
+ }
67
+ },
68
+ "scripts": {
69
+ "build": "tsup src/index.ts --format cjs,esm --dts",
70
+ "dev": "tsup src/index.ts --format cjs,esm --dts --watch",
71
+ "lint": "eslint \"src/**/*.ts\"",
72
+ "test": "vitest run",
73
+ "test:watch": "vitest"
74
+ }
75
+ }