@behio/storefront-sdk 0.21.0 → 0.23.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.
@@ -110,6 +110,8 @@ function toSdkError(err2) {
110
110
  // src/client.ts
111
111
  var BehioStorefront = class {
112
112
  constructor(config) {
113
+ /** Consent-gated persistent visitor id — set by the analytics tracker. */
114
+ this.analyticsVisitorId = null;
113
115
  // Token refresh lock
114
116
  this.isRefreshing = false;
115
117
  this.refreshPromise = null;
@@ -146,6 +148,40 @@ var BehioStorefront = class {
146
148
  this.shipping = new ShippingModule(this);
147
149
  }
148
150
  // --- Public methods ---
151
+ /**
152
+ * Called by the analytics tracker when the visitor grants (id) or revokes
153
+ * (null) analytics consent. When set, requests carry the X-Behio-Vid header
154
+ * so the backend can attribute orders to the visitor journey.
155
+ */
156
+ setAnalyticsVisitorId(id) {
157
+ this.analyticsVisitorId = id;
158
+ }
159
+ /** The consent-gated visitor id, if analytics consent was granted. */
160
+ getAnalyticsVisitorId() {
161
+ return this.analyticsVisitorId;
162
+ }
163
+ /**
164
+ * Fire-and-forget Behio Analytics ingest. Uses a bare keepalive fetch (not
165
+ * the interceptor pipeline) so flushes on pagehide still land, and swallows
166
+ * every error — analytics must never break the shop. The client sends no
167
+ * identity; the visitor hash is computed server-side from a daily salt.
168
+ */
169
+ async sendAnalyticsEvents(input) {
170
+ try {
171
+ const headers = {
172
+ "X-Api-Key": this.apiKey,
173
+ "Content-Type": "application/json"
174
+ };
175
+ if (this.shopDomain) headers["X-Shop-Domain"] = this.shopDomain;
176
+ await fetch(`${this.baseUrl}/storefront/v1/analytics/events`, {
177
+ method: "POST",
178
+ keepalive: true,
179
+ headers,
180
+ body: JSON.stringify(input)
181
+ });
182
+ } catch {
183
+ }
184
+ }
149
185
  /** Get basic shop info */
150
186
  async getShopInfo() {
151
187
  return this.request("GET", "/shop");
@@ -342,6 +378,9 @@ var BehioStorefront = class {
342
378
  if (this.cartSession) {
343
379
  headers["X-Cart-Session"] = this.cartSession;
344
380
  }
381
+ if (this.analyticsVisitorId) {
382
+ headers["X-Behio-Vid"] = this.analyticsVisitorId;
383
+ }
345
384
  if (options?.headers) {
346
385
  Object.assign(headers, options.headers);
347
386
  }
@@ -110,6 +110,8 @@ function toSdkError(err2) {
110
110
  // src/client.ts
111
111
  var BehioStorefront = class {
112
112
  constructor(config) {
113
+ /** Consent-gated persistent visitor id — set by the analytics tracker. */
114
+ this.analyticsVisitorId = null;
113
115
  // Token refresh lock
114
116
  this.isRefreshing = false;
115
117
  this.refreshPromise = null;
@@ -146,6 +148,40 @@ var BehioStorefront = class {
146
148
  this.shipping = new ShippingModule(this);
147
149
  }
148
150
  // --- Public methods ---
151
+ /**
152
+ * Called by the analytics tracker when the visitor grants (id) or revokes
153
+ * (null) analytics consent. When set, requests carry the X-Behio-Vid header
154
+ * so the backend can attribute orders to the visitor journey.
155
+ */
156
+ setAnalyticsVisitorId(id) {
157
+ this.analyticsVisitorId = id;
158
+ }
159
+ /** The consent-gated visitor id, if analytics consent was granted. */
160
+ getAnalyticsVisitorId() {
161
+ return this.analyticsVisitorId;
162
+ }
163
+ /**
164
+ * Fire-and-forget Behio Analytics ingest. Uses a bare keepalive fetch (not
165
+ * the interceptor pipeline) so flushes on pagehide still land, and swallows
166
+ * every error — analytics must never break the shop. The client sends no
167
+ * identity; the visitor hash is computed server-side from a daily salt.
168
+ */
169
+ async sendAnalyticsEvents(input) {
170
+ try {
171
+ const headers = {
172
+ "X-Api-Key": this.apiKey,
173
+ "Content-Type": "application/json"
174
+ };
175
+ if (this.shopDomain) headers["X-Shop-Domain"] = this.shopDomain;
176
+ await fetch(`${this.baseUrl}/storefront/v1/analytics/events`, {
177
+ method: "POST",
178
+ keepalive: true,
179
+ headers,
180
+ body: JSON.stringify(input)
181
+ });
182
+ } catch (e) {
183
+ }
184
+ }
149
185
  /** Get basic shop info */
150
186
  async getShopInfo() {
151
187
  return this.request("GET", "/shop");
@@ -231,7 +267,7 @@ var BehioStorefront = class {
231
267
  _optionalChain([this, 'access', _7 => _7.listeners, 'access', _8 => _8.get, 'call', _9 => _9(event), 'optionalAccess', _10 => _10.forEach, 'call', _11 => _11((fn) => {
232
268
  try {
233
269
  fn(data);
234
- } catch (e) {
270
+ } catch (e2) {
235
271
  }
236
272
  })]);
237
273
  }
@@ -342,6 +378,9 @@ var BehioStorefront = class {
342
378
  if (this.cartSession) {
343
379
  headers["X-Cart-Session"] = this.cartSession;
344
380
  }
381
+ if (this.analyticsVisitorId) {
382
+ headers["X-Behio-Vid"] = this.analyticsVisitorId;
383
+ }
345
384
  if (_optionalChain([options, 'optionalAccess', _14 => _14.headers])) {
346
385
  Object.assign(headers, options.headers);
347
386
  }
@@ -405,7 +444,7 @@ var BehioStorefront = class {
405
444
  try {
406
445
  await this.handleTokenRefresh();
407
446
  return this.rawRequest(method, path, { ...options, _isRetryAfterRefresh: true });
408
- } catch (e2) {
447
+ } catch (e3) {
409
448
  this.emit("error", apiError);
410
449
  throw apiError;
411
450
  }
@@ -421,7 +460,7 @@ var BehioStorefront = class {
421
460
  for (const interceptor of this.responseInterceptors) {
422
461
  try {
423
462
  await interceptor({ status: res.status, data: responseData, headers: res.headers });
424
- } catch (e3) {
463
+ } catch (e4) {
425
464
  }
426
465
  }
427
466
  return responseData;
@@ -0,0 +1,40 @@
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }// src/react/utils/format-price.ts
2
+ function formatPrice(amount, currency, locale) {
3
+ const resolvedLocale = _nullishCoalesce(locale, () => ( "cs"));
4
+ try {
5
+ return new Intl.NumberFormat(resolvedLocale, {
6
+ style: "currency",
7
+ currency,
8
+ minimumFractionDigits: Number.isInteger(amount) ? 0 : 2,
9
+ maximumFractionDigits: 2
10
+ }).format(amount);
11
+ } catch (e) {
12
+ return `${amount} ${currency}`;
13
+ }
14
+ }
15
+
16
+ // src/analytics.ts
17
+ function trackEcommerceEvent(event, payload) {
18
+ if (typeof window === "undefined") return;
19
+ const w = window;
20
+ try {
21
+ _optionalChain([w, 'access', _ => _.__behioEcommerceSink, 'optionalCall', _2 => _2(event, payload)]);
22
+ } catch (e2) {
23
+ }
24
+ try {
25
+ if (typeof w.gtag === "function") {
26
+ w.gtag("event", event, payload);
27
+ return;
28
+ }
29
+ if (Array.isArray(w.dataLayer)) {
30
+ w.dataLayer.push({ ecommerce: null });
31
+ w.dataLayer.push({ event, ecommerce: payload });
32
+ }
33
+ } catch (e3) {
34
+ }
35
+ }
36
+
37
+
38
+
39
+
40
+ exports.formatPrice = formatPrice; exports.trackEcommerceEvent = trackEcommerceEvent;
@@ -0,0 +1,40 @@
1
+ // src/react/utils/format-price.ts
2
+ function formatPrice(amount, currency, locale) {
3
+ const resolvedLocale = locale ?? "cs";
4
+ try {
5
+ return new Intl.NumberFormat(resolvedLocale, {
6
+ style: "currency",
7
+ currency,
8
+ minimumFractionDigits: Number.isInteger(amount) ? 0 : 2,
9
+ maximumFractionDigits: 2
10
+ }).format(amount);
11
+ } catch {
12
+ return `${amount} ${currency}`;
13
+ }
14
+ }
15
+
16
+ // src/analytics.ts
17
+ function trackEcommerceEvent(event, payload) {
18
+ if (typeof window === "undefined") return;
19
+ const w = window;
20
+ try {
21
+ w.__behioEcommerceSink?.(event, payload);
22
+ } catch {
23
+ }
24
+ try {
25
+ if (typeof w.gtag === "function") {
26
+ w.gtag("event", event, payload);
27
+ return;
28
+ }
29
+ if (Array.isArray(w.dataLayer)) {
30
+ w.dataLayer.push({ ecommerce: null });
31
+ w.dataLayer.push({ event, ecommerce: payload });
32
+ }
33
+ } catch {
34
+ }
35
+ }
36
+
37
+ export {
38
+ formatPrice,
39
+ trackEcommerceEvent
40
+ };
@@ -454,6 +454,12 @@ interface CheckoutAddress {
454
454
  phone?: string;
455
455
  }
456
456
  interface CheckoutInput {
457
+ /**
458
+ * Consent-gated Behio Analytics visitor id (behio_visitor_id). Optional;
459
+ * lets the backend attribute the order to the visitor journey. Send it only
460
+ * when the visitor granted analytics consent.
461
+ */
462
+ analyticsVisitorId?: string;
457
463
  shippingAddress: CheckoutAddress;
458
464
  billingAddress: CheckoutAddress;
459
465
  email: string;
@@ -993,6 +999,8 @@ interface SubmitQuoteInput {
993
999
  declare class BehioStorefront {
994
1000
  private baseUrl;
995
1001
  private apiKey;
1002
+ /** Consent-gated persistent visitor id — set by the analytics tracker. */
1003
+ private analyticsVisitorId;
996
1004
  private shopDomain?;
997
1005
  private defaultLocale?;
998
1006
  private defaultCurrency?;
@@ -1025,6 +1033,39 @@ declare class BehioStorefront {
1025
1033
  readonly quotes: QuotesModule;
1026
1034
  readonly addresses: AddressModule;
1027
1035
  readonly shipping: ShippingModule;
1036
+ /**
1037
+ * Called by the analytics tracker when the visitor grants (id) or revokes
1038
+ * (null) analytics consent. When set, requests carry the X-Behio-Vid header
1039
+ * so the backend can attribute orders to the visitor journey.
1040
+ */
1041
+ setAnalyticsVisitorId(id: string | null): void;
1042
+ /** The consent-gated visitor id, if analytics consent was granted. */
1043
+ getAnalyticsVisitorId(): string | null;
1044
+ /**
1045
+ * Fire-and-forget Behio Analytics ingest. Uses a bare keepalive fetch (not
1046
+ * the interceptor pipeline) so flushes on pagehide still land, and swallows
1047
+ * every error — analytics must never break the shop. The client sends no
1048
+ * identity; the visitor hash is computed server-side from a daily salt.
1049
+ */
1050
+ sendAnalyticsEvents(input: {
1051
+ sessionId?: string;
1052
+ /** Persistent consent-gated visitor id (behio_visitor_id). */
1053
+ visitorId?: string;
1054
+ events: Array<{
1055
+ type: "pageview" | "ecommerce" | "custom";
1056
+ name?: string;
1057
+ ts?: number;
1058
+ path?: string;
1059
+ referrer?: string;
1060
+ utmSource?: string;
1061
+ utmMedium?: string;
1062
+ utmCampaign?: string;
1063
+ dwellMs?: number;
1064
+ value?: number;
1065
+ currency?: string;
1066
+ props?: Record<string, unknown>;
1067
+ }>;
1068
+ }): Promise<void>;
1028
1069
  /** Get basic shop info */
1029
1070
  getShopInfo(): Promise<SdkResult<ShopInfo>>;
1030
1071
  /** Get SEO metadata for the shop homepage in the given locale (defaults to shop default). */
@@ -454,6 +454,12 @@ interface CheckoutAddress {
454
454
  phone?: string;
455
455
  }
456
456
  interface CheckoutInput {
457
+ /**
458
+ * Consent-gated Behio Analytics visitor id (behio_visitor_id). Optional;
459
+ * lets the backend attribute the order to the visitor journey. Send it only
460
+ * when the visitor granted analytics consent.
461
+ */
462
+ analyticsVisitorId?: string;
457
463
  shippingAddress: CheckoutAddress;
458
464
  billingAddress: CheckoutAddress;
459
465
  email: string;
@@ -993,6 +999,8 @@ interface SubmitQuoteInput {
993
999
  declare class BehioStorefront {
994
1000
  private baseUrl;
995
1001
  private apiKey;
1002
+ /** Consent-gated persistent visitor id — set by the analytics tracker. */
1003
+ private analyticsVisitorId;
996
1004
  private shopDomain?;
997
1005
  private defaultLocale?;
998
1006
  private defaultCurrency?;
@@ -1025,6 +1033,39 @@ declare class BehioStorefront {
1025
1033
  readonly quotes: QuotesModule;
1026
1034
  readonly addresses: AddressModule;
1027
1035
  readonly shipping: ShippingModule;
1036
+ /**
1037
+ * Called by the analytics tracker when the visitor grants (id) or revokes
1038
+ * (null) analytics consent. When set, requests carry the X-Behio-Vid header
1039
+ * so the backend can attribute orders to the visitor journey.
1040
+ */
1041
+ setAnalyticsVisitorId(id: string | null): void;
1042
+ /** The consent-gated visitor id, if analytics consent was granted. */
1043
+ getAnalyticsVisitorId(): string | null;
1044
+ /**
1045
+ * Fire-and-forget Behio Analytics ingest. Uses a bare keepalive fetch (not
1046
+ * the interceptor pipeline) so flushes on pagehide still land, and swallows
1047
+ * every error — analytics must never break the shop. The client sends no
1048
+ * identity; the visitor hash is computed server-side from a daily salt.
1049
+ */
1050
+ sendAnalyticsEvents(input: {
1051
+ sessionId?: string;
1052
+ /** Persistent consent-gated visitor id (behio_visitor_id). */
1053
+ visitorId?: string;
1054
+ events: Array<{
1055
+ type: "pageview" | "ecommerce" | "custom";
1056
+ name?: string;
1057
+ ts?: number;
1058
+ path?: string;
1059
+ referrer?: string;
1060
+ utmSource?: string;
1061
+ utmMedium?: string;
1062
+ utmCampaign?: string;
1063
+ dwellMs?: number;
1064
+ value?: number;
1065
+ currency?: string;
1066
+ props?: Record<string, unknown>;
1067
+ }>;
1068
+ }): Promise<void>;
1028
1069
  /** Get basic shop info */
1029
1070
  getShopInfo(): Promise<SdkResult<ShopInfo>>;
1030
1071
  /** Get SEO metadata for the shop homepage in the given locale (defaults to shop default). */
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as AddressSuggestion, a4 as AddressType, a5 as AddressTypes, L as AuthTokens, J as BackInStockSubscription, M as BehioApiError, a6 as BehioErrorCode, a7 as BehioEventHandler, a8 as BehioEventType, a9 as BehioNetworkError, a as BehioStorefront, B as BehioStorefrontConfig, s as Bundle, N as BundleItem, g as Cart, aa as CartBundleLine, ab as CartBundleLineItem, T as CartDiscount, U as CartItem, ac as CartItemProduct, C as Category, e as CategoryDetail, V as CheckoutAddress, n as CheckoutInput, ad as CheckoutPaymentMethod, E as CookieConsent, H as CookieConsentInput, t as CrossSellItem, i as CustomerAddress, h as CustomerProfile, ae as DataGroupFieldType, F as FilterField, X as FulfillmentStatus, af as FulfillmentStatuses, G as GiftCardBalance, ag as GiftCardSummary, Y as LoginInput, Z as MessageResponse, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, k as OrderDetail, _ as OrderItem, O as OrderListItem, $ as OrderStatus, ah as OrderStatusHistory, ai as OrderStatuses, aj as OrderTracking, p as Page, ak as PageAttachment, o as PageDetail, b as PaginatedResponse, a0 as PaymentStatus, al as PaymentStatuses, d as ProductDetail, f as ProductLabel, c as ProductListItem, am as ProductMedia, an as ProductMediaVariant, a1 as ProductPrice, a2 as ProductReview, v as ProductReviewsResponse, ao as ProductSort, ap as ProductSortValue, a3 as ProductVariant, aq as ProductVolumePrice, P as ProductsQuery, ar as QuoteItem, Q as QuoteRequest, R as RegisterInput, as as RegisterResult, at as RequestInterceptor, au as RequestInterceptorConfig, av as ResponseInterceptor, aw as ResponseInterceptorData, z as ReturnRequest, ax as ReturnRequestItem, y as ReturnStatus, ay as ReturnStatusItem, x as ReturnableOrder, az as ReturnableOrderItem, aA as SdkError, aB as SdkResult, aC as ShippingMethodSummary, aD as ShippingQuote, aE as ShippingQuoteInput, S as ShopInfo, aF as ShopScript, aG as ShopScriptPlacement, aH as ShopScriptType, q as ShopScripts, r as ShopSeo, I as SubmitQuoteInput, D as SubmitReturnInput, w as SubmitReviewInput, W as WishlistItem, aI as err, aJ as ok, aK as toSdkError } from './client-hCuGQERQ.mjs';
1
+ export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as AddressSuggestion, a4 as AddressType, a5 as AddressTypes, L as AuthTokens, J as BackInStockSubscription, M as BehioApiError, a6 as BehioErrorCode, a7 as BehioEventHandler, a8 as BehioEventType, a9 as BehioNetworkError, a as BehioStorefront, B as BehioStorefrontConfig, s as Bundle, N as BundleItem, g as Cart, aa as CartBundleLine, ab as CartBundleLineItem, T as CartDiscount, U as CartItem, ac as CartItemProduct, C as Category, e as CategoryDetail, V as CheckoutAddress, n as CheckoutInput, ad as CheckoutPaymentMethod, E as CookieConsent, H as CookieConsentInput, t as CrossSellItem, i as CustomerAddress, h as CustomerProfile, ae as DataGroupFieldType, F as FilterField, X as FulfillmentStatus, af as FulfillmentStatuses, G as GiftCardBalance, ag as GiftCardSummary, Y as LoginInput, Z as MessageResponse, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, k as OrderDetail, _ as OrderItem, O as OrderListItem, $ as OrderStatus, ah as OrderStatusHistory, ai as OrderStatuses, aj as OrderTracking, p as Page, ak as PageAttachment, o as PageDetail, b as PaginatedResponse, a0 as PaymentStatus, al as PaymentStatuses, d as ProductDetail, f as ProductLabel, c as ProductListItem, am as ProductMedia, an as ProductMediaVariant, a1 as ProductPrice, a2 as ProductReview, v as ProductReviewsResponse, ao as ProductSort, ap as ProductSortValue, a3 as ProductVariant, aq as ProductVolumePrice, P as ProductsQuery, ar as QuoteItem, Q as QuoteRequest, R as RegisterInput, as as RegisterResult, at as RequestInterceptor, au as RequestInterceptorConfig, av as ResponseInterceptor, aw as ResponseInterceptorData, z as ReturnRequest, ax as ReturnRequestItem, y as ReturnStatus, ay as ReturnStatusItem, x as ReturnableOrder, az as ReturnableOrderItem, aA as SdkError, aB as SdkResult, aC as ShippingMethodSummary, aD as ShippingQuote, aE as ShippingQuoteInput, S as ShopInfo, aF as ShopScript, aG as ShopScriptPlacement, aH as ShopScriptType, q as ShopScripts, r as ShopSeo, I as SubmitQuoteInput, D as SubmitReturnInput, w as SubmitReviewInput, W as WishlistItem, aI as err, aJ as ok, aK as toSdkError } from './client-B0VFrsad.mjs';
2
2
 
3
3
  /**
4
4
  * Format a price amount with currency using Intl.NumberFormat.
@@ -10,4 +10,40 @@ export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as Add
10
10
  */
11
11
  declare function formatPrice(amount: number, currency: string, locale?: string): string;
12
12
 
13
- export { formatPrice };
13
+ /**
14
+ * GA4 e-commerce event helper.
15
+ *
16
+ * Fires standard GA4 ecommerce events (view_item, add_to_cart, begin_checkout,
17
+ * purchase, ...) into whatever analytics runtime the shop has injected via
18
+ * `<StorefrontScripts/>`:
19
+ *
20
+ * - direct GA4 (`gtag` present) -> `gtag("event", name, payload)`
21
+ * - GTM (`dataLayer` array present) -> `dataLayer.push({event, ecommerce})`
22
+ * (with the recommended `ecommerce: null` reset push first)
23
+ * - neither present (no analytics configured, or consent not granted yet so
24
+ * the consent-gated script never loaded) -> silent no-op
25
+ *
26
+ * Consent stays the script layer's job: this helper never loads anything, it
27
+ * only talks to runtimes that already exist on the page.
28
+ */
29
+ type EcommerceEventName = "view_item" | "add_to_cart" | "remove_from_cart" | "view_cart" | "begin_checkout" | "add_payment_info" | "add_shipping_info" | "purchase";
30
+ type EcommerceItem = {
31
+ item_id: string;
32
+ item_name: string;
33
+ price?: number;
34
+ quantity?: number;
35
+ item_variant?: string;
36
+ item_category?: string;
37
+ };
38
+ type EcommercePayload = {
39
+ currency?: string;
40
+ /** Order / cart total in `currency`. */
41
+ value?: number;
42
+ /** Required for `purchase` — the order number. */
43
+ transaction_id?: string;
44
+ shipping?: number;
45
+ items: EcommerceItem[];
46
+ };
47
+ declare function trackEcommerceEvent(event: EcommerceEventName, payload: EcommercePayload): void;
48
+
49
+ export { type EcommerceEventName, type EcommerceItem, type EcommercePayload, formatPrice, trackEcommerceEvent };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as AddressSuggestion, a4 as AddressType, a5 as AddressTypes, L as AuthTokens, J as BackInStockSubscription, M as BehioApiError, a6 as BehioErrorCode, a7 as BehioEventHandler, a8 as BehioEventType, a9 as BehioNetworkError, a as BehioStorefront, B as BehioStorefrontConfig, s as Bundle, N as BundleItem, g as Cart, aa as CartBundleLine, ab as CartBundleLineItem, T as CartDiscount, U as CartItem, ac as CartItemProduct, C as Category, e as CategoryDetail, V as CheckoutAddress, n as CheckoutInput, ad as CheckoutPaymentMethod, E as CookieConsent, H as CookieConsentInput, t as CrossSellItem, i as CustomerAddress, h as CustomerProfile, ae as DataGroupFieldType, F as FilterField, X as FulfillmentStatus, af as FulfillmentStatuses, G as GiftCardBalance, ag as GiftCardSummary, Y as LoginInput, Z as MessageResponse, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, k as OrderDetail, _ as OrderItem, O as OrderListItem, $ as OrderStatus, ah as OrderStatusHistory, ai as OrderStatuses, aj as OrderTracking, p as Page, ak as PageAttachment, o as PageDetail, b as PaginatedResponse, a0 as PaymentStatus, al as PaymentStatuses, d as ProductDetail, f as ProductLabel, c as ProductListItem, am as ProductMedia, an as ProductMediaVariant, a1 as ProductPrice, a2 as ProductReview, v as ProductReviewsResponse, ao as ProductSort, ap as ProductSortValue, a3 as ProductVariant, aq as ProductVolumePrice, P as ProductsQuery, ar as QuoteItem, Q as QuoteRequest, R as RegisterInput, as as RegisterResult, at as RequestInterceptor, au as RequestInterceptorConfig, av as ResponseInterceptor, aw as ResponseInterceptorData, z as ReturnRequest, ax as ReturnRequestItem, y as ReturnStatus, ay as ReturnStatusItem, x as ReturnableOrder, az as ReturnableOrderItem, aA as SdkError, aB as SdkResult, aC as ShippingMethodSummary, aD as ShippingQuote, aE as ShippingQuoteInput, S as ShopInfo, aF as ShopScript, aG as ShopScriptPlacement, aH as ShopScriptType, q as ShopScripts, r as ShopSeo, I as SubmitQuoteInput, D as SubmitReturnInput, w as SubmitReviewInput, W as WishlistItem, aI as err, aJ as ok, aK as toSdkError } from './client-hCuGQERQ.js';
1
+ export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as AddressSuggestion, a4 as AddressType, a5 as AddressTypes, L as AuthTokens, J as BackInStockSubscription, M as BehioApiError, a6 as BehioErrorCode, a7 as BehioEventHandler, a8 as BehioEventType, a9 as BehioNetworkError, a as BehioStorefront, B as BehioStorefrontConfig, s as Bundle, N as BundleItem, g as Cart, aa as CartBundleLine, ab as CartBundleLineItem, T as CartDiscount, U as CartItem, ac as CartItemProduct, C as Category, e as CategoryDetail, V as CheckoutAddress, n as CheckoutInput, ad as CheckoutPaymentMethod, E as CookieConsent, H as CookieConsentInput, t as CrossSellItem, i as CustomerAddress, h as CustomerProfile, ae as DataGroupFieldType, F as FilterField, X as FulfillmentStatus, af as FulfillmentStatuses, G as GiftCardBalance, ag as GiftCardSummary, Y as LoginInput, Z as MessageResponse, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, k as OrderDetail, _ as OrderItem, O as OrderListItem, $ as OrderStatus, ah as OrderStatusHistory, ai as OrderStatuses, aj as OrderTracking, p as Page, ak as PageAttachment, o as PageDetail, b as PaginatedResponse, a0 as PaymentStatus, al as PaymentStatuses, d as ProductDetail, f as ProductLabel, c as ProductListItem, am as ProductMedia, an as ProductMediaVariant, a1 as ProductPrice, a2 as ProductReview, v as ProductReviewsResponse, ao as ProductSort, ap as ProductSortValue, a3 as ProductVariant, aq as ProductVolumePrice, P as ProductsQuery, ar as QuoteItem, Q as QuoteRequest, R as RegisterInput, as as RegisterResult, at as RequestInterceptor, au as RequestInterceptorConfig, av as ResponseInterceptor, aw as ResponseInterceptorData, z as ReturnRequest, ax as ReturnRequestItem, y as ReturnStatus, ay as ReturnStatusItem, x as ReturnableOrder, az as ReturnableOrderItem, aA as SdkError, aB as SdkResult, aC as ShippingMethodSummary, aD as ShippingQuote, aE as ShippingQuoteInput, S as ShopInfo, aF as ShopScript, aG as ShopScriptPlacement, aH as ShopScriptType, q as ShopScripts, r as ShopSeo, I as SubmitQuoteInput, D as SubmitReturnInput, w as SubmitReviewInput, W as WishlistItem, aI as err, aJ as ok, aK as toSdkError } from './client-B0VFrsad.js';
2
2
 
3
3
  /**
4
4
  * Format a price amount with currency using Intl.NumberFormat.
@@ -10,4 +10,40 @@ export { u as ActivePromotion, K as AddToCartInput, j as AddressDetail, A as Add
10
10
  */
11
11
  declare function formatPrice(amount: number, currency: string, locale?: string): string;
12
12
 
13
- export { formatPrice };
13
+ /**
14
+ * GA4 e-commerce event helper.
15
+ *
16
+ * Fires standard GA4 ecommerce events (view_item, add_to_cart, begin_checkout,
17
+ * purchase, ...) into whatever analytics runtime the shop has injected via
18
+ * `<StorefrontScripts/>`:
19
+ *
20
+ * - direct GA4 (`gtag` present) -> `gtag("event", name, payload)`
21
+ * - GTM (`dataLayer` array present) -> `dataLayer.push({event, ecommerce})`
22
+ * (with the recommended `ecommerce: null` reset push first)
23
+ * - neither present (no analytics configured, or consent not granted yet so
24
+ * the consent-gated script never loaded) -> silent no-op
25
+ *
26
+ * Consent stays the script layer's job: this helper never loads anything, it
27
+ * only talks to runtimes that already exist on the page.
28
+ */
29
+ type EcommerceEventName = "view_item" | "add_to_cart" | "remove_from_cart" | "view_cart" | "begin_checkout" | "add_payment_info" | "add_shipping_info" | "purchase";
30
+ type EcommerceItem = {
31
+ item_id: string;
32
+ item_name: string;
33
+ price?: number;
34
+ quantity?: number;
35
+ item_variant?: string;
36
+ item_category?: string;
37
+ };
38
+ type EcommercePayload = {
39
+ currency?: string;
40
+ /** Order / cart total in `currency`. */
41
+ value?: number;
42
+ /** Required for `purchase` — the order number. */
43
+ transaction_id?: string;
44
+ shipping?: number;
45
+ items: EcommerceItem[];
46
+ };
47
+ declare function trackEcommerceEvent(event: EcommerceEventName, payload: EcommercePayload): void;
48
+
49
+ export { type EcommerceEventName, type EcommerceItem, type EcommercePayload, formatPrice, trackEcommerceEvent };
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkXWYDXBLGjs = require('./chunk-XWYDXBLG.js');
4
3
 
4
+ var _chunkJIAOZ5YWjs = require('./chunk-JIAOZ5YW.js');
5
5
 
6
6
 
7
7
 
@@ -13,8 +13,8 @@ var _chunkXWYDXBLGjs = require('./chunk-XWYDXBLG.js');
13
13
 
14
14
 
15
15
 
16
- var _chunkBF4YVFHXjs = require('./chunk-BF4YVFHX.js');
17
16
 
17
+ var _chunk3RI2QBQOjs = require('./chunk-3RI2QBQO.js');
18
18
 
19
19
 
20
20
 
@@ -27,4 +27,6 @@ var _chunkBF4YVFHXjs = require('./chunk-BF4YVFHX.js');
27
27
 
28
28
 
29
29
 
30
- exports.AddressTypes = _chunkBF4YVFHXjs.AddressTypes; exports.BehioApiError = _chunkBF4YVFHXjs.BehioApiError; exports.BehioNetworkError = _chunkBF4YVFHXjs.BehioNetworkError; exports.BehioStorefront = _chunkBF4YVFHXjs.BehioStorefront; exports.FulfillmentStatuses = _chunkBF4YVFHXjs.FulfillmentStatuses; exports.OrderStatuses = _chunkBF4YVFHXjs.OrderStatuses; exports.PaymentStatuses = _chunkBF4YVFHXjs.PaymentStatuses; exports.ProductSort = _chunkBF4YVFHXjs.ProductSort; exports.err = _chunkBF4YVFHXjs.err; exports.formatPrice = _chunkXWYDXBLGjs.formatPrice; exports.ok = _chunkBF4YVFHXjs.ok; exports.toSdkError = _chunkBF4YVFHXjs.toSdkError;
30
+
31
+
32
+ exports.AddressTypes = _chunk3RI2QBQOjs.AddressTypes; exports.BehioApiError = _chunk3RI2QBQOjs.BehioApiError; exports.BehioNetworkError = _chunk3RI2QBQOjs.BehioNetworkError; exports.BehioStorefront = _chunk3RI2QBQOjs.BehioStorefront; exports.FulfillmentStatuses = _chunk3RI2QBQOjs.FulfillmentStatuses; exports.OrderStatuses = _chunk3RI2QBQOjs.OrderStatuses; exports.PaymentStatuses = _chunk3RI2QBQOjs.PaymentStatuses; exports.ProductSort = _chunk3RI2QBQOjs.ProductSort; exports.err = _chunk3RI2QBQOjs.err; exports.formatPrice = _chunkJIAOZ5YWjs.formatPrice; exports.ok = _chunk3RI2QBQOjs.ok; exports.toSdkError = _chunk3RI2QBQOjs.toSdkError; exports.trackEcommerceEvent = _chunkJIAOZ5YWjs.trackEcommerceEvent;
package/dist/index.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
- formatPrice
3
- } from "./chunk-YJ45WIQZ.mjs";
2
+ formatPrice,
3
+ trackEcommerceEvent
4
+ } from "./chunk-ZOZAJG6T.mjs";
4
5
  import {
5
6
  AddressTypes,
6
7
  BehioApiError,
@@ -13,7 +14,7 @@ import {
13
14
  err,
14
15
  ok,
15
16
  toSdkError
16
- } from "./chunk-PZED7VMQ.mjs";
17
+ } from "./chunk-2CD4CPEV.mjs";
17
18
  export {
18
19
  AddressTypes,
19
20
  BehioApiError,
@@ -26,5 +27,6 @@ export {
26
27
  err,
27
28
  formatPrice,
28
29
  ok,
29
- toSdkError
30
+ toSdkError,
31
+ trackEcommerceEvent
30
32
  };
package/dist/next.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as BehioStorefrontConfig, a as BehioStorefront } from './client-hCuGQERQ.mjs';
1
+ import { B as BehioStorefrontConfig, a as BehioStorefront } from './client-B0VFrsad.mjs';
2
2
 
3
3
  interface GetBehioOptions extends Partial<BehioStorefrontConfig> {
4
4
  /** Override the cart session cookie name (default: "behio_cart_session"). */
package/dist/next.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as BehioStorefrontConfig, a as BehioStorefront } from './client-hCuGQERQ.js';
1
+ import { B as BehioStorefrontConfig, a as BehioStorefront } from './client-B0VFrsad.js';
2
2
 
3
3
  interface GetBehioOptions extends Partial<BehioStorefrontConfig> {
4
4
  /** Override the cart session cookie name (default: "behio_cart_session"). */
package/dist/next.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
2
 
3
- var _chunkBF4YVFHXjs = require('./chunk-BF4YVFHX.js');
3
+ var _chunk3RI2QBQOjs = require('./chunk-3RI2QBQO.js');
4
4
 
5
5
  // src/next.ts
6
6
  var _headers = require('next/headers');
@@ -18,7 +18,7 @@ async function getBehio(options = {}) {
18
18
  const locale = _nullishCoalesce(options.locale, () => ( process.env.BEHIO_LOCALE));
19
19
  const currency = _nullishCoalesce(options.currency, () => ( process.env.BEHIO_CURRENCY));
20
20
  const cookieName = _nullishCoalesce(options.cartCookieName, () => ( CART_COOKIE_NAME));
21
- const client = new (0, _chunkBF4YVFHXjs.BehioStorefront)({
21
+ const client = new (0, _chunk3RI2QBQOjs.BehioStorefront)({
22
22
  apiKey,
23
23
  ...baseUrl ? { baseUrl } : {},
24
24
  ...locale ? { locale } : {},
package/dist/next.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  BehioStorefront
3
- } from "./chunk-PZED7VMQ.mjs";
3
+ } from "./chunk-2CD4CPEV.mjs";
4
4
 
5
5
  // src/next.ts
6
6
  import { cookies } from "next/headers";
package/dist/react.d.mts CHANGED
@@ -1,10 +1,10 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
  import * as _tanstack_react_query from '@tanstack/react-query';
3
3
  import { QueryClient } from '@tanstack/react-query';
4
- import { a as BehioStorefront, P as ProductsQuery, b as PaginatedResponse, c as ProductListItem, d as ProductDetail, C as Category, e as CategoryDetail, f as ProductLabel, F as FilterField, g as Cart, h as CustomerProfile, R as RegisterInput, i as CustomerAddress, A as AddressSuggestion, j as AddressDetail, O as OrderListItem, k as OrderDetail, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, n as CheckoutInput, o as PageDetail, p as Page, S as ShopInfo, q as ShopScripts, r as ShopSeo, s as Bundle, t as CrossSellItem, u as ActivePromotion, G as GiftCardBalance, W as WishlistItem, v as ProductReviewsResponse, w as SubmitReviewInput, x as ReturnableOrder, y as ReturnStatus, z as ReturnRequest, D as SubmitReturnInput, E as CookieConsent, H as CookieConsentInput, Q as QuoteRequest, I as SubmitQuoteInput, J as BackInStockSubscription } from './client-hCuGQERQ.mjs';
5
- export { K as AddToCartInput, L as AuthTokens, M as BehioApiError, N as BundleItem, T as CartDiscount, U as CartItem, V as CheckoutAddress, X as FulfillmentStatus, Y as LoginInput, Z as MessageResponse, _ as OrderItem, $ as OrderStatus, a0 as PaymentStatus, a1 as ProductPrice, a2 as ProductReview, a3 as ProductVariant } from './client-hCuGQERQ.mjs';
4
+ import { a as BehioStorefront, P as ProductsQuery, b as PaginatedResponse, c as ProductListItem, d as ProductDetail, C as Category, e as CategoryDetail, f as ProductLabel, F as FilterField, g as Cart, h as CustomerProfile, R as RegisterInput, i as CustomerAddress, A as AddressSuggestion, j as AddressDetail, O as OrderListItem, k as OrderDetail, l as OrderAccessRequestResponse, m as OrderAccessVerifyResponse, n as CheckoutInput, o as PageDetail, p as Page, S as ShopInfo, q as ShopScripts, r as ShopSeo, s as Bundle, t as CrossSellItem, u as ActivePromotion, G as GiftCardBalance, W as WishlistItem, v as ProductReviewsResponse, w as SubmitReviewInput, x as ReturnableOrder, y as ReturnStatus, z as ReturnRequest, D as SubmitReturnInput, E as CookieConsent, H as CookieConsentInput, Q as QuoteRequest, I as SubmitQuoteInput, J as BackInStockSubscription } from './client-B0VFrsad.mjs';
5
+ export { K as AddToCartInput, L as AuthTokens, M as BehioApiError, N as BundleItem, T as CartDiscount, U as CartItem, V as CheckoutAddress, X as FulfillmentStatus, Y as LoginInput, Z as MessageResponse, _ as OrderItem, $ as OrderStatus, a0 as PaymentStatus, a1 as ProductPrice, a2 as ProductReview, a3 as ProductVariant } from './client-B0VFrsad.mjs';
6
6
  import * as _tanstack_query_core from '@tanstack/query-core';
7
- export { formatPrice } from './index.mjs';
7
+ export { EcommerceEventName, EcommerceItem, EcommercePayload, formatPrice, trackEcommerceEvent } from './index.mjs';
8
8
 
9
9
  interface StorageAdapter {
10
10
  get(key: string): string | null;
@@ -504,6 +504,27 @@ interface StorefrontScriptsProps {
504
504
  */
505
505
  declare function StorefrontScripts({ visitorId: visitorIdProp }?: StorefrontScriptsProps): null;
506
506
 
507
+ /**
508
+ * Behio Analytics auto-tracker. Mount ONCE in the root layout (next to
509
+ * <StorefrontScripts/>).
510
+ *
511
+ * Identity is three-tiered:
512
+ * - anonymous: no consent needed — the server computes a daily-rotating hash,
513
+ * the client sends nothing identifying
514
+ * - consented: once the visitor grants analytics consent (the shop's consent
515
+ * banner, keyed by the existing `behio_visitor_id`), events carry that
516
+ * persistent first-party id — enabling returning-visitor metrics and the
517
+ * customer journey
518
+ * - customer: the backend links the id to the customer at checkout/login
519
+ *
520
+ * Captures: pageviews (load + SPA route changes), visibility-aware dwell time
521
+ * per page, click events on interactive elements, UTM + referrer on landing.
522
+ * Events are batched (flush on 20 events / 5 s / route change / pagehide) via
523
+ * keepalive fetch. Listens for the `behio:consent-changed` window event to
524
+ * pick up consent grants/revocations immediately.
525
+ */
526
+ declare function BehioAnalyticsTracker(): null;
527
+
507
528
  /** List all active bundles. */
508
529
  declare function useBundles(options?: {
509
530
  enabled?: boolean;
@@ -1028,4 +1049,4 @@ declare function useNotifyWhenAvailable(): _tanstack_react_query.UseMutationResu
1028
1049
  */
1029
1050
  declare function useBehioClient(): BehioStorefront;
1030
1051
 
1031
- export { ActivePromotion, BehioProvider, type BehioProviderProps, Bundle, Cart, Category, CategoryDetail, CheckoutInput, CookieConsent, CookieConsentInput, CrossSellItem, CurrencySwitcher, type CurrencySwitcherProps, type CurrencySwitcherRenderProps, CustomerAddress, CustomerProfile, FilterField, GiftCardBalance, OrderDetail, OrderListItem, Page, PageDetail, PaginatedResponse, ProductDetail, ProductLabel, ProductListItem, ProductReviewsResponse, ProductsQuery, QuoteRequest, RegisterInput, ReturnRequest, ShopInfo, ShopSeo, type StorageAdapter, StorefrontScripts, type StorefrontScriptsProps, SubmitQuoteInput, SubmitReturnInput, SubmitReviewInput, type UseAddressAutocompleteOptions, type UseAddressAutocompleteReturn, type UseAddressesOptions, type UseCartCountOptions, type UseCartOptions, type UseCategoriesOptions, type UseCategoryOptions, type UseCurrencyResult, type UseCustomerOptions, type UseFeaturedOptions, type UseFiltersOptions, type UseLabelsOptions, type UseOrderOptions, type UseOrdersOptions, type UsePageOptions, type UsePagesOptions, type UseProductOptions, type UseProductsOptions, type UseSearchOptions, type UseShopInfoOptions, type UseShopScriptsOptions, type UseShopSeoOptions, WishlistItem, cookieStorage, createMemoryStorage, detectStorage, localStorageAdapter, memoryStorage, useAddressAutocomplete, useAddresses, useAuth, useBehio, useBehioClient, useBundle, useBundles, useCart, useCartCount, useCategories, useCategory, useCheckout, useCookieConsent, useCrossSell, useCurrency, useCustomer, useFeatured, useFilters, useGiftCardBalance, useIsInWishlist, useLabels, useLookupReturnableOrder, useNotifyWhenAvailable, useOrder, useOrderAccess, useOrders, usePage, usePages, useProduct, useProductPromotions, useProductReviews, useProducts, useQuoteStatus, useReturnStatus, useSearch, useShopInfo, useShopScripts, useShopSeo, useSubmitQuote, useSubmitReturn, useSubmitReview, useWishlist };
1052
+ export { ActivePromotion, BehioAnalyticsTracker, BehioProvider, type BehioProviderProps, Bundle, Cart, Category, CategoryDetail, CheckoutInput, CookieConsent, CookieConsentInput, CrossSellItem, CurrencySwitcher, type CurrencySwitcherProps, type CurrencySwitcherRenderProps, CustomerAddress, CustomerProfile, FilterField, GiftCardBalance, OrderDetail, OrderListItem, Page, PageDetail, PaginatedResponse, ProductDetail, ProductLabel, ProductListItem, ProductReviewsResponse, ProductsQuery, QuoteRequest, RegisterInput, ReturnRequest, ShopInfo, ShopSeo, type StorageAdapter, StorefrontScripts, type StorefrontScriptsProps, SubmitQuoteInput, SubmitReturnInput, SubmitReviewInput, type UseAddressAutocompleteOptions, type UseAddressAutocompleteReturn, type UseAddressesOptions, type UseCartCountOptions, type UseCartOptions, type UseCategoriesOptions, type UseCategoryOptions, type UseCurrencyResult, type UseCustomerOptions, type UseFeaturedOptions, type UseFiltersOptions, type UseLabelsOptions, type UseOrderOptions, type UseOrdersOptions, type UsePageOptions, type UsePagesOptions, type UseProductOptions, type UseProductsOptions, type UseSearchOptions, type UseShopInfoOptions, type UseShopScriptsOptions, type UseShopSeoOptions, WishlistItem, cookieStorage, createMemoryStorage, detectStorage, localStorageAdapter, memoryStorage, useAddressAutocomplete, useAddresses, useAuth, useBehio, useBehioClient, useBundle, useBundles, useCart, useCartCount, useCategories, useCategory, useCheckout, useCookieConsent, useCrossSell, useCurrency, useCustomer, useFeatured, useFilters, useGiftCardBalance, useIsInWishlist, useLabels, useLookupReturnableOrder, useNotifyWhenAvailable, useOrder, useOrderAccess, useOrders, usePage, usePages, useProduct, useProductPromotions, useProductReviews, useProducts, useQuoteStatus, useReturnStatus, useSearch, useShopInfo, useShopScripts, useShopSeo, useSubmitQuote, useSubmitReturn, useSubmitReview, useWishlist };