brainerce 1.47.1 → 1.48.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
@@ -76,6 +76,31 @@ interface BrainerceClientOptions {
76
76
  statusCode: number;
77
77
  path?: string;
78
78
  }) => void;
79
+ /**
80
+ * Callback fired when the SDK silently resets the guest session cart because
81
+ * the previously-stored cart could no longer be resolved as-is — either the
82
+ * fetch failed (network error, 404 — cart deleted/expired) or the cart was
83
+ * found but is no longer `ACTIVE` (e.g. a prior checkout on it already
84
+ * completed or the cart was abandoned/merged). In both cases the SDK
85
+ * transparently creates a fresh empty cart so `smartAddToCart()` /
86
+ * `smartGetCart()` keep working — this callback is your only signal that it
87
+ * happened, so the storefront can tell the shopper their cart expired
88
+ * instead of them just seeing it silently empty out.
89
+ *
90
+ * @example
91
+ * ```typescript
92
+ * const client = new BrainerceClient({
93
+ * salesChannelId: 'vc_abc123...',
94
+ * onCartReset: ({ previousCartId, reason }) => {
95
+ * toast.warn('Your cart session expired — please re-add your items.');
96
+ * },
97
+ * });
98
+ * ```
99
+ */
100
+ onCartReset?: (info: {
101
+ previousCartId: string;
102
+ reason: 'not_found' | 'not_active';
103
+ }) => void;
79
104
  /**
80
105
  * Origin header to send with requests.
81
106
  * Browsers add this automatically, but Node.js environments (SSR, scripts, npx)
@@ -204,6 +229,26 @@ interface StoreInfo {
204
229
  seo?: {
205
230
  indexNowKey: string | null;
206
231
  };
232
+ /**
233
+ * Real merchant-configured shipping rates (sales-channel mode only) —
234
+ * flat-rate/free zones only, each with a single unconditional price.
235
+ * Weight/price-tiered and local-pickup rates are excluded because their
236
+ * cost depends on cart contents, so there's no single number to declare.
237
+ * Feeds Product JSON-LD `shippingDetails` — pass as `buildProductJsonLd(product, { ..., shipping: storeInfo.shipping })`.
238
+ */
239
+ shipping?: ShippingSummaryEntry[];
240
+ }
241
+ /** One flat-rate/free shipping zone, as exposed by `StoreInfo.shipping`. */
242
+ interface ShippingSummaryEntry {
243
+ /** ISO 3166-1 alpha-2 country codes this rate applies to. */
244
+ countries: string[];
245
+ rateType: 'FLAT_RATE' | 'FREE';
246
+ /** Shipping cost in the store's currency. `0` for FREE, `null` if a FLAT_RATE has no configured amount. */
247
+ amount: number | null;
248
+ minDeliveryDays: number | null;
249
+ maxDeliveryDays: number | null;
250
+ /** Order-processing time in business days before the item ships. */
251
+ handlingTime: number | null;
207
252
  }
208
253
  /** Multi-language configuration exposed to the storefront */
209
254
  interface I18nSettings {
@@ -254,6 +299,8 @@ interface CustomerProfile {
254
299
  phone?: string;
255
300
  emailVerified: boolean;
256
301
  acceptsMarketing: boolean;
302
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. Admin-set only, never customer-editable. */
303
+ role?: string;
257
304
  addresses: CustomerAddress[];
258
305
  createdAt: string;
259
306
  updatedAt: string;
@@ -497,6 +544,10 @@ interface Product {
497
544
  * `SIMPLE` products it is the product's own stored sale price.
498
545
  */
499
546
  salePrice?: string | null;
547
+ /** ISO 8601 — start of the sale-price effective window. `null` when unset (sale has no window). */
548
+ salePriceStartsAt?: string | null;
549
+ /** ISO 8601 — end of the sale-price effective window. Feeds Product JSON-LD `priceValidUntil`. `null` when unset. */
550
+ salePriceEndsAt?: string | null;
500
551
  /** Cost price as string. Use parseFloat() for calculations. */
501
552
  costPrice?: string | null;
502
553
  /** Lowest effective variant price (VARIABLE products only). String Decimal, e.g. "19.99". */
@@ -526,13 +577,15 @@ interface Product {
526
577
  inventory?: InventoryInfo | null;
527
578
  variants?: ProductVariant[];
528
579
  /**
529
- * Categories as objects with `id` and `name`.
530
- * NOT string[] - each category is `{ id: string; name: string }`.
531
- * Access: `product.categories?.map(cat => cat.name)`
580
+ * Categories as objects with `id`, `name`, and `slug`.
581
+ * NOT string[] - each category is `{ id: string; name: string; slug?: string | null }`.
582
+ * Access: `product.categories?.map(cat => cat.name)`. Use `slug` to link to
583
+ * that category's `/category/{slug}` landing page.
532
584
  */
533
585
  categories?: Array<{
534
586
  id: string;
535
587
  name: string;
588
+ slug?: string | null;
536
589
  }>;
537
590
  /** Brands as objects with id and name */
538
591
  brands?: Array<{
@@ -704,6 +757,10 @@ interface ProductVariant {
704
757
  price?: string | null;
705
758
  /** Variant sale price as string. Use parseFloat() for calculations. */
706
759
  salePrice?: string | null;
760
+ /** Variant unit cost (COGS) override as string — falls back to the product
761
+ * costPrice in margin analytics. Admin (apiKey) reads only; public
762
+ * storefront responses never include it. */
763
+ costPrice?: string | null;
707
764
  /** PRD §23: variant price converted to the region's currency via the daily
708
765
  * FX snapshot. Present only with `getProducts({ regionId })`. Display-only. */
709
766
  displayPrice?: string;
@@ -1808,6 +1865,8 @@ interface Customer {
1808
1865
  emailVerified: boolean;
1809
1866
  acceptsMarketing: boolean;
1810
1867
  tags: string[];
1868
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. Admin-set only, never customer-editable. */
1869
+ role?: string;
1811
1870
  totalOrders: number;
1812
1871
  lastOrderAt?: string;
1813
1872
  metadata?: Record<string, unknown>;
@@ -1907,6 +1966,8 @@ interface CreateCustomerDto {
1907
1966
  password?: string;
1908
1967
  acceptsMarketing?: boolean;
1909
1968
  tags?: string[];
1969
+ /** Free-form merchant-set segment (e.g. "wholesale", "vip"), max 50 chars. */
1970
+ role?: string;
1910
1971
  metadata?: Record<string, unknown>;
1911
1972
  }
1912
1973
  interface UpdateCustomerDto {
@@ -1916,6 +1977,8 @@ interface UpdateCustomerDto {
1916
1977
  lastName?: string;
1917
1978
  acceptsMarketing?: boolean;
1918
1979
  tags?: string[];
1980
+ /** Free-form merchant-set segment. Pass '' to clear it. */
1981
+ role?: string;
1919
1982
  metadata?: Record<string, unknown>;
1920
1983
  }
1921
1984
  interface CustomerQueryParams {
@@ -1923,6 +1986,8 @@ interface CustomerQueryParams {
1923
1986
  limit?: number;
1924
1987
  search?: string;
1925
1988
  hasAccount?: boolean;
1989
+ /** Filter by merchant-set customer role/segment (exact match, case-insensitive). */
1990
+ role?: string;
1926
1991
  sortBy?: 'createdAt' | 'email' | 'firstName' | 'lastName' | 'lastOrderAt';
1927
1992
  sortOrder?: 'asc' | 'desc';
1928
1993
  }
@@ -3120,6 +3185,8 @@ interface CreateVariantDto {
3120
3185
  attributes?: Record<string, string>;
3121
3186
  price?: number;
3122
3187
  salePrice?: number;
3188
+ /** Variant unit cost (COGS) override — falls back to product costPrice in margin analytics. */
3189
+ costPrice?: number;
3123
3190
  inventory?: number;
3124
3191
  image?: unknown;
3125
3192
  position?: number;
@@ -3131,6 +3198,8 @@ interface UpdateVariantDto {
3131
3198
  attributes?: Record<string, string>;
3132
3199
  price?: number;
3133
3200
  salePrice?: number;
3201
+ /** Variant unit cost (COGS) override. Pass null to clear (falls back to product costPrice). */
3202
+ costPrice?: number | null;
3134
3203
  image?: string | unknown;
3135
3204
  position?: number;
3136
3205
  status?: VariantStatus;
@@ -3149,6 +3218,8 @@ interface BulkVariantInput {
3149
3218
  attributes: Record<string, string>;
3150
3219
  price?: number | null;
3151
3220
  salePrice?: number | null;
3221
+ /** Variant unit cost (COGS) override. null clears (falls back to product costPrice). */
3222
+ costPrice?: number | null;
3152
3223
  stock: number;
3153
3224
  position?: number;
3154
3225
  image?: unknown | null;
@@ -6012,6 +6083,7 @@ declare class BrainerceClient {
6012
6083
  private readonly origin?;
6013
6084
  private readonly proxyMode;
6014
6085
  private readonly onAuthError?;
6086
+ private readonly onCartReset?;
6015
6087
  /** Active locale for content translation. When set, content endpoints return translated data. */
6016
6088
  private locale?;
6017
6089
  constructor(options: BrainerceClientOptions);
@@ -7301,6 +7373,8 @@ declare class BrainerceClient {
7301
7373
  lastName?: string;
7302
7374
  phone?: string;
7303
7375
  emailVerified: boolean;
7376
+ /** Free-form segment set by the merchant (e.g. "wholesale", "vip") — use to gate custom storefront features. */
7377
+ role?: string;
7304
7378
  }>;
7305
7379
  /**
7306
7380
  * Get all addresses for a customer
@@ -9283,6 +9357,25 @@ declare class BrainerceClient {
9283
9357
  * ```
9284
9358
  */
9285
9359
  cancelMembership(): Promise<PaidMembershipInfo>;
9360
+ /**
9361
+ * Mint a short-lived session for the embeddable loyalty widget (Phase 5) and
9362
+ * return the ready-to-use iframe URL. Requires customerToken. The returned
9363
+ * `embedUrl` is safe to drop straight into an `<iframe src>` — it carries a
9364
+ * scoped ~15-minute session token, never the real customerToken. Re-call this
9365
+ * before the iframe reloads (e.g. on page navigation) to refresh it.
9366
+ *
9367
+ * @example
9368
+ * ```typescript
9369
+ * const { embedUrl } = await client.getLoyaltyWidgetSession();
9370
+ * // <iframe src={embedUrl} width="360" height="420" />
9371
+ * ```
9372
+ */
9373
+ getLoyaltyWidgetSession(): Promise<{
9374
+ sessionId: string;
9375
+ expiresAt: string;
9376
+ storeId: string;
9377
+ embedUrl: string;
9378
+ }>;
9286
9379
  /**
9287
9380
  * Get the current customer's orders (requires customerToken)
9288
9381
  * Works in vibe-coded and storefront modes
@@ -10503,7 +10596,7 @@ declare class BrainerceError extends Error {
10503
10596
  constructor(message: string, statusCode: number, details?: unknown);
10504
10597
  }
10505
10598
 
10506
- declare const SDK_VERSION = "1.45.0";
10599
+ declare const SDK_VERSION = "1.48.0";
10507
10600
 
10508
10601
  /**
10509
10602
  * Verify a webhook signature from Brainerce
@@ -10686,6 +10779,8 @@ declare function buildProductJsonLd(product: Product, opts: JsonLdOptions & {
10686
10779
  currency: string;
10687
10780
  /** Brand display name; falls back to product.brands[0]. */
10688
10781
  brandName?: string;
10782
+ /** Flat-rate/free shipping zones (from `StoreInfo.shipping`). Omitted entirely when not provided — no fabricated shipping cost. */
10783
+ shipping?: ShippingSummaryEntry[];
10689
10784
  }): JsonLd;
10690
10785
  /**
10691
10786
  * schema.org/Organization for the homepage (Knowledge Panel + AI-answer
@@ -10786,4 +10881,4 @@ interface CategorySitemapOptions {
10786
10881
  */
10787
10882
  declare function getCategorySitemapEntries(client: BrainerceClient, opts: CategorySitemapOptions): Promise<SitemapEntry[]>;
10788
10883
 
10789
- export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogSitemapOptions, 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 CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, 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 ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, 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 CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, 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 FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, 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 PageContent, type PageSeo, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SubmitProductReviewInput, type SupportedLocaleObject, 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 UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, 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 UpdateModifierGroupInput, type UpdateModifierInput, 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, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseWebhookEvent, safePaymentRedirect, stripHtml, verifyWebhook };
10884
+ export { type AddToCartDto, type AddressDetailsResult, type AddressSuggestion, type AnnouncementContent, type AnnouncementSeverity, type AppliedDiscount, type ApplyCouponDto, type AttachModifierGroupInput, type Attribute, type AttributeOption, type AttributeSource, type BlogSitemapOptions, 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 CartItemModifierLine, type CartNudge, type CartRecommendationsResponse, type CartStatus, type CartUpgradeSuggestion, type CartUpgradesResponse, type CartWithIncludes, type Category, type CategoryDetail, type CategoryNode, type CategorySitemapOptions, 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 ContactFormFieldType, type ContactFormFieldValidation, type ContactFormPublic, type ContactFormPublicField, type ContactFormSummary, type Content, type ContentDataMap, type ContentStatus, type ContentSummary, type ContentType, 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 CreateContentInput, type CreateCouponDto, type CreateCustomApiDto, type CreateCustomerDto, type CreateEmailTemplateDto as CreateEmailTemplateInput, type CreateGuestOrderDto, type CreateInquiryInput, type CreateInquiryResponse, type CreateMetafieldDefinitionDto as CreateMetafieldDefinitionInput, type CreateModifierGroupInput, type CreateModifierInput, 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 FaqContent, type FaqItem, type FooterColumn, type FooterContent, type FooterLink, type FooterSocialLink, type FormatPriceOptions, type FormatProductPriceOptions, type FreeAllocationPolicy, type FulfillOrderDto, type GuestCheckoutStartResponse, type GuestOrderResponse, type HeaderContent, type HeaderCta, type HeaderLogo, type HeaderNavItem, type InsufficientStockError, type InventoryInfo, type InventoryReservationStrategy, type InventorySyncStatus, type InventoryTrackingMode, type InvitationStatus, type InviteMemberDto as InviteMemberInput, type InviteStoreMemberDto as InviteStoreMemberInput, type JsonLdOptions, type ListModifierGroupsParams, type LocalCart, type LocalCartItem, type LockedVariant, type LoyaltyNextTierSummary, type LoyaltyReward, type LoyaltyStatus, type LoyaltyTierSummary, type MergeCartsDto, type MetafieldConflict, type MetafieldConflictResolution, type MetafieldDefinition, type MetafieldType, type Modifier, type ModifierGroup, type ModifierSelection, type ModifierSelectionType, type ModifierValidationCode, type ModifierValidationError, type MyProductReview, 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 PageContent, type PageSeo, type PaginatedResponse, type PaymentClientSdk, type PaymentConfig, type PaymentIntent, type PaymentProvider, type PaymentProviderConfig, type PaymentProvidersConfig, type PaymentStatus, type PaymentUrlOptions, type PickupLocation, type PlatformCouponCapabilities, type PlatformMetafieldMetadata, type PreviewEmailTemplateDto as PreviewEmailTemplateInput, type Product, type ProductAttributeInput, type ProductAvailability, type ProductCustomizationField, type ProductDiscount, type ProductDiscountBadge, type ProductImage, type ProductMetafield, type ProductMetafieldValue, type ProductModifierGroupAttachment, type ProductQueryParams, type ProductRecommendation, type ProductRecommendationsResponse, type ProductRelationType, type ProductReview, type ProductReviewAdmin, type ProductSuggestion, type ProductVariant, type PublicMetafieldDefinition, type PublishProductResponse, RTL_LOCALES, type RecommendationVariant, type ReconcileInventoryResponse, type RedeemRewardResult, type ReferralInfo, type Refund, type RefundLineItem, type RefundLineItemResponse, type RefundType, type RegisterCustomerDto, type ReservationInfo, type ResolveMetafieldConflictDto as ResolveMetafieldConflictInput, type ResolveSyncConflictDto as ResolveSyncConflictInput, type RichTextContent, SDK_VERSION, type SearchSuggestions, type SelectPickupLocationDto, type SelectShippingMethodDto, type SendInvoiceDto, type SessionCartRef, type SetBillingAddressDto, type SetCheckoutCustomFieldsDto, type SetCheckoutCustomerDto, type SetDefinitionProductsDto as SetDefinitionProductsInput, type SetMetafieldPlatformsDto as SetMetafieldPlatformsInput, type SetShippingAddressDto, type SetShippingAddressResponse, type ShippingDestinations, type ShippingLine, type ShippingRate, type ShippingRateConfig, type ShippingRateType, type ShippingSummaryEntry, type ShippingZone, type ShippingZoneQueryParams, type SitemapEntry, type StockAvailabilityRequest, type StockAvailabilityResponse, type StockAvailabilityResult, type StoreInfo, type StoreInvitation, type StoreInvitationDetails, type StoreMember, type StorePermission, type StoreRole, type StoreTeamResponse, type SubmitProductReviewInput, type SupportedLocaleObject, 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 UpdateAttachmentInput, type UpdateAttributeDto as UpdateAttributeInput, type UpdateAttributeOptionDto as UpdateAttributeOptionInput, type UpdateBrandDto as UpdateBrandInput, type UpdateCartItemDto, type UpdateCategoryDto as UpdateCategoryInput, type UpdateContentInput, 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 UpdateModifierGroupInput, type UpdateModifierInput, 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, type WriteProductReviewInput, buildArticleJsonLd, buildBreadcrumbJsonLd, buildCollectionPageJsonLd, buildOrganizationJsonLd, buildProductJsonLd, buildWebsiteJsonLd, createWebhookHandler, deriveSeoDescription, enableDevGuards, formatMoney, formatPrice, formatProductPrice, formatVariantPrice, getBlogSitemapEntries, getCartItemImage, getCartItemName, getCartTotals, getCategorySitemapEntries, getDescriptionContent, getDirectionForLocale, formatPrice as getPriceDisplay, getProductCustomizationFields, getProductMetafield, getProductMetafieldValue, getProductMetafieldsByType, getProductPrice, getProductPriceInfo, getProductSwatches, getStockStatus, getVariantOptions, getVariantPrice, isAllowedPaymentUrl, isCouponApplicableToProduct, isHtmlDescription, isWebhookEventType, jsonLdScriptProps, parseWebhookEvent, safePaymentRedirect, stripHtml, verifyWebhook };
package/dist/index.js CHANGED
@@ -194,7 +194,7 @@ function isDevGuardsEnabled() {
194
194
  }
195
195
 
196
196
  // src/version.ts
197
- var SDK_VERSION = "1.45.0";
197
+ var SDK_VERSION = "1.48.0";
198
198
 
199
199
  // src/client.ts
200
200
  var DEFAULT_BASE_URL = "https://api.brainerce.com";
@@ -664,6 +664,7 @@ var BrainerceClient = class {
664
664
  this.proxyMode = options.proxyMode || false;
665
665
  this.analyticsBaseUrl = this.resolveAnalyticsBaseUrl(options.analyticsBaseUrl, resolvedBase);
666
666
  this.onAuthError = options.onAuthError;
667
+ this.onCartReset = options.onCartReset;
667
668
  this.hydrateSessionCart();
668
669
  this.detectRecoverCartFromUrl();
669
670
  }
@@ -4262,14 +4263,17 @@ var BrainerceClient = class {
4262
4263
  const migrated = await this.migrateLocalCartToSession();
4263
4264
  if (migrated) return migrated;
4264
4265
  if (this.sessionCartId && this.sessionToken) {
4266
+ const previousCartId = this.sessionCartId;
4265
4267
  try {
4266
4268
  const cart2 = await this.getCart(this.sessionCartId);
4267
4269
  if (cart2.status === "ACTIVE") {
4268
4270
  return cart2;
4269
4271
  }
4270
4272
  this.clearSessionCart();
4273
+ this.onCartReset?.({ previousCartId, reason: "not_active" });
4271
4274
  } catch {
4272
4275
  this.clearSessionCart();
4276
+ this.onCartReset?.({ previousCartId, reason: "not_found" });
4273
4277
  }
4274
4278
  }
4275
4279
  if (this.sessionToken) {
@@ -6498,9 +6502,9 @@ var BrainerceClient = class {
6498
6502
  );
6499
6503
  }
6500
6504
  // -------------------- Loyalty --------------------
6501
- // Storefront-mode only (storeId + customerToken). The backend exposes loyalty
6502
- // solely under /api/stores/:storeId/loyalty there is no vibe-coded route, so
6503
- // these do NOT branch on isVibeCodedMode() (that would 404 silently).
6505
+ // Available in both storefront mode (storeId + customerToken) and
6506
+ // vibe-coded mode (salesChannelId + customerToken) Phase 5 added the
6507
+ // /api/vc/:connectionId/loyalty/* routes mirroring /api/stores/:storeId/loyalty.
6504
6508
  /**
6505
6509
  * Get the logged-in customer's loyalty status: enrollment, points balance,
6506
6510
  * lifetime earned, the program's display config, earned milestone `badges`,
@@ -6524,10 +6528,16 @@ var BrainerceClient = class {
6524
6528
  401
6525
6529
  );
6526
6530
  }
6531
+ if (this.isVibeCodedMode()) {
6532
+ return this.vibeCodedRequest("GET", "/loyalty/me");
6533
+ }
6527
6534
  if (this.storeId && !this.apiKey) {
6528
6535
  return this.storefrontRequest("GET", "/loyalty/me");
6529
6536
  }
6530
- throw new BrainerceError("getLoyaltyStatus is only available in storefront mode", 400);
6537
+ throw new BrainerceError(
6538
+ "getLoyaltyStatus is only available in vibe-coded or storefront mode",
6539
+ 400
6540
+ );
6531
6541
  }
6532
6542
  /**
6533
6543
  * Enroll the logged-in customer in the store's loyalty program (requires
@@ -6546,10 +6556,16 @@ var BrainerceClient = class {
6546
6556
  401
6547
6557
  );
6548
6558
  }
6559
+ if (this.isVibeCodedMode()) {
6560
+ return this.vibeCodedRequest("POST", "/loyalty/enroll");
6561
+ }
6549
6562
  if (this.storeId && !this.apiKey) {
6550
6563
  return this.storefrontRequest("POST", "/loyalty/enroll");
6551
6564
  }
6552
- throw new BrainerceError("enrollInLoyalty is only available in storefront mode", 400);
6565
+ throw new BrainerceError(
6566
+ "enrollInLoyalty is only available in vibe-coded or storefront mode",
6567
+ 400
6568
+ );
6553
6569
  }
6554
6570
  /**
6555
6571
  * List the rewards the customer can redeem points for (active rewards, cheapest
@@ -6568,10 +6584,16 @@ var BrainerceClient = class {
6568
6584
  401
6569
6585
  );
6570
6586
  }
6587
+ if (this.isVibeCodedMode()) {
6588
+ return this.vibeCodedRequest("GET", "/loyalty/rewards/available");
6589
+ }
6571
6590
  if (this.storeId && !this.apiKey) {
6572
6591
  return this.storefrontRequest("GET", "/loyalty/rewards/available");
6573
6592
  }
6574
- throw new BrainerceError("getAvailableRewards is only available in storefront mode", 400);
6593
+ throw new BrainerceError(
6594
+ "getAvailableRewards is only available in vibe-coded or storefront mode",
6595
+ 400
6596
+ );
6575
6597
  }
6576
6598
  /**
6577
6599
  * Redeem a reward: spends the customer's points and mints a one-time coupon
@@ -6591,10 +6613,16 @@ var BrainerceClient = class {
6591
6613
  401
6592
6614
  );
6593
6615
  }
6616
+ if (this.isVibeCodedMode()) {
6617
+ return this.vibeCodedRequest("POST", "/loyalty/redeem", { rewardId });
6618
+ }
6594
6619
  if (this.storeId && !this.apiKey) {
6595
6620
  return this.storefrontRequest("POST", "/loyalty/redeem", { rewardId });
6596
6621
  }
6597
- throw new BrainerceError("redeemLoyaltyReward is only available in storefront mode", 400);
6622
+ throw new BrainerceError(
6623
+ "redeemLoyaltyReward is only available in vibe-coded or storefront mode",
6624
+ 400
6625
+ );
6598
6626
  }
6599
6627
  /**
6600
6628
  * Report a social share, granting the SOCIAL_SHARE earning-rule bonus if the
@@ -6614,6 +6642,13 @@ var BrainerceClient = class {
6614
6642
  401
6615
6643
  );
6616
6644
  }
6645
+ if (this.isVibeCodedMode()) {
6646
+ return this.vibeCodedRequest(
6647
+ "POST",
6648
+ "/loyalty/social-share",
6649
+ platform ? { platform } : {}
6650
+ );
6651
+ }
6617
6652
  if (this.storeId && !this.apiKey) {
6618
6653
  return this.storefrontRequest(
6619
6654
  "POST",
@@ -6621,7 +6656,10 @@ var BrainerceClient = class {
6621
6656
  platform ? { platform } : {}
6622
6657
  );
6623
6658
  }
6624
- throw new BrainerceError("reportSocialShare is only available in storefront mode", 400);
6659
+ throw new BrainerceError(
6660
+ "reportSocialShare is only available in vibe-coded or storefront mode",
6661
+ 400
6662
+ );
6625
6663
  }
6626
6664
  /**
6627
6665
  * Public referral-link lookup: who referred the visitor and what welcome
@@ -6640,12 +6678,20 @@ var BrainerceClient = class {
6640
6678
  * ```
6641
6679
  */
6642
6680
  async getReferralInfo(code) {
6681
+ if (this.isVibeCodedMode()) {
6682
+ return this.vibeCodedRequest("GET", "/loyalty/referral-info", void 0, {
6683
+ code
6684
+ });
6685
+ }
6643
6686
  if (this.storeId && !this.apiKey) {
6644
6687
  return this.storefrontRequest("GET", "/loyalty/referral-info", void 0, {
6645
6688
  code
6646
6689
  });
6647
6690
  }
6648
- throw new BrainerceError("getReferralInfo is only available in storefront mode", 400);
6691
+ throw new BrainerceError(
6692
+ "getReferralInfo is only available in vibe-coded or storefront mode",
6693
+ 400
6694
+ );
6649
6695
  }
6650
6696
  /**
6651
6697
  * AI-recommended reward for the logged-in customer — "recommended for you"
@@ -6669,13 +6715,22 @@ var BrainerceClient = class {
6669
6715
  401
6670
6716
  );
6671
6717
  }
6718
+ if (this.isVibeCodedMode()) {
6719
+ return this.vibeCodedRequest(
6720
+ "GET",
6721
+ "/loyalty/rewards/recommended"
6722
+ );
6723
+ }
6672
6724
  if (this.storeId && !this.apiKey) {
6673
6725
  return this.storefrontRequest(
6674
6726
  "GET",
6675
6727
  "/loyalty/rewards/recommended"
6676
6728
  );
6677
6729
  }
6678
- throw new BrainerceError("getRecommendedReward is only available in storefront mode", 400);
6730
+ throw new BrainerceError(
6731
+ "getRecommendedReward is only available in vibe-coded or storefront mode",
6732
+ 400
6733
+ );
6679
6734
  }
6680
6735
  /**
6681
6736
  * List the paid membership plans the customer can subscribe to (requires
@@ -6694,10 +6749,16 @@ var BrainerceClient = class {
6694
6749
  401
6695
6750
  );
6696
6751
  }
6752
+ if (this.isVibeCodedMode()) {
6753
+ return this.vibeCodedRequest("GET", "/loyalty/membership/plans");
6754
+ }
6697
6755
  if (this.storeId && !this.apiKey) {
6698
6756
  return this.storefrontRequest("GET", "/loyalty/membership/plans");
6699
6757
  }
6700
- throw new BrainerceError("getMembershipPlans is only available in storefront mode", 400);
6758
+ throw new BrainerceError(
6759
+ "getMembershipPlans is only available in vibe-coded or storefront mode",
6760
+ 400
6761
+ );
6701
6762
  }
6702
6763
  /**
6703
6764
  * List the customer's saved payment methods (display fields only — brand /
@@ -6717,6 +6778,12 @@ var BrainerceClient = class {
6717
6778
  401
6718
6779
  );
6719
6780
  }
6781
+ if (this.isVibeCodedMode()) {
6782
+ return this.vibeCodedRequest(
6783
+ "GET",
6784
+ "/loyalty/membership/payment-methods"
6785
+ );
6786
+ }
6720
6787
  if (this.storeId && !this.apiKey) {
6721
6788
  return this.storefrontRequest(
6722
6789
  "GET",
@@ -6724,7 +6791,7 @@ var BrainerceClient = class {
6724
6791
  );
6725
6792
  }
6726
6793
  throw new BrainerceError(
6727
- "getMySavedPaymentMethods is only available in storefront mode",
6794
+ "getMySavedPaymentMethods is only available in vibe-coded or storefront mode",
6728
6795
  400
6729
6796
  );
6730
6797
  }
@@ -6751,6 +6818,13 @@ var BrainerceClient = class {
6751
6818
  401
6752
6819
  );
6753
6820
  }
6821
+ if (this.isVibeCodedMode()) {
6822
+ return this.vibeCodedRequest(
6823
+ "POST",
6824
+ "/loyalty/membership/subscribe",
6825
+ params
6826
+ );
6827
+ }
6754
6828
  if (this.storeId && !this.apiKey) {
6755
6829
  return this.storefrontRequest(
6756
6830
  "POST",
@@ -6758,7 +6832,10 @@ var BrainerceClient = class {
6758
6832
  params
6759
6833
  );
6760
6834
  }
6761
- throw new BrainerceError("subscribeToMembership is only available in storefront mode", 400);
6835
+ throw new BrainerceError(
6836
+ "subscribeToMembership is only available in vibe-coded or storefront mode",
6837
+ 400
6838
+ );
6762
6839
  }
6763
6840
  /**
6764
6841
  * Cancel the customer's paid membership (requires customerToken).
@@ -6780,10 +6857,52 @@ var BrainerceClient = class {
6780
6857
  401
6781
6858
  );
6782
6859
  }
6860
+ if (this.isVibeCodedMode()) {
6861
+ return this.vibeCodedRequest("POST", "/loyalty/membership/cancel");
6862
+ }
6783
6863
  if (this.storeId && !this.apiKey) {
6784
6864
  return this.storefrontRequest("POST", "/loyalty/membership/cancel");
6785
6865
  }
6786
- throw new BrainerceError("cancelMembership is only available in storefront mode", 400);
6866
+ throw new BrainerceError(
6867
+ "cancelMembership is only available in vibe-coded or storefront mode",
6868
+ 400
6869
+ );
6870
+ }
6871
+ /**
6872
+ * Mint a short-lived session for the embeddable loyalty widget (Phase 5) and
6873
+ * return the ready-to-use iframe URL. Requires customerToken. The returned
6874
+ * `embedUrl` is safe to drop straight into an `<iframe src>` — it carries a
6875
+ * scoped ~15-minute session token, never the real customerToken. Re-call this
6876
+ * before the iframe reloads (e.g. on page navigation) to refresh it.
6877
+ *
6878
+ * @example
6879
+ * ```typescript
6880
+ * const { embedUrl } = await client.getLoyaltyWidgetSession();
6881
+ * // <iframe src={embedUrl} width="360" height="420" />
6882
+ * ```
6883
+ */
6884
+ async getLoyaltyWidgetSession() {
6885
+ if (!this.customerToken && !this.proxyMode) {
6886
+ throw new BrainerceError(
6887
+ "Customer token required. Call setCustomerToken() after login.",
6888
+ 401
6889
+ );
6890
+ }
6891
+ let result;
6892
+ if (this.isVibeCodedMode()) {
6893
+ result = await this.vibeCodedRequest("POST", "/loyalty/widget-session");
6894
+ } else if (this.storeId && !this.apiKey) {
6895
+ result = await this.storefrontRequest("POST", "/loyalty/widget-session");
6896
+ } else {
6897
+ throw new BrainerceError(
6898
+ "getLoyaltyWidgetSession is only available in vibe-coded or storefront mode",
6899
+ 400
6900
+ );
6901
+ }
6902
+ return {
6903
+ ...result,
6904
+ embedUrl: `${this.baseUrl}/api/loyalty/embed/${encodePathSegment(result.storeId)}/${encodePathSegment(result.sessionId)}`
6905
+ };
6787
6906
  }
6788
6907
  /**
6789
6908
  * Get the current customer's orders (requires customerToken)
@@ -9098,25 +9217,60 @@ function buildArticleJsonLd(post, opts) {
9098
9217
  return result;
9099
9218
  }
9100
9219
  function buildProductJsonLd(product, opts) {
9101
- const url = absoluteUrl(opts.siteUrl, opts.path ?? (product.slug ? `/products/${product.slug}` : void 0));
9220
+ const url = absoluteUrl(
9221
+ opts.siteUrl,
9222
+ opts.path ?? (product.slug ? `/products/${product.slug}` : void 0)
9223
+ );
9102
9224
  const images = (product.images ?? []).map((img) => img.url).filter(Boolean);
9103
9225
  const brand = opts.brandName ?? product.brands?.[0]?.name;
9104
9226
  const description = stripHtml(product.description).slice(0, 5e3);
9105
9227
  const effectivePrice = product.salePrice ?? product.basePrice;
9106
9228
  const inStock = product.inventory ? (product.inventory.available ?? 0) > 0 : true;
9107
9229
  const isVariable = product.type === "VARIABLE" && product.priceMin && product.priceMax;
9230
+ const itemCondition = "https://schema.org/NewCondition";
9231
+ const shippingDetails = (opts.shipping ?? []).filter((z) => z.amount !== null).map((z) => ({
9232
+ "@type": "OfferShippingDetails",
9233
+ shippingRate: { "@type": "MonetaryAmount", value: z.amount, currency: opts.currency },
9234
+ shippingDestination: { "@type": "DefinedRegion", addressCountry: z.countries },
9235
+ ...z.handlingTime != null || z.minDeliveryDays != null || z.maxDeliveryDays != null ? {
9236
+ deliveryTime: {
9237
+ "@type": "ShippingDeliveryTime",
9238
+ ...z.handlingTime != null ? {
9239
+ handlingTime: {
9240
+ "@type": "QuantitativeValue",
9241
+ minValue: 0,
9242
+ maxValue: z.handlingTime
9243
+ }
9244
+ } : {},
9245
+ ...z.minDeliveryDays != null || z.maxDeliveryDays != null ? {
9246
+ transitTime: {
9247
+ "@type": "QuantitativeValue",
9248
+ minValue: z.minDeliveryDays ?? z.maxDeliveryDays,
9249
+ maxValue: z.maxDeliveryDays ?? z.minDeliveryDays
9250
+ }
9251
+ } : {}
9252
+ }
9253
+ } : {}
9254
+ }));
9108
9255
  const offer = isVariable ? {
9109
9256
  "@type": "AggregateOffer",
9110
9257
  lowPrice: product.priceMin,
9111
9258
  highPrice: product.priceMax,
9112
9259
  priceCurrency: opts.currency,
9113
9260
  availability: inStock ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
9261
+ itemCondition,
9262
+ ...shippingDetails.length > 0 ? { shippingDetails } : {},
9114
9263
  ...url ? { url } : {}
9115
9264
  } : {
9116
9265
  "@type": "Offer",
9117
9266
  price: effectivePrice,
9118
9267
  priceCurrency: opts.currency,
9119
9268
  availability: inStock ? "https://schema.org/InStock" : "https://schema.org/OutOfStock",
9269
+ itemCondition,
9270
+ // Only meaningful for an active sale price with a known end date —
9271
+ // a regular (non-sale) price has no expiry to declare.
9272
+ ...product.salePrice && product.salePriceEndsAt ? { priceValidUntil: product.salePriceEndsAt } : {},
9273
+ ...shippingDetails.length > 0 ? { shippingDetails } : {},
9120
9274
  ...url ? { url } : {}
9121
9275
  };
9122
9276
  return {