brainerce 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -895,6 +895,32 @@ interface Order {
895
895
  /** Tax amount */
896
896
  taxAmount?: string | null;
897
897
  createdAt: string;
898
+ /** Payment method used (e.g., "card", "paypal", "cash_on_delivery"). */
899
+ paymentMethod?: string | null;
900
+ /** Financial status: "pending", "paid", "refunded", "partially_refunded", "voided". */
901
+ financialStatus?: string | null;
902
+ /** Fulfillment status: "unfulfilled", "partial", "fulfilled". */
903
+ fulfillmentStatus?: string | null;
904
+ /** Tracking number, e.g., "1Z999AA10123456784". */
905
+ trackingNumber?: string | null;
906
+ /** Deep link to the carrier's tracking page. */
907
+ trackingUrl?: string | null;
908
+ /** Carrier name, e.g., "UPS", "USPS", "DHL". */
909
+ carrier?: string | null;
910
+ /** ISO-8601 timestamp when the order was shipped. */
911
+ shippedAt?: string | null;
912
+ /** ISO-8601 timestamp when the order was delivered. */
913
+ deliveredAt?: string | null;
914
+ /** Status timeline entries in chronological order. */
915
+ statusHistory?: OrderStatusChange[] | null;
916
+ }
917
+ /** One status transition on an order. */
918
+ interface OrderStatusChange {
919
+ status: OrderStatus;
920
+ /** ISO-8601 timestamp of the transition. */
921
+ at: string;
922
+ /** Optional note (why the status changed). */
923
+ note?: string | null;
898
924
  }
899
925
  /**
900
926
  * Order status values are **lowercase**.
@@ -961,10 +987,13 @@ interface OrderItem {
961
987
  totalPrice?: string;
962
988
  /** Product image URL (flat, not nested under product object) */
963
989
  image?: string;
964
- /** Customer input field values captured at checkout (e.g., cake text, uploaded logo) */
990
+ /**
991
+ * Customer input field values captured at checkout (e.g., cake text, uploaded logo).
992
+ * `value` is `string[]` for MULTI_SELECT / GALLERY types, `string` otherwise.
993
+ */
965
994
  customizations?: Record<string, {
966
995
  label: string;
967
- value: string;
996
+ value: string | string[];
968
997
  type: string;
969
998
  }>;
970
999
  }
@@ -2498,8 +2527,8 @@ interface CustomApiTestResult {
2498
2527
  * The frontend dynamically loads the SDK script and calls init/render methods.
2499
2528
  */
2500
2529
  interface PaymentClientSdk {
2501
- /** How the payment UI is rendered: 'sdk-widget' (JS SDK), 'iframe', 'redirect', or 'sandbox' (test orders) */
2502
- renderType: 'sdk-widget' | 'iframe' | 'redirect' | 'sandbox';
2530
+ /** How the payment UI is rendered: 'sdk-widget' (JS SDK), 'iframe', 'redirect', 'sandbox' (test orders), or 'embedded-fields' (PCI-compliant provider-hosted fields embedded in merchant DOM, e.g. Cardcom OpenFields, Stripe Elements) */
2531
+ renderType: 'sdk-widget' | 'iframe' | 'redirect' | 'sandbox' | 'embedded-fields';
2503
2532
  /** URL of the main SDK script to load */
2504
2533
  scriptUrl?: string;
2505
2534
  /** Name of the global variable set by the SDK script (e.g., 'growPayment') */
@@ -2521,6 +2550,12 @@ interface PaymentClientSdk {
2521
2550
  }>;
2522
2551
  /** CSS to inject into <head> when SDK is active (e.g., LTR overrides for body-level popups on RTL pages) */
2523
2552
  bodyStyles?: string;
2553
+ /** For renderType='embedded-fields': base URL the sensitive-field iframes load (e.g. 'https://secure.cardcom.solutions'). postMessage origin is strictly validated against this. */
2554
+ embeddedFieldsUrl?: string;
2555
+ /** For renderType='embedded-fields': opaque provider session id used in the iframe init handshake (e.g., Cardcom LowProfileId) */
2556
+ embeddedFieldsSessionId?: string;
2557
+ /** Provider discriminator that selects the correct embedded-fields component on the storefront */
2558
+ embeddedFieldsProvider?: 'cardcom';
2524
2559
  }
2525
2560
  /**
2526
2561
  * Payment provider configuration (returned by `getPaymentProviders()`).
@@ -3156,7 +3191,7 @@ interface UpdateTaxRateDto {
3156
3191
  /**
3157
3192
  * Metafield type for defining value structure
3158
3193
  */
3159
- type MetafieldType = 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME' | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON' | 'IMAGE' | 'GALLERY';
3194
+ type MetafieldType = 'TEXT' | 'TEXTAREA' | 'NUMBER' | 'BOOLEAN' | 'DATE' | 'DATETIME' | 'URL' | 'COLOR' | 'DIMENSION' | 'WEIGHT' | 'JSON' | 'IMAGE' | 'GALLERY' | 'SELECT' | 'MULTI_SELECT';
3160
3195
  /**
3161
3196
  * Metafield definition - schema for product metafields
3162
3197
  */
@@ -3168,6 +3203,13 @@ interface MetafieldDefinition {
3168
3203
  description?: string | null;
3169
3204
  type: MetafieldType;
3170
3205
  required: boolean;
3206
+ isCustomerInput?: boolean;
3207
+ /**
3208
+ * When `true`, the field is treated as present on every product of this
3209
+ * account — including products created later. Clients don't need to list
3210
+ * individual `ProductCustomizationField` rows when this is set.
3211
+ */
3212
+ appliesToAllProducts?: boolean;
3171
3213
  minLength?: number | null;
3172
3214
  maxLength?: number | null;
3173
3215
  minValue?: number | null;
@@ -3177,6 +3219,11 @@ interface MetafieldDefinition {
3177
3219
  position: number;
3178
3220
  isActive: boolean;
3179
3221
  mappings?: MetafieldPlatformMapping[];
3222
+ /** Products this definition is explicitly attached to (customer-input only). */
3223
+ products?: Array<{
3224
+ id: string;
3225
+ name: string;
3226
+ }>;
3180
3227
  createdAt: string;
3181
3228
  updatedAt: string;
3182
3229
  }
@@ -3192,6 +3239,11 @@ interface PublicMetafieldDefinition {
3192
3239
  type: MetafieldType;
3193
3240
  required: boolean;
3194
3241
  isCustomerInput?: boolean;
3242
+ /**
3243
+ * When true, this definition applies to every product of the account —
3244
+ * including ones created after the flag was set.
3245
+ */
3246
+ appliesToAllProducts?: boolean;
3195
3247
  enumValues?: string[];
3196
3248
  minLength?: number | null;
3197
3249
  maxLength?: number | null;
@@ -3238,6 +3290,14 @@ interface CreateMetafieldDefinitionDto {
3238
3290
  description?: string;
3239
3291
  type?: MetafieldType;
3240
3292
  required?: boolean;
3293
+ isCustomerInput?: boolean;
3294
+ /** When true the field applies to every product in the account. */
3295
+ appliesToAllProducts?: boolean;
3296
+ /**
3297
+ * Assign the new (customer-input) definition to specific products atomically
3298
+ * in the same create call. Only valid when `isCustomerInput` is true.
3299
+ */
3300
+ productIds?: string[];
3241
3301
  minLength?: number;
3242
3302
  maxLength?: number;
3243
3303
  minValue?: number;
@@ -3251,6 +3311,8 @@ interface UpdateMetafieldDefinitionDto {
3251
3311
  description?: string | null;
3252
3312
  type?: MetafieldType;
3253
3313
  required?: boolean;
3314
+ isCustomerInput?: boolean;
3315
+ appliesToAllProducts?: boolean;
3254
3316
  minLength?: number | null;
3255
3317
  maxLength?: number | null;
3256
3318
  minValue?: number | null;
@@ -3260,6 +3322,16 @@ interface UpdateMetafieldDefinitionDto {
3260
3322
  position?: number;
3261
3323
  isActive?: boolean;
3262
3324
  }
3325
+ /**
3326
+ * Set (replace with diff-scoped semantics) the list of products linked to a
3327
+ * single customer-input metafield definition. Passing an empty array detaches
3328
+ * the definition from every product.
3329
+ */
3330
+ interface SetDefinitionProductsDto {
3331
+ productIds: string[];
3332
+ /** Optionally flip the `appliesToAllProducts` flag in the same call. */
3333
+ appliesToAllProducts?: boolean;
3334
+ }
3263
3335
  /**
3264
3336
  * Product metafield value
3265
3337
  */
@@ -3693,6 +3765,21 @@ interface CartBundleOffer {
3693
3765
  interface CartBundlesResponse {
3694
3766
  bundles: CartBundleOffer[];
3695
3767
  }
3768
+ /** Valid values for the cart `include` query parameter */
3769
+ type CartIncludeOption = 'recommendations' | 'upgrades' | 'bundles';
3770
+ /** Options for getCart / smartGetCart with optional includes */
3771
+ interface CartIncludeOptions {
3772
+ include?: CartIncludeOption[];
3773
+ }
3774
+ /** Cart response enriched with optional included data */
3775
+ interface CartWithIncludes extends Cart {
3776
+ /** Cross-sell recommendations (present when include contains 'recommendations') */
3777
+ recommendations?: CartRecommendationsResponse;
3778
+ /** Upgrade suggestions (present when include contains 'upgrades') */
3779
+ upgrades?: CartUpgradesResponse;
3780
+ /** Bundle offers (present when include contains 'bundles') */
3781
+ bundles?: CartBundlesResponse;
3782
+ }
3696
3783
  interface OrderBump {
3697
3784
  id: string;
3698
3785
  title: string;
@@ -4911,18 +4998,60 @@ declare class BrainerceClient {
4911
4998
  getCartByCustomer(customerId: string): Promise<Cart>;
4912
4999
  /**
4913
5000
  * Get a cart by ID
5001
+ *
5002
+ * @param cartId - The cart ID
5003
+ * @param options - Optional settings. Use `include` to fetch related data in a single request.
5004
+ *
5005
+ * @example
5006
+ * ```typescript
5007
+ * // Basic cart fetch
5008
+ * const cart = await client.getCart('cart_123');
5009
+ *
5010
+ * // Fetch cart with recommendations, upgrades, and bundles in one call
5011
+ * const enriched = await client.getCart('cart_123', {
5012
+ * include: ['recommendations', 'upgrades', 'bundles'],
5013
+ * });
5014
+ * console.log(enriched.recommendations); // { recommendations: [...] }
5015
+ * console.log(enriched.upgrades); // { upgrades: { ... } }
5016
+ * console.log(enriched.bundles); // { bundles: [...] }
5017
+ * ```
4914
5018
  */
4915
- getCart(cartId: string): Promise<Cart>;
5019
+ getCart(cartId: string, options?: CartIncludeOptions): Promise<CartWithIncludes>;
4916
5020
  /**
4917
- * Add an item to the cart
5021
+ * Add an item to the cart.
5022
+ *
5023
+ * If the product has `customizationFields` (merchant-defined buyer input
5024
+ * like engraving text, uploaded photos, select options), pass the buyer's
5025
+ * values in `metadata`. Keys must match each field's `key`. For `IMAGE` /
5026
+ * `GALLERY` types, upload the file first via `uploadCustomizationFile()`
5027
+ * and pass the returned URL. The server validates every value against its
5028
+ * `MetafieldDefinition` and rejects the request with HTTP 400 if anything
5029
+ * fails (type mismatch, required missing, not in `enumValues`, etc.).
5030
+ *
5031
+ * Values are snapshotted onto the order line at checkout — later edits to
5032
+ * the field definition do not retroactively change existing orders.
4918
5033
  *
4919
5034
  * @example
4920
5035
  * ```typescript
5036
+ * // Product with no customization fields
4921
5037
  * const cart = await client.addToCart('cart_123', {
4922
5038
  * productId: 'prod_abc',
4923
5039
  * quantity: 2,
4924
5040
  * notes: 'Gift wrap please',
4925
5041
  * });
5042
+ *
5043
+ * // Product WITH customization fields (engraving + photo + select + multi)
5044
+ * const { url: photoUrl } = await client.uploadCustomizationFile(file);
5045
+ * const cart = await client.addToCart('cart_123', {
5046
+ * productId: 'prod_mug',
5047
+ * quantity: 1,
5048
+ * metadata: {
5049
+ * engraving_text: 'Happy Birthday!', // TEXT
5050
+ * frame_color: 'Gold', // SELECT (must be in enumValues)
5051
+ * upload_photo: photoUrl, // IMAGE
5052
+ * addons: ['Gift wrap'], // MULTI_SELECT (always array)
5053
+ * },
5054
+ * });
4926
5055
  * ```
4927
5056
  */
4928
5057
  addToCart(cartId: string, item: AddToCartDto): Promise<Cart>;
@@ -5263,6 +5392,7 @@ declare class BrainerceClient {
5263
5392
  productId: string;
5264
5393
  variantId?: string;
5265
5394
  quantity: number;
5395
+ metadata?: Record<string, unknown>;
5266
5396
  }): Promise<Cart>;
5267
5397
  /**
5268
5398
  * Smart get cart - returns the current cart (server-side for both guests and logged-in users)
@@ -5271,13 +5401,21 @@ declare class BrainerceClient {
5271
5401
  * - **Guest with session**: Returns server-side session cart
5272
5402
  * - **Guest without session**: Returns empty cart (no server call, cart created lazily on add)
5273
5403
  *
5404
+ * @param options - Optional. Use `include` to fetch recommendations, upgrades, and bundles
5405
+ * in a single request instead of separate calls.
5406
+ *
5274
5407
  * @example
5275
5408
  * ```typescript
5276
5409
  * const cart = await client.smartGetCart();
5277
5410
  * console.log('Items:', cart.items.length);
5411
+ *
5412
+ * // With includes — single request for cart + extras
5413
+ * const enriched = await client.smartGetCart({
5414
+ * include: ['recommendations', 'upgrades', 'bundles'],
5415
+ * });
5278
5416
  * ```
5279
5417
  */
5280
- smartGetCart(): Promise<Cart>;
5418
+ smartGetCart(options?: CartIncludeOptions): Promise<CartWithIncludes>;
5281
5419
  /**
5282
5420
  * Smart update cart item quantity
5283
5421
  *
@@ -6636,6 +6774,26 @@ declare class BrainerceClient {
6636
6774
  * Requires Admin mode (apiKey)
6637
6775
  */
6638
6776
  deleteMetafieldDefinition(definitionId: string): Promise<void>;
6777
+ /**
6778
+ * Replace the list of products a (customer-input) metafield definition is
6779
+ * attached to. Diff-scoped: only rows for this definition are touched, so
6780
+ * concurrent edits to other definitions on the same product are safe.
6781
+ *
6782
+ * Optionally toggles `appliesToAllProducts` in the same call. When that
6783
+ * flag is true the `productIds` list is still respected as the explicit
6784
+ * subset, but buyers will see the field on every product regardless.
6785
+ *
6786
+ * Requires Admin mode (apiKey).
6787
+ *
6788
+ * @example
6789
+ * ```typescript
6790
+ * await client.setDefinitionProducts('def_123', {
6791
+ * productIds: ['prod_a', 'prod_b'],
6792
+ * appliesToAllProducts: false,
6793
+ * });
6794
+ * ```
6795
+ */
6796
+ setDefinitionProducts(definitionId: string, data: SetDefinitionProductsDto): Promise<MetafieldDefinition>;
6639
6797
  /**
6640
6798
  * Get all metafield values for a product
6641
6799
  * Requires Admin mode (apiKey)
@@ -6670,9 +6828,35 @@ declare class BrainerceClient {
6670
6828
  */
6671
6829
  setProductCustomizationFields(productId: string, definitionIds: string[]): Promise<ProductCustomizationField[]>;
6672
6830
  /**
6673
- * Upload a file for product customization (e.g., customer logo for printing).
6674
- * Available in storefront and vibe-coded modes.
6675
- * Returns the uploaded file URL and key.
6831
+ * Upload a buyer-submitted file (engraving photo, custom image, etc.) for a
6832
+ * product customization field of type `IMAGE` or `GALLERY`. The returned `url`
6833
+ * is what you pass back in the add-to-cart `metadata` payload.
6834
+ *
6835
+ * Available in storefront and vibe-coded modes — no customer login required.
6836
+ *
6837
+ * Server rules:
6838
+ * - `image/*` MIME only. Other types → HTTP 400.
6839
+ * - Max 5 MB per file.
6840
+ * - Throttled to 10 uploads / minute per IP → HTTP 429.
6841
+ * - Retention: at least 7 days. If the cart never becomes an order, the file
6842
+ * is reclaimed automatically. Once the order exists, the file is kept for
6843
+ * order-history purposes.
6844
+ *
6845
+ * @example
6846
+ * ```ts
6847
+ * // On a product page with IMAGE/GALLERY customization fields:
6848
+ * const { url } = await client.uploadCustomizationFile(fileInput.files[0]);
6849
+ *
6850
+ * // Then include the URL in the add-to-cart metadata:
6851
+ * await client.addToCart(cart.id, {
6852
+ * productId: product.id,
6853
+ * quantity: 1,
6854
+ * metadata: {
6855
+ * engraving_text: 'Happy Birthday!',
6856
+ * upload_photo: url,
6857
+ * },
6858
+ * });
6859
+ * ```
6676
6860
  */
6677
6861
  uploadCustomizationFile(file: File | Blob): Promise<{
6678
6862
  url: string;
@@ -6999,4 +7183,4 @@ declare function enableDevGuards(options?: {
6999
7183
  force?: boolean;
7000
7184
  }): void;
7001
7185
 
7002
- export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type Attribute, type AttributeOption, type AttributeSource, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartItem, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type Category, type CategoryNode, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, 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 DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type LocalCart, type LocalCartItem, type LockedVariant, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldPlatformMapping, type MetafieldType, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PickupLocation, type PlatformCouponCapabilities, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, type RecommendationVariant, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingZone, type ShippingZoneQueryParams, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type UpdateAddressDto, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, enableDevGuards, formatPrice, getCartItemImage, getCartItemName, getCartTotals, getDescriptionContent, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
7186
+ export { type AddToCartDto, type AppliedDiscount, type ApplyCouponDto, type Attribute, type AttributeOption, type AttributeSource, type BrainerceApiError, BrainerceClient, type BrainerceClientOptions, BrainerceError, type Brand, type BulkInventoryResponse, type BulkSaveVariantsDto, type BulkSaveVariantsResponse, type BulkVariantInput, type Cart, type CartAppliedDiscount, type CartBundleOffer, type CartBundlesResponse, type CartIncludeOption, type CartIncludeOptions, type CartItem, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryNode, type CategorySuggestion, type Checkout, type CheckoutAddress, type CheckoutBumpsResponse, type CheckoutCustomFieldDefinition, type CheckoutFieldPricing, type CheckoutFieldVisibility, type CheckoutLineItem, type CheckoutPrefillData, type CheckoutStatus, type CompleteCheckoutResponse, type CompleteDraftDto, type ConfigureOAuthProviderDto as ConfigureOAuthProviderInput, type ConflictStatus, type ConnectorPlatform, type Coupon, type CouponCreateResponse, type CouponQueryParams, type CouponStatus, type CouponType, type CouponValidationWarning, type CreateAddressDto, type CreateAttributeDto as CreateAttributeInput, type CreateAttributeOptionDto as CreateAttributeOptionInput, type CreateBrandDto as CreateBrandInput, type CreateCategoryDto as CreateCategoryInput, type CreateCheckoutDto, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateOrderDto, type CreateProductDto, type CreateRefundDto, type CreateShippingRateDto as CreateShippingRateInput, type CreateShippingZoneDto as CreateShippingZoneInput, type CreateTagDto as CreateTagInput, type CreateTaxRateDto as CreateTaxRateInput, 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 DeleteProductResponse, type DiscountBanner, type DiscountRuleType, type DownloadFile, type DraftLineItem, type EditInventoryDto, type EmailDomain, type EmailEventSettings, type EmailEventType, type EmailSettings, type EmailTemplate, type EmailTemplatePreview, type EmailTemplatesResponse, type EmailVerificationResponse, type ExtendReservationResponse, type FormatPriceOptions, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type LocalCart, type LocalCartItem, type LockedVariant, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldPlatformMapping, type MetafieldType, type OAuthAuthorizeResponse, type OAuthCallbackResponse, type OAuthConnection, type OAuthConnectionsResponse, type OAuthProviderConfig, type OAuthProviderType, type OAuthProvidersResponse, type Order, type OrderAddress, type OrderBump, type OrderCustomer, type OrderDownloadLink, type OrderItem, type OrderQueryParams, type OrderStatus, type OrderStatusChange, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PickupLocation, type PlatformCouponCapabilities, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, type RecommendationVariant, type ReconcileInventoryResponse, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingZone, type ShippingZoneQueryParams, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SyncConflict, type SyncConflictResolution, type SyncJob, type Tag, type TaxBreakdown, type TaxBreakdownItem, type TaxRate, type TaxonomyQueryParams, type TeamInvitation, type TeamInvitationsResponse, type TeamMember, type TeamMembersResponse, type TeamRole, type UpdateAddressDto, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateCouponDto, type UpdateCustomApiDto, type UpdateCustomerDto, type UpdateDraftDto, type UpdateEmailSettingsDto as UpdateEmailSettingsInput, type UpdateEmailTemplateDto as UpdateEmailTemplateInput, type UpdateInventoryDto, type UpdateMemberRoleDto as UpdateMemberRoleInput, type UpdateMetafieldDefinitionDto as UpdateMetafieldDefinitionInput, type UpdateOAuthProviderDto as UpdateOAuthProviderInput, type UpdateOrderDto, type UpdateOrderShippingDto, type UpdateProductDto, type UpdateShippingRateDto as UpdateShippingRateInput, type UpdateShippingZoneDto as UpdateShippingZoneInput, type UpdateStoreMemberDto as UpdateStoreMemberInput, type UpdateTagDto as UpdateTagInput, type UpdateTaxRateDto as UpdateTaxRateInput, type UpdateVariantDto, type UpdateVariantInventoryDto, type UpsertProductMetafieldDto as UpsertProductMetafieldInput, type UserStore, type UserStorePermissions, type VariantInventoryResponse, type VariantPlatformOverlay, type VariantStatus, type WaitForOrderOptions, type WaitForOrderResult, type WebhookEvent, type WebhookEventType, createWebhookHandler, enableDevGuards, formatPrice, getCartItemImage, getCartItemName, getCartTotals, getDescriptionContent, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, parseWebhookEvent, verifyWebhook };
package/dist/index.js CHANGED
@@ -439,11 +439,14 @@ var BrainerceClient = class {
439
439
  const controller = new AbortController();
440
440
  const timeoutId = setTimeout(() => controller.abort(), this.timeout);
441
441
  try {
442
+ const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
442
443
  const headers = {
443
- "Content-Type": "application/json",
444
444
  "X-SDK-Version": SDK_VERSION,
445
445
  "ngrok-skip-browser-warning": "true"
446
446
  };
447
+ if (!isFormData) {
448
+ headers["Content-Type"] = "application/json";
449
+ }
447
450
  if (this.origin) {
448
451
  headers["Origin"] = this.origin;
449
452
  }
@@ -462,7 +465,7 @@ var BrainerceClient = class {
462
465
  const response = await fetch(url.toString(), {
463
466
  method,
464
467
  headers,
465
- body: body ? JSON.stringify(body) : void 0,
468
+ body: body ? isFormData ? body : JSON.stringify(body) : void 0,
466
469
  signal: controller.signal
467
470
  });
468
471
  clearTimeout(timeoutId);
@@ -516,11 +519,14 @@ var BrainerceClient = class {
516
519
  const controller = new AbortController();
517
520
  const timeoutId = setTimeout(() => controller.abort(), this.timeout);
518
521
  try {
522
+ const isFormData = typeof FormData !== "undefined" && body instanceof FormData;
519
523
  const headers = {
520
- "Content-Type": "application/json",
521
524
  "X-SDK-Version": SDK_VERSION,
522
525
  "ngrok-skip-browser-warning": "true"
523
526
  };
527
+ if (!isFormData) {
528
+ headers["Content-Type"] = "application/json";
529
+ }
524
530
  if (this.origin) {
525
531
  headers["Origin"] = this.origin;
526
532
  }
@@ -536,7 +542,7 @@ var BrainerceClient = class {
536
542
  const response = await fetch(url.toString(), {
537
543
  method,
538
544
  headers,
539
- body: body ? JSON.stringify(body) : void 0,
545
+ body: body ? isFormData ? body : JSON.stringify(body) : void 0,
540
546
  signal: controller.signal
541
547
  });
542
548
  clearTimeout(timeoutId);
@@ -2112,30 +2118,82 @@ var BrainerceClient = class {
2112
2118
  }
2113
2119
  /**
2114
2120
  * Get a cart by ID
2121
+ *
2122
+ * @param cartId - The cart ID
2123
+ * @param options - Optional settings. Use `include` to fetch related data in a single request.
2124
+ *
2125
+ * @example
2126
+ * ```typescript
2127
+ * // Basic cart fetch
2128
+ * const cart = await client.getCart('cart_123');
2129
+ *
2130
+ * // Fetch cart with recommendations, upgrades, and bundles in one call
2131
+ * const enriched = await client.getCart('cart_123', {
2132
+ * include: ['recommendations', 'upgrades', 'bundles'],
2133
+ * });
2134
+ * console.log(enriched.recommendations); // { recommendations: [...] }
2135
+ * console.log(enriched.upgrades); // { upgrades: { ... } }
2136
+ * console.log(enriched.bundles); // { bundles: [...] }
2137
+ * ```
2115
2138
  */
2116
- async getCart(cartId) {
2139
+ async getCart(cartId, options) {
2117
2140
  if (cartId === this.VIRTUAL_LOCAL_CART_ID) {
2118
2141
  console.warn('getCart("__local__") is deprecated. Use smartGetCart() instead.');
2119
2142
  return this.withGuards(this.localCartToCart(this.getLocalCart()), "cart");
2120
2143
  }
2144
+ const queryParams = options?.include?.length ? { include: options.include.join(",") } : void 0;
2121
2145
  if (this.isVibeCodedMode()) {
2122
- return this.withGuards(this.vibeCodedRequest("GET", `/cart/${cartId}`), "cart");
2146
+ return this.withGuards(
2147
+ this.vibeCodedRequest("GET", `/cart/${cartId}`, void 0, queryParams),
2148
+ "cart"
2149
+ );
2123
2150
  }
2124
2151
  if (this.storeId && !this.apiKey) {
2125
- return this.withGuards(this.storefrontRequest("GET", `/cart/${cartId}`), "cart");
2152
+ return this.withGuards(
2153
+ this.storefrontRequest("GET", `/cart/${cartId}`, void 0, queryParams),
2154
+ "cart"
2155
+ );
2126
2156
  }
2127
- return this.withGuards(this.adminRequest("GET", `/api/v1/cart/${cartId}`), "cart");
2157
+ return this.withGuards(
2158
+ this.adminRequest("GET", `/api/v1/cart/${cartId}`, void 0, queryParams),
2159
+ "cart"
2160
+ );
2128
2161
  }
2129
2162
  /**
2130
- * Add an item to the cart
2163
+ * Add an item to the cart.
2164
+ *
2165
+ * If the product has `customizationFields` (merchant-defined buyer input
2166
+ * like engraving text, uploaded photos, select options), pass the buyer's
2167
+ * values in `metadata`. Keys must match each field's `key`. For `IMAGE` /
2168
+ * `GALLERY` types, upload the file first via `uploadCustomizationFile()`
2169
+ * and pass the returned URL. The server validates every value against its
2170
+ * `MetafieldDefinition` and rejects the request with HTTP 400 if anything
2171
+ * fails (type mismatch, required missing, not in `enumValues`, etc.).
2172
+ *
2173
+ * Values are snapshotted onto the order line at checkout — later edits to
2174
+ * the field definition do not retroactively change existing orders.
2131
2175
  *
2132
2176
  * @example
2133
2177
  * ```typescript
2178
+ * // Product with no customization fields
2134
2179
  * const cart = await client.addToCart('cart_123', {
2135
2180
  * productId: 'prod_abc',
2136
2181
  * quantity: 2,
2137
2182
  * notes: 'Gift wrap please',
2138
2183
  * });
2184
+ *
2185
+ * // Product WITH customization fields (engraving + photo + select + multi)
2186
+ * const { url: photoUrl } = await client.uploadCustomizationFile(file);
2187
+ * const cart = await client.addToCart('cart_123', {
2188
+ * productId: 'prod_mug',
2189
+ * quantity: 1,
2190
+ * metadata: {
2191
+ * engraving_text: 'Happy Birthday!', // TEXT
2192
+ * frame_color: 'Gold', // SELECT (must be in enumValues)
2193
+ * upload_photo: photoUrl, // IMAGE
2194
+ * addons: ['Gift wrap'], // MULTI_SELECT (always array)
2195
+ * },
2196
+ * });
2139
2197
  * ```
2140
2198
  */
2141
2199
  async addToCart(cartId, item) {
@@ -2783,11 +2841,21 @@ var BrainerceClient = class {
2783
2841
  * Uses promise dedup lock to prevent race conditions on parallel calls.
2784
2842
  * @internal
2785
2843
  */
2786
- async getOrCreateSessionCart() {
2787
- if (this._sessionCartPromise) return this._sessionCartPromise;
2844
+ async getOrCreateSessionCart(options) {
2845
+ if (this._sessionCartPromise) {
2846
+ const base = await this._sessionCartPromise;
2847
+ if (options?.include?.length && base.id) {
2848
+ return this.getCart(base.id, options);
2849
+ }
2850
+ return base;
2851
+ }
2788
2852
  this._sessionCartPromise = this._getOrCreateSessionCartImpl();
2789
2853
  try {
2790
- return await this._sessionCartPromise;
2854
+ const base = await this._sessionCartPromise;
2855
+ if (options?.include?.length && base.id) {
2856
+ return this.getCart(base.id, options);
2857
+ }
2858
+ return base;
2791
2859
  } finally {
2792
2860
  this._sessionCartPromise = null;
2793
2861
  }
@@ -2920,10 +2988,10 @@ var BrainerceClient = class {
2920
2988
  * Caches the cart ID for subsequent calls
2921
2989
  * @internal
2922
2990
  */
2923
- async getOrCreateCustomerCart() {
2991
+ async getOrCreateCustomerCart(options) {
2924
2992
  if (this.customerCartId) {
2925
2993
  try {
2926
- const existingCart = await this.getCart(this.customerCartId);
2994
+ const existingCart = await this.getCart(this.customerCartId, options);
2927
2995
  if (existingCart.status === "ACTIVE") {
2928
2996
  return existingCart;
2929
2997
  }
@@ -2936,6 +3004,9 @@ var BrainerceClient = class {
2936
3004
  const cart2 = await this.fetchCustomerCart();
2937
3005
  if (cart2.status === "ACTIVE") {
2938
3006
  this.customerCartId = cart2.id;
3007
+ if (options?.include?.length) {
3008
+ return this.getCart(cart2.id, options);
3009
+ }
2939
3010
  return cart2;
2940
3011
  }
2941
3012
  } catch {
@@ -2987,7 +3058,8 @@ var BrainerceClient = class {
2987
3058
  const updated = await this.addToCart(cart.id, {
2988
3059
  productId: item.productId,
2989
3060
  variantId: item.variantId,
2990
- quantity: item.quantity
3061
+ quantity: item.quantity,
3062
+ metadata: item.metadata
2991
3063
  });
2992
3064
  return updated;
2993
3065
  } else {
@@ -2995,7 +3067,8 @@ var BrainerceClient = class {
2995
3067
  const updated = await this.addToCart(cart.id, {
2996
3068
  productId: item.productId,
2997
3069
  variantId: item.variantId,
2998
- quantity: item.quantity
3070
+ quantity: item.quantity,
3071
+ metadata: item.metadata
2999
3072
  });
3000
3073
  this.updateSessionCartItemCount(updated.items?.length ?? 0);
3001
3074
  return updated;
@@ -3008,20 +3081,28 @@ var BrainerceClient = class {
3008
3081
  * - **Guest with session**: Returns server-side session cart
3009
3082
  * - **Guest without session**: Returns empty cart (no server call, cart created lazily on add)
3010
3083
  *
3084
+ * @param options - Optional. Use `include` to fetch recommendations, upgrades, and bundles
3085
+ * in a single request instead of separate calls.
3086
+ *
3011
3087
  * @example
3012
3088
  * ```typescript
3013
3089
  * const cart = await client.smartGetCart();
3014
3090
  * console.log('Items:', cart.items.length);
3091
+ *
3092
+ * // With includes — single request for cart + extras
3093
+ * const enriched = await client.smartGetCart({
3094
+ * include: ['recommendations', 'upgrades', 'bundles'],
3095
+ * });
3015
3096
  * ```
3016
3097
  */
3017
- async smartGetCart() {
3098
+ async smartGetCart(options) {
3018
3099
  if (this.isCustomerLoggedIn()) {
3019
- return this.getOrCreateCustomerCart();
3100
+ return this.getOrCreateCustomerCart(options);
3020
3101
  } else {
3021
3102
  if (!this.sessionToken) {
3022
3103
  return this.emptyCart();
3023
3104
  }
3024
- return this.getOrCreateSessionCart();
3105
+ return this.getOrCreateSessionCart(options);
3025
3106
  }
3026
3107
  }
3027
3108
  /**
@@ -5634,6 +5715,32 @@ var BrainerceClient = class {
5634
5715
  async deleteMetafieldDefinition(definitionId) {
5635
5716
  await this.adminRequest("DELETE", `/api/v1/metafield-definitions/${definitionId}`);
5636
5717
  }
5718
+ /**
5719
+ * Replace the list of products a (customer-input) metafield definition is
5720
+ * attached to. Diff-scoped: only rows for this definition are touched, so
5721
+ * concurrent edits to other definitions on the same product are safe.
5722
+ *
5723
+ * Optionally toggles `appliesToAllProducts` in the same call. When that
5724
+ * flag is true the `productIds` list is still respected as the explicit
5725
+ * subset, but buyers will see the field on every product regardless.
5726
+ *
5727
+ * Requires Admin mode (apiKey).
5728
+ *
5729
+ * @example
5730
+ * ```typescript
5731
+ * await client.setDefinitionProducts('def_123', {
5732
+ * productIds: ['prod_a', 'prod_b'],
5733
+ * appliesToAllProducts: false,
5734
+ * });
5735
+ * ```
5736
+ */
5737
+ async setDefinitionProducts(definitionId, data) {
5738
+ return this.adminRequest(
5739
+ "PATCH",
5740
+ `/api/v1/metafield-definitions/${definitionId}/products`,
5741
+ data
5742
+ );
5743
+ }
5637
5744
  // -------------------- Metafields: Product Values --------------------
5638
5745
  // These methods require Admin mode (apiKey)
5639
5746
  /**
@@ -5698,9 +5805,35 @@ var BrainerceClient = class {
5698
5805
  );
5699
5806
  }
5700
5807
  /**
5701
- * Upload a file for product customization (e.g., customer logo for printing).
5702
- * Available in storefront and vibe-coded modes.
5703
- * Returns the uploaded file URL and key.
5808
+ * Upload a buyer-submitted file (engraving photo, custom image, etc.) for a
5809
+ * product customization field of type `IMAGE` or `GALLERY`. The returned `url`
5810
+ * is what you pass back in the add-to-cart `metadata` payload.
5811
+ *
5812
+ * Available in storefront and vibe-coded modes — no customer login required.
5813
+ *
5814
+ * Server rules:
5815
+ * - `image/*` MIME only. Other types → HTTP 400.
5816
+ * - Max 5 MB per file.
5817
+ * - Throttled to 10 uploads / minute per IP → HTTP 429.
5818
+ * - Retention: at least 7 days. If the cart never becomes an order, the file
5819
+ * is reclaimed automatically. Once the order exists, the file is kept for
5820
+ * order-history purposes.
5821
+ *
5822
+ * @example
5823
+ * ```ts
5824
+ * // On a product page with IMAGE/GALLERY customization fields:
5825
+ * const { url } = await client.uploadCustomizationFile(fileInput.files[0]);
5826
+ *
5827
+ * // Then include the URL in the add-to-cart metadata:
5828
+ * await client.addToCart(cart.id, {
5829
+ * productId: product.id,
5830
+ * quantity: 1,
5831
+ * metadata: {
5832
+ * engraving_text: 'Happy Birthday!',
5833
+ * upload_photo: url,
5834
+ * },
5835
+ * });
5836
+ * ```
5704
5837
  */
5705
5838
  async uploadCustomizationFile(file) {
5706
5839
  const formData = new FormData();