bitsnap-react 1.12.1 → 1.14.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/README.md +19 -6
- package/dist/CartProvider-6D5WE2HA.js +2 -0
- package/dist/CartProvider-6D5WE2HA.js.map +1 -0
- package/dist/CartProvider-GLUQHAG3.mjs +2 -0
- package/dist/analytics.d.mts +2 -2
- package/dist/analytics.d.ts +2 -2
- package/dist/analytics.js +1 -1
- package/dist/analytics.js.map +1 -1
- package/dist/analytics.mjs +1 -1
- package/dist/catalog.d.mts +1 -1
- package/dist/catalog.d.ts +1 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/{chunk-HDLCLZOK.js → chunk-3N2VK426.js} +2 -2
- package/dist/chunk-3N2VK426.js.map +1 -0
- package/dist/{chunk-T2YSOHJM.mjs → chunk-3OEKRPWV.mjs} +2 -2
- package/dist/{chunk-T2YSOHJM.mjs.map → chunk-3OEKRPWV.mjs.map} +1 -1
- package/dist/{chunk-I6BRDRPB.js → chunk-5DDLYVBG.js} +2 -2
- package/dist/chunk-5DDLYVBG.js.map +1 -0
- package/dist/{chunk-4ZFIL5S7.js → chunk-7SYNGA3R.js} +2 -2
- package/dist/chunk-7SYNGA3R.js.map +1 -0
- package/dist/chunk-AWG5OAK7.js +2 -0
- package/dist/chunk-AWG5OAK7.js.map +1 -0
- package/dist/{chunk-G3VVAVG7.mjs → chunk-CYLZ5GYW.mjs} +2 -2
- package/dist/{chunk-STVEBT6M.js → chunk-FLDI3BPY.js} +2 -2
- package/dist/chunk-FLDI3BPY.js.map +1 -0
- package/dist/chunk-GKFET34B.mjs +2 -0
- package/dist/chunk-GKFET34B.mjs.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/{chunk-3ITTSNWG.js → chunk-JXVAT2ZE.js} +2 -2
- package/dist/chunk-JXVAT2ZE.js.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-MDCP5JNP.mjs +2 -0
- package/dist/chunk-MDCP5JNP.mjs.map +1 -0
- package/dist/{chunk-VF62KDNS.mjs → chunk-MVOJMCZG.mjs} +2 -2
- package/dist/{chunk-MZSLLGFS.js → chunk-PLS5RR27.js} +2 -2
- package/dist/chunk-PLS5RR27.js.map +1 -0
- package/dist/{chunk-VRL3IF5J.js → chunk-R2M6W4LD.js} +3 -3
- package/dist/chunk-R2M6W4LD.js.map +1 -0
- package/dist/{chunk-HBPSSGYN.mjs → chunk-SKFE6TUP.mjs} +2 -2
- package/dist/{chunk-GJNFDUJN.mjs → chunk-U5SAO2SH.mjs} +3 -3
- package/dist/chunk-U5SAO2SH.mjs.map +1 -0
- package/dist/{chunk-DRAKVCD7.mjs → chunk-VY7RNSFP.mjs} +2 -2
- package/dist/{chunk-VDLJW4JJ.mjs → chunk-VYYUTJZB.mjs} +2 -2
- package/dist/chunk-W3RGQYPD.js +2 -0
- package/dist/chunk-W3RGQYPD.js.map +1 -0
- package/dist/consent.js +4 -4
- package/dist/consent.js.map +1 -1
- package/dist/consent.mjs +4 -4
- package/dist/consent.mjs.map +1 -1
- package/dist/course.d.mts +2 -2
- package/dist/course.d.ts +2 -2
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/embed/analytics.js +1 -1
- package/dist/embed/consent.js +4 -4
- package/dist/errors.js.map +1 -1
- package/dist/index.d.mts +20 -10
- package/dist/index.d.ts +20 -10
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/{instrument-CmxK7S4T.d.mts → instrument-BE8ktMUv.d.mts} +14 -0
- package/dist/{instrument-CmxK7S4T.d.ts → instrument-BE8ktMUv.d.ts} +14 -0
- package/dist/internal.js.map +1 -1
- package/dist/methods-N35A2OGE.mjs +2 -0
- package/dist/methods-WSICR2JH.js +2 -0
- package/dist/methods-WSICR2JH.js.map +1 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +1 -1
- package/dist/returns.d.ts +1 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-BnVWLcoB.d.mts → types-DP1vxo5E.d.mts} +1 -1
- package/dist/{types-i-IuN4Im.d.ts → types-u8VwmC3j.d.ts} +1 -1
- package/package.json +38 -13
- package/dist/CartProvider-WPJWECBS.mjs +0 -2
- package/dist/CartProvider-YPZ3HD7W.js +0 -2
- package/dist/CartProvider-YPZ3HD7W.js.map +0 -1
- package/dist/chunk-3ITTSNWG.js.map +0 -1
- package/dist/chunk-4BV5IUZH.js +0 -2
- package/dist/chunk-4BV5IUZH.js.map +0 -1
- package/dist/chunk-4ZFIL5S7.js.map +0 -1
- package/dist/chunk-ADYVTMGH.mjs +0 -2
- package/dist/chunk-ADYVTMGH.mjs.map +0 -1
- package/dist/chunk-GJNFDUJN.mjs.map +0 -1
- package/dist/chunk-HDLCLZOK.js.map +0 -1
- package/dist/chunk-I6BRDRPB.js.map +0 -1
- package/dist/chunk-MZSLLGFS.js.map +0 -1
- package/dist/chunk-STVEBT6M.js.map +0 -1
- package/dist/chunk-T3PAOMHI.mjs +0 -2
- package/dist/chunk-T3PAOMHI.mjs.map +0 -1
- package/dist/chunk-VRL3IF5J.js.map +0 -1
- package/dist/chunk-XIHGWNTS.js +0 -2
- package/dist/chunk-XIHGWNTS.js.map +0 -1
- package/dist/methods-FVDH6Y57.mjs +0 -2
- package/dist/methods-ISVX5JQ7.js +0 -2
- package/dist/methods-ISVX5JQ7.js.map +0 -1
- /package/dist/{CartProvider-WPJWECBS.mjs.map → CartProvider-GLUQHAG3.mjs.map} +0 -0
- /package/dist/{chunk-G3VVAVG7.mjs.map → chunk-CYLZ5GYW.mjs.map} +0 -0
- /package/dist/{chunk-VF62KDNS.mjs.map → chunk-MVOJMCZG.mjs.map} +0 -0
- /package/dist/{chunk-HBPSSGYN.mjs.map → chunk-SKFE6TUP.mjs.map} +0 -0
- /package/dist/{chunk-DRAKVCD7.mjs.map → chunk-VY7RNSFP.mjs.map} +0 -0
- /package/dist/{chunk-VDLJW4JJ.mjs.map → chunk-VYYUTJZB.mjs.map} +0 -0
- /package/dist/{methods-FVDH6Y57.mjs.map → methods-N35A2OGE.mjs.map} +0 -0
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{A as N,f as m,i,j as d,k as R,s as c,t as E,u as p,v as S,w as l,x as y,y as I,z as T}from"./chunk-CYLZ5GYW.mjs";import{d as a}from"./chunk-GKFET34B.mjs";var B=["orders","order","confirmation","result","myReturns","myReturn"];function P(e){return B.includes(e)}function f(e){return e?{name:"orders"}:{name:"email"}}function C(e,n){switch(n.type){case"SESSION_EXPIRED":return P(e.name)?{name:"email"}:e;case"CODE_SENT":return e.name==="email"?{name:"code"}:e;case"AUTHENTICATED":return e.name==="email"||e.name==="code"?{name:"orders"}:e;case"SELECT_ORDER":return e.name==="orders"?{name:"order",orderId:n.orderId}:e;case"REVIEW":return e.name==="order"?{name:"confirmation",orderId:e.orderId,items:n.items,note:n.note}:e;case"SUBMITTED":return e.name==="confirmation"?{name:"result",returnId:n.returnId}:e;case"OPEN_MY_RETURNS":return e.name==="orders"||e.name==="result"?{name:"myReturns"}:e;case"SELECT_RETURN":return e.name==="myReturns"?{name:"myReturn",returnId:n.returnId}:e;case"CONTINUE":return e.name==="result"?{name:"orders"}:e;case"BACK":switch(e.name){case"code":return{name:"email"};case"order":case"myReturns":return{name:"orders"};case"confirmation":return{name:"order",orderId:e.orderId,items:e.items,note:e.note};case"myReturn":return{name:"myReturns"};default:return e}}}var x={email:1,code:2,orders:3,order:4,confirmation:5,result:6},_=6;function O(e){return x[e]}import{useEffect as D,useReducer as A}from"react";import{jsx as o,jsxs as L}from"react/jsx-runtime";function g({current:e}){let n=i(),r=m("stepIndicator");return o("p",{"data-bitsnap-returns-slot":"stepIndicator",className:a("text-xs",r.className),style:r.style,children:n("stepIndicator",{current:e,total:_})})}function b({panelToken:e}){let{status:n}=d("BitsnapReturns"),[r,t]=A(C,f(!1));if(D(()=>{n==="authenticated"?t({type:"AUTHENTICATED"}):n==="anonymous"&&t({type:"SESSION_EXPIRED"})},[n]),n==="exchanging"||n==="hydrating"&&e)return o(c,{});let s=O(r.name);return L("div",{className:"flex flex-col gap-4",children:[s!=null&&o(g,{current:s}),r.name==="email"&&o(E,{onSubmitted:()=>t({type:"CODE_SENT"})}),r.name==="code"&&o(p,{onVerified:()=>t({type:"AUTHENTICATED"}),onBack:()=>t({type:"BACK"})}),r.name==="orders"&&o(S,{showLogout:!e,onSelectOrder:u=>t({type:"SELECT_ORDER",orderId:u}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="order"&&o(l,{orderId:r.orderId,initialItems:r.items,initialNote:r.note,onBack:()=>t({type:"BACK"}),onContinue:({items:u,note:U})=>t({type:"REVIEW",items:u,note:U})}),r.name==="confirmation"&&o(y,{orderId:r.orderId,items:r.items,note:r.note,onBack:()=>t({type:"BACK"}),onSubmitted:u=>t({type:"SUBMITTED",returnId:u})}),r.name==="result"&&o(I,{returnId:r.returnId,onContinue:()=>t({type:"CONTINUE"}),onOpenMyReturns:()=>t({type:"OPEN_MY_RETURNS"})}),r.name==="myReturns"&&o(T,{onSelectReturn:u=>t({type:"SELECT_RETURN",returnId:u}),onBack:()=>t({type:"BACK"})}),r.name==="myReturn"&&o(N,{returnId:r.returnId,onBack:()=>t({type:"BACK"})})]})}function q(e){return o(R,{...e,children:o(b,{panelToken:e.panelAccessToken!=null&&e.panelAccessToken!==""})})}export{q as a};
|
|
2
|
+
//# sourceMappingURL=chunk-VY7RNSFP.mjs.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as dt,b as ut}from"./chunk-KOVKUJAW.mjs";import{c as tt,d as F,e as it,f as U,g as ct,i as lt,k as D}from"./chunk-T3PAOMHI.mjs";import{f as et,k as rt,l as ot,m as nt,n as st,p as at}from"./chunk-T2YSOHJM.mjs";var wt=["root","grid","card","cardLink","image","imagePlaceholder","body","name","description","price","comparePrice","badge","actions","addToCartButton","selectButton","message","pagination","paginationButton","pageIndicator","emptyState","error","retryButton","skeleton"],Et={fontFamily:"--bitsnap-products-font-family",fontSize:"--bitsnap-products-font-size",background:"--bitsnap-products-background",surface:"--bitsnap-products-surface",foreground:"--bitsnap-products-foreground",mutedForeground:"--bitsnap-products-muted-foreground",border:"--bitsnap-products-border",buttonBackground:"--bitsnap-products-button-background",buttonForeground:"--bitsnap-products-button-foreground",buttonHoverBackground:"--bitsnap-products-button-hover-background",hoverSurface:"--bitsnap-products-hover-surface",focusRing:"--bitsnap-products-focus-ring",error:"--bitsnap-products-error",badgeBackground:"--bitsnap-products-badge-background",badgeForeground:"--bitsnap-products-badge-foreground",radius:"--bitsnap-products-radius"},_t={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",radius:"8px"},dark:{background:"#18181b",surface:"#27272a",foreground:"#fafafa",mutedForeground:"#a1a1aa",border:"#3f3f46",buttonBackground:"#fafafa",buttonForeground:"#18181b",buttonHoverBackground:"#e4e4e7",hoverSurface:"#3f3f46",focusRing:"#a1a1aa",error:"#f87171",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",radius:"8px"}},Dt=[];function pt(t){let e=dt(t,{defaultTheme:"light",presets:_t,variables:Et,shadcnVariables:Dt});return{theme:e.theme,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle}}function q(t,e){return ut(t.elements,e)}function mt(t,e){try{return new Intl.NumberFormat(t,{style:"currency",currency:e,currencyDisplay:"symbol"})}catch{return}}function H(t,e,r=D){let o=t/100,n=mt(r,e)??mt(D,e);return n!=null?n.format(o):`${o.toFixed(2)} ${e}`}import{useCallback as Pt,useEffect as jt,useMemo as Ft,useState as z}from"react";var Ot=24,Nt=48,M=class extends Error{status;constructor(e,r){super(e),this.name="ProductListError",this.status=r}};function O(t){return t==null||!Number.isFinite(t)?Ot:Math.min(Nt,Math.max(1,Math.floor(t)))}function ft(t,e){return Math.max(1,Math.ceil(t/e))}function N(t){return t.replace(/\/+$/,"")}function Rt(t){let e=new URLSearchParams;e.set("limit",String(t.limit)),e.set("offset",String(t.offset)),t.locale&&e.set("locale",t.locale);let r=t.search?.trim();return r&&e.set("search",r),`${N(t.host)}/api/integrations/${encodeURIComponent(t.projectID)}/public-commerce/product-list?${e.toString()}`}function Bt(t){return typeof t=="object"&&t!=null&&Array.isArray(t.items)&&typeof t.totalCount=="number"}async function gt(t,e){let r=await fetch(tt(Rt(t)),{method:"GET",credentials:"omit",headers:{Accept:"application/json"},signal:e});if(!r.ok)throw new M(`Could not load products (${r.status})`,r.status);let o=await r.json();if(!Bt(o))throw new M("Unexpected product list response");return o}function G(t){let{projectID:e,locale:r,search:o,initialData:n}=t,[s]=z(()=>U),i=t.host??s,d=O(t.pageSize),c=JSON.stringify([e,i,r??null,o?.trim()??null,d]),[m,u]=z({queryKey:c,page:1});m.queryKey!==c&&u({queryKey:c,page:1});let[b,v]=z(0),[f,l]=z(()=>({requestKey:n!=null?`${c}|1|0`:"",data:n,error:void 0})),g=f.data?.totalCount??0,P=ft(g,d),h=m.queryKey===c?m.page:1,k=g>0?Math.min(h,P):h,C=`${c}|${k}|${b}`,T=f.requestKey===C;jt(()=>{if(T)return;let y=new AbortController;return gt({projectID:e,host:i,locale:r,search:o,limit:d,offset:(k-1)*d},y.signal).then(x=>{y.signal.aborted||l({requestKey:C,data:x,error:void 0})},x=>{y.signal.aborted||l(E=>({requestKey:C,data:E.data,error:x instanceof Error?x:new Error(String(x))}))}),()=>y.abort()},[C,T]);let I=Pt(y=>{let x=Math.max(1,Math.floor(y));u({queryKey:c,page:g>0?Math.min(x,P):x})},[c,g,P]),A=Pt(()=>v(y=>y+1),[]);return Ft(()=>({products:f.data?.items??[],totalCount:g,page:k,pageCount:P,setPage:I,isLoading:!T,error:T?f.error:void 0,refetch:A}),[f,g,k,P,I,T,A])}import{createContext as xt,useCallback as V,useContext as Tt,useEffect as R,useMemo as B,useRef as K,useState as zt}from"react";function bt(t,e){if(t.projectID!=null&&t.projectID!==e.projectID)return{ok:!1,reason:`the page cart already belongs to project "${t.projectID}"`};let r=null,o=e.host?N(e.host):"",n=N(t.host);if(o&&o!==n){if(n!==N(t.defaultHost))return{ok:!1,reason:`the page cart already uses the host "${t.host}"`};r=o}return{ok:!0,setProjectID:t.projectID==null?e.projectID:null,setHost:r}}function Q(t,e){let r=e.cartItemId!=null&&e.cartItemId!==e.id?e.cartItemId:null;t.track("add_to_cart",{qty:1,value_minor:e.price,currency:e.currency},{product_id:e.id,variant_id:r})}async function yt(t,e){let[{Bitsnap:r},{getProjectID:o,setProjectID:n}]=await Promise.all([import("./methods-FVDH6Y57.mjs"),import("./CartProvider-WPJWECBS.mjs")]),s=bt({projectID:o(),host:U,defaultHost:it},e);if(!s.ok)return Ut(s.reason);if(s.setProjectID!=null&&n(s.setProjectID),s.setHost!=null&&ct(s.setHost),await r.addProductToCart(t.cartItemId??t.id,1,void 0,{url:e.url,name:t.name,price:t.price,currency:t.currency,analytics:rt})!=null)throw new Error("Could not add the product to the cart");e.analytics!=null&&Q(e.analytics,t),e.showCart&&r.showCart()}function Ut(t){throw console.warn(`bitsnap-react: ProductList did not add to the cart because ${t}. Pass onAddToCart to use another cart.`),new Error("The page cart belongs to another project or host")}var $=50,Ht=1e3;function Lt(t,e=Ht){let r=new Set,o=new Map,n=[],s=[],i,d,c=!1;function m(){for(d!==void 0&&clearTimeout(d),d=void 0;n.length>0;){let l=n.slice(0,$),g=s.slice(0,$);n=n.slice($),s=s.slice($);try{t({productIds:l,positions:g})}catch{}}}function u(){m();try{et()?.flush()}catch{}}let b=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&u()};function v(){c||typeof window>"u"||(c=!0,window.addEventListener("pagehide",u,!0),document.addEventListener("visibilitychange",b,!0))}function f(){if(i)return i;if(!(typeof IntersectionObserver>"u"))return i=new IntersectionObserver(l=>{for(let g of l){let P=o.get(g.target);!P||!g.isIntersecting||g.intersectionRatio<.5||(o.delete(g.target),i?.unobserve(g.target),!r.has(P.id)&&(r.add(P.id),n.push(P.id),s.push(P.position)))}n.length>0&&d===void 0&&(d=setTimeout(m,e),d.unref?.())},{threshold:[.5]}),v(),i}return{observe(l,g,P){try{if(r.has(g))return()=>{};let h=f();return h?(o.set(l,{id:g,position:P}),h.observe(l),()=>{o.delete(l),h.unobserve(l)}):()=>{}}catch{return()=>{}}},flush:m,destroy(){try{m(),i?.disconnect(),c&&(window.removeEventListener("pagehide",u,!0),document.removeEventListener("visibilitychange",b,!0),c=!1)}catch{}i=void 0,o.clear()}}}var Mt={en:{addToCart:"Add to cart",addingToCart:"Adding\u2026",addedToCart:"Added to cart",addToCartError:"Could not add to the cart. Try again.",chooseOptions:"Choose",viewProduct:"View",unavailable:"Unavailable",subscription:"Subscription",priceFrom:"from {price}",originalPrice:"Original price",loading:"Loading products",empty:"There are no products to show.",error:"Could not load the products.",retry:"Try again",pagination:"Pagination",previousPage:"Previous",nextPage:"Next",pageOf:"Page {page} of {pageCount}"},pl:{addToCart:"Dodaj do koszyka",addingToCart:"Dodawanie\u2026",addedToCart:"Dodano do koszyka",addToCartError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",chooseOptions:"Wybierz",viewProduct:"Zobacz",unavailable:"Niedost\u0119pny",subscription:"Subskrypcja",priceFrom:"od {price}",originalPrice:"Cena przed obni\u017Ck\u0105",loading:"\u0141adowanie produkt\xF3w",empty:"Brak produkt\xF3w do wy\u015Bwietlenia.",error:"Nie uda\u0142o si\u0119 za\u0142adowa\u0107 produkt\xF3w.",retry:"Spr\xF3buj ponownie",pagination:"Paginacja",previousPage:"Poprzednia",nextPage:"Nast\u0119pna",pageOf:"Strona {page} z {pageCount}"}};function ht(t,e){return lt(Mt,t,e)}function X(t,e){return t.replace(/\{(\w+)\}/g,(r,o)=>o in e?String(e[o]):r)}import{Fragment as kt,jsx as a,jsxs as S}from"react/jsx-runtime";var vt=xt(void 0),$t={observe:()=>()=>{},clicked:()=>{}},Ct=xt($t);function j(){let t=Tt(vt);if(t==null)throw new Error("ProductList parts must be rendered inside ProductList");return t}function p(t,e){let{appearance:r}=j(),o=q(r,t);return{"data-bitsnap-products-slot":t,className:F(e,o?.className),style:o?.style}}var Z="inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50",St=`${Z} w-full`,Kt=`${St} no-underline`;function Vt({product:t,onAdd:e}){let{texts:r}=j(),[o,n]=zt("idle"),s=p("addToCartButton",St),i=p("message","mt-2 text-xs");R(()=>{if(o!=="added")return;let m=setTimeout(()=>n("idle"),2e3);return()=>clearTimeout(m)},[o]);let d=V(async()=>{n("adding");try{await e(),n("added")}catch(m){console.error("bitsnap-react: could not add to the cart",m),n("error")}},[e]),c=o==="adding"?r.addingToCart:o==="added"?r.addedToCart:r.addToCart;return S(kt,{children:[a("button",{type:"button",...s,disabled:o==="adding","aria-label":`${c}: ${t.name}`,onClick:d,children:c}),o==="error"?a("p",{...i,role:"alert",children:r.addToCartError}):null]})}function qt({product:t,position:e,href:r,onAdd:o,renderItem:n}){let{texts:s,locale:i}=j(),d=Tt(Ct),c=K(null);R(()=>{if(c.current!=null)return d.observe(c.current,t.id,e)},[d,t.id,e]);let m=V(()=>d.clicked(t,e),[d,t,e]),u=p("card","relative flex flex-col overflow-hidden border transition-colors"),b=p("cardLink","flex flex-1 flex-col no-underline"),v=p("image","aspect-square w-full overflow-hidden"),f=p("imagePlaceholder","aspect-square w-full"),l=p("body","flex flex-1 flex-col gap-1 p-4"),g=p("name","text-base font-medium leading-snug"),P=p("description","line-clamp-2 text-sm"),h=p("price","mt-auto pt-2 text-base font-semibold"),k=p("comparePrice","ml-2 text-sm font-normal"),C=p("badge","absolute left-3 top-3 px-2 py-0.5 text-xs font-medium"),T=p("actions","p-4 pt-0"),I=p("selectButton",Kt),A=H(t.price,t.currency,i),y=t.compareAtPrice!=null&&t.compareAtPrice>t.price?H(t.compareAtPrice,t.currency,i):null;if(n!=null)return a("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:n(t,{href:r,price:A,compareAtPrice:y,texts:s,locale:i,addToCart:o,trackClick:m})});let x=t.image?.thumbnailUrl??t.image?.url,E=t.available?t.isRecurring?s.subscription:null:s.unavailable;return S("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:[S("a",{...b,href:r,onClick:m,children:[x!=null?a("div",{...v,children:a("img",{src:x,alt:"",loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})}):a("div",{...f,"aria-hidden":"true"}),S("div",{...l,children:[a("h3",{...g,children:t.name}),t.shortDescription?a("p",{...P,children:t.shortDescription}):null,S("p",{...h,children:[t.priceFrom?X(s.priceFrom,{price:A}):A,y!=null?S(kt,{children:[S("span",{className:"sr-only",children:[s.originalPrice,": "]}),a("del",{...k,children:y})]}):null]})]})]}),E!=null?a("span",{...C,"data-kind":t.available?"subscription":"unavailable",children:E}):null,a("div",{...T,children:t.available?t.addToCart?a(Vt,{product:t,onAdd:o}):a("a",{...I,href:r,onClick:m,children:t.variantCount>1?s.chooseOptions:s.viewProduct}):a("button",{type:"button",...I,disabled:!0,children:s.unavailable})})]})}var At="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0";function Gt({count:t,label:e}){let r=p("grid",At),o=p("skeleton","aspect-[3/4] animate-pulse");return a("div",{...r,role:"status","aria-busy":"true","aria-label":e,children:Array.from({length:t},(n,s)=>a("div",{...o,"aria-hidden":"true"},s))})}function Qt({page:t,pageCount:e,isLoading:r,onPage:o}){let{texts:n}=j(),s=p("pagination","mt-8 flex items-center justify-center gap-4"),i=p("paginationButton",Z),d=p("pageIndicator","text-sm");return S("nav",{...s,"aria-label":n.pagination,children:[a("button",{type:"button",...i,"aria-disabled":r||t<=1,onClick:()=>{!r&&t>1&&o(t-1)},children:n.previousPage}),a("span",{...d,"aria-live":"polite",children:X(n.pageOf,{page:t,pageCount:e})}),a("button",{type:"button",...i,"aria-disabled":r||t>=e,onClick:()=>{!r&&t<e&&o(t+1)},children:n.nextPage})]})}function Xt({options:t,productHref:e,renderItem:r,onAddToCart:o,showCartOnAdd:n}){let{texts:s}=j(),{products:i,page:d,pageCount:c,setPage:m,isLoading:u,error:b,refetch:v}=G(t),f=nt(),l=t.search?.trim()?"search":"catalog",g=O(t.pageSize),P=K(!1);R(()=>{P.current||u||b!=null||(P.current=!0,f.track("product_list_viewed",{list_id:l,item_count:i.length}))},[f,u,b,l,i.length]);let h=B(()=>Lt(({productIds:L,positions:w})=>f.track("product_impression",{list_id:l,product_ids:L,positions:w})),[f,l]);R(()=>()=>h.destroy(),[h]);let k=B(()=>({observe:h.observe,clicked:(L,w)=>f.track("product_clicked",{list_id:l,position:w},{product_id:L.id})}),[h,f,l]),C=K(null),T=K(!1),I=V(L=>{T.current=!0,m(L)},[m]);R(()=>{u||!T.current||(T.current=!1,C.current?.focus({preventScroll:!0}),C.current?.scrollIntoView({block:"start"}))},[u]);let A=p("grid",At),y=p("emptyState","py-12 text-center text-sm"),x=p("error","flex flex-col items-center gap-3 py-12 text-center text-sm"),E=p("retryButton",Z),{projectID:J,host:W}=t,It=V((L,w)=>async()=>{if(o!=null){await at(()=>o(L)),Q(f,L);return}await yt(L,{projectID:J,host:W,showCart:n,analytics:f,url:w})},[o,J,W,n,f]),_;return u&&i.length===0?_=a(Gt,{count:Math.min(O(t.pageSize),8),label:s.loading}):b!=null?_=S("div",{...x,role:"alert",children:[a("p",{children:s.error}),a("button",{type:"button",...E,onClick:v,children:s.retry})]}):i.length===0?_=a("p",{...y,children:s.empty}):_=a("ul",{...A,"aria-busy":u||void 0,className:F(A.className,u&&"opacity-60"),children:i.map((L,w)=>{let Y=e(L);return a(qt,{product:L,position:(d-1)*g+w,href:Y,onAdd:It(L,Y),renderItem:r},L.id)})}),a(Ct.Provider,{value:k,children:S("div",{ref:C,tabIndex:-1,className:"p-1 outline-none scroll-mt-4",children:[_,c>1&&b==null?a(Qt,{page:d,pageCount:c,isLoading:u,onPage:I}):null]})})}var Zt=t=>`/p/${encodeURIComponent(t.uniqueSlug)}`;function Jt({productHref:t=Zt,appearance:e,texts:r,renderItem:o,onAddToCart:n,showCartOnAdd:s=!0,className:i,analytics:d,...c}){let m=st(c.projectID,d,"catalog"),u=c.locale??D,b=B(()=>pt(e),[e]),v=B(()=>ht(u,r),[u,r]),f=B(()=>({appearance:b,texts:v,locale:u}),[b,v,u]),l=q(b,"root");return a(ot,{value:m,children:a(vt.Provider,{value:f,children:a("div",{"data-bitsnap-products":"root","data-bitsnap-products-slot":"root",className:F("bitsnap-react",b.boundaryClassName,i,l?.className),style:{...b.boundaryStyle,...l?.style},children:a(Xt,{options:c,productHref:t,renderItem:o,onAddToCart:n,showCartOnAdd:s})})})})}export{wt as a,H as b,G as c,Jt as d};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as dt,b as ut}from"./chunk-KOVKUJAW.mjs";import{c as tt,d as F,e as it,f as U,g as ct,i as lt,k as D}from"./chunk-GKFET34B.mjs";import{f as et,k as rt,l as ot,m as nt,n as st,p as at}from"./chunk-3OEKRPWV.mjs";var wt=["root","grid","card","cardLink","image","imagePlaceholder","body","name","description","price","comparePrice","badge","actions","addToCartButton","selectButton","message","pagination","paginationButton","pageIndicator","emptyState","error","retryButton","skeleton"],Et={fontFamily:"--bitsnap-products-font-family",fontSize:"--bitsnap-products-font-size",background:"--bitsnap-products-background",surface:"--bitsnap-products-surface",foreground:"--bitsnap-products-foreground",mutedForeground:"--bitsnap-products-muted-foreground",border:"--bitsnap-products-border",buttonBackground:"--bitsnap-products-button-background",buttonForeground:"--bitsnap-products-button-foreground",buttonHoverBackground:"--bitsnap-products-button-hover-background",hoverSurface:"--bitsnap-products-hover-surface",focusRing:"--bitsnap-products-focus-ring",error:"--bitsnap-products-error",badgeBackground:"--bitsnap-products-badge-background",badgeForeground:"--bitsnap-products-badge-foreground",radius:"--bitsnap-products-radius"},_t={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",radius:"8px"},dark:{background:"#18181b",surface:"#27272a",foreground:"#fafafa",mutedForeground:"#a1a1aa",border:"#3f3f46",buttonBackground:"#fafafa",buttonForeground:"#18181b",buttonHoverBackground:"#e4e4e7",hoverSurface:"#3f3f46",focusRing:"#a1a1aa",error:"#f87171",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",radius:"8px"}},Dt=[];function pt(t){let e=dt(t,{defaultTheme:"light",presets:_t,variables:Et,shadcnVariables:Dt});return{theme:e.theme,tokens:e.tokens,elements:e.elements,boundaryClassName:e.theme,boundaryStyle:e.boundaryStyle}}function q(t,e){return ut(t.elements,e)}function mt(t,e){try{return new Intl.NumberFormat(t,{style:"currency",currency:e,currencyDisplay:"symbol"})}catch{return}}function H(t,e,r=D){let o=t/100,n=mt(r,e)??mt(D,e);return n!=null?n.format(o):`${o.toFixed(2)} ${e}`}import{useCallback as Pt,useEffect as jt,useMemo as Ft,useState as z}from"react";var Ot=24,Nt=48,M=class extends Error{status;constructor(e,r){super(e),this.name="ProductListError",this.status=r}};function O(t){return t==null||!Number.isFinite(t)?Ot:Math.min(Nt,Math.max(1,Math.floor(t)))}function ft(t,e){return Math.max(1,Math.ceil(t/e))}function N(t){return t.replace(/\/+$/,"")}function Rt(t){let e=new URLSearchParams;e.set("limit",String(t.limit)),e.set("offset",String(t.offset)),t.locale&&e.set("locale",t.locale);let r=t.search?.trim();return r&&e.set("search",r),`${N(t.host)}/api/integrations/${encodeURIComponent(t.projectID)}/public-commerce/product-list?${e.toString()}`}function Bt(t){return typeof t=="object"&&t!=null&&Array.isArray(t.items)&&typeof t.totalCount=="number"}async function gt(t,e){let r=await fetch(tt(Rt(t)),{method:"GET",credentials:"omit",headers:{Accept:"application/json"},signal:e});if(!r.ok)throw new M(`Could not load products (${r.status})`,r.status);let o=await r.json();if(!Bt(o))throw new M("Unexpected product list response");return o}function G(t){let{projectID:e,locale:r,search:o,initialData:n}=t,[s]=z(()=>U),i=t.host??s,d=O(t.pageSize),c=JSON.stringify([e,i,r??null,o?.trim()??null,d]),[m,u]=z({queryKey:c,page:1});m.queryKey!==c&&u({queryKey:c,page:1});let[b,v]=z(0),[f,l]=z(()=>({requestKey:n!=null?`${c}|1|0`:"",data:n,error:void 0})),g=f.data?.totalCount??0,P=ft(g,d),h=m.queryKey===c?m.page:1,k=g>0?Math.min(h,P):h,C=`${c}|${k}|${b}`,T=f.requestKey===C;jt(()=>{if(T)return;let y=new AbortController;return gt({projectID:e,host:i,locale:r,search:o,limit:d,offset:(k-1)*d},y.signal).then(x=>{y.signal.aborted||l({requestKey:C,data:x,error:void 0})},x=>{y.signal.aborted||l(E=>({requestKey:C,data:E.data,error:x instanceof Error?x:new Error(String(x))}))}),()=>y.abort()},[C,T]);let I=Pt(y=>{let x=Math.max(1,Math.floor(y));u({queryKey:c,page:g>0?Math.min(x,P):x})},[c,g,P]),A=Pt(()=>v(y=>y+1),[]);return Ft(()=>({products:f.data?.items??[],totalCount:g,page:k,pageCount:P,setPage:I,isLoading:!T,error:T?f.error:void 0,refetch:A}),[f,g,k,P,I,T,A])}import{createContext as xt,useCallback as V,useContext as Tt,useEffect as R,useMemo as B,useRef as K,useState as zt}from"react";function bt(t,e){if(t.projectID!=null&&t.projectID!==e.projectID)return{ok:!1,reason:`the page cart already belongs to project "${t.projectID}"`};let r=null,o=e.host?N(e.host):"",n=N(t.host);if(o&&o!==n){if(n!==N(t.defaultHost))return{ok:!1,reason:`the page cart already uses the host "${t.host}"`};r=o}return{ok:!0,setProjectID:t.projectID==null?e.projectID:null,setHost:r}}function Q(t,e){let r=e.cartItemId!=null&&e.cartItemId!==e.id?e.cartItemId:null;t.track("add_to_cart",{qty:1,value_minor:e.price,currency:e.currency},{product_id:e.id,variant_id:r})}async function yt(t,e){let[{Bitsnap:r},{getProjectID:o,setProjectID:n}]=await Promise.all([import("./methods-N35A2OGE.mjs"),import("./CartProvider-GLUQHAG3.mjs")]),s=bt({projectID:o(),host:U,defaultHost:it},e);if(!s.ok)return Ut(s.reason);if(s.setProjectID!=null&&n(s.setProjectID),s.setHost!=null&&ct(s.setHost),await r.addProductToCart(t.cartItemId??t.id,1,void 0,{url:e.url,name:t.name,price:t.price,currency:t.currency,analytics:rt})!=null)throw new Error("Could not add the product to the cart");e.analytics!=null&&Q(e.analytics,t),e.showCart&&r.showCart()}function Ut(t){throw console.warn(`bitsnap-react: ProductList did not add to the cart because ${t}. Pass onAddToCart to use another cart.`),new Error("The page cart belongs to another project or host")}var $=50,Ht=1e3;function Lt(t,e=Ht){let r=new Set,o=new Map,n=[],s=[],i,d,c=!1;function m(){for(d!==void 0&&clearTimeout(d),d=void 0;n.length>0;){let l=n.slice(0,$),g=s.slice(0,$);n=n.slice($),s=s.slice($);try{t({productIds:l,positions:g})}catch{}}}function u(){m();try{et()?.flush()}catch{}}let b=()=>{typeof document<"u"&&document.visibilityState==="hidden"&&u()};function v(){c||typeof window>"u"||(c=!0,window.addEventListener("pagehide",u,!0),document.addEventListener("visibilitychange",b,!0))}function f(){if(i)return i;if(!(typeof IntersectionObserver>"u"))return i=new IntersectionObserver(l=>{for(let g of l){let P=o.get(g.target);!P||!g.isIntersecting||g.intersectionRatio<.5||(o.delete(g.target),i?.unobserve(g.target),!r.has(P.id)&&(r.add(P.id),n.push(P.id),s.push(P.position)))}n.length>0&&d===void 0&&(d=setTimeout(m,e),d.unref?.())},{threshold:[.5]}),v(),i}return{observe(l,g,P){try{if(r.has(g))return()=>{};let h=f();return h?(o.set(l,{id:g,position:P}),h.observe(l),()=>{o.delete(l),h.unobserve(l)}):()=>{}}catch{return()=>{}}},flush:m,destroy(){try{m(),i?.disconnect(),c&&(window.removeEventListener("pagehide",u,!0),document.removeEventListener("visibilitychange",b,!0),c=!1)}catch{}i=void 0,o.clear()}}}var Mt={en:{addToCart:"Add to cart",addingToCart:"Adding\u2026",addedToCart:"Added to cart",addToCartError:"Could not add to the cart. Try again.",chooseOptions:"Choose",viewProduct:"View",unavailable:"Unavailable",subscription:"Subscription",priceFrom:"from {price}",originalPrice:"Original price",loading:"Loading products",empty:"There are no products to show.",error:"Could not load the products.",retry:"Try again",pagination:"Pagination",previousPage:"Previous",nextPage:"Next",pageOf:"Page {page} of {pageCount}"},pl:{addToCart:"Dodaj do koszyka",addingToCart:"Dodawanie\u2026",addedToCart:"Dodano do koszyka",addToCartError:"Nie uda\u0142o si\u0119 doda\u0107 do koszyka. Spr\xF3buj ponownie.",chooseOptions:"Wybierz",viewProduct:"Zobacz",unavailable:"Niedost\u0119pny",subscription:"Subskrypcja",priceFrom:"od {price}",originalPrice:"Cena przed obni\u017Ck\u0105",loading:"\u0141adowanie produkt\xF3w",empty:"Brak produkt\xF3w do wy\u015Bwietlenia.",error:"Nie uda\u0142o si\u0119 za\u0142adowa\u0107 produkt\xF3w.",retry:"Spr\xF3buj ponownie",pagination:"Paginacja",previousPage:"Poprzednia",nextPage:"Nast\u0119pna",pageOf:"Strona {page} z {pageCount}"}};function ht(t,e){return lt(Mt,t,e)}function X(t,e){return t.replace(/\{(\w+)\}/g,(r,o)=>o in e?String(e[o]):r)}import{Fragment as kt,jsx as a,jsxs as S}from"react/jsx-runtime";var vt=xt(void 0),$t={observe:()=>()=>{},clicked:()=>{}},Ct=xt($t);function j(){let t=Tt(vt);if(t==null)throw new Error("ProductList parts must be rendered inside ProductList");return t}function p(t,e){let{appearance:r}=j(),o=q(r,t);return{"data-bitsnap-products-slot":t,className:F(e,o?.className),style:o?.style}}var Z="inline-flex cursor-pointer items-center justify-center px-4 py-2 text-sm font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-50 aria-disabled:cursor-not-allowed aria-disabled:opacity-50",St=`${Z} w-full`,Kt=`${St} no-underline`;function Vt({product:t,onAdd:e}){let{texts:r}=j(),[o,n]=zt("idle"),s=p("addToCartButton",St),i=p("message","mt-2 text-xs");R(()=>{if(o!=="added")return;let m=setTimeout(()=>n("idle"),2e3);return()=>clearTimeout(m)},[o]);let d=V(async()=>{n("adding");try{await e(),n("added")}catch(m){console.error("bitsnap-react: could not add to the cart",m),n("error")}},[e]),c=o==="adding"?r.addingToCart:o==="added"?r.addedToCart:r.addToCart;return S(kt,{children:[a("button",{type:"button",...s,disabled:o==="adding","aria-label":`${c}: ${t.name}`,onClick:d,children:c}),o==="error"?a("p",{...i,role:"alert",children:r.addToCartError}):null]})}function qt({product:t,position:e,href:r,onAdd:o,renderItem:n}){let{texts:s,locale:i}=j(),d=Tt(Ct),c=K(null);R(()=>{if(c.current!=null)return d.observe(c.current,t.id,e)},[d,t.id,e]);let m=V(()=>d.clicked(t,e),[d,t,e]),u=p("card","relative flex flex-col overflow-hidden border transition-colors"),b=p("cardLink","flex flex-1 flex-col no-underline"),v=p("image","aspect-square w-full overflow-hidden"),f=p("imagePlaceholder","aspect-square w-full"),l=p("body","flex flex-1 flex-col gap-1 p-4"),g=p("name","text-base font-medium leading-snug"),P=p("description","line-clamp-2 text-sm"),h=p("price","mt-auto pt-2 text-base font-semibold"),k=p("comparePrice","ml-2 text-sm font-normal"),C=p("badge","absolute left-3 top-3 px-2 py-0.5 text-xs font-medium"),T=p("actions","p-4 pt-0"),I=p("selectButton",Kt),A=H(t.price,t.currency,i),y=t.compareAtPrice!=null&&t.compareAtPrice>t.price?H(t.compareAtPrice,t.currency,i):null;if(n!=null)return a("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:n(t,{href:r,price:A,compareAtPrice:y,texts:s,locale:i,addToCart:o,trackClick:m})});let x=t.image?.thumbnailUrl??t.image?.url,E=t.available?t.isRecurring?s.subscription:null:s.unavailable;return S("li",{ref:c,...u,"data-unavailable":t.available?void 0:"",children:[S("a",{...b,href:r,onClick:m,children:[x!=null?a("div",{...v,children:a("img",{src:x,alt:"",loading:"lazy",decoding:"async",className:"h-full w-full object-cover"})}):a("div",{...f,"aria-hidden":"true"}),S("div",{...l,children:[a("h3",{...g,children:t.name}),t.shortDescription?a("p",{...P,children:t.shortDescription}):null,S("p",{...h,children:[t.priceFrom?X(s.priceFrom,{price:A}):A,y!=null?S(kt,{children:[S("span",{className:"sr-only",children:[s.originalPrice,": "]}),a("del",{...k,children:y})]}):null]})]})]}),E!=null?a("span",{...C,"data-kind":t.available?"subscription":"unavailable",children:E}):null,a("div",{...T,children:t.available?t.addToCart?a(Vt,{product:t,onAdd:o}):a("a",{...I,href:r,onClick:m,children:t.variantCount>1?s.chooseOptions:s.viewProduct}):a("button",{type:"button",...I,disabled:!0,children:s.unavailable})})]})}var At="m-0 grid list-none grid-cols-[repeat(auto-fill,minmax(min(100%,15rem),1fr))] gap-5 p-0";function Gt({count:t,label:e}){let r=p("grid",At),o=p("skeleton","aspect-[3/4] animate-pulse");return a("div",{...r,role:"status","aria-busy":"true","aria-label":e,children:Array.from({length:t},(n,s)=>a("div",{...o,"aria-hidden":"true"},s))})}function Qt({page:t,pageCount:e,isLoading:r,onPage:o}){let{texts:n}=j(),s=p("pagination","mt-8 flex items-center justify-center gap-4"),i=p("paginationButton",Z),d=p("pageIndicator","text-sm");return S("nav",{...s,"aria-label":n.pagination,children:[a("button",{type:"button",...i,"aria-disabled":r||t<=1,onClick:()=>{!r&&t>1&&o(t-1)},children:n.previousPage}),a("span",{...d,"aria-live":"polite",children:X(n.pageOf,{page:t,pageCount:e})}),a("button",{type:"button",...i,"aria-disabled":r||t>=e,onClick:()=>{!r&&t<e&&o(t+1)},children:n.nextPage})]})}function Xt({options:t,productHref:e,renderItem:r,onAddToCart:o,showCartOnAdd:n}){let{texts:s}=j(),{products:i,page:d,pageCount:c,setPage:m,isLoading:u,error:b,refetch:v}=G(t),f=nt(),l=t.search?.trim()?"search":"catalog",g=O(t.pageSize),P=K(!1);R(()=>{P.current||u||b!=null||(P.current=!0,f.track("product_list_viewed",{list_id:l,item_count:i.length}))},[f,u,b,l,i.length]);let h=B(()=>Lt(({productIds:L,positions:w})=>f.track("product_impression",{list_id:l,product_ids:L,positions:w})),[f,l]);R(()=>()=>h.destroy(),[h]);let k=B(()=>({observe:h.observe,clicked:(L,w)=>f.track("product_clicked",{list_id:l,position:w},{product_id:L.id})}),[h,f,l]),C=K(null),T=K(!1),I=V(L=>{T.current=!0,m(L)},[m]);R(()=>{u||!T.current||(T.current=!1,C.current?.focus({preventScroll:!0}),C.current?.scrollIntoView({block:"start"}))},[u]);let A=p("grid",At),y=p("emptyState","py-12 text-center text-sm"),x=p("error","flex flex-col items-center gap-3 py-12 text-center text-sm"),E=p("retryButton",Z),{projectID:J,host:W}=t,It=V((L,w)=>async()=>{if(o!=null){await at(()=>o(L)),Q(f,L);return}await yt(L,{projectID:J,host:W,showCart:n,analytics:f,url:w})},[o,J,W,n,f]),_;return u&&i.length===0?_=a(Gt,{count:Math.min(O(t.pageSize),8),label:s.loading}):b!=null?_=S("div",{...x,role:"alert",children:[a("p",{children:s.error}),a("button",{type:"button",...E,onClick:v,children:s.retry})]}):i.length===0?_=a("p",{...y,children:s.empty}):_=a("ul",{...A,"aria-busy":u||void 0,className:F(A.className,u&&"opacity-60"),children:i.map((L,w)=>{let Y=e(L);return a(qt,{product:L,position:(d-1)*g+w,href:Y,onAdd:It(L,Y),renderItem:r},L.id)})}),a(Ct.Provider,{value:k,children:S("div",{ref:C,tabIndex:-1,className:"p-1 outline-none scroll-mt-4",children:[_,c>1&&b==null?a(Qt,{page:d,pageCount:c,isLoading:u,onPage:I}):null]})})}var Zt=t=>`/p/${encodeURIComponent(t.uniqueSlug)}`;function Jt({productHref:t=Zt,appearance:e,texts:r,renderItem:o,onAddToCart:n,showCartOnAdd:s=!0,className:i,analytics:d,...c}){let m=st(c.projectID,d,"catalog"),u=c.locale??D,b=B(()=>pt(e),[e]),v=B(()=>ht(u,r),[u,r]),f=B(()=>({appearance:b,texts:v,locale:u}),[b,v,u]),l=q(b,"root");return a(ot,{value:m,children:a(vt.Provider,{value:f,children:a("div",{"data-bitsnap-products":"root","data-bitsnap-products-slot":"root",className:F("bitsnap-react",b.boundaryClassName,i,l?.className),style:{...b.boundaryStyle,...l?.style},children:a(Xt,{options:c,productHref:t,renderItem:o,onAddToCart:n,showCartOnAdd:s})})})})}export{wt as a,H as b,G as c,Jt as d};
|
|
2
|
+
//# sourceMappingURL=chunk-VYYUTJZB.mjs.map
|
|
@@ -0,0 +1,2 @@
|
|
|
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; }var o={maxBatchEvents:50,maxBodyBytes:65536,maxPropsChars:4096,maxPropString:200,maxPropArray:50,host:253,path:512,referrerHost:253,utm:100,refCode:64,id:64,sdk:64,pageId:32,region:64,osBrowser:32,tsSkewMs:864e5},w=["storefront_events","app_events","business_events"],N=["live","test"],A=["storefront","sdk_react","script","server","dashboard"],P=["hosted","custom_domain","embed","api","panel"],T=["shop","catalog","product","cart","checkout","payment","panel","course","custom_page","order","returns","app","other"];var O={storefront_events:["storefront","sdk_react","script"],app_events:["dashboard"],business_events:["server"]},_={value_minor:"number",currency:"string"},h={page_view:{landing:"boolean"},product_list_viewed:{list_id:"string?",item_count:"number"},product_impression:{list_id:"string?",product_ids:"string[]",positions:"number[]"},product_clicked:{list_id:"string?",position:"number?"},product_view:{price_minor:"number",currency:"string",availability:"enum:in_stock|out_of_stock|preorder"},variant_selected:{},add_to_cart:{qty:"number",..._},remove_from_cart:{qty:"number",..._},cart_opened:{item_count:"number",..._},checkout_started:{item_count:"number",checkout_type:"enum:single|cart|link",..._},checkout_step_completed:{step:"enum:contact|delivery|invoice|consents"},checkout_validation_error:{field:"string",rule:"string"},coupon_applied:{coupon_id:"string"},coupon_rejected:{coupon_id:"string?",reason:"string"},delivery_method_selected:{method:"string"},payment_method_selected:{gateway:"string",method:"string"},payment_submitted:{gateway:"string",method:"string"},apple_pay_clicked:{},apple_pay_result:{outcome:"enum:success|fail|cancel"},payment_returned:{gateway:"string",method:"string?",outcome:"enum:success|fail|cancel|pending",error_code:"string?"},availability_signup:{},panel_login:{},panel_order_viewed:{},panel_download:{},return_started:{},return_submitted:{reason_code:"string",item_count:"number"},course_opened:{course_id:"string"},lesson_started:{course_id:"string",lesson_id:"string",position:"number"},lesson_completed:{course_id:"string",lesson_id:"string",position:"number"},video_progress:{course_id:"string",lesson_id:"string",milestone:"number"},test_submitted:{course_id:"string",lesson_id:"string",score_bucket:"enum:0-24|25-49|50-74|75-99|100"},lesson_rated:{course_id:"string",lesson_id:"string",rating:"number"},consent_updated:{consent_id:"string",action:"enum:accept_all|reject_all|custom|withdraw",analytics:"boolean",marketing:"boolean",preferences:"boolean",banner_version:"number"},consent_shown:{banner_version:"number"}},E={app_page_view:{route:"string",previous_route:"string?"},insight_shown:{insight_type:"string",rank:"number",category:"string"},insight_clicked:{insight_type:"string",rank:"number",category:"string"},insight_dismissed:{insight_type:"string",rank:"number",category:"string"},checklist_step_viewed:{step:"string"},checklist_step_completed:{step:"string"},gateway_connect_started:{gateway:"string",step:"string?"},gateway_connect_completed:{gateway:"string",step:"string?"},gateway_connect_failed:{gateway:"string",step:"string?",error_code:"string?"},domain_connect_started:{},domain_connect_verified:{},domain_connect_failed:{error_code:"string?"},product_created:{product_type:"string?"},product_published:{product_type:"string?"},product_editor_section_opened:{section:"string"},feature_enabled:{feature:"string"},stats_viewed:{tab:"string"},stats_filter_changed:{tab:"string",filter:"string"},report_exported:{report:"string",format:"string?"},search_performed:{result_count:"number"},error_shown:{code:"string",route:"string"},help_opened:{topic:"string?"},ai_assistant_used:{topic:"string?"},member_invited:{role:"string"}},d={gateway:"string?",method:"string?",value_minor:"number?",currency:"string?"},u={subscription_id:"string?",value_minor:"number?",currency:"string?"},S={transaction_created:d,transaction_success:d,transaction_failure:{...d,error_code:"string?"},transaction_expired:d,transaction_charge:d,subscription_created:u,subscription_paused:u,subscription_resumed:u,subscription_updated:u,subscription_deleted:u,subscription_charge_paid:u,subscription_charge_failed:{...u,error_code:"string?"},subscription_past_due:u,subscription_canceled:u,access_expires_in_3_days:{},access_expired:{},cart_recovery:{value_minor:"number?",currency:"string?"},testimonial_email_send:{},testimonial_fulfilled:{},partner_commission_earned:{partner_id:"string",commission_minor:"number",currency:"string"},checkout_session_created:{item_count:"number",checkout_type:"enum:single|cart|link",gateway:"string?",..._},order_paid:{gateway:"string",method:"string?",item_count:"number?",visitor_day:"string?",items:"line_items?",..._},refund_issued:{gateway:"string?",reason:"string?",..._},return_requested:{item_count:"number",reason_code:"string?"},automation_run_completed:{automation_id:"string",status:"string",trigger:"string?"},notification_sent:{medium:"string",template:"string?"},notification_failed:{medium:"string",template:"string?",error_code:"string?"},recovery_email_sent:{step:"number?"},recovery_link_clicked:{},api_request:{endpoint:"string",client:"string?",status:"number",latency_bucket:"enum:lt_50|lt_200|lt_1000|gte_1000",sample_rate:"number"}};var $={...h,...E,...S},R={storefront_events:Object.keys(h),app_events:Object.keys(E),business_events:Object.keys(S)},v=Object.fromEntries(w.flatMap(t=>R[t].map(e=>[e,t])));function x(t){return typeof t=="string"&&Object.hasOwn(v,t)}var et=365*24*60*60;var nt="shown";function rt(t){let e=t.startsWith("pk_")?t.slice(3):t;return/^[A-Za-z0-9]{1,32}$/.test(e)?e:null}var I=/^([a-z][a-z0-9-]{0,39})@(\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;function k(t){if(!t||t.length>o.sdk)return null;let e=I.exec(t);return e?{package:e[1],version:e[2]}:null}var m=o.utm;function g(t,e){if(t==null)return null;let r=t.trim();return r.length===0||r.includes("@")?null:r.slice(0,e)}function M(t){let r=t.split("/").map(n=>n.includes("@")||n.includes("%40")?":email":/^[A-Za-z0-9_-]{24,}$/.test(n)?":token":n).join("/")||"/";return(r.startsWith("/")?r:`/${r}`).slice(0,o.path)}function ot(t,e){let r;try{r=new URL(t,e)}catch (e2){return null}if(r.protocol!=="https:"&&r.protocol!=="http:")return null;let n=r.searchParams;return{host:r.hostname.toLowerCase().slice(0,o.host),path:M(r.pathname),utm_source:g(n.get("utm_source"),m),utm_medium:g(n.get("utm_medium"),m),utm_campaign:g(n.get("utm_campaign"),m),utm_content:g(n.get("utm_content"),m),utm_term:g(n.get("utm_term"),m),ref_code:g(n.get("ref"),o.refCode)}}var U=/^[A-Za-z0-9_-]{1,64}$/;function st(t){if(!t)return null;try{let e=new URL(t);return e.protocol!=="https:"&&e.protocol!=="http:"?null:e.hostname.toLowerCase().slice(0,o.referrerHost)}catch (e3){return null}}var it=new TextEncoder;function at(t){return`bs_vid_${t}`}var V=/^[A-Za-z0-9_-]{22}$/;var D=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,L=/^[A-Za-z0-9_-]{8,32}$/,j=/[^\s@]+@[^\s@]+\.[A-Za-z]{2,}\b/;function f(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function B(t,e,r){let n=t[e];return n==null?null:typeof n!="string"?`bad_${e}`:n.length>r?`too_long_${e}`:null}function z(t,e){let n=t.endsWith("?")?t.slice(0,-1):t;if(n.startsWith("enum:"))return typeof e=="string"&&n.slice(5).split("|").includes(e);switch(n){case"string":return typeof e=="string"&&e.length<=o.maxPropString;case"number":return typeof e=="number"&&Number.isFinite(e);case"boolean":return typeof e=="boolean";case"string[]":return Array.isArray(e)&&e.length<=o.maxPropArray&&e.every(s=>typeof s=="string"&&s.length<=o.maxPropString);case"number[]":return Array.isArray(e)&&e.length<=o.maxPropArray&&e.every(s=>typeof s=="number"&&Number.isFinite(s));case"line_items":return Array.isArray(e)&&e.length<=o.maxPropArray&&e.every(s=>f(s)&&typeof s.product_id=="string"&&U.test(s.product_id)&&b(s.qty)&&b(s.value_minor));default:return!1}}function b(t){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0}function H(t){return k(t)!==null?!1:j.test(t)}function y(t){return typeof t=="string"?H(t):Array.isArray(t)?t.some(y):f(t)?Object.values(t).some(y):!1}function K(t,e){if(!x(t))return{ok:!1,reason:"unknown_event"};let r=$[t];if(!r)return{ok:!1,reason:"unknown_event"};if(!f(e))return{ok:!1,reason:"bad_props"};let n={};for(let[s,c]of Object.entries(r)){let a=e[s];if(a==null){if(!c.endsWith("?"))return{ok:!1,reason:`props_missing_${s}`};continue}if(!z(c,a))return{ok:!1,reason:`props_bad_${s}`};if(y(a))return{ok:!1,reason:`props_pii_${s}`};n[s]=c.startsWith("line_items")&&Array.isArray(a)?a.map(i=>({product_id:i.product_id,qty:i.qty,value_minor:i.value_minor})):a}return JSON.stringify(n).length>o.maxPropsChars?{ok:!1,reason:"props_too_large"}:{ok:!0,props:n}}function ct(t,e={}){let r=_nullishCoalesce(e.from, () => ("browser")),n=i=>({ok:!1,reason:i});if(!f(t))return n("not_object");if(typeof t.event_id!="string"||!D.test(t.event_id))return n("bad_event_id");if(!x(t.event))return n("unknown_event");let s=v[t.event];if(r==="browser"){if(s==="business_events")return n("server_only_event");if(t.event==="consent_updated"||t.event==="consent_shown")return n("consent_via_consent_endpoint")}if(typeof t.ts!="number"||!Number.isInteger(t.ts)||t.ts<=0||t.ts>4e12)return n("bad_ts");if(t.schema_version!==1)return n("bad_schema_version");if(!N.includes(t.env))return n("bad_env");if(!A.includes(t.source))return n("bad_source");if(!O[s].includes(t.source))return n("source_not_allowed_for_event");if(!P.includes(t.channel))return n("bad_channel");if(t.sdk!=null&&(typeof t.sdk!="string"||k(t.sdk)===null))return n("bad_sdk");if(t.page_id!=null&&(typeof t.page_id!="string"||!L.test(t.page_id)))return n("bad_page_id");if(t.page_type!=null&&!T.includes(t.page_type))return n("bad_page_type");if(r==="browser"){if(typeof t.host!="string"||t.host.length===0)return n("bad_host");if(typeof t.path!="string"||!t.path.startsWith("/"))return n("bad_path")}if(typeof t.path=="string"&&t.path.includes("?"))return n("path_has_query");if(typeof t.path=="string"&&t.path.includes("#"))return n("path_has_fragment");let c=[["host",o.host],["path",o.path],["referrer_host",o.referrerHost],["utm_source",o.utm],["utm_medium",o.utm],["utm_campaign",o.utm],["utm_content",o.utm],["utm_term",o.utm],["ref_code",o.refCode],["product_id",o.id],["variant_id",o.id],["order_ref",o.id]];for(let[i,p]of c){let l=B(t,i,p);if(l)return n(l)}if(t.visitor_id!=null&&(typeof t.visitor_id!="string"||!/^[A-Za-z0-9_-]{22}$/.test(t.visitor_id)))return n("bad_visitor_id");if(t.client_id!=null&&(typeof t.client_id!="string"||!V.test(t.client_id)))return n("bad_client_id");let a=K(t.event,t.props);return a.ok?{ok:!0}:n(a.reason)}var C="bitsnap_consent";function lt(t,e){return e==="project"&&t?`${C}_${t.replace(/[^A-Za-z0-9_-]/g,"_")}`:C}function q(t){return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function W(t){let e=t.replace(/-/g,"+").replace(/_/g,"/");return atob(e+"=".repeat((4-e.length%4)%4))}function Y(t){return q(JSON.stringify({v:1,id:t.id,ts:t.ts,bv:t.bv,c:t.c}))}function Z(t){try{let e=JSON.parse(W(t));return!e||e.v!==1||typeof e.id!="string"||e.id===""||typeof e.ts!="number"||typeof e.bv!="number"||!e.c||typeof e.c.analytics!="boolean"||typeof e.c.marketing!="boolean"||typeof e.c.preferences!="boolean"?null:{id:e.id,ts:e.ts,bv:e.bv,c:{analytics:e.c.analytics,marketing:e.c.marketing,preferences:e.c.preferences}}}catch (e4){return null}}function F(t,e,r){return`${t}=${Y(e)}; Max-Age=31536000; Path=/; SameSite=Lax`+(r?"; Secure":"")}function X(t){return t.split(";").map(e=>e.split("=")[0].trim()).filter(Boolean)}function G(t,e){for(let r of t.split(";")){let n=r.indexOf("=");if(n!==-1&&r.slice(0,n).trim()===e)return Z(r.slice(n+1).trim())}return null}function pt(){try{if(typeof crypto<"u"&&typeof crypto.randomUUID=="function")return crypto.randomUUID()}catch (e5){}let t="";for(let e=0;e<32;e++)t+=Math.floor(Math.random()*16).toString(16);return t}function _t(t,e){try{return G(t.cookie,e)}catch (e6){return null}}function gt(t,e,r){try{t.cookie=F(e,r,_optionalChain([t, 'access', _2 => _2.location, 'optionalAccess', _3 => _3.protocol])==="https:")}catch (e7){}}function dt(t,e){try{t.cookie=`${e}=; Max-Age=0; Path=/; SameSite=Lax`}catch (e8){}}function J(t){if(!t||/^[\d.]+$/.test(t)||t.includes(":"))return[];let e=t.split("."),r=[];for(let n=0;n<=e.length-2;n++)r.push(e.slice(n).join("."));return r}function mt(t,e,r){try{let n=e.filter(i=>r.includes(i.category)).flatMap(i=>_nullishCoalesce(i.cookies, () => ([])));if(n.length===0)return;let s=X(t.cookie),c=new Set;for(let i of n)if(i.endsWith("*")){let p=i.slice(0,-1);for(let l of s)l.startsWith(p)&&c.add(l)}else c.add(i);let a=J(_nullishCoalesce(_optionalChain([t, 'access', _4 => _4.location, 'optionalAccess', _5 => _5.hostname]), () => ("")));for(let i of c){let p=`${encodeURIComponent(i)}=; Max-Age=0; Path=/`;t.cookie=p;for(let l of a)t.cookie=`${p}; Domain=${l}`,t.cookie=`${p}; Domain=.${l}`}}catch (e9){}}var _react = require('react');function bt(t,e){(typeof window<"u"?_react.useLayoutEffect:(0, _react.useEffect))(t,e)}exports.a = o; exports.b = nt; exports.c = rt; exports.d = M; exports.e = ot; exports.f = st; exports.g = at; exports.h = K; exports.i = ct; exports.j = lt; exports.k = pt; exports.l = _t; exports.m = gt; exports.n = dt; exports.o = J; exports.p = mt; exports.q = bt;
|
|
2
|
+
//# sourceMappingURL=chunk-W3RGQYPD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/contract.ts"],"names":["LIMITS","STREAMS","ENVS","SOURCES","CHANNELS","PAGE_TYPES","SOURCES_FOR_STREAM","MONEY","STOREFRONT_EVENT_SPEC","APP_EVENT_SPEC","TX","SUB","BUSINESS_EVENT_SPEC","EVENT_SPEC","EVENT_NAMES","STREAM_FOR_EVENT","stream","name","isEventName","CONSENT_COOKIE_MAX_AGE_SECONDS","CONSENT_SHOWN_ACTION","normalizeProjectKey","key","bare","CLIENT_RE","parseClientHeader","value","m","MAX_QUERY_VALUE","cleanValue","v","max","t","sanitizePath","pathname","joined","seg"],"mappings":"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","file":"/home/emems/.t3/worktrees/bitsnap-react/consent-shown/dist/chunk-W3RGQYPD.js","sourcesContent":["/**\n * Bitsnap merchant analytics: the wire contract.\n *\n * SOURCE OF TRUTH: instapay `apps/collector/src/contract.ts` (prose version:\n * `docs/merchant-analytics-contract.md`). This file is a verbatim copy of it\n * (everything below the next comment block). Do not edit it here: change\n * instapay's file and copy it over. `computeVisitorId` and\n * `computeConsentedVisitorId` are pure but need the server secret; they are\n * server-only: the browser never calls them, so bundlers drop them.\n */\n\nexport const SCHEMA_VERSION = 1;\n\n// ---------------------------------------------------------------------------\n// Limits\n// ---------------------------------------------------------------------------\n\nexport const LIMITS = {\n /** Events in one POST /e. */\n maxBatchEvents: 50,\n /** Body of one POST /e or /consent, in bytes. */\n maxBodyBytes: 64 * 1024,\n /** `JSON.stringify(props)` of one event, in UTF-16 code units. */\n maxPropsChars: 4096,\n maxPropString: 200,\n maxPropArray: 50,\n host: 253,\n path: 512,\n referrerHost: 253,\n utm: 100,\n refCode: 64,\n id: 64,\n sdk: 64,\n pageId: 32,\n region: 64,\n osBrowser: 32,\n /** Collector replaces a client `ts` farther than this from `received_at`. */\n tsSkewMs: 24 * 60 * 60 * 1000,\n} as const;\n\n// ---------------------------------------------------------------------------\n// Enumerations\n// ---------------------------------------------------------------------------\n\nexport const STREAMS = [\n \"storefront_events\",\n \"app_events\",\n \"business_events\",\n] as const;\nexport type Stream = (typeof STREAMS)[number];\n\nexport const ENVS = [\"live\", \"test\"] as const;\nexport type Env = (typeof ENVS)[number];\n\nexport const SOURCES = [\n \"storefront\",\n \"sdk_react\",\n \"script\",\n \"server\",\n \"dashboard\",\n] as const;\nexport type Source = (typeof SOURCES)[number];\n\nexport const CHANNELS = [\n \"hosted\",\n \"custom_domain\",\n \"embed\",\n \"api\",\n \"panel\",\n] as const;\nexport type Channel = (typeof CHANNELS)[number];\n\nexport const PAGE_TYPES = [\n \"shop\",\n \"catalog\",\n \"product\",\n \"cart\",\n \"checkout\",\n \"payment\",\n \"panel\",\n \"course\",\n \"custom_page\",\n \"order\",\n \"returns\",\n \"app\",\n \"other\",\n] as const;\nexport type PageType = (typeof PAGE_TYPES)[number];\n\nexport const DEVICE_TYPES = [\"desktop\", \"mobile\", \"tablet\", \"other\"] as const;\nexport type DeviceType = (typeof DEVICE_TYPES)[number];\n\n/** Sources a browser may claim, per stream. `business_events` is server-only. */\nexport const SOURCES_FOR_STREAM: Record<Stream, readonly Source[]> = {\n storefront_events: [\"storefront\", \"sdk_react\", \"script\"],\n app_events: [\"dashboard\"],\n business_events: [\"server\"],\n};\n\n// ---------------------------------------------------------------------------\n// Event catalogue\n//\n// Each prop is `<type>[?]`: type is `string`, `number`, `boolean`, `string[]`,\n// `number[]` or `enum:a|b|c`; a trailing `?` makes the prop optional.\n// Money is always integer minor units (`*_minor`, grosze/cents) + `currency`\n// (ISO 4217, upper case). `product_id`, `variant_id` and `order_ref` live in\n// the envelope, never in props. Strings never hold PII (see the prose doc).\n// ---------------------------------------------------------------------------\n\nconst MONEY = { value_minor: \"number\", currency: \"string\" } as const;\n\n/** Browser events from hosted pages (H), bitsnap-react (R) and the script (S). */\nexport const STOREFRONT_EVENT_SPEC = {\n page_view: { landing: \"boolean\" },\n product_list_viewed: { list_id: \"string?\", item_count: \"number\" },\n product_impression: {\n list_id: \"string?\",\n product_ids: \"string[]\",\n positions: \"number[]\",\n },\n product_clicked: { list_id: \"string?\", position: \"number?\" },\n product_view: {\n price_minor: \"number\",\n currency: \"string\",\n availability: \"enum:in_stock|out_of_stock|preorder\",\n },\n variant_selected: {},\n add_to_cart: { qty: \"number\", ...MONEY },\n remove_from_cart: { qty: \"number\", ...MONEY },\n cart_opened: { item_count: \"number\", ...MONEY },\n checkout_started: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n ...MONEY,\n },\n checkout_step_completed: {\n step: \"enum:contact|delivery|invoice|consents\",\n },\n checkout_validation_error: { field: \"string\", rule: \"string\" },\n coupon_applied: { coupon_id: \"string\" },\n coupon_rejected: { coupon_id: \"string?\", reason: \"string\" },\n delivery_method_selected: { method: \"string\" },\n payment_method_selected: { gateway: \"string\", method: \"string\" },\n payment_submitted: { gateway: \"string\", method: \"string\" },\n apple_pay_clicked: {},\n apple_pay_result: { outcome: \"enum:success|fail|cancel\" },\n payment_returned: {\n gateway: \"string\",\n method: \"string?\",\n outcome: \"enum:success|fail|cancel|pending\",\n error_code: \"string?\",\n },\n availability_signup: {},\n panel_login: {},\n panel_order_viewed: {},\n panel_download: {},\n return_started: {},\n return_submitted: { reason_code: \"string\", item_count: \"number\" },\n course_opened: { course_id: \"string\" },\n lesson_started: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n lesson_completed: {\n course_id: \"string\",\n lesson_id: \"string\",\n position: \"number\",\n },\n video_progress: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 25, 50, 75 or 100. */\n milestone: \"number\",\n },\n test_submitted: {\n course_id: \"string\",\n lesson_id: \"string\",\n score_bucket: \"enum:0-24|25-49|50-74|75-99|100\",\n },\n lesson_rated: {\n course_id: \"string\",\n lesson_id: \"string\",\n /** 1..5. */\n rating: \"number\",\n },\n /** Written by the collector's POST /consent, never sent to POST /e. */\n consent_updated: {\n consent_id: \"string\",\n action: \"enum:accept_all|reject_all|custom|withdraw\",\n analytics: \"boolean\",\n marketing: \"boolean\",\n preferences: \"boolean\",\n banner_version: \"number\",\n },\n /**\n * Written by the collector's POST /consent (action `shown`), never sent to\n * POST /e. A banner impression: no consent id, no choice, no visitor.\n */\n consent_shown: {\n banner_version: \"number\",\n },\n} as const;\n\n/** Merchant behaviour in /app, sent through the same tracker core. */\nexport const APP_EVENT_SPEC = {\n app_page_view: { route: \"string\", previous_route: \"string?\" },\n insight_shown: { insight_type: \"string\", rank: \"number\", category: \"string\" },\n insight_clicked: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n insight_dismissed: {\n insight_type: \"string\",\n rank: \"number\",\n category: \"string\",\n },\n checklist_step_viewed: { step: \"string\" },\n checklist_step_completed: { step: \"string\" },\n gateway_connect_started: { gateway: \"string\", step: \"string?\" },\n gateway_connect_completed: { gateway: \"string\", step: \"string?\" },\n gateway_connect_failed: {\n gateway: \"string\",\n step: \"string?\",\n error_code: \"string?\",\n },\n domain_connect_started: {},\n domain_connect_verified: {},\n domain_connect_failed: { error_code: \"string?\" },\n product_created: { product_type: \"string?\" },\n product_published: { product_type: \"string?\" },\n product_editor_section_opened: { section: \"string\" },\n feature_enabled: { feature: \"string\" },\n stats_viewed: { tab: \"string\" },\n stats_filter_changed: { tab: \"string\", filter: \"string\" },\n report_exported: { report: \"string\", format: \"string?\" },\n search_performed: { result_count: \"number\" },\n error_shown: { code: \"string\", route: \"string\" },\n help_opened: { topic: \"string?\" },\n ai_assistant_used: { topic: \"string?\" },\n member_invited: { role: \"string\" },\n} as const;\n\nconst TX = {\n gateway: \"string?\",\n method: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\nconst SUB = {\n subscription_id: \"string?\",\n value_minor: \"number?\",\n currency: \"string?\",\n} as const;\n\n/**\n * Emitted by instapay only. The lower-cased `EventType` of\n * server/event-system/event.list.ts maps 1:1 to the first group.\n */\nexport const BUSINESS_EVENT_SPEC = {\n // Mirror of the event bus (EventType.X -> x.toLowerCase()).\n transaction_created: TX,\n transaction_success: TX,\n transaction_failure: { ...TX, error_code: \"string?\" },\n transaction_expired: TX,\n transaction_charge: TX,\n subscription_created: SUB,\n subscription_paused: SUB,\n subscription_resumed: SUB,\n subscription_updated: SUB,\n subscription_deleted: SUB,\n subscription_charge_paid: SUB,\n subscription_charge_failed: { ...SUB, error_code: \"string?\" },\n subscription_past_due: SUB,\n subscription_canceled: SUB,\n access_expires_in_3_days: {},\n access_expired: {},\n cart_recovery: { value_minor: \"number?\", currency: \"string?\" },\n testimonial_email_send: {},\n testimonial_fulfilled: {},\n partner_commission_earned: {\n partner_id: \"string\",\n commission_minor: \"number\",\n currency: \"string\",\n },\n // Added by the analytics work.\n checkout_session_created: {\n item_count: \"number\",\n checkout_type: \"enum:single|cart|link\",\n gateway: \"string?\",\n ...MONEY,\n },\n order_paid: {\n gateway: \"string\",\n method: \"string?\",\n item_count: \"number?\",\n /** UTC date (`YYYY-MM-DD`) the envelope `visitor_id` was computed for. */\n visitor_day: \"string?\",\n /** Every line of the order (public hashed product ids), at most 50. */\n items: \"line_items?\",\n ...MONEY,\n },\n refund_issued: {\n gateway: \"string?\",\n reason: \"string?\",\n ...MONEY,\n },\n return_requested: { item_count: \"number\", reason_code: \"string?\" },\n automation_run_completed: {\n automation_id: \"string\",\n status: \"string\",\n trigger: \"string?\",\n },\n notification_sent: { medium: \"string\", template: \"string?\" },\n notification_failed: {\n medium: \"string\",\n template: \"string?\",\n error_code: \"string?\",\n },\n recovery_email_sent: { step: \"number?\" },\n recovery_link_clicked: {},\n api_request: {\n /** Route template without ids or query, e.g. `/api/rpc/public.v1.PublicApiService/ListProducts`. */\n endpoint: \"string\",\n /** `X-Bitsnap-Client` value, absent when the caller sent none. */\n client: \"string?\",\n status: \"number\",\n latency_bucket: \"enum:lt_50|lt_200|lt_1000|gte_1000\",\n /** 1 for errors, <1 for sampled successes; rollups divide counts by it. */\n sample_rate: \"number\",\n },\n} as const;\n\nexport const EVENT_SPEC_BY_STREAM = {\n storefront_events: STOREFRONT_EVENT_SPEC,\n app_events: APP_EVENT_SPEC,\n business_events: BUSINESS_EVENT_SPEC,\n} as const;\n\nexport const EVENT_SPEC = {\n ...STOREFRONT_EVENT_SPEC,\n ...APP_EVENT_SPEC,\n ...BUSINESS_EVENT_SPEC,\n} as const;\n\nexport type StorefrontEventName = keyof typeof STOREFRONT_EVENT_SPEC;\nexport type AppEventName = keyof typeof APP_EVENT_SPEC;\nexport type BusinessEventName = keyof typeof BUSINESS_EVENT_SPEC;\nexport type EventName = StorefrontEventName | AppEventName | BusinessEventName;\n\nexport const EVENT_NAMES = {\n storefront_events: Object.keys(STOREFRONT_EVENT_SPEC) as StorefrontEventName[],\n app_events: Object.keys(APP_EVENT_SPEC) as AppEventName[],\n business_events: Object.keys(BUSINESS_EVENT_SPEC) as BusinessEventName[],\n} as const;\n\nexport const STREAM_FOR_EVENT: Record<EventName, Stream> = Object.fromEntries(\n STREAMS.flatMap((stream) =>\n (EVENT_NAMES[stream] as string[]).map((name) => [name, stream] as const),\n ),\n) as Record<EventName, Stream>;\n\n/** True for a catalogue event name; own keys only (`constructor`, `toString` are not events). */\nexport function isEventName(name: unknown): name is EventName {\n return typeof name === \"string\" && Object.hasOwn(STREAM_FOR_EVENT, name);\n}\n\n// -- props types, derived from the spec ------------------------------------\n\ntype PropPrimitives = {\n string: string;\n number: number;\n boolean: boolean;\n \"string[]\": string[];\n \"number[]\": number[];\n line_items: Array<{ product_id: string; qty: number; value_minor: number }>;\n};\ntype SplitEnum<S extends string> = S extends `${infer H}|${infer R}`\n ? H | SplitEnum<R>\n : S;\ntype StripOpt<S extends string> = S extends `${infer B}?` ? B : S;\ntype ResolveProp<S extends string> =\n StripOpt<S> extends `enum:${infer E}`\n ? SplitEnum<E>\n : StripOpt<S> extends keyof PropPrimitives\n ? PropPrimitives[StripOpt<S>]\n : never;\ntype PropsFromSpec<S extends Record<string, string>> = {\n [K in keyof S as S[K] extends `${string}?` ? never : K]: ResolveProp<S[K]>;\n} & {\n [K in keyof S as S[K] extends `${string}?` ? K : never]?: ResolveProp<S[K]>;\n};\n\nexport type EventProps<E extends EventName> = PropsFromSpec<\n (typeof EVENT_SPEC)[E]\n>;\n\n// ---------------------------------------------------------------------------\n// Envelope\n// ---------------------------------------------------------------------------\n\n/** Fields the emitter fills in. Everything else is derived by the collector. */\nexport interface ClientEvent<E extends EventName = EventName> {\n /** UUIDv7, generated by the emitter. Dedupe key. */\n event_id: string;\n event: E;\n /** Client clock, unix ms. */\n ts: number;\n schema_version: typeof SCHEMA_VERSION;\n env: Env;\n source: Source;\n channel: Channel;\n /** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. */\n sdk?: string | null;\n /** Random per page load, in memory only. */\n page_id?: string | null;\n page_type?: PageType | null;\n host?: string | null;\n /** Path without query string and fragment, already run through `sanitizePath`. */\n path?: string | null;\n referrer_host?: string | null;\n utm_source?: string | null;\n utm_medium?: string | null;\n utm_campaign?: string | null;\n utm_content?: string | null;\n utm_term?: string | null;\n ref_code?: string | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Object on the wire; the collector stores `JSON.stringify(props)`. */\n props: EventProps<E>;\n /**\n * Only honoured for `source: \"dashboard\"`: the hashed Clerk user id computed\n * by instapay and handed to the dashboard tracker. Ignored for every other\n * source (the collector computes `visitor_id` itself).\n */\n visitor_id?: string | null;\n /**\n * The value of the first-party `bs_vid_<projectKey>` cookie (`CLIENT_ID_RE`), sent only\n * while analytics consent is granted. The collector turns it into a stable\n * `consentedVisitorId` and never stores it.\n */\n client_id?: string | null;\n}\n\n/** One row as stored in Basin (all three streams share this shape). */\nexport interface StoredEvent {\n event_id: string;\n event: EventName;\n /** Unix ms, client clock after `clampTs`. */\n ts: number;\n /** Unix ms, collector clock. */\n received_at: number;\n schema_version: number;\n /** Numeric database id. Resolved by the collector, never taken from the client. */\n project_id: number;\n env: Env;\n source: Source;\n channel: Channel;\n sdk: string | null;\n visitor_id: string | null;\n page_id: string | null;\n page_type: PageType | null;\n host: string | null;\n path: string | null;\n referrer_host: string | null;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n ref_code: string | null;\n country: string | null;\n region: string | null;\n device_type: DeviceType | null;\n os: string | null;\n browser: string | null;\n product_id: string | null;\n variant_id: string | null;\n order_ref: string | null;\n /** `JSON.stringify` of the props object. */\n props: string;\n}\n\n/** POST /e body. */\nexport interface IngestBody {\n /** Project key, see `normalizeProjectKey`. */\n k: string;\n events: ClientEvent[];\n}\n\n// ---------------------------------------------------------------------------\n// Consent shapes\n// ---------------------------------------------------------------------------\n\nexport const CONSENT_TEXT_KEYS = [\n \"title\",\n \"description\",\n \"acceptAll\",\n \"rejectAll\",\n \"settings\",\n \"save\",\n \"close\",\n \"necessaryTitle\",\n \"necessaryDescription\",\n \"analyticsTitle\",\n \"analyticsDescription\",\n \"marketingTitle\",\n \"marketingDescription\",\n \"preferencesTitle\",\n \"preferencesDescription\",\n \"poweredBy\",\n] as const;\nexport type ConsentTextKey = (typeof CONSENT_TEXT_KEYS)[number];\nexport type ConsentTexts = Record<ConsentTextKey, string>;\n\nexport type ConsentCategory = \"analytics\" | \"marketing\" | \"preferences\";\nexport type ConsentChoice = Record<ConsentCategory, boolean>;\n\nexport type ConsentConfig = {\n version: number;\n theme: \"auto\" | \"light\" | \"dark\";\n accentColor?: string;\n position: \"bottom\" | \"bottom-left\" | \"bottom-right\";\n privacyPolicyUrl?: string;\n categories: { analytics: boolean; marketing: boolean; preferences: boolean };\n services: Array<{\n name: string;\n category: \"analytics\" | \"marketing\" | \"preferences\";\n cookies?: string[];\n }>;\n texts?: Partial<Record<\"pl\" | \"en\", Partial<ConsentTexts>>>;\n poweredBy: true;\n};\n\n/** Value of the consent cookie, JSON then base64url. */\nexport interface ConsentCookie {\n v: 1;\n /** Random consent id (also sent to POST /consent). */\n id: string;\n /** Unix seconds. */\n ts: number;\n /** Banner version (`ConsentConfig.version`) the visitor answered. */\n bv: number;\n c: ConsentChoice;\n}\n\nexport const CONSENT_COOKIE_NAME = \"bitsnap_consent\";\nexport const CONSENT_COOKIE_MAX_AGE_SECONDS = 365 * 24 * 60 * 60;\nexport const CONSENT_ACTIONS = [\n \"accept_all\",\n \"reject_all\",\n \"custom\",\n \"withdraw\",\n] as const;\nexport type ConsentAction = (typeof CONSENT_ACTIONS)[number];\n/** POST /consent `action` of a banner impression (not a choice, not in `CONSENT_ACTIONS`). */\nexport const CONSENT_SHOWN_ACTION = \"shown\";\n\n/** POST /consent body of a choice (`CONSENT_ACTIONS`). */\nexport interface ConsentLogBody {\n k: string;\n /** Same random id as `ConsentCookie.id`. 16 to 64 chars of `[A-Za-z0-9_-]`. */\n consent_id: string;\n action: ConsentAction;\n c: ConsentChoice;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/**\n * POST /consent body of a banner impression: the banner opened by itself\n * because the visitor has no valid choice. Once per page load; no consent id\n * and no choice.\n */\nexport interface ConsentShownBody {\n k: string;\n action: typeof CONSENT_SHOWN_ACTION;\n /** Banner version. */\n bv: number;\n /** Hostname the banner ran on. Collector overwrites it with the Origin host. */\n host: string;\n /** Unix SECONDS (like the cookie), not ms. */\n ts: number;\n}\n\n/** Any POST /consent body; discriminate on `action`. */\nexport type ConsentBody = ConsentLogBody | ConsentShownBody;\n\n/** `bitsnap_consent`, or `bitsnap_consent_<projectKey>` for `data-scope=\"project\"`. */\nexport function consentCookieName(scope: \"site\" | \"project\", projectKey?: string): string {\n if (scope === \"project\") {\n if (!projectKey) throw new Error(\"projectKey required for project scope\");\n return `${CONSENT_COOKIE_NAME}_${normalizeProjectKey(projectKey)}`;\n }\n return CONSENT_COOKIE_NAME;\n}\n\n/**\n * Decodes the value of a consent cookie (§11.3). Null when it is not base64url\n * JSON of the documented shape (`v` 1 and a boolean per category).\n */\nexport function parseConsentCookie(value: string | null | undefined): ConsentCookie | null {\n if (!value || !/^[A-Za-z0-9_-]+$/.test(value)) return null;\n try {\n const padded = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n const bin = atob(padded + \"=\".repeat((4 - (padded.length % 4)) % 4));\n const json: unknown = JSON.parse(\n new TextDecoder().decode(Uint8Array.from(bin, (ch) => ch.charCodeAt(0))),\n );\n if (!isRecord(json) || json.v !== 1) return null;\n const c = json.c;\n if (!isRecord(c)) return null;\n if (\n typeof c.analytics !== \"boolean\" ||\n typeof c.marketing !== \"boolean\" ||\n typeof c.preferences !== \"boolean\"\n ) {\n return null;\n }\n return json as unknown as ConsentCookie;\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Project key\n// ---------------------------------------------------------------------------\n\n/**\n * The project key is the existing public hashed project id\n * (`hashId(projectId)` in apps/bitsnap/queries/hashids.ts, the `projectID`\n * of bitsnap-react). A leading `pk_` is accepted and dropped so the\n * documented `pk_…` snippets work too. Returns null when it is not a plausible\n * key (hashids default alphabet).\n */\nexport function normalizeProjectKey(key: string): string | null {\n const bare = key.startsWith(\"pk_\") ? key.slice(3) : key;\n return /^[A-Za-z0-9]{1,32}$/.test(bare) ? bare : null;\n}\n\n// ---------------------------------------------------------------------------\n// X-Bitsnap-Client\n// ---------------------------------------------------------------------------\n\nconst CLIENT_RE = /^([a-z][a-z0-9-]{0,39})@(\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.+-]{1,20})?)$/;\n\n/** `<package>@<version>`, e.g. `bitsnap-react@1.9.0`. Also the shape of `sdk`. */\nexport function parseClientHeader(\n value: string | null | undefined,\n): { package: string; version: string } | null {\n if (!value || value.length > LIMITS.sdk) return null;\n const m = CLIENT_RE.exec(value);\n return m ? { package: m[1], version: m[2] } : null;\n}\n\n// ---------------------------------------------------------------------------\n// URL stripping\n// ---------------------------------------------------------------------------\n\nconst MAX_QUERY_VALUE = LIMITS.utm;\n\n/**\n * Campaign/ref value: trimmed, capped, null when empty or when it holds an \"@\"\n * (someone put an email in a tag). The collector runs every client-supplied\n * `utm_*` and `ref_code` through it again.\n */\nexport function cleanValue(v: string | null | undefined, max: number): string | null {\n if (v == null) return null;\n const t = v.trim();\n // An \"@\" means someone put an email in a campaign tag: drop the value.\n if (t.length === 0 || t.includes(\"@\")) return null;\n return t.slice(0, max);\n}\n\n/**\n * Path sanitiser: no query, no fragment, capped. Opaque segments (24+ chars of\n * `[A-Za-z0-9_-]`, i.e. tokens in order/panel links) become `:token` and\n * segments containing `@` become `:email`.\n */\nexport function sanitizePath(pathname: string): string {\n const segments = pathname.split(\"/\").map((seg) => {\n if (seg.includes(\"@\") || seg.includes(\"%40\")) return \":email\";\n if (/^[A-Za-z0-9_-]{24,}$/.test(seg)) return \":token\";\n return seg;\n });\n const joined = segments.join(\"/\") || \"/\";\n return (joined.startsWith(\"/\") ? joined : `/${joined}`).slice(0, LIMITS.path);\n}\n\nexport interface UrlParts {\n host: string;\n /** Sanitised path, no query. */\n path: string;\n utm_source: string | null;\n utm_medium: string | null;\n utm_campaign: string | null;\n utm_content: string | null;\n utm_term: string | null;\n /** The `ref` query parameter. */\n ref_code: string | null;\n}\n\n/**\n * Parses a URL and keeps only what may leave the browser: host, sanitised path\n * and the `utm_*` and `ref` query parameters. Returns null for non-http(s) or\n * unparseable input. `base` resolves relative URLs.\n */\nexport function parseUrl(url: string, base?: string): UrlParts | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const q = u.searchParams;\n return {\n host: u.hostname.toLowerCase().slice(0, LIMITS.host),\n path: sanitizePath(u.pathname),\n utm_source: cleanValue(q.get(\"utm_source\"), MAX_QUERY_VALUE),\n utm_medium: cleanValue(q.get(\"utm_medium\"), MAX_QUERY_VALUE),\n utm_campaign: cleanValue(q.get(\"utm_campaign\"), MAX_QUERY_VALUE),\n utm_content: cleanValue(q.get(\"utm_content\"), MAX_QUERY_VALUE),\n utm_term: cleanValue(q.get(\"utm_term\"), MAX_QUERY_VALUE),\n ref_code: cleanValue(q.get(\"ref\"), LIMITS.refCode),\n };\n}\n\n/**\n * Returns the URL with userinfo, fragment and every query parameter removed\n * except `utm_*` and `ref`. Null when `url` is not a usable http(s) URL.\n */\nexport function stripUrl(url: string, base?: string): string | null {\n let u: URL;\n try {\n u = new URL(url, base);\n } catch {\n return null;\n }\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n const keep = new URLSearchParams();\n for (const [key, value] of u.searchParams) {\n if (key !== \"ref\" && !key.startsWith(\"utm_\")) continue;\n const cleaned = cleanValue(value, MAX_QUERY_VALUE);\n if (cleaned != null) keep.append(key, cleaned);\n }\n const qs = keep.toString();\n return `${u.protocol}//${u.host}${sanitizePath(u.pathname)}${qs ? `?${qs}` : \"\"}`;\n}\n\nconst HOSTNAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;\n\n/** A plain DNS hostname (lower-cased), or null: no scheme, port, path, userinfo or \"@\". */\nexport function cleanHostname(\n v: string | null | undefined,\n max: number = LIMITS.referrerHost,\n): string | null {\n if (typeof v !== \"string\") return null;\n const h = v.trim().toLowerCase();\n return h.length > 0 && h.length <= max && HOSTNAME_RE.test(h) ? h : null;\n}\n\n/** Public hashed ids (`product_id`, `variant_id`, `order_ref`): URL-safe, at most `LIMITS.id`. */\nexport const ID_RE = /^[A-Za-z0-9_-]{1,64}$/;\n\nexport function cleanId(v: string | null | undefined): string | null {\n return typeof v === \"string\" && ID_RE.test(v) ? v : null;\n}\n\n/** Host of a referrer URL, or null (also null for non-http(s) referrers). */\nexport function referrerHost(referrer: string | null | undefined): string | null {\n if (!referrer) return null;\n try {\n const u = new URL(referrer);\n if (u.protocol !== \"https:\" && u.protocol !== \"http:\") return null;\n return u.hostname.toLowerCase().slice(0, LIMITS.referrerHost);\n } catch {\n return null;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Bot rule\n// ---------------------------------------------------------------------------\n\nconst BOT_UA =\n /bot\\b|crawl|spider|slurp|facebookexternalhit|bingpreview|headless|phantomjs|lighthouse|pagespeed|gtmetrix|pingdom|uptime|statuscake|monitor|preview|scrapy|curl\\/|wget|python-|go-http-client|java\\/|okhttp|axios|node-fetch|undici|libwww|httpclient|aiohttp|postman|insomnia/i;\n\n/** True when the User-Agent is empty or looks automated. Such events are dropped. */\nexport function isBotUserAgent(ua: string | null | undefined): boolean {\n if (!ua || ua.trim().length === 0) return true;\n return BOT_UA.test(ua);\n}\n\n// ---------------------------------------------------------------------------\n// visitor_id\n// ---------------------------------------------------------------------------\n\nconst encoder = new TextEncoder();\n\nasync function hmacSha256(\n key: Uint8Array,\n message: string,\n): Promise<Uint8Array> {\n const cryptoKey = await crypto.subtle.importKey(\n \"raw\",\n key,\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n return new Uint8Array(\n await crypto.subtle.sign(\"HMAC\", cryptoKey, encoder.encode(message)),\n );\n}\n\nfunction base64url(bytes: Uint8Array): string {\n let bin = \"\";\n for (const b of bytes) bin += String.fromCharCode(b);\n return btoa(bin).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** `YYYY-MM-DD` of a unix-ms timestamp in UTC. */\nexport function utcDate(ms: number): string {\n return new Date(ms).toISOString().slice(0, 10);\n}\n\n/**\n * IP as hashed: lower-case; IPv4 unchanged; IPv4-mapped IPv6 (`::ffff:1.2.3.4`\n * or `::ffff:102:304`) becomes plain IPv4; any other IPv6, including one with\n * an embedded dotted quad (`64:ff9b::1.2.3.4`), is cut to its /64 (first four\n * hextets, canonical form `a:b:c:d::`). Both the Worker and the instapay\n * server MUST call this on the client IP before `computeVisitorId`.\n */\nexport function normalizeIp(ip: string): string {\n let s = ip.trim().toLowerCase();\n const zone = s.indexOf(\"%\");\n if (zone >= 0) s = s.slice(0, zone);\n if (!s.includes(\":\")) return s; // plain IPv4 (or not an IP at all)\n\n // Embedded dotted quad in the last 32 bits: turn it into two hextets.\n const quad = /^(.*:)(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})$/.exec(s);\n if (quad) {\n const o = [quad[2], quad[3], quad[4], quad[5]].map(Number);\n if (o.some((n) => n > 255)) return s;\n const hex = (hi: number, lo: number) => (hi * 256 + lo).toString(16);\n s = `${quad[1]}${hex(o[0], o[1])}:${hex(o[2], o[3])}`;\n }\n\n const [head, tail] = s.split(\"::\");\n const headParts = head ? head.split(\":\") : [];\n const tailParts = tail !== undefined && tail !== \"\" ? tail.split(\":\") : [];\n const fill =\n tail === undefined ? 0 : Math.max(0, 8 - headParts.length - tailParts.length);\n const groups = [...headParts, ...Array<string>(fill).fill(\"0\"), ...tailParts];\n if (groups.length !== 8) return s;\n const h = groups.map((g) => Number.parseInt(g, 16) || 0);\n\n // ::ffff:a.b.c.d in hex form.\n if (h.slice(0, 5).every((x) => x === 0) && h[5] === 0xffff) {\n return `${h[6] >> 8}.${h[6] & 255}.${h[7] >> 8}.${h[7] & 255}`;\n }\n return `${h\n .slice(0, 4)\n .map((g) => g.toString(16))\n .join(\":\")}::`;\n}\n\n/**\n * Cookieless visitor id, identical in the Worker and the instapay server.\n *\n * day_secret = HMAC-SHA256(key = utf8(masterSecret), msg = utf8(\"YYYY-MM-DD\")) // 32 raw bytes\n * visitor_id = base64url(HMAC-SHA256(key = day_secret, msg = utf8(ip + \"\\n\" + ua + \"\\n\" + projectId))).slice(0, 22)\n *\n * `dateUtc` is the UTC date of the request; `ip` is `normalizeIp(<client IP>)`;\n * `ua` is the raw `User-Agent` request header; `projectId` is the decimal\n * numeric project id.\n */\nexport async function computeVisitorId(\n masterSecret: string,\n dateUtc: string,\n ip: string,\n ua: string,\n projectId: number | string,\n): Promise<string> {\n if (!/^\\d{4}-\\d{2}-\\d{2}$/.test(dateUtc)) {\n throw new Error(`dateUtc must be YYYY-MM-DD, got ${dateUtc}`);\n }\n const daySecret = await hmacSha256(encoder.encode(masterSecret), dateUtc);\n const mac = await hmacSha256(daySecret, `${ip}\\n${ua}\\n${projectId}`);\n return base64url(mac).slice(0, 22);\n}\n\n/**\n * The `bs_vid_<projectKey>` cookie name. `projectKey` is the bare public key\n * (like `consentCookieName`): consent is per project, so is the client id.\n */\nexport function clientIdCookieName(projectKey: string): string {\n return `bs_vid_${projectKey}`;\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie: 16 random bytes, base64url without padding. */\nexport const CLIENT_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\n/**\n * Stable visitor id of a browser that granted analytics consent (contract §6).\n *\n * consented_visitor_id = \"p_\" + base64url(HMAC-SHA256(key = utf8(masterSecret),\n * msg = utf8(\"client\\n\" + clientId + \"\\n\" + projectId))).slice(0, 22)\n *\n * 24 characters; daily ids are 22, so `isConsentedVisitorId` tells them apart.\n * `clientId` is the `bs_vid_<projectKey>` cookie value and is never stored.\n */\nexport async function computeConsentedVisitorId(\n masterSecret: string,\n clientId: string,\n projectId: number | string,\n): Promise<string> {\n if (!CLIENT_ID_RE.test(clientId)) {\n throw new Error(\"clientId must be 22 base64url characters\");\n }\n const mac = await hmacSha256(\n encoder.encode(masterSecret),\n `client\\n${clientId}\\n${projectId}`,\n );\n return `p_${base64url(mac).slice(0, 22)}`;\n}\n\n/** Whether `visitorId` came from `computeConsentedVisitorId` (not a daily id). */\nexport function isConsentedVisitorId(visitorId: string): boolean {\n return visitorId.length === 24 && visitorId.startsWith(\"p_\");\n}\n\n// ---------------------------------------------------------------------------\n// Validation\n// ---------------------------------------------------------------------------\n\nexport type ValidationResult = { ok: true } | { ok: false; reason: string };\n\nconst UUID_V7 =\n /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst PAGE_ID_RE = /^[A-Za-z0-9_-]{8,32}$/;\n/** A letter TLD is required: `bitsnap-react@1.9.0` and `v@1.2` are not addresses. */\nconst EMAIL_LIKE = /[^\\s@]+@[^\\s@]+\\.[A-Za-z]{2,}\\b/;\n\nfunction isRecord(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\nfunction nullableString(\n e: Record<string, unknown>,\n key: string,\n max: number,\n): string | null {\n const v = e[key];\n if (v === undefined || v === null) return null;\n if (typeof v !== \"string\") return `bad_${key}`;\n return v.length > max ? `too_long_${key}` : null;\n}\n\nfunction checkPropValue(spec: string, value: unknown): boolean {\n const optional = spec.endsWith(\"?\");\n const type = optional ? spec.slice(0, -1) : spec;\n if (type.startsWith(\"enum:\")) {\n return typeof value === \"string\" && type.slice(5).split(\"|\").includes(value);\n }\n switch (type) {\n case \"string\":\n return typeof value === \"string\" && value.length <= LIMITS.maxPropString;\n case \"number\":\n return typeof value === \"number\" && Number.isFinite(value);\n case \"boolean\":\n return typeof value === \"boolean\";\n case \"string[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"string\" && x.length <= LIMITS.maxPropString)\n );\n case \"number[]\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every((x) => typeof x === \"number\" && Number.isFinite(x))\n );\n case \"line_items\":\n return (\n Array.isArray(value) &&\n value.length <= LIMITS.maxPropArray &&\n value.every(\n (x) =>\n isRecord(x) &&\n typeof x.product_id === \"string\" &&\n ID_RE.test(x.product_id) &&\n isNonNegativeSafeInteger(x.qty) &&\n isNonNegativeSafeInteger(x.value_minor),\n )\n );\n default:\n return false;\n }\n}\n\nfunction isNonNegativeSafeInteger(value: unknown): boolean {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0;\n}\n\n/** True when `value` looks like an email address (also exported for the collector's re-checks). */\nexport function looksLikeEmail(value: string): boolean {\n // A well-formed `<package>@<version>` client id is never an address.\n if (parseClientHeader(value) !== null) return false;\n return EMAIL_LIKE.test(value);\n}\n\nfunction hasEmailLike(value: unknown): boolean {\n if (typeof value === \"string\") return looksLikeEmail(value);\n if (Array.isArray(value)) return value.some(hasEmailLike);\n if (isRecord(value)) return Object.values(value).some(hasEmailLike);\n return false;\n}\n\n/**\n * Validates `props` against the catalogue and returns a copy without keys the\n * catalogue does not know (forward compatibility: a newer SDK adding an\n * optional prop must not get its events dropped by an older collector).\n * Fails on missing required props, wrong types, bad enum values, oversize\n * props and string values that look like an email address.\n */\nexport function sanitizeProps(\n event: string,\n props: unknown,\n): { ok: true; props: Record<string, unknown> } | { ok: false; reason: string } {\n if (!isEventName(event)) return { ok: false, reason: \"unknown_event\" };\n const spec = (EVENT_SPEC as Record<string, Record<string, string>>)[event];\n if (!spec) return { ok: false, reason: \"unknown_event\" };\n if (!isRecord(props)) return { ok: false, reason: \"bad_props\" };\n const out: Record<string, unknown> = {};\n for (const [key, type] of Object.entries(spec)) {\n const value = props[key];\n if (value === undefined || value === null) {\n if (!type.endsWith(\"?\")) return { ok: false, reason: `props_missing_${key}` };\n continue;\n }\n if (!checkPropValue(type, value)) return { ok: false, reason: `props_bad_${key}` };\n if (hasEmailLike(value)) return { ok: false, reason: `props_pii_${key}` };\n out[key] =\n type.startsWith(\"line_items\") && Array.isArray(value)\n ? value.map((x) => ({ product_id: x.product_id, qty: x.qty, value_minor: x.value_minor }))\n : value;\n }\n if (JSON.stringify(out).length > LIMITS.maxPropsChars) {\n return { ok: false, reason: \"props_too_large\" };\n }\n return { ok: true, props: out };\n}\n\nexport interface ValidateOptions {\n /**\n * Who sent it. `browser` (default) is POST /e: the event must belong to\n * `storefront_events` or `app_events`, `consent_updated` and `consent_shown`\n * are refused (only POST /consent writes them) and `source` must fit the\n * stream. `server` is the instapay emitter: any stream, `source` must fit the\n * stream.\n */\n from?: \"browser\" | \"server\";\n}\n\n/**\n * Validates the emitter-controlled part of an event: names, types, enums,\n * lengths, the event/source/stream pairing and `props`. It does not check\n * that `ts` is plausible (use `clampTs`), origins or project keys.\n */\nexport function validateEnvelope(\n e: unknown,\n options: ValidateOptions = {},\n): ValidationResult {\n const from = options.from ?? \"browser\";\n const fail = (reason: string): ValidationResult => ({ ok: false, reason });\n if (!isRecord(e)) return fail(\"not_object\");\n\n if (typeof e.event_id !== \"string\" || !UUID_V7.test(e.event_id)) {\n return fail(\"bad_event_id\");\n }\n if (!isEventName(e.event)) return fail(\"unknown_event\");\n const stream = STREAM_FOR_EVENT[e.event as EventName];\n if (from === \"browser\") {\n if (stream === \"business_events\") return fail(\"server_only_event\");\n if (e.event === \"consent_updated\" || e.event === \"consent_shown\") {\n return fail(\"consent_via_consent_endpoint\");\n }\n }\n if (\n typeof e.ts !== \"number\" ||\n !Number.isInteger(e.ts) ||\n e.ts <= 0 ||\n e.ts > 4e12\n ) {\n return fail(\"bad_ts\");\n }\n if (e.schema_version !== SCHEMA_VERSION) return fail(\"bad_schema_version\");\n if (!ENVS.includes(e.env as Env)) return fail(\"bad_env\");\n if (!SOURCES.includes(e.source as Source)) return fail(\"bad_source\");\n if (!SOURCES_FOR_STREAM[stream].includes(e.source as Source)) {\n return fail(\"source_not_allowed_for_event\");\n }\n if (!CHANNELS.includes(e.channel as Channel)) return fail(\"bad_channel\");\n\n if (e.sdk != null) {\n if (typeof e.sdk !== \"string\" || parseClientHeader(e.sdk) === null) {\n return fail(\"bad_sdk\");\n }\n }\n if (e.page_id != null) {\n if (typeof e.page_id !== \"string\" || !PAGE_ID_RE.test(e.page_id)) {\n return fail(\"bad_page_id\");\n }\n }\n if (e.page_type != null && !PAGE_TYPES.includes(e.page_type as PageType)) {\n return fail(\"bad_page_type\");\n }\n if (from === \"browser\") {\n if (typeof e.host !== \"string\" || e.host.length === 0) return fail(\"bad_host\");\n if (typeof e.path !== \"string\" || !e.path.startsWith(\"/\")) return fail(\"bad_path\");\n }\n if (typeof e.path === \"string\" && e.path.includes(\"?\")) return fail(\"path_has_query\");\n if (typeof e.path === \"string\" && e.path.includes(\"#\")) return fail(\"path_has_fragment\");\n\n const lengths: Array<[string, number]> = [\n [\"host\", LIMITS.host],\n [\"path\", LIMITS.path],\n [\"referrer_host\", LIMITS.referrerHost],\n [\"utm_source\", LIMITS.utm],\n [\"utm_medium\", LIMITS.utm],\n [\"utm_campaign\", LIMITS.utm],\n [\"utm_content\", LIMITS.utm],\n [\"utm_term\", LIMITS.utm],\n [\"ref_code\", LIMITS.refCode],\n [\"product_id\", LIMITS.id],\n [\"variant_id\", LIMITS.id],\n [\"order_ref\", LIMITS.id],\n ];\n for (const [key, max] of lengths) {\n const problem = nullableString(e, key, max);\n if (problem) return fail(problem);\n }\n if (e.visitor_id != null) {\n if (typeof e.visitor_id !== \"string\" || !/^[A-Za-z0-9_-]{22}$/.test(e.visitor_id)) {\n return fail(\"bad_visitor_id\");\n }\n }\n if (e.client_id != null) {\n if (typeof e.client_id !== \"string\" || !CLIENT_ID_RE.test(e.client_id)) {\n return fail(\"bad_client_id\");\n }\n }\n\n const props = sanitizeProps(e.event, e.props);\n if (!props.ok) return fail(props.reason);\n return { ok: true };\n}\n\n/** Client `ts` as stored: replaced by `receivedAt` when more than 24 h away from it. */\nexport function clampTs(ts: number, receivedAt: number): number {\n return Math.abs(ts - receivedAt) > LIMITS.tsSkewMs ? receivedAt : ts;\n}\n"]}
|
package/dist/consent.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
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; }var
|
|
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; }var _chunkW3RGQYPDjs = require('./chunk-W3RGQYPD.js');require('./chunk-JSDGZ4NY.js');var _react = require('react');var T=["analytics","marketing","preferences"];var je='script[type="text/plain"][data-bitsnap-consent]:not([data-bitsnap-queued])',Pe="iframe[data-bitsnap-consent][data-src]",de=(e,n)=>T.includes(_nullishCoalesce(n, () => ("")))&&e[n];function Oe(e){return new Promise(n=>{e.addEventListener("load",()=>n(),{once:!0}),e.addEventListener("error",()=>n(),{once:!0})})}function pe(e,n){let t=e.createElement("script");for(let{name:a,value:c}of Array.from(n.attributes))a==="type"||a==="data-bitsnap-queued"||(a==="data-type"?c==="module"&&t.setAttribute("type","module"):a==="data-src"?t.setAttribute("src",c):t.setAttribute(a,c));n.nonce&&(t.nonce=n.nonce);let s=t.hasAttribute("src");s?n.hasAttribute("async")||(t.async=!1):t.text=n.text;let d=s?Oe(t):void 0;return _optionalChain([n, 'access', _2 => _2.parentNode, 'optionalAccess', _3 => _3.replaceChild, 'call', _4 => _4(t,n)]),d}function fe(e,n){let t=0;try{let s=null,d=[];e.querySelectorAll(je).forEach(a=>{if(!de(n,a.getAttribute("data-bitsnap-consent")))return;t++;let c=!a.hasAttribute("data-src")&&!a.hasAttribute("src");if(s||c&&d.length>0){a.setAttribute("data-bitsnap-queued",""),s=(_nullishCoalesce(s, () => (Promise.all(d).then(()=>{})))).then(()=>{try{return pe(e,a)}catch (e2){}}),d=[];return}let m=pe(e,a);m&&d.push(m)}),e.querySelectorAll(Pe).forEach(a=>{if(!de(n,a.getAttribute("data-bitsnap-consent")))return;let c=a.getAttribute("data-src");c&&a.getAttribute("src")!==c&&(a.setAttribute("src",c),a.removeAttribute("data-src"),t++)})}catch (e3){}return t}var ue="https://bitsnap.pl",ge="https://collect.bitsnap.pl";function Q(){return{version:1,theme:"auto",position:"bottom",categories:{analytics:!0,marketing:!0,preferences:!1},services:[],poweredBy:!0}}var _e=["auto","light","dark"],ze=["bottom","bottom-left","bottom-right"],Me=/^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;function Ue(e){return typeof e=="string"&&Me.test(e.trim())?e.trim():void 0}function Be(e){if(typeof e!="string")return;let n=e.trim();return/^(?:https?:\/\/|\/(?!\/)|#|\?)/i.test(n)?n:void 0}function De(e){if(!Array.isArray(e))return[];let n=[];for(let t of e)t&&typeof t.name=="string"&&T.includes(t.category)&&n.push({name:t.name,category:t.category,cookies:Array.isArray(t.cookies)?t.cookies.filter(s=>typeof s=="string"):void 0});return n}function R(...e){let n=Q();for(let t of e){if(!t||typeof t!="object")continue;typeof t.version=="number"&&t.version>=0&&(n.version=Math.floor(t.version)),_e.includes(t.theme)&&(n.theme=t.theme),ze.includes(t.position)&&(n.position=t.position);let s=Ue(t.accentColor);s&&(n.accentColor=s);let d=Be(t.privacyPolicyUrl);if(d&&(n.privacyPolicyUrl=d),t.categories&&typeof t.categories=="object")for(let a of T)typeof t.categories[a]=="boolean"&&(n.categories[a]=t.categories[a]);t.services!==void 0&&(n.services=De(t.services)),t.texts&&typeof t.texts=="object"&&(n.texts=t.texts)}return n}async function ye(e,n,t=3e3){if(typeof fetch!="function")return null;let s=typeof AbortController=="function"?new AbortController:void 0,d=setTimeout(()=>_optionalChain([s, 'optionalAccess', _5 => _5.abort, 'call', _6 => _6()]),t);try{let a=await fetch(`${e.replace(/\/+$/,"")}/api/consent/config?key=${encodeURIComponent(n)}`,{signal:_optionalChain([s, 'optionalAccess', _7 => _7.signal]),credentials:"omit"});if(!a.ok)return null;let c=await a.json();if(!c||typeof c!="object")return null;let m=c.config&&typeof c.config=="object"?c.config:null,g=c.enabled!==!1;return m||!g?{enabled:g,config:m}:null}catch (e4){return null}finally{clearTimeout(d)}}var He={ad_storage:"denied",ad_user_data:"denied",ad_personalization:"denied",analytics_storage:"denied",functionality_storage:"denied",personalization_storage:"denied",security_storage:"granted",wait_for_update:500},z=e=>e?"granted":"denied";function ee(e){return{analytics_storage:z(e.analytics),ad_storage:z(e.marketing),ad_user_data:z(e.marketing),ad_personalization:z(e.marketing),functionality_storage:z(e.preferences),personalization_storage:z(e.preferences)}}function Re(e,n){return n==="off"?!1:n==="on"||typeof e.gtag=="function"||Array.isArray(e.dataLayer)}function Ne(e){if(typeof e.gtag=="function")return e.gtag;let n=e.dataLayer=e.dataLayer||[],t=function(){n.push(arguments)};return e.gtag=t,t}function me(e,n){if(!Re(e,n))return null;let t=Ne(e);return{setDefault:()=>t("consent","default",{...He}),update:s=>t("consent","update",ee(s))}}var te={pl:{title:"Szanujemy Twoj\u0105 prywatno\u015B\u0107",description:"U\u017Cywamy plik\xF3w cookie, aby strona dzia\u0142a\u0142a poprawnie. Za Twoj\u0105 zgod\u0105 wykorzystujemy je te\u017C do statystyk, personalizacji i reklam. Mo\u017Cesz zaakceptowa\u0107 wszystkie, odrzuci\u0107 wszystkie albo wybra\u0107, na co si\u0119 zgadzasz.",acceptAll:"Akceptuj wszystkie",rejectAll:"Odrzu\u0107 wszystkie",settings:"Ustawienia",save:"Zapisz wyb\xF3r",close:"Zamknij",necessaryTitle:"Niezb\u0119dne",necessaryDescription:"Potrzebne do dzia\u0142ania strony: koszyk, zapami\u0119tanie Twojego wyboru, bezpiecze\u0144stwo. Nie mo\u017Cna ich wy\u0142\u0105czy\u0107.",analyticsTitle:"Statystyki",analyticsDescription:"Pomagaj\u0105 nam zrozumie\u0107, jak odwiedzaj\u0105cy korzystaj\u0105 ze strony, \u017Ceby\u015Bmy mogli j\u0105 ulepsza\u0107.",marketingTitle:"Marketing",marketingDescription:"Pozwalaj\u0105 mierzy\u0107 skuteczno\u015B\u0107 reklam i pokazywa\u0107 Ci oferty dopasowane do zainteresowa\u0144.",preferencesTitle:"Preferencje",preferencesDescription:"Zapami\u0119tuj\u0105 Twoje ustawienia, na przyk\u0142ad j\u0119zyk czy wygl\u0105d strony.",poweredBy:"Powered by"},en:{title:"We value your privacy",description:"We use cookies to make this site work. With your consent we also use them for statistics, personalization and ads. You can accept all, reject all, or choose what you agree to.",acceptAll:"Accept all",rejectAll:"Reject all",settings:"Settings",save:"Save choices",close:"Close",necessaryTitle:"Necessary",necessaryDescription:"Needed for the site to work: the cart, remembering your choice, security. They cannot be turned off.",analyticsTitle:"Analytics",analyticsDescription:"Help us understand how visitors use the site, so we can improve it.",marketingTitle:"Marketing",marketingDescription:"Measure how well ads work and show you offers that match your interests.",preferencesTitle:"Preferences",preferencesDescription:"Remember your settings, such as language or how the site looks.",poweredBy:"Powered by"}},be={pl:{privacy:"Polityka prywatno\u015Bci",services:"Us\u0142ugi",always:"Zawsze aktywne"},en:{privacy:"Privacy policy",services:"Services",always:"Always on"}};function X(e,n){return e==="pl"||e==="en"?e:/^pl\b/i.test(_nullishCoalesce(n, () => ("")))?"pl":"en"}function q(e,n){let t={...te[e]},s=_optionalChain([n, 'optionalAccess', _8 => _8[e]]);if(s)for(let d of Object.keys(t)){let a=s[d];typeof a=="string"&&a.trim()!==""&&(t[d]=a)}return t}function Ie(e){let n=e.replace("#","");n.length===3&&(n=n.replace(/./g,"$&$&"));let t=parseInt(n,16);return[t>>16&255,t>>8&255,t&255]}function he(e){let[n,t,s]=Ie(e).map(d=>{let a=d/255;return a<=.03928?a/12.92:Math.pow((a+.055)/1.055,2.4)});return .2126*n+.7152*t+.0722*s}function Y(e,n){let[t,s]=[he(e),he(n)].sort((d,a)=>a-d);return(t+.05)/(s+.05)}function Ce(e){return Y(e,"#ffffff")>=Y(e,"#111111")?"#ffffff":"#111111"}var Z={light:{bg:"#ffffff",fg:"#14171c",muted:"#495260",border:"#c9ced6",off:"#6b7280",thumb:"#ffffff",accent:"#1d4ed8",onAccent:"#ffffff",link:"#1d4ed8"},dark:{bg:"#171a20",fg:"#f1f3f6",muted:"#b7beca",border:"#3a404b",off:"#8b93a1",thumb:"#171a20",accent:"#8ab4ff",onAccent:"#0b1220",link:"#9dc0ff"}},xe=e=>`--bg:${e.bg};--fg:${e.fg};--muted:${e.muted};--border:${e.border};--off:${e.off};--thumb:${e.thumb};--accent:${e.accent};--on-accent:${e.onAccent};--link:${e.link};--focus:${e.accent}`,ve=`
|
|
2
2
|
:host{all:initial}
|
|
3
3
|
*{box-sizing:border-box}
|
|
4
4
|
[hidden]{display:none!important}
|
|
5
|
-
.root{${
|
|
6
|
-
.root[data-theme=dark]{${
|
|
5
|
+
.root{${xe(Z.light)};position:fixed;inset:0;pointer-events:none;z-index:2147483000;font:14px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;color:var(--fg);-webkit-text-size-adjust:100%}
|
|
6
|
+
.root[data-theme=dark]{${xe(Z.dark)};color-scheme:dark}
|
|
7
7
|
button,input{font:inherit;color:inherit}
|
|
8
8
|
.banner,.overlay{pointer-events:auto}
|
|
9
9
|
@supports (color:color-mix(in srgb,red 50%,blue)){::selection{background:color-mix(in srgb,var(--accent) 24%,transparent)}}
|
|
@@ -86,5 +86,5 @@ input:focus-visible+.track{outline:2px solid var(--focus);outline-offset:2px}
|
|
|
86
86
|
.btn,.link-btn{padding:0 12px;min-height:40px}
|
|
87
87
|
}
|
|
88
88
|
@media(prefers-reduced-motion:reduce){*,*::before,*::after{animation:none!important;transition:none!important}}
|
|
89
|
-
`.replace(/\n/g,"");var He='<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect width="16" height="16" rx="4" fill="currentColor" style="color:var(--fg)"/><circle cx="8" cy="8" r="3" fill="var(--bg)"/></svg>',Re='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>',Ie="button:not([disabled]),input:not([disabled]),a[href]";function xe(e){let{doc:n,config:t,texts:r,locale:p}=e,s=ye[p],l=null,b=null,g,u,f,C,v,h="none",w=null,T=null,S=new Map;function c(o,a={},...d){let y=n.createElement(o);for(let m of Object.keys(a))m==="class"?y.className=a[m]:y.setAttribute(m,a[m]);for(let m of d)y.append(m);return y}function x(o,a,d){let y=c("button",{type:"button",class:o},a);return y.addEventListener("click",d),y}function M(){let o=c("a",{href:`https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(_nullishCoalesce(_optionalChain([n, 'access', _9 => _9.location, 'optionalAccess', _10 => _10.hostname]), () => ("")))}`,target:"_blank",rel:"noopener"});return o.append(r.poweredBy+" "),o.insertAdjacentHTML("beforeend",He),o.append(c("b",{},"bitsnap")),c("div",{class:"foot"},o)}function k(){let o=c("p",{class:"desc",id:"d"},r.description);return t.privacyPolicyUrl&&o.append(" ",c("a",{href:t.privacyPolicyUrl,target:"_blank",rel:"noopener"},s.privacy)),o}function j(){v=x("link-btn",r.settings,()=>D()),u=c("div",{class:`banner ${t.position==="bottom"?"bottom":`card ${t.position}`}`,role:"region","aria-live":"polite","aria-labelledby":"t","aria-describedby":"d",tabindex:"-1"},c("div",{class:"inner"},c("div",{class:"text"},c("div",{class:"title",id:"t"},r.title),k()),c("div",{class:"actions"},x("btn",r.acceptAll,e.onAcceptAll),x("btn",r.rejectAll,e.onRejectAll),v),M()))}function U(o){let a=t.services.filter(m=>m.category===o),d=c("input",{type:"checkbox",role:"switch","aria-labelledby":`l-${o}`,"aria-describedby":`p-${o}`});o==="necessary"?(d.checked=!0,d.disabled=!0):S.set(o,d);let y=c("div",{class:"cat"},c("div",{class:"row"},c("span",{class:"cat-title",id:`l-${o}`},r[`${o}Title`]),c("span",{style:"display:flex;align-items:center"},...o==="necessary"?[c("span",{class:"always"},s.always)]:[],c("label",{class:"switch"},d,c("span",{class:"track"})))),c("p",{id:`p-${o}`},r[`${o}Description`]));return a.length>0&&y.append(c("p",{class:"svc"},c("b",{},`${s.services}: `),a.map(m=>m.name).join(", "))),y}function I(){let o=c("button",{type:"button",class:"x","aria-label":r.close});o.insertAdjacentHTML("beforeend",Re),o.addEventListener("click",()=>O());let a=c("div",{class:"d-body"},U("necessary"));for(let d of A)t.categories[d]&&a.append(U(d));C=c("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"st",tabindex:"-1"},c("div",{class:"d-head"},c("div",{class:"title",id:"st"},r.settings),o),a,c("div",{class:"d-foot"},c("div",{class:"actions"},x("btn",r.save,()=>e.onSave(N())),x("btn",r.acceptAll,e.onAcceptAll),x("btn",r.rejectAll,e.onRejectAll)),M())),f=c("div",{class:"overlay"},C),f.addEventListener("mousedown",d=>{d.target===f&&O()})}function N(){let o={analytics:!1,marketing:!1,preferences:!1};return S.forEach((a,d)=>o[d]=a.checked),o}function E(){let o=t.theme==="dark"||t.theme==="auto"&&!!_optionalChain([T, 'optionalAccess', _11 => _11.matches]);g.setAttribute("data-theme",o?"dark":"light"),$(o)}function $(o){let a=t.accentColor;if(a){if(o&&q(a,Y.dark.bg)<3){for(let d of["--accent","--focus","--on-accent"])g.style.removeProperty(d);return}g.style.setProperty("--accent",a),g.style.setProperty("--focus",a),g.style.setProperty("--on-accent",be(a))}}function B(){l||(l=c("div",{id:"bitsnap-consent","data-bitsnap-consent-host":""}),b=l.attachShadow({mode:"open"}),b.append(c("style",{},Ce)),g=c("div",{class:"root",lang:p}),j(),I(),u.hidden=!0,f.hidden=!0,g.append(u,f),b.append(g),typeof _optionalChain([n, 'access', _12 => _12.defaultView, 'optionalAccess', _13 => _13.matchMedia])=="function"&&(T=n.defaultView.matchMedia("(prefers-color-scheme: dark)"),_optionalChain([T, 'access', _14 => _14.addEventListener, 'optionalCall', _15 => _15("change",E)])),E(),n.body.append(l))}function L(){return Array.from(C.querySelectorAll(Ie))}function P(o){if(h!=="settings")return;if(o.key==="Escape"){o.preventDefault(),O();return}if(o.key!=="Tab")return;let a=L();if(a.length===0)return;let d=_optionalChain([b, 'optionalAccess', _16 => _16.activeElement]),y=a[0],m=a[a.length-1],W=!d||!C.contains(d);o.shiftKey&&(W||d===y||d===C)?(o.preventDefault(),m.focus()):!o.shiftKey&&(W||d===m)&&(o.preventDefault(),y.focus())}function K(o=!1){try{B(),h="banner",n.removeEventListener("keydown",P,!0),f.hidden=!0,u.hidden=!1,o&&u.focus({preventScroll:!0})}catch (e5){}}function D(){try{if(B(),h!=="settings"){let a=n.activeElement;w=a&&a!==l&&a!==n.body?a:null}let o=e.getChoices();S.forEach((a,d)=>a.checked=!!_optionalChain([o, 'optionalAccess', _17 => _17[d]])),h="settings",u.hidden=!0,f.hidden=!1,n.addEventListener("keydown",P,!0),C.focus({preventScroll:!0})}catch (e6){}}function O(){h==="settings"&&(n.removeEventListener("keydown",P,!0),f.hidden=!0,e.hasChoice()?(h="none",_optionalChain([w, 'optionalAccess', _18 => _18.focus, 'optionalCall', _19 => _19({preventScroll:!0})])):(h="banner",u.hidden=!1,v.focus({preventScroll:!0})))}function G(){if(!l)return;n.removeEventListener("keydown",P,!0);let o=h==="settings";h="none",u.hidden=!0,f.hidden=!0,o&&_optionalChain([w, 'optionalAccess', _20 => _20.focus, 'optionalCall', _21 => _21({preventScroll:!0})])}function i(){n.removeEventListener("keydown",P,!0),_optionalChain([T, 'optionalAccess', _22 => _22.removeEventListener, 'optionalCall', _23 => _23("change",E)]),_optionalChain([l, 'optionalAccess', _24 => _24.remove, 'call', _25 => _25()]),l=null,b=null,h="none"}return{showBanner:K,showSettings:D,hide:G,destroy:i}}var _=()=>({analytics:!1,marketing:!1,preferences:!1}),ve=e=>e&&{id:e.id,ts:e.ts,bv:e.bv,c:{...e.c}};function Z(e={}){let n=typeof window<"u"?window:void 0,t=_optionalChain([n, 'optionalAccess', _26 => _26.document]),r=new Set,p=e.apiHost||pe,s=e.collectHost||fe,l=e.projectKey?_chunkXIHGWNTSjs.b.call(void 0, e.projectKey):null,b=_chunkXIHGWNTSjs.i.call(void 0, _nullishCoalesce(l, () => (void 0)),e.scope),g=!!e.preview,u=H(M()),f=null,C=null,v=null,h=!1,w=!1,T,S=[],c=n&&!g?k(()=>ge(n,e.gcm),null):null;k(()=>_optionalChain([c, 'optionalAccess', _27 => _27.setDefault, 'call', _28 => _28()]),void 0);let x=t&&!g?_chunkXIHGWNTSjs.k.call(void 0, t,b):null;function M(i){let o={...e.config};return e.theme&&(o.theme=e.theme),e.position&&(o.position=e.position),e.privacyPolicyUrl&&(o.privacyPolicyUrl=e.privacyPolicyUrl),{...i,...o}}function k(i,o){try{return i()}catch (e7){return o}}function j(i){let o=_();for(let a of A)o[a]=!!_optionalChain([i, 'optionalAccess', _29 => _29[a]])&&u.categories[a];return o}function U(i){r.forEach(o=>k(()=>o({...i,c:{...i.c}}),void 0)),k(()=>{_optionalChain([n, 'optionalAccess', _30 => _30.dispatchEvent, 'call', _31 => _31(new n.CustomEvent("bitsnap:consent",{detail:{...i,c:{...i.c}}}))])},void 0)}function I(i,o){g||!l||typeof fetch!="function"||k(()=>{let a=JSON.stringify({k:l,consent_id:o.id,action:i,c:o.c,bv:o.bv,host:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _32 => _32.location, 'optionalAccess', _33 => _33.hostname]), () => ("")),ts:o.ts});fetch(`${s.replace(/\/+$/,"")}/consent`,{method:"POST",keepalive:!0,credentials:"omit",body:a}).catch(()=>{})},void 0)}function N(i){return A.filter(o=>i[o]&&u.categories[o])}function E(i,o){if(!t||w)return;if(g){_optionalChain([v, 'optionalAccess', _34 => _34.hide, 'call', _35 => _35()]);return}let a=_nullishCoalesce(f, () => (C)),d=a?N(a.c).filter(W=>!i[W]):[],y=d.length>0?"withdraw":o,m={id:_nullishCoalesce(_optionalChain([a, 'optionalAccess', _36 => _36.id]), () => (_chunkXIHGWNTSjs.j.call(void 0, ))),ts:Math.floor(Date.now()/1e3),bv:u.version,c:i};_chunkXIHGWNTSjs.l.call(void 0, t,b,m),f=m,C=null,$(m.c),d.length>0&&_chunkXIHGWNTSjs.o.call(void 0, t,u.services,d),_optionalChain([v, 'optionalAccess', _37 => _37.hide, 'call', _38 => _38()]),U({...m,action:y}),I(y,m),d.length>0&&e.reloadOnWithdraw&&B()}function $(i){k(()=>_optionalChain([c, 'optionalAccess', _39 => _39.update, 'call', _40 => _40(i)]),void 0),t&&de(t,i)}function B(){setTimeout(()=>k(()=>_optionalChain([n, 'optionalAccess', _41 => _41.location, 'access', _42 => _42.reload, 'call', _43 => _43()]),void 0),50)}function L(){if(!t||!h||w)return null;if(!v){let i=F(e.locale,_optionalChain([n, 'optionalAccess', _44 => _44.navigator, 'optionalAccess', _45 => _45.language]));v=xe({doc:t,config:u,locale:i,texts:P(X(i,u.texts)),getChoices:()=>_nullishCoalesce(_optionalChain([f, 'optionalAccess', _46 => _46.c]), () => (null)),hasChoice:()=>f!==null,onAcceptAll:()=>E(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all"),onRejectAll:()=>E(_(),"reject_all"),onSave:o=>E(j(o),"custom")})}return v}function P(i){let o=_optionalChain([e, 'access', _47 => _47.title, 'optionalAccess', _48 => _48.trim, 'call', _49 => _49()]),a=_optionalChain([e, 'access', _50 => _50.description, 'optionalAccess', _51 => _51.trim, 'call', _52 => _52()]);return{...i,...o&&{title:o},...a&&{description:a}}}function K(i){_optionalChain([i, 'access', _53 => _53.target, 'optionalAccess', _54 => _54.closest, 'optionalCall', _55 => _55("[data-bitsnap-consent-open]")])&&(i.preventDefault(),G.open())}let D=(async()=>{if(!t||!n)return null;let i=l&&!g?await ue(p,l):null;if(w)return null;let o=_optionalChain([i, 'optionalAccess', _56 => _56.config])?void 0:e.categories;if(u=H(_optionalChain([i, 'optionalAccess', _57 => _57.config]),o?{categories:{..._(),...o}}:void 0,M()),t.readyState==="loading"&&await new Promise(y=>t.addEventListener("DOMContentLoaded",()=>y(),{once:!0})),w)return null;h=!0,t.addEventListener("click",K),T=()=>t.removeEventListener("click",K);let a=!l||_optionalChain([i, 'optionalAccess', _58 => _58.config])!=null,d=_optionalChain([i, 'optionalAccess', _59 => _59.enabled])===!1;return g?_optionalChain([L, 'call', _60 => _60(), 'optionalAccess', _61 => _61.showBanner, 'call', _62 => _62()]):x&&(d||!a||x.bv===u.version)?(f=x,$(j(f.c))):(x&&(C=x),d||_optionalChain([L, 'call', _63 => _63(), 'optionalAccess', _64 => _64.showBanner, 'call', _65 => _65()])),S.splice(0).forEach(y=>k(y,void 0)),k(()=>n.dispatchEvent(new n.CustomEvent("bitsnap:consent:ready")),void 0),ve(f)})().catch(()=>null);function O(i){h?i():S.push(i)}let G={scope:e.scope==="project"&&l?"project":"global",projectKey:l,get:()=>ve(f),denied:i=>_optionalChain([(_nullishCoalesce(f, () => (C))), 'optionalAccess', _66 => _66.c, 'access', _67 => _67[i]])===!1,on(i,o){return i!=="change"||typeof o!="function"?()=>{}:(r.add(o),()=>void r.delete(o))},open(){h?_optionalChain([L, 'call', _68 => _68(), 'optionalAccess', _69 => _69.showSettings, 'call', _70 => _70()]):D.then(()=>_optionalChain([L, 'call', _71 => _71(), 'optionalAccess', _72 => _72.showSettings, 'call', _73 => _73()]))},close(){_optionalChain([v, 'optionalAccess', _74 => _74.hide, 'call', _75 => _75()])},accept:i=>O(()=>E(j(i),"custom")),acceptAll:()=>O(()=>E(j({analytics:!0,marketing:!0,preferences:!0}),"accept_all")),rejectAll:()=>O(()=>E(_(),"reject_all")),reset(){if(!t||w)return;if(g){_optionalChain([L, 'call', _76 => _76(), 'optionalAccess', _77 => _77.showBanner, 'call', _78 => _78()]);return}let i=_nullishCoalesce(f, () => (C)),o=i?N(i.c):[];_chunkXIHGWNTSjs.m.call(void 0, t,b),f=null,C=i,k(()=>_optionalChain([c, 'optionalAccess', _79 => _79.update, 'call', _80 => _80(_())]),void 0),o.length>0&&_chunkXIHGWNTSjs.o.call(void 0, t,u.services,o),U({id:_nullishCoalesce(_optionalChain([i, 'optionalAccess', _81 => _81.id]), () => ("")),ts:Math.floor(Date.now()/1e3),bv:u.version,c:_(),action:"reset"}),i&&o.length>0&&I("withdraw",{id:i.id,ts:Math.floor(Date.now()/1e3),bv:u.version,c:_()}),_optionalChain([L, 'call', _82 => _82(), 'optionalAccess', _83 => _83.showBanner, 'call', _84 => _84(!0)]),o.length>0&&e.reloadOnWithdraw&&B()},ready:D,destroy(){w=!0,_optionalChain([T, 'optionalCall', _85 => _85()]),_optionalChain([v, 'optionalAccess', _86 => _86.destroy, 'call', _87 => _87()]),v=null,r.clear()}};return Ne(G)}function Ne(e){let n={...e};for(let t of Object.keys(e)){let r=e[t];typeof r=="function"&&(n[t]=(...p)=>{try{return r(...p)}catch (e8){return t==="get"?null:t==="on"?()=>{}:void 0}})}return n}function Ke(e){let{projectKey:n,theme:t,locale:r,position:p,privacyPolicyUrl:s,scope:l,apiHost:b,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:C,title:v,description:h}=e,w=JSON.stringify(_nullishCoalesce(e.config, () => (null))),T=_react.useRef.call(void 0, e.config);T.current=e.config;let S=JSON.stringify(_nullishCoalesce(e.categories, () => (null))),c=_react.useRef.call(void 0, e.categories);return c.current=e.categories,_chunkXIHGWNTSjs.p.call(void 0, ()=>{if(window.BitsnapConsent)return;let x=Z({projectKey:n,theme:t,locale:r,position:p,privacyPolicyUrl:s,scope:l,apiHost:b,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:C,title:v,description:h,categories:c.current,config:T.current});return window.BitsnapConsent=x,()=>{x.destroy(),window.BitsnapConsent===x&&delete window.BitsnapConsent}},[n,t,r,p,s,l,b,g,u,f,C,v,h,S,w]),null}var ke="null",Te=null;function Ge(){let e=typeof window>"u"?null:_nullishCoalesce(_optionalChain([window, 'access', _88 => _88.BitsnapConsent, 'optionalAccess', _89 => _89.get, 'call', _90 => _90()]), () => (null)),n=JSON.stringify(e);return n!==ke&&(ke=n,Te=e),Te}function We(e){return window.addEventListener("bitsnap:consent",e),window.addEventListener("bitsnap:consent:ready",e),()=>{window.removeEventListener("bitsnap:consent",e),window.removeEventListener("bitsnap:consent:ready",e)}}function Fe(){let e=_react.useSyncExternalStore.call(void 0, We,Ge,()=>null),n=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _91 => _91.BitsnapConsent, 'optionalAccess', _92 => _92.open, 'call', _93 => _93()]),[]),t=_react.useCallback.call(void 0, l=>_optionalChain([window, 'access', _94 => _94.BitsnapConsent, 'optionalAccess', _95 => _95.accept, 'call', _96 => _96(l)]),[]),r=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _97 => _97.BitsnapConsent, 'optionalAccess', _98 => _98.acceptAll, 'call', _99 => _99()]),[]),p=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _100 => _100.BitsnapConsent, 'optionalAccess', _101 => _101.rejectAll, 'call', _102 => _102()]),[]),s=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _103 => _103.BitsnapConsent, 'optionalAccess', _104 => _104.reset, 'call', _105 => _105()]),[]);return{consent:e,decided:e!==null,open:n,accept:t,acceptAll:r,rejectAll:p,reset:s}}exports.BitsnapConsent = Ke; exports.DEFAULT_TEXTS = ee; exports.createConsent = Z; exports.defaultConfig = V; exports.mergeConfig = H; exports.mergeTexts = X; exports.resolveLocale = F; exports.toConsentModeUpdate = Q; exports.useConsent = Fe;
|
|
89
|
+
`.replace(/\n/g,"");var $e='<svg width="14" height="14" viewBox="0 0 16 16" aria-hidden="true"><rect width="16" height="16" rx="4" fill="currentColor" style="color:var(--fg)"/><circle cx="8" cy="8" r="3" fill="var(--bg)"/></svg>',Ke='<svg width="16" height="16" viewBox="0 0 16 16" aria-hidden="true"><path d="M3 3l10 10M13 3L3 13" stroke="currentColor" stroke-width="2" stroke-linecap="round" fill="none"/></svg>',We="button:not([disabled]),input:not([disabled]),a[href]";function we(e){let{doc:n,config:t,texts:s,locale:d}=e,a=be[d],c=null,m=null,g,u,f,h,x,b="none",v=null,k=null,S=new Map;function l(r,o={},...i){let p=n.createElement(r);for(let y of Object.keys(o))y==="class"?p.className=o[y]:p.setAttribute(y,o[y]);for(let y of i)p.append(y);return p}function C(r,o,i){let p=l("button",{type:"button",class:r},o);return p.addEventListener("click",i),p}function M(){let r=l("a",{href:`https://bitsnap.pl/?utm_source=consent_banner&utm_medium=referral&utm_content=${encodeURIComponent(_nullishCoalesce(_optionalChain([n, 'access', _9 => _9.location, 'optionalAccess', _10 => _10.hostname]), () => ("")))}`,target:"_blank",rel:"noopener"});return r.append(s.poweredBy+" "),r.insertAdjacentHTML("beforeend",$e),r.append(l("b",{},"bitsnap")),l("div",{class:"foot"},r)}function w(){let r=l("p",{class:"desc",id:"d"},s.description);return t.privacyPolicyUrl&&r.append(" ",l("a",{href:t.privacyPolicyUrl,target:"_blank",rel:"noopener"},a.privacy)),r}function P(){x=C("link-btn",s.settings,()=>G()),u=l("div",{class:`banner ${t.position==="bottom"?"bottom":`card ${t.position}`}`,role:"region","aria-live":"polite","aria-labelledby":"t","aria-describedby":"d",tabindex:"-1"},l("div",{class:"inner"},l("div",{class:"text"},l("div",{class:"title",id:"t"},s.title),w()),l("div",{class:"actions"},C("btn",s.acceptAll,e.onAcceptAll),C("btn",s.rejectAll,e.onRejectAll),x),M()))}function U(r){let o=t.services.filter(y=>y.category===r),i=l("input",{type:"checkbox",role:"switch","aria-labelledby":`l-${r}`,"aria-describedby":`p-${r}`});r==="necessary"?(i.checked=!0,i.disabled=!0):S.set(r,i);let p=l("div",{class:"cat"},l("div",{class:"row"},l("span",{class:"cat-title",id:`l-${r}`},s[`${r}Title`]),l("span",{style:"display:flex;align-items:center"},...r==="necessary"?[l("span",{class:"always"},a.always)]:[],l("label",{class:"switch"},i,l("span",{class:"track"})))),l("p",{id:`p-${r}`},s[`${r}Description`]));return o.length>0&&p.append(l("p",{class:"svc"},l("b",{},`${a.services}: `),o.map(y=>y.name).join(", "))),p}function I(){let r=l("button",{type:"button",class:"x","aria-label":s.close});r.insertAdjacentHTML("beforeend",Ke),r.addEventListener("click",()=>_());let o=l("div",{class:"d-body"},U("necessary"));for(let i of T)t.categories[i]&&o.append(U(i));h=l("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"st",tabindex:"-1"},l("div",{class:"d-head"},l("div",{class:"title",id:"st"},s.settings),r),o,l("div",{class:"d-foot"},l("div",{class:"actions"},C("btn",s.save,()=>e.onSave($())),C("btn",s.acceptAll,e.onAcceptAll),C("btn",s.rejectAll,e.onRejectAll)),M())),f=l("div",{class:"overlay"},h),f.addEventListener("mousedown",i=>{i.target===f&&_()})}function $(){let r={analytics:!1,marketing:!1,preferences:!1};return S.forEach((o,i)=>r[i]=o.checked),r}function B(){let r=t.theme==="dark"||t.theme==="auto"&&!!_optionalChain([k, 'optionalAccess', _11 => _11.matches]);g.setAttribute("data-theme",r?"dark":"light"),K(r)}function K(r){let o=t.accentColor;if(o){if(r&&Y(o,Z.dark.bg)<3){for(let i of["--accent","--focus","--on-accent"])g.style.removeProperty(i);return}g.style.setProperty("--accent",o),g.style.setProperty("--focus",o),g.style.setProperty("--on-accent",Ce(o))}}function E(){c||(c=l("div",{id:"bitsnap-consent","data-bitsnap-consent-host":""}),m=c.attachShadow({mode:"open"}),m.append(l("style",{},ve)),g=l("div",{class:"root",lang:d}),P(),I(),u.hidden=!0,f.hidden=!0,g.append(u,f),m.append(g),typeof _optionalChain([n, 'access', _12 => _12.defaultView, 'optionalAccess', _13 => _13.matchMedia])=="function"&&(k=n.defaultView.matchMedia("(prefers-color-scheme: dark)"),_optionalChain([k, 'access', _14 => _14.addEventListener, 'optionalCall', _15 => _15("change",B)])),B(),n.body.append(c))}function W(){return Array.from(h.querySelectorAll(We))}function L(r){if(b!=="settings")return;if(r.key==="Escape"){r.preventDefault(),_();return}if(r.key!=="Tab")return;let o=W();if(o.length===0)return;let i=_optionalChain([m, 'optionalAccess', _16 => _16.activeElement]),p=o[0],y=o[o.length-1],A=!i||!h.contains(i);r.shiftKey&&(A||i===p||i===h)?(r.preventDefault(),y.focus()):!r.shiftKey&&(A||i===y)&&(r.preventDefault(),p.focus())}function j(r=!1){try{E(),b="banner",n.removeEventListener("keydown",L,!0),f.hidden=!0,u.hidden=!1,r&&u.focus({preventScroll:!0})}catch (e5){}}function G(){try{if(E(),b!=="settings"){let o=n.activeElement;v=o&&o!==c&&o!==n.body?o:null}let r=e.getChoices();S.forEach((o,i)=>o.checked=!!_optionalChain([r, 'optionalAccess', _17 => _17[i]])),b="settings",u.hidden=!0,f.hidden=!1,n.addEventListener("keydown",L,!0),h.focus({preventScroll:!0})}catch (e6){}}function _(){b==="settings"&&(n.removeEventListener("keydown",L,!0),f.hidden=!0,e.hasChoice()?(b="none",_optionalChain([v, 'optionalAccess', _18 => _18.focus, 'optionalCall', _19 => _19({preventScroll:!0})])):(b="banner",u.hidden=!1,x.focus({preventScroll:!0})))}function F(){if(!c)return;n.removeEventListener("keydown",L,!0);let r=b==="settings";b="none",u.hidden=!0,f.hidden=!0,r&&_optionalChain([v, 'optionalAccess', _20 => _20.focus, 'optionalCall', _21 => _21({preventScroll:!0})])}function D(){n.removeEventListener("keydown",L,!0),_optionalChain([k, 'optionalAccess', _22 => _22.removeEventListener, 'optionalCall', _23 => _23("change",B)]),_optionalChain([c, 'optionalAccess', _24 => _24.remove, 'call', _25 => _25()]),c=null,m=null,b="none"}return{showBanner:j,showSettings:G,hide:F,destroy:D}}var O=()=>({analytics:!1,marketing:!1,preferences:!1}),ke=e=>e&&{id:e.id,ts:e.ts,bv:e.bv,c:{...e.c}},Te=new WeakMap;function J(e={}){let n=typeof window<"u"?window:void 0,t=_optionalChain([n, 'optionalAccess', _26 => _26.document]),s=new Set,d=e.apiHost||ue,a=e.collectHost||ge,c=e.projectKey?_chunkW3RGQYPDjs.c.call(void 0, e.projectKey):null,m=_chunkW3RGQYPDjs.j.call(void 0, _nullishCoalesce(c, () => (void 0)),e.scope),g=!!e.preview,u=R(M()),f=null,h=null,x=null,b=!1,v=!1,k,S=[],l=n&&!g?w(()=>me(n,e.gcm),null):null;w(()=>_optionalChain([l, 'optionalAccess', _27 => _27.setDefault, 'call', _28 => _28()]),void 0);let C=t&&!g?_chunkW3RGQYPDjs.l.call(void 0, t,m):null;function M(o){let i={...e.config};return e.theme&&(i.theme=e.theme),e.position&&(i.position=e.position),e.privacyPolicyUrl&&(i.privacyPolicyUrl=e.privacyPolicyUrl),{...o,...i}}function w(o,i){try{return o()}catch (e7){return i}}function P(o){let i=O();for(let p of T)i[p]=!!_optionalChain([o, 'optionalAccess', _29 => _29[p]])&&u.categories[p];return i}function U(o){s.forEach(i=>w(()=>i({...o,c:{...o.c}}),void 0)),w(()=>{_optionalChain([n, 'optionalAccess', _30 => _30.dispatchEvent, 'call', _31 => _31(new n.CustomEvent("bitsnap:consent",{detail:{...o,c:{...o.c}}}))])},void 0)}function I(o){g||!c||typeof fetch!="function"||w(()=>{fetch(`${a.replace(/\/+$/,"")}/consent`,{method:"POST",keepalive:!0,credentials:"omit",body:JSON.stringify({k:c,host:_nullishCoalesce(_optionalChain([n, 'optionalAccess', _32 => _32.location, 'optionalAccess', _33 => _33.hostname]), () => ("")),...o})}).catch(()=>{})},void 0)}function $(o,i){I({consent_id:i.id,action:o,c:i.c,bv:i.bv,ts:i.ts})}function B(){if(!n||!c)return;let o=_nullishCoalesce(Te.get(n), () => (new Set));o.has(c)||(Te.set(n,o.add(c)),I({action:_chunkW3RGQYPDjs.b,bv:u.version,ts:Math.floor(Date.now()/1e3)}))}function K(o){return T.filter(i=>o[i]&&u.categories[i])}function E(o,i){if(!t||v)return;if(g){_optionalChain([x, 'optionalAccess', _34 => _34.hide, 'call', _35 => _35()]);return}let p=_nullishCoalesce(f, () => (h)),y=p?K(p.c).filter(Le=>!o[Le]):[],A=y.length>0?"withdraw":i,H={id:_nullishCoalesce(_optionalChain([p, 'optionalAccess', _36 => _36.id]), () => (_chunkW3RGQYPDjs.k.call(void 0, ))),ts:Math.floor(Date.now()/1e3),bv:u.version,c:o};_chunkW3RGQYPDjs.m.call(void 0, t,m,H),f=H,h=null,W(H.c),y.length>0&&_chunkW3RGQYPDjs.p.call(void 0, t,u.services,y),_optionalChain([x, 'optionalAccess', _37 => _37.hide, 'call', _38 => _38()]),U({...H,action:A}),$(A,H),y.length>0&&e.reloadOnWithdraw&&L()}function W(o){w(()=>_optionalChain([l, 'optionalAccess', _39 => _39.update, 'call', _40 => _40(o)]),void 0),t&&fe(t,o)}function L(){setTimeout(()=>w(()=>_optionalChain([n, 'optionalAccess', _41 => _41.location, 'access', _42 => _42.reload, 'call', _43 => _43()]),void 0),50)}function j(){if(!t||!b||v)return null;if(!x){let o=X(e.locale,_optionalChain([n, 'optionalAccess', _44 => _44.navigator, 'optionalAccess', _45 => _45.language]));x=we({doc:t,config:u,locale:o,texts:G(q(o,u.texts)),getChoices:()=>_nullishCoalesce(_optionalChain([f, 'optionalAccess', _46 => _46.c]), () => (null)),hasChoice:()=>f!==null,onAcceptAll:()=>E(P({analytics:!0,marketing:!0,preferences:!0}),"accept_all"),onRejectAll:()=>E(O(),"reject_all"),onSave:i=>E(P(i),"custom")})}return x}function G(o){let i=_optionalChain([e, 'access', _47 => _47.title, 'optionalAccess', _48 => _48.trim, 'call', _49 => _49()]),p=_optionalChain([e, 'access', _50 => _50.description, 'optionalAccess', _51 => _51.trim, 'call', _52 => _52()]);return{...o,...i&&{title:i},...p&&{description:p}}}function _(o){_optionalChain([o, 'access', _53 => _53.target, 'optionalAccess', _54 => _54.closest, 'optionalCall', _55 => _55("[data-bitsnap-consent-open]")])&&(o.preventDefault(),r.open())}let F=(async()=>{if(!t||!n)return null;let o=c&&!g?await ye(d,c):null;if(v)return null;let i=_optionalChain([o, 'optionalAccess', _56 => _56.config])?void 0:e.categories;if(u=R(_optionalChain([o, 'optionalAccess', _57 => _57.config]),i?{categories:{...O(),...i}}:void 0,M()),t.readyState==="loading"&&await new Promise(A=>t.addEventListener("DOMContentLoaded",()=>A(),{once:!0})),v)return null;b=!0,t.addEventListener("click",_),k=()=>t.removeEventListener("click",_);let p=!c||_optionalChain([o, 'optionalAccess', _58 => _58.config])!=null,y=_optionalChain([o, 'optionalAccess', _59 => _59.enabled])===!1;return g?_optionalChain([j, 'call', _60 => _60(), 'optionalAccess', _61 => _61.showBanner, 'call', _62 => _62()]):C&&(y||!p||C.bv===u.version)?(f=C,W(P(f.c))):(C&&(h=C),y||_optionalChain([j, 'call', _63 => _63(), 'optionalAccess', _64 => _64.showBanner, 'call', _65 => _65()])),S.splice(0).forEach(A=>w(A,void 0)),!v&&!g&&!y&&f===null&&B(),w(()=>n.dispatchEvent(new n.CustomEvent("bitsnap:consent:ready")),void 0),ke(f)})().catch(()=>null);function D(o){b?o():S.push(o)}let r={scope:e.scope==="project"&&c?"project":"global",projectKey:c,get:()=>ke(f),denied:o=>_optionalChain([(_nullishCoalesce(f, () => (h))), 'optionalAccess', _66 => _66.c, 'access', _67 => _67[o]])===!1,on(o,i){return o!=="change"||typeof i!="function"?()=>{}:(s.add(i),()=>void s.delete(i))},open(){b?_optionalChain([j, 'call', _68 => _68(), 'optionalAccess', _69 => _69.showSettings, 'call', _70 => _70()]):F.then(()=>_optionalChain([j, 'call', _71 => _71(), 'optionalAccess', _72 => _72.showSettings, 'call', _73 => _73()]))},close(){_optionalChain([x, 'optionalAccess', _74 => _74.hide, 'call', _75 => _75()])},accept:o=>D(()=>E(P(o),"custom")),acceptAll:()=>D(()=>E(P({analytics:!0,marketing:!0,preferences:!0}),"accept_all")),rejectAll:()=>D(()=>E(O(),"reject_all")),reset(){if(!t||v)return;if(g){_optionalChain([j, 'call', _76 => _76(), 'optionalAccess', _77 => _77.showBanner, 'call', _78 => _78()]);return}let o=_nullishCoalesce(f, () => (h)),i=o?K(o.c):[];_chunkW3RGQYPDjs.n.call(void 0, t,m),f=null,h=o,w(()=>_optionalChain([l, 'optionalAccess', _79 => _79.update, 'call', _80 => _80(O())]),void 0),i.length>0&&_chunkW3RGQYPDjs.p.call(void 0, t,u.services,i),U({id:_nullishCoalesce(_optionalChain([o, 'optionalAccess', _81 => _81.id]), () => ("")),ts:Math.floor(Date.now()/1e3),bv:u.version,c:O(),action:"reset"}),o&&i.length>0&&$("withdraw",{id:o.id,ts:Math.floor(Date.now()/1e3),bv:u.version,c:O()}),_optionalChain([j, 'call', _82 => _82(), 'optionalAccess', _83 => _83.showBanner, 'call', _84 => _84(!0)]),i.length>0&&e.reloadOnWithdraw&&L()},ready:F,destroy(){v=!0,_optionalChain([k, 'optionalCall', _85 => _85()]),_optionalChain([x, 'optionalAccess', _86 => _86.destroy, 'call', _87 => _87()]),x=null,s.clear()}};return Ge(r)}function Ge(e){let n={...e};for(let t of Object.keys(e)){let s=e[t];typeof s=="function"&&(n[t]=(...d)=>{try{return s(...d)}catch (e8){return t==="get"?null:t==="on"?()=>{}:void 0}})}return n}function Xe(e){let{projectKey:n,theme:t,locale:s,position:d,privacyPolicyUrl:a,scope:c,apiHost:m,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:h,title:x,description:b}=e,v=JSON.stringify(_nullishCoalesce(e.config, () => (null))),k=_react.useRef.call(void 0, e.config);k.current=e.config;let S=JSON.stringify(_nullishCoalesce(e.categories, () => (null))),l=_react.useRef.call(void 0, e.categories);return l.current=e.categories,_chunkW3RGQYPDjs.q.call(void 0, ()=>{if(window.BitsnapConsent)return;let C=J({projectKey:n,theme:t,locale:s,position:d,privacyPolicyUrl:a,scope:c,apiHost:m,collectHost:g,reloadOnWithdraw:u,gcm:f,preview:h,title:x,description:b,categories:l.current,config:k.current});return window.BitsnapConsent=C,()=>{C.destroy(),window.BitsnapConsent===C&&delete window.BitsnapConsent}},[n,t,s,d,a,c,m,g,u,f,h,x,b,S,v]),null}var Ae="null",Se=null;function qe(){let e=typeof window>"u"?null:_nullishCoalesce(_optionalChain([window, 'access', _88 => _88.BitsnapConsent, 'optionalAccess', _89 => _89.get, 'call', _90 => _90()]), () => (null)),n=JSON.stringify(e);return n!==Ae&&(Ae=n,Se=e),Se}function Ye(e){return window.addEventListener("bitsnap:consent",e),window.addEventListener("bitsnap:consent:ready",e),()=>{window.removeEventListener("bitsnap:consent",e),window.removeEventListener("bitsnap:consent:ready",e)}}function Ze(){let e=_react.useSyncExternalStore.call(void 0, Ye,qe,()=>null),n=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _91 => _91.BitsnapConsent, 'optionalAccess', _92 => _92.open, 'call', _93 => _93()]),[]),t=_react.useCallback.call(void 0, c=>_optionalChain([window, 'access', _94 => _94.BitsnapConsent, 'optionalAccess', _95 => _95.accept, 'call', _96 => _96(c)]),[]),s=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _97 => _97.BitsnapConsent, 'optionalAccess', _98 => _98.acceptAll, 'call', _99 => _99()]),[]),d=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _100 => _100.BitsnapConsent, 'optionalAccess', _101 => _101.rejectAll, 'call', _102 => _102()]),[]),a=_react.useCallback.call(void 0, ()=>_optionalChain([window, 'access', _103 => _103.BitsnapConsent, 'optionalAccess', _104 => _104.reset, 'call', _105 => _105()]),[]);return{consent:e,decided:e!==null,open:n,accept:t,acceptAll:s,rejectAll:d,reset:a}}exports.BitsnapConsent = Xe; exports.DEFAULT_TEXTS = te; exports.createConsent = J; exports.defaultConfig = Q; exports.mergeConfig = R; exports.mergeTexts = q; exports.resolveLocale = X; exports.toConsentModeUpdate = ee; exports.useConsent = Ze;
|
|
90
90
|
//# sourceMappingURL=consent.js.map
|