bitsnap-react 1.8.0 → 1.10.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 +162 -0
- package/dist/CartProvider-HXLGQ4EX.mjs +2 -0
- package/dist/CartProvider-OHHYOMSG.js +2 -0
- package/dist/CartProvider-OHHYOMSG.js.map +1 -0
- package/dist/analytics.d.mts +45 -0
- package/dist/analytics.d.ts +45 -0
- package/dist/analytics.js +2 -0
- package/dist/analytics.js.map +1 -0
- package/dist/analytics.mjs +2 -0
- package/dist/catalog.d.mts +14 -1
- package/dist/catalog.d.ts +14 -1
- package/dist/catalog.js +1 -1
- package/dist/catalog.js.map +1 -1
- package/dist/catalog.mjs +1 -1
- package/dist/chunk-3Z6VNXBP.js +2 -0
- package/dist/chunk-3Z6VNXBP.js.map +1 -0
- package/dist/chunk-43IIYJ6J.mjs +2 -0
- package/dist/chunk-43IIYJ6J.mjs.map +1 -0
- package/dist/chunk-6D3OORMK.mjs +2 -0
- package/dist/chunk-6D3OORMK.mjs.map +1 -0
- package/dist/chunk-ADYVTMGH.mjs +2 -0
- package/dist/chunk-ADYVTMGH.mjs.map +1 -0
- package/dist/{chunk-WRCXZMKK.js → chunk-AJNULBC3.js} +2 -2
- package/dist/chunk-AJNULBC3.js.map +1 -0
- package/dist/chunk-B32ACCW2.js +2 -0
- package/dist/chunk-B32ACCW2.js.map +1 -0
- package/dist/chunk-DDY7IBMG.mjs +2 -0
- package/dist/chunk-DDY7IBMG.mjs.map +1 -0
- package/dist/chunk-DPKT6ITB.js +4 -0
- package/dist/chunk-DPKT6ITB.js.map +1 -0
- package/dist/{chunk-T2POA6RW.js → chunk-F46RJVWC.js} +2 -2
- package/dist/chunk-F46RJVWC.js.map +1 -0
- package/dist/chunk-F6GQLKA6.js +2 -0
- package/dist/chunk-F6GQLKA6.js.map +1 -0
- package/dist/chunk-JSDGZ4NY.js.map +1 -1
- package/dist/chunk-JXCHRSPW.mjs +4 -0
- package/dist/chunk-JXCHRSPW.mjs.map +1 -0
- package/dist/chunk-KOYBZORL.js.map +1 -1
- package/dist/chunk-RLEC25JI.mjs +2 -0
- package/dist/chunk-RLEC25JI.mjs.map +1 -0
- package/dist/chunk-RVILRUW3.js +2 -0
- package/dist/chunk-RVILRUW3.js.map +1 -0
- package/dist/chunk-T2OUOO4X.mjs +2 -0
- package/dist/chunk-T2OUOO4X.mjs.map +1 -0
- package/dist/chunk-VIII45AC.js +2 -0
- package/dist/chunk-VIII45AC.js.map +1 -0
- package/dist/chunk-XIHGWNTS.js +2 -0
- package/dist/chunk-XIHGWNTS.js.map +1 -0
- package/dist/chunk-YXFJG4MF.mjs +2 -0
- package/dist/chunk-YXFJG4MF.mjs.map +1 -0
- package/dist/chunk-ZPTHK4OX.mjs +2 -0
- package/dist/{chunk-OJT3YO2R.mjs.map → chunk-ZPTHK4OX.mjs.map} +1 -1
- package/dist/consent.d.mts +165 -0
- package/dist/consent.d.ts +165 -0
- package/dist/consent.js +75 -0
- package/dist/consent.js.map +1 -0
- package/dist/consent.mjs +75 -0
- package/dist/consent.mjs.map +1 -0
- package/dist/course.d.mts +13 -3
- package/dist/course.d.ts +13 -3
- package/dist/course.js +1 -1
- package/dist/course.js.map +1 -1
- package/dist/course.mjs +1 -1
- package/dist/course.mjs.map +1 -1
- package/dist/embed/analytics.js +1 -0
- package/dist/embed/consent.js +74 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.css +1 -1
- package/dist/index.css.map +1 -1
- package/dist/index.d.mts +54 -7
- package/dist/index.d.ts +54 -7
- 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 +929 -0
- package/dist/instrument-CmxK7S4T.d.ts +929 -0
- package/dist/internal.js.map +1 -1
- package/dist/methods-A5KGZBAM.js +2 -0
- package/dist/methods-A5KGZBAM.js.map +1 -0
- package/dist/methods-AOHKV7IN.mjs +2 -0
- package/dist/methods-AOHKV7IN.mjs.map +1 -0
- package/dist/models.js.map +1 -1
- package/dist/returns.d.mts +9 -1
- package/dist/returns.d.ts +9 -1
- package/dist/returns.js +1 -1
- package/dist/returns.js.map +1 -1
- package/dist/returns.mjs +1 -1
- package/dist/{types-PSBBDdQm.d.mts → types-BnVWLcoB.d.mts} +13 -0
- package/dist/{types-BTm_ZolC.d.ts → types-i-IuN4Im.d.ts} +13 -0
- package/package.json +46 -45
- package/dist/CartProvider-5KAG5QGA.mjs +0 -2
- package/dist/CartProvider-7GJXW2IP.js +0 -2
- package/dist/CartProvider-7GJXW2IP.js.map +0 -1
- package/dist/chunk-45AP7UZE.mjs +0 -2
- package/dist/chunk-45AP7UZE.mjs.map +0 -1
- package/dist/chunk-7XTDFTQU.js +0 -4
- package/dist/chunk-7XTDFTQU.js.map +0 -1
- package/dist/chunk-C6Z7LOHB.mjs +0 -2
- package/dist/chunk-C6Z7LOHB.mjs.map +0 -1
- package/dist/chunk-HB6KQT26.mjs +0 -4
- package/dist/chunk-HB6KQT26.mjs.map +0 -1
- package/dist/chunk-LWK4E5G5.js +0 -2
- package/dist/chunk-LWK4E5G5.js.map +0 -1
- package/dist/chunk-OJT3YO2R.mjs +0 -2
- package/dist/chunk-OUYRKNZJ.mjs +0 -2
- package/dist/chunk-OUYRKNZJ.mjs.map +0 -1
- package/dist/chunk-P2YB25KZ.js +0 -2
- package/dist/chunk-P2YB25KZ.js.map +0 -1
- package/dist/chunk-T2POA6RW.js.map +0 -1
- package/dist/chunk-VPKE2ZOR.mjs +0 -2
- package/dist/chunk-VPKE2ZOR.mjs.map +0 -1
- package/dist/chunk-WRCXZMKK.js.map +0 -1
- package/dist/chunk-WSM4OM72.mjs +0 -2
- package/dist/chunk-WSM4OM72.mjs.map +0 -1
- package/dist/chunk-XRNTUSBH.js +0 -2
- package/dist/chunk-XRNTUSBH.js.map +0 -1
- package/dist/chunk-Z2BKIX6F.js +0 -2
- package/dist/chunk-Z2BKIX6F.js.map +0 -1
- package/dist/methods-ITD6WFIY.mjs +0 -2
- package/dist/methods-JENIGNF7.js +0 -2
- package/dist/methods-JENIGNF7.js.map +0 -1
- /package/dist/{CartProvider-5KAG5QGA.mjs.map → CartProvider-HXLGQ4EX.mjs.map} +0 -0
- /package/dist/{methods-ITD6WFIY.mjs.map → analytics.mjs.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/lib/appearance-core.ts"],"names":["omitUndefined","tokens","result","key","value","hasAnyElement","elements","element","resolveBoundaryStyle","variables","shadcnVariables","style","token","variable","resolveAppearanceCore","appearance","config","theme","getSlotAppearance","slot"],"mappings":"AA8DO,0rBAASA,CAAAA,CACdC,CAAAA,CACgC,CAChC,IAAMC,CAAAA,CAAkC,CAAC,CAAA,CAEzC,GAAA,CAAA,GAAW,CAACC,CAAAA,CAAKC,CAAK,CAAA,GAAK,MAAA,CAAO,OAAA,CAAQH,CAAM,CAAA,CAC1CG,CAAAA,EAAS,IAAA,EAAA,CACXF,CAAAA,CAAOC,CAAG,CAAA,CAAIC,CAAAA,CAAAA,CAIlB,OAAOF,CACT,CAEO,SAASG,CAAAA,CACdC,CAAAA,CACS,CACT,OAAO,MAAA,CAAO,MAAA,CAAmCA,CAAQ,CAAA,CAAE,IAAA,CACxDC,CAAAA,EACCA,CAAAA,EAAW,IAAA,EAAA,CAASA,CAAAA,CAAQ,SAAA,EAAa,IAAA,EAAQA,CAAAA,CAAQ,KAAA,EAAS,IAAA,CACtE,CACF,CAMO,SAASC,CAAAA,CACdP,CAAAA,CACAQ,CAAAA,CACAC,CAAAA,CACe,CACf,IAAMC,CAAAA,CAAgC,CAAC,CAAA,CAEvC,GAAA,CAAA,GAAW,CAACC,CAAAA,CAAOC,CAAQ,CAAA,GAAK,MAAA,CAAO,OAAA,CAAgBJ,CAAS,CAAA,CAAG,CACjE,IAAML,CAAAA,CAAQH,CAAAA,CAAOW,CAAc,CAAA,CAC/BR,CAAAA,EAAS,IAAA,EAAA,CACXO,CAAAA,CAAME,CAAQ,CAAA,CAAIT,CAAAA,CAEtB,CAEA,GAAA,CAAA,GAAW,CAAE,KAAA,CAAAQ,CAAAA,CAAO,QAAA,CAAAC,CAAS,CAAA,GAAKH,CAAAA,CAAiB,CACjD,IAAMN,CAAAA,CAAQH,CAAAA,CAAOW,CAAK,CAAA,CACtBR,CAAAA,EAAS,IAAA,EAAA,CACXO,CAAAA,CAAME,CAAQ,CAAA,CAAIT,CAAAA,CAEtB,CAEA,OAAOO,CACT,CAOO,SAASG,CAAAA,CAKdC,CAAAA,CAOAC,CAAAA,CAC4C,CAC5C,IAAMC,CAAAA,kCAAeF,CAAAA,2BAAY,OAAA,SAASC,CAAAA,CAAO,cAAA,CAE3Cf,CAAAA,CAASD,CAAAA,CAAqB,CAClC,GAAGgB,CAAAA,CAAO,OAAA,CAAQC,CAAK,CAAA,CACvB,mBAAGF,CAAAA,6BAAY,QACjB,CAAC,CAAA,CAEKT,CAAAA,kCAAWS,CAAAA,6BAAY,UAAA,SAAY,CAAC,GAAA,CAE1C,MAAO,CACL,KAAA,CAAAE,CAAAA,CACA,YAAA,iBACEF,CAAAA,6BAAY,OAAA,EAAS,IAAA,EACrB,MAAA,CAAO,IAAA,CAAKd,CAAM,CAAA,CAAE,MAAA,CAAS,CAAA,EAC7BI,CAAAA,CAAcC,CAAQ,CAAA,CACxB,MAAA,CAAAL,CAAAA,CACA,QAAA,CAAAK,CAAAA,CACA,aAAA,CAAeE,CAAAA,CACbP,CAAAA,CACAe,CAAAA,CAAO,SAAA,CACPA,CAAAA,CAAO,eACT,CACF,CACF,CAGO,SAASE,CAAAA,CACdZ,CAAAA,CACAa,CAAAA,CAC4B,CAC5B,OAAOb,CAAAA,CAASa,CAAI,CACtB,CAAA,6BAAA","file":"/home/emems/
|
|
1
|
+
{"version":3,"sources":["../src/lib/appearance-core.ts"],"names":["omitUndefined","tokens","result","key","value","hasAnyElement","elements","element","resolveBoundaryStyle","variables","shadcnVariables","style","token","variable","res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AAA,CAC4C,CAC5C,IAAMC,CAAAA,kCAAeF,CAAAA,2BAAY,OAAA,SAASC,CAAAA,CAAO,cAAA,CAE3Cf,CAAAA,CAASD,CAAAA,CAAqB,CAClC,GAAGgB,CAAAA,CAAO,OAAA,CAAQC,CAAK,CAAA,CACvB,mBAAGF,CAAAA,6BAAY,QACjB,CAAC,CAAA,CAEKT,CAAAA,kCAAWS,CAAAA,6BAAY,UAAA,SAAY,CAAC,GAAA,CAE1C,MAAO,CACL,KAAA,CAAAE,CAAAA,CACA,YAAA,iBACEF,CAAAA,6BAAY,OAAA,EAAS,IAAA,EACrB,MAAA,CAAO,IAAA,CAAKd,CAAM,CAAA,CAAE,MAAA,CAAS,CAAA,EAC7BI,CAAAA,CAAcC,CAAQ,CAAA,CACxB,MAAA,CAAAL,CAAAA,CACA,QAAA,CAAAK,CAAAA,CACA,aAAA,CAAeE,CAAAA,CACbP,CAAAA,CACAe,CAAAA,CAAO,SAAA,CACPA,CAAAA,CAAO,eACT,CACF,CACF,CAGO,SAASE,CAAAA,CACdZ,CAAAA,CACAa,CAAAA,CAC4B,CAC5B,OAAOb,CAAAA,CAASa,CAAI,CACtB,CAAA,6BAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-KOYBZORL.js","sourcesContent":["import type { CSSProperties } from \"react\";\n\n/**\n * Generic building blocks shared by the appearance modules (checkout, and\n * later returns). Each module supplies its own token to CSS variable map, theme\n * presets and shadcn mapping, and keeps its own public types. Everything here\n * is pure so it can be tested without a DOM.\n */\n\n/** Caller overrides for a single slot. */\nexport type SlotAppearance = {\n /** Merged after the built-in classes with `cn`, so Tailwind conflicts resolve. */\n className?: string;\n /** Merged after the built-in inline styles. */\n style?: CSSProperties;\n};\n\n/** Typed partial map of slot name to its overrides. */\nexport type AppearanceElements<Slot extends string> = Partial<\n Record<Slot, SlotAppearance>\n>;\n\n/** CSS custom property used for each token. */\nexport type TokenVariables<Token extends string> = Readonly<\n Record<Token, string>\n>;\n\n/**\n * Remaps a token onto a shadcn theme variable (`--background`, `--ring`, ...)\n * so shared UI primitives follow the module's tokens. Only written when the\n * token is in effect.\n */\nexport type ShadcnVariableMapping<Token extends string> = readonly {\n token: Token;\n variable: string;\n}[];\n\nexport type AppearanceCoreConfig<Token extends string, Theme extends string> = {\n /** Theme used when the caller does not select one. */\n defaultTheme: Theme;\n /** Partial token sets applied underneath the caller tokens. */\n presets: Record<Theme, Partial<Record<Token, string>>>;\n variables: TokenVariables<Token>;\n shadcnVariables: ShadcnVariableMapping<Token>;\n};\n\nexport type ResolvedAppearanceCore<\n Token extends string,\n Theme extends string,\n Slot extends string,\n> = {\n theme: Theme;\n /** `true` as soon as the caller passed a theme, a token or a slot override. */\n isCustomized: boolean;\n /** Tokens that are in effect. Empty entries were dropped. */\n tokens: Partial<Record<Token, string>>;\n elements: AppearanceElements<Slot>;\n /** Inline custom properties for the theme boundary. */\n boundaryStyle: CSSProperties;\n};\n\n/** Drops `undefined`/`null` tokens so unset values keep the stylesheet default. */\nexport function omitUndefined<Token extends string>(\n tokens: Partial<Record<Token, string>>,\n): Partial<Record<Token, string>> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(tokens)) {\n if (value != null) {\n result[key] = value;\n }\n }\n\n return result as Partial<Record<Token, string>>;\n}\n\nexport function hasAnyElement<Slot extends string>(\n elements: AppearanceElements<Slot>,\n): boolean {\n return Object.values<SlotAppearance | undefined>(elements).some(\n (element) =>\n element != null && (element.className != null || element.style != null),\n );\n}\n\n/**\n * Token to CSS variable resolution, followed by the shadcn remapping. Only\n * tokens that are in effect produce a variable.\n */\nexport function resolveBoundaryStyle<Token extends string>(\n tokens: Partial<Record<Token, string>>,\n variables: TokenVariables<Token>,\n shadcnVariables: ShadcnVariableMapping<Token>,\n): CSSProperties {\n const style: Record<string, string> = {};\n\n for (const [token, variable] of Object.entries<string>(variables)) {\n const value = tokens[token as Token];\n if (value != null) {\n style[variable] = value;\n }\n }\n\n for (const { token, variable } of shadcnVariables) {\n const value = tokens[token];\n if (value != null) {\n style[variable] = value;\n }\n }\n\n return style as CSSProperties;\n}\n\n/**\n * Resolves theme, tokens, slot overrides and the boundary style. The resolver\n * never invents values: a token is only present when the caller provided it or\n * selected a theme preset that carries it.\n */\nexport function resolveAppearanceCore<\n Token extends string,\n Theme extends string,\n Slot extends string,\n>(\n appearance:\n | {\n theme?: Theme;\n tokens?: Partial<Record<Token, string>>;\n elements?: AppearanceElements<Slot>;\n }\n | undefined,\n config: AppearanceCoreConfig<Token, Theme>,\n): ResolvedAppearanceCore<Token, Theme, Slot> {\n const theme: Theme = appearance?.theme ?? config.defaultTheme;\n\n const tokens = omitUndefined<Token>({\n ...config.presets[theme],\n ...appearance?.tokens,\n });\n\n const elements = appearance?.elements ?? {};\n\n return {\n theme,\n isCustomized:\n appearance?.theme != null ||\n Object.keys(tokens).length > 0 ||\n hasAnyElement(elements),\n tokens,\n elements,\n boundaryStyle: resolveBoundaryStyle(\n tokens,\n config.variables,\n config.shadcnVariables,\n ),\n };\n}\n\n/** Caller overrides for a slot, if any were provided. */\nexport function getSlotAppearance<Slot extends string>(\n elements: AppearanceElements<Slot>,\n slot: Slot,\n): SlotAppearance | undefined {\n return elements[slot];\n}\n"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as le,b as _,c as ue,d as z,e as de,f as V,g as fe,h as pe,n as Y,p as L}from"./chunk-ADYVTMGH.mjs";var Oe=Symbol.for("bitsnap.pageViews");function ye(e){let t=e;return t[Oe]??={path:null,starters:new Set,watching:!1}}function De(e,t){let n=()=>{try{t()}catch{}};for(let o of["pushState","replaceState"]){let a=e.history[o];e.history[o]=function(...i){let c=a.apply(this,i);return n(),c}}e.addEventListener("popstate",n)}function A(e,t=window){try{let n=ye(t),o=()=>e();n.watching||(n.watching=!0,De(t,()=>{let i=t.location.pathname;i===n.path||n.starters.size===0||(n.path=i,n.starters.values().next().value?.())})),n.starters.add(o);let a=t.location.pathname;return a!==n.path&&(n.path=a,o()),()=>void n.starters.delete(o)}catch{return()=>{}}}function ge(e=window){let t=ye(e);t.path=null,t.starters.clear()}var ve="1.10.0";function I(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&typeof n.getRandomValues=="function")n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.floor(Math.random()*256);return t}var me="X-Bitsnap-Visitor",$e=390*24*60*60,Me=/^[A-Za-z0-9_-]{22}$/;function R(e){return e.BitsnapConsent}function je(e,t){for(let n of e.cookie.split(";")){let o=n.indexOf("=");if(o!==-1&&n.slice(0,o).trim()===t)return n.slice(o+1).trim()}return null}function He(e){let t=e.toLowerCase();return t==="bitsnap.pl"||t.endsWith(".bitsnap.pl")}function F(e,t){try{let n=R(e);if(!n)return!1;if(n.scope==="project")return n.projectKey===t;let o=He(e.location.hostname);return n.scope==="global"?!o:!1}catch{return!1}}function J(e,t){try{return R(e)?.get()?.c.analytics===!0&&F(e,t)}catch{return!1}}function he(){let e="";return I(16).forEach(t=>e+=String.fromCharCode(t)),btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ee(e,t){try{return je(e,V(t))}catch{return null}}function B(e,t){let n=Ee(e,t);return n!==null&&Me.test(n)?n:null}function ke(e,t,n){try{let o=e.document,a=`${V(t)}=${n}; Max-Age=${$e}; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");for(let i of Y(e.location.hostname).reverse())if(o.cookie=`${a}; Domain=${i}`,B(o,t)===n)return;o.cookie=a}catch{}}function be(e,t){try{let n=e.document;if(Ee(n,t)===null)return;let o=`${V(t)}=; Max-Age=0; Path=/; SameSite=Lax`+(e.location.protocol==="https:"?"; Secure":"");n.cookie=o;for(let a of Y(e.location.hostname))n.cookie=`${o}; Domain=${a}`}catch{}}function N(e,t){try{let n=e.navigator;return n?.globalPrivacyControl===!0||n?.webdriver===!0?null:J(e,t)?B(e.document,t):null}catch{return null}}var Ue="https://collect.bitsnap.pl",Ke=5e3,Ge=20,Te=32*1024,ze=60*1024,xe=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function _e(e){return typeof TextEncoder=="function"?new TextEncoder().encode(e).length:unescape(encodeURIComponent(e)).length}var y={track(){},page(){},clientId:()=>null,flush(){},setEnabled(){},onEvent:()=>()=>{},configure(){},destroy(){}};function Ye(e=Date.now()){let t=I(16),n=e;for(let a=5;a>=0;a--)t[a]=n%256,n=Math.floor(n/256);t[6]=t[6]&15|112,t[8]=t[8]&63|128;let o=Array.from(t,a=>a.toString(16).padStart(2,"0")).join("");return`${o.slice(0,8)}-${o.slice(8,12)}-${o.slice(12,16)}-${o.slice(16,20)}-${o.slice(20)}`}var Ce="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";function Fe(){return Array.from(I(16),e=>Ce[e%Ce.length]).join("")}function Je(e,t,n=!1){let o=_e(JSON.stringify({k:e,events:[]})),a=[],i=[],c=o,s=()=>{i.length>0&&a.push({body:JSON.stringify({k:e,events:i}),bytes:c,count:i.length}),i=[],c=o};for(let u of t){let l=_e(JSON.stringify(u));o+l>Te||((i.length>=le.maxBatchEvents||c+l+(i.length>0?1:0)>Te)&&s(),c+=l+(i.length>0?1:0),i.push(u))}if(s(),n){let u=0,l=a.length;for(;l>0&&u+a[l-1].bytes<=ze;)u+=a[l-1].bytes,l--;a=a.slice(l)}return a}function Xe(e){try{return typeof window>"u"||typeof document>"u"?y:qe(e,window)}catch{return y}}function qe(e,t){let n=_(e.projectKey??""),o=!!e.debug,a=(...r)=>{o&&console.warn("[bitsnap analytics]",...r)};if(!n)return a("invalid projectKey, tracking is off"),y;let i=n,c=r=>`${(r||Ue).replace(/\/+$/,"")}/e`,s=c(e.endpoint),u=e.source??"sdk_react",l=e.channel??"embed",b=`bitsnap-react@${ve}`,M=Fe(),T=z(t.location.href),j=e.env??"live";if(!e.env)try{new URLSearchParams(t.location.search).has("test")&&(j="test")}catch{}let Le=de(document.referrer),H=e.enabled!==!1,ee=null,Re=0,p=[],h=null,C=new Set;e.onEvent&&C.add(e.onEvent);let E=[],g,m=!0;function W(){let r=R(t);!r||r===g||(g=r,m=!r.ready,r.ready?.then(()=>{g===r&&(m=!0,re())},()=>{g===r&&(m=!0)}))}function te(){W();try{if(!g)return!1;let r=g.get();return!!g.denied&&g.denied("analytics")||!!r&&r.c.analytics===!1}catch{return!1}}function ne(r){C.forEach(f=>{try{f(r)}catch{}})}function U(r){try{if(W(),!g||!F(t,i))return;J(t,i)?P()&&B(t.document,i)===null&&ke(t,i,he()):r&&be(t,i)}catch{}}function re(){if(U(!0),te())p=[],E=[],w();else{if(m&&E.length>0){let r=E;E=[],r.forEach(ne)}p.length>0&&x()}}function P(){if(!H)return!1;let r=t.navigator;return r&&(r.globalPrivacyControl===!0||r.webdriver===!0)?!1:!te()}function w(){h!==null&&clearTimeout(h),h=null}function Be(){h===null&&(h=setTimeout(()=>{h=null,x()},Ke),h.unref?.())}function Ne(r){try{if(typeof fetch=="function"){fetch(s,{method:"POST",body:r,keepalive:!0,credentials:"omit",headers:{"Content-Type":"text/plain"}}).catch(()=>{});return}}catch{}try{let f=t.navigator;f&&typeof f.sendBeacon=="function"&&f.sendBeacon(s,new Blob([r],{type:"text/plain"}))}catch{}}function x(r=!1){try{if(w(),p.length===0)return;if(!P()){p=[];return}if(!m)return;U(m);let f=N(t,i),d=f?p.map(k=>({...k,client_id:f})):p;p=[],Je(i,d,r).forEach(k=>Ne(k.body))}catch{}}function oe(r,f,d){if(!P())return;let k=fe(r,f);if(!k.ok){a("dropped",r,k.reason);return}let se=z(t.location.href),K={event_id:d?.event_id&&xe.test(d.event_id)?d.event_id:Ye(),event:r,ts:Date.now(),schema_version:1,env:j,source:u,channel:l,sdk:b,page_id:M,page_type:d?.page_type!==void 0?d.page_type:ee,host:se?.host??null,path:d?.path?ue(d.path.split(/[?#]/)[0]):se?.path??null,referrer_host:Le,utm_source:T?.utm_source??null,utm_medium:T?.utm_medium??null,utm_campaign:T?.utm_campaign??null,utm_content:T?.utm_content??null,utm_term:T?.utm_term??null,ref_code:T?.ref_code??null,product_id:d?.product_id??null,variant_id:d?.variant_id??null,order_ref:d?.order_ref??null,props:k.props};d?.event_id&&!xe.test(d.event_id)&&a("ignored invalid event_id",r),u==="dashboard"&&e.visitorId&&(K.visitor_id=e.visitorId);let ce=pe(K);if(!ce.ok){a("dropped",r,ce.reason);return}let G=K;m?ne(G):E.push(G),p.push(G),p.length>=Ge?x():Be()}let ie=()=>x(!0),ae=()=>{document.visibilityState==="hidden"&&x(!0)},S=()=>re();return t.addEventListener("pagehide",ie),document.addEventListener("visibilitychange",ae),t.addEventListener("bitsnap:consent",S),t.addEventListener("bitsnap:consent:ready",S),W(),U(m),{track(r,f,d){try{oe(r,f,d)}catch{}},page(r,f){try{r!==void 0&&(ee=r),oe("page_view",{landing:Re++===0},f)}catch{}},clientId(r){try{return r!==void 0&&_(r)!==i?null:P()?N(t,i):null}catch{return null}},flush:()=>x(),setEnabled(r){H=!!r,H||(p=[],E=[],w())},configure(r){try{(r.env==="live"||r.env==="test")&&(j=r.env),typeof r.endpoint=="string"&&r.endpoint&&(s=c(r.endpoint))}catch{}},onEvent(r){return C.add(r),()=>void C.delete(r)},destroy(){p=[],E=[],w(),C.clear(),t.removeEventListener("pagehide",ie),document.removeEventListener("visibilitychange",ae),t.removeEventListener("bitsnap:consent",S),t.removeEventListener("bitsnap:consent:ready",S)}}}var v,O=null;function D(e){if(!v){let t=Xe(e);return t===y||(v=t,O=_(e.projectKey??"")),t}try{let t=_(e.projectKey??"");t!==O&&e.debug&&console.warn("[bitsnap analytics]","tracker already started for another projectKey, ignoring",e.projectKey),t===O&&((e.env||e.endpoint)&&v.configure({env:e.env,endpoint:e.endpoint}),e.enabled!=null&&v.setEnabled(e.enabled))}catch{}return v}function Ae(){return v}function xt(){typeof window<"u"&&ge(window),v?.destroy(),v=void 0,O=null}function _t(e){try{if(typeof window>"u")return{};let t=v,n=null;if(t)n=t.clientId(e);else{let o=e?_(e):null;n=o?N(window,o):null}return n?{[me]:n}:{}}catch{return{}}}import{createContext as Ze,createElement as Qe,useContext as et,useMemo as Ie,useRef as tt}from"react";var nt={track:y.track,page:y.page},Pe=Ze(nt);function St({projectKey:e,env:t,enabled:n,endpoint:o,onEvent:a,autoPageViews:i,children:c}){let s=Ie(()=>D({projectKey:e,env:t,endpoint:o,enabled:n}),[e,t,o]),u=tt(a);u.current=a,L(()=>{s.setEnabled(n!==!1)},[s,n]),L(()=>{if(!(i===!1||n===!1||s===y))return A(()=>s.page(null))},[s,i,n]),L(()=>s.onEvent(b=>u.current?.(b)),[s]);let l=Ie(()=>({track:s.track.bind(s),page:s.page.bind(s)}),[s]);return Qe(Pe.Provider,{value:l},c)}function we(){return et(Pe)}import{createContext as rt,createElement as ot,useContext as Ve,useEffect as it,useLayoutEffect as at,useMemo as st,useRef as ct}from"react";var $={track(){}},X=null;function lt(e){let t=Symbol("bitsnap-instrument");function n(){if(typeof window>"u")return null;let{projectKey:i,analytics:c,provided:s}=e();return c===!1?null:s||(i?D({projectKey:i,source:"sdk_react",channel:"embed",env:typeof c=="object"?c.env:void 0}):null)}let o={track(i,c,s){try{let u=n();if(!u)return;let{analytics:l,pageType:b}=e(),M=b&&s?.page_type===void 0?{...s,page_type:b}:s;X=typeof l=="object"&&l.onEvent?t:null,u.track(i,c,M)}catch{}finally{X=null}}};function a(){try{if(!n())return()=>{};let i=Ae();if(!i)return()=>{};let c=e().provided?()=>{}:A(()=>i.page(e().pageType??null)),s=i.onEvent(u=>{if(X===t)try{let{analytics:l}=e();typeof l=="object"&&l.onEvent?.(u)}catch{}});return()=>{c(),s()}}catch{return()=>{}}}return{instrument:o,attach:a}}var Z=rt(null);function Nt({value:e,children:t}){return ot(Z.Provider,{value:e},t)}function Ot(){return Ve(Z)??$}function Dt(e,t,n){let o=Ve(Z),a=we(),i=a.track===y.track?null:a,c=ct({projectKey:e,analytics:t,pageType:n,provided:i});c.current={projectKey:e,analytics:t,pageType:n,provided:i};let s=st(()=>lt(()=>c.current),[]),u=t===void 0&&o!==null,l=typeof t=="object"&&!!t.onEvent;return at(()=>{if(!u)return s.attach()},[s,u,l,e]),u?o:s.instrument}var Q=$;function Se(e){Q=e??$}var q=0;function $t(){return q>0?$:Q}async function Mt(e){q++;try{return await e()}finally{q--}}function jt(e){it(()=>(Se(e),()=>{Q===e&&Se(null)}),[e])}function Ht(e){let t=Number.isFinite(e)?Math.max(0,Math.min(100,e)):0;return t>=100?"100":t>=75?"75-99":t>=50?"50-74":t>=25?"25-49":"0-24"}function Wt(e,t){let n=[];for(let o of[25,50,75,100])e>=o&&!t.has(o)&&(t.add(o),n.push(o));return n}export{ve as a,A as b,Ue as c,Xe as d,D as e,Ae as f,xt as g,_t as h,St as i,we as j,$ as k,Nt as l,Ot as m,Dt as n,$t as o,Mt as p,jt as q,Ht as r,Wt as s};
|
|
2
|
+
//# sourceMappingURL=chunk-RLEC25JI.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/analytics/pageviews.ts","../src/version.ts","../src/analytics/random.ts","../src/analytics/visitor.ts","../src/analytics/core.ts","../src/analytics/react.tsx","../src/analytics/instrument.ts"],"sourcesContent":["/**\n * Page-wide state of the automatic page views. It lives on `window`, so the\n * npm package, a second copy of it and the `analytics.js` script agree on who\n * reports a path and the history is patched once.\n */\ntype Registry = {\n /** Last path some starter reported. */\n path: string | null;\n starters: Set<() => void>;\n watching: boolean;\n};\n\nconst REGISTRY = Symbol.for(\"bitsnap.pageViews\");\n\nfunction registry(win: Window): Registry {\n const holder = win as unknown as Record<symbol, Registry | undefined>;\n return (holder[REGISTRY] ??= { path: null, starters: new Set(), watching: false });\n}\n\n/** Calls `onChange` when the path changes through `history.pushState`/`replaceState` or Back/Forward. */\nfunction watchNavigation(win: Window, onChange: () => void) {\n const check = () => {\n try {\n onChange();\n } catch {}\n };\n for (const name of [\"pushState\", \"replaceState\"] as const) {\n const original = win.history[name];\n win.history[name] = function (this: History, ...args: Parameters<History[typeof name]>) {\n const result = original.apply(this, args);\n check();\n return result;\n };\n }\n win.addEventListener(\"popstate\", check);\n}\n\n/**\n * Calls `send` for the current path and again on every path change, unless\n * another starter on the page already reported that path: the page gets one\n * `page_view` per path change however many providers, components and embeds\n * start it. Returns the function that stops this starter.\n */\nexport function startAutoPageViews(send: () => void, win: Window = window): () => void {\n try {\n const reg = registry(win);\n const starter = () => send();\n if (!reg.watching) {\n reg.watching = true;\n watchNavigation(win, () => {\n const path = win.location.pathname;\n // Nobody listening: leave the path unreported so the next starter sends it.\n if (path === reg.path || reg.starters.size === 0) return;\n reg.path = path;\n reg.starters.values().next().value?.();\n });\n }\n reg.starters.add(starter);\n const path = win.location.pathname;\n if (path !== reg.path) {\n reg.path = path;\n starter();\n }\n return () => void reg.starters.delete(starter);\n } catch {\n return () => {};\n }\n}\n\n/** Forgets the reported path and the starters (tests, hot reload). The history patch stays. */\nexport function resetAutoPageViews(win: Window = window) {\n const reg = registry(win);\n reg.path = null;\n reg.starters.clear();\n}\n","// Generated by scripts/write-version.mjs from package.json. Do not edit.\nexport const SDK_VERSION = \"1.10.0\";\n","export function randomBytes(n: number): Uint8Array {\n const bytes = new Uint8Array(n);\n const c = typeof crypto !== \"undefined\" ? crypto : undefined;\n if (c && typeof c.getRandomValues === \"function\") c.getRandomValues(bytes);\n else for (let i = 0; i < n; i++) bytes[i] = Math.floor(Math.random() * 256);\n return bytes;\n}\n","import { domainCandidates } from \"../consent/core/cookie\";\nimport { clientIdCookieName } from \"./contract\";\nimport { randomBytes } from \"./random\";\n\n/** The part of `window.BitsnapConsent` (`bitsnap-react/consent`) the tracker reads. */\nexport type ConsentLike = {\n /** Absent on a consent script older than 1.9.0, which never counts as the project's banner. */\n scope?: \"global\" | \"project\";\n projectKey?: string | null;\n get(): { c: { analytics?: boolean } } | null;\n /** Also true for a refusal made on an older banner version, which `get()` no longer returns. */\n denied?(category: \"analytics\"): boolean;\n ready?: Promise<unknown>;\n};\n\n/** Sent to the Bitsnap server on the requests that create a checkout or payment link. */\nexport const VISITOR_HEADER = \"X-Bitsnap-Visitor\";\n// 390 days, under the 13 months CNIL allows. Set once, never extended.\nconst MAX_AGE_SECONDS = 390 * 24 * 60 * 60;\nconst VISITOR_ID_RE = /^[A-Za-z0-9_-]{22}$/;\n\nexport function consentApi(win: Window): ConsentLike | undefined {\n return (win as unknown as { BitsnapConsent?: ConsentLike }).BitsnapConsent;\n}\n\nfunction readCookie(doc: Document, name: string): string | null {\n for (const part of doc.cookie.split(\";\")) {\n const index = part.indexOf(\"=\");\n if (index !== -1 && part.slice(0, index).trim() === name) return part.slice(index + 1).trim();\n }\n return null;\n}\n\n/** bitsnap.pl and its subdomains: many merchants share them, and the site-wide choice is bitsnap's own. */\nfunction isBitsnapHost(hostname: string): boolean {\n const host = hostname.toLowerCase();\n return host === \"bitsnap.pl\" || host.endsWith(\".bitsnap.pl\");\n}\n\n/**\n * Whether the page's consent banner speaks for `projectKey`: a project-scope banner of that\n * key, or a site-scope banner on a merchant's own site. On bitsnap.pl a site-scope choice is\n * bitsnap's own, so only a project-scope one counts.\n */\nexport function consentBelongsTo(win: Window, projectKey: string): boolean {\n try {\n const api = consentApi(win);\n if (!api) return false;\n if (api.scope === \"project\") return api.projectKey === projectKey;\n const onBitsnap = isBitsnapHost(win.location.hostname);\n if (api.scope === \"global\") return !onBitsnap;\n // A consent script from before the scope info: it cannot be told apart from another project's banner.\n return false;\n } catch {\n return false;\n }\n}\n\n/** `true` only while a banner that speaks for `projectKey` holds a valid choice that grants `analytics`. */\nexport function analyticsGranted(win: Window, projectKey: string): boolean {\n try {\n return consentApi(win)?.get()?.c.analytics === true && consentBelongsTo(win, projectKey);\n } catch {\n return false;\n }\n}\n\n/** 16 random bytes as 22 base64url characters. */\nexport function newVisitorId(): string {\n let binary = \"\";\n randomBytes(16).forEach((byte) => (binary += String.fromCharCode(byte)));\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\n/** Value of the `bs_vid_<projectKey>` cookie, whatever it holds; `null` when it is absent. */\nfunction rawVisitorCookie(doc: Document, projectKey: string): string | null {\n try {\n return readCookie(doc, clientIdCookieName(projectKey));\n } catch {\n return null;\n }\n}\n\n/** The project's client id from its first-party cookie (`bs_vid_<projectKey>`), or `null` if absent or malformed. */\nexport function readVisitorCookie(doc: Document, projectKey: string): string | null {\n const value = rawVisitorCookie(doc, projectKey);\n return value !== null && VISITOR_ID_RE.test(value) ? value : null;\n}\n\n/**\n * Sets the cookie on the widest registrable domain the browser accepts\n * (shortest suffix with two labels first, so `shop.example.co.uk` skips the\n * refused `co.uk`), host-only where no domain sticks (localhost, IP hosts).\n */\nexport function writeVisitorCookie(win: Window, projectKey: string, id: string): void {\n try {\n const doc = win.document;\n const base =\n `${clientIdCookieName(projectKey)}=${id}; Max-Age=${MAX_AGE_SECONDS}; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n for (const domain of domainCandidates(win.location.hostname).reverse()) {\n doc.cookie = `${base}; Domain=${domain}`;\n if (readVisitorCookie(doc, projectKey) === id) return;\n }\n doc.cookie = base;\n } catch {\n // cookies blocked (sandboxed frame)\n }\n}\n\n/** Expires the cookie on the host and on every parent domain it may have been set on. */\nexport function deleteVisitorCookie(win: Window, projectKey: string): void {\n try {\n const doc = win.document;\n // Present under any value: a malformed one must go too.\n if (rawVisitorCookie(doc, projectKey) === null) return;\n const base =\n `${clientIdCookieName(projectKey)}=; Max-Age=0; Path=/; SameSite=Lax` +\n (win.location.protocol === \"https:\" ? \"; Secure\" : \"\");\n doc.cookie = base;\n for (const domain of domainCandidates(win.location.hostname)) doc.cookie = `${base}; Domain=${domain}`;\n } catch {\n // best effort\n }\n}\n\n/**\n * The project's client id to send, or `null`: analytics consent is granted,\n * Global Privacy Control is off, the browser is not automated and the cookie exists.\n */\nexport function readVisitorId(win: Window, projectKey: string): string | null {\n try {\n const nav = win.navigator as { globalPrivacyControl?: boolean; webdriver?: boolean } | undefined;\n if (nav?.globalPrivacyControl === true || nav?.webdriver === true) return null;\n return analyticsGranted(win, projectKey) ? readVisitorCookie(win.document, projectKey) : null;\n } catch {\n return null;\n }\n}\n","import {\n LIMITS,\n PAGE_TYPES,\n SCHEMA_VERSION,\n normalizeProjectKey,\n parseUrl,\n referrerHost,\n sanitizeProps,\n sanitizePath,\n validateEnvelope,\n type AppEventName,\n type Channel,\n type ClientEvent,\n type Env,\n type EventProps,\n type PageType,\n type Source,\n type StorefrontEventName,\n} from \"./contract\";\nimport { SDK_VERSION } from \"../version\";\nimport { resetAutoPageViews } from \"./pageviews\";\nimport { randomBytes } from \"./random\";\nimport {\n analyticsGranted,\n consentApi,\n consentBelongsTo,\n deleteVisitorCookie,\n newVisitorId,\n readVisitorCookie,\n readVisitorId,\n VISITOR_HEADER,\n writeVisitorCookie,\n type ConsentLike,\n} from \"./visitor\";\n\nexport { startAutoPageViews } from \"./pageviews\";\n\n/** Events a browser may send. `consent_updated` is written by the consent log only. */\nexport type BrowserEventName = Exclude<StorefrontEventName, \"consent_updated\"> | AppEventName;\n\nexport type TrackerOptions = {\n /** Public project key (the hashed project id). `pk_` prefix is accepted. */\n projectKey: string;\n /** Defaults to `live`, or `test` when the page URL has the `?test=` test-mode parameter. */\n env?: Env;\n /** Collector origin. Default `https://collect.bitsnap.pl`. */\n endpoint?: string;\n /** `false` turns tracking off. Default `true`. */\n enabled?: boolean;\n /** Default `embed`. */\n channel?: Channel;\n /** Default `sdk_react`. */\n source?: Source;\n /** Only honoured by the collector for `source: \"dashboard\"` (hashed user id). */\n visitorId?: string;\n /** Receives every valid envelope before it is queued, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /** `console.warn` dropped events. */\n debug?: boolean;\n};\n\n/** Envelope fields a call site may set per event. */\nexport type TrackExtra = {\n page_type?: PageType | null;\n product_id?: string | null;\n variant_id?: string | null;\n order_ref?: string | null;\n /** Route template for pages whose URL path is not the path to report (the dashboard). */\n path?: string;\n /**\n * Deterministic UUIDv7 for events another system reports too (e.g. hosted\n * `payment_returned`), so the collector dedupes them. An invalid value is\n * ignored and a fresh id is used.\n */\n event_id?: string;\n};\n\nexport interface Tracker {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n /**\n * Sends `page_view` and makes `pageType` the page type of the following events\n * (`null` clears it, `undefined` keeps the current one).\n */\n page(pageType?: PageType | null, extra?: TrackExtra): void;\n /**\n * The visitor's `bs_vid_<projectKey>` client id, only while this tracker is on\n * (enabled, no Global Privacy Control, not automated, analytics not denied) and\n * Bitsnap Consent grants analytics. `projectKey` must match the tracker's, if given.\n */\n clientId(projectKey?: string): string | null;\n /** Sends the queue now. */\n flush(): void;\n setEnabled(enabled: boolean): void;\n /** Returns an unsubscribe function. */\n onEvent(fn: (event: ClientEvent) => void): () => void;\n /** Updates `env` and `endpoint` of a running tracker. Other options are fixed at creation. */\n configure(patch: { env?: Env; endpoint?: string }): void;\n /** Removes the page listeners and drops the queue. */\n destroy(): void;\n}\n\nexport const DEFAULT_ENDPOINT = \"https://collect.bitsnap.pl\";\n\nconst FLUSH_INTERVAL_MS = 5000;\nconst FLUSH_AT = 20;\n// Half the collector's 64 KB body limit, measured in UTF-8 bytes of the whole body.\nconst MAX_BODY_BYTES = 32 * 1024;\n// Browsers share ~64 KB of in-flight keepalive requests; stay under it on pagehide.\nconst KEEPALIVE_BUDGET_BYTES = 60 * 1024;\nconst EVENT_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nfunction byteLength(text: string): number {\n if (typeof TextEncoder === \"function\") return new TextEncoder().encode(text).length;\n return unescape(encodeURIComponent(text)).length;\n}\n\nexport const noopTracker: Tracker = {\n track() {},\n page() {},\n clientId: () => null,\n flush() {},\n setEnabled() {},\n onEvent: () => () => {},\n configure() {},\n destroy() {},\n};\n\n/** UUIDv7: 48-bit unix ms, version 7, variant 10, 74 random bits. */\nexport function uuidv7(now = Date.now()): string {\n const b = randomBytes(16);\n let t = now;\n for (let i = 5; i >= 0; i--) {\n b[i] = t % 256;\n t = Math.floor(t / 256);\n }\n b[6] = (b[6] & 0x0f) | 0x70;\n b[8] = (b[8] & 0x3f) | 0x80;\n const hex = Array.from(b, (x) => x.toString(16).padStart(2, \"0\")).join(\"\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\nconst PAGE_ID_ALPHABET = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789\";\n\nfunction newPageId(): string {\n return Array.from(randomBytes(16), (x) => PAGE_ID_ALPHABET[x % PAGE_ID_ALPHABET.length]).join(\"\");\n}\n\nexport function isPageType(value: unknown): value is PageType {\n return typeof value === \"string\" && (PAGE_TYPES as readonly string[]).includes(value);\n}\n\nexport type PackedBody = { body: string; bytes: number; count: number };\n\n/**\n * Splits events into `POST /e` bodies of at most `MAX_BODY_BYTES` UTF-8 bytes\n * (wrapper included) and `maxBatchEvents` events. With `leaving` (pagehide)\n * only the newest bodies that fit the shared keepalive quota are kept.\n */\nexport function packEvents(projectKey: string, events: ClientEvent[], leaving = false): PackedBody[] {\n const wrapper = byteLength(JSON.stringify({ k: projectKey, events: [] }));\n let bodies: PackedBody[] = [];\n let batch: ClientEvent[] = [];\n let size = wrapper;\n const close = () => {\n if (batch.length > 0) bodies.push({ body: JSON.stringify({ k: projectKey, events: batch }), bytes: size, count: batch.length });\n batch = [];\n size = wrapper;\n };\n for (const event of events) {\n const own = byteLength(JSON.stringify(event));\n if (wrapper + own > MAX_BODY_BYTES) continue; // a single event that can never fit\n // +1 for the comma that joins it to the previous event.\n if (batch.length >= LIMITS.maxBatchEvents || size + own + (batch.length > 0 ? 1 : 0) > MAX_BODY_BYTES) close();\n size += own + (batch.length > 0 ? 1 : 0);\n batch.push(event);\n }\n close();\n if (leaving) {\n let total = 0;\n let keep = bodies.length;\n while (keep > 0 && total + bodies[keep - 1].bytes <= KEEPALIVE_BUDGET_BYTES) {\n total += bodies[keep - 1].bytes;\n keep--;\n }\n bodies = bodies.slice(keep);\n }\n return bodies;\n}\n\n/**\n * In-memory event tracker. It never throws into the host page and touches no\n * cookie or Web Storage, except the `bs_vid_<projectKey>` client id cookie, which it keeps\n * only while Bitsnap Consent grants analytics. On the server it returns a no-op.\n */\nexport function createTracker(options: TrackerOptions): Tracker {\n try {\n if (typeof window === \"undefined\" || typeof document === \"undefined\") return noopTracker;\n return build(options, window);\n } catch {\n return noopTracker;\n }\n}\n\nfunction build(options: TrackerOptions, win: Window & typeof globalThis): Tracker {\n const projectKey = normalizeProjectKey(options.projectKey ?? \"\");\n const debug = !!options.debug;\n const warn = (...args: unknown[]) => {\n if (debug) console.warn(\"[bitsnap analytics]\", ...args);\n };\n if (!projectKey) {\n warn(\"invalid projectKey, tracking is off\");\n return noopTracker;\n }\n const key: string = projectKey;\n\n const endpointUrl = (endpoint: string | undefined) => `${(endpoint || DEFAULT_ENDPOINT).replace(/\\/+$/, \"\")}/e`;\n let url = endpointUrl(options.endpoint);\n const source = options.source ?? \"sdk_react\";\n const channel = options.channel ?? \"embed\";\n const sdk = `bitsnap-react@${SDK_VERSION}`;\n const pageId = newPageId();\n const landing = parseUrl(win.location.href);\n let env: Env = options.env ?? \"live\";\n if (!options.env) {\n try {\n if (new URLSearchParams(win.location.search).has(\"test\")) env = \"test\";\n } catch {}\n }\n const refHost = referrerHost(document.referrer);\n\n let enabled = options.enabled !== false;\n let pageType: PageType | null = null;\n let pageViews = 0;\n let queue: ClientEvent[] = [];\n let timer: ReturnType<typeof setTimeout> | null = null;\n const listeners = new Set<(event: ClientEvent) => void>();\n if (options.onEvent) listeners.add(options.onEvent);\n /** Events the listeners have not seen yet because consent was still loading. */\n let held: ClientEvent[] = [];\n\n // -- consent: respect a rejection, wait for the stored choice to load -----\n\n let attached: ConsentLike | undefined;\n let consentReady = true;\n\n function attachConsent() {\n const api = consentApi(win);\n if (!api || api === attached) return;\n attached = api;\n consentReady = !api.ready;\n api.ready?.then(\n () => {\n if (attached !== api) return;\n consentReady = true;\n afterConsentChange();\n },\n () => {\n if (attached === api) consentReady = true;\n },\n );\n }\n\n function consentDenied(): boolean {\n attachConsent();\n try {\n if (!attached) return false;\n const state = attached.get();\n return (!!attached.denied && attached.denied(\"analytics\")) || (!!state && state.c.analytics === false);\n } catch {\n return false;\n }\n }\n\n function notify(event: ClientEvent) {\n listeners.forEach((fn) => {\n try {\n fn(event);\n } catch {}\n });\n }\n\n /**\n * Keeps the `bs_vid_<projectKey>` cookie in line with the consent: set while analytics is granted, deleted once\n * it is not. Before the stored choice has loaded `get()` is empty, so nothing is deleted then.\n * Without Bitsnap Consent on the page the tracker is cookieless.\n */\n function syncVisitorCookie(final: boolean) {\n try {\n attachConsent();\n if (!attached) return;\n // A banner of another project, or bitsnap's own on bitsnap.pl, neither grants nor withdraws this id.\n if (!consentBelongsTo(win, key)) return;\n if (analyticsGranted(win, key)) {\n if (active() && readVisitorCookie(win.document, key) === null) writeVisitorCookie(win, key, newVisitorId());\n } else if (final) {\n deleteVisitorCookie(win, key);\n }\n } catch {}\n }\n\n function afterConsentChange() {\n syncVisitorCookie(true);\n if (consentDenied()) {\n queue = [];\n held = [];\n clearTimer();\n } else {\n if (consentReady && held.length > 0) {\n const release = held;\n held = [];\n release.forEach(notify);\n }\n if (queue.length > 0) flush();\n }\n }\n\n // -- state ----------------------------------------------------------------\n\n function active(): boolean {\n if (!enabled) return false;\n const nav = win.navigator;\n if (nav && ((nav as { globalPrivacyControl?: boolean }).globalPrivacyControl === true || nav.webdriver === true)) {\n return false;\n }\n return !consentDenied();\n }\n\n function clearTimer() {\n if (timer !== null) clearTimeout(timer);\n timer = null;\n }\n\n function schedule() {\n if (timer !== null) return;\n timer = setTimeout(() => {\n timer = null;\n flush();\n }, FLUSH_INTERVAL_MS);\n (timer as { unref?: () => void }).unref?.();\n }\n\n // -- sending --------------------------------------------------------------\n\n function send(body: string) {\n // fetch keepalive first (no size cap below the shared quota); sendBeacon only as a fallback.\n try {\n if (typeof fetch === \"function\") {\n fetch(url, {\n method: \"POST\",\n body,\n keepalive: true,\n credentials: \"omit\",\n headers: { \"Content-Type\": \"text/plain\" },\n }).catch(() => {});\n return;\n }\n } catch {}\n try {\n const nav = win.navigator;\n if (nav && typeof nav.sendBeacon === \"function\") {\n nav.sendBeacon(url, new Blob([body], { type: \"text/plain\" }));\n }\n } catch {}\n }\n\n function flush(leaving = false) {\n try {\n clearTimer();\n if (queue.length === 0) return;\n if (!active()) {\n queue = [];\n return;\n }\n // Hold events until Bitsnap Consent has loaded the stored choice.\n if (!consentReady) return;\n // The client id is added on the way out, so events held for the stored choice carry it too.\n syncVisitorCookie(consentReady);\n const clientId = readVisitorId(win, key);\n const pending = clientId ? queue.map((event) => ({ ...event, client_id: clientId })) : queue;\n queue = [];\n packEvents(key, pending, leaving).forEach((entry) => send(entry.body));\n } catch {}\n }\n\n // -- building -------------------------------------------------------------\n\n function emit(name: string, props: unknown, extra: TrackExtra | undefined) {\n if (!active()) return;\n const cleaned = sanitizeProps(name, props);\n if (!cleaned.ok) {\n warn(\"dropped\", name, cleaned.reason);\n return;\n }\n const here = parseUrl(win.location.href);\n const event: Record<string, unknown> = {\n event_id: extra?.event_id && EVENT_ID_RE.test(extra.event_id) ? extra.event_id : uuidv7(),\n event: name,\n ts: Date.now(),\n schema_version: SCHEMA_VERSION,\n env,\n source,\n channel,\n sdk,\n page_id: pageId,\n page_type: extra?.page_type !== undefined ? extra.page_type : pageType,\n host: here?.host ?? null,\n path: extra?.path ? sanitizePath(extra.path.split(/[?#]/)[0]) : (here?.path ?? null),\n referrer_host: refHost,\n utm_source: landing?.utm_source ?? null,\n utm_medium: landing?.utm_medium ?? null,\n utm_campaign: landing?.utm_campaign ?? null,\n utm_content: landing?.utm_content ?? null,\n utm_term: landing?.utm_term ?? null,\n ref_code: landing?.ref_code ?? null,\n product_id: extra?.product_id ?? null,\n variant_id: extra?.variant_id ?? null,\n order_ref: extra?.order_ref ?? null,\n props: cleaned.props,\n };\n if (extra?.event_id && !EVENT_ID_RE.test(extra.event_id)) warn(\"ignored invalid event_id\", name);\n if (source === \"dashboard\" && options.visitorId) event.visitor_id = options.visitorId;\n\n const verdict = validateEnvelope(event);\n if (!verdict.ok) {\n warn(\"dropped\", name, verdict.reason);\n return;\n }\n const valid = event as unknown as ClientEvent;\n // Listeners (the merchant's own tools) only see events once consent is known and not denied.\n if (consentReady) notify(valid);\n else held.push(valid);\n queue.push(valid);\n if (queue.length >= FLUSH_AT) flush();\n else schedule();\n }\n\n // -- page lifecycle -------------------------------------------------------\n\n const onHide = () => flush(true);\n const onVisibility = () => {\n if (document.visibilityState === \"hidden\") flush(true);\n };\n const onConsent = () => afterConsentChange();\n win.addEventListener(\"pagehide\", onHide);\n document.addEventListener(\"visibilitychange\", onVisibility);\n win.addEventListener(\"bitsnap:consent\", onConsent);\n win.addEventListener(\"bitsnap:consent:ready\", onConsent);\n attachConsent();\n syncVisitorCookie(consentReady);\n\n return {\n track(event, props, extra) {\n try {\n emit(event, props, extra);\n } catch {}\n },\n page(type, extra) {\n try {\n if (type !== undefined) pageType = type;\n emit(\"page_view\", { landing: pageViews++ === 0 }, extra);\n } catch {}\n },\n clientId(projectKey) {\n try {\n if (projectKey !== undefined && normalizeProjectKey(projectKey) !== key) return null;\n return active() ? readVisitorId(win, key) : null;\n } catch {\n return null;\n }\n },\n flush: () => flush(),\n setEnabled(value) {\n enabled = !!value;\n if (!enabled) {\n queue = [];\n held = [];\n clearTimer();\n }\n },\n configure(patch) {\n try {\n if (patch.env === \"live\" || patch.env === \"test\") env = patch.env;\n if (typeof patch.endpoint === \"string\" && patch.endpoint) url = endpointUrl(patch.endpoint);\n } catch {}\n },\n onEvent(fn) {\n listeners.add(fn);\n return () => void listeners.delete(fn);\n },\n destroy() {\n queue = [];\n held = [];\n clearTimer();\n listeners.clear();\n win.removeEventListener(\"pagehide\", onHide);\n document.removeEventListener(\"visibilitychange\", onVisibility);\n win.removeEventListener(\"bitsnap:consent\", onConsent);\n win.removeEventListener(\"bitsnap:consent:ready\", onConsent);\n },\n };\n}\n\n// -- singleton ----------------------------------------------------------------\n\nlet instance: Tracker | undefined;\nlet instanceKey: string | null = null;\n\n/**\n * Creates the page's tracker on the first call and returns that same tracker\n * afterwards. A later call with another `projectKey` is ignored (warns in\n * debug mode); a later call with `env`, `endpoint` or `enabled` updates the\n * running tracker. A malformed key is not remembered, so a later valid call still works.\n */\nexport function initTracker(options: TrackerOptions): Tracker {\n if (!instance) {\n const created = createTracker(options);\n if (created === noopTracker) return created;\n instance = created;\n instanceKey = normalizeProjectKey(options.projectKey ?? \"\");\n return created;\n }\n try {\n const key = normalizeProjectKey(options.projectKey ?? \"\");\n if (key !== instanceKey && options.debug) {\n console.warn(\"[bitsnap analytics]\", \"tracker already started for another projectKey, ignoring\", options.projectKey);\n }\n if (key === instanceKey) {\n if (options.env || options.endpoint) instance.configure({ env: options.env, endpoint: options.endpoint });\n if (options.enabled != null) instance.setEnabled(options.enabled);\n }\n } catch {}\n return instance;\n}\n\n/** The tracker made by `initTracker`, if any. */\nexport function getTracker(): Tracker | undefined {\n return instance;\n}\n\n/** Destroys the singleton so that `initTracker` can build a fresh one (tests, hot reload). */\nexport function resetTracker() {\n if (typeof window !== \"undefined\") resetAutoPageViews(window);\n instance?.destroy();\n instance = undefined;\n instanceKey = null;\n}\n\n/**\n * `X-Bitsnap-Visitor` for a request that creates a checkout or payment link:\n * the client id of `projectKey` (default: the running tracker's project), only\n * while tracking is on and Bitsnap Consent grants analytics. Empty otherwise.\n */\nexport function visitorHeaders(projectKey?: string): Record<string, string> {\n try {\n if (typeof window === \"undefined\") return {};\n const tracker = instance;\n let id: string | null = null;\n if (tracker) {\n id = tracker.clientId(projectKey);\n } else {\n // No tracker of this bundle (e.g. only the analytics.js script runs): read the cookie it set.\n const key = projectKey ? normalizeProjectKey(projectKey) : null;\n id = key ? readVisitorId(window, key) : null;\n }\n return id ? { [VISITOR_HEADER]: id } : {};\n } catch {\n return {};\n }\n}\n","import { createContext, createElement, useContext, useMemo, useRef, type ReactNode } from \"react\";\nimport { useIsomorphicLayoutEffect } from \"../lib/isomorphic-layout-effect\";\nimport { initTracker, noopTracker, startAutoPageViews, type Tracker, type TrackerOptions } from \"./core\";\nimport type { ClientEvent } from \"./contract\";\n\nexport type AnalyticsApi = Pick<Tracker, \"track\" | \"page\">;\n\nconst noop: AnalyticsApi = { track: noopTracker.track, page: noopTracker.page };\n\nconst AnalyticsContext = createContext<AnalyticsApi>(noop);\n\nexport type BitsnapAnalyticsProviderProps = {\n /** Public project key (the `projectID` the rest of the SDK uses). */\n projectKey: string;\n env?: TrackerOptions[\"env\"];\n /** `false` turns tracking off. */\n enabled?: boolean;\n endpoint?: string;\n /** Called with every event before it is sent, e.g. to forward it to the merchant's own tools. */\n onEvent?: (event: ClientEvent) => void;\n /**\n * Sends `page_view` on mount and on every path change (`pushState`, `replaceState`, Back/Forward).\n * Default `true`; set `false` to call `page()` yourself.\n */\n autoPageViews?: boolean;\n children?: ReactNode;\n};\n\n/**\n * Starts the page's tracker and hands `track` and `page` to `useAnalytics()`.\n * The tracker is a per-page singleton: the first valid `projectKey` wins, but\n * `env`, `endpoint` and `enabled` of any provider update the running tracker.\n * It sends a `page_view` for the current page and every path change, once per\n * path however many providers, instrumented components or `analytics.js`\n * embeds the page has.\n * Nothing is tracked on the server. The only thing stored on the visitor's\n * device is the `bs_vid_<projectKey>` cookie, and only while Bitsnap Consent grants analytics.\n */\nexport function BitsnapAnalyticsProvider({\n projectKey,\n env,\n enabled,\n endpoint,\n onEvent,\n autoPageViews,\n children,\n}: BitsnapAnalyticsProviderProps) {\n const tracker = useMemo(\n () => initTracker({ projectKey, env, endpoint, enabled }),\n // The tracker is a per-page singleton; `initTracker` applies env/endpoint/enabled changes.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [projectKey, env, endpoint],\n );\n const onEventRef = useRef(onEvent);\n onEventRef.current = onEvent;\n\n // Before the passive effects of the children, whose first events must already respect it.\n useIsomorphicLayoutEffect(() => {\n tracker.setEnabled(enabled !== false);\n }, [tracker, enabled]);\n\n // Also before the children's events, so the page view comes first. The page type is cleared:\n // an automatic view must not inherit the type of an earlier manual `page(type)`.\n useIsomorphicLayoutEffect(() => {\n if (autoPageViews === false || enabled === false || tracker === noopTracker) return;\n return startAutoPageViews(() => tracker.page(null));\n }, [tracker, autoPageViews, enabled]);\n\n // Layout effects run before the passive effects of the children, whose\n // first events (list viewed, cart opened) would otherwise be missed.\n useIsomorphicLayoutEffect(() => tracker.onEvent((event) => onEventRef.current?.(event)), [tracker]);\n\n const api = useMemo<AnalyticsApi>(\n () => ({ track: tracker.track.bind(tracker), page: tracker.page.bind(tracker) }),\n [tracker],\n );\n return createElement(AnalyticsContext.Provider, { value: api }, children);\n}\n\n/** `track` and `page`; no-ops outside a `<BitsnapAnalyticsProvider>`. */\nexport function useAnalytics(): AnalyticsApi {\n return useContext(AnalyticsContext);\n}\n","import { createContext, createElement, useContext, useEffect, useLayoutEffect, useMemo, useRef, type ReactNode } from \"react\";\nimport type { ClientEvent, Env, EventProps, PageType } from \"./contract\";\nimport { getTracker, initTracker, noopTracker, startAutoPageViews, type BrowserEventName, type TrackExtra } from \"./core\";\nimport { useAnalytics, type AnalyticsApi } from \"./react\";\n\n/**\n * The `analytics` prop of every instrumented bitsnap-react component.\n * `true` (the default) tracks, `false` opts out, an object tracks and can\n * forward each event to the merchant's own tools.\n */\nexport type AnalyticsOption =\n | boolean\n | {\n /** Called with every event this component emits, after Bitsnap Consent allows analytics. */\n onEvent?: (event: ClientEvent) => void;\n /** `test` events are stored but never reach the merchant's stats. */\n env?: Env;\n };\n\n/** What the components call. It never throws and does nothing on the server. */\nexport interface Instrument {\n track<E extends BrowserEventName>(event: E, props: EventProps<E>, extra?: TrackExtra): void;\n}\n\nexport const noopInstrument: Instrument = { track() {} };\n\ntype Latest = {\n projectKey: string | null | undefined;\n analytics: AnalyticsOption | undefined;\n pageType: PageType | undefined;\n provided: AnalyticsApi | null;\n};\n\n/** The instrument whose `track` call is running; lets `onEvent` listeners tell their own events apart. */\nlet emitting: symbol | null = null;\n\nfunction createInstrument(read: () => Latest) {\n const id = Symbol(\"bitsnap-instrument\");\n\n function target(): Pick<AnalyticsApi, \"track\"> | null {\n if (typeof window === \"undefined\") return null;\n const { projectKey, analytics, provided } = read();\n if (analytics === false) return null;\n // A <BitsnapAnalyticsProvider> owns the tracker.\n if (provided) return provided;\n if (!projectKey) return null;\n return initTracker({\n projectKey,\n source: \"sdk_react\",\n channel: \"embed\",\n env: typeof analytics === \"object\" ? analytics.env : undefined,\n });\n }\n\n const instrument: Instrument = {\n track(event, props, extra) {\n try {\n const tracker = target();\n if (!tracker) return;\n const { analytics, pageType } = read();\n const withPage = pageType && extra?.page_type === undefined ? { ...extra, page_type: pageType } : extra;\n emitting = typeof analytics === \"object\" && analytics.onEvent ? id : null;\n tracker.track(event, props, withPage);\n } catch {\n // Analytics never breaks the host page.\n } finally {\n emitting = null;\n }\n },\n };\n\n /** Starts the tracker on mount, wires `onEvent` and, without a provider, the automatic page views. Returns the cleanup. */\n function attach(): () => void {\n try {\n if (!target()) return () => {};\n const tracker = getTracker();\n if (!tracker) return () => {};\n // A <BitsnapAnalyticsProvider> decides on the page views itself (`autoPageViews`).\n const stopPageViews = read().provided ? () => {} : startAutoPageViews(() => tracker.page(read().pageType ?? null));\n const stopListening = tracker.onEvent((event) => {\n if (emitting !== id) return;\n try {\n const { analytics } = read();\n if (typeof analytics === \"object\") analytics.onEvent?.(event);\n } catch {}\n });\n return () => {\n stopPageViews();\n stopListening();\n };\n } catch {\n return () => {};\n }\n }\n\n return { instrument, attach };\n}\n\nconst InstrumentContext = createContext<Instrument | null>(null);\n\n/** Hands the instrument of a top-level component to the parts below it. */\nexport function InstrumentProvider({ value, children }: { value: Instrument; children?: ReactNode }) {\n return createElement(InstrumentContext.Provider, { value }, children);\n}\n\n/** The instrument of the closest instrumented ancestor, or a no-op. */\nexport function useInstrumentContext(): Instrument {\n return useContext(InstrumentContext) ?? noopInstrument;\n}\n\n/**\n * The instrument of a top-level component. `projectKey` is the public\n * project id the component already has. When `analytics` is not given and an\n * ancestor is instrumented, the ancestor's instrument is reused.\n */\nexport function useInstrument(\n projectKey: string | null | undefined,\n analytics?: AnalyticsOption,\n pageType?: PageType,\n): Instrument {\n const parent = useContext(InstrumentContext);\n const api = useAnalytics();\n const provided = api.track === noopTracker.track ? null : api;\n const latest = useRef<Latest>({ projectKey, analytics, pageType, provided });\n latest.current = { projectKey, analytics, pageType, provided };\n\n const own = useMemo(() => createInstrument(() => latest.current), []);\n const inherit = analytics === undefined && parent !== null;\n const hasListener = typeof analytics === \"object\" && !!analytics.onEvent;\n\n // A layout effect runs before the passive effects of the children, whose\n // first events (list viewed, cart opened) `onEvent` must not miss.\n useLayoutEffect(() => {\n if (inherit) return;\n return own.attach();\n }, [own, inherit, hasListener, projectKey]);\n\n return inherit ? parent : own.instrument;\n}\n\n// -- cart sink ---------------------------------------------------------------\n\nlet cartInstrument: Instrument = noopInstrument;\n\n/**\n * The instrument used for cart changes made outside of a component (the\n * `Bitsnap.addProductToCart` helper). `<BitsnapCheckout>` registers its own.\n */\nexport function setCartInstrument(instrument: Instrument | null) {\n cartInstrument = instrument ?? noopInstrument;\n}\n\nlet cartMuted = 0;\n\nexport function getCartInstrument(): Instrument {\n return cartMuted > 0 ? noopInstrument : cartInstrument;\n}\n\n/**\n * Runs `fn` with the cart sink muted, so a cart change made inside it (a custom\n * `onAddToCart` calling `Bitsnap.addProductToCart`) is not reported a second\n * time by the caller that reports it itself. Await the cart call inside `fn`.\n */\nexport async function withCartAnalyticsMuted<T>(fn: () => T | Promise<T>): Promise<T> {\n cartMuted++;\n try {\n return await fn();\n } finally {\n cartMuted--;\n }\n}\n\n/** Registers the instrument as the cart sink while the calling component is mounted. */\nexport function useCartInstrument(instrument: Instrument) {\n useEffect(() => {\n setCartInstrument(instrument);\n return () => {\n if (cartInstrument === instrument) setCartInstrument(null);\n };\n }, [instrument]);\n}\n\n// -- shared helpers ----------------------------------------------------------\n\n/** Score (0..100) → the contract's bucket. */\nexport function scoreBucket(percent: number): \"0-24\" | \"25-49\" | \"50-74\" | \"75-99\" | \"100\" {\n const value = Number.isFinite(percent) ? Math.max(0, Math.min(100, percent)) : 0;\n if (value >= 100) return \"100\";\n if (value >= 75) return \"75-99\";\n if (value >= 50) return \"50-74\";\n if (value >= 25) return \"25-49\";\n return \"0-24\";\n}\n\n/** Milestones (25/50/75/100) reached by `percent` that are not in `seen` yet. Adds them to `seen`. */\nexport function newMilestones(percent: number, seen: Set<number>): number[] {\n const reached: number[] = [];\n for (const milestone of [25, 50, 75, 100]) {\n if (percent >= milestone && !seen.has(milestone)) {\n seen.add(milestone);\n reached.push(milestone);\n }\n }\n return reached;\n}\n"],"mappings":"6GAYA,IAAMA,GAAW,OAAO,IAAI,mBAAmB,EAE/C,SAASC,GAASC,EAAuB,CACvC,IAAMC,EAASD,EACf,OAAQC,EAAOH,EAAQ,IAAM,CAAE,KAAM,KAAM,SAAU,IAAI,IAAO,SAAU,EAAM,CAClF,CAGA,SAASI,GAAgBF,EAAaG,EAAsB,CAC1D,IAAMC,EAAQ,IAAM,CAClB,GAAI,CACFD,EAAS,CACX,MAAQ,CAAC,CACX,EACA,QAAWE,IAAQ,CAAC,YAAa,cAAc,EAAY,CACzD,IAAMC,EAAWN,EAAI,QAAQK,CAAI,EACjCL,EAAI,QAAQK,CAAI,EAAI,YAA4BE,EAAwC,CACtF,IAAMC,EAASF,EAAS,MAAM,KAAMC,CAAI,EACxC,OAAAH,EAAM,EACCI,CACT,CACF,CACAR,EAAI,iBAAiB,WAAYI,CAAK,CACxC,CAQO,SAASK,EAAmBC,EAAkBV,EAAc,OAAoB,CACrF,GAAI,CACF,IAAMW,E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,CAACF,EAAK,IAAIE,CAAS,IAC7CF,EAAK,IAAIE,CAAS,EAClBD,EAAQ,KAAKC,CAAS,GAG1B,OAAOD,CACT","names":["REGISTRY","registry","win","holder","watchNavigation","onChange","check","name","original","args","result","startAutoPageViews","send","reg","starter","path","resetAutoPageViews","SDK_VERSION","randomBytes","n","bytes","c","i","VISITOR_HEADER","MAX_AGE_SECONDS","VISITOR_ID_RE","consentApi","win","readCookie","doc","name","part","index","isBitsnapHost","hostname","host","consentBelongsTo","projectKey","api","onBitsnap","analyticsGranted","newVisitorId","binary","randomBytes","byte","rawVisitorCookie","clientIdCookieName","readVisitorCookie","value","writeVisitorCookie","id","base","domain","domainCandidates","deleteVisitorCookie","readVisitorId","nav","DEFAULT_ENDPOINT","FLUSH_INTERVAL_MS","FLUSH_AT","MAX_BODY_BYTES","KEEPALIVE_BUDGET_BYTES","EVENT_ID_RE","byteLength","text","noopTracker","uuidv7","now","b","randomBytes","t","i","hex","x","PAGE_ID_ALPHABET","newPageId","packEvents","projectKey","events","leaving","wrapper","byteLength","bodies","batch","size","close","event","own","MAX_BODY_BYTES","LIMITS","total","keep","KEEPALIVE_BUDGET_BYTES","createTracker","options","noopTracker","build","win","normalizeProjectKey","debug","warn","args","key","endpointUrl","endpoint","DEFAULT_ENDPOINT","url","source","channel","sdk","SDK_VERSION","pageId","newPageId","landing","parseUrl","env","refHost","referrerHost","enabled","pageType","pageViews","queue","timer","listeners","held","attached","consentReady","attachConsent","api","consentApi","afterConsentChange","consentDenied","state","notify","fn","syncVisitorCookie","final","consentBelongsTo","analyticsGranted","active","readVisitorCookie","writeVisitorCookie","newVisitorId","deleteVisitorCookie","clearTimer","release","flush","nav","schedule","FLUSH_INTERVAL_MS","send","body","clientId","readVisitorId","pending","entry","emit","name","props","extra","cleaned","sanitizeProps","here","EVENT_ID_RE","uuidv7","sanitizePath","verdict","validateEnvelope","valid","FLUSH_AT","onHide","onVisibility","onConsent","type","value","patch","instance","instanceKey","initTracker","created","getTracker","resetTracker","resetAutoPageViews","visitorHeaders","tracker","id","VISITOR_HEADER","createContext","createElement","useContext","useMemo","useRef","noop","noopTracker","AnalyticsContext","createContext","BitsnapAnalyticsProvider","projectKey","env","enabled","endpoint","onEvent","autoPageViews","children","tracker","useMemo","initTracker","onEventRef","useRef","useIsomorphicLayoutEffect","startAutoPageViews","event","api","createElement","useAnalytics","useContext","createContext","createElement","useContext","useEffect","useLayoutEffect","useMemo","useRef","noopInstrument","emitting","createInstrument","read","id","target","projectKey","analytics","provided","initTracker","instrument","event","props","extra","tracker","pageType","withPage","attach","getTracker","stopPageViews","startAutoPageViews","stopListening","InstrumentContext","createContext","InstrumentProvider","value","children","createElement","useInstrumentContext","useContext","useInstrument","parent","api","useAnalytics","noopTracker","latest","useRef","own","useMemo","inherit","hasListener","useLayoutEffect","cartInstrument","setCartInstrument","cartMuted","getCartInstrument","withCartAnalyticsMuted","fn","useCartInstrument","useEffect","scoreBucket","percent","newMilestones","seen","reached","milestone"]}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } 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 _chunkKOYBZORLjs = require('./chunk-KOYBZORL.js');var _chunkAJNULBC3js = require('./chunk-AJNULBC3.js');var _chunkVIII45ACjs = require('./chunk-VIII45AC.js');var _chunkB32ACCW2js = require('./chunk-B32ACCW2.js');var vr=["root","header","title","description","backButton","stepIndicator","error","emptyState","skeleton","emailForm","emailInput","codeForm","codeInput","resendButton","logoutButton","orderList","orderCard","orderReference","orderDate","orderTotal","pagination","lineList","line","lineName","linePrice","lineQuantityControl","quantityButton","quantityInput","lineIneligibleReason","noteInput","summary","submitButton","secondaryButton","successState","returnReference","returnInstructions","returnList","returnCard","statusBadge","history","historyEntry"],zt={fontFamily:"--bitsnap-returns-font-family",fontSize:"--bitsnap-returns-font-size",background:"--bitsnap-returns-background",surface:"--bitsnap-returns-surface",foreground:"--bitsnap-returns-foreground",mutedForeground:"--bitsnap-returns-muted-foreground",border:"--bitsnap-returns-border",buttonBackground:"--bitsnap-returns-button-background",buttonForeground:"--bitsnap-returns-button-foreground",buttonHoverBackground:"--bitsnap-returns-button-hover-background",hoverSurface:"--bitsnap-returns-hover-surface",focusRing:"--bitsnap-returns-focus-ring",error:"--bitsnap-returns-error",success:"--bitsnap-returns-success",warning:"--bitsnap-returns-warning",badgeBackground:"--bitsnap-returns-badge-background",badgeForeground:"--bitsnap-returns-badge-foreground",inputBackground:"--bitsnap-returns-input-background",radius:"--bitsnap-returns-radius"},Dt={light:{background:"#ffffff",surface:"#f9fafb",foreground:"#18181b",mutedForeground:"#71717a",border:"#e4e4e7",buttonBackground:"#18181b",buttonForeground:"#fafafa",buttonHoverBackground:"#000000",hoverSurface:"#f4f4f5",focusRing:"#71717a",error:"#dc2626",success:"#16a34a",warning:"#d97706",badgeBackground:"#f4f4f5",badgeForeground:"#3f3f46",inputBackground:"#ffffff",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",success:"#4ade80",warning:"#fbbf24",badgeBackground:"#3f3f46",badgeForeground:"#e4e4e7",inputBackground:"#27272a",radius:"8px"}},Ot=[{token:"background",variable:"--background"},{token:"foreground",variable:"--foreground"},{token:"surface",variable:"--card"},{token:"foreground",variable:"--card-foreground"},{token:"surface",variable:"--popover"},{token:"foreground",variable:"--popover-foreground"},{token:"buttonBackground",variable:"--primary"},{token:"buttonForeground",variable:"--primary-foreground"},{token:"surface",variable:"--secondary"},{token:"foreground",variable:"--secondary-foreground"},{token:"hoverSurface",variable:"--accent"},{token:"foreground",variable:"--accent-foreground"},{token:"mutedForeground",variable:"--muted-foreground"},{token:"border",variable:"--border"},{token:"border",variable:"--input"},{token:"focusRing",variable:"--ring"},{token:"error",variable:"--destructive"},{token:"radius",variable:"--radius"}];function ve(e){let r=_chunkKOYBZORLjs.a.call(void 0, e,{defaultTheme:"light",presets:Dt,variables:zt,shadcnVariables:Ot});return{theme:r.theme,tokens:r.tokens,elements:r.elements,boundaryClassName:r.theme,boundaryStyle:r.boundaryStyle}}function tt(e,r){return _chunkKOYBZORLjs.b.call(void 0, e.elements,r)}var _react = require('react');var _jsxruntime = require('react/jsx-runtime');var rt=_react.createContext.call(void 0, ve());function nt({appearance:e,children:r}){let t=_react.useMemo.call(void 0, ()=>ve(e),[e]);return _jsxruntime.jsx.call(void 0, rt.Provider,{value:t,children:r})}function Ne(){return _react.useContext.call(void 0, rt)}function l(e){let r=Ne();return _nullishCoalesce(tt(r,e), () => ({}))}function ot(e){return e==="test"||e===1?1:0}var st={title:["emailStepTitle"],email:["emailLabel"],sendCode:["emailSubmit"],code:["codeLabel"],verify:["codeSubmit"],orders:["ordersTitle"],submit:["confirmationSubmit"],note:["noteLabel"],history:["myReturnsTitle","myReturnsLink"]};function at(e){if(e==null)return;let r={};for(let[t,n]of Object.entries(st)){let o=e[t];if(typeof o=="string")for(let u of n)r[u]=o}for(let t of Object.keys(e)){if(t in st)continue;let n=e[t];typeof n=="string"&&(r[t]=n)}return r}function it(e,r){let t=_optionalChain([r, 'optionalAccess', _2 => _2.brandColor, 'optionalAccess', _3 => _3.trim, 'call', _4 => _4()]);return t==null||t===""?e:{...e,tokens:{..._chunkAJNULBC3js.t.call(void 0, t),..._optionalChain([e, 'optionalAccess', _5 => _5.tokens])}}}function he(e,r){return typeof e=="object"&&e!=null?{pageSize:_nullishCoalesce(e.pageSize, () => (20)),explicitPageToken:void 0}:typeof e=="number"||r!==void 0?{pageSize:_nullishCoalesce(e, () => (20)),explicitPageToken:_nullishCoalesce(r, () => (""))}:{pageSize:20,explicitPageToken:void 0}}var _t={en:{back:"Back",stepIndicator:"Step {current} of {total}",loading:"Loading",myReturnsLink:"My returns",emailStepTitle:"Return a product",emailStepDescription:"Enter the email address you used for the order. We will send you a verification code.",emailLabel:"Email address",emailPlaceholder:"name@example.com",emailSubmit:"Send code",codeStepTitle:"Enter the code",codeStepDescription:"We sent a verification code to {email}.",codeLabel:"Verification code",codeSubmit:"Verify",resend:"Send the code again",resendIn:"Send again in {seconds} s",logout:"Sign out",ordersTitle:"Your orders",ordersDescription:"Choose the order that contains the product to return.",ordersEmpty:"There are no orders eligible for return.",orderTitle:"Order {reference}",orderReturnableLines:"Products available to return: {count}",orderSelect:"Choose",paginationPrevious:"Previous",paginationNext:"Next",paginationInfo:"Page {page}, {total} orders",orderDetailTitle:"Order {reference}",orderDetailDescription:"Select the products and quantities to return.",quantityLabel:"Quantity to return: {name}",quantityDecrease:"Decrease quantity: {name}",quantityIncrease:"Increase quantity: {name}",quantityOfAvailable:"of {available}",lineIneligibleFallback:"This product cannot be returned.",noteLabel:"Note (optional)",notePlaceholder:"Tell us why you are returning the product",selectionContinue:"Continue",selectionEmpty:"Select at least one item to return.",previousReturnsTitle:"Earlier returns for this order",confirmationTitle:"Confirm the return",confirmationDescription:"Check the products before you submit the request.",confirmationSummary:"Products to return",confirmationQuantity:"Quantity: {quantity}",confirmationNote:"Your note",confirmationSubmit:"Submit return request",successTitle:"Return request submitted",successDescription:"We received your request and will keep you posted.",successReference:"Request number",successInstructions:"What to do next",successDone:"Back to orders",myReturnsTitle:"My returns",myReturnsDescription:"Track the status of your return requests.",myReturnsEmpty:"You have not submitted any return requests yet.",myReturnOpen:"Details",myReturnDetailTitle:"Return details",myReturnTitle:"Return {reference}",myReturnCreatedAt:"Submitted",myReturnRefund:"Refund",myReturnLines:"Products",myReturnLineQuantities:"Requested: {requested}, approved: {approved}, received: {received}",myReturnNote:"Your note",myReturnHistory:"History",statusSubmitted:"Submitted",statusApproved:"Approved",statusRejected:"Rejected",statusAwaitingReceipt:"Awaiting the package",statusReceived:"Package received",statusCompleted:"Completed",statusCancelled:"Cancelled",statusRefunded:"Refunded",statusFallback:"In progress",refundStatusNotStarted:"Not started",refundStatusPending:"Refund in progress",refundStatusSucceeded:"Refunded",refundStatusFailed:"Refund failed",refundStatusFallback:"Unknown",errorGeneric:"Something went wrong. Please try again.",errorInvalidEmail:"Enter a valid email address.",errorInvalidCode:"The code is invalid or has expired.",errorSessionExpired:"Your session has expired. Verify your email again.",errorOrderNotFound:"We could not find this order.",errorReturnNotFound:"We could not find this return request.",errorQuantityUnavailable:"The selected quantity is no longer available for return.",errorItemNotReturnable:"One of the selected products cannot be returned.",errorReturnsDisabled:"Returns are not available in this shop.",errorRateLimited:"Too many attempts. Please try again later.",errorIdempotencyConflict:"This request was already submitted with different contents. Reload and try again.",errorDeliveryFailed:"We could not send the code. Please try again.",errorRetry:"Try again"},pl:{back:"Wstecz",stepIndicator:"Krok {current} z {total}",loading:"\u0141adowanie",myReturnsLink:"Moje zwroty",emailStepTitle:"Zwr\xF3\u0107 produkt",emailStepDescription:"Podaj adres e-mail u\u017Cyty w zam\xF3wieniu. Wy\u015Blemy na niego kod weryfikacyjny.",emailLabel:"Adres e-mail",emailPlaceholder:"jan@example.com",emailSubmit:"Wy\u015Blij kod",codeStepTitle:"Wpisz kod",codeStepDescription:"Wys\u0142ali\u015Bmy kod weryfikacyjny na adres {email}.",codeLabel:"Kod weryfikacyjny",codeSubmit:"Zweryfikuj",resend:"Wy\u015Blij kod ponownie",resendIn:"Wy\u015Blij ponownie za {seconds} s",logout:"Wyloguj si\u0119",ordersTitle:"Twoje zam\xF3wienia",ordersDescription:"Wybierz zam\xF3wienie z produktem do zwrotu.",ordersEmpty:"Brak zam\xF3wie\u0144, kt\xF3re mo\u017Cna zwr\xF3ci\u0107.",orderTitle:"Zam\xF3wienie {reference}",orderReturnableLines:"Produkty do zwrotu: {count}",orderSelect:"Wybierz",paginationPrevious:"Poprzednia",paginationNext:"Nast\u0119pna",paginationInfo:"Strona {page}, zam\xF3wie\u0144: {total}",orderDetailTitle:"Zam\xF3wienie {reference}",orderDetailDescription:"Wybierz produkty i ilo\u015Bci do zwrotu.",quantityLabel:"Ilo\u015B\u0107 do zwrotu: {name}",quantityDecrease:"Zmniejsz ilo\u015B\u0107: {name}",quantityIncrease:"Zwi\u0119ksz ilo\u015B\u0107: {name}",quantityOfAvailable:"z {available}",lineIneligibleFallback:"Ten produkt nie podlega zwrotowi.",noteLabel:"Uwagi (opcjonalnie)",notePlaceholder:"Napisz, dlaczego zwracasz produkt",selectionContinue:"Dalej",selectionEmpty:"Wybierz co najmniej jedn\u0105 sztuk\u0119 do zwrotu.",previousReturnsTitle:"Wcze\u015Bniejsze zwroty tego zam\xF3wienia",confirmationTitle:"Potwierd\u017A zwrot",confirmationDescription:"Sprawd\u017A produkty przed wys\u0142aniem zg\u0142oszenia.",confirmationSummary:"Produkty do zwrotu",confirmationQuantity:"Ilo\u015B\u0107: {quantity}",confirmationNote:"Twoje uwagi",confirmationSubmit:"Wy\u015Blij zg\u0142oszenie zwrotu",successTitle:"Zg\u0142oszenie zwrotu zosta\u0142o wys\u0142ane",successDescription:"Otrzymali\u015Bmy zg\u0142oszenie i b\u0119dziemy informowa\u0107 o jego statusie.",successReference:"Numer zg\u0142oszenia",successInstructions:"Co dalej",successDone:"Wr\xF3\u0107 do zam\xF3wie\u0144",myReturnsTitle:"Moje zwroty",myReturnsDescription:"Sprawd\u017A status swoich zg\u0142osze\u0144 zwrotu.",myReturnsEmpty:"Nie masz jeszcze \u017Cadnych zg\u0142osze\u0144 zwrotu.",myReturnOpen:"Szczeg\xF3\u0142y",myReturnDetailTitle:"Szczeg\xF3\u0142y zwrotu",myReturnTitle:"Zwrot {reference}",myReturnCreatedAt:"Zg\u0142oszono",myReturnRefund:"Zwrot \u015Brodk\xF3w",myReturnLines:"Produkty",myReturnLineQuantities:"Zg\u0142oszono: {requested}, zaakceptowano: {approved}, odebrano: {received}",myReturnNote:"Twoje uwagi",myReturnHistory:"Historia",statusSubmitted:"Zg\u0142oszony",statusApproved:"Zaakceptowany",statusRejected:"Odrzucony",statusAwaitingReceipt:"Oczekiwanie na paczk\u0119",statusReceived:"Paczka odebrana",statusCompleted:"Zako\u0144czony",statusCancelled:"Anulowany",statusRefunded:"\u015Arodki zwr\xF3cone",statusFallback:"W trakcie",refundStatusNotStarted:"Nie rozpocz\u0119to",refundStatusPending:"Zwrot \u015Brodk\xF3w w toku",refundStatusSucceeded:"\u015Arodki zwr\xF3cone",refundStatusFailed:"Zwrot \u015Brodk\xF3w nie powi\xF3d\u0142 si\u0119",refundStatusFallback:"Nieznany",errorGeneric:"Co\u015B posz\u0142o nie tak. Spr\xF3buj ponownie.",errorInvalidEmail:"Podaj poprawny adres e-mail.",errorInvalidCode:"Kod jest nieprawid\u0142owy lub wygas\u0142.",errorSessionExpired:"Sesja wygas\u0142a. Zweryfikuj adres e-mail ponownie.",errorOrderNotFound:"Nie znaleziono tego zam\xF3wienia.",errorReturnNotFound:"Nie znaleziono tego zg\u0142oszenia zwrotu.",errorQuantityUnavailable:"Wybrana ilo\u015B\u0107 nie jest ju\u017C dost\u0119pna do zwrotu.",errorItemNotReturnable:"Jeden z wybranych produkt\xF3w nie podlega zwrotowi.",errorReturnsDisabled:"Zwroty nie s\u0105 dost\u0119pne w tym sklepie.",errorRateLimited:"Zbyt wiele pr\xF3b. Spr\xF3buj ponownie p\xF3\u017Aniej.",errorIdempotencyConflict:"To zg\u0142oszenie zosta\u0142o ju\u017C wys\u0142ane z inn\u0105 zawarto\u015Bci\u0105. Od\u015Bwie\u017C stron\u0119 i spr\xF3buj ponownie.",errorDeliveryFailed:"Nie uda\u0142o si\u0119 wys\u0142a\u0107 kodu. Spr\xF3buj ponownie.",errorRetry:"Spr\xF3buj ponownie"}};function ke(e,r){return _chunkVIII45ACjs.i.call(void 0, _t,e,r)}function ut(e,r){return e.replace(/\{(\w+)\}/g,(t,n)=>Object.prototype.hasOwnProperty.call(r,n)?String(r[n]):t)}var jt={submitted:"statusSubmitted",approved:"statusApproved",rejected:"statusRejected",awaiting_receipt:"statusAwaitingReceipt",received:"statusReceived",completed:"statusCompleted",cancelled:"statusCancelled",refunded:"statusRefunded"},Ut={not_started:"refundStatusNotStarted",pending:"refundStatusPending",succeeded:"refundStatusSucceeded",failed:"refundStatusFailed"};function lt(e){return _nullishCoalesce(jt[e], () => ("statusFallback"))}function ct(e){return _nullishCoalesce(Ut[e], () => ("refundStatusFallback"))}var Te=_react.createContext.call(void 0, {locale:"pl-PL",texts:ke("pl-PL")});function pt({texts:e,locale:r,children:t}){let n=_nullishCoalesce(r, () => (_chunkVIII45ACjs.m.call(void 0, ))),o=_react.useMemo.call(void 0, ()=>({locale:n,texts:ke(n,e)}),[n,e]);return _jsxruntime.jsx.call(void 0, Te.Provider,{value:o,children:t})}function h(){let{texts:e}=_react.useContext.call(void 0, Te);return _react.useCallback.call(void 0, (r,t)=>t==null?e[r]:ut(e[r],t),[e])}function Y(){return _react.useContext.call(void 0, Te).locale}var _connect = require('@connectrpc/connect');var _connectquery = require('@connectrpc/connect-query');var _reactquery = require('@tanstack/react-query');var _wkt = require('@bufbuild/protobuf/wkt');var Zt="bitsnap-returns-session:";function we(e){return`${Zt}${e}`}function oe(){try{return typeof window<"u"?window.sessionStorage:void 0}catch (e2){return}}function mt(e,r,t=Date.now()){if(e==null)return;let n=we(r);try{let o=e.getItem(n);if(o==null)return;let u=JSON.parse(o);if(u!=null&&typeof u=="object"&&typeof u.token=="string"&&u.token.length>0&&typeof u.expiresAt=="number"&&u.expiresAt>t){let{token:s,expiresAt:a}=u;return{token:s,expiresAt:a}}e.removeItem(n)}catch (e3){try{e.removeItem(n)}catch (e4){}}}function yt(e,r,t){try{_optionalChain([e, 'optionalAccess', _6 => _6.setItem, 'call', _7 => _7(we(r),JSON.stringify(t))])}catch (e5){}}function Ie(e,r){try{_optionalChain([e, 'optionalAccess', _8 => _8.removeItem, 'call', _9 => _9(we(r))])}catch (e6){}}function ae(e){return e==null?void 0:_wkt.timestampMs.call(void 0, e)}var Rt=_react.createContext.call(void 0, void 0);function T(e){let r=_react.useContext.call(void 0, Rt);if(r==null)throw new Error(`${e} must be rendered inside <ReturnsProvider>`);return r}function Ce(){return _connectquery.createConnectQueryKey.call(void 0, {schema:_chunkAJNULBC3js.i,cardinality:void 0})}var or=2**31-1;function ar({projectID:e,environment:r,transport:t,panelAccessToken:n,className:o,children:u}){let s=_reactquery.useQueryClient.call(void 0, ),{boundaryClassName:a,boundaryStyle:y}=Ne(),m=l("root"),[p,f]=_react.useState.call(void 0, {status:"hydrating"}),[c,b]=_react.useState.call(void 0, ),[g,C]=_react.useState.call(void 0, ),I=_react.useRef.call(void 0, void 0),N=_react.useCallback.call(void 0, ()=>{s.removeQueries({queryKey:Ce()})},[s]),B=_react.useCallback.call(void 0, ()=>{Ie(oe(),e),C(void 0),f({status:"anonymous"}),N()},[e,N]),w=_react.useCallback.call(void 0, k=>{yt(oe(),e,k),b(void 0),C(void 0),f({status:"authenticated",token:k.token,expiresAt:k.expiresAt})},[e]);_react.useEffect.call(void 0, ()=>{let k=!1,Q=oe();if(n==null||n===""){let O=I.current!=null;if(I.current=void 0,O){B();return}let q=mt(Q,e);f(q!=null?{status:"authenticated",token:q.token,expiresAt:q.expiresAt}:{status:"anonymous"});return}return I.current=n,Ie(Q,e),N(),b(void 0),f({status:"exchanging"}),_connect.createClient.call(void 0, _chunkAJNULBC3js.i,t).exchangePanelSession({projectId:e,accessToken:n,environment:r}).then(O=>{if(k)return;let q=ae(O.expiresAt);if(O.sessionToken===""||q==null)throw new Error("EMPTY_SESSION");w({token:O.sessionToken,expiresAt:q})}).catch(O=>{k||(b(O),f({status:"anonymous"}))}),()=>{k=!0}},[n,e,r,t]),_react.useEffect.call(void 0, ()=>{if(p.status!=="authenticated"||p.expiresAt==null)return;let k=p.expiresAt-Date.now();if(k<=0){B();return}let Q=setTimeout(B,Math.min(k,or));return()=>clearTimeout(Q)},[p.status,p.expiresAt,B]);let P=_react.useMemo.call(void 0, ()=>({projectID:e,environment:r,status:p.status,token:p.token,exchangeError:c,challenge:g,setChallenge:C,authenticate:w,clearSession:B}),[e,r,p.status,p.token,c,g,w,B]);return _jsxruntime.jsx.call(void 0, Rt.Provider,{value:P,children:_jsxruntime.jsx.call(void 0, "div",{"data-bitsnap-returns":"root","data-bitsnap-returns-slot":"root",className:_chunkVIII45ACjs.d.call(void 0, "bitsnap-react",a,o,m.className),style:{...y,...m.style},children:u})})}function ir({projectID:e,host:r,environment:t,appearance:n,texts:o,theme:u,locale:s,panelAccessToken:a,className:y,analytics:m,children:p}){let f=_chunkB32ACCW2js.n.call(void 0, e,m,"returns"),c=_react.useContext.call(void 0, _reactquery.QueryClientContext),[b]=_react.useState.call(void 0, ()=>c==null?new (0, _reactquery.QueryClient)({defaultOptions:{queries:{staleTime:5e3}}}):void 0),g=_nullishCoalesce(r, () => (_chunkAJNULBC3js.m.call(void 0, ))),C=_react.useMemo.call(void 0, ()=>_chunkAJNULBC3js.n.call(void 0, g),[g]),I=_optionalChain([u, 'optionalAccess', _10 => _10.brandColor]),N=_react.useMemo.call(void 0, ()=>it(n,{brandColor:I}),[n,I]),B=_react.useMemo.call(void 0, ()=>at(o),[o]),w=_jsxruntime.jsx.call(void 0, _chunkB32ACCW2js.l,{value:f,children:_jsxruntime.jsx.call(void 0, _connectquery.TransportProvider,{transport:C,children:_jsxruntime.jsx.call(void 0, nt,{appearance:N,children:_jsxruntime.jsx.call(void 0, pt,{texts:B,locale:s,children:_jsxruntime.jsx.call(void 0, ar,{projectID:e,environment:ot(t),transport:C,panelAccessToken:a,className:y,children:p})})})})});return c==null&&b!=null?_jsxruntime.jsx.call(void 0, _reactquery.QueryClientProvider,{client:b,children:w}):w}var Xr=ir;var ur="SESSION_EXPIRED",bt={INVALID_EMAIL:"errorInvalidEmail",INVALID_OR_EXPIRED_CODE:"errorInvalidCode",SESSION_EXPIRED:"errorSessionExpired",ORDER_NOT_FOUND:"errorOrderNotFound",RETURN_NOT_FOUND:"errorReturnNotFound",QUANTITY_UNAVAILABLE:"errorQuantityUnavailable",ITEM_NOT_RETURNABLE:"errorItemNotReturnable",INVALID_RETURN_ITEMS:"errorItemNotReturnable",RETURNS_DISABLED:"errorReturnsDisabled",SUBMISSION_RATE_LIMITED:"errorRateLimited",IDEMPOTENCY_CONFLICT:"errorIdempotencyConflict",VERIFICATION_DELIVERY_FAILED:"errorDeliveryFailed"};function xt(e){if(e==null||typeof e!="object")return;let{rawMessage:r,message:t}=e;if(typeof r=="string"&&r.length>0)return r;if(typeof t=="string")return Object.keys(bt).find(n=>t.includes(n))}function Pe(e){return xt(e)===ur}function St(e){let r=xt(e);return_nullishCoalesce((r!=null?bt[r]:void 0), () => ("errorGeneric"))}function Le(){let e=typeof globalThis<"u"?globalThis.crypto:void 0;if(typeof _optionalChain([e, 'optionalAccess', _11 => _11.randomUUID])=="function")return e.randomUUID();let r=new Uint8Array(16);if(typeof _optionalChain([e, 'optionalAccess', _12 => _12.getRandomValues])=="function")e.getRandomValues(r);else for(let t=0;t<r.length;t++)r[t]=Math.floor(Math.random()*256);return Array.from(r,t=>t.toString(16).padStart(2,"0")).join("")}function $(e){return e==null?null:e instanceof Error?e:new Error(String(e))}function X(e){return e==null?void 0:St(e)}function ce(e,r){_react.useEffect.call(void 0, ()=>{Pe(e)&&r()},[e,r])}function Nt(e){let[r,t]=_react.useState.call(void 0, [""]);return _react.useEffect.call(void 0, ()=>{t([""])},[e]),{pageToken:_nullishCoalesce(r[r.length-1], () => ("")),page:r.length,push:n=>t(o=>[...o,n]),pop:()=>t(n=>n.length>1?n.slice(0,-1):n)}}function de(){let e=T("useReturnSession"),r=_connectquery.useMutation.call(void 0, _chunkAJNULBC3js.j.returns.startReturnSession),t=_connectquery.useMutation.call(void 0, _chunkAJNULBC3js.j.returns.verifyReturnSession),{setChallenge:n,authenticate:o,clearSession:u}=e,s=_react.useCallback.call(void 0, async c=>{t.reset();let b=c.trim(),g=await r.mutateAsync({projectId:e.projectID,email:b,environment:e.environment});return n({challengeId:g.challengeId,email:b,resendAvailableAt:Date.now()+Math.max(0,g.resendAfterSeconds)*1e3}),g},[e.projectID,e.environment,n,r,t]),a=_react.useCallback.call(void 0, async c=>{let b=await t.mutateAsync({projectId:e.projectID,challengeId:c.challengeId,code:c.code,environment:e.environment}),g=ae(b.expiresAt);if(b.sessionToken===""||g==null)throw new Error("EMPTY_SESSION");return o({token:b.sessionToken,expiresAt:g}),b},[e.projectID,e.environment,o,t]),y=_react.useCallback.call(void 0, async c=>{try{return await s(c),!0}catch (e7){return!1}},[s]),m=_react.useCallback.call(void 0, async c=>{if(e.challenge==null)return!1;try{return await a({challengeId:e.challenge.challengeId,code:c.trim()}),!0}catch (e8){return!1}},[e.challenge,a]),p=_react.useCallback.call(void 0, ()=>e.challenge!=null?y(e.challenge.email):Promise.resolve(!1),[e.challenge,y]),f=$(_nullishCoalesce(_nullishCoalesce(r.error, () => (t.error)), () => (e.exchangeError)));return{status:e.status,isAuthenticated:e.status==="authenticated",challenge:e.challenge,isStarting:r.isPending,isVerifying:t.isPending,starting:r.isPending,verifying:t.isPending,error:f,errorKey:X(f),start:y,startSession:s,verifySession:a,verify:m,resend:p,logout:u}}function pe(e){return e.status==="hydrating"||e.status==="exchanging"}function ht(e,r){let t=T("useReturnOrders"),{pageSize:n,explicitPageToken:o}=he(e,r),u=Nt(t.token),s=_connectquery.useQuery.call(void 0, _chunkAJNULBC3js.j.returns.listReturnOrders,{projectId:t.projectID,sessionToken:_nullishCoalesce(t.token, () => ("")),pageSize:n,pageToken:_nullishCoalesce(o, () => (u.pageToken))},{enabled:t.token!=null});ce(s.error,t.clearSession);let a=_nullishCoalesce(_optionalChain([s, 'access', _13 => _13.data, 'optionalAccess', _14 => _14.nextPageToken]), () => (""));return{orders:_nullishCoalesce(_optionalChain([s, 'access', _15 => _15.data, 'optionalAccess', _16 => _16.orders]), () => ([])),total:_nullishCoalesce(_optionalChain([s, 'access', _17 => _17.data, 'optionalAccess', _18 => _18.total]), () => (0)),data:s.data,isLoading:pe(t)||s.isLoading,isFetching:s.isFetching,error:$(s.error),errorKey:X(s.error),status:s.status,isError:s.isError,isSuccess:s.isSuccess,page:u.page,hasNext:a!=="",hasPrevious:u.page>1,next:()=>{a!==""&&u.push(a)},previous:u.pop,refetch:()=>s.refetch()}}function Be(e){let r=T("useReturnableOrder"),t=_connectquery.useQuery.call(void 0, _chunkAJNULBC3js.j.returns.getReturnableOrder,{projectId:r.projectID,sessionToken:_nullishCoalesce(r.token, () => ("")),canonicalOrderId:_nullishCoalesce(e, () => (""))},{enabled:r.token!=null&&e!=null&&e!==""});return ce(t.error,r.clearSession),{order:_optionalChain([t, 'access', _19 => _19.data, 'optionalAccess', _20 => _20.order]),returnHistory:_nullishCoalesce(_optionalChain([t, 'access', _21 => _21.data, 'optionalAccess', _22 => _22.returnHistory]), () => ([])),data:t.data,isLoading:e!=null&&e!==""&&(pe(r)||t.isLoading),error:$(t.error),errorKey:X(t.error),status:t.status,isError:t.isError,isSuccess:t.isSuccess,refetch:()=>t.refetch()}}function kt(){let e=T("useCreateReturn"),r=_reactquery.useQueryClient.call(void 0, ),t=_connectquery.useMutation.call(void 0, _chunkAJNULBC3js.j.returns.createReturnRequest),n=_chunkB32ACCW2js.m.call(void 0, ),o=_react.useRef.call(void 0, void 0),{clearSession:u}=e,s=_react.useCallback.call(void 0, async(p,f)=>{try{let c=await t.mutateAsync({projectId:e.projectID,sessionToken:_nullishCoalesce(e.token, () => ("")),canonicalOrderId:p.orderId,items:p.items,note:_nullishCoalesce(p.note, () => ("")),idempotencyKey:f});return r.invalidateQueries({queryKey:Ce()}),n.track("return_submitted",{reason_code:"unspecified",item_count:p.items.length},{order_ref:null}),c}catch(c){throw Pe(c)&&u(),c}},[e.projectID,e.token,t,r,u,n]),a=_react.useCallback.call(void 0, async p=>{o.current??=Le();try{let f=await s(p,o.current);return o.current=void 0,f.request}catch (e9){return}},[s]),y=_react.useCallback.call(void 0, async p=>{if(e.token==null)throw new Error("Verify your email to continue.");return s({orderId:p.canonicalOrderID,items:p.items,note:p.note},_nullishCoalesce(p.idempotencyKey, () => (Le())))},[e.token,s]),m=_react.useCallback.call(void 0, (p,f)=>{y(p).then(c=>_optionalChain([f, 'optionalAccess', _23 => _23.onSuccess, 'optionalCall', _24 => _24(c)]),c=>_optionalChain([f, 'optionalAccess', _25 => _25.onError, 'optionalCall', _26 => _26($(c))]))},[y]);return{submit:a,isPending:t.isPending,error:$(t.error),errorKey:X(t.error),mutateAsync:y,mutate:m,data:t.data,reset:t.reset,status:t.status,isError:t.isError,isSuccess:t.isSuccess}}function Tt(e,r){let t=T("useMyReturns"),{pageSize:n,explicitPageToken:o}=he(e,r),u=Nt(t.token),s=_connectquery.useQuery.call(void 0, _chunkAJNULBC3js.j.returns.listMyReturns,{projectId:t.projectID,sessionToken:_nullishCoalesce(t.token, () => ("")),pageSize:n,pageToken:_nullishCoalesce(o, () => (u.pageToken))},{enabled:t.token!=null});ce(s.error,t.clearSession);let a=_nullishCoalesce(_optionalChain([s, 'access', _27 => _27.data, 'optionalAccess', _28 => _28.nextPageToken]), () => (""));return{returns:_nullishCoalesce(_optionalChain([s, 'access', _29 => _29.data, 'optionalAccess', _30 => _30.returns]), () => ([])),total:_nullishCoalesce(_optionalChain([s, 'access', _31 => _31.data, 'optionalAccess', _32 => _32.total]), () => (0)),data:s.data,isLoading:pe(t)||s.isLoading,isFetching:s.isFetching,error:$(s.error),errorKey:X(s.error),status:s.status,isError:s.isError,isSuccess:s.isSuccess,page:u.page,hasNext:a!=="",hasPrevious:u.page>1,next:()=>{a!==""&&u.push(a)},previous:u.pop,refetch:()=>s.refetch()}}function me(e){let r=T("useMyReturn"),t=_connectquery.useQuery.call(void 0, _chunkAJNULBC3js.j.returns.getMyReturn,{projectId:r.projectID,sessionToken:_nullishCoalesce(r.token, () => ("")),returnId:e},{enabled:r.token!=null});return ce(t.error,r.clearSession),{request:_optionalChain([t, 'access', _33 => _33.data, 'optionalAccess', _34 => _34.request]),isLoading:pe(r)||t.isLoading,error:t.error,errorKey:X(t.error),refetch:()=>t.refetch()}}var _reactlabel = require('@radix-ui/react-label'); var wt = _interopRequireWildcard(_reactlabel);function te({className:e,...r}){return _jsxruntime.jsx.call(void 0, wt.Root,{"data-slot":"label",className:_chunkVIII45ACjs.d.call(void 0, "flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",e),...r})}var _lucidereact = require('lucide-react');function re({className:e,...r}){return _jsxruntime.jsx.call(void 0, _lucidereact.Loader2Icon,{role:"status","aria-label":"Loading",className:_chunkVIII45ACjs.d.call(void 0, "size-4 animate-spin",e),...r})}var H="bg-[var(--bitsnap-returns-button-background,#18181b)] text-[color:var(--bitsnap-returns-button-foreground,#fafafa)] hover:bg-[var(--bitsnap-returns-button-hover-background,#000000)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50",L="border border-[color:var(--bitsnap-returns-border,#e4e4e7)] bg-transparent text-[color:var(--bitsnap-returns-foreground,#18181b)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50",G="bg-[var(--bitsnap-returns-input-background,#ffffff)] dark:bg-[var(--bitsnap-returns-input-background,#ffffff)] border-[color:var(--bitsnap-returns-border,#e4e4e7)] text-[color:var(--bitsnap-returns-foreground,#18181b)] placeholder:text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] focus-visible:border-[color:var(--bitsnap-returns-focus-ring,#71717a)] focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]/50";function M({title:e,description:r,onBack:t,className:n,children:o}){let u=h(),s=l("header"),a=l("title"),y=l("description"),m=l("backButton");return _jsxruntime.jsxs.call(void 0, "section",{className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-5",n),children:[_jsxruntime.jsxs.call(void 0, "div",{"data-bitsnap-returns-slot":"header",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-2",s.className),style:s.style,children:[t!=null&&_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"ghost",size:"sm","data-bitsnap-returns-slot":"backButton",className:_chunkVIII45ACjs.d.call(void 0, "self-start -ml-3 text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",m.className),style:m.style,onClick:t,children:u("back")}),_jsxruntime.jsx.call(void 0, "h2",{"data-bitsnap-returns-slot":"title",className:_chunkVIII45ACjs.d.call(void 0, "text-2xl font-semibold",a.className),style:a.style,children:e}),r!=null&&_jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"description",className:_chunkVIII45ACjs.d.call(void 0, "text-sm",y.className),style:y.style,children:r})]}),o]})}function A({errorKey:e,onRetry:r}){let t=h(),n=l("error"),o=l("secondaryButton");return _jsxruntime.jsxs.call(void 0, "div",{role:"alert","data-bitsnap-returns-slot":"error",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col items-start gap-2 text-sm",n.className),style:n.style,children:[_jsxruntime.jsx.call(void 0, "p",{children:t(e)}),r!=null&&_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,o.className),style:o.style,onClick:r,children:t("errorRetry")})]})}function fe({children:e}){let r=l("emptyState");return _jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"emptyState",className:_chunkVIII45ACjs.d.call(void 0, "py-6 text-center text-sm",r.className),style:r.style,children:e})}function U({rows:e=3}){let r=h(),t=l("skeleton");return _jsxruntime.jsx.call(void 0, "div",{role:"status","aria-busy":"true","aria-label":r("loading"),className:"flex flex-col gap-3",children:Array.from({length:e},(n,o)=>_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.u,{"data-bitsnap-returns-slot":"skeleton",className:_chunkVIII45ACjs.d.call(void 0, "h-16 w-full bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",t.className),style:t.style},o))})}function J({status:e}){let r=h(),t=l("statusBadge");return _jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"statusBadge","data-status":e,className:_chunkVIII45ACjs.d.call(void 0, "inline-flex items-center rounded-full px-2.5 py-0.5 text-xs font-medium",t.className),style:t.style,children:r(lt(e))})}function ze(){let e=h();return r=>e(ct(r))}function ge({page:e,total:r,hasNext:t,hasPrevious:n,isFetching:o,onNext:u,onPrevious:s}){let a=h(),y=l("pagination"),m=l("secondaryButton");return!t&&!n?null:_jsxruntime.jsxs.call(void 0, "nav",{"data-bitsnap-returns-slot":"pagination",className:_chunkVIII45ACjs.d.call(void 0, "flex items-center justify-between gap-3 text-sm",y.className),style:y.style,children:[_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,m.className),style:m.style,disabled:!n||o,onClick:s,children:a("paginationPrevious")}),_jsxruntime.jsx.call(void 0, "span",{"aria-live":"polite",children:a("paginationInfo",{page:e,total:r})}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,m.className),style:m.style,disabled:!t||o,onClick:u,children:a("paginationNext")})]})}function Kn({onSubmitted:e,className:r}){T("ReturnsEmailStep");let t=h(),n=de(),[o,u]=_react.useState.call(void 0, ""),s=l("emailForm"),a=l("emailInput"),y=l("submitButton");async function m(p){p.preventDefault(),!n.isStarting&&await n.start(o)&&_optionalChain([e, 'optionalCall', _35 => _35(o.trim())])}return _jsxruntime.jsx.call(void 0, M,{className:r,title:t("emailStepTitle"),description:t("emailStepDescription"),children:_jsxruntime.jsxs.call(void 0, "form",{"data-bitsnap-returns-slot":"emailForm",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-4",s.className),style:s.style,onSubmit:m,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, te,{htmlFor:"bitsnap-returns-email",children:t("emailLabel")}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.r,{id:"bitsnap-returns-email",type:"email",name:"email",autoComplete:"email",required:!0,value:o,placeholder:t("emailPlaceholder"),disabled:n.isStarting,"data-bitsnap-returns-slot":"emailInput",className:_chunkVIII45ACjs.d.call(void 0, G,a.className),style:a.style,onChange:p=>u(p.target.value)})]}),n.errorKey!=null&&_jsxruntime.jsx.call(void 0, A,{errorKey:n.errorKey}),_jsxruntime.jsxs.call(void 0, _chunkAJNULBC3js.q,{type:"submit",disabled:n.isStarting,"data-bitsnap-returns-slot":"submitButton",className:_chunkVIII45ACjs.d.call(void 0, H,y.className),style:y.style,children:[n.isStarting&&_jsxruntime.jsx.call(void 0, re,{}),t("emailSubmit")]})]})})}function gr(e){let[r,t]=_react.useState.call(void 0, );return _react.useEffect.call(void 0, ()=>{if(e==null)return;t(Date.now());let n=setInterval(()=>{let o=Date.now();t(o),o>=e&&clearInterval(n)},1e3);return()=>clearInterval(n)},[e]),e!=null&&r!=null?Math.max(0,Math.ceil((e-r)/1e3)):0}function _n({onVerified:e,onBack:r,className:t}){T("ReturnsCodeStep");let n=h(),o=de(),[u,s]=_react.useState.call(void 0, ""),a=gr(_optionalChain([o, 'access', _36 => _36.challenge, 'optionalAccess', _37 => _37.resendAvailableAt])),y=l("codeForm"),m=l("codeInput"),p=l("submitButton"),f=l("resendButton"),c=o.isVerifying||o.isStarting;async function b(g){g.preventDefault(),!c&&await o.verify(u)&&_optionalChain([e, 'optionalCall', _38 => _38()])}return _jsxruntime.jsx.call(void 0, M,{className:t,onBack:r,title:n("codeStepTitle"),description:n("codeStepDescription",{email:_nullishCoalesce(_optionalChain([o, 'access', _39 => _39.challenge, 'optionalAccess', _40 => _40.email]), () => (""))}),children:_jsxruntime.jsxs.call(void 0, "form",{"data-bitsnap-returns-slot":"codeForm",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-4",y.className),style:y.style,onSubmit:b,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, te,{htmlFor:"bitsnap-returns-code",children:n("codeLabel")}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.r,{id:"bitsnap-returns-code",name:"code",inputMode:"numeric",autoComplete:"one-time-code",required:!0,value:u,disabled:c,"data-bitsnap-returns-slot":"codeInput",className:_chunkVIII45ACjs.d.call(void 0, G,m.className),style:m.style,onChange:g=>s(g.target.value)})]}),o.errorKey!=null&&_jsxruntime.jsx.call(void 0, A,{errorKey:o.errorKey}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap items-center gap-3",children:[_jsxruntime.jsxs.call(void 0, _chunkAJNULBC3js.q,{type:"submit",disabled:c||o.challenge==null,"data-bitsnap-returns-slot":"submitButton",className:_chunkVIII45ACjs.d.call(void 0, H,p.className),style:p.style,children:[o.isVerifying&&_jsxruntime.jsx.call(void 0, re,{}),n("codeSubmit")]}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",disabled:c||a>0||o.challenge==null,"data-bitsnap-returns-slot":"resendButton",className:_chunkVIII45ACjs.d.call(void 0, L,f.className),style:f.style,onClick:()=>void o.resend(),children:a>0?n("resendIn",{seconds:a}):n("resend")})]})]})})}function It(){let e=h(),r=de(),t=l("logoutButton");return _jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"ghost",size:"sm","data-bitsnap-returns-slot":"logoutButton",className:_chunkVIII45ACjs.d.call(void 0, "text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] hover:bg-[var(--bitsnap-returns-hover-surface,#f4f4f5)]",t.className),style:t.style,onClick:r.logout,children:e("logout")})}function Z(e,r){if(e==null)return"";let t=_wkt.timestampDate.call(void 0, e);try{return new Intl.DateTimeFormat(r,{dateStyle:"medium"}).format(t)}catch (e10){return t.toISOString().slice(0,10)}}function ee(e,r,t){let n=typeof e=="bigint"?e:BigInt(Math.trunc(e));try{let o=new Intl.NumberFormat(t,{style:"currency",currency:r}),u=_nullishCoalesce(o.resolvedOptions().maximumFractionDigits, () => (2));return o.format(Et(n,u))}catch (e11){return`${Et(n,2)} ${r}`}}function Et(e,r){let t=e<BigInt(0),n=t?-e:e;if(r<=0)return`${t?"-":""}${n}`;let o=BigInt(10)**BigInt(r),u=n/o,s=(n%o).toString().padStart(r,"0");return`${t?"-":""}${u}.${s}`}function Ct(e,r){return Number.isFinite(e)?Math.min(Math.max(0,Math.trunc(e)),Math.max(0,r)):0}function Oe(e){return e.eligible&&e.availableQuantity>0}function Pt(e,r){return e.map(t=>({lineId:t,quantity:_nullishCoalesce(r[t], () => (0))})).filter(t=>t.quantity>0)}function cs({onSelectOrder:e,onOpenMyReturns:r,showLogout:t=!0,pageSize:n,className:o}){T("ReturnsOrderList");let u=h(),s=Y(),a=ht({pageSize:n}),y=l("orderList"),m=l("orderCard"),p=l("orderReference"),f=l("orderDate"),c=l("orderTotal"),b=l("secondaryButton");return _jsxruntime.jsxs.call(void 0, M,{className:o,title:u("ordersTitle"),description:u("ordersDescription"),children:[(t||r!=null)&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap items-center justify-between gap-2",children:[r!=null?_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,b.className),style:b.style,onClick:r,children:u("myReturnsLink")}):_jsxruntime.jsx.call(void 0, "span",{}),t&&_jsxruntime.jsx.call(void 0, It,{})]}),a.isLoading?_jsxruntime.jsx.call(void 0, U,{}):a.errorKey!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:a.errorKey,onRetry:a.refetch}):a.orders.length===0?_jsxruntime.jsx.call(void 0, fe,{children:u("ordersEmpty")}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"orderList",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3",y.className),style:y.style,children:a.orders.map(g=>_jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"orderCard",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-center justify-between gap-3 border p-4",m.className),style:m.style,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"orderReference",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",p.className),style:p.style,children:u("orderTitle",{reference:g.displayReference})}),_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"orderDate",className:_chunkVIII45ACjs.d.call(void 0, "text-sm",f.className),style:f.style,children:Z(g.purchasedAt,s)}),_jsxruntime.jsx.call(void 0, "span",{className:"text-sm",children:u("orderReturnableLines",{count:g.returnableLineCount})})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-4",children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"orderTotal",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",c.className),style:c.style,children:ee(g.totalMinor,g.currency,s)}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","aria-label":`${u("orderSelect")}: ${u("orderTitle",{reference:g.displayReference})}`,"data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,b.className),style:b.style,onClick:()=>_optionalChain([e, 'optionalCall', _41 => _41(g.canonicalOrderId)]),children:u("orderSelect")})]})]},g.canonicalOrderId))}),_jsxruntime.jsx.call(void 0, ge,{page:a.page,total:a.total,hasNext:a.hasNext,hasPrevious:a.hasPrevious,isFetching:a.isFetching,onNext:a.next,onPrevious:a.previous})]})]})}function ds({orderId:e,onContinue:r,onBack:t,initialItems:n,initialNote:o,className:u}){T("ReturnsOrderDetail");let s=_chunkB32ACCW2js.m.call(void 0, );_react.useEffect.call(void 0, ()=>{s.track("return_started",{},{order_ref:null})},[s]);let a=h(),y=Y(),{order:m,returnHistory:p,isLoading:f,errorKey:c,refetch:b}=Be(e),[g,C]=_react.useState.call(void 0, ()=>Object.fromEntries((_nullishCoalesce(n, () => ([]))).map(R=>[R.lineId,R.quantity]))),[I,N]=_react.useState.call(void 0, _nullishCoalesce(o, () => (""))),[B,w]=_react.useState.call(void 0, !1),P=l("lineList"),k=l("line"),Q=l("lineName"),O=l("linePrice"),q=l("lineQuantityControl"),ne=l("quantityButton"),Me=l("quantityInput"),qe=l("lineIneligibleReason"),Ke=l("noteInput"),_e=l("submitButton"),je=l("history"),Ue=l("historyEntry");function Re(R,V){w(!1),C(F=>({...F,[R.lineId]:Ct(V,R.availableQuantity)}))}function At(R){if(R.preventDefault(),m==null)return;let V=Pt(m.lines.filter(Oe).map(F=>F.lineId),g);if(V.length===0){w(!0);return}_optionalChain([r, 'optionalCall', _42 => _42({items:V,note:I.trim()})])}return _jsxruntime.jsx.call(void 0, M,{className:u,onBack:t,title:a("orderDetailTitle",{reference:_nullishCoalesce(_optionalChain([m, 'optionalAccess', _43 => _43.displayReference]), () => (""))}),description:a("orderDetailDescription"),children:f?_jsxruntime.jsx.call(void 0, U,{}):c!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:c,onRetry:b}):m==null?null:_jsxruntime.jsxs.call(void 0, "form",{className:"flex flex-col gap-5",onSubmit:At,children:[_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"lineList",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3",P.className),style:P.style,children:m.lines.map(R=>{let V=Oe(R),F=_nullishCoalesce(g[R.lineId], () => (0)),be=`bitsnap-returns-quantity-${R.lineId}`;return _jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"line","data-selected":F>0?"":void 0,"data-ineligible":V?void 0:"",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3 border p-4",k.className),style:k.style,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap items-baseline justify-between gap-2",children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"lineName",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",Q.className),style:Q.style,children:R.name}),_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"linePrice",className:_chunkVIII45ACjs.d.call(void 0, "text-sm",O.className),style:O.style,children:ee(R.paidUnitMinor,R.currency,y)})]}),V?_jsxruntime.jsxs.call(void 0, "div",{role:"group","aria-label":a("quantityLabel",{name:R.name}),"data-bitsnap-returns-slot":"lineQuantityControl",className:_chunkVIII45ACjs.d.call(void 0, "flex items-center gap-2",q.className),style:q.style,children:[_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"icon-sm","aria-label":a("quantityDecrease",{name:R.name}),"aria-controls":be,disabled:F<=0,"data-bitsnap-returns-slot":"quantityButton",className:_chunkVIII45ACjs.d.call(void 0, L,ne.className),style:ne.style,onClick:()=>Re(R,F-1),children:_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:"-"})}),_jsxruntime.jsx.call(void 0, "input",{id:be,type:"number",inputMode:"numeric",min:0,max:R.availableQuantity,step:1,value:F,"aria-label":a("quantityLabel",{name:R.name}),"data-bitsnap-returns-slot":"quantityInput",className:_chunkVIII45ACjs.d.call(void 0, "h-8 w-16 rounded-md border px-2 text-center text-sm outline-none focus-visible:ring-[3px]",G,Me.className),style:Me.style,onChange:Bt=>Re(R,Bt.target.valueAsNumber)}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"icon-sm","aria-label":a("quantityIncrease",{name:R.name}),"aria-controls":be,disabled:F>=R.availableQuantity,"data-bitsnap-returns-slot":"quantityButton",className:_chunkVIII45ACjs.d.call(void 0, L,ne.className),style:ne.style,onClick:()=>Re(R,F+1),children:_jsxruntime.jsx.call(void 0, "span",{"aria-hidden":"true",children:"+"})}),_jsxruntime.jsx.call(void 0, "span",{className:"text-sm",children:a("quantityOfAvailable",{available:R.availableQuantity})})]}):_jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"lineIneligibleReason",className:_chunkVIII45ACjs.d.call(void 0, "text-sm",qe.className),style:qe.style,children:R.exclusionReason!==""?R.exclusionReason:a("lineIneligibleFallback")})]},R.lineId)})}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, te,{htmlFor:"bitsnap-returns-note",children:a("noteLabel")}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.v,{id:"bitsnap-returns-note",name:"note",rows:3,maxLength:1e3,value:I,placeholder:a("notePlaceholder"),"data-bitsnap-returns-slot":"noteInput",className:_chunkVIII45ACjs.d.call(void 0, G,"dark:border-[color:var(--bitsnap-returns-border,#e4e4e7)] dark:placeholder:text-[color:var(--bitsnap-returns-muted-foreground,#71717a)] dark:focus-visible:ring-[color:var(--bitsnap-returns-focus-ring,#71717a)]",Ke.className),style:Ke.style,onChange:R=>N(R.target.value)})]}),B&&_jsxruntime.jsx.call(void 0, A,{errorKey:"selectionEmpty"}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"submit","data-bitsnap-returns-slot":"submitButton",className:_chunkVIII45ACjs.d.call(void 0, H,_e.className),style:_e.style,children:a("selectionContinue")}),p.length>0&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-sm font-medium",children:a("previousReturnsTitle")}),_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"history",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-2",je.className),style:je.style,children:p.map(R=>_jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"historyEntry",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-center justify-between gap-2 text-sm",Ue.className),style:Ue.style,children:[_jsxruntime.jsx.call(void 0, "span",{children:R.reference}),_jsxruntime.jsx.call(void 0, "span",{children:Z(R.createdAt,y)}),_jsxruntime.jsx.call(void 0, J,{status:R.status})]},R.id))})]})]})})}function ps({orderId:e,items:r,note:t,onSubmitted:n,onBack:o,className:u}){T("ReturnsConfirmation");let s=h(),a=Y(),{order:y,isLoading:m,errorKey:p,refetch:f}=Be(e),c=kt(),b=l("summary"),g=l("line"),C=l("lineName"),I=l("linePrice"),N=l("submitButton");async function B(w){if(w.preventDefault(),c.isPending)return;let P=await c.submit({orderId:e,items:r.map(k=>({lineId:k.lineId,quantity:k.quantity})),note:t});P!=null&&_optionalChain([n, 'optionalCall', _44 => _44(P.id,P)])}return _jsxruntime.jsx.call(void 0, M,{className:u,onBack:o,title:s("confirmationTitle"),description:s("confirmationDescription"),children:m?_jsxruntime.jsx.call(void 0, U,{rows:2}):p!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:p,onRetry:f}):_jsxruntime.jsxs.call(void 0, "form",{className:"flex flex-col gap-5",onSubmit:B,children:[_jsxruntime.jsxs.call(void 0, "div",{"data-bitsnap-returns-slot":"summary",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3 border p-4",b.className),style:b.style,children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-sm font-medium",children:s("confirmationSummary")}),_jsxruntime.jsx.call(void 0, "ul",{className:"flex flex-col gap-3",children:r.map(w=>{let P=_optionalChain([y, 'optionalAccess', _45 => _45.lines, 'access', _46 => _46.find, 'call', _47 => _47(k=>k.lineId===w.lineId)]);return _jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"line",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-baseline justify-between gap-2",g.className),style:g.style,children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"lineName",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",C.className),style:C.style,children:_nullishCoalesce(_optionalChain([P, 'optionalAccess', _48 => _48.name]), () => (w.lineId))}),_jsxruntime.jsxs.call(void 0, "span",{"data-bitsnap-returns-slot":"linePrice",className:_chunkVIII45ACjs.d.call(void 0, "text-sm",I.className),style:I.style,children:[s("confirmationQuantity",{quantity:w.quantity}),P!=null&&` \xB7 ${ee(P.paidUnitMinor*BigInt(w.quantity),P.currency,a)}`]})]},w.lineId)})}),t!=null&&t!==""&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1 text-sm",children:[_jsxruntime.jsx.call(void 0, "span",{className:"font-medium",children:s("confirmationNote")}),_jsxruntime.jsx.call(void 0, "span",{className:"whitespace-pre-wrap",children:t})]})]}),c.errorKey!=null&&_jsxruntime.jsx.call(void 0, A,{errorKey:c.errorKey}),_jsxruntime.jsxs.call(void 0, _chunkAJNULBC3js.q,{type:"submit",disabled:c.isPending||r.length===0,"data-bitsnap-returns-slot":"submitButton",className:_chunkVIII45ACjs.d.call(void 0, H,N.className),style:N.style,children:[c.isPending&&_jsxruntime.jsx.call(void 0, re,{}),s("confirmationSubmit")]})]})})}function ms({returnId:e,onContinue:r,onOpenMyReturns:t,className:n}){T("ReturnsResult");let o=h(),{request:u,isLoading:s,errorKey:a,refetch:y}=me(e),m=l("successState"),p=l("returnReference"),f=l("returnInstructions"),c=l("submitButton"),b=l("secondaryButton");return _jsxruntime.jsxs.call(void 0, "section",{className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-5",n),children:[_jsxruntime.jsxs.call(void 0, "div",{role:"status","data-bitsnap-returns-slot":"successState",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-4 border p-5",m.className),style:m.style,children:[_jsxruntime.jsx.call(void 0, "h2",{className:"text-2xl font-semibold",children:o("successTitle")}),_jsxruntime.jsx.call(void 0, "p",{className:"text-sm",children:o("successDescription")}),s?_jsxruntime.jsx.call(void 0, U,{rows:2}):a!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:a,onRetry:y}):u!=null&&_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "span",{className:"text-sm",children:o("successReference")}),_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"returnReference",className:_chunkVIII45ACjs.d.call(void 0, "text-lg font-semibold",p.className),style:p.style,children:u.reference})]}),u.returnInstructions!==""&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "span",{className:"text-sm font-medium",children:o("successInstructions")}),_jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"returnInstructions",className:_chunkVIII45ACjs.d.call(void 0, "whitespace-pre-wrap border p-3 text-sm",f.className),style:f.style,children:u.returnInstructions})]})]})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-wrap gap-3",children:[_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button","data-bitsnap-returns-slot":"submitButton",className:_chunkVIII45ACjs.d.call(void 0, H,c.className),style:c.style,onClick:r,children:o("successDone")}),t!=null&&_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary","data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,b.className),style:b.style,onClick:t,children:o("myReturnsLink")})]})]})}function Ts({onSelectReturn:e,onBack:r,pageSize:t,className:n}){T("ReturnsMyReturnsList");let o=h(),u=Y(),s=ze(),a=Tt({pageSize:t}),y=l("returnList"),m=l("returnCard"),p=l("returnReference"),f=l("secondaryButton");return _jsxruntime.jsx.call(void 0, M,{className:n,onBack:r,title:o("myReturnsTitle"),description:o("myReturnsDescription"),children:a.isLoading?_jsxruntime.jsx.call(void 0, U,{}):a.errorKey!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:a.errorKey,onRetry:a.refetch}):a.returns.length===0?_jsxruntime.jsx.call(void 0, fe,{children:o("myReturnsEmpty")}):_jsxruntime.jsxs.call(void 0, _jsxruntime.Fragment,{children:[_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"returnList",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3",y.className),style:y.style,children:a.returns.map(c=>_jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"returnCard",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-center justify-between gap-3 border p-4",m.className),style:m.style,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-1",children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"returnReference",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",p.className),style:p.style,children:c.reference}),_jsxruntime.jsx.call(void 0, "span",{className:"text-sm",children:Z(c.createdAt,u)}),_jsxruntime.jsxs.call(void 0, "span",{className:"text-sm",children:[o("myReturnRefund"),": ",s(c.refundStatus)]})]}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center gap-3",children:[_jsxruntime.jsx.call(void 0, J,{status:c.status}),_jsxruntime.jsx.call(void 0, _chunkAJNULBC3js.q,{type:"button",variant:"secondary",size:"sm","aria-label":`${o("myReturnOpen")}: ${c.reference}`,"data-bitsnap-returns-slot":"secondaryButton",className:_chunkVIII45ACjs.d.call(void 0, L,f.className),style:f.style,onClick:()=>_optionalChain([e, 'optionalCall', _49 => _49(c.id)]),children:o("myReturnOpen")})]})]},c.id))}),_jsxruntime.jsx.call(void 0, ge,{page:a.page,total:a.total,hasNext:a.hasNext,hasPrevious:a.hasPrevious,isFetching:a.isFetching,onNext:a.next,onPrevious:a.previous})]})})}function ws({returnId:e,onBack:r,className:t}){T("ReturnsMyReturnDetail");let n=h(),o=Y(),u=ze(),{request:s,isLoading:a,errorKey:y,refetch:m}=me(e),p=l("summary"),f=l("lineList"),c=l("line"),b=l("lineName"),g=l("returnInstructions"),C=l("history"),I=l("historyEntry");return _jsxruntime.jsx.call(void 0, M,{className:t,onBack:r,title:s!=null?n("myReturnTitle",{reference:s.reference}):n("myReturnDetailTitle"),children:a?_jsxruntime.jsx.call(void 0, U,{}):y!=null?_jsxruntime.jsx.call(void 0, A,{errorKey:y,onRetry:m}):s!=null&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-5",children:[_jsxruntime.jsxs.call(void 0, "div",{"data-bitsnap-returns-slot":"summary",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-2 border p-4 text-sm",p.className),style:p.style,children:[_jsxruntime.jsxs.call(void 0, "div",{className:"flex items-center justify-between gap-2",children:[_jsxruntime.jsx.call(void 0, J,{status:s.status}),_jsxruntime.jsxs.call(void 0, "span",{children:[n("myReturnCreatedAt"),":"," ",Z(s.createdAt,o)]})]}),_jsxruntime.jsxs.call(void 0, "span",{children:[n("myReturnRefund"),": ",u(s.refundStatus),s.refundAmountMinor>BigInt(0)&&` \xB7 ${ee(s.refundAmountMinor,s.currency,o)}`]}),s.customerNote!==""&&_jsxruntime.jsxs.call(void 0, "span",{className:"whitespace-pre-wrap",children:[n("myReturnNote"),": ",s.customerNote]})]}),s.returnInstructions!==""&&_jsxruntime.jsx.call(void 0, "p",{"data-bitsnap-returns-slot":"returnInstructions",className:_chunkVIII45ACjs.d.call(void 0, "whitespace-pre-wrap border p-3 text-sm",g.className),style:g.style,children:s.returnInstructions}),_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-sm font-medium",children:n("myReturnLines")}),_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"lineList",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-3",f.className),style:f.style,children:s.lines.map(N=>_jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"line",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-baseline justify-between gap-2 border p-4",c.className),style:c.style,children:[_jsxruntime.jsx.call(void 0, "span",{"data-bitsnap-returns-slot":"lineName",className:_chunkVIII45ACjs.d.call(void 0, "font-medium",b.className),style:b.style,children:N.name}),_jsxruntime.jsx.call(void 0, "span",{className:"text-sm",children:n("myReturnLineQuantities",{requested:N.requestedQuantity,approved:N.approvedQuantity,received:N.receivedQuantity})})]},N.lineId))})]}),s.history.length>0&&_jsxruntime.jsxs.call(void 0, "div",{className:"flex flex-col gap-2",children:[_jsxruntime.jsx.call(void 0, "h3",{className:"text-sm font-medium",children:n("myReturnHistory")}),_jsxruntime.jsx.call(void 0, "ul",{"data-bitsnap-returns-slot":"history",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-col gap-2",C.className),style:C.style,children:s.history.map(N=>_jsxruntime.jsxs.call(void 0, "li",{"data-bitsnap-returns-slot":"historyEntry",className:_chunkVIII45ACjs.d.call(void 0, "flex flex-wrap items-center justify-between gap-2 text-sm",I.className),style:I.style,children:[_jsxruntime.jsx.call(void 0, J,{status:N.status}),_jsxruntime.jsx.call(void 0, "span",{children:Z(N.createdAt,o)})]},N.id))})]})]})})}exports.a = te; exports.b = re; exports.c = vr; exports.d = nt; exports.e = Ne; exports.f = l; exports.g = Pe; exports.h = St; exports.i = h; exports.j = T; exports.k = ir; exports.l = Xr; exports.m = de; exports.n = ht; exports.o = Be; exports.p = kt; exports.q = Tt; exports.r = me; exports.s = U; exports.t = Kn; exports.u = _n; exports.v = cs; exports.w = ds; exports.x = ps; exports.y = ms; exports.z = Ts; exports.A = ws;
|
|
2
|
+
//# sourceMappingURL=chunk-RVILRUW3.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-RVILRUW3.js","../src/components/returns/appearance.ts","../src/components/returns/appearance.context.tsx","../src/components/returns/legacy.ts","../src/components/returns/texts.ts","../src/components/returns/texts.context.tsx","../src/components/returns/ReturnsProvider.tsx","../src/components/returns/session-storage.ts"],"names":["RETURNS_SLOT_NAMES","RETURNS_TOKEN_VARIABLES","RETURNS_THEME_PRESETS","RETURNS_SHADCN_VARIABLES","resolveReturnsAppearance","appearance","resolved","resolveAppearanceCore","getReturnsSlotAppearance","slot","getSlotAppearance","ReturnsAppearanceContext","createContext","ReturnsAppearanceProvider","children","useMemo","jsx","useReturnsAppearance","useContext","useReturnsSlot","resolveReturnsEnvironment","environment","LEGACY_TEXT_KEYS","mapLegacyTexts","texts","result","legacyKey","targets","value","target","key","resolveBrandAppearance","theme","color","brandColorTokens","resolvePagedArguments","first","pageToken","RETURNS_TEXT_TABLES","resolveReturnsTexts","locale","overrides","resolveTexts","fillText","template","values","match","name","STATUS_TEXT_KEYS","REFUND_STATUS_TEXT_KEYS","statusTextKey","status","refundStatusTextKey","ReturnsTextsContext","ReturnsTextsProvider","activeLocale","getLocale","useReturnsText","useCallback","useReturnsLocale","KEY_PREFIX","sessionStorageKey","projectID"],"mappings":"AAAA,y/BAAgD,sDAAuG,sDAAwD,sDAAyD,ICiE3PA,EAAAA,CAAqB,CAEhC,MAAA,CACA,QAAA,CACA,OAAA,CACA,aAAA,CACA,YAAA,CACA,eAAA,CACA,OAAA,CACA,YAAA,CACA,UAAA,CAEA,WAAA,CACA,YAAA,CACA,UAAA,CACA,WAAA,CACA,cAAA,CACA,cAAA,CAEA,WAAA,CAC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AAA,CACJ5B,CAAAA,CAAKe,CAAAA,CAAAA,EACJA,CAAAA,EAAU,IAAA,CAAOrB,CAAAA,CAAMM,CAAG,CAAA,CAAIa,EAAAA,CAASnB,CAAAA,CAAMM,CAAG,CAAA,CAAGe,CAAM,CAAA,CAC3D,CAACrB,CAAK,CACR,CACF,CAGO,SAASmC,CAAAA,CAAAA,CAA2B,CACzC,OAAOzC,+BAAAA,EAA8B,CAAA,CAAE,MACzC,CCtEA,8CAA6B,yDAItB,mDAMA,6CCVqC,IAetC0C,EAAAA,CAAa,0BAAA,CAGZ,SAASC,EAAAA,CAAkBC,CAAAA,CAA2B,CAC3D,MAAO,CAAA,EAAA","file":"/home/emems/.t3/worktrees/bitsnap-react/visitor-cookie/dist/chunk-RVILRUW3.js","sourcesContent":[null,"import type { CSSProperties } from \"react\";\nimport {\n getSlotAppearance,\n resolveAppearanceCore,\n type AppearanceElements,\n type ShadcnVariableMapping,\n type SlotAppearance,\n} from \"@/src/lib/appearance-core\";\n\n/**\n * Returns appearance API.\n *\n * It mirrors `CheckoutAppearance` (theme, tokens, elements) so a shop can reuse\n * one brand object for both. The resolver is pure: it turns the caller input\n * into a theme name, the tokens in effect, the slot overrides and the inline\n * style for the theme boundary.\n */\n\nexport type ReturnsTheme = \"light\" | \"dark\";\n\nexport type ReturnsAppearanceTokens = {\n /** Font family of the returns views. The library never loads fonts. */\n fontFamily?: string;\n /** Base font size. */\n fontSize?: string;\n /** Page background. */\n background?: string;\n /** Raised surfaces: cards, skeletons, summaries. */\n surface?: string;\n /** Main text color. */\n foreground?: string;\n /** Secondary text: descriptions, dates, hints. */\n mutedForeground?: string;\n /** Borders of cards, inputs and separators. */\n border?: string;\n /** Primary button background. */\n buttonBackground?: string;\n /** Primary button text. */\n buttonForeground?: string;\n /** Primary button background on hover. */\n buttonHoverBackground?: string;\n /** Hover surface of secondary buttons and selectable cards. */\n hoverSurface?: string;\n /** Focus ring color. Also applied to shared UI primitives through `--ring`. */\n focusRing?: string;\n /** Error color. */\n error?: string;\n /** Success color: result screen, completed and refunded statuses. */\n success?: string;\n /** Warning color: statuses that need attention. */\n warning?: string;\n /** Status badge background. */\n badgeBackground?: string;\n /** Status badge text. */\n badgeForeground?: string;\n /** Background of text inputs and the note field. */\n inputBackground?: string;\n /** Corner radius, applied through `--radius`. */\n radius?: string;\n};\n\n/**\n * Stable slot names. They are exposed as `data-bitsnap-returns-slot`\n * attributes so they can also be targeted from plain CSS.\n */\nexport const RETURNS_SLOT_NAMES = [\n // Frame\n \"root\",\n \"header\",\n \"title\",\n \"description\",\n \"backButton\",\n \"stepIndicator\",\n \"error\",\n \"emptyState\",\n \"skeleton\",\n // Auth\n \"emailForm\",\n \"emailInput\",\n \"codeForm\",\n \"codeInput\",\n \"resendButton\",\n \"logoutButton\",\n // Orders\n \"orderList\",\n \"orderCard\",\n \"orderReference\",\n \"orderDate\",\n \"orderTotal\",\n \"pagination\",\n // Selection\n \"lineList\",\n \"line\",\n \"lineName\",\n \"linePrice\",\n \"lineQuantityControl\",\n \"quantityButton\",\n \"quantityInput\",\n \"lineIneligibleReason\",\n \"noteInput\",\n // Confirmation and result\n \"summary\",\n \"submitButton\",\n \"secondaryButton\",\n \"successState\",\n \"returnReference\",\n \"returnInstructions\",\n // My returns\n \"returnList\",\n \"returnCard\",\n \"statusBadge\",\n \"history\",\n \"historyEntry\",\n] as const;\n\nexport type ReturnsSlotName = (typeof RETURNS_SLOT_NAMES)[number];\n\nexport type ReturnsSlotAppearance = SlotAppearance;\n\nexport type ReturnsAppearanceElements = AppearanceElements<ReturnsSlotName>;\n\nexport type ReturnsAppearance = {\n /** `\"light\"` or `\"dark\"`. Omitted means `\"light\"`. */\n theme?: ReturnsTheme;\n /** Partial overrides applied over the theme preset. */\n tokens?: ReturnsAppearanceTokens;\n /** Per element `className`/`style` overrides. */\n elements?: ReturnsAppearanceElements;\n};\n\nexport type ResolvedReturnsAppearance = {\n theme: ReturnsTheme;\n /** Tokens that are in effect (the theme preset plus caller overrides). */\n tokens: ReturnsAppearanceTokens;\n elements: ReturnsAppearanceElements;\n /** Theme marker class for the theme boundary. */\n boundaryClassName: string;\n /** Inline custom properties applied to the returns root. */\n boundaryStyle: CSSProperties;\n};\n\n/** CSS custom property used for each token. */\nexport const RETURNS_TOKEN_VARIABLES = {\n fontFamily: \"--bitsnap-returns-font-family\",\n fontSize: \"--bitsnap-returns-font-size\",\n background: \"--bitsnap-returns-background\",\n surface: \"--bitsnap-returns-surface\",\n foreground: \"--bitsnap-returns-foreground\",\n mutedForeground: \"--bitsnap-returns-muted-foreground\",\n border: \"--bitsnap-returns-border\",\n buttonBackground: \"--bitsnap-returns-button-background\",\n buttonForeground: \"--bitsnap-returns-button-foreground\",\n buttonHoverBackground: \"--bitsnap-returns-button-hover-background\",\n hoverSurface: \"--bitsnap-returns-hover-surface\",\n focusRing: \"--bitsnap-returns-focus-ring\",\n error: \"--bitsnap-returns-error\",\n success: \"--bitsnap-returns-success\",\n warning: \"--bitsnap-returns-warning\",\n badgeBackground: \"--bitsnap-returns-badge-background\",\n badgeForeground: \"--bitsnap-returns-badge-foreground\",\n inputBackground: \"--bitsnap-returns-input-background\",\n radius: \"--bitsnap-returns-radius\",\n} as const;\n\nexport type ReturnsTokenName = keyof typeof RETURNS_TOKEN_VARIABLES;\n\n/**\n * Complete palettes. They carry colors and radius only, so typography is never\n * reset implicitly. `returns.css` falls back to the light values, which keeps\n * the views usable even when the boundary style is missing.\n */\nexport const RETURNS_THEME_PRESETS: Record<\n ReturnsTheme,\n ReturnsAppearanceTokens\n> = {\n light: {\n background: \"#ffffff\",\n surface: \"#f9fafb\",\n foreground: \"#18181b\",\n mutedForeground: \"#71717a\",\n border: \"#e4e4e7\",\n buttonBackground: \"#18181b\",\n buttonForeground: \"#fafafa\",\n buttonHoverBackground: \"#000000\",\n hoverSurface: \"#f4f4f5\",\n focusRing: \"#71717a\",\n error: \"#dc2626\",\n success: \"#16a34a\",\n warning: \"#d97706\",\n badgeBackground: \"#f4f4f5\",\n badgeForeground: \"#3f3f46\",\n inputBackground: \"#ffffff\",\n radius: \"8px\",\n },\n dark: {\n background: \"#18181b\",\n surface: \"#27272a\",\n foreground: \"#fafafa\",\n mutedForeground: \"#a1a1aa\",\n border: \"#3f3f46\",\n buttonBackground: \"#fafafa\",\n buttonForeground: \"#18181b\",\n buttonHoverBackground: \"#e4e4e7\",\n hoverSurface: \"#3f3f46\",\n focusRing: \"#a1a1aa\",\n error: \"#f87171\",\n success: \"#4ade80\",\n warning: \"#fbbf24\",\n badgeBackground: \"#3f3f46\",\n badgeForeground: \"#e4e4e7\",\n inputBackground: \"#27272a\",\n radius: \"8px\",\n },\n};\n\n/**\n * Shared UI primitives (`Button`, `Input`, `Label`, ...) read the shadcn theme\n * variables, so those follow the returns tokens inside the boundary.\n */\nconst RETURNS_SHADCN_VARIABLES: ShadcnVariableMapping<ReturnsTokenName> = [\n { token: \"background\", variable: \"--background\" },\n { token: \"foreground\", variable: \"--foreground\" },\n { token: \"surface\", variable: \"--card\" },\n { token: \"foreground\", variable: \"--card-foreground\" },\n { token: \"surface\", variable: \"--popover\" },\n { token: \"foreground\", variable: \"--popover-foreground\" },\n { token: \"buttonBackground\", variable: \"--primary\" },\n { token: \"buttonForeground\", variable: \"--primary-foreground\" },\n { token: \"surface\", variable: \"--secondary\" },\n { token: \"foreground\", variable: \"--secondary-foreground\" },\n { token: \"hoverSurface\", variable: \"--accent\" },\n { token: \"foreground\", variable: \"--accent-foreground\" },\n { token: \"mutedForeground\", variable: \"--muted-foreground\" },\n { token: \"border\", variable: \"--border\" },\n { token: \"border\", variable: \"--input\" },\n { token: \"focusRing\", variable: \"--ring\" },\n { token: \"error\", variable: \"--destructive\" },\n { token: \"radius\", variable: \"--radius\" },\n];\n\nexport function resolveReturnsAppearance(\n appearance?: ReturnsAppearance,\n): ResolvedReturnsAppearance {\n const resolved = resolveAppearanceCore<\n ReturnsTokenName,\n ReturnsTheme,\n ReturnsSlotName\n >(appearance, {\n defaultTheme: \"light\",\n presets: RETURNS_THEME_PRESETS,\n variables: RETURNS_TOKEN_VARIABLES,\n shadcnVariables: RETURNS_SHADCN_VARIABLES,\n });\n\n return {\n theme: resolved.theme,\n tokens: resolved.tokens,\n elements: resolved.elements,\n boundaryClassName: resolved.theme,\n boundaryStyle: resolved.boundaryStyle,\n };\n}\n\n/** Caller overrides for a single slot, if any were provided. */\nexport function getReturnsSlotAppearance(\n resolved: ResolvedReturnsAppearance,\n slot: ReturnsSlotName,\n): ReturnsSlotAppearance | undefined {\n return getSlotAppearance(resolved.elements, slot);\n}\n","import { createContext, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport {\n getReturnsSlotAppearance,\n resolveReturnsAppearance,\n type ResolvedReturnsAppearance,\n type ReturnsAppearance,\n type ReturnsSlotAppearance,\n type ReturnsSlotName,\n} from \"./appearance\";\n\nconst ReturnsAppearanceContext = createContext<ResolvedReturnsAppearance>(\n resolveReturnsAppearance(),\n);\n\n/**\n * Returns scoped appearance provider. It only wraps the returns views, so the\n * configuration never leaks into checkout, the panel or the host page.\n */\nexport function ReturnsAppearanceProvider({\n appearance,\n children,\n}: {\n appearance?: ReturnsAppearance;\n children: ReactNode;\n}) {\n const resolved = useMemo(\n () => resolveReturnsAppearance(appearance),\n [appearance],\n );\n\n return (\n <ReturnsAppearanceContext.Provider value={resolved}>\n {children}\n </ReturnsAppearanceContext.Provider>\n );\n}\n\nexport function useReturnsAppearance(): ResolvedReturnsAppearance {\n return useContext(ReturnsAppearanceContext);\n}\n\n/**\n * Returns the caller overrides for a slot, meant to be merged with the\n * built-in presentation:\n *\n * ```tsx\n * const slot = useReturnsSlot(\"title\");\n *\n * return <h2 className={cn(\"text-xl font-semibold\", slot.className)} style={slot.style} />;\n * ```\n */\nexport function useReturnsSlot(slot: ReturnsSlotName): ReturnsSlotAppearance {\n const resolved = useReturnsAppearance();\n\n return getReturnsSlotAppearance(resolved, slot) ?? {};\n}\n","import { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport { brandColorTokens } from \"./color\";\nimport type { ReturnsTexts } from \"./texts\";\n\n/**\n * Compatibility layer for the `bitsnap-react` 1.6.0 returns widget. Everything\n * here is pure; the components and hooks apply it at their boundary.\n */\n\n/** Environment as a string or as the proto enum used by 1.6.0. */\nexport type ReturnsEnvironmentInput = \"production\" | \"test\" | Environment;\n\n/** Text keys of the 1.6.0 widget. */\nexport type LegacyReturnsTexts = Partial<{\n title: string;\n email: string;\n sendCode: string;\n code: string;\n verify: string;\n orders: string;\n submit: string;\n note: string;\n loading: string;\n history: string;\n}>;\n\n/** Our text keys plus the 1.6.0 ones. Our keys win when both are given. */\nexport type ReturnsTextsInput = Partial<ReturnsTexts> & LegacyReturnsTexts;\n\n/** 1.6.0 `theme` prop. */\nexport type LegacyReturnsTheme = { brandColor?: string };\n\n/** Backend environment for a string or enum value. Defaults to production. */\nexport function resolveReturnsEnvironment(\n environment?: ReturnsEnvironmentInput,\n): Environment {\n return environment === \"test\" || environment === Environment.TEST\n ? Environment.TEST\n : Environment.PRODUCTION;\n}\n\nconst LEGACY_TEXT_KEYS: Record<\n Exclude<keyof LegacyReturnsTexts, \"loading\">,\n readonly (keyof ReturnsTexts)[]\n> = {\n title: [\"emailStepTitle\"],\n email: [\"emailLabel\"],\n sendCode: [\"emailSubmit\"],\n code: [\"codeLabel\"],\n verify: [\"codeSubmit\"],\n orders: [\"ordersTitle\"],\n submit: [\"confirmationSubmit\"],\n note: [\"noteLabel\"],\n history: [\"myReturnsTitle\", \"myReturnsLink\"],\n};\n\n/**\n * Maps 1.6.0 text keys onto ours. A key of the new API always wins over the\n * legacy key that maps to it. `loading` has the same name in both.\n */\nexport function mapLegacyTexts(\n texts: ReturnsTextsInput | undefined,\n): Partial<ReturnsTexts> | undefined {\n if (texts == null) {\n return undefined;\n }\n\n const result: Partial<ReturnsTexts> = {};\n for (const [legacyKey, targets] of Object.entries(LEGACY_TEXT_KEYS) as [\n keyof typeof LEGACY_TEXT_KEYS,\n readonly (keyof ReturnsTexts)[],\n ][]) {\n const value = texts[legacyKey];\n if (typeof value === \"string\") {\n for (const target of targets) {\n result[target] = value;\n }\n }\n }\n\n for (const key of Object.keys(texts) as (keyof ReturnsTextsInput)[]) {\n if (key in LEGACY_TEXT_KEYS) {\n continue;\n }\n const value = texts[key];\n if (typeof value === \"string\") {\n result[key as keyof ReturnsTexts] = value;\n }\n }\n\n return result;\n}\n\n/**\n * Appearance with the 1.6.0 `brandColor` applied as button background, focus\n * ring and readable button foreground. Explicit `appearance.tokens` win.\n */\nexport function resolveBrandAppearance(\n appearance: ReturnsAppearance | undefined,\n theme: LegacyReturnsTheme | undefined,\n): ReturnsAppearance | undefined {\n const color = theme?.brandColor?.trim();\n if (color == null || color === \"\") {\n return appearance;\n }\n return {\n ...appearance,\n tokens: { ...brandColorTokens(color), ...appearance?.tokens },\n };\n}\n\n/** Arguments of the paged hooks in either call style. */\nexport type PagedArguments = {\n pageSize: number;\n /** Explicit page token of the positional (1.6.0) form. */\n explicitPageToken: string | undefined;\n};\n\n/**\n * Normalizes `(pageSize?, pageToken?)` (1.6.0) and `({ pageSize })` (ours).\n * Both forms default to 20 items, like 1.6.0.\n */\nexport function resolvePagedArguments(\n first: number | { pageSize?: number } | undefined,\n pageToken: string | undefined,\n): PagedArguments {\n if (typeof first === \"object\" && first != null) {\n return { pageSize: first.pageSize ?? 20, explicitPageToken: undefined };\n }\n if (typeof first === \"number\" || pageToken !== undefined) {\n return { pageSize: first ?? 20, explicitPageToken: pageToken ?? \"\" };\n }\n return { pageSize: 20, explicitPageToken: undefined };\n}\n","import { lookupText, resolveTexts, type LocaleTables } from \"@/src/lib/texts\";\n\n/**\n * Every string the returns views render. Pass a partial object through the\n * `texts` prop of `BitsnapReturns`/`ReturnsProvider` to override any of them,\n * whatever the locale. Strings with `{name}` placeholders keep them in\n * overrides; unknown placeholders are left untouched.\n */\nexport type ReturnsTexts = {\n // Frame\n /** Label of the back buttons. */\n back: string;\n /** Step indicator, placeholders `{current}` and `{total}`. */\n stepIndicator: string;\n /** Skeleton accessible label. */\n loading: string;\n /** Button that opens the list of previous returns. */\n myReturnsLink: string;\n\n // Email step\n emailStepTitle: string;\n emailStepDescription: string;\n emailLabel: string;\n emailPlaceholder: string;\n emailSubmit: string;\n\n // Code step\n codeStepTitle: string;\n /** Placeholder `{email}`. */\n codeStepDescription: string;\n codeLabel: string;\n codeSubmit: string;\n resend: string;\n /** Placeholder `{seconds}`. */\n resendIn: string;\n logout: string;\n\n // Orders\n ordersTitle: string;\n ordersDescription: string;\n ordersEmpty: string;\n /** Placeholder `{reference}`. */\n orderTitle: string;\n /** Placeholder `{count}`. */\n orderReturnableLines: string;\n orderSelect: string;\n paginationPrevious: string;\n paginationNext: string;\n /** Placeholders `{page}` and `{total}` (number of orders). */\n paginationInfo: string;\n\n // Order detail\n /** Placeholder `{reference}`. */\n orderDetailTitle: string;\n orderDetailDescription: string;\n /** Placeholder `{name}`. */\n quantityLabel: string;\n /** Placeholder `{name}`. */\n quantityDecrease: string;\n /** Placeholder `{name}`. */\n quantityIncrease: string;\n /** Placeholder `{available}`. */\n quantityOfAvailable: string;\n /** Shown for an ineligible line without a reason from the backend. */\n lineIneligibleFallback: string;\n noteLabel: string;\n notePlaceholder: string;\n selectionContinue: string;\n selectionEmpty: string;\n previousReturnsTitle: string;\n\n // Confirmation\n confirmationTitle: string;\n confirmationDescription: string;\n confirmationSummary: string;\n /** Placeholder `{quantity}`. */\n confirmationQuantity: string;\n confirmationNote: string;\n confirmationSubmit: string;\n\n // Result\n successTitle: string;\n successDescription: string;\n successReference: string;\n successInstructions: string;\n successDone: string;\n\n // My returns\n myReturnsTitle: string;\n myReturnsDescription: string;\n myReturnsEmpty: string;\n myReturnOpen: string;\n myReturnDetailTitle: string;\n /** Placeholder `{reference}`. */\n myReturnTitle: string;\n myReturnCreatedAt: string;\n myReturnRefund: string;\n myReturnLines: string;\n /** Placeholders `{requested}`, `{approved}`, `{received}`. */\n myReturnLineQuantities: string;\n myReturnNote: string;\n myReturnHistory: string;\n\n // Request status labels\n statusSubmitted: string;\n statusApproved: string;\n statusRejected: string;\n statusAwaitingReceipt: string;\n statusReceived: string;\n statusCompleted: string;\n statusCancelled: string;\n statusRefunded: string;\n /** Any status the backend adds later. */\n statusFallback: string;\n\n // Refund status labels\n refundStatusNotStarted: string;\n refundStatusPending: string;\n refundStatusSucceeded: string;\n refundStatusFailed: string;\n refundStatusFallback: string;\n\n // Error messages\n errorGeneric: string;\n errorInvalidEmail: string;\n errorInvalidCode: string;\n errorSessionExpired: string;\n errorOrderNotFound: string;\n errorReturnNotFound: string;\n errorQuantityUnavailable: string;\n errorItemNotReturnable: string;\n errorReturnsDisabled: string;\n errorRateLimited: string;\n errorIdempotencyConflict: string;\n errorDeliveryFailed: string;\n errorRetry: string;\n};\n\nexport type ReturnsTextKey = keyof ReturnsTexts;\n\nexport const RETURNS_TEXT_TABLES: LocaleTables<ReturnsTextKey> = {\n en: {\n back: \"Back\",\n stepIndicator: \"Step {current} of {total}\",\n loading: \"Loading\",\n myReturnsLink: \"My returns\",\n\n emailStepTitle: \"Return a product\",\n emailStepDescription:\n \"Enter the email address you used for the order. We will send you a verification code.\",\n emailLabel: \"Email address\",\n emailPlaceholder: \"name@example.com\",\n emailSubmit: \"Send code\",\n\n codeStepTitle: \"Enter the code\",\n codeStepDescription: \"We sent a verification code to {email}.\",\n codeLabel: \"Verification code\",\n codeSubmit: \"Verify\",\n resend: \"Send the code again\",\n resendIn: \"Send again in {seconds} s\",\n logout: \"Sign out\",\n\n ordersTitle: \"Your orders\",\n ordersDescription: \"Choose the order that contains the product to return.\",\n ordersEmpty: \"There are no orders eligible for return.\",\n orderTitle: \"Order {reference}\",\n orderReturnableLines: \"Products available to return: {count}\",\n orderSelect: \"Choose\",\n paginationPrevious: \"Previous\",\n paginationNext: \"Next\",\n paginationInfo: \"Page {page}, {total} orders\",\n\n orderDetailTitle: \"Order {reference}\",\n orderDetailDescription: \"Select the products and quantities to return.\",\n quantityLabel: \"Quantity to return: {name}\",\n quantityDecrease: \"Decrease quantity: {name}\",\n quantityIncrease: \"Increase quantity: {name}\",\n quantityOfAvailable: \"of {available}\",\n lineIneligibleFallback: \"This product cannot be returned.\",\n noteLabel: \"Note (optional)\",\n notePlaceholder: \"Tell us why you are returning the product\",\n selectionContinue: \"Continue\",\n selectionEmpty: \"Select at least one item to return.\",\n previousReturnsTitle: \"Earlier returns for this order\",\n\n confirmationTitle: \"Confirm the return\",\n confirmationDescription: \"Check the products before you submit the request.\",\n confirmationSummary: \"Products to return\",\n confirmationQuantity: \"Quantity: {quantity}\",\n confirmationNote: \"Your note\",\n confirmationSubmit: \"Submit return request\",\n\n successTitle: \"Return request submitted\",\n successDescription: \"We received your request and will keep you posted.\",\n successReference: \"Request number\",\n successInstructions: \"What to do next\",\n successDone: \"Back to orders\",\n\n myReturnsTitle: \"My returns\",\n myReturnsDescription: \"Track the status of your return requests.\",\n myReturnsEmpty: \"You have not submitted any return requests yet.\",\n myReturnOpen: \"Details\",\n myReturnDetailTitle: \"Return details\",\n myReturnTitle: \"Return {reference}\",\n myReturnCreatedAt: \"Submitted\",\n myReturnRefund: \"Refund\",\n myReturnLines: \"Products\",\n myReturnLineQuantities:\n \"Requested: {requested}, approved: {approved}, received: {received}\",\n myReturnNote: \"Your note\",\n myReturnHistory: \"History\",\n\n statusSubmitted: \"Submitted\",\n statusApproved: \"Approved\",\n statusRejected: \"Rejected\",\n statusAwaitingReceipt: \"Awaiting the package\",\n statusReceived: \"Package received\",\n statusCompleted: \"Completed\",\n statusCancelled: \"Cancelled\",\n statusRefunded: \"Refunded\",\n statusFallback: \"In progress\",\n\n refundStatusNotStarted: \"Not started\",\n refundStatusPending: \"Refund in progress\",\n refundStatusSucceeded: \"Refunded\",\n refundStatusFailed: \"Refund failed\",\n refundStatusFallback: \"Unknown\",\n\n errorGeneric: \"Something went wrong. Please try again.\",\n errorInvalidEmail: \"Enter a valid email address.\",\n errorInvalidCode: \"The code is invalid or has expired.\",\n errorSessionExpired: \"Your session has expired. Verify your email again.\",\n errorOrderNotFound: \"We could not find this order.\",\n errorReturnNotFound: \"We could not find this return request.\",\n errorQuantityUnavailable:\n \"The selected quantity is no longer available for return.\",\n errorItemNotReturnable: \"One of the selected products cannot be returned.\",\n errorReturnsDisabled: \"Returns are not available in this shop.\",\n errorRateLimited: \"Too many attempts. Please try again later.\",\n errorIdempotencyConflict:\n \"This request was already submitted with different contents. Reload and try again.\",\n errorDeliveryFailed: \"We could not send the code. Please try again.\",\n errorRetry: \"Try again\",\n },\n pl: {\n back: \"Wstecz\",\n stepIndicator: \"Krok {current} z {total}\",\n loading: \"Ładowanie\",\n myReturnsLink: \"Moje zwroty\",\n\n emailStepTitle: \"Zwróć produkt\",\n emailStepDescription:\n \"Podaj adres e-mail użyty w zamówieniu. Wyślemy na niego kod weryfikacyjny.\",\n emailLabel: \"Adres e-mail\",\n emailPlaceholder: \"jan@example.com\",\n emailSubmit: \"Wyślij kod\",\n\n codeStepTitle: \"Wpisz kod\",\n codeStepDescription: \"Wysłaliśmy kod weryfikacyjny na adres {email}.\",\n codeLabel: \"Kod weryfikacyjny\",\n codeSubmit: \"Zweryfikuj\",\n resend: \"Wyślij kod ponownie\",\n resendIn: \"Wyślij ponownie za {seconds} s\",\n logout: \"Wyloguj się\",\n\n ordersTitle: \"Twoje zamówienia\",\n ordersDescription: \"Wybierz zamówienie z produktem do zwrotu.\",\n ordersEmpty: \"Brak zamówień, które można zwrócić.\",\n orderTitle: \"Zamówienie {reference}\",\n orderReturnableLines: \"Produkty do zwrotu: {count}\",\n orderSelect: \"Wybierz\",\n paginationPrevious: \"Poprzednia\",\n paginationNext: \"Następna\",\n paginationInfo: \"Strona {page}, zamówień: {total}\",\n\n orderDetailTitle: \"Zamówienie {reference}\",\n orderDetailDescription: \"Wybierz produkty i ilości do zwrotu.\",\n quantityLabel: \"Ilość do zwrotu: {name}\",\n quantityDecrease: \"Zmniejsz ilość: {name}\",\n quantityIncrease: \"Zwiększ ilość: {name}\",\n quantityOfAvailable: \"z {available}\",\n lineIneligibleFallback: \"Ten produkt nie podlega zwrotowi.\",\n noteLabel: \"Uwagi (opcjonalnie)\",\n notePlaceholder: \"Napisz, dlaczego zwracasz produkt\",\n selectionContinue: \"Dalej\",\n selectionEmpty: \"Wybierz co najmniej jedną sztukę do zwrotu.\",\n previousReturnsTitle: \"Wcześniejsze zwroty tego zamówienia\",\n\n confirmationTitle: \"Potwierdź zwrot\",\n confirmationDescription: \"Sprawdź produkty przed wysłaniem zgłoszenia.\",\n confirmationSummary: \"Produkty do zwrotu\",\n confirmationQuantity: \"Ilość: {quantity}\",\n confirmationNote: \"Twoje uwagi\",\n confirmationSubmit: \"Wyślij zgłoszenie zwrotu\",\n\n successTitle: \"Zgłoszenie zwrotu zostało wysłane\",\n successDescription: \"Otrzymaliśmy zgłoszenie i będziemy informować o jego statusie.\",\n successReference: \"Numer zgłoszenia\",\n successInstructions: \"Co dalej\",\n successDone: \"Wróć do zamówień\",\n\n myReturnsTitle: \"Moje zwroty\",\n myReturnsDescription: \"Sprawdź status swoich zgłoszeń zwrotu.\",\n myReturnsEmpty: \"Nie masz jeszcze żadnych zgłoszeń zwrotu.\",\n myReturnOpen: \"Szczegóły\",\n myReturnDetailTitle: \"Szczegóły zwrotu\",\n myReturnTitle: \"Zwrot {reference}\",\n myReturnCreatedAt: \"Zgłoszono\",\n myReturnRefund: \"Zwrot środków\",\n myReturnLines: \"Produkty\",\n myReturnLineQuantities:\n \"Zgłoszono: {requested}, zaakceptowano: {approved}, odebrano: {received}\",\n myReturnNote: \"Twoje uwagi\",\n myReturnHistory: \"Historia\",\n\n statusSubmitted: \"Zgłoszony\",\n statusApproved: \"Zaakceptowany\",\n statusRejected: \"Odrzucony\",\n statusAwaitingReceipt: \"Oczekiwanie na paczkę\",\n statusReceived: \"Paczka odebrana\",\n statusCompleted: \"Zakończony\",\n statusCancelled: \"Anulowany\",\n statusRefunded: \"Środki zwrócone\",\n statusFallback: \"W trakcie\",\n\n refundStatusNotStarted: \"Nie rozpoczęto\",\n refundStatusPending: \"Zwrot środków w toku\",\n refundStatusSucceeded: \"Środki zwrócone\",\n refundStatusFailed: \"Zwrot środków nie powiódł się\",\n refundStatusFallback: \"Nieznany\",\n\n errorGeneric: \"Coś poszło nie tak. Spróbuj ponownie.\",\n errorInvalidEmail: \"Podaj poprawny adres e-mail.\",\n errorInvalidCode: \"Kod jest nieprawidłowy lub wygasł.\",\n errorSessionExpired: \"Sesja wygasła. Zweryfikuj adres e-mail ponownie.\",\n errorOrderNotFound: \"Nie znaleziono tego zamówienia.\",\n errorReturnNotFound: \"Nie znaleziono tego zgłoszenia zwrotu.\",\n errorQuantityUnavailable:\n \"Wybrana ilość nie jest już dostępna do zwrotu.\",\n errorItemNotReturnable: \"Jeden z wybranych produktów nie podlega zwrotowi.\",\n errorReturnsDisabled: \"Zwroty nie są dostępne w tym sklepie.\",\n errorRateLimited: \"Zbyt wiele prób. Spróbuj ponownie później.\",\n errorIdempotencyConflict:\n \"To zgłoszenie zostało już wysłane z inną zawartością. Odśwież stronę i spróbuj ponownie.\",\n errorDeliveryFailed: \"Nie udało się wysłać kodu. Spróbuj ponownie.\",\n errorRetry: \"Spróbuj ponownie\",\n },\n};\n\n/** Default texts for a locale merged with the caller overrides. */\nexport function resolveReturnsTexts(\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): ReturnsTexts {\n return resolveTexts(RETURNS_TEXT_TABLES, locale, overrides);\n}\n\nexport function getReturnsText(\n key: ReturnsTextKey,\n locale: string,\n overrides?: Partial<ReturnsTexts>,\n): string {\n return lookupText(resolveReturnsTexts(locale, overrides), key);\n}\n\n/** Replaces `{name}` placeholders. Unknown placeholders stay as they are. */\nexport function fillText(\n template: string,\n values: Record<string, string | number>,\n): string {\n return template.replace(/\\{(\\w+)\\}/g, (match, name: string) =>\n Object.prototype.hasOwnProperty.call(values, name)\n ? String(values[name])\n : match,\n );\n}\n\nconst STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n submitted: \"statusSubmitted\",\n approved: \"statusApproved\",\n rejected: \"statusRejected\",\n awaiting_receipt: \"statusAwaitingReceipt\",\n received: \"statusReceived\",\n completed: \"statusCompleted\",\n cancelled: \"statusCancelled\",\n refunded: \"statusRefunded\",\n};\n\nconst REFUND_STATUS_TEXT_KEYS: Record<string, ReturnsTextKey> = {\n not_started: \"refundStatusNotStarted\",\n pending: \"refundStatusPending\",\n succeeded: \"refundStatusSucceeded\",\n failed: \"refundStatusFailed\",\n};\n\n/** Text key for a backend request status, with a fallback for unknown ones. */\nexport function statusTextKey(status: string): ReturnsTextKey {\n return STATUS_TEXT_KEYS[status] ?? \"statusFallback\";\n}\n\n/** Text key for a backend refund status, with a fallback for unknown ones. */\nexport function refundStatusTextKey(status: string): ReturnsTextKey {\n return REFUND_STATUS_TEXT_KEYS[status] ?? \"refundStatusFallback\";\n}\n","import { createContext, useCallback, useContext, useMemo } from \"react\";\nimport type { ReactNode } from \"react\";\nimport { getLocale } from \"@/src/components/checkout/locale\";\nimport {\n fillText,\n resolveReturnsTexts,\n type ReturnsTextKey,\n type ReturnsTexts,\n} from \"./texts\";\n\ntype ReturnsTextsContextValue = {\n /** Active locale (the `locale` prop or the library locale). */\n locale: string;\n texts: ReturnsTexts;\n};\n\nconst ReturnsTextsContext = createContext<ReturnsTextsContextValue>({\n locale: \"pl-PL\",\n texts: resolveReturnsTexts(\"pl-PL\"),\n});\n\n/**\n * Returns scoped texts provider. Carries the `texts` overrides and the\n * `locale` prop down to the returns tree.\n */\nexport function ReturnsTextsProvider({\n texts,\n locale,\n children,\n}: {\n texts?: Partial<ReturnsTexts>;\n locale?: string;\n children: ReactNode;\n}) {\n const activeLocale = locale ?? getLocale();\n const value = useMemo(\n () => ({\n locale: activeLocale,\n texts: resolveReturnsTexts(activeLocale, texts),\n }),\n [activeLocale, texts],\n );\n\n return (\n <ReturnsTextsContext.Provider value={value}>\n {children}\n </ReturnsTextsContext.Provider>\n );\n}\n\n/**\n * Returns a lookup for the returns strings: the caller override when provided,\n * otherwise the default for the locale. Optional `values` fill `{placeholders}`.\n */\nexport function useReturnsText(): (\n key: ReturnsTextKey,\n values?: Record<string, string | number>,\n) => string {\n const { texts } = useContext(ReturnsTextsContext);\n\n return useCallback(\n (key, values) =>\n values == null ? texts[key] : fillText(texts[key], values),\n [texts],\n );\n}\n\n/** Active locale of the returns views, for date and money formatting. */\nexport function useReturnsLocale(): string {\n return useContext(ReturnsTextsContext).locale;\n}\n","import { createClient } from \"@connectrpc/connect\";\nimport {\n createConnectQueryKey,\n TransportProvider,\n} from \"@connectrpc/connect-query\";\nimport {\n QueryClient,\n QueryClientContext,\n QueryClientProvider,\n useQueryClient,\n} from \"@tanstack/react-query\";\nimport {\n createContext,\n useCallback,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { CSSProperties, ReactNode } from \"react\";\nimport { Environment } from \"@/src/gen/proto/common/v1/environment_pb\";\nimport { ReturnsService } from \"@/src/gen/proto/public/v1/returns_pb\";\nimport {\n InstrumentProvider,\n useInstrument,\n type AnalyticsOption,\n} from \"@/src/analytics/instrument\";\nimport { cn } from \"@/src/lib/utils\";\nimport { getRpcTransport, getTransportHost } from \"@/src/rpc-provider\";\nimport type { Transport } from \"@connectrpc/connect\";\nimport type { ReturnsAppearance } from \"./appearance\";\nimport {\n ReturnsAppearanceProvider,\n useReturnsAppearance,\n useReturnsSlot,\n} from \"./appearance.context\";\nimport {\n clearStoredSession,\n expiryToMillis,\n getBrowserSessionStorage,\n readStoredSession,\n writeStoredSession,\n type StoredReturnsSession,\n} from \"./session-storage\";\nimport {\n mapLegacyTexts,\n resolveBrandAppearance,\n resolveReturnsEnvironment,\n type LegacyReturnsTheme,\n type ReturnsEnvironmentInput,\n type ReturnsTextsInput,\n} from \"./legacy\";\nimport { ReturnsTextsProvider } from \"./texts.context\";\n\n/**\n * Backend environment the returns calls run against. The library has no other\n * environment switch for public API calls, so this defaults to `\"production\"`.\n */\nexport type ReturnsEnvironment = \"production\" | \"test\";\n\nexport type ReturnsSessionStatus =\n /** Server render and first client render: storage has not been read yet. */\n | \"hydrating\"\n /** A `panelAccessToken` is being exchanged for a returns session. */\n | \"exchanging\"\n | \"anonymous\"\n | \"authenticated\";\n\n/** A pending email verification. */\nexport type ReturnsChallenge = {\n challengeId: string;\n email: string;\n /** Unix milliseconds when the next code may be requested. */\n resendAvailableAt: number;\n};\n\nexport type ReturnsContextValue = {\n projectID: string;\n environment: Environment;\n status: ReturnsSessionStatus;\n /** Session token. Never log it. */\n token: string | undefined;\n /** Failure of the last panel token exchange, if any. */\n exchangeError: unknown;\n challenge: ReturnsChallenge | undefined;\n setChallenge: (challenge: ReturnsChallenge | undefined) => void;\n /** Stores a freshly issued session in state and `sessionStorage`. */\n authenticate: (session: StoredReturnsSession) => void;\n /** Drops the session, the pending challenge and cached customer data. */\n clearSession: () => void;\n};\n\nconst ReturnsContext = createContext<ReturnsContextValue | undefined>(\n undefined,\n);\n\n/**\n * Context of the nearest `ReturnsProvider`. Throws a clear error outside of\n * it, naming the component or hook that was misplaced.\n */\nexport function useReturnsContext(name: string): ReturnsContextValue {\n const value = useContext(ReturnsContext);\n\n if (value == null) {\n throw new Error(`${name} must be rendered inside <ReturnsProvider>`);\n }\n\n return value;\n}\n\nexport type ReturnsProviderProps = {\n /** Bitsnap project ID. */\n projectID: string;\n /**\n * API host. Defaults to the host set with `setCustomHost`/`setHost`, then to\n * `https://bitsnap.pl`. Each provider keeps its own transport.\n */\n host?: string;\n /**\n * Backend environment, `\"production\"` unless set to `\"test\"`. The proto\n * `Environment` enum is accepted too.\n */\n environment?: ReturnsEnvironmentInput;\n /** Theme, tokens and per-element overrides. */\n appearance?: ReturnsAppearance;\n /**\n * Text overrides, applied whatever the locale. The keys of `bitsnap-react`\n * 1.6.0 (`title`, `email`, `sendCode`, ...) are accepted too; our own keys\n * win when both are given.\n */\n texts?: ReturnsTextsInput;\n /** `bitsnap-react` 1.6.0 brand color. Explicit `appearance.tokens` win. */\n theme?: LegacyReturnsTheme;\n /** Locale of texts, dates and money. Defaults to the library locale. */\n locale?: string;\n /**\n * Customer panel access token. When set, it is exchanged for a returns\n * session on mount, so the customer needs no second verification code.\n * Changing or removing it drops the session.\n */\n panelAccessToken?: string;\n /** Class of the themed root element. */\n className?: string;\n /**\n * Usage statistics for your Bitsnap dashboard (return started, return\n * submitted). On by default; `false` turns it off. An object lets you\n * forward every event: `{ onEvent }`. Inside `<Panel>` the panel's setting\n * applies unless this is given. Nothing is stored on the visitor's device.\n */\n analytics?: AnalyticsOption;\n children?: ReactNode;\n};\n\n/** Key prefix that matches every returns query, for invalidation and removal. */\nexport function returnsQueryKey(): readonly unknown[] {\n return createConnectQueryKey({\n schema: ReturnsService,\n cardinality: undefined,\n });\n}\n\n/** Longest delay `setTimeout` accepts. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\nfunction SessionProvider({\n projectID,\n environment,\n transport,\n panelAccessToken,\n className,\n children,\n}: {\n projectID: string;\n environment: Environment;\n transport: Transport;\n panelAccessToken?: string;\n className?: string;\n children?: ReactNode;\n}) {\n const queryClient = useQueryClient();\n const { boundaryClassName, boundaryStyle } = useReturnsAppearance();\n const root = useReturnsSlot(\"root\");\n\n const [session, setSession] = useState<{\n status: ReturnsSessionStatus;\n token?: string;\n expiresAt?: number;\n }>({ status: \"hydrating\" });\n const [exchangeError, setExchangeError] = useState<unknown>();\n const [challenge, setChallenge] = useState<ReturnsChallenge>();\n const previousPanelToken = useRef<string | undefined>(undefined);\n\n const dropCachedData = useCallback(() => {\n // Query inputs carry the session token, so cached customer data must not\n // outlive the session. Only returns queries are touched.\n queryClient.removeQueries({ queryKey: returnsQueryKey() });\n }, [queryClient]);\n\n const clearSession = useCallback(() => {\n clearStoredSession(getBrowserSessionStorage(), projectID);\n setChallenge(undefined);\n setSession({ status: \"anonymous\" });\n dropCachedData();\n }, [projectID, dropCachedData]);\n\n const authenticate = useCallback(\n (next: StoredReturnsSession) => {\n writeStoredSession(getBrowserSessionStorage(), projectID, next);\n setExchangeError(undefined);\n setChallenge(undefined);\n setSession({\n status: \"authenticated\",\n token: next.token,\n expiresAt: next.expiresAt,\n });\n },\n [projectID],\n );\n\n // Hydrates from `sessionStorage`, or exchanges the panel token. Runs after\n // mount, so render never touches `window`.\n useEffect(() => {\n let cancelled = false;\n const storage = getBrowserSessionStorage();\n\n if (panelAccessToken == null || panelAccessToken === \"\") {\n const hadPanelToken = previousPanelToken.current != null;\n previousPanelToken.current = undefined;\n\n if (hadPanelToken) {\n clearSession();\n return;\n }\n\n const stored = readStoredSession(storage, projectID);\n setSession(\n stored != null\n ? {\n status: \"authenticated\",\n token: stored.token,\n expiresAt: stored.expiresAt,\n }\n : { status: \"anonymous\" },\n );\n return;\n }\n\n previousPanelToken.current = panelAccessToken;\n clearStoredSession(storage, projectID);\n dropCachedData();\n setExchangeError(undefined);\n setSession({ status: \"exchanging\" });\n\n createClient(ReturnsService, transport)\n .exchangePanelSession({\n projectId: projectID,\n accessToken: panelAccessToken,\n environment,\n })\n .then((response) => {\n if (cancelled) {\n return;\n }\n const expiresAt = expiryToMillis(response.expiresAt);\n if (response.sessionToken === \"\" || expiresAt == null) {\n throw new Error(\"EMPTY_SESSION\");\n }\n authenticate({ token: response.sessionToken, expiresAt });\n })\n .catch((error: unknown) => {\n if (cancelled) {\n return;\n }\n setExchangeError(error);\n setSession({ status: \"anonymous\" });\n });\n\n return () => {\n cancelled = true;\n };\n // `clearSession`, `authenticate` and `dropCachedData` only change with the\n // project or the query client, which are already covered.\n }, [panelAccessToken, projectID, environment, transport]);\n\n // Expired sessions are dropped even when the page stays open.\n useEffect(() => {\n if (session.status !== \"authenticated\" || session.expiresAt == null) {\n return;\n }\n const remaining = session.expiresAt - Date.now();\n if (remaining <= 0) {\n clearSession();\n return;\n }\n const timer = setTimeout(\n clearSession,\n Math.min(remaining, MAX_TIMEOUT_MS),\n );\n return () => clearTimeout(timer);\n }, [session.status, session.expiresAt, clearSession]);\n\n const value = useMemo<ReturnsContextValue>(\n () => ({\n projectID,\n environment,\n status: session.status,\n token: session.token,\n exchangeError,\n challenge,\n setChallenge,\n authenticate,\n clearSession,\n }),\n [\n projectID,\n environment,\n session.status,\n session.token,\n exchangeError,\n challenge,\n authenticate,\n clearSession,\n ],\n );\n\n return (\n <ReturnsContext.Provider value={value}>\n <div\n data-bitsnap-returns=\"root\"\n data-bitsnap-returns-slot=\"root\"\n className={cn(\"bitsnap-react\", boundaryClassName, className, root.className)}\n style={{ ...boundaryStyle, ...root.style } as CSSProperties}\n >\n {children}\n </div>\n </ReturnsContext.Provider>\n );\n}\n\n/**\n * Holds everything the returns views share: the per-instance transport, the\n * query client (when the app has none), appearance, texts and the returns\n * session. It renders the themed root element, so step components composed\n * under it are themed without extra markup.\n *\n * ```tsx\n * <ReturnsProvider projectID=\"…\" appearance={brand}>\n * <ReturnsOrderList onSelectOrder={setOrderId} />\n * </ReturnsProvider>\n * ```\n */\nexport function ReturnsProvider({\n projectID,\n host,\n environment,\n appearance,\n texts,\n theme,\n locale,\n panelAccessToken,\n className,\n analytics,\n children,\n}: ReturnsProviderProps) {\n const instrument = useInstrument(projectID, analytics, \"returns\");\n const existingQueryClient = useContext(QueryClientContext);\n const [ownQueryClient] = useState(() =>\n existingQueryClient == null\n ? new QueryClient({ defaultOptions: { queries: { staleTime: 5000 } } })\n : undefined,\n );\n\n const resolvedHost = host ?? getTransportHost();\n const transport = useMemo(\n () => getRpcTransport(resolvedHost),\n [resolvedHost],\n );\n\n const brandColor = theme?.brandColor;\n const resolvedAppearance = useMemo(\n () => resolveBrandAppearance(appearance, { brandColor }),\n [appearance, brandColor],\n );\n const resolvedTexts = useMemo(() => mapLegacyTexts(texts), [texts]);\n\n const content = (\n <InstrumentProvider value={instrument}>\n <TransportProvider transport={transport}>\n <ReturnsAppearanceProvider appearance={resolvedAppearance}>\n <ReturnsTextsProvider texts={resolvedTexts} locale={locale}>\n <SessionProvider\n projectID={projectID}\n environment={resolveReturnsEnvironment(environment)}\n transport={transport}\n panelAccessToken={panelAccessToken}\n className={className}\n >\n {children}\n </SessionProvider>\n </ReturnsTextsProvider>\n </ReturnsAppearanceProvider>\n </TransportProvider>\n </InstrumentProvider>\n );\n\n return existingQueryClient == null && ownQueryClient != null ? (\n <QueryClientProvider client={ownQueryClient}>{content}</QueryClientProvider>\n ) : (\n content\n );\n}\n\n/** Name of {@link ReturnsProvider} in `bitsnap-react` 1.6.0. */\nexport const BitsnapReturnsProvider = ReturnsProvider;\n\nexport type BitsnapReturnsProviderProps = ReturnsProviderProps;\n","import { timestampMs, type Timestamp } from \"@bufbuild/protobuf/wkt\";\n\n/** Returns session as kept in `sessionStorage`. */\nexport type StoredReturnsSession = {\n token: string;\n /** Expiry as unix milliseconds. */\n expiresAt: number;\n};\n\n/** The part of `Storage` the session code needs. */\nexport type SessionStorageLike = Pick<\n Storage,\n \"getItem\" | \"setItem\" | \"removeItem\"\n>;\n\nconst KEY_PREFIX = \"bitsnap-returns-session:\";\n\n/** One key per project, so projects on the same page never share a session. */\nexport function sessionStorageKey(projectID: string): string {\n return `${KEY_PREFIX}${projectID}`;\n}\n\n/**\n * `window.sessionStorage` when it is usable, otherwise `undefined`. Safe to\n * call on the server and where storage access throws (blocked cookies).\n */\nexport function getBrowserSessionStorage(): SessionStorageLike | undefined {\n try {\n return typeof window !== \"undefined\" ? window.sessionStorage : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads the stored session. Malformed and expired entries are removed and\n * reported as no session.\n */\nexport function readStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n now: number = Date.now(),\n): StoredReturnsSession | undefined {\n if (storage == null) {\n return undefined;\n }\n\n const key = sessionStorageKey(projectID);\n\n try {\n const raw = storage.getItem(key);\n if (raw == null) {\n return undefined;\n }\n\n const parsed: unknown = JSON.parse(raw);\n if (\n parsed != null &&\n typeof parsed === \"object\" &&\n typeof (parsed as StoredReturnsSession).token === \"string\" &&\n (parsed as StoredReturnsSession).token.length > 0 &&\n typeof (parsed as StoredReturnsSession).expiresAt === \"number\" &&\n (parsed as StoredReturnsSession).expiresAt > now\n ) {\n const { token, expiresAt } = parsed as StoredReturnsSession;\n return { token, expiresAt };\n }\n\n storage.removeItem(key);\n } catch {\n try {\n storage.removeItem(key);\n } catch {\n // Storage is unusable; nothing else to clean up.\n }\n }\n\n return undefined;\n}\n\nexport function writeStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n session: StoredReturnsSession,\n): void {\n try {\n storage?.setItem(sessionStorageKey(projectID), JSON.stringify(session));\n } catch {\n // The session still works in memory when storage is full or blocked.\n }\n}\n\nexport function clearStoredSession(\n storage: SessionStorageLike | undefined,\n projectID: string,\n): void {\n try {\n storage?.removeItem(sessionStorageKey(projectID));\n } catch {\n // Nothing to do when storage is blocked.\n }\n}\n\n/** Expiry of a backend session in unix milliseconds, `undefined` when missing. */\nexport function expiryToMillis(\n expiresAt: Timestamp | undefined,\n): number | undefined {\n return expiresAt == null ? undefined : timestampMs(expiresAt);\n}\n"]}
|