@kanorio/elements 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{KanorioAccount-GXRAMZCI.js → KanorioAccount-BGIMYMGL.js} +2 -2
- package/dist/{KanorioAccount-P6IIPIZ2.js → KanorioAccount-E3NDKUX5.js} +2 -2
- package/dist/{KanorioAnalytics-XHKBWYTS.js → KanorioAnalytics-CNEIZ4VZ.js} +2 -2
- package/dist/{KanorioAnalytics-KYTK3T2L.js → KanorioAnalytics-RTCJ62AP.js} +2 -2
- package/dist/KanorioCurriculum-CDHXCPSI.js +2 -0
- package/dist/{KanorioCurriculum-SQ4S3U5T.js → KanorioCurriculum-JIKUHPOJ.js} +2 -2
- package/dist/{KanorioForm-FDS5UKUT.js → KanorioForm-QU243SAP.js} +2 -2
- package/dist/{KanorioForm-K3H3YUQH.js → KanorioForm-W6XBJW74.js} +2 -2
- package/dist/{KanorioLightbox-QPJQJLNO.js → KanorioLightbox-2YTEYM57.js} +2 -2
- package/dist/{KanorioLightbox-WBMR7MLG.js → KanorioLightbox-WCQ4NW5Z.js} +2 -2
- package/dist/{KanorioLogin-QMPBTK55.js → KanorioLogin-CDSAAJJE.js} +2 -2
- package/dist/{KanorioLogin-JMHHBRU7.js → KanorioLogin-OYIESFJL.js} +2 -2
- package/dist/{KanorioMedia-5P63OK4U.js → KanorioMedia-BEFSUKSN.js} +2 -2
- package/dist/KanorioMedia-ZGHENDE3.js +2 -0
- package/dist/KanorioReviews-O67GJZ24.js +2 -0
- package/dist/{KanorioReviews-AAQ27MYU.js → KanorioReviews-V5RUA2TV.js} +2 -2
- package/dist/KanorioUnit-2FXOUNOP.js +2 -0
- package/dist/{KanorioUnit-YBKFHGLB.js → KanorioUnit-AIM4O7QI.js} +2 -2
- package/dist/account.js +1 -1
- package/dist/analytics.js +1 -1
- package/dist/bot-protection.js +1 -1
- package/dist/{chunk-RI64PHGM.js → chunk-73S6VKNV.js} +2 -2
- package/dist/{chunk-QRKYFFDH.js → chunk-7UCZ56EJ.js} +2 -2
- package/dist/{chunk-HAHAYDYM.js → chunk-A4ZGBTRT.js} +2 -2
- package/dist/{chunk-GWUOOGNK.js → chunk-DIHLDYIG.js} +2 -2
- package/dist/{chunk-RTF2NUMK.js → chunk-EGMCB2MQ.js} +2 -2
- package/dist/{chunk-WKKPZXK3.js → chunk-FFSPNYLJ.js} +2 -2
- package/dist/{chunk-G5673RJK.js → chunk-FXDWRWZ3.js} +2 -2
- package/dist/{chunk-IDY2ZCXL.js → chunk-I6KLZIN6.js} +2 -2
- package/dist/{chunk-SB5665ZK.js → chunk-J24HGQ7U.js} +2 -2
- package/dist/{chunk-CIVS7LYU.js → chunk-JYBSXLT3.js} +2 -2
- package/dist/{chunk-EGJ6SNTR.js → chunk-N4Y3DCC6.js} +2 -2
- package/dist/{chunk-SGFVHVLE.js → chunk-OSXFUIAV.js} +2 -2
- package/dist/{chunk-R5M6FXXQ.js → chunk-UWRJBUJY.js} +2 -2
- package/dist/{chunk-CD7JDUB6.js → chunk-VRD67HVO.js} +2 -2
- package/dist/{chunk-J5SMJRYC.js → chunk-VT2B53EX.js} +2 -2
- package/dist/{chunk-OWXGUUSI.js → chunk-W5QS3RHM.js} +2 -2
- package/dist/{chunk-CMYBXWO5.js → chunk-XJPS3G7J.js} +2 -2
- package/dist/curriculum.js +1 -1
- package/dist/form.js +1 -1
- package/dist/index.js +1 -1
- package/dist/kanorio-elements.js +1 -1
- package/dist/lightbox.js +1 -1
- package/dist/login.js +1 -1
- package/dist/media.js +1 -1
- package/dist/provider.js +1 -1
- package/dist/reviews.js +1 -1
- package/dist/unit.js +1 -1
- package/dist/web-components.js +1 -1
- package/package.json +2 -2
- package/dist/KanorioCurriculum-3TLNLUL4.js +0 -2
- package/dist/KanorioMedia-LONTU7H2.js +0 -2
- package/dist/KanorioReviews-LUB4KF23.js +0 -2
- package/dist/KanorioUnit-ADFQ7POH.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{a as He}from"./chunk-ARU5PTJV.js";import{a as pe,b as ge,c as Ue,d as he,g as ne}from"./chunk-KW2CH7SS.js";import{a as Me,c as Be}from"./chunk-WJPCDZSL.js";import{a as Le}from"./chunk-2J5XQK4H.js";import{a as Ie,b as _e}from"./chunk-IDY2ZCXL.js";import{b as fe}from"./chunk-GWUOOGNK.js";import{a as te,c as me,t as Oe}from"./chunk-CMYBXWO5.js";import{a as Ee}from"./chunk-MXGMJAWS.js";import{a as Pe}from"./chunk-WP7UEAIB.js";import{b as ee}from"./chunk-2E6RCDAA.js";import{a as Ae}from"./chunk-U7KVGD47.js";import{$ as we,A as Re,Y as de,ba as _}from"./chunk-S2NFWI7C.js";import{b as Te}from"./chunk-AFNEGNVJ.js";import{a as N}from"./chunk-OU4IOHLN.js";import{a as ce,b as ke}from"./chunk-DLJDYXKL.js";import{a as it}from"./chunk-NSY72ZYX.js";import{a as W}from"./chunk-6LGTFWQS.js";import{c as h}from"./chunk-CDG7S4P5.js";var U=h(W(),1);var Ve=h(N());var ut=h(N());var Ke=h(N());var De=h(W());var $e=h(N());var m=h(W());var k=h(W()),je=h(it());var x=h(N()),ve='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function We({open:e,onClose:n,title:t,closeLabel:s,children:i,footer:a,showHeader:l=!0,dismissible:o=!0,desktopZIndexClassName:u="z-[var(--z-dialog,200)]",drawerZIndexClassName:r="z-[var(--z-dialog,200)]",maxWidthClassName:c="max-w-lg",desktopVariant:f="dialog",surface:v="glass",headerSlot:A,subheader:P,bodyClassName:L,footerClassName:y,id:K}){let g=f==="side",w=Le(),C=Ae(),I=(0,k.useRef)(n),R=(0,k.useRef)(o);(0,k.useEffect)(()=>{I.current=n,R.current=o}),(0,k.useEffect)(()=>{if(!e)return;let S=Ee(),E=j=>{j.key==="Escape"&&R.current&&I.current()};return document.addEventListener("keydown",E),()=>{S(),document.removeEventListener("keydown",E)}},[e]);let T=(0,k.useRef)(null),G=(0,k.useRef)(null),D=(0,k.useRef)(null),Y=(0,k.useRef)(null),B=(0,k.useRef)(null),H=(0,k.useRef)(0),d=w?w.slots.modal:C?document.body:null,O=e&&!!d;(0,k.useEffect)(()=>{if(!O)return;let S=T.current;if(!S)return;let E=document.activeElement instanceof HTMLElement?document.activeElement:null,j=()=>Array.from(S.querySelectorAll(ve)).filter(z=>!z.hasAttribute("disabled")&&z.getAttribute("aria-hidden")!=="true"),le=G.current?.querySelector(ve),st=D.current?.querySelector(ve);(le??st??j()[0]??S).focus({preventScroll:!0});let Ce=z=>{if(z.key!=="Tab")return;let Q=j();if(Q.length===0){z.preventDefault(),S.focus();return}let xe=Q[0],Se=Q[Q.length-1],Z=document.activeElement,Ne=Z instanceof Node&&S.contains(Z);z.shiftKey?(!Ne||Z===xe||Z===S)&&(z.preventDefault(),Se.focus()):(!Ne||Z===Se)&&(z.preventDefault(),xe.focus())};return document.addEventListener("keydown",Ce),()=>{document.removeEventListener("keydown",Ce),E&&E.isConnected&&E.focus({preventScroll:!0})}},[O]);let $=(0,k.useCallback)(S=>{if(!R.current)return;let E=S.target instanceof Node?S.target:null,j=!!E&&!!Y.current?.contains(E),le=(D.current?.scrollTop??0)<=0;!j&&!le||(B.current=S.touches[0].clientY,H.current=0)},[]),q=(0,k.useCallback)(S=>{if(B.current==null)return;let E=S.touches[0].clientY-B.current;if(E<0&&(D.current?.scrollTop??0)>0){B.current=null,T.current&&(T.current.style.transform="");return}H.current=E,E>0&&T.current&&(T.current.style.transform=`translateY(${E}px)`)},[]),X=(0,k.useCallback)(()=>{B.current!=null&&(T.current&&(T.current.style.transform=""),H.current>100&&R.current&&I.current(),B.current=null,H.current=0)},[]);if(!O)return null;let J=(0,x.jsx)("button",{type:"button",onClick:n,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})}),M=(0,x.jsx)("button",{type:"button",onClick:n,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})});return(0,je.createPortal)((0,x.jsxs)("div",{className:_("pointer-events-auto fixed inset-0 flex items-end justify-center",g?"md:items-stretch md:justify-end":"md:items-center md:p-4",u,r),role:"dialog","aria-modal":"true","aria-label":t,children:[(0,x.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:o?n:void 0,"aria-hidden":"true"}),(0,x.jsxs)("div",{id:K,ref:T,tabIndex:-1,onTouchStart:$,onTouchMove:q,onTouchEnd:X,className:_("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",g?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",v==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",c),children:[(0,x.jsxs)("div",{ref:Y,className:"flex shrink-0 flex-col",children:[o&&(0,x.jsx)("button",{type:"button",onClick:n,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":s,children:(0,x.jsx)("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),l?(0,x.jsxs)("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[A??(0,x.jsx)("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:t}),A&&(0,x.jsx)("h2",{className:"sr-only",children:t}),o&&J]}):o&&M]}),P&&(0,x.jsx)("div",{ref:G,className:"shrink-0",children:P}),(0,x.jsx)("div",{ref:D,className:_("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",l?"p-4":"p-0",L),children:i}),a&&(0,x.jsx)("div",{className:_("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",y),children:a})]})]}),d)}var Xe=h(W());var b=h(W(),1);var re=h(N(),1),lt=Symbol.for("react.lazy"),oe=b[" use ".trim().toString()];function ct(e){return typeof e=="object"&&e!==null&&"then"in e}function Fe(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===lt&&"_payload"in e&&ct(e._payload)}function dt(e){let n=mt(e),t=b.forwardRef((s,i)=>{let{children:a,...l}=s;Fe(a)&&typeof oe=="function"&&(a=oe(a._payload));let o=b.Children.toArray(a),u=o.find(pt);if(u){let r=u.props.children,c=o.map(f=>f===u?b.Children.count(r)>1?b.Children.only(null):b.isValidElement(r)?r.props.children:null:f);return(0,re.jsx)(n,{...l,ref:i,children:b.isValidElement(r)?b.cloneElement(r,void 0,c):null})}return(0,re.jsx)(n,{...l,ref:i,children:a})});return t.displayName=`${e}.Slot`,t}var Ge=dt("Slot");function mt(e){let n=b.forwardRef((t,s)=>{let{children:i,...a}=t;if(Fe(i)&&typeof oe=="function"&&(i=oe(i._payload)),b.isValidElement(i)){let l=ht(i),o=gt(a,i.props);return i.type!==b.Fragment&&(o.ref=s?He(s,l):l),b.cloneElement(i,o)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${e}.SlotClone`,n}var ft=Symbol("radix.slottable");function pt(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ft}function gt(e,n){let t={...n};for(let s in n){let i=e[s],a=n[s];/^on[A-Z]/.test(s)?i&&a?t[s]=(...o)=>{let u=a(...o);return i(...o),u}:i&&(t[s]=i):s==="style"?t[s]={...i,...a}:s==="className"&&(t[s]=[i,a].filter(Boolean).join(" "))}return{...e,...t}}function ht(e){let n=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Ye=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,qe=we,Ze=(e,n)=>t=>{var s;if(n?.variants==null)return qe(e,t?.class,t?.className);let{variants:i,defaultVariants:a}=n,l=Object.keys(i).map(r=>{let c=t?.[r],f=a?.[r];if(c===null)return null;let v=Ye(c)||Ye(f);return i[r][v]}),o=t&&Object.entries(t).reduce((r,c)=>{let[f,v]=c;return v===void 0||(r[f]=v),r},{}),u=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((r,c)=>{let{class:f,className:v,...A}=c;return Object.entries(A).every(P=>{let[L,y]=P;return Array.isArray(y)?y.includes({...a,...o}[L]):{...a,...o}[L]===y})?[...r,f,v]:r},[]);return qe(e,l,u,t?.class,t?.className)};var Qe=h(N()),vt=Ze("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}}),Je=Xe.forwardRef(({className:e,variant:n,size:t,asChild:s=!1,...i},a)=>(0,Qe.jsx)(s?Ge:"button",{className:_(vt({variant:n,size:t,className:e})),ref:a,...i}));Je.displayName="Button";var V=h(N()),yt=Pe(()=>import("./CustomerAccountPanel-FXJEOS4F.js").then(e=>e.CustomerAccountPanel),()=>(0,V.jsx)("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:(0,V.jsx)(Re,{className:"h-5 w-5 animate-spin opacity-50"})}));function bt(){return typeof document>"u"?!1:document.cookie.split(";").some(e=>e.trim().startsWith(`${ge}=`))}function et(){typeof document>"u"||(document.cookie=`${ge}=; Max-Age=0; Path=/; SameSite=Lax`)}var ye=e=>`knr_customer_overview:${e}`;function tt(e){if(e===null)return"";let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Ct(e,n){try{let t=typeof sessionStorage>"u"?null:sessionStorage.getItem(ye(e));if(!t)return null;let s=JSON.parse(t);return!s||typeof s!="object"||!s.contact||s.session!==tt(n)?null:s}catch{return null}}function F(e,n,t){try{if(typeof sessionStorage>"u")return;if(n){let{id:s,email:i,name:a}=n.contact,l={session:tt(t),contact:{id:s,email:i,name:a},sections:n.sections,landing:n.landing};sessionStorage.setItem(ye(e),JSON.stringify(l))}else sessionStorage.removeItem(ye(e))}catch{}}var xt=[1e3,3e3,1e4],nt=(0,m.createContext)(null);function be({config:e,children:n}){let[t,s]=(0,m.useState)(null),[i,a]=(0,m.useState)([]),[l,o]=(0,m.useState)(null),[u,r]=(0,m.useState)("pending"),[c,f]=(0,m.useState)(!1),[v,A]=(0,m.useState)(!1),[P,L]=(0,m.useState)(0),y=(0,m.useMemo)(()=>e?.transport??he(),[e?.transport]),K=e?.sessionHint??bt,g=e?.siteId??null,w=e?.sessionKey??null,C=(0,m.useRef)(null),I=(0,m.useRef)(w);I.current=w;let R=(0,m.useCallback)(d=>{g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done"),d||L(O=>O+1)},[g]),T=(0,m.useCallback)(()=>{r("pending"),L(d=>d+1)},[]);(0,m.useEffect)(()=>{if(g===null)return;let d=C.current;if(C.current={siteId:g,sessionKey:w},!K()){F(g,null,w),f(!1),s(null),a([]),o(null),r("done");return}f(!0),(d===null||d.siteId!==g||d.sessionKey!==w)&&r("pending");let O=Ct(g,w);O?(s(O.contact),a(O.sections??[]),o(O.landing??null)):d!==null&&(d.siteId!==g||d.sessionKey!==null&&d.sessionKey!==w)&&(s(null),a([]),o(null));let $=!1,q=null,X=J=>{y.session().then(M=>{$||(F(g,M,w),M||et(),s(M?.contact??null),a(M?.sections??[]),o(M?.landing??null),r("done"))}).catch(()=>{if($)return;let M=xt[J];if(M!==void 0){q=setTimeout(()=>X(J+1),M);return}r(S=>S==="pending"?"failed":S)})};return X(0),()=>{$=!0,q!==null&&clearTimeout(q)}},[g,w,y,P]),(0,m.useEffect)(()=>{if(!e||typeof document>"u")return;let d=()=>{if(document.visibilityState!=="visible")return;let O=K();O&&t===null&&L($=>$+1),!O&&t!==null&&(F(e.siteId,null,w),s(null),a([]),o(null),r("done"))};return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d)}},[e,t]);let G=(0,m.useCallback)(async()=>{let d;try{d=await y.session()}catch{r("done");return}g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done")},[y,g]),D=(0,m.useCallback)(async()=>{await y.signOut(),g&&F(g,null,I.current),et(),s(null),a([]),o(null),r("done")},[y,g]),Y=(0,m.useCallback)(()=>A(!0),[]),B=(0,m.useCallback)(()=>A(!1),[]),H=(0,m.useMemo)(()=>e?{siteId:e.siteId,siteName:e.siteName,locale:e.locale,siteLocale:e.siteLocale,accountBaseUrl:e.accountBaseUrl,showNavEntry:e.showNavEntry,allowSignup:e.allowSignup,methods:e.methods,messages:e.messages,transport:y,user:t,sections:i,landing:l,checked:u!=="pending",pending:c&&u==="pending"&&t===null,sessionUnavailable:c&&u==="failed"&&t===null,retrySession:T,applySession:R,refresh:G,signOut:D,panelOpen:v,openPanel:Y,closePanel:B}:null,[e,y,t,i,l,u,c,R,T,G,D,v,Y,B]);return(0,V.jsxs)(nt.Provider,{value:H,children:[n,H?(0,V.jsx)(St,{auth:H}):null]})}function se(){return(0,m.useContext)(nt)}function St({auth:e}){let{ui:n}=Te(),t=e.user||e.pending?n.myAccount:ee(e.messages.signInTitle,{siteName:e.siteName});return(0,V.jsx)(We,{id:"customer-account-panel",open:e.panelOpen,onClose:e.closePanel,title:t,closeLabel:n.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:(0,V.jsx)(yt,{variant:"panel",auth:e,onNavigate:e.closePanel})})}var p=h(N(),1);function Nt(e){if(e?.startsWith("/"))return e;if(typeof window>"u")return;let n=new URL(window.location.href);for(let t of["token","handoff","error","verify","email"])n.searchParams.delete(t);return`${n.pathname}${n.search}`}function rt(e){return e instanceof te?{ok:!1,code:e.code??"SERVER_ERROR"}:{ok:!1,code:"NETWORK_ERROR"}}var ie=new Map;function lr(e){return ot(e,!1)}function ot(e,n){let t=e.siteUrl.replace(/\/+$/,""),s=me({siteUrl:t,token:e.token}),i=async(o,u)=>{try{return{ok:!0,...await s.post(o,{body:u})}}catch(r){return rt(r)}},a=async o=>{try{return{ok:!0,...await s.get(o,{})}}catch(u){return rt(u)}},l=o=>(o.ok&&o.sessionToken&&e.onToken(o.sessionToken),o);return{altchaChallengeUrl:`${t}/api/form-protection/altcha`,challengeUrl:`${t}/api/form-protection/challenge`,requestChallenge:({email:o,locale:u,returnTo:r,protection:c})=>i("/auth/challenge",{email:o,locale:u,returnTo:r,...c}),verifyCode:async({email:o,code:u})=>l(await i("/auth/verify",{method:"code",email:o,code:u,channel:"bearer"})),verifyToken:async({method:o,token:u})=>l(await i("/auth/verify",{method:o,token:u,channel:"bearer"})),startOauth:({method:o,returnTo:u,locale:r})=>i("/auth/oauth/start",{method:o,returnTo:u,locale:r}),passkeyLoginOptions:()=>i("/auth/passkey/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyLoginVerify:async o=>l(await i("/auth/passkey/verify",{...o,channel:"bearer"})),listPasskeys:()=>a("/passkeys"),passkeyRegisterOptions:()=>i("/passkeys/register/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyRegister:o=>i("/passkeys/register",o),session:()=>{let o=e.token();if(!o)return Promise.resolve(null);let u=`${t}
|
|
1
|
+
import{a as He}from"./chunk-ARU5PTJV.js";import{a as pe,b as ge,c as Ue,d as he,g as ne}from"./chunk-KW2CH7SS.js";import{a as Me,c as Be}from"./chunk-WJPCDZSL.js";import{a as Le}from"./chunk-2J5XQK4H.js";import{a as Ie,b as _e}from"./chunk-I6KLZIN6.js";import{b as fe}from"./chunk-DIHLDYIG.js";import{a as te,c as me,t as Oe}from"./chunk-XJPS3G7J.js";import{a as Ee}from"./chunk-MXGMJAWS.js";import{a as Pe}from"./chunk-WP7UEAIB.js";import{b as ee}from"./chunk-2E6RCDAA.js";import{a as Ae}from"./chunk-U7KVGD47.js";import{$ as we,A as Re,Y as de,ba as _}from"./chunk-S2NFWI7C.js";import{b as Te}from"./chunk-AFNEGNVJ.js";import{a as N}from"./chunk-OU4IOHLN.js";import{a as ce,b as ke}from"./chunk-DLJDYXKL.js";import{a as it}from"./chunk-NSY72ZYX.js";import{a as W}from"./chunk-6LGTFWQS.js";import{c as h}from"./chunk-CDG7S4P5.js";var U=h(W(),1);var Ve=h(N());var ut=h(N());var Ke=h(N());var De=h(W());var $e=h(N());var m=h(W());var k=h(W()),je=h(it());var x=h(N()),ve='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function We({open:e,onClose:n,title:t,closeLabel:s,children:i,footer:a,showHeader:l=!0,dismissible:o=!0,desktopZIndexClassName:u="z-[var(--z-dialog,200)]",drawerZIndexClassName:r="z-[var(--z-dialog,200)]",maxWidthClassName:c="max-w-lg",desktopVariant:f="dialog",surface:v="glass",headerSlot:A,subheader:P,bodyClassName:L,footerClassName:y,id:K}){let g=f==="side",w=Le(),C=Ae(),I=(0,k.useRef)(n),R=(0,k.useRef)(o);(0,k.useEffect)(()=>{I.current=n,R.current=o}),(0,k.useEffect)(()=>{if(!e)return;let S=Ee(),E=j=>{j.key==="Escape"&&R.current&&I.current()};return document.addEventListener("keydown",E),()=>{S(),document.removeEventListener("keydown",E)}},[e]);let T=(0,k.useRef)(null),G=(0,k.useRef)(null),D=(0,k.useRef)(null),Y=(0,k.useRef)(null),B=(0,k.useRef)(null),H=(0,k.useRef)(0),d=w?w.slots.modal:C?document.body:null,O=e&&!!d;(0,k.useEffect)(()=>{if(!O)return;let S=T.current;if(!S)return;let E=document.activeElement instanceof HTMLElement?document.activeElement:null,j=()=>Array.from(S.querySelectorAll(ve)).filter(z=>!z.hasAttribute("disabled")&&z.getAttribute("aria-hidden")!=="true"),le=G.current?.querySelector(ve),st=D.current?.querySelector(ve);(le??st??j()[0]??S).focus({preventScroll:!0});let Ce=z=>{if(z.key!=="Tab")return;let Q=j();if(Q.length===0){z.preventDefault(),S.focus();return}let xe=Q[0],Se=Q[Q.length-1],Z=document.activeElement,Ne=Z instanceof Node&&S.contains(Z);z.shiftKey?(!Ne||Z===xe||Z===S)&&(z.preventDefault(),Se.focus()):(!Ne||Z===Se)&&(z.preventDefault(),xe.focus())};return document.addEventListener("keydown",Ce),()=>{document.removeEventListener("keydown",Ce),E&&E.isConnected&&E.focus({preventScroll:!0})}},[O]);let $=(0,k.useCallback)(S=>{if(!R.current)return;let E=S.target instanceof Node?S.target:null,j=!!E&&!!Y.current?.contains(E),le=(D.current?.scrollTop??0)<=0;!j&&!le||(B.current=S.touches[0].clientY,H.current=0)},[]),q=(0,k.useCallback)(S=>{if(B.current==null)return;let E=S.touches[0].clientY-B.current;if(E<0&&(D.current?.scrollTop??0)>0){B.current=null,T.current&&(T.current.style.transform="");return}H.current=E,E>0&&T.current&&(T.current.style.transform=`translateY(${E}px)`)},[]),X=(0,k.useCallback)(()=>{B.current!=null&&(T.current&&(T.current.style.transform=""),H.current>100&&R.current&&I.current(),B.current=null,H.current=0)},[]);if(!O)return null;let J=(0,x.jsx)("button",{type:"button",onClick:n,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})}),M=(0,x.jsx)("button",{type:"button",onClick:n,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":s,children:(0,x.jsx)(de,{className:"h-5 w-5"})});return(0,je.createPortal)((0,x.jsxs)("div",{className:_("pointer-events-auto fixed inset-0 flex items-end justify-center",g?"md:items-stretch md:justify-end":"md:items-center md:p-4",u,r),role:"dialog","aria-modal":"true","aria-label":t,children:[(0,x.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:o?n:void 0,"aria-hidden":"true"}),(0,x.jsxs)("div",{id:K,ref:T,tabIndex:-1,onTouchStart:$,onTouchMove:q,onTouchEnd:X,className:_("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",g?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",v==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",c),children:[(0,x.jsxs)("div",{ref:Y,className:"flex shrink-0 flex-col",children:[o&&(0,x.jsx)("button",{type:"button",onClick:n,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":s,children:(0,x.jsx)("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),l?(0,x.jsxs)("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[A??(0,x.jsx)("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:t}),A&&(0,x.jsx)("h2",{className:"sr-only",children:t}),o&&J]}):o&&M]}),P&&(0,x.jsx)("div",{ref:G,className:"shrink-0",children:P}),(0,x.jsx)("div",{ref:D,className:_("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",l?"p-4":"p-0",L),children:i}),a&&(0,x.jsx)("div",{className:_("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",y),children:a})]})]}),d)}var Xe=h(W());var b=h(W(),1);var re=h(N(),1),lt=Symbol.for("react.lazy"),oe=b[" use ".trim().toString()];function ct(e){return typeof e=="object"&&e!==null&&"then"in e}function Fe(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===lt&&"_payload"in e&&ct(e._payload)}function dt(e){let n=mt(e),t=b.forwardRef((s,i)=>{let{children:a,...l}=s;Fe(a)&&typeof oe=="function"&&(a=oe(a._payload));let o=b.Children.toArray(a),u=o.find(pt);if(u){let r=u.props.children,c=o.map(f=>f===u?b.Children.count(r)>1?b.Children.only(null):b.isValidElement(r)?r.props.children:null:f);return(0,re.jsx)(n,{...l,ref:i,children:b.isValidElement(r)?b.cloneElement(r,void 0,c):null})}return(0,re.jsx)(n,{...l,ref:i,children:a})});return t.displayName=`${e}.Slot`,t}var Ge=dt("Slot");function mt(e){let n=b.forwardRef((t,s)=>{let{children:i,...a}=t;if(Fe(i)&&typeof oe=="function"&&(i=oe(i._payload)),b.isValidElement(i)){let l=ht(i),o=gt(a,i.props);return i.type!==b.Fragment&&(o.ref=s?He(s,l):l),b.cloneElement(i,o)}return b.Children.count(i)>1?b.Children.only(null):null});return n.displayName=`${e}.SlotClone`,n}var ft=Symbol("radix.slottable");function pt(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===ft}function gt(e,n){let t={...n};for(let s in n){let i=e[s],a=n[s];/^on[A-Z]/.test(s)?i&&a?t[s]=(...o)=>{let u=a(...o);return i(...o),u}:i&&(t[s]=i):s==="style"?t[s]={...i,...a}:s==="className"&&(t[s]=[i,a].filter(Boolean).join(" "))}return{...e,...t}}function ht(e){let n=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning;return t?e.ref:(n=Object.getOwnPropertyDescriptor(e,"ref")?.get,t=n&&"isReactWarning"in n&&n.isReactWarning,t?e.props.ref:e.props.ref||e.ref)}var Ye=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,qe=we,Ze=(e,n)=>t=>{var s;if(n?.variants==null)return qe(e,t?.class,t?.className);let{variants:i,defaultVariants:a}=n,l=Object.keys(i).map(r=>{let c=t?.[r],f=a?.[r];if(c===null)return null;let v=Ye(c)||Ye(f);return i[r][v]}),o=t&&Object.entries(t).reduce((r,c)=>{let[f,v]=c;return v===void 0||(r[f]=v),r},{}),u=n==null||(s=n.compoundVariants)===null||s===void 0?void 0:s.reduce((r,c)=>{let{class:f,className:v,...A}=c;return Object.entries(A).every(P=>{let[L,y]=P;return Array.isArray(y)?y.includes({...a,...o}[L]):{...a,...o}[L]===y})?[...r,f,v]:r},[]);return qe(e,l,u,t?.class,t?.className)};var Qe=h(N()),vt=Ze("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}}),Je=Xe.forwardRef(({className:e,variant:n,size:t,asChild:s=!1,...i},a)=>(0,Qe.jsx)(s?Ge:"button",{className:_(vt({variant:n,size:t,className:e})),ref:a,...i}));Je.displayName="Button";var V=h(N()),yt=Pe(()=>import("./CustomerAccountPanel-FXJEOS4F.js").then(e=>e.CustomerAccountPanel),()=>(0,V.jsx)("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:(0,V.jsx)(Re,{className:"h-5 w-5 animate-spin opacity-50"})}));function bt(){return typeof document>"u"?!1:document.cookie.split(";").some(e=>e.trim().startsWith(`${ge}=`))}function et(){typeof document>"u"||(document.cookie=`${ge}=; Max-Age=0; Path=/; SameSite=Lax`)}var ye=e=>`knr_customer_overview:${e}`;function tt(e){if(e===null)return"";let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return(n>>>0).toString(36)}function Ct(e,n){try{let t=typeof sessionStorage>"u"?null:sessionStorage.getItem(ye(e));if(!t)return null;let s=JSON.parse(t);return!s||typeof s!="object"||!s.contact||s.session!==tt(n)?null:s}catch{return null}}function F(e,n,t){try{if(typeof sessionStorage>"u")return;if(n){let{id:s,email:i,name:a}=n.contact,l={session:tt(t),contact:{id:s,email:i,name:a},sections:n.sections,landing:n.landing};sessionStorage.setItem(ye(e),JSON.stringify(l))}else sessionStorage.removeItem(ye(e))}catch{}}var xt=[1e3,3e3,1e4],nt=(0,m.createContext)(null);function be({config:e,children:n}){let[t,s]=(0,m.useState)(null),[i,a]=(0,m.useState)([]),[l,o]=(0,m.useState)(null),[u,r]=(0,m.useState)("pending"),[c,f]=(0,m.useState)(!1),[v,A]=(0,m.useState)(!1),[P,L]=(0,m.useState)(0),y=(0,m.useMemo)(()=>e?.transport??he(),[e?.transport]),K=e?.sessionHint??bt,g=e?.siteId??null,w=e?.sessionKey??null,C=(0,m.useRef)(null),I=(0,m.useRef)(w);I.current=w;let R=(0,m.useCallback)(d=>{g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done"),d||L(O=>O+1)},[g]),T=(0,m.useCallback)(()=>{r("pending"),L(d=>d+1)},[]);(0,m.useEffect)(()=>{if(g===null)return;let d=C.current;if(C.current={siteId:g,sessionKey:w},!K()){F(g,null,w),f(!1),s(null),a([]),o(null),r("done");return}f(!0),(d===null||d.siteId!==g||d.sessionKey!==w)&&r("pending");let O=Ct(g,w);O?(s(O.contact),a(O.sections??[]),o(O.landing??null)):d!==null&&(d.siteId!==g||d.sessionKey!==null&&d.sessionKey!==w)&&(s(null),a([]),o(null));let $=!1,q=null,X=J=>{y.session().then(M=>{$||(F(g,M,w),M||et(),s(M?.contact??null),a(M?.sections??[]),o(M?.landing??null),r("done"))}).catch(()=>{if($)return;let M=xt[J];if(M!==void 0){q=setTimeout(()=>X(J+1),M);return}r(S=>S==="pending"?"failed":S)})};return X(0),()=>{$=!0,q!==null&&clearTimeout(q)}},[g,w,y,P]),(0,m.useEffect)(()=>{if(!e||typeof document>"u")return;let d=()=>{if(document.visibilityState!=="visible")return;let O=K();O&&t===null&&L($=>$+1),!O&&t!==null&&(F(e.siteId,null,w),s(null),a([]),o(null),r("done"))};return document.addEventListener("visibilitychange",d),window.addEventListener("focus",d),()=>{document.removeEventListener("visibilitychange",d),window.removeEventListener("focus",d)}},[e,t]);let G=(0,m.useCallback)(async()=>{let d;try{d=await y.session()}catch{r("done");return}g&&F(g,d,I.current),s(d?.contact??null),a(d?.sections??[]),o(d?.landing??null),r("done")},[y,g]),D=(0,m.useCallback)(async()=>{await y.signOut(),g&&F(g,null,I.current),et(),s(null),a([]),o(null),r("done")},[y,g]),Y=(0,m.useCallback)(()=>A(!0),[]),B=(0,m.useCallback)(()=>A(!1),[]),H=(0,m.useMemo)(()=>e?{siteId:e.siteId,siteName:e.siteName,locale:e.locale,siteLocale:e.siteLocale,accountBaseUrl:e.accountBaseUrl,showNavEntry:e.showNavEntry,allowSignup:e.allowSignup,methods:e.methods,messages:e.messages,transport:y,user:t,sections:i,landing:l,checked:u!=="pending",pending:c&&u==="pending"&&t===null,sessionUnavailable:c&&u==="failed"&&t===null,retrySession:T,applySession:R,refresh:G,signOut:D,panelOpen:v,openPanel:Y,closePanel:B}:null,[e,y,t,i,l,u,c,R,T,G,D,v,Y,B]);return(0,V.jsxs)(nt.Provider,{value:H,children:[n,H?(0,V.jsx)(St,{auth:H}):null]})}function se(){return(0,m.useContext)(nt)}function St({auth:e}){let{ui:n}=Te(),t=e.user||e.pending?n.myAccount:ee(e.messages.signInTitle,{siteName:e.siteName});return(0,V.jsx)(We,{id:"customer-account-panel",open:e.panelOpen,onClose:e.closePanel,title:t,closeLabel:n.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:(0,V.jsx)(yt,{variant:"panel",auth:e,onNavigate:e.closePanel})})}var p=h(N(),1);function Nt(e){if(e?.startsWith("/"))return e;if(typeof window>"u")return;let n=new URL(window.location.href);for(let t of["token","handoff","error","verify","email"])n.searchParams.delete(t);return`${n.pathname}${n.search}`}function rt(e){return e instanceof te?{ok:!1,code:e.code??"SERVER_ERROR"}:{ok:!1,code:"NETWORK_ERROR"}}var ie=new Map;function lr(e){return ot(e,!1)}function ot(e,n){let t=e.siteUrl.replace(/\/+$/,""),s=me({siteUrl:t,token:e.token}),i=async(o,u)=>{try{return{ok:!0,...await s.post(o,{body:u})}}catch(r){return rt(r)}},a=async o=>{try{return{ok:!0,...await s.get(o,{})}}catch(u){return rt(u)}},l=o=>(o.ok&&o.sessionToken&&e.onToken(o.sessionToken),o);return{altchaChallengeUrl:`${t}/api/form-protection/altcha`,challengeUrl:`${t}/api/form-protection/challenge`,requestChallenge:({email:o,locale:u,returnTo:r,protection:c})=>i("/auth/challenge",{email:o,locale:u,returnTo:r,...c}),verifyCode:async({email:o,code:u})=>l(await i("/auth/verify",{method:"code",email:o,code:u,channel:"bearer"})),verifyToken:async({method:o,token:u})=>l(await i("/auth/verify",{method:o,token:u,channel:"bearer"})),startOauth:({method:o,returnTo:u,locale:r})=>i("/auth/oauth/start",{method:o,returnTo:u,locale:r}),passkeyLoginOptions:()=>i("/auth/passkey/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyLoginVerify:async o=>l(await i("/auth/passkey/verify",{...o,channel:"bearer"})),listPasskeys:()=>a("/passkeys"),passkeyRegisterOptions:()=>i("/passkeys/register/options",{origin:typeof window>"u"?void 0:window.location.origin}),passkeyRegister:o=>i("/passkeys/register",o),session:()=>{let o=e.token();if(!o)return Promise.resolve(null);let u=`${t}
|
|
2
2
|
${o}`,r=ie.get(u),c=r??me({siteUrl:t,token:o}).get("/me").then(f=>{let v=f;if(!v.contact)return null;let{id:A,email:P,name:L}=v.contact;return{contact:{id:A,email:P,name:L},sections:v.sections??[],landing:v.landing??"/account"}},f=>{if(f instanceof te&&f.status===401)return null;throw f});return r||(ie.set(u,c),c.then(()=>ie.delete(u),()=>ie.delete(u))),n?c:c.catch(()=>null)},signOut:async()=>{try{await s.delete("/session",{body:{mode:"current"}})}catch{}e.onToken(null)}}}var ae=new Map;function kt(e,n){let t=`${e}|${n}`,s=ae.get(t);if(s)return s;if(!new URLSearchParams(window.location.search).has("code"))return null;let i={result:_e({siteUrl:e,clientId:n}),signedIn:!1};return ae.set(t,i),i.result.then(()=>ae.delete(t),()=>ae.delete(t)),i}function cr({siteName:e,mode:n="direct",redirectUri:t,returnTo:s,onLogin:i,onLogout:a,renderSignedIn:l,className:o,...u}){let r=Oe(u,{needsSite:!0}),c=r.site,[f,v]=(0,U.useState)({busy:!1,error:null}),A=c?.id??"",P=r.setToken;(0,U.useEffect)(()=>{if(n!=="redirect"||!A||typeof window>"u")return;let C=kt(r.siteUrl,A);if(!C)return;let I=!1;return v({busy:!0,error:null}),C.result.then(R=>{if(!I){if(R&&!C.signedIn){C.signedIn=!0,P(R.accessToken);let T={token:R.accessToken,contactId:R.contactId,expiresAt:R.expiresAt};i?.(T),window.dispatchEvent(new CustomEvent(ce,{detail:T}))}v({busy:!1,error:null})}}).catch(R=>{I||v({busy:!1,error:R instanceof te?R.code:"NETWORK_ERROR"})}),()=>{I=!0}},[n,A,r.siteUrl,P]);let[L]=(0,U.useState)(()=>{if(typeof window>"u")return{};let C=new URLSearchParams(window.location.search);return{email:C.get("email")??void 0,token:C.get("token")??void 0,handoff:C.get("handoff")??void 0,verify:C.get("verify")==="1",error:C.get("error")??void 0}}),y=At(r.token),K=(0,U.useMemo)(()=>ot({siteUrl:r.siteUrl,token:()=>y.current,onToken:C=>{y.current=C,P(C)}},!0),[r.siteUrl,P,y]),g=e??c?.brand?.displayName??c?.name??"",w=(0,U.useMemo)(()=>c&&r.messages?{siteId:c.id,siteName:g,locale:r.locale,siteLocale:c.locale??r.locale,accountBaseUrl:r.siteUrl,showNavEntry:c.customerAccess?.showNavEntry===!0,allowSignup:c.customerAccess?.allowSignup===!0,methods:Ue(c.customerAccess?.methods),messages:r.messages.account,transport:K,sessionHint:()=>!!y.current,sessionKey:r.token}:null,[c,r.messages,r.locale,r.siteUrl,r.token,g,K,y]);return r.messages?(0,p.jsx)(fe,{context:r,className:o,children:(0,p.jsx)(Me,{value:Be(c?.botProtection),children:(0,p.jsx)(be,{config:w,children:n==="redirect"?(0,p.jsx)(Rt,{siteUrl:r.siteUrl,siteId:A,siteName:g,redirectUri:t,busy:f.busy,error:f.error,messages:r.messages.account,onLogout:a,renderSignedIn:l}):(0,p.jsx)(wt,{returnTo:Nt(s),initial:L,onLogin:i,onLogout:a,renderSignedIn:l})})})}):(0,p.jsx)(fe,{context:r,className:o,loading:!0})}function Rt({siteUrl:e,siteId:n,siteName:t,redirectUri:s,busy:i,error:a,messages:l,onLogout:o,renderSignedIn:u}){let r=se(),[c,f]=(0,U.useState)(!1);if(!r)return(0,p.jsx)("div",{"aria-busy":"true"});if(r.user)return u?(0,p.jsx)(p.Fragment,{children:u(()=>{r.signOut().then(()=>ue(o))})}):(0,p.jsx)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:(0,p.jsx)(ne,{variant:"panel",auth:r,onSignedOut:()=>ue(o)})});let v=async()=>{if(n){f(!0);try{await Ie({siteUrl:e,clientId:n,redirectUri:s})}catch{f(!1)}}};return r.sessionUnavailable?(0,p.jsxs)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[(0,p.jsx)("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:l.errorServiceUnavailable}),(0,p.jsx)("button",{type:"button",className:pe({block:!0}),onClick:r.retrySession,children:l.contentRetry})]}):(0,p.jsxs)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[a?(0,p.jsx)("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:l.errorGeneric}):null,(0,p.jsx)("button",{type:"button",className:pe({block:!0}),onClick:()=>{v()},disabled:c||i||r.pending||!n,"aria-busy":i||r.pending||void 0,children:i||r.pending?l.sessionChecking:ee(l.signInTitle,{siteName:t})})]})}function wt({returnTo:e,initial:n,onLogin:t,onLogout:s,renderSignedIn:i}){let a=se();return a?a.user&&i?(0,p.jsx)(p.Fragment,{children:i(()=>{a.signOut().then(()=>ue(s))})}):(0,p.jsx)("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:(0,p.jsx)(ne,{variant:"panel",auth:a,initial:n,returnTo:e,onSignedIn:l=>{if(!l.sessionToken)return;let o={token:l.sessionToken,contactId:l.contactId??"",expiresAt:l.expiresAt??""};t?.(o),window.dispatchEvent(new CustomEvent(ce,{detail:o}))},onSignedOut:()=>ue(s)})}):(0,p.jsx)("div",{"aria-busy":"true"})}function ue(e){e?.(),window.dispatchEvent(new CustomEvent(ke))}function At(e){let n=(0,U.useState)(()=>({current:e}))[0];return(0,U.useEffect)(()=>{n.current=e},[n,e]),n.current=e,n}export{lr as a,cr as b};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-EGMCB2MQ.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{useKanorioSiteUrl}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{useKanorioSiteUrl}from"./chunk-73S6VKNV.js";import{useEffect,useRef}from"react";function normalizeExclude(exclude){const list=typeof exclude==="string"?exclude.split(","):exclude??[];return list.map(p=>p.trim().replace(/\/+$/,"")).filter(p=>p.startsWith("/"))}function isExcludedPath(path,exclude){return normalizeExclude(exclude).some(prefix=>path===prefix||path.startsWith(`${prefix}/`))}var SESSION_GAP_MS=30*60*1e3;var SESSION_LAST_SEEN_KEY="kanorio-analytics-last";var ATTRIBUTION_PARAMS=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","fbclid","oppref"];var MAX_ATTRIBUTION_VALUE_LENGTH=200;var memoryLastSeenAt=null;function markSessionEntry(now=Date.now()){try{const raw=window.sessionStorage.getItem(SESSION_LAST_SEEN_KEY);const last=raw?Number(raw):NaN;window.sessionStorage.setItem(SESSION_LAST_SEEN_KEY,String(now));return!Number.isFinite(last)||now-last>SESSION_GAP_MS}catch{const isEntry=memoryLastSeenAt===null||now-memoryLastSeenAt>SESSION_GAP_MS;memoryLastSeenAt=now;return isEntry}}function externalReferrer(){if(typeof document==="undefined"||!document.referrer)return void 0;try{const sameHost=new URL(document.referrer).hostname.toLowerCase()===window.location.hostname.toLowerCase();return sameHost?void 0:document.referrer}catch{return void 0}}function readAttribution(search){if(!search)return void 0;try{const params=new URLSearchParams(search);const out={};for(const key of ATTRIBUTION_PARAMS){const value=params.get(key)?.trim();if(value)out[key]=value.slice(0,MAX_ATTRIBUTION_VALUE_LENGTH)}return Object.keys(out).length>0?out:void 0}catch{return void 0}}function reportKanorioPageview(params){const base=params.siteUrl.replace(/\/+$/,"");const cleanPath=params.path.startsWith("/")?params.path:`/${params.path}`;const url=`${base}/api/v1/analytics/pageview`;const payload=JSON.stringify({path:cleanPath,...params.title?{title:params.title}:{},...params.referrer?{referrer:params.referrer}:{},...params.entry!==void 0?{entry:params.entry}:{},...params.utm?{utm:params.utm}:{}});if(!params.fetch&&typeof navigator!=="undefined"&&typeof navigator.sendBeacon==="function"){try{const queued=navigator.sendBeacon(url,new Blob([payload],{type:"text/plain;charset=UTF-8"}));if(queued)return Promise.resolve(true)}catch{}}const fetchImpl=params.fetch??globalThis.fetch;return fetchImpl(url,{method:"POST",headers:{"Content-Type":"text/plain;charset=UTF-8"},body:payload,keepalive:true}).then(r=>r.ok).catch(()=>false)}var NAVIGATION_EVENT="kanorio:navigation";var historyPatched=false;function ensureHistoryPatched(){if(historyPatched||typeof window==="undefined"||typeof window.history==="undefined")return;historyPatched=true;for(const method of["pushState","replaceState"]){const original=window.history[method];if(typeof original!=="function")continue;window.history[method]=function patched(...args){const result=original.apply(this,args);window.dispatchEvent(new Event(NAVIGATION_EVENT));return result}}}function KanorioAnalytics({siteUrl:propSiteUrl,path,title,referrer,exclude}){const siteUrl=useKanorioSiteUrl(propSiteUrl);const lastSeenPathRef=useRef(null);const hasReportedRef=useRef(false);const overridesRef=useRef({title,referrer,exclude});overridesRef.current={title,referrer,exclude};useEffect(()=>{if(typeof window==="undefined")return;ensureHistoryPatched();const send=targetPath=>{if(!targetPath||lastSeenPathRef.current===targetPath)return;lastSeenPathRef.current=targetPath;if(isExcludedPath(targetPath,overridesRef.current.exclude))return;const isFirst=!hasReportedRef.current;hasReportedRef.current=true;const entry=markSessionEntry();const{title:titleOverride,referrer:referrerOverride}=overridesRef.current;const fire=()=>void reportKanorioPageview({siteUrl,path:targetPath,title:titleOverride??(typeof document!=="undefined"?document.title:void 0),referrer:referrerOverride??(isFirst&&entry?externalReferrer():void 0),entry,utm:readAttribution(window.location.search)});if(typeof window.requestAnimationFrame==="function")window.requestAnimationFrame(fire);else setTimeout(fire,0)};const onNavigate=()=>send(path??window.location.pathname);onNavigate();window.addEventListener("popstate",onNavigate);window.addEventListener(NAVIGATION_EVENT,onNavigate);return()=>{window.removeEventListener("popstate",onNavigate);window.removeEventListener(NAVIGATION_EVENT,onNavigate)}},[siteUrl,path]);return null}export{isExcludedPath,reportKanorioPageview,KanorioAnalytics};
|
|
2
|
+
//# sourceMappingURL=chunk-FFSPNYLJ.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{CUSTOMER_SESSION_HINT_COOKIE_NAME,CustomerAccountPanel,createHostedCustomerAuthTransport,customerButtonClass,normalizeCustomerAuthMethods}from"./chunk-4OC7BRQS.js";import{composeRefs}from"./chunk-AQ6F6MIJ.js";import{useHydrated}from"./chunk-63XJWMJG.js";import{completeHostedCustomerLogin,startHostedCustomerLogin}from"./chunk-R5M6FXXQ.js";import{onDemand}from"./chunk-E77WGXYW.js";import{LOGIN_EVENT,LOGOUT_EVENT}from"./chunk-LWKCGUHS.js";import{BotProtectionConfigProvider,parsePublicBotProtectionConfig}from"./chunk-KYXZNMNA.js";import{useSiteChrome}from"./chunk-Z4A5NQWJ.js";import{lockPageScroll}from"./chunk-HFYLTH5B.js";import{LoaderCircle,X}from"./chunk-33AQQY6T.js";import{clsx,cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-QRKYFFDH.js";import{fillLabel}from"./chunk-KNNN5V3T.js";import{useSiteLabels}from"./chunk-U7H3W23Q.js";import{KanorioApiError,createCustomerClient,useElementContext}from"./chunk-RI64PHGM.js";import{useEffect as useEffect4,useMemo as useMemo2,useState as useState2}from"react";import{jsx,jsxs}from"react/jsx-runtime";import{jsx as jsx2}from"react/jsx-runtime";import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";import{useEffect,useRef}from"react";import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";import{createContext,useCallback as useCallback2,useContext,useEffect as useEffect3,useMemo,useRef as useRef3,useState}from"react";import{useCallback,useEffect as useEffect2,useRef as useRef2}from"react";import{createPortal}from"react-dom";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var FOCUSABLE_SELECTOR='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function SiteResponsiveModal({open,onClose,title,closeLabel,children,footer,showHeader=true,dismissible=true,desktopZIndexClassName="z-[var(--z-dialog,200)]",drawerZIndexClassName="z-[var(--z-dialog,200)]",maxWidthClassName="max-w-lg",desktopVariant="dialog",surface="glass",headerSlot,subheader,bodyClassName,footerClassName,id}){const isSide=desktopVariant==="side";const chrome=useSiteChrome();const mounted=useHydrated();const onCloseRef=useRef2(onClose);const dismissibleRef=useRef2(dismissible);useEffect2(()=>{onCloseRef.current=onClose;dismissibleRef.current=dismissible});useEffect2(()=>{if(!open)return;const releaseScrollLock=lockPageScroll();const onKeyDown=e=>{if(e.key==="Escape"&&dismissibleRef.current)onCloseRef.current()};document.addEventListener("keydown",onKeyDown);return()=>{releaseScrollLock();document.removeEventListener("keydown",onKeyDown)}},[open]);const sheetRef=useRef2(null);const subheaderRef=useRef2(null);const bodyRef=useRef2(null);const dragZoneRef=useRef2(null);const dragStartY=useRef2(null);const dragDelta=useRef2(0);const portalTarget=chrome?chrome.slots.modal:mounted?document.body:null;const rendered=open&&!!portalTarget;useEffect2(()=>{if(!rendered)return;const sheet=sheetRef.current;if(!sheet)return;const previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const focusables=()=>Array.from(sheet.querySelectorAll(FOCUSABLE_SELECTOR)).filter(el=>!el.hasAttribute("disabled")&&el.getAttribute("aria-hidden")!=="true");const firstInSubheader=subheaderRef.current?.querySelector(FOCUSABLE_SELECTOR);const firstInBody=bodyRef.current?.querySelector(FOCUSABLE_SELECTOR);(firstInSubheader??firstInBody??focusables()[0]??sheet).focus({preventScroll:true});const onKeyDown=e=>{if(e.key!=="Tab")return;const list=focusables();if(list.length===0){e.preventDefault();sheet.focus();return}const first=list[0];const last=list[list.length-1];const active=document.activeElement;const inside=active instanceof Node&&sheet.contains(active);if(e.shiftKey){if(!inside||active===first||active===sheet){e.preventDefault();last.focus()}}else if(!inside||active===last){e.preventDefault();first.focus()}};document.addEventListener("keydown",onKeyDown);return()=>{document.removeEventListener("keydown",onKeyDown);if(previouslyFocused&&previouslyFocused.isConnected){previouslyFocused.focus({preventScroll:true})}}},[rendered]);const onTouchStart=useCallback(e=>{if(!dismissibleRef.current)return;const target=e.target instanceof Node?e.target:null;const fromDragZone=!!target&&!!dragZoneRef.current?.contains(target);const bodyAtTop=(bodyRef.current?.scrollTop??0)<=0;if(!fromDragZone&&!bodyAtTop)return;dragStartY.current=e.touches[0].clientY;dragDelta.current=0},[]);const onTouchMove=useCallback(e=>{if(dragStartY.current==null)return;const delta=e.touches[0].clientY-dragStartY.current;if(delta<0&&(bodyRef.current?.scrollTop??0)>0){dragStartY.current=null;if(sheetRef.current)sheetRef.current.style.transform="";return}dragDelta.current=delta;if(delta>0&&sheetRef.current){sheetRef.current.style.transform=`translateY(${delta}px)`}},[]);const onTouchEnd=useCallback(()=>{if(dragStartY.current==null)return;if(sheetRef.current){sheetRef.current.style.transform=""}if(dragDelta.current>100&&dismissibleRef.current){onCloseRef.current()}dragStartY.current=null;dragDelta.current=0},[]);if(!rendered)return null;const headerCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});const floatingCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});return createPortal(jsxs4("div",{className:cn("pointer-events-auto fixed inset-0 flex items-end justify-center",isSide?"md:items-stretch md:justify-end":"md:items-center md:p-4",desktopZIndexClassName,drawerZIndexClassName),role:"dialog","aria-modal":"true","aria-label":title,children:[jsx5("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:dismissible?onClose:void 0,"aria-hidden":"true"}),jsxs4("div",{id,ref:sheetRef,tabIndex:-1,onTouchStart,onTouchMove,onTouchEnd,className:cn("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",isSide?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",surface==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",maxWidthClassName),children:[jsxs4("div",{ref:dragZoneRef,className:"flex shrink-0 flex-col",children:[dismissible&&jsx5("button",{type:"button",onClick:onClose,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":closeLabel,children:jsx5("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),showHeader?jsxs4("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[headerSlot??jsx5("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:title}),headerSlot&&jsx5("h2",{className:"sr-only",children:title}),dismissible&&headerCloseButton]}):dismissible&&floatingCloseButton]}),subheader&&jsx5("div",{ref:subheaderRef,className:"shrink-0",children:subheader}),jsx5("div",{ref:bodyRef,className:cn("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",showHeader?"p-4":"p-0",bodyClassName),children}),footer&&jsx5("div",{className:cn("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",footerClassName),children:footer})]})]}),portalTarget)}import*as React2 from"react";import*as React from"react";import{Fragment as Fragment2,jsx as jsx6}from"react/jsx-runtime";var REACT_LAZY_TYPE=Symbol.for("react.lazy");var use=React[" use ".trim().toString()];function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value}function isLazyComponent(element){return element!=null&&typeof element==="object"&&"$$typeof"in element&&element.$$typeof===REACT_LAZY_TYPE&&"_payload"in element&&isPromiseLike(element._payload)}function createSlot(ownerName){const SlotClone=createSlotClone(ownerName);const Slot2=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}const childrenArray=React.Children.toArray(children);const slottable=childrenArray.find(isSlottable);if(slottable){const newElement=slottable.props.children;const newChildren=childrenArray.map(child=>{if(child===slottable){if(React.Children.count(newElement)>1)return React.Children.only(null);return React.isValidElement(newElement)?newElement.props.children:null}else{return child}});return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children:React.isValidElement(newElement)?React.cloneElement(newElement,void 0,newChildren):null})}return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children})});Slot2.displayName=`${ownerName}.Slot`;return Slot2}var Slot=createSlot("Slot");function createSlotClone(ownerName){const SlotClone=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}if(React.isValidElement(children)){const childrenRef=getElementRef(children);const props2=mergeProps(slotProps,children.props);if(children.type!==React.Fragment){props2.ref=forwardedRef?composeRefs(forwardedRef,childrenRef):childrenRef}return React.cloneElement(children,props2)}return React.Children.count(children)>1?React.Children.only(null):null});SlotClone.displayName=`${ownerName}.SlotClone`;return SlotClone}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function isSlottable(child){return React.isValidElement(child)&&typeof child.type==="function"&&"__radixId"in child.type&&child.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(slotProps,childProps){const overrideProps={...childProps};for(const propName in childProps){const slotPropValue=slotProps[propName];const childPropValue=childProps[propName];const isHandler=/^on[A-Z]/.test(propName);if(isHandler){if(slotPropValue&&childPropValue){overrideProps[propName]=(...args)=>{const result=childPropValue(...args);slotPropValue(...args);return result}}else if(slotPropValue){overrideProps[propName]=slotPropValue}}else if(propName==="style"){overrideProps[propName]={...slotPropValue,...childPropValue}}else if(propName==="className"){overrideProps[propName]=[slotPropValue,childPropValue].filter(Boolean).join(" ")}}return{...slotProps,...overrideProps}}function getElementRef(element){let getter=Object.getOwnPropertyDescriptor(element.props,"ref")?.get;let mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.ref}getter=Object.getOwnPropertyDescriptor(element,"ref")?.get;mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.props.ref}return element.props.ref||element.ref}var falsyToString=value=>typeof value==="boolean"?`${value}`:value===0?"0":value;var cx=clsx;var cva=(base,config)=>props=>{var _config_compoundVariants;if((config===null||config===void 0?void 0:config.variants)==null)return cx(base,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className);const{variants,defaultVariants}=config;const getVariantClassNames=Object.keys(variants).map(variant=>{const variantProp=props===null||props===void 0?void 0:props[variant];const defaultVariantProp=defaultVariants===null||defaultVariants===void 0?void 0:defaultVariants[variant];if(variantProp===null)return null;const variantKey=falsyToString(variantProp)||falsyToString(defaultVariantProp);return variants[variant][variantKey]});const propsWithoutUndefined=props&&Object.entries(props).reduce((acc,param)=>{let[key,value]=param;if(value===void 0){return acc}acc[key]=value;return acc},{});const getCompoundVariantClassNames=config===null||config===void 0?void 0:(_config_compoundVariants=config.compoundVariants)===null||_config_compoundVariants===void 0?void 0:_config_compoundVariants.reduce((acc,param)=>{let{class:cvClass,className:cvClassName,...compoundVariantOptions}=param;return Object.entries(compoundVariantOptions).every(param2=>{let[key,value]=param2;return Array.isArray(value)?value.includes({...defaultVariants,...propsWithoutUndefined}[key]):{...defaultVariants,...propsWithoutUndefined}[key]===value})?[...acc,cvClass,cvClassName]:acc},[]);return cx(base,getVariantClassNames,getCompoundVariantClassNames,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className)};import{jsx as jsx7}from"react/jsx-runtime";var buttonVariants=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}});var Button=React2.forwardRef(({className,variant,size,asChild=false,...props},ref)=>{const Comp=asChild?Slot:"button";return jsx7(Comp,{className:cn(buttonVariants({variant,size,className})),ref,...props})});Button.displayName="Button";import{jsx as jsx8,jsxs as jsxs5}from"react/jsx-runtime";var CustomerAccountPanel2=onDemand(()=>import("./CustomerAccountPanel-LK4GSYYU.js").then(m=>m.CustomerAccountPanel),()=>jsx8("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:jsx8(LoaderCircle,{className:"h-5 w-5 animate-spin opacity-50"})}));function hasCustomerSessionHint(){if(typeof document==="undefined")return false;return document.cookie.split(";").some(part=>part.trim().startsWith(`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=`))}function clearCustomerSessionHint(){if(typeof document==="undefined")return;document.cookie=`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=; Max-Age=0; Path=/; SameSite=Lax`}var overviewCacheKey=siteId=>`knr_customer_overview:${siteId}`;function sessionFingerprint(sessionKey){if(sessionKey===null)return"";let hash=2166136261;for(let index=0;index<sessionKey.length;index+=1){hash^=sessionKey.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function readCachedOverview(siteId,sessionKey){try{const raw=typeof sessionStorage==="undefined"?null:sessionStorage.getItem(overviewCacheKey(siteId));if(!raw)return null;const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||!parsed.contact||parsed.session!==sessionFingerprint(sessionKey))return null;return parsed}catch{return null}}function writeCachedOverview(siteId,overview,sessionKey){try{if(typeof sessionStorage==="undefined")return;if(overview){const{id,email,name}=overview.contact;const cached={session:sessionFingerprint(sessionKey),contact:{id,email,name},sections:overview.sections,landing:overview.landing};sessionStorage.setItem(overviewCacheKey(siteId),JSON.stringify(cached))}else sessionStorage.removeItem(overviewCacheKey(siteId))}catch{}}var SESSION_RETRY_DELAYS_MS=[1e3,3e3,1e4];var CustomerAuthContext=createContext(null);function CustomerAuthProvider({config,children}){const[user,setUser]=useState(null);const[sections,setSections]=useState([]);const[landing,setLanding]=useState(null);const[check,setCheck]=useState("pending");const[hinted,setHinted]=useState(false);const[panelOpen,setPanelOpen]=useState(false);const[refreshTick,setRefreshTick]=useState(0);const transport=useMemo(()=>config?.transport??createHostedCustomerAuthTransport(),[config?.transport]);const sessionHint=config?.sessionHint??hasCustomerSessionHint;const siteId=config?.siteId??null;const sessionKey=config?.sessionKey??null;const lastCheckRef=useRef3(null);const sessionKeyRef=useRef3(sessionKey);sessionKeyRef.current=sessionKey;const applySession=useCallback2(overview=>{if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done");if(!overview)setRefreshTick(tick=>tick+1)},[siteId]);const retrySession=useCallback2(()=>{setCheck("pending");setRefreshTick(tick=>tick+1)},[]);useEffect3(()=>{if(siteId===null)return;const previous=lastCheckRef.current;lastCheckRef.current={siteId,sessionKey};if(!sessionHint()){writeCachedOverview(siteId,null,sessionKey);setHinted(false);setUser(null);setSections([]);setLanding(null);setCheck("done");return}setHinted(true);if(previous===null||previous.siteId!==siteId||previous.sessionKey!==sessionKey)setCheck("pending");const cached=readCachedOverview(siteId,sessionKey);if(cached){setUser(cached.contact);setSections(cached.sections??[]);setLanding(cached.landing??null)}else if(previous!==null&&(previous.siteId!==siteId||previous.sessionKey!==null&&previous.sessionKey!==sessionKey)){setUser(null);setSections([]);setLanding(null)}let cancelled=false;let retryTimer=null;const ask=attempt=>{transport.session().then(overview=>{if(cancelled)return;writeCachedOverview(siteId,overview,sessionKey);if(!overview)clearCustomerSessionHint();setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")}).catch(()=>{if(cancelled)return;const delay=SESSION_RETRY_DELAYS_MS[attempt];if(delay!==void 0){retryTimer=setTimeout(()=>ask(attempt+1),delay);return}setCheck(current=>current==="pending"?"failed":current)})};ask(0);return()=>{cancelled=true;if(retryTimer!==null)clearTimeout(retryTimer)}},[siteId,sessionKey,transport,refreshTick]);useEffect3(()=>{if(!config||typeof document==="undefined")return;const sync=()=>{if(document.visibilityState!=="visible")return;const hint=sessionHint();if(hint&&user===null)setRefreshTick(tick=>tick+1);if(!hint&&user!==null){writeCachedOverview(config.siteId,null,sessionKey);setUser(null);setSections([]);setLanding(null);setCheck("done")}};document.addEventListener("visibilitychange",sync);window.addEventListener("focus",sync);return()=>{document.removeEventListener("visibilitychange",sync);window.removeEventListener("focus",sync)}},[config,user]);const refresh=useCallback2(async()=>{let overview;try{overview=await transport.session()}catch{setCheck("done");return}if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")},[transport,siteId]);const signOut=useCallback2(async()=>{await transport.signOut();if(siteId)writeCachedOverview(siteId,null,sessionKeyRef.current);clearCustomerSessionHint();setUser(null);setSections([]);setLanding(null);setCheck("done")},[transport,siteId]);const openPanel=useCallback2(()=>setPanelOpen(true),[]);const closePanel=useCallback2(()=>setPanelOpen(false),[]);const value=useMemo(()=>config?{siteId:config.siteId,siteName:config.siteName,locale:config.locale,siteLocale:config.siteLocale,accountBaseUrl:config.accountBaseUrl,showNavEntry:config.showNavEntry,allowSignup:config.allowSignup,methods:config.methods,messages:config.messages,transport,user,sections,landing,checked:check!=="pending",pending:hinted&&check==="pending"&&user===null,sessionUnavailable:hinted&&check==="failed"&&user===null,retrySession,applySession,refresh,signOut,panelOpen,openPanel,closePanel}:null,[config,transport,user,sections,landing,check,hinted,applySession,retrySession,refresh,signOut,panelOpen,openPanel,closePanel]);return jsxs5(CustomerAuthContext.Provider,{value,children:[children,value?jsx8(CustomerAccountModal,{auth:value}):null]})}function useCustomerAuth(){return useContext(CustomerAuthContext)}function CustomerAccountModal({auth}){const{ui}=useSiteLabels();const title=auth.user||auth.pending?ui.myAccount:fillLabel(auth.messages.signInTitle,{siteName:auth.siteName});return jsx8(SiteResponsiveModal,{id:"customer-account-panel",open:auth.panelOpen,onClose:auth.closePanel,title,closeLabel:ui.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:jsx8(CustomerAccountPanel2,{variant:"panel",auth,onNavigate:auth.closePanel})})}import{Fragment as Fragment3,jsx as jsx9,jsxs as jsxs6}from"react/jsx-runtime";function loginReturnTo(returnTo){if(returnTo?.startsWith("/"))return returnTo;if(typeof window==="undefined")return void 0;const url=new URL(window.location.href);for(const key of["token","handoff","error","verify","email"])url.searchParams.delete(key);return`${url.pathname}${url.search}`}function failure(error){if(error instanceof KanorioApiError)return{ok:false,code:error.code??"SERVER_ERROR"};return{ok:false,code:"NETWORK_ERROR"}}var sessionRequests=new Map;function createBearerCustomerAuthTransport(params){return bearerTransport(params,false)}function bearerTransport(params,strictSession){const siteUrl=params.siteUrl.replace(/\/+$/,"");const client=createCustomerClient({siteUrl,token:params.token});const post=async(path,body)=>{try{const data=await client.post(path,{body});return{ok:true,...data}}catch(error){return failure(error)}};const get=async path=>{try{const data=await client.get(path,{});return{ok:true,...data}}catch(error){return failure(error)}};const grant=result=>{if(result.ok&&result.sessionToken)params.onToken(result.sessionToken);return result};return{altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,requestChallenge:({email,locale,returnTo,protection})=>post("/auth/challenge",{email,locale,returnTo,...protection}),verifyCode:async({email,code})=>grant(await post("/auth/verify",{method:"code",email,code,channel:"bearer"})),verifyToken:async({method,token})=>grant(await post("/auth/verify",{method,token,channel:"bearer"})),startOauth:({method,returnTo,locale})=>post("/auth/oauth/start",{method,returnTo,locale}),passkeyLoginOptions:()=>post("/auth/passkey/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyLoginVerify:async input=>grant(await post("/auth/passkey/verify",{...input,channel:"bearer"})),listPasskeys:()=>get("/passkeys"),passkeyRegisterOptions:()=>post("/passkeys/register/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyRegister:input=>post("/passkeys/register",input),session:()=>{const token=params.token();if(!token)return Promise.resolve(null);const key=`${siteUrl}
|
|
1
|
+
import{CUSTOMER_SESSION_HINT_COOKIE_NAME,CustomerAccountPanel,createHostedCustomerAuthTransport,customerButtonClass,normalizeCustomerAuthMethods}from"./chunk-4OC7BRQS.js";import{composeRefs}from"./chunk-AQ6F6MIJ.js";import{useHydrated}from"./chunk-63XJWMJG.js";import{completeHostedCustomerLogin,startHostedCustomerLogin}from"./chunk-UWRJBUJY.js";import{onDemand}from"./chunk-E77WGXYW.js";import{LOGIN_EVENT,LOGOUT_EVENT}from"./chunk-LWKCGUHS.js";import{BotProtectionConfigProvider,parsePublicBotProtectionConfig}from"./chunk-KYXZNMNA.js";import{useSiteChrome}from"./chunk-Z4A5NQWJ.js";import{lockPageScroll}from"./chunk-HFYLTH5B.js";import{LoaderCircle,X}from"./chunk-33AQQY6T.js";import{clsx,cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{fillLabel}from"./chunk-KNNN5V3T.js";import{useSiteLabels}from"./chunk-U7H3W23Q.js";import{KanorioApiError,createCustomerClient,useElementContext}from"./chunk-73S6VKNV.js";import{useEffect as useEffect4,useMemo as useMemo2,useState as useState2}from"react";import{jsx,jsxs}from"react/jsx-runtime";import{jsx as jsx2}from"react/jsx-runtime";import{jsx as jsx3,jsxs as jsxs2}from"react/jsx-runtime";import{useEffect,useRef}from"react";import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";import{createContext,useCallback as useCallback2,useContext,useEffect as useEffect3,useMemo,useRef as useRef3,useState}from"react";import{useCallback,useEffect as useEffect2,useRef as useRef2}from"react";import{createPortal}from"react-dom";import{jsx as jsx5,jsxs as jsxs4}from"react/jsx-runtime";var FOCUSABLE_SELECTOR='a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';function SiteResponsiveModal({open,onClose,title,closeLabel,children,footer,showHeader=true,dismissible=true,desktopZIndexClassName="z-[var(--z-dialog,200)]",drawerZIndexClassName="z-[var(--z-dialog,200)]",maxWidthClassName="max-w-lg",desktopVariant="dialog",surface="glass",headerSlot,subheader,bodyClassName,footerClassName,id}){const isSide=desktopVariant==="side";const chrome=useSiteChrome();const mounted=useHydrated();const onCloseRef=useRef2(onClose);const dismissibleRef=useRef2(dismissible);useEffect2(()=>{onCloseRef.current=onClose;dismissibleRef.current=dismissible});useEffect2(()=>{if(!open)return;const releaseScrollLock=lockPageScroll();const onKeyDown=e=>{if(e.key==="Escape"&&dismissibleRef.current)onCloseRef.current()};document.addEventListener("keydown",onKeyDown);return()=>{releaseScrollLock();document.removeEventListener("keydown",onKeyDown)}},[open]);const sheetRef=useRef2(null);const subheaderRef=useRef2(null);const bodyRef=useRef2(null);const dragZoneRef=useRef2(null);const dragStartY=useRef2(null);const dragDelta=useRef2(0);const portalTarget=chrome?chrome.slots.modal:mounted?document.body:null;const rendered=open&&!!portalTarget;useEffect2(()=>{if(!rendered)return;const sheet=sheetRef.current;if(!sheet)return;const previouslyFocused=document.activeElement instanceof HTMLElement?document.activeElement:null;const focusables=()=>Array.from(sheet.querySelectorAll(FOCUSABLE_SELECTOR)).filter(el=>!el.hasAttribute("disabled")&&el.getAttribute("aria-hidden")!=="true");const firstInSubheader=subheaderRef.current?.querySelector(FOCUSABLE_SELECTOR);const firstInBody=bodyRef.current?.querySelector(FOCUSABLE_SELECTOR);(firstInSubheader??firstInBody??focusables()[0]??sheet).focus({preventScroll:true});const onKeyDown=e=>{if(e.key!=="Tab")return;const list=focusables();if(list.length===0){e.preventDefault();sheet.focus();return}const first=list[0];const last=list[list.length-1];const active=document.activeElement;const inside=active instanceof Node&&sheet.contains(active);if(e.shiftKey){if(!inside||active===first||active===sheet){e.preventDefault();last.focus()}}else if(!inside||active===last){e.preventDefault();first.focus()}};document.addEventListener("keydown",onKeyDown);return()=>{document.removeEventListener("keydown",onKeyDown);if(previouslyFocused&&previouslyFocused.isConnected){previouslyFocused.focus({preventScroll:true})}}},[rendered]);const onTouchStart=useCallback(e=>{if(!dismissibleRef.current)return;const target=e.target instanceof Node?e.target:null;const fromDragZone=!!target&&!!dragZoneRef.current?.contains(target);const bodyAtTop=(bodyRef.current?.scrollTop??0)<=0;if(!fromDragZone&&!bodyAtTop)return;dragStartY.current=e.touches[0].clientY;dragDelta.current=0},[]);const onTouchMove=useCallback(e=>{if(dragStartY.current==null)return;const delta=e.touches[0].clientY-dragStartY.current;if(delta<0&&(bodyRef.current?.scrollTop??0)>0){dragStartY.current=null;if(sheetRef.current)sheetRef.current.style.transform="";return}dragDelta.current=delta;if(delta>0&&sheetRef.current){sheetRef.current.style.transform=`translateY(${delta}px)`}},[]);const onTouchEnd=useCallback(()=>{if(dragStartY.current==null)return;if(sheetRef.current){sheetRef.current.style.transform=""}if(dragDelta.current>100&&dismissibleRef.current){onCloseRef.current()}dragStartY.current=null;dragDelta.current=0},[]);if(!rendered)return null;const headerCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"relative h-10 w-10 flex items-center justify-center rounded-full text-zinc-500 hover:text-zinc-700 dark:text-zinc-400 dark:hover:text-zinc-200 hover:bg-zinc-100 dark:hover:bg-zinc-800 transition-colors before:absolute before:-inset-0.5 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});const floatingCloseButton=jsx5("button",{type:"button",onClick:onClose,className:"absolute right-2 top-2 z-10 h-9 w-9 flex items-center justify-center rounded-full bg-black/40 text-white backdrop-blur-sm hover:bg-black/60 transition-colors before:absolute before:-inset-1 before:content-['']","aria-label":closeLabel,children:jsx5(X,{className:"h-5 w-5"})});return createPortal(jsxs4("div",{className:cn("pointer-events-auto fixed inset-0 flex items-end justify-center",isSide?"md:items-stretch md:justify-end":"md:items-center md:p-4",desktopZIndexClassName,drawerZIndexClassName),role:"dialog","aria-modal":"true","aria-label":title,children:[jsx5("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:dismissible?onClose:void 0,"aria-hidden":"true"}),jsxs4("div",{id,ref:sheetRef,tabIndex:-1,onTouchStart,onTouchMove,onTouchEnd,className:cn("relative flex w-full flex-col overflow-hidden outline-none transition-transform duration-150 ease-out","max-h-[90dvh] rounded-t-[var(--site-radius-card)]",isSide?"animate-site-side-panel md:h-full md:max-h-full md:rounded-none md:rounded-l-[var(--site-radius-card)] md:border-y-0 md:border-r-0":"animate-site-sheet-up md:max-h-[80vh] md:rounded-[var(--site-radius-card)]",surface==="glass"?"glass-card":"border border-zinc-200/50 bg-white shadow-2xl shadow-black/20 dark:border-zinc-700/50 dark:bg-zinc-900 dark:shadow-black/40","max-md:max-w-none",maxWidthClassName),children:[jsxs4("div",{ref:dragZoneRef,className:"flex shrink-0 flex-col",children:[dismissible&&jsx5("button",{type:"button",onClick:onClose,className:"mx-auto mt-1.5 mb-0.5 flex h-4 w-14 shrink-0 items-center justify-center md:hidden","aria-label":closeLabel,children:jsx5("span",{className:"h-1 w-full rounded-full bg-zinc-400 dark:bg-zinc-500"})}),showHeader?jsxs4("div",{className:"flex flex-shrink-0 items-center justify-between border-b border-zinc-200/50 px-4 py-2 dark:border-zinc-700/50",children:[headerSlot??jsx5("h2",{className:"text-lg font-semibold text-zinc-900 dark:text-zinc-50",children:title}),headerSlot&&jsx5("h2",{className:"sr-only",children:title}),dismissible&&headerCloseButton]}):dismissible&&floatingCloseButton]}),subheader&&jsx5("div",{ref:subheaderRef,className:"shrink-0",children:subheader}),jsx5("div",{ref:bodyRef,className:cn("min-h-0 flex-1 overflow-y-auto overscroll-contain kano-scrollbar",showHeader?"p-4":"p-0",bodyClassName),children}),footer&&jsx5("div",{className:cn("flex-shrink-0 border-t border-zinc-200/50 p-4 dark:border-zinc-700/50",footerClassName),children:footer})]})]}),portalTarget)}import*as React2 from"react";import*as React from"react";import{Fragment as Fragment2,jsx as jsx6}from"react/jsx-runtime";var REACT_LAZY_TYPE=Symbol.for("react.lazy");var use=React[" use ".trim().toString()];function isPromiseLike(value){return typeof value==="object"&&value!==null&&"then"in value}function isLazyComponent(element){return element!=null&&typeof element==="object"&&"$$typeof"in element&&element.$$typeof===REACT_LAZY_TYPE&&"_payload"in element&&isPromiseLike(element._payload)}function createSlot(ownerName){const SlotClone=createSlotClone(ownerName);const Slot2=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}const childrenArray=React.Children.toArray(children);const slottable=childrenArray.find(isSlottable);if(slottable){const newElement=slottable.props.children;const newChildren=childrenArray.map(child=>{if(child===slottable){if(React.Children.count(newElement)>1)return React.Children.only(null);return React.isValidElement(newElement)?newElement.props.children:null}else{return child}});return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children:React.isValidElement(newElement)?React.cloneElement(newElement,void 0,newChildren):null})}return jsx6(SlotClone,{...slotProps,ref:forwardedRef,children})});Slot2.displayName=`${ownerName}.Slot`;return Slot2}var Slot=createSlot("Slot");function createSlotClone(ownerName){const SlotClone=React.forwardRef((props,forwardedRef)=>{let{children,...slotProps}=props;if(isLazyComponent(children)&&typeof use==="function"){children=use(children._payload)}if(React.isValidElement(children)){const childrenRef=getElementRef(children);const props2=mergeProps(slotProps,children.props);if(children.type!==React.Fragment){props2.ref=forwardedRef?composeRefs(forwardedRef,childrenRef):childrenRef}return React.cloneElement(children,props2)}return React.Children.count(children)>1?React.Children.only(null):null});SlotClone.displayName=`${ownerName}.SlotClone`;return SlotClone}var SLOTTABLE_IDENTIFIER=Symbol("radix.slottable");function isSlottable(child){return React.isValidElement(child)&&typeof child.type==="function"&&"__radixId"in child.type&&child.type.__radixId===SLOTTABLE_IDENTIFIER}function mergeProps(slotProps,childProps){const overrideProps={...childProps};for(const propName in childProps){const slotPropValue=slotProps[propName];const childPropValue=childProps[propName];const isHandler=/^on[A-Z]/.test(propName);if(isHandler){if(slotPropValue&&childPropValue){overrideProps[propName]=(...args)=>{const result=childPropValue(...args);slotPropValue(...args);return result}}else if(slotPropValue){overrideProps[propName]=slotPropValue}}else if(propName==="style"){overrideProps[propName]={...slotPropValue,...childPropValue}}else if(propName==="className"){overrideProps[propName]=[slotPropValue,childPropValue].filter(Boolean).join(" ")}}return{...slotProps,...overrideProps}}function getElementRef(element){let getter=Object.getOwnPropertyDescriptor(element.props,"ref")?.get;let mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.ref}getter=Object.getOwnPropertyDescriptor(element,"ref")?.get;mayWarn=getter&&"isReactWarning"in getter&&getter.isReactWarning;if(mayWarn){return element.props.ref}return element.props.ref||element.ref}var falsyToString=value=>typeof value==="boolean"?`${value}`:value===0?"0":value;var cx=clsx;var cva=(base,config)=>props=>{var _config_compoundVariants;if((config===null||config===void 0?void 0:config.variants)==null)return cx(base,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className);const{variants,defaultVariants}=config;const getVariantClassNames=Object.keys(variants).map(variant=>{const variantProp=props===null||props===void 0?void 0:props[variant];const defaultVariantProp=defaultVariants===null||defaultVariants===void 0?void 0:defaultVariants[variant];if(variantProp===null)return null;const variantKey=falsyToString(variantProp)||falsyToString(defaultVariantProp);return variants[variant][variantKey]});const propsWithoutUndefined=props&&Object.entries(props).reduce((acc,param)=>{let[key,value]=param;if(value===void 0){return acc}acc[key]=value;return acc},{});const getCompoundVariantClassNames=config===null||config===void 0?void 0:(_config_compoundVariants=config.compoundVariants)===null||_config_compoundVariants===void 0?void 0:_config_compoundVariants.reduce((acc,param)=>{let{class:cvClass,className:cvClassName,...compoundVariantOptions}=param;return Object.entries(compoundVariantOptions).every(param2=>{let[key,value]=param2;return Array.isArray(value)?value.includes({...defaultVariants,...propsWithoutUndefined}[key]):{...defaultVariants,...propsWithoutUndefined}[key]===value})?[...acc,cvClass,cvClassName]:acc},[]);return cx(base,getVariantClassNames,getCompoundVariantClassNames,props===null||props===void 0?void 0:props.class,props===null||props===void 0?void 0:props.className)};import{jsx as jsx7}from"react/jsx-runtime";var buttonVariants=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-all duration-200 hover:scale-[1.02] hover:shadow-md active:scale-[0.98] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 cursor-pointer disabled:cursor-not-allowed disabled:pointer-events-none disabled:opacity-50 disabled:hover:scale-100 disabled:hover:shadow-none [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-11 rounded-[var(--site-radius-button)] px-4 py-2",sm:"h-9 rounded-[var(--site-radius-button)] px-3",lg:"h-14 rounded-[var(--site-radius-button)] px-8",icon:"h-11 w-11 rounded-full"}},defaultVariants:{variant:"default",size:"default"}});var Button=React2.forwardRef(({className,variant,size,asChild=false,...props},ref)=>{const Comp=asChild?Slot:"button";return jsx7(Comp,{className:cn(buttonVariants({variant,size,className})),ref,...props})});Button.displayName="Button";import{jsx as jsx8,jsxs as jsxs5}from"react/jsx-runtime";var CustomerAccountPanel2=onDemand(()=>import("./CustomerAccountPanel-LK4GSYYU.js").then(m=>m.CustomerAccountPanel),()=>jsx8("div",{className:"flex min-h-40 items-center justify-center","aria-busy":"true",children:jsx8(LoaderCircle,{className:"h-5 w-5 animate-spin opacity-50"})}));function hasCustomerSessionHint(){if(typeof document==="undefined")return false;return document.cookie.split(";").some(part=>part.trim().startsWith(`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=`))}function clearCustomerSessionHint(){if(typeof document==="undefined")return;document.cookie=`${CUSTOMER_SESSION_HINT_COOKIE_NAME}=; Max-Age=0; Path=/; SameSite=Lax`}var overviewCacheKey=siteId=>`knr_customer_overview:${siteId}`;function sessionFingerprint(sessionKey){if(sessionKey===null)return"";let hash=2166136261;for(let index=0;index<sessionKey.length;index+=1){hash^=sessionKey.charCodeAt(index);hash=Math.imul(hash,16777619)}return(hash>>>0).toString(36)}function readCachedOverview(siteId,sessionKey){try{const raw=typeof sessionStorage==="undefined"?null:sessionStorage.getItem(overviewCacheKey(siteId));if(!raw)return null;const parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||!parsed.contact||parsed.session!==sessionFingerprint(sessionKey))return null;return parsed}catch{return null}}function writeCachedOverview(siteId,overview,sessionKey){try{if(typeof sessionStorage==="undefined")return;if(overview){const{id,email,name}=overview.contact;const cached={session:sessionFingerprint(sessionKey),contact:{id,email,name},sections:overview.sections,landing:overview.landing};sessionStorage.setItem(overviewCacheKey(siteId),JSON.stringify(cached))}else sessionStorage.removeItem(overviewCacheKey(siteId))}catch{}}var SESSION_RETRY_DELAYS_MS=[1e3,3e3,1e4];var CustomerAuthContext=createContext(null);function CustomerAuthProvider({config,children}){const[user,setUser]=useState(null);const[sections,setSections]=useState([]);const[landing,setLanding]=useState(null);const[check,setCheck]=useState("pending");const[hinted,setHinted]=useState(false);const[panelOpen,setPanelOpen]=useState(false);const[refreshTick,setRefreshTick]=useState(0);const transport=useMemo(()=>config?.transport??createHostedCustomerAuthTransport(),[config?.transport]);const sessionHint=config?.sessionHint??hasCustomerSessionHint;const siteId=config?.siteId??null;const sessionKey=config?.sessionKey??null;const lastCheckRef=useRef3(null);const sessionKeyRef=useRef3(sessionKey);sessionKeyRef.current=sessionKey;const applySession=useCallback2(overview=>{if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done");if(!overview)setRefreshTick(tick=>tick+1)},[siteId]);const retrySession=useCallback2(()=>{setCheck("pending");setRefreshTick(tick=>tick+1)},[]);useEffect3(()=>{if(siteId===null)return;const previous=lastCheckRef.current;lastCheckRef.current={siteId,sessionKey};if(!sessionHint()){writeCachedOverview(siteId,null,sessionKey);setHinted(false);setUser(null);setSections([]);setLanding(null);setCheck("done");return}setHinted(true);if(previous===null||previous.siteId!==siteId||previous.sessionKey!==sessionKey)setCheck("pending");const cached=readCachedOverview(siteId,sessionKey);if(cached){setUser(cached.contact);setSections(cached.sections??[]);setLanding(cached.landing??null)}else if(previous!==null&&(previous.siteId!==siteId||previous.sessionKey!==null&&previous.sessionKey!==sessionKey)){setUser(null);setSections([]);setLanding(null)}let cancelled=false;let retryTimer=null;const ask=attempt=>{transport.session().then(overview=>{if(cancelled)return;writeCachedOverview(siteId,overview,sessionKey);if(!overview)clearCustomerSessionHint();setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")}).catch(()=>{if(cancelled)return;const delay=SESSION_RETRY_DELAYS_MS[attempt];if(delay!==void 0){retryTimer=setTimeout(()=>ask(attempt+1),delay);return}setCheck(current=>current==="pending"?"failed":current)})};ask(0);return()=>{cancelled=true;if(retryTimer!==null)clearTimeout(retryTimer)}},[siteId,sessionKey,transport,refreshTick]);useEffect3(()=>{if(!config||typeof document==="undefined")return;const sync=()=>{if(document.visibilityState!=="visible")return;const hint=sessionHint();if(hint&&user===null)setRefreshTick(tick=>tick+1);if(!hint&&user!==null){writeCachedOverview(config.siteId,null,sessionKey);setUser(null);setSections([]);setLanding(null);setCheck("done")}};document.addEventListener("visibilitychange",sync);window.addEventListener("focus",sync);return()=>{document.removeEventListener("visibilitychange",sync);window.removeEventListener("focus",sync)}},[config,user]);const refresh=useCallback2(async()=>{let overview;try{overview=await transport.session()}catch{setCheck("done");return}if(siteId)writeCachedOverview(siteId,overview,sessionKeyRef.current);setUser(overview?.contact??null);setSections(overview?.sections??[]);setLanding(overview?.landing??null);setCheck("done")},[transport,siteId]);const signOut=useCallback2(async()=>{await transport.signOut();if(siteId)writeCachedOverview(siteId,null,sessionKeyRef.current);clearCustomerSessionHint();setUser(null);setSections([]);setLanding(null);setCheck("done")},[transport,siteId]);const openPanel=useCallback2(()=>setPanelOpen(true),[]);const closePanel=useCallback2(()=>setPanelOpen(false),[]);const value=useMemo(()=>config?{siteId:config.siteId,siteName:config.siteName,locale:config.locale,siteLocale:config.siteLocale,accountBaseUrl:config.accountBaseUrl,showNavEntry:config.showNavEntry,allowSignup:config.allowSignup,methods:config.methods,messages:config.messages,transport,user,sections,landing,checked:check!=="pending",pending:hinted&&check==="pending"&&user===null,sessionUnavailable:hinted&&check==="failed"&&user===null,retrySession,applySession,refresh,signOut,panelOpen,openPanel,closePanel}:null,[config,transport,user,sections,landing,check,hinted,applySession,retrySession,refresh,signOut,panelOpen,openPanel,closePanel]);return jsxs5(CustomerAuthContext.Provider,{value,children:[children,value?jsx8(CustomerAccountModal,{auth:value}):null]})}function useCustomerAuth(){return useContext(CustomerAuthContext)}function CustomerAccountModal({auth}){const{ui}=useSiteLabels();const title=auth.user||auth.pending?ui.myAccount:fillLabel(auth.messages.signInTitle,{siteName:auth.siteName});return jsx8(SiteResponsiveModal,{id:"customer-account-panel",open:auth.panelOpen,onClose:auth.closePanel,title,closeLabel:ui.close,maxWidthClassName:"max-w-md",surface:"solid",bodyClassName:"p-5 sm:p-6",children:jsx8(CustomerAccountPanel2,{variant:"panel",auth,onNavigate:auth.closePanel})})}import{Fragment as Fragment3,jsx as jsx9,jsxs as jsxs6}from"react/jsx-runtime";function loginReturnTo(returnTo){if(returnTo?.startsWith("/"))return returnTo;if(typeof window==="undefined")return void 0;const url=new URL(window.location.href);for(const key of["token","handoff","error","verify","email"])url.searchParams.delete(key);return`${url.pathname}${url.search}`}function failure(error){if(error instanceof KanorioApiError)return{ok:false,code:error.code??"SERVER_ERROR"};return{ok:false,code:"NETWORK_ERROR"}}var sessionRequests=new Map;function createBearerCustomerAuthTransport(params){return bearerTransport(params,false)}function bearerTransport(params,strictSession){const siteUrl=params.siteUrl.replace(/\/+$/,"");const client=createCustomerClient({siteUrl,token:params.token});const post=async(path,body)=>{try{const data=await client.post(path,{body});return{ok:true,...data}}catch(error){return failure(error)}};const get=async path=>{try{const data=await client.get(path,{});return{ok:true,...data}}catch(error){return failure(error)}};const grant=result=>{if(result.ok&&result.sessionToken)params.onToken(result.sessionToken);return result};return{altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,requestChallenge:({email,locale,returnTo,protection})=>post("/auth/challenge",{email,locale,returnTo,...protection}),verifyCode:async({email,code})=>grant(await post("/auth/verify",{method:"code",email,code,channel:"bearer"})),verifyToken:async({method,token})=>grant(await post("/auth/verify",{method,token,channel:"bearer"})),startOauth:({method,returnTo,locale})=>post("/auth/oauth/start",{method,returnTo,locale}),passkeyLoginOptions:()=>post("/auth/passkey/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyLoginVerify:async input=>grant(await post("/auth/passkey/verify",{...input,channel:"bearer"})),listPasskeys:()=>get("/passkeys"),passkeyRegisterOptions:()=>post("/passkeys/register/options",{origin:typeof window==="undefined"?void 0:window.location.origin}),passkeyRegister:input=>post("/passkeys/register",input),session:()=>{const token=params.token();if(!token)return Promise.resolve(null);const key=`${siteUrl}
|
|
2
2
|
${token}`;const running=sessionRequests.get(key);const request=running??createCustomerClient({siteUrl,token}).get("/me").then(data=>{const overview=data;if(!overview.contact)return null;const{id,email,name}=overview.contact;return{contact:{id,email,name},sections:overview.sections??[],landing:overview.landing??"/account"}},error=>{if(error instanceof KanorioApiError&&error.status===401)return null;throw error});if(!running){sessionRequests.set(key,request);void request.then(()=>sessionRequests.delete(key),()=>sessionRequests.delete(key))}return strictSession?request:request.catch(()=>null)},signOut:async()=>{try{await client.delete("/session",{body:{mode:"current"}})}catch{}params.onToken(null)}}}var hostedExchanges=new Map;function hostedExchange(siteUrl,clientId){const key=`${siteUrl}|${clientId}`;const running=hostedExchanges.get(key);if(running)return running;if(!new URLSearchParams(window.location.search).has("code"))return null;const exchange={result:completeHostedCustomerLogin({siteUrl,clientId}),signedIn:false};hostedExchanges.set(key,exchange);void exchange.result.then(()=>hostedExchanges.delete(key),()=>hostedExchanges.delete(key));return exchange}function KanorioAccount({siteName,mode="direct",redirectUri,returnTo,onLogin,onLogout,renderSignedIn,className,...config}){const ctx=useElementContext(config,{needsSite:true});const site=ctx.site;const[redirectState,setRedirectState]=useState2({busy:false,error:null});const siteId=site?.id??"";const setToken=ctx.setToken;useEffect4(()=>{if(mode!=="redirect"||!siteId||typeof window==="undefined")return;const exchange=hostedExchange(ctx.siteUrl,siteId);if(!exchange)return;let cancelled=false;setRedirectState({busy:true,error:null});exchange.result.then(grant=>{if(cancelled)return;if(grant&&!exchange.signedIn){exchange.signedIn=true;setToken(grant.accessToken);const session={token:grant.accessToken,contactId:grant.contactId,expiresAt:grant.expiresAt};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))}setRedirectState({busy:false,error:null})}).catch(error=>{if(cancelled)return;setRedirectState({busy:false,error:error instanceof KanorioApiError?error.code:"NETWORK_ERROR"})});return()=>{cancelled=true}},[mode,siteId,ctx.siteUrl,setToken]);const[initial]=useState2(()=>{if(typeof window==="undefined")return{};const params=new URLSearchParams(window.location.search);return{email:params.get("email")??void 0,token:params.get("token")??void 0,handoff:params.get("handoff")??void 0,verify:params.get("verify")==="1",error:params.get("error")??void 0}});const tokenRef=useLatest(ctx.token);const transport=useMemo2(()=>bearerTransport({siteUrl:ctx.siteUrl,token:()=>tokenRef.current,onToken:token=>{tokenRef.current=token;setToken(token)}},true),[ctx.siteUrl,setToken,tokenRef]);const resolvedSiteName=siteName??site?.brand?.displayName??site?.name??"";const authConfig=useMemo2(()=>site&&ctx.messages?{siteId:site.id,siteName:resolvedSiteName,locale:ctx.locale,siteLocale:site.locale??ctx.locale,accountBaseUrl:ctx.siteUrl,showNavEntry:site.customerAccess?.showNavEntry===true,allowSignup:site.customerAccess?.allowSignup===true,methods:normalizeCustomerAuthMethods(site.customerAccess?.methods),messages:ctx.messages.account,transport,sessionHint:()=>Boolean(tokenRef.current),sessionKey:ctx.token}:null,[site,ctx.messages,ctx.locale,ctx.siteUrl,ctx.token,resolvedSiteName,transport,tokenRef]);if(!ctx.messages)return jsx9(ElementsRoot,{context:ctx,className,loading:true});return jsx9(ElementsRoot,{context:ctx,className,children:jsx9(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site?.botProtection),children:jsx9(CustomerAuthProvider,{config:authConfig,children:mode==="redirect"?jsx9(RedirectBody,{siteUrl:ctx.siteUrl,siteId,siteName:resolvedSiteName,redirectUri,busy:redirectState.busy,error:redirectState.error,messages:ctx.messages.account,onLogout,renderSignedIn}):jsx9(AccountBody,{returnTo:loginReturnTo(returnTo),initial,onLogin,onLogout,renderSignedIn})})})})}function RedirectBody({siteUrl,siteId,siteName,redirectUri,busy,error,messages,onLogout,renderSignedIn}){const auth=useCustomerAuth();const[starting,setStarting]=useState2(false);if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user){if(renderSignedIn)return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))});return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,onSignedOut:()=>emitLogout(onLogout)})})}const start=async()=>{if(!siteId)return;setStarting(true);try{await startHostedCustomerLogin({siteUrl,clientId:siteId,redirectUri})}catch{setStarting(false)}};if(auth.sessionUnavailable){return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorServiceUnavailable}),jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:auth.retrySession,children:messages.contentRetry})]})}return jsxs6("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:[error?jsx9("p",{role:"alert",className:"mb-4 text-sm text-red-700 dark:text-red-300",children:messages.errorGeneric}):null,jsx9("button",{type:"button",className:customerButtonClass({block:true}),onClick:()=>void start(),disabled:starting||busy||auth.pending||!siteId,"aria-busy":busy||auth.pending||void 0,children:busy||auth.pending?messages.sessionChecking:fillLabel(messages.signInTitle,{siteName})})]})}function AccountBody({returnTo,initial,onLogin,onLogout,renderSignedIn}){const auth=useCustomerAuth();if(!auth)return jsx9("div",{"aria-busy":"true"});if(auth.user&&renderSignedIn){return jsx9(Fragment3,{children:renderSignedIn(()=>void auth.signOut().then(()=>emitLogout(onLogout)))})}return jsx9("div",{className:"kanorio-account rounded-[var(--site-radius-card,1rem)] border border-[var(--site-border,rgba(0,0,0,0.12))] bg-[var(--site-surface,#ffffff)] p-6",children:jsx9(CustomerAccountPanel,{variant:"panel",auth,initial,returnTo,onSignedIn:grant=>{if(!grant.sessionToken)return;const session={token:grant.sessionToken,contactId:grant.contactId??"",expiresAt:grant.expiresAt??""};onLogin?.(session);window.dispatchEvent(new CustomEvent(LOGIN_EVENT,{detail:session}))},onSignedOut:()=>emitLogout(onLogout)})})}function emitLogout(onLogout){onLogout?.();window.dispatchEvent(new CustomEvent(LOGOUT_EVENT))}function useLatest(value){const ref=useState2(()=>({current:value}))[0];useEffect4(()=>{ref.current=value},[ref,value]);ref.current=value;return ref}export{createBearerCustomerAuthTransport,KanorioAccount};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-FXDWRWZ3.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as a,d as l}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{c as a,d as l}from"./chunk-XJPS3G7J.js";var c="kanorio.customer.pkce";function h(e){return{accessToken:e.access_token,tokenType:e.token_type,expiresIn:e.expires_in,expiresAt:e.expires_at,refreshToken:e.refresh_token,refreshTokenExpiresIn:e.refresh_token_expires_in,contactId:e.contactId}}function g(e){let t="";for(let r of e)t+=String.fromCharCode(r);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function d(e=32){let t=new Uint8Array(e);return crypto.getRandomValues(t),g(t)}async function y(){let e=d(32),t=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e));return{verifier:e,challenge:g(new Uint8Array(t)),method:"S256"}}function m(e){let t=e.siteUrl.replace(/\/+$/,""),r=new URL(`${t}${e.localeRoot??""}/account/login`);return r.searchParams.set("client_id",e.clientId),r.searchParams.set("redirect_uri",e.redirectUri),r.searchParams.set("code_challenge",e.codeChallenge),r.searchParams.set("code_challenge_method","S256"),r.searchParams.set("state",e.state),r.toString()}function E(){let e=new URL(window.location.href);return e.searchParams.delete("code"),e.searchParams.delete("state"),e.hash="",e.toString()}async function f(e){let t=e.storage??sessionStorage,r=e.redirectUri??E(),n=await y(),i=d(16);t.setItem(c,JSON.stringify({verifier:n.verifier,state:i,redirectUri:r}));let s=m({siteUrl:e.siteUrl,clientId:e.clientId,redirectUri:r,codeChallenge:n.challenge,state:i,localeRoot:e.localeRoot});(e.navigate??(o=>window.location.assign(o)))(s)}async function _(e){let t=new URL(window.location.href),r=t.searchParams.get("code"),n=t.searchParams.get("state");if(!r)return null;let i=e.storage??sessionStorage,s=i.getItem(c);i.removeItem(c);let o=s?JSON.parse(s):null;if(!o||o.state!==n)throw new Error("Hosted sign-in state mismatch; start the sign-in again.");e.cleanUrl!==!1&&(t.searchParams.delete("code"),t.searchParams.delete("state"),window.history.replaceState(window.history.state,"",t.toString()));let p=await u({siteUrl:e.siteUrl,clientId:e.clientId,code:r,codeVerifier:o.verifier,redirectUri:o.redirectUri});return e.storeToken!==!1&&l(p.accessToken),p}async function u(e){let r=await a({siteUrl:e.siteUrl,serverKey:e.serverKey,visitorIp:e.visitorIp}).post("/auth/oauth2/token",{body:{grant_type:"authorization_code",code:e.code,code_verifier:e.codeVerifier,redirect_uri:e.redirectUri,client_id:e.clientId}});return h(r)}export{f as a,_ as b};
|
|
2
|
+
//# sourceMappingURL=chunk-I6KLZIN6.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{NO_HEAVY_FIELD_VALIDATORS,OTHER_OPTION_PLACEHOLDER,countAnswered,hasVisibilityRules,ownFieldValue,resolveFormPhoneCountry,resolveVisibleFieldIds,sanitizeFormSubmitResponse,validateFormAnswerWith,validateFormAnswersWith}from"./chunk-D4KDA3KL.js";import{checkFormFile,uploadFormFile}from"./chunk-QF55WZDP.js";import{FORM_ACCENT_ICON,FORM_DANGER,FORM_FG,FORM_FG_MUTED,FORM_FIELD_CLASS,FORM_FIELD_INVALID_CLASS,FORM_SUBMIT_COLORS}from"./chunk-SVWEVSYJ.js";import{FORM_REDIRECT_EXPANDED_URL_MAX,isKnownFormFieldType,parseFormRedirectUrl,resolveConsentLabel,resolveFormAvailability,resolveFormDateBound}from"./chunk-APWDEDWM.js";import{onDemand}from"./chunk-E77WGXYW.js";import{useAdoptTypedOnMount,useComposingEnterGuard,useControlRef}from"./chunk-C7HUM2EN.js";import{FORM_SUBMIT_EVENT}from"./chunk-LWKCGUHS.js";import{KanorioBotProtection}from"./chunk-J5SMJRYC.js";import{BotProtectionChallenge,BotProtectionConfigProvider,BotProtectionFields,parsePublicBotProtectionConfig,useBotProtection}from"./chunk-KYXZNMNA.js";import{TONE_BG_TINT,TONE_BG_TINT_STRONG_HOVER,TONE_BORDER_STRONG,TONE_TEXT_FAINT}from"./chunk-RKEHHJDU.js";import{EMPTY_VALUE,dateTimeFormat}from"./chunk-4BEKWYEW.js";import{clampText}from"./chunk-O2SYHUQF.js";import{CircleCheck,Heart,LoaderCircle,Star,ThumbsUp}from"./chunk-33AQQY6T.js";import{cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-QRKYFFDH.js";import{loadSiteMeta,useElementContext}from"./chunk-RI64PHGM.js";import{useEffect,useMemo,useState}from"react";var SITE_RETRY_DELAYS_MS=[1e3,3e3,1e4];function useDefinitionByContent(definition){const content=definition?JSON.stringify(definition):null;return useMemo(()=>definition??null,[content])}function useKanorioFormSetup(config,formId,initialDefinition,labels){const ctx=useElementContext(config,{needsSite:true});const{site,siteError,siteUrl}=ctx;const given=useDefinitionByContent(initialDefinition);const[read,setRead]=useState(null);const siteMissing=!site&&siteError;const[siteRetries,setSiteRetries]=useState({siteUrl,count:0});const retried=siteRetries.siteUrl===siteUrl?siteRetries.count:0;useEffect(()=>{if(!siteMissing)return;const delay=SITE_RETRY_DELAYS_MS[retried];if(delay===void 0)return;const timer=setTimeout(()=>{void loadSiteMeta(siteUrl).then(meta=>{if(meta===null)setSiteRetries({siteUrl,count:retried+1})})},delay);return()=>clearTimeout(timer)},[siteMissing,siteUrl,retried]);useEffect(()=>{if(given||!formId)return;let cancelled=false;fetch(`${siteUrl}/api/v1/forms/${encodeURIComponent(formId)}`).then(res=>res.ok?res.json():Promise.reject(new Error(`HTTP ${res.status}`))).then(data=>{if(cancelled)return;const resolved=data&&typeof data==="object"&&"fields"in data?data:data?.form??null;setRead({siteUrl,formId,form:resolved??null})}).catch(()=>{if(!cancelled)setRead({siteUrl,formId,form:null})});return()=>{cancelled=true}},[siteUrl,formId,given]);const current=read!==null&&read.siteUrl===siteUrl&&read.formId===formId?read:null;const form=given??current?.form??null;const siteText=ctx.messages?.form;const mergedLabels=useMemo(()=>siteText||labels?{...siteText??{},...labels??{}}:void 0,[siteText,labels]);return{ctx,form,loadFailed:!given&¤t!==null&¤t.form===null,siteUnavailable:Boolean(siteMissing)&&retried>=SITE_RETRY_DELAYS_MS.length,textUnavailable:ctx.messages===null&&ctx.messagesError,mergedLabels,ready:Boolean(form&&ctx.messages&&site)}}import{useContext as useContext2}from"react";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";function SiteChoiceInput({type,className,...props}){const inputRef=useRef(null);useAdoptTypedOnMount(inputRef,props.onChange);return jsxs("span",{className:cn("relative inline-grid h-[18px] w-[18px] shrink-0 place-items-center",className),children:[jsx("input",{ref:inputRef,type,className:cn("peer col-start-1 row-start-1 m-0 h-[18px] w-[18px] cursor-pointer appearance-none border-2 transition-colors","bg-transparent "+TONE_BORDER_STRONG,"checked:border-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))] checked:bg-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))]","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]","disabled:cursor-not-allowed disabled:opacity-50",type==="radio"?"rounded-full":"rounded-[4px]"),...props}),type==="checkbox"?jsx("svg",{"aria-hidden":true,viewBox:"0 0 16 16",fill:"none",className:"pointer-events-none col-start-1 row-start-1 h-3.5 w-3.5 text-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50",children:jsx("path",{d:"M3.5 8.5l3 3 6-6.5",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})}):jsx("span",{"aria-hidden":true,className:"pointer-events-none col-start-1 row-start-1 h-2 w-2 rounded-full bg-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50"})]})}var MAX_COLUMNS_FALLBACK={mobile:1,tablet:2,desktop:2};var GRID_COLS={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6"};var SM_GRID_COLS={1:"sm:grid-cols-1",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-4",5:"sm:grid-cols-5",6:"sm:grid-cols-6"};var MD_GRID_COLS={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4",5:"md:grid-cols-5",6:"md:grid-cols-6"};function clampColumn(value){const n=Math.max(1,Math.min(6,Math.round(value)));return n}function getGridColumnsClass(maxColumns,itemCount){const resolve=raw=>{const capped=clampColumn(raw);if(itemCount==null)return capped;return clampColumn(Math.min(capped,Math.max(1,itemCount)))};const mobile=resolve(maxColumns?.mobile??MAX_COLUMNS_FALLBACK.mobile);const tablet=resolve(maxColumns?.tablet??MAX_COLUMNS_FALLBACK.tablet);const desktop=resolve(maxColumns?.desktop??MAX_COLUMNS_FALLBACK.desktop);return`${GRID_COLS[mobile]} ${SM_GRID_COLS[tablet]} ${MD_GRID_COLS[desktop]}`}import{createContext}from"react";var FormFieldComponentsContext=createContext(null);var FormFieldUnavailableLabelContext=createContext("");import{useContext}from"react";import{jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function FieldLoading({failed,props}){const unavailableLabel=useContext(FormFieldUnavailableLabelContext);const{inputId}=props;return jsxs2("div",{children:[jsx2("div",{id:inputId,tabIndex:inputId?-1:void 0,className:cn("h-11 w-full",FORM_FIELD_CLASS),"aria-busy":failed?void 0:"true","data-field-unavailable":failed?"":void 0}),failed&&unavailableLabel&&jsx2("p",{role:"alert",className:cn("mt-1.5 text-xs",FORM_DANGER),children:unavailableLabel})]})}var ON_DEMAND_FORM_FIELDS={PhoneInput:onDemand(()=>import("./phone-input-DOL46AIF.js").then(m=>m.PhoneInput),FieldLoading),FormAddressField:onDemand(()=>import("./FormAddressField-NH5LD6K7.js").then(m=>m.FormAddressField),FieldLoading),FormTaxIdField:onDemand(()=>import("./FormTaxIdField-XJSMW3II.js").then(m=>m.FormTaxIdField),FieldLoading),FormFileField:onDemand(()=>import("./FormFileField-5YFTKIRZ.js").then(m=>m.FormFileField),FieldLoading),FormChoiceDropdown:onDemand(()=>import("./FormChoiceDropdown-U3NIOOHG.js").then(m=>m.FormChoiceDropdown),FieldLoading)};var FORM_LIFECYCLE_EVENT="kanorio:form-event";import{useCallback,useEffect as useEffect2,useId,useMemo as useMemo2,useRef as useRef2,useState as useState2}from"react";var DATE_PRESETS={date:{dateStyle:"medium"},dateLong:{dateStyle:"long"},dateTime:{dateStyle:"medium",timeStyle:"short"},dateTimeFull:{dateStyle:"full",timeStyle:"short"},time:{timeStyle:"short"},monthDay:{month:"short",day:"numeric"},monthDayTime:{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},monthYear:{year:"numeric",month:"long"},dateWithZone:{year:"numeric",month:"long",day:"numeric",timeZoneName:"short"}};var CALENDAR_DATE=/^\d{4}-\d{2}-\d{2}$/;function isCalendarDate(value){return typeof value==="string"&&CALENDAR_DATE.test(value)}function toDate(value){if(value==null||value==="")return null;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?null:date}function formatCalendarDate(value,preset="date",options){if(!isCalendarDate(value))return EMPTY_VALUE;const date=new Date(`${value}T00:00:00Z`);if(Number.isNaN(date.getTime()))return EMPTY_VALUE;return dateTimeFormat(options.locale,{...DATE_PRESETS[preset],timeZone:"UTC"}).format(date)}function toCalendarDateIn(value,timeZone){const date=toDate(value);if(!date)return"";return dateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit",timeZone}).format(date)}var MINUTE=6e4;var HOUR=60*MINUTE;var DAY=24*HOUR;var loaded={...NO_HEAVY_FIELD_VALIDATORS};var pending=new Map;var LOADERS={phone:()=>import("./forms-answers-phone-2VZ46OME.js").then(m=>void(loaded.phone=m.validatePhoneAnswer)),address:()=>import("./forms-answers-address-5MXQYIH3.js").then(m=>void(loaded.address=m.validateAddressAnswer)),tax_id:()=>import("./forms-answers-tax-id-3AYXCNP5.js").then(m=>void(loaded.tax_id=m.validateTaxIdAnswer))};function isHeavyFieldType(type){return Object.hasOwn(LOADERS,type)}function loadedFormFieldValidators(){return loaded}function canValidateFormField(type){return!isHeavyFieldType(type)||loaded[type]!==null}function hasFormFieldValidators(types){for(const type of types)if(!canValidateFormField(type))return false;return true}function loadFormFieldValidators(types){const waits=[];for(const type of new Set(types)){if(!isHeavyFieldType(type)||loaded[type])continue;let wait=pending.get(type);if(!wait){wait=LOADERS[type]().finally(()=>pending.delete(type));pending.set(type,wait)}waits.push(wait)}return Promise.all(waits).then(()=>loaded)}var PAGEVIEW_ATTRIBUTION_PARAMS=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","fbclid","oppref"];var MAX_ATTRIBUTION_VALUE_LENGTH=200;var ATTRIBUTION_VALUE_ALLOWED=/[^\p{L}\p{N} _\-./:+%()&=|]/gu;function sanitizePageviewAttribution(read){const utm={};for(const key of PAGEVIEW_ATTRIBUTION_PARAMS){const raw=read(key);if(typeof raw!=="string"||!raw)continue;const val=clampText(raw.replace(ATTRIBUTION_VALUE_ALLOWED,"").trim(),MAX_ATTRIBUTION_VALUE_LENGTH);if(val)utm[key]=val}return Object.keys(utm).length>0?utm:null}var HOST_RE=/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;var LANDING_PATH_MAX=500;function sanitizeHost(raw){if(typeof raw!=="string")return void 0;const host=raw.trim().toLowerCase();return HOST_RE.test(host)?host:void 0}function sanitizeLandingPath(raw){if(typeof raw!=="string")return void 0;const path=raw.trim().split(/[?#]/)[0]??"";if(!path.startsWith("/")||path.startsWith("//")||/[\s\\\0]/.test(path))return void 0;return path.slice(0,LANDING_PATH_MAX)}function sanitizeFormAttribution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const input=raw;const utmInput=input.utm&&typeof input.utm==="object"&&!Array.isArray(input.utm)?input.utm:{};const utm=sanitizePageviewAttribution(key=>utmInput[key]);const referrerHost=sanitizeHost(input.referrerHost);const landingPath=sanitizeLandingPath(input.landingPath);const out={};if(utm)out.utm=utm;if(referrerHost)out.referrerHost=referrerHost;if(landingPath)out.landingPath=landingPath;return Object.keys(out).length>0?out:null}function buildFormAttribution(input){let utm=null;try{const params=new URLSearchParams(input.search??"");utm=sanitizePageviewAttribution(key=>params.get(key))}catch{utm=null}let referrerHost;try{referrerHost=input.referrer?new URL(input.referrer).hostname:void 0}catch{referrerHost=void 0}return sanitizeFormAttribution({utm:utm??void 0,referrerHost,landingPath:input.path??void 0})}var SESSION_ATTRIBUTION_KEY="kano-session-attribution";function readSessionAttribution(){if(typeof window==="undefined")return null;try{const raw=window.sessionStorage.getItem(SESSION_ATTRIBUTION_KEY);return raw?sanitizeFormAttribution(JSON.parse(raw)):null}catch{return null}}function currentFormAttribution(){if(typeof window==="undefined")return null;const stored=readSessionAttribution();if(stored)return stored;let referrer=null;try{referrer=document.referrer&&new URL(document.referrer).hostname.toLowerCase()!==window.location.hostname.toLowerCase()?document.referrer:null}catch{referrer=null}return buildFormAttribution({search:window.location.search,referrer,path:window.location.pathname})}var VALIDATOR_WAIT_MS=4e3;var DEFAULT_FORM_LABELS={submit:"Submit",submitting:"Submitting\u2026",success:"Thanks! We\u2019ll be in touch soon.",error:"Something went wrong. Please try again.",required:"This field is required.",invalidEmail:"Please enter a valid email address.",invalidPhone:"Please enter a valid phone number.",invalidDate:"Please enter a valid date.",invalidTime:"Please enter a valid time.",tooLong:"This answer is too long.",otherRequired:"Please specify your answer.",duplicate:"This email or phone number has already been used. Only one response per person is allowed.",temporarilyUnavailable:"This form isn\u2019t accepting responses right now. Please try again later.",rateLimited:"Too many submissions. Please wait a moment and try again.",verificationExpired:"Verification expired. Please verify again and resubmit.",outdated:"This form has changed since you opened it. Please refresh the page and submit again.",edgeChallenge:"Your browser didn\u2019t pass this site\u2019s security check. Please reload the page and submit again.",tooLarge:"Your answers are too long to send. Please shorten them and try again.",redirecting:"Taking you to the next page\u2026",invalid:"Please check this answer.",tooShort:"Please enter at least {min} characters.",invalidNumber:"Please enter a number.",notInteger:"Please enter a whole number.",numberMin:"Please enter {min} or more.",numberMax:"Please enter {max} or less.",numberRange:"Please enter a number from {min} to {max}.",invalidUrl:"Please enter a web address, such as example.com.",dateMin:"Please choose {min} or later.",dateMax:"Please choose {max} or earlier.",dateRange:"Please choose a date from {min} to {max}.",tooFewOptions:"Please select {min} or more.",tooManyOptions:"Please select no more than {max}.",selectPlaceholder:"Select an option",invalidAddress:"Please complete the address.",invalidTaxId:"Please check this tax ID.",taxIdChecking:"Looking up the public registry\u2026",taxIdRegisteredName:"Registered name: {name}",taxIdInactive:"The registry shows this business as suspended or closed. Please check the tax ID.",taxIdSource:"Source: {provider}",invalidPostalCode:"Please check the postal code.",addressCountry:"Country or region",addressRecipient:"Recipient name",addressLine1:"Address",addressLine2:"Apartment, suite, etc. (optional)",addressPostal_postal:"Postal code",addressPostal_zip:"ZIP code",addressPostal_pin:"PIN code",addressPostal_eircode:"Eircode",addressLocality_city:"City",addressLocality_district:"District",addressLocality_post_town:"Town or city",addressLocality_suburb:"Suburb",addressRegion_area:"Area",addressRegion_county:"County",addressRegion_department:"Department",addressRegion_district:"District",addressRegion_do_si:"Province or city",addressRegion_emirate:"Emirate",addressRegion_island:"Island",addressRegion_oblast:"Oblast",addressRegion_parish:"Parish",addressRegion_prefecture:"Prefecture",addressRegion_province:"Province",addressRegion_state:"State",marketingOptIn:"I\u2019d like to receive news and offers from {siteName} by email. I can unsubscribe from any email with one click.",subscribeOnSubmit:"By clicking \u201C{button}\u201D, you agree to receive news and offers from {siteName} by email. You can unsubscribe from any email with one click.",otherOption:"Other",otherPlaceholder:"Please specify",closed:"This form is closed.",notOpenYet:"This form isn\u2019t open yet.",full:"All spots have been filled. Thank you for your interest.",fileChoose:"Choose a file",fileLimitHint:"Up to {max} file(s), {size} each.",fileWaiting:"Waiting for verification\u2026",fileUploading:"Uploading\u2026",fileUploadFailed:"Upload failed. Please try again.",fileTooLarge:"This file is too large.",fileTypeNotAllowed:"This file type isn\u2019t supported.",fileUnavailable:"Attachments can\u2019t be uploaded right now. You can still submit the form.",fileRemove:"Remove",noFormSelected:"Select a form in the panel to display it here.",formNotFound:"The selected form no longer exists.",previewNotice:"Preview only \u2014 submissions are disabled here."};function fill(template,values){return template.replaceAll("{min}",String(values.min??"")).replaceAll("{max}",String(values.max??""))}function errorLabel(code,field,{labels,today,locale}){switch(code){case"invalid_email":return labels.invalidEmail;case"invalid_phone":return labels.invalidPhone;case"invalid_date":return labels.invalidDate;case"invalid_time":return labels.invalidTime;case"too_long":return labels.tooLong;case"too_short":return(field.type==="short_text"||field.type==="long_text")&&field.minLength!==void 0?fill(labels.tooShort,{min:field.minLength}):labels.invalid;case"invalid_format":return field.type==="short_text"&&field.patternMessage?field.patternMessage:labels.invalid;case"other_required":return labels.otherRequired;case"too_few_options":return field.type==="choice"&&field.minSelections!==void 0?fill(labels.tooFewOptions,{min:field.minSelections}):labels.invalid;case"too_many_options":return field.type==="choice"&&field.maxSelections!==void 0?fill(labels.tooManyOptions,{max:field.maxSelections}):labels.invalid;case"invalid_number":return labels.invalidNumber;case"not_integer":return labels.notInteger;case"out_of_range":{if(field.type!=="number")return labels.invalid;const{min,max}=field;if(min!==void 0&&max!==void 0)return fill(labels.numberRange,{min,max});if(min!==void 0)return fill(labels.numberMin,{min});if(max!==void 0)return fill(labels.numberMax,{max});return labels.invalid}case"invalid_url":return labels.invalidUrl;case"date_out_of_range":{if(field.type!=="date")return labels.invalid;const min=resolveFormDateBound(field.range?.min,today);const max=resolveFormDateBound(field.range?.max,today);const show=date=>formatCalendarDate(date,"date",{locale});if(min&&max)return fill(labels.dateRange,{min:show(min),max:show(max)});if(min)return fill(labels.dateMin,{min:show(min)});if(max)return fill(labels.dateMax,{max:show(max)});return labels.invalid}case"invalid_address":return labels.invalidAddress;case"invalid_tax_id":return labels.invalidTaxId;case"invalid_postal_code":return labels.invalidPostalCode;case"invalid":return labels.invalid;case"required":case"invalid_option":return labels.required}}function todayIn(timeZone){const now=new Date;if(timeZone){try{const date=toCalendarDateIn(now,timeZone);if(date)return date}catch{}}const pad=n=>String(n).padStart(2,"0");return`${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`}function submitErrorLabel(error,labels){switch(error){case"outdated":return labels.outdated;case"edge_challenge":return labels.edgeChallenge;case"duplicate":return labels.duplicate;case"daily_limit":case"temporarily_unavailable":return labels.temporarilyUnavailable;case"rate_limited":return labels.rateLimited;case"verification_expired":return labels.verificationExpired;case"too_large":return labels.tooLarge;case"invalid_answers":case"server_error":return labels.error}}function cssAttributeValue(value){return value.replace(/["\\]/g,"\\$&")}function dispatchLifecycle(detail){if(typeof window==="undefined")return;window.dispatchEvent(new CustomEvent(FORM_LIFECYCLE_EVENT,{detail}))}function singleLineInputProps(field,today){switch(field.type){case"short_text":return{type:"text",maxLength:field.maxLength,autoComplete:field.contactMapping==="name"?"name":void 0};case"email":return{type:"email",inputMode:"email",autoComplete:"email"};case"date":return{type:"date",min:resolveFormDateBound(field.range?.min,today)??void 0,max:resolveFormDateBound(field.range?.max,today)??void 0};case"time":return{type:"time"};case"number":return{type:"text",inputMode:field.integer&&(field.min??-1)>=0?"numeric":"decimal",autoComplete:"off"};case"url":return{type:"url",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:false,placeholder:"https://"};default:return null}}function useFormController(options){const{form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues:hiddenValuesProp,isEditing=false,labels:labelsProp,locale,websiteName,botProtectionConfig,botProtectionPending=false}=options;const formId=form?.id??options.formId??"";const labels=useMemo2(()=>({...DEFAULT_FORM_LABELS,...labelsProp}),[labelsProp]);const formFields=form?.fields;const fields=useMemo2(()=>(formFields??[]).filter(field=>isKnownFormFieldType(field.type)),[formFields]);const consentLabel=form?resolveConsentLabel(form.settings,labels,websiteName):null;const canSubmit=Boolean(submitUrl)&&!isEditing&&form!==null;const[serverState,setServerState]=useState2(null);const availability=serverState??(form?resolveFormAvailability(form):"open");const isClosed=availability!=="open";const[answers,setAnswers]=useState2({});const[otherText,setOtherText]=useState2({});const answersRef=useRef2(answers);const otherTextRef=useRef2(otherText);const marketingOptInRef=useRef2(false);const updateAnswers=useCallback(update=>{const next=update(answersRef.current);if(next===answersRef.current)return;answersRef.current=next;setAnswers(next)},[]);const[uploadUnavailable,setUploadUnavailable]=useState2({});const[uploadBusy,setUploadBusy]=useState2({});const anyUploadBusy=Object.values(uploadBusy).some(Boolean);const uploadsInFlightRef=useRef2({});const hasUploadInFlight=useCallback(()=>Object.values(uploadsInFlightRef.current).some(count=>count>0),[]);const consentMode=form?.settings.marketingConsent??"off";const[marketingOptIn,setMarketingOptInState]=useState2(false);const setMarketingOptIn=useCallback(checked=>{marketingOptInRef.current=checked;setMarketingOptInState(checked)},[]);const[errors,setErrors]=useState2({});const[submitError,setSubmitError]=useState2(null);const[status,setStatusState]=useState2("idle");const statusRef=useRef2("idle");const setStatus=useCallback(next=>{statusRef.current=next;setStatusState(next)},[]);const[result,setResult]=useState2(null);const[altchaKey,setAltchaKey]=useState2(0);const[redirecting,setRedirecting]=useState2(false);const declaredHiddenFields=form?.settings.hiddenFields;const hiddenFields=useMemo2(()=>declaredHiddenFields??[],[declaredHiddenFields]);const[urlHiddenValues,setUrlHiddenValues]=useState2({});const hiddenFieldIds=JSON.stringify(hiddenFields.map(hidden=>hidden.id));useEffect2(()=>{const ids=JSON.parse(hiddenFieldIds);if(ids.length===0||typeof window==="undefined")return;const params=new URLSearchParams(window.location.search);const next={};for(const id of ids){const value=params.get(id);if(value)next[id]=value}setUrlHiddenValues(next)},[hiddenFieldIds]);const hiddenValues=useMemo2(()=>({...urlHiddenValues,...hiddenValuesProp??{}}),[urlHiddenValues,hiddenValuesProp]);const hasRules=useMemo2(()=>hasVisibilityRules(fields),[fields]);const visibleFieldsFor=useCallback(current=>{if(!hasRules)return fields;const visible=resolveVisibleFieldIds(fields,{...hiddenValues,...current});return fields.filter(field=>visible.has(field.id))},[hasRules,fields,hiddenValues]);const visibleFields=useMemo2(()=>visibleFieldsFor(answers),[visibleFieldsFor,answers]);const startedRef=useRef2(false);const viewedRef=useRef2(false);const rootRef=useRef2(null);const[rootElement,setRootElement]=useState2(null);const setRoot=useCallback(element=>{rootRef.current=element;setRootElement(element)},[]);const fieldIdPrefix=`form-${useId().replace(/[^A-Za-z0-9_-]/g,"")}-field`;const inputIdOf=useCallback(fieldId=>`${fieldIdPrefix}-${fieldId}`,[fieldIdPrefix]);const protection=useBotProtection({variant:"full",context:formId,entry:"forms",needsUploadToken:fields.some(field=>field.type==="file"||field.type==="tax_id"),...challengeUrl?{challengeUrl}:{},...altchaChallengeUrl?{altchaChallengeUrl}:{},...botProtectionConfig!==void 0?{config:botProtectionConfig}:{}});const protectionSubmittable=protection.isSubmittable&&!botProtectionPending;const uploadReady=protection.isUploadReady&&!botProtectionPending;const uploadUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/upload-request"):null;const taxIdLookupUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/tax-id-lookup"):null;const taxIdLookupReady=Boolean(taxIdLookupUrl)&&uploadReady;const getUploadProtectionData=protection.getUploadProtectionData;const lookupTaxId=useCallback(async(fieldId,input)=>{if(!taxIdLookupUrl)return null;try{const res=await fetch(taxIdLookupUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fieldId,...input,...getUploadProtectionData()})});if(!res.ok)return null;const data=await res.json();if(!data||data.ok===false||typeof data.status!=="string")return null;return{...data,ok:true}}catch{return null}},[taxIdLookupUrl,getUploadProtectionData]);useEffect2(()=>{if(!canSubmit||viewedRef.current||!rootElement)return;const el=rootElement;if(typeof IntersectionObserver==="undefined"){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});return}const io=new IntersectionObserver(entries=>{if(entries.some(e=>e.isIntersecting)&&!viewedRef.current){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});io.disconnect()}},{threshold:.3});io.observe(el);return()=>io.disconnect()},[canSubmit,formId,rootElement]);const lastFieldRef=useRef2(null);const abandonRef=useRef2({status,visibleFields,answers});useEffect2(()=>{abandonRef.current={status,visibleFields,answers}},[status,visibleFields,answers]);useEffect2(()=>{if(!canSubmit||typeof window==="undefined")return;let sent=false;const onPageHide=()=>{const latest=abandonRef.current;if(sent||!startedRef.current||latest.status==="success")return;sent=true;dispatchLifecycle({type:"form_abandon",formId,lastFieldId:lastFieldRef.current,answeredCount:countAnswered(latest.visibleFields,latest.answers)})};window.addEventListener("pagehide",onPageHide);return()=>window.removeEventListener("pagehide",onPageHide)},[canSubmit,formId]);const markStarted=useCallback(()=>{protection.registerFocus();if(startedRef.current||!canSubmit)return;startedRef.current=true;dispatchLifecycle({type:"form_start",formId})},[protection,canSubmit,formId]);const focusField=useCallback(fieldId=>{lastFieldRef.current=fieldId;markStarted()},[markStarted]);const clearError=useCallback(id=>{setErrors(prev=>{if(!ownFieldValue(prev,id))return prev;const next={...prev};delete next[id];return next})},[]);const setAnswer=useCallback((id,value)=>{lastFieldRef.current=id;updateAnswers(prev=>({...prev,[id]:value}));clearError(id);setSubmitError(null)},[clearError,updateAnswers]);const setOtherAnswer=useCallback((id,text)=>{otherTextRef.current={...otherTextRef.current,[id]:text};setOtherText(otherTextRef.current);clearError(id)},[clearError]);const[today,setToday]=useState2(null);const timezone=form?.timezone;useEffect2(()=>{setToday(todayIn(timezone))},[timezone]);const fieldTypes=useMemo2(()=>Array.from(new Set(fields.map(field=>field.type))),[fields]);useEffect2(()=>{loadFormFieldValidators(fieldTypes).catch(()=>void 0)},[fieldTypes]);const[preparing,setPreparing]=useState2(false);const preparingRef=useRef2(false);const resendSameRef=useRef2(false);const defaultPhoneCountry=form?.defaultPhoneCountry;const validationCtx=useMemo2(()=>({defaultPhoneCountry,fileRequired:{exempt:Object.keys(uploadUnavailable).filter(id=>uploadUnavailable[id])},today}),[defaultPhoneCountry,uploadUnavailable,today]);const errorCtx=useMemo2(()=>({labels,today:today??todayIn(timezone),locale:locale||(typeof navigator!=="undefined"?navigator.language:"en")}),[labels,today,timezone,locale]);const validateOne=useCallback(field=>{if(!canValidateFormField(field.type))return;const code=validateFormAnswerWith(loadedFormFieldValidators(),field,{answers:answersRef.current,otherText:otherTextRef.current},validationCtx);if(code&&code!=="required")setErrors(prev=>({...prev,[field.id]:code}));else clearError(field.id)},[validationCtx,clearError]);const validateField=useCallback(fieldId=>{const field=fields.find(f=>f.id===fieldId);if(field)validateOne(field)},[fields,validateOne]);const focusFirstError=useCallback(errorIds=>{const root=rootRef.current;if(!root)return;for(const field of fields){if(!errorIds.includes(field.id))continue;const el=root.querySelector(`[id="${cssAttributeValue(inputIdOf(field.id))}"]`);if(!el)continue;el.scrollIntoView?.({behavior:"smooth",block:"center"});el.focus({preventScroll:true});return}},[fields,inputIdOf]);const submitAnswers=useCallback(async validators=>{if(!canSubmit||!form||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight())return;const current=answersRef.current;const optedIn=marketingOptInRef.current;const validated=validateFormAnswersWith(validators,fields,{answers:{...hiddenValues,...current},otherText:otherTextRef.current},{...validationCtx,hiddenFields});if(!validated.ok){setErrors(validated.errors);focusFirstError(Object.keys(validated.errors));return}setStatus("submitting");setSubmitError(null);let sent=false;try{if(!resendSameRef.current)await protection.prepare();sent=true;const res=await fetch(submitUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:validated.answers,...consentMode==="submit"?{consent:"submit_statement",consentTextId:form.consentTextId}:consentMode==="checkbox"&&optedIn?{consent:"checked",consentTextId:form.consentTextId}:{},locale:typeof navigator!=="undefined"?navigator.language:void 0,...locale?{pageLocale:locale}:{},pagePath:typeof window!=="undefined"?window.location.pathname:void 0,attribution:currentFormAttribution()??void 0,...protection.getProtectionData()})});if(res.headers.get("cf-mitigated")==="challenge"){setStatus("idle");setSubmitError("edge_challenge");resendSameRef.current=false;protection.renewCaptcha();return}const data=sanitizeFormSubmitResponse(res.status===429?{ok:false,error:"rate_limited"}:res.status===503?{ok:false,error:"temporarily_unavailable"}:await res.json().catch(()=>null));setStatus("idle");const resendSame=!data.ok&&data.error==="temporarily_unavailable";resendSameRef.current=resendSame;if(data.ok?Boolean(data.state):!resendSame){protection.renewCaptcha()}if(data.ok){if(data.state){setServerState(data.state);return}setStatus("success");const redirectUrl=data.redirectUrl??parseFormRedirectUrl(form.redirectUrl,{maxLength:FORM_REDIRECT_EXPANDED_URL_MAX})?.url;const detail={formId:form.id,...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}};setResult({...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}});onSuccess?.(detail);if(redirectUrl&&followRedirect){setRedirecting(true);window.location.assign(redirectUrl)}return}const errorIds=data.error==="invalid_answers"&&data.errors?Object.keys(data.errors):[];const renderedIds=new Set(visibleFieldsFor(current).map(f=>f.id));setSubmitError(errorIds.some(id=>!renderedIds.has(id))?"outdated":data.error);if(errorIds.length>0){setErrors(data.errors);focusFirstError(errorIds)}if(data.error==="verification_expired"||data.error==="duplicate")setAltchaKey(k=>k+1)}catch{setStatus("idle");setSubmitError("server_error");if(sent)resendSameRef.current=true;else protection.renewCaptcha()}},[canSubmit,form,setStatus,isClosed,anyUploadBusy,hasUploadInFlight,validationCtx,focusFirstError,fields,visibleFieldsFor,hiddenFields,hiddenValues,followRedirect,submitUrl,consentMode,locale,protection,onSuccess]);const submitAnswersRef=useRef2(submitAnswers);useEffect2(()=>{submitAnswersRef.current=submitAnswers},[submitAnswers]);const handleSubmit=useCallback(async e=>{e?.preventDefault();if(!canSubmit||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight()||preparingRef.current||!protectionSubmittable)return;if(hasFormFieldValidators(fieldTypes))return submitAnswers(loadedFormFieldValidators());preparingRef.current=true;setPreparing(true);let timer;try{await Promise.race([loadFormFieldValidators(fieldTypes),new Promise(resolve=>timer=setTimeout(resolve,VALIDATOR_WAIT_MS))])}catch{}finally{clearTimeout(timer);preparingRef.current=false;setPreparing(false)}await submitAnswersRef.current(loadedFormFieldValidators())},[canSubmit,isClosed,anyUploadBusy,hasUploadInFlight,protectionSubmittable,fieldTypes,submitAnswers]);const autofilledRef=useRef2({});const fillCompanyName=useCallback((targetId,name)=>{updateAnswers(prev=>{const currentValue=prev[targetId];const text=typeof currentValue==="string"?currentValue:"";if(text.trim()!==""&&text!==autofilledRef.current[targetId])return prev;autofilledRef.current[targetId]=name;return{...prev,[targetId]:name}})},[updateAnswers]);const setUnavailable=useCallback((id,unavailable)=>{setUploadUnavailable(prev=>prev[id]===unavailable?prev:{...prev,[id]:unavailable})},[]);const setBusy=useCallback((id,busy)=>{setUploadBusy(prev=>prev[id]===busy?prev:{...prev,[id]:busy})},[]);const uploadFile=useCallback(async(fieldId,file,uploadOptions={})=>{const field=fields.find(f=>f.id===fieldId);if(!field||field.type!=="file")return{ok:false,reason:"not_a_file_question"};focusField(fieldId);if(!uploadUrl||!uploadReady)return{ok:false,reason:"not_ready"};const current=ownFieldValue(answersRef.current,fieldId);const accepted=Array.isArray(current)?current.length:0;const inFlight=ownFieldValue(uploadsInFlightRef.current,fieldId)??0;if(accepted+inFlight>=field.maxFiles)return{ok:false,reason:"too_many_files"};const problem=checkFormFile(field,file);if(problem)return{ok:false,reason:problem};uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:inFlight+1};setBusy(fieldId,true);try{const uploaded=await uploadFormFile({uploadUrl,fieldId,file,protection:getUploadProtectionData(),onProgress:uploadOptions.onProgress,signal:uploadOptions.signal});if(uploaded.ok){updateAnswers(prev=>{const ids=Array.isArray(prev[fieldId])?prev[fieldId]:[];return{...prev,[fieldId]:[...ids,uploaded.uploadId]}});clearError(fieldId);setSubmitError(null)}else if(uploaded.reason==="unavailable"){setUnavailable(fieldId,true)}return uploaded}finally{const left=Math.max(0,(ownFieldValue(uploadsInFlightRef.current,fieldId)??1)-1);uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:left};if(left===0)setBusy(fieldId,false)}},[fields,uploadUrl,uploadReady,focusField,setBusy,getUploadProtectionData,updateAnswers,clearError,setUnavailable]);const errorMessage=useCallback(fieldId=>{const code=ownFieldValue(errors,fieldId);if(!code)return void 0;const field=fields.find(f=>f.id===fieldId);return field?errorLabel(code,field,errorCtx):labels.invalid},[errors,fields,errorCtx,labels.invalid]);return{form,formId,labels,fields,visibleFields,canSubmit,availability,isClosed,status,preparing,redirecting,result,successMessage:form?.settings.successMessage||labels.success,answers,setAnswer,otherText,setOtherAnswer,errors,errorMessage,validateField,validateOne,submitError,submitErrorMessage:submitError?submitErrorLabel(submitError,labels):null,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,inputIdOf,setRoot,markStarted,focusField,handleSubmit,submitDisabled:!canSubmit||status==="submitting"||preparing||!protectionSubmittable||anyUploadBusy,uploadUrl,uploadReady,getUploadProtectionData,setUploadUnavailable:setUnavailable,setUploadBusy:setBusy,uploadFile,lookupTaxId:taxIdLookupReady?lookupTaxId:null,fillCompanyName,phoneCountryOf:field=>field.type==="phone"?resolveFormPhoneCountry(field,form?.defaultPhoneCountry):null,siteCountry:form?.defaultPhoneCountry??null}}import{forwardRef}from"react";import{jsx as jsx3}from"react/jsx-runtime";var NativeInput=forwardRef(function NativeInput2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("input",{...ime.props,...props,ref:setRef})});var NativeTextarea=forwardRef(function NativeTextarea2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("textarea",{...ime.props,...props,ref:setRef})});import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";function shouldSpanFullRow(field){return field.type==="long_text"||field.type==="file"||field.type==="statement"||field.type==="address"}function onGroupBlur(onBlur){return e=>{if(e.relatedTarget&&e.currentTarget.contains(e.relatedTarget))return;onBlur()}}var INPUT_CLASS=cn("w-full py-2.5",FORM_FIELD_CLASS);function FormWidget({form,maxColumns,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues,isEditing=false,labels:labelsProp,locale,websiteName,captchaTheme}){const controller=useFormController({form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect,hiddenValues,isEditing,labels:labelsProp,locale,websiteName});const{labels,visibleFields,availability,isClosed,status,preparing,redirecting,answers,otherText,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,submitError,submitErrorMessage,uploadUrl,lookupTaxId}=controller;const gridClass=getGridColumnsClass(maxColumns,visibleFields.length);const isPreview=isEditing&&submitUrl===void 0;return jsx4(FormFieldUnavailableLabelContext.Provider,{value:labels.error,children:jsx4("div",{ref:controller.setRoot,className:"w-full min-w-0",children:isClosed?jsx4("p",{className:cn("rounded-lg px-4 py-6 text-center text-sm",TONE_BG_TINT,FORM_FG_MUTED),children:availability==="not_open"?labels.notOpenYet:availability==="full"?labels.full:labels.closed}):status==="success"?jsxs3("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[jsx4(CircleCheck,{className:cn("h-10 w-10",FORM_ACCENT_ICON)}),jsx4("p",{className:cn("whitespace-pre-wrap text-base",FORM_FG),children:controller.successMessage}),redirecting&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:labels.redirecting})]}):jsxs3("form",{onSubmit:controller.handleSubmit,noValidate:true,className:cn("grid gap-x-8 gap-y-7",gridClass),children:[jsx4(BotProtectionFields,{...protection.fieldProps,renderAltcha:false}),visibleFields.map(field=>jsx4(FieldRow,{inputId:controller.inputIdOf(field.id),className:shouldSpanFullRow(field)?"col-span-full":void 0,field,value:ownFieldValue(answers,field.id)??null,otherText:ownFieldValue(otherText,field.id)??"",onOtherTextChange:v=>controller.setOtherAnswer(field.id,v),error:controller.errorMessage(field.id),labels,today,phoneCountry:controller.phoneCountryOf(field),siteCountry:controller.siteCountry,onChange:v=>controller.setAnswer(field.id,v),onFocus:()=>controller.focusField(field.id),onBlur:()=>controller.validateOne(field),upload:{url:uploadUrl,ready:controller.uploadReady,getProtectionData:controller.getUploadProtectionData,onUnavailableChange:u=>controller.setUploadUnavailable(field.id,u),onBusyChange:b=>controller.setUploadBusy(field.id,b)},taxId:field.type==="tax_id"?{lookup:lookupTaxId?input=>lookupTaxId(field.id,input):void 0,onRegistryName:field.companyNameFieldId?name=>controller.fillCompanyName(field.companyNameFieldId,name):void 0}:void 0},field.id)),consentMode==="checkbox"&&jsxs3("label",{className:cn("col-span-full flex cursor-pointer items-start gap-2.5 pt-1 text-sm",FORM_FG),children:[jsx4(SiteChoiceInput,{type:"checkbox",className:"mt-0.5",checked:marketingOptIn,onFocus:controller.markStarted,onChange:e=>setMarketingOptIn(e.target.checked)}),jsx4("span",{children:consentLabel})]}),jsx4(BotProtectionChallenge,{...protection.challengeProps,locale,theme:captchaTheme,className:"col-span-full sm:max-w-sm"},altchaKey),submitError&&jsx4("p",{role:"alert",className:cn("col-span-full text-sm",FORM_DANGER),children:submitErrorMessage}),jsxs3("div",{className:"col-span-full flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4",children:[jsxs3("button",{type:"submit",disabled:controller.submitDisabled,className:cn("inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-[15px] font-medium transition sm:w-auto",FORM_SUBMIT_COLORS,"shadow-md hover:brightness-110 hover:shadow-lg","disabled:cursor-not-allowed disabled:opacity-60"),children:[(status==="submitting"||preparing)&&jsx4(LoaderCircle,{className:"h-4 w-4 animate-spin"}),status==="submitting"||preparing?labels.submitting:form.settings.submitLabel||labels.submit]}),isPreview&&jsx4("p",{className:cn("text-xs",FORM_FG_MUTED),children:labels.previewNotice})]}),consentMode==="submit"&&jsx4("p",{className:cn("col-span-full -mt-4 text-xs leading-relaxed",FORM_FG_MUTED),children:consentLabel})]})})})}function FieldRow({field,inputId,className,value,otherText,onOtherTextChange,error,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const errorId=`${inputId}-error`;const describedBy=error?errorId:void 0;if(field.type==="statement"){return jsxs3("div",{className:cn("min-w-0 space-y-1.5",className),children:[jsx4("p",{className:cn("text-base font-semibold leading-snug",FORM_FG),children:field.label}),field.description&&jsx4("p",{className:cn("whitespace-pre-wrap text-sm leading-relaxed",FORM_FG_MUTED),children:field.description})]})}return jsxs3("div",{className:cn("min-w-0 space-y-2",className),children:[jsxs3("label",{htmlFor:inputId,className:cn("block text-base font-semibold leading-snug",FORM_FG),children:[field.label,field.required&&jsx4("span",{"aria-hidden":true,className:cn("ml-0.5",FORM_DANGER),children:"*"})]}),field.description&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:field.description}),jsx4(FieldInput,{field,inputId,describedBy,invalid:Boolean(error),value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}),error&&jsx4("p",{id:errorId,role:"alert",className:cn("text-xs",FORM_DANGER),children:error})]})}function OtherTextInput({className,placeholder,value,onFocus,onChange}){return jsx4("input",{type:"text",className:cn(INPUT_CLASS,className),placeholder,"aria-label":placeholder,value,onFocus,onChange:e=>onChange(e.target.value)})}function FieldInput({field,inputId,describedBy,invalid,value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const{PhoneInput,FormAddressField,FormTaxIdField,FormFileField,FormChoiceDropdown}=useContext2(FormFieldComponentsContext)??ON_DEMAND_FORM_FIELDS;const common={id:inputId,"aria-describedby":describedBy,"aria-invalid":invalid||void 0,onFocus,onBlur,required:field.required,className:cn(INPUT_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)};const singleLine=singleLineInputProps(field,today);if(singleLine){return jsx4(NativeInput,{...common,...singleLine,value:typeof value==="string"?value:typeof value==="number"?String(value):"",onChange:e=>onChange(e.target.value)})}switch(field.type){case"short_text":case"email":case"date":case"time":case"number":case"url":return null;case"long_text":return jsx4(NativeTextarea,{...common,rows:4,maxLength:field.maxLength,value:typeof value==="string"?value:"",onChange:e=>onChange(e.target.value)});case"phone":return jsx4("div",{id:inputId,onFocus,onBlur:onGroupBlur(onBlur),tabIndex:-1,className:"outline-none",children:jsx4(PhoneInput,{value:typeof value==="string"?value:"",onChange:v=>onChange(v??null),defaultCountry:phoneCountry,error:invalid,controlClassName:cn(FORM_FIELD_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)})});case"statement":return null;case"tax_id":return jsx4(FormTaxIdField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,lookup:taxId?.lookup,onRegistryName:taxId?.onRegistryName,onChange,onFocus,onBlur});case"address":return jsx4(FormAddressField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,onChange,onFocus,onBlur});case"choice":{const selected=Array.isArray(value)?value:typeof value==="string"&&value?[value]:[];const options=[...field.options.map(o=>({id:o.id,label:o.label})),...field.allowOther?[{id:OTHER_OPTION_PLACEHOLDER,label:labels.otherOption}]:[]];const showOther=field.allowOther&&selected.includes(OTHER_OPTION_PLACEHOLDER);if(field.display==="dropdown"&&!field.allowMultiple){return jsxs3("div",{className:"space-y-2.5",onBlur:onGroupBlur(onBlur),children:[jsx4(FormChoiceDropdown,{inputId,describedBy,invalid,value:selected[0]||void 0,options,placeholder:labels.selectPlaceholder,onChange,onFocus}),showOther&&jsx4(OtherTextInput,{placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}return jsxs3("div",{role:field.allowMultiple?"group":"radiogroup","aria-describedby":describedBy,className:"space-y-2.5 pt-0.5",onBlur:onGroupBlur(onBlur),children:[options.map((opt,i)=>{const checked=selected.includes(opt.id);return jsxs3("label",{className:cn("flex cursor-pointer items-center gap-2.5 text-[15px]",FORM_FG),children:[jsx4(SiteChoiceInput,{id:i===0?inputId:void 0,type:field.allowMultiple?"checkbox":"radio",name:inputId,checked,onFocus,onChange:()=>{if(field.allowMultiple){onChange(checked?selected.filter(x=>x!==opt.id):[...selected,opt.id])}else{onChange(opt.id)}}}),jsx4("span",{children:opt.label})]},opt.id)}),showOther&&jsx4(OtherTextInput,{className:"mt-1",placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}case"rating":{const Icon=field.icon==="heart"?Heart:field.icon==="thumb"?ThumbsUp:Star;const current=typeof value==="number"?value:0;return jsx4("div",{role:"radiogroup","aria-describedby":describedBy,className:"flex flex-wrap gap-1.5",onBlur:onGroupBlur(onBlur),children:Array.from({length:field.max},(_,i)=>i+1).map(n=>{const active=n<=current;return jsx4("button",{type:"button",role:"radio","aria-checked":current===n,"aria-label":String(n),id:n===1?inputId:void 0,onFocus,onClick:()=>onChange(current===n?null:n),className:cn("flex h-10 w-10 items-center justify-center rounded-lg transition",TONE_BG_TINT_STRONG_HOVER),children:jsx4(Icon,{className:cn("h-6 w-6 transition",active?"fill-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))] text-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]":TONE_TEXT_FAINT)})},n)})})}case"file":return jsx4(FormFileField,{field,inputId,describedBy,invalid,labels,uploadUrl:upload.url,protectionReady:upload.ready,getProtectionData:upload.getProtectionData,onChange,onUnavailableChange:upload.onUnavailableChange,onBusyChange:upload.onBusyChange,onFocus})}}import{createElement,useCallback as useCallback2,useMemo as useMemo3}from"react";function useKanorioForm(options){const{formId,definition,siteName,labels,hiddenValues,followRedirect,onSuccess,siteUrl:siteUrlOption,locale:localeOption}=options;const setup=useKanorioFormSetup({siteUrl:siteUrlOption,locale:localeOption},formId,definition,labels);const{ctx,form}=setup;const site=ctx.site;const botProtectionConfig=useMemo3(()=>site?parsePublicBotProtectionConfig(site.botProtection):null,[site]);const handleSuccess=useCallback2(detail=>{if(typeof window!=="undefined")window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}));onSuccess?.(detail)},[onSuccess]);const submitUrl=form?`${ctx.siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`:null;const controller=useFormController({form:setup.ready?form:null,formId,submitUrl,challengeUrl:`${ctx.siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${ctx.siteUrl}/api/form-protection/altcha`,onSuccess:handleSuccess,followRedirect,hiddenValues,labels:setup.mergedLabels,locale:ctx.locale,websiteName:siteName??null,botProtectionConfig,botProtectionPending:site===null});const{inputIdOf,answers,errors,today,setAnswer,focusField,validateField}=controller;const getInputProps=useCallback2(fieldId=>{const field=controller.fields.find(f=>f.id===fieldId);const inputId=inputIdOf(fieldId);const value=ownFieldValue(answers,fieldId);const typed=field?singleLineInputProps(field,today)??(field.type==="long_text"?{maxLength:field.maxLength}:{}):{};return{...typed,id:inputId,name:fieldId,value:typeof value==="string"?value:typeof value==="number"?String(value):"",required:Boolean(field&&"required"in field&&field.required),...ownFieldValue(errors,fieldId)?{"aria-invalid":true,"aria-describedby":`${inputId}-error`}:{},onChange:event=>setAnswer(fieldId,event.target.value),onFocus:()=>focusField(fieldId),onBlur:()=>validateField(fieldId)}},[controller.fields,inputIdOf,answers,today,errors,setAnswer,focusField,validateField]);const pending2=site===null;const captcha=controller.protection.challengeProps.captcha;const botProtection=createElement(KanorioBotProtection,{key:controller.altchaKey,...controller.protection.fieldProps,captcha,pending:pending2,locale:ctx.locale});const status=setup.loadFailed||setup.siteUnavailable||setup.textUnavailable?"unavailable":!setup.ready?"loading":controller.status==="success"?"success":controller.status==="submitting"||controller.preparing?"submitting":"ready";return{status,definition:setup.ready?form:null,fields:controller.visibleFields,availability:controller.availability,values:answers,setValue:setAnswer,otherText:controller.otherText,setOtherText:controller.setOtherAnswer,errors,errorMessage:controller.errorMessage,validateField,getInputProps,getErrorProps:fieldId=>({id:`${inputIdOf(fieldId)}-error`,role:"alert"}),formProps:{ref:controller.setRoot,onSubmit:event=>void controller.handleSubmit(event),onFocus:controller.markStarted,noValidate:true},botProtection,consent:{mode:controller.consentMode,text:form?.consentText??controller.consentLabel,checked:controller.marketingOptIn,setChecked:controller.setMarketingOptIn},canSubmit:status==="ready"&&!controller.isClosed&&!controller.submitDisabled,submit:()=>controller.handleSubmit(),submitError:controller.submitError,submitErrorMessage:controller.submitErrorMessage,result:controller.result,successMessage:controller.successMessage,uploadReady:controller.uploadReady&&status==="ready",uploadFile:controller.uploadFile,lookupTaxId:(fieldId,input)=>controller.lookupTaxId?controller.lookupTaxId(fieldId,input):Promise.resolve(null),labels:controller.labels}}import{jsx as jsx5}from"react/jsx-runtime";function KanorioForm({formId,definition:initialDefinition,maxColumns,siteName,labels,onSuccess,followRedirect,hiddenValues,className,...config}){const{ctx,form,loadFailed,siteUnavailable,mergedLabels,ready}=useKanorioFormSetup(config,formId,initialDefinition,labels);const site=ctx.site;const siteUrl=ctx.siteUrl;if(loadFailed){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"load_failed",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(siteUnavailable){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"site_unavailable",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(!ready||!form||!site){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-loading":"",loading:true})}return jsx5(ElementsRoot,{context:ctx,className,children:jsx5(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site.botProtection),children:jsx5(FormWidget,{form,maxColumns,submitUrl:`${siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,locale:ctx.locale,websiteName:siteName,captchaTheme:ctx.theme,labels:mergedLabels,followRedirect,hiddenValues,onSuccess:detail=>{if(typeof window!=="undefined"){window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}))}onSuccess?.(detail)}})})})}export{SITE_RETRY_DELAYS_MS,useKanorioForm,KanorioForm};
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{NO_HEAVY_FIELD_VALIDATORS,OTHER_OPTION_PLACEHOLDER,countAnswered,hasVisibilityRules,ownFieldValue,resolveFormPhoneCountry,resolveVisibleFieldIds,sanitizeFormSubmitResponse,validateFormAnswerWith,validateFormAnswersWith}from"./chunk-D4KDA3KL.js";import{checkFormFile,uploadFormFile}from"./chunk-QF55WZDP.js";import{FORM_ACCENT_ICON,FORM_DANGER,FORM_FG,FORM_FG_MUTED,FORM_FIELD_CLASS,FORM_FIELD_INVALID_CLASS,FORM_SUBMIT_COLORS}from"./chunk-SVWEVSYJ.js";import{FORM_REDIRECT_EXPANDED_URL_MAX,isKnownFormFieldType,parseFormRedirectUrl,resolveConsentLabel,resolveFormAvailability,resolveFormDateBound}from"./chunk-APWDEDWM.js";import{onDemand}from"./chunk-E77WGXYW.js";import{useAdoptTypedOnMount,useComposingEnterGuard,useControlRef}from"./chunk-C7HUM2EN.js";import{FORM_SUBMIT_EVENT}from"./chunk-LWKCGUHS.js";import{KanorioBotProtection}from"./chunk-VT2B53EX.js";import{BotProtectionChallenge,BotProtectionConfigProvider,BotProtectionFields,parsePublicBotProtectionConfig,useBotProtection}from"./chunk-KYXZNMNA.js";import{TONE_BG_TINT,TONE_BG_TINT_STRONG_HOVER,TONE_BORDER_STRONG,TONE_TEXT_FAINT}from"./chunk-RKEHHJDU.js";import{EMPTY_VALUE,dateTimeFormat}from"./chunk-4BEKWYEW.js";import{clampText}from"./chunk-O2SYHUQF.js";import{CircleCheck,Heart,LoaderCircle,Star,ThumbsUp}from"./chunk-33AQQY6T.js";import{cn}from"./chunk-VUTODQFX.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{loadSiteMeta,useElementContext}from"./chunk-73S6VKNV.js";import{useEffect,useMemo,useState}from"react";var SITE_RETRY_DELAYS_MS=[1e3,3e3,1e4];function useDefinitionByContent(definition){const content=definition?JSON.stringify(definition):null;return useMemo(()=>definition??null,[content])}function useKanorioFormSetup(config,formId,initialDefinition,labels){const ctx=useElementContext(config,{needsSite:true});const{site,siteError,siteUrl}=ctx;const given=useDefinitionByContent(initialDefinition);const[read,setRead]=useState(null);const siteMissing=!site&&siteError;const[siteRetries,setSiteRetries]=useState({siteUrl,count:0});const retried=siteRetries.siteUrl===siteUrl?siteRetries.count:0;useEffect(()=>{if(!siteMissing)return;const delay=SITE_RETRY_DELAYS_MS[retried];if(delay===void 0)return;const timer=setTimeout(()=>{void loadSiteMeta(siteUrl).then(meta=>{if(meta===null)setSiteRetries({siteUrl,count:retried+1})})},delay);return()=>clearTimeout(timer)},[siteMissing,siteUrl,retried]);useEffect(()=>{if(given||!formId)return;let cancelled=false;fetch(`${siteUrl}/api/v1/forms/${encodeURIComponent(formId)}`).then(res=>res.ok?res.json():Promise.reject(new Error(`HTTP ${res.status}`))).then(data=>{if(cancelled)return;const resolved=data&&typeof data==="object"&&"fields"in data?data:data?.form??null;setRead({siteUrl,formId,form:resolved??null})}).catch(()=>{if(!cancelled)setRead({siteUrl,formId,form:null})});return()=>{cancelled=true}},[siteUrl,formId,given]);const current=read!==null&&read.siteUrl===siteUrl&&read.formId===formId?read:null;const form=given??current?.form??null;const siteText=ctx.messages?.form;const mergedLabels=useMemo(()=>siteText||labels?{...siteText??{},...labels??{}}:void 0,[siteText,labels]);return{ctx,form,loadFailed:!given&¤t!==null&¤t.form===null,siteUnavailable:Boolean(siteMissing)&&retried>=SITE_RETRY_DELAYS_MS.length,textUnavailable:ctx.messages===null&&ctx.messagesError,mergedLabels,ready:Boolean(form&&ctx.messages&&site)}}import{useContext as useContext2}from"react";import{useRef}from"react";import{jsx,jsxs}from"react/jsx-runtime";function SiteChoiceInput({type,className,...props}){const inputRef=useRef(null);useAdoptTypedOnMount(inputRef,props.onChange);return jsxs("span",{className:cn("relative inline-grid h-[18px] w-[18px] shrink-0 place-items-center",className),children:[jsx("input",{ref:inputRef,type,className:cn("peer col-start-1 row-start-1 m-0 h-[18px] w-[18px] cursor-pointer appearance-none border-2 transition-colors","bg-transparent "+TONE_BORDER_STRONG,"checked:border-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))] checked:bg-[var(--site-cta-brand-bg,var(--brand-color,#FF5733))]","focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]","disabled:cursor-not-allowed disabled:opacity-50",type==="radio"?"rounded-full":"rounded-[4px]"),...props}),type==="checkbox"?jsx("svg",{"aria-hidden":true,viewBox:"0 0 16 16",fill:"none",className:"pointer-events-none col-start-1 row-start-1 h-3.5 w-3.5 text-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50",children:jsx("path",{d:"M3.5 8.5l3 3 6-6.5",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round"})}):jsx("span",{"aria-hidden":true,className:"pointer-events-none col-start-1 row-start-1 h-2 w-2 rounded-full bg-[var(--site-cta-brand-fg,var(--brand-foreground,#ffffff))] opacity-0 peer-checked:opacity-100 peer-disabled:peer-checked:opacity-50"})]})}var MAX_COLUMNS_FALLBACK={mobile:1,tablet:2,desktop:2};var GRID_COLS={1:"grid-cols-1",2:"grid-cols-2",3:"grid-cols-3",4:"grid-cols-4",5:"grid-cols-5",6:"grid-cols-6"};var SM_GRID_COLS={1:"sm:grid-cols-1",2:"sm:grid-cols-2",3:"sm:grid-cols-3",4:"sm:grid-cols-4",5:"sm:grid-cols-5",6:"sm:grid-cols-6"};var MD_GRID_COLS={1:"md:grid-cols-1",2:"md:grid-cols-2",3:"md:grid-cols-3",4:"md:grid-cols-4",5:"md:grid-cols-5",6:"md:grid-cols-6"};function clampColumn(value){const n=Math.max(1,Math.min(6,Math.round(value)));return n}function getGridColumnsClass(maxColumns,itemCount){const resolve=raw=>{const capped=clampColumn(raw);if(itemCount==null)return capped;return clampColumn(Math.min(capped,Math.max(1,itemCount)))};const mobile=resolve(maxColumns?.mobile??MAX_COLUMNS_FALLBACK.mobile);const tablet=resolve(maxColumns?.tablet??MAX_COLUMNS_FALLBACK.tablet);const desktop=resolve(maxColumns?.desktop??MAX_COLUMNS_FALLBACK.desktop);return`${GRID_COLS[mobile]} ${SM_GRID_COLS[tablet]} ${MD_GRID_COLS[desktop]}`}import{createContext}from"react";var FormFieldComponentsContext=createContext(null);var FormFieldUnavailableLabelContext=createContext("");import{useContext}from"react";import{jsx as jsx2,jsxs as jsxs2}from"react/jsx-runtime";function FieldLoading({failed,props}){const unavailableLabel=useContext(FormFieldUnavailableLabelContext);const{inputId}=props;return jsxs2("div",{children:[jsx2("div",{id:inputId,tabIndex:inputId?-1:void 0,className:cn("h-11 w-full",FORM_FIELD_CLASS),"aria-busy":failed?void 0:"true","data-field-unavailable":failed?"":void 0}),failed&&unavailableLabel&&jsx2("p",{role:"alert",className:cn("mt-1.5 text-xs",FORM_DANGER),children:unavailableLabel})]})}var ON_DEMAND_FORM_FIELDS={PhoneInput:onDemand(()=>import("./phone-input-DOL46AIF.js").then(m=>m.PhoneInput),FieldLoading),FormAddressField:onDemand(()=>import("./FormAddressField-NH5LD6K7.js").then(m=>m.FormAddressField),FieldLoading),FormTaxIdField:onDemand(()=>import("./FormTaxIdField-XJSMW3II.js").then(m=>m.FormTaxIdField),FieldLoading),FormFileField:onDemand(()=>import("./FormFileField-5YFTKIRZ.js").then(m=>m.FormFileField),FieldLoading),FormChoiceDropdown:onDemand(()=>import("./FormChoiceDropdown-U3NIOOHG.js").then(m=>m.FormChoiceDropdown),FieldLoading)};var FORM_LIFECYCLE_EVENT="kanorio:form-event";import{useCallback,useEffect as useEffect2,useId,useMemo as useMemo2,useRef as useRef2,useState as useState2}from"react";var DATE_PRESETS={date:{dateStyle:"medium"},dateLong:{dateStyle:"long"},dateTime:{dateStyle:"medium",timeStyle:"short"},dateTimeFull:{dateStyle:"full",timeStyle:"short"},time:{timeStyle:"short"},monthDay:{month:"short",day:"numeric"},monthDayTime:{month:"short",day:"numeric",hour:"numeric",minute:"2-digit"},monthYear:{year:"numeric",month:"long"},dateWithZone:{year:"numeric",month:"long",day:"numeric",timeZoneName:"short"}};var CALENDAR_DATE=/^\d{4}-\d{2}-\d{2}$/;function isCalendarDate(value){return typeof value==="string"&&CALENDAR_DATE.test(value)}function toDate(value){if(value==null||value==="")return null;const date=value instanceof Date?value:new Date(value);return Number.isNaN(date.getTime())?null:date}function formatCalendarDate(value,preset="date",options){if(!isCalendarDate(value))return EMPTY_VALUE;const date=new Date(`${value}T00:00:00Z`);if(Number.isNaN(date.getTime()))return EMPTY_VALUE;return dateTimeFormat(options.locale,{...DATE_PRESETS[preset],timeZone:"UTC"}).format(date)}function toCalendarDateIn(value,timeZone){const date=toDate(value);if(!date)return"";return dateTimeFormat("en-CA",{year:"numeric",month:"2-digit",day:"2-digit",timeZone}).format(date)}var MINUTE=6e4;var HOUR=60*MINUTE;var DAY=24*HOUR;var loaded={...NO_HEAVY_FIELD_VALIDATORS};var pending=new Map;var LOADERS={phone:()=>import("./forms-answers-phone-2VZ46OME.js").then(m=>void(loaded.phone=m.validatePhoneAnswer)),address:()=>import("./forms-answers-address-5MXQYIH3.js").then(m=>void(loaded.address=m.validateAddressAnswer)),tax_id:()=>import("./forms-answers-tax-id-3AYXCNP5.js").then(m=>void(loaded.tax_id=m.validateTaxIdAnswer))};function isHeavyFieldType(type){return Object.hasOwn(LOADERS,type)}function loadedFormFieldValidators(){return loaded}function canValidateFormField(type){return!isHeavyFieldType(type)||loaded[type]!==null}function hasFormFieldValidators(types){for(const type of types)if(!canValidateFormField(type))return false;return true}function loadFormFieldValidators(types){const waits=[];for(const type of new Set(types)){if(!isHeavyFieldType(type)||loaded[type])continue;let wait=pending.get(type);if(!wait){wait=LOADERS[type]().finally(()=>pending.delete(type));pending.set(type,wait)}waits.push(wait)}return Promise.all(waits).then(()=>loaded)}var PAGEVIEW_ATTRIBUTION_PARAMS=["utm_source","utm_medium","utm_campaign","utm_content","utm_term","gclid","fbclid","oppref"];var MAX_ATTRIBUTION_VALUE_LENGTH=200;var ATTRIBUTION_VALUE_ALLOWED=/[^\p{L}\p{N} _\-./:+%()&=|]/gu;function sanitizePageviewAttribution(read){const utm={};for(const key of PAGEVIEW_ATTRIBUTION_PARAMS){const raw=read(key);if(typeof raw!=="string"||!raw)continue;const val=clampText(raw.replace(ATTRIBUTION_VALUE_ALLOWED,"").trim(),MAX_ATTRIBUTION_VALUE_LENGTH);if(val)utm[key]=val}return Object.keys(utm).length>0?utm:null}var HOST_RE=/^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;var LANDING_PATH_MAX=500;function sanitizeHost(raw){if(typeof raw!=="string")return void 0;const host=raw.trim().toLowerCase();return HOST_RE.test(host)?host:void 0}function sanitizeLandingPath(raw){if(typeof raw!=="string")return void 0;const path=raw.trim().split(/[?#]/)[0]??"";if(!path.startsWith("/")||path.startsWith("//")||/[\s\\\0]/.test(path))return void 0;return path.slice(0,LANDING_PATH_MAX)}function sanitizeFormAttribution(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;const input=raw;const utmInput=input.utm&&typeof input.utm==="object"&&!Array.isArray(input.utm)?input.utm:{};const utm=sanitizePageviewAttribution(key=>utmInput[key]);const referrerHost=sanitizeHost(input.referrerHost);const landingPath=sanitizeLandingPath(input.landingPath);const out={};if(utm)out.utm=utm;if(referrerHost)out.referrerHost=referrerHost;if(landingPath)out.landingPath=landingPath;return Object.keys(out).length>0?out:null}function buildFormAttribution(input){let utm=null;try{const params=new URLSearchParams(input.search??"");utm=sanitizePageviewAttribution(key=>params.get(key))}catch{utm=null}let referrerHost;try{referrerHost=input.referrer?new URL(input.referrer).hostname:void 0}catch{referrerHost=void 0}return sanitizeFormAttribution({utm:utm??void 0,referrerHost,landingPath:input.path??void 0})}var SESSION_ATTRIBUTION_KEY="kano-session-attribution";function readSessionAttribution(){if(typeof window==="undefined")return null;try{const raw=window.sessionStorage.getItem(SESSION_ATTRIBUTION_KEY);return raw?sanitizeFormAttribution(JSON.parse(raw)):null}catch{return null}}function currentFormAttribution(){if(typeof window==="undefined")return null;const stored=readSessionAttribution();if(stored)return stored;let referrer=null;try{referrer=document.referrer&&new URL(document.referrer).hostname.toLowerCase()!==window.location.hostname.toLowerCase()?document.referrer:null}catch{referrer=null}return buildFormAttribution({search:window.location.search,referrer,path:window.location.pathname})}var VALIDATOR_WAIT_MS=4e3;var DEFAULT_FORM_LABELS={submit:"Submit",submitting:"Submitting\u2026",success:"Thanks! We\u2019ll be in touch soon.",error:"Something went wrong. Please try again.",required:"This field is required.",invalidEmail:"Please enter a valid email address.",invalidPhone:"Please enter a valid phone number.",invalidDate:"Please enter a valid date.",invalidTime:"Please enter a valid time.",tooLong:"This answer is too long.",otherRequired:"Please specify your answer.",duplicate:"This email or phone number has already been used. Only one response per person is allowed.",temporarilyUnavailable:"This form isn\u2019t accepting responses right now. Please try again later.",rateLimited:"Too many submissions. Please wait a moment and try again.",verificationExpired:"Verification expired. Please verify again and resubmit.",outdated:"This form has changed since you opened it. Please refresh the page and submit again.",edgeChallenge:"Your browser didn\u2019t pass this site\u2019s security check. Please reload the page and submit again.",tooLarge:"Your answers are too long to send. Please shorten them and try again.",redirecting:"Taking you to the next page\u2026",invalid:"Please check this answer.",tooShort:"Please enter at least {min} characters.",invalidNumber:"Please enter a number.",notInteger:"Please enter a whole number.",numberMin:"Please enter {min} or more.",numberMax:"Please enter {max} or less.",numberRange:"Please enter a number from {min} to {max}.",invalidUrl:"Please enter a web address, such as example.com.",dateMin:"Please choose {min} or later.",dateMax:"Please choose {max} or earlier.",dateRange:"Please choose a date from {min} to {max}.",tooFewOptions:"Please select {min} or more.",tooManyOptions:"Please select no more than {max}.",selectPlaceholder:"Select an option",invalidAddress:"Please complete the address.",invalidTaxId:"Please check this tax ID.",taxIdChecking:"Looking up the public registry\u2026",taxIdRegisteredName:"Registered name: {name}",taxIdInactive:"The registry shows this business as suspended or closed. Please check the tax ID.",taxIdSource:"Source: {provider}",invalidPostalCode:"Please check the postal code.",addressCountry:"Country or region",addressRecipient:"Recipient name",addressLine1:"Address",addressLine2:"Apartment, suite, etc. (optional)",addressPostal_postal:"Postal code",addressPostal_zip:"ZIP code",addressPostal_pin:"PIN code",addressPostal_eircode:"Eircode",addressLocality_city:"City",addressLocality_district:"District",addressLocality_post_town:"Town or city",addressLocality_suburb:"Suburb",addressRegion_area:"Area",addressRegion_county:"County",addressRegion_department:"Department",addressRegion_district:"District",addressRegion_do_si:"Province or city",addressRegion_emirate:"Emirate",addressRegion_island:"Island",addressRegion_oblast:"Oblast",addressRegion_parish:"Parish",addressRegion_prefecture:"Prefecture",addressRegion_province:"Province",addressRegion_state:"State",marketingOptIn:"I\u2019d like to receive news and offers from {siteName} by email. I can unsubscribe from any email with one click.",subscribeOnSubmit:"By clicking \u201C{button}\u201D, you agree to receive news and offers from {siteName} by email. You can unsubscribe from any email with one click.",otherOption:"Other",otherPlaceholder:"Please specify",closed:"This form is closed.",notOpenYet:"This form isn\u2019t open yet.",full:"All spots have been filled. Thank you for your interest.",fileChoose:"Choose a file",fileLimitHint:"Up to {max} file(s), {size} each.",fileWaiting:"Waiting for verification\u2026",fileUploading:"Uploading\u2026",fileUploadFailed:"Upload failed. Please try again.",fileTooLarge:"This file is too large.",fileTypeNotAllowed:"This file type isn\u2019t supported.",fileUnavailable:"Attachments can\u2019t be uploaded right now. You can still submit the form.",fileRemove:"Remove",noFormSelected:"Select a form in the panel to display it here.",formNotFound:"The selected form no longer exists.",previewNotice:"Preview only \u2014 submissions are disabled here."};function fill(template,values){return template.replaceAll("{min}",String(values.min??"")).replaceAll("{max}",String(values.max??""))}function errorLabel(code,field,{labels,today,locale}){switch(code){case"invalid_email":return labels.invalidEmail;case"invalid_phone":return labels.invalidPhone;case"invalid_date":return labels.invalidDate;case"invalid_time":return labels.invalidTime;case"too_long":return labels.tooLong;case"too_short":return(field.type==="short_text"||field.type==="long_text")&&field.minLength!==void 0?fill(labels.tooShort,{min:field.minLength}):labels.invalid;case"invalid_format":return field.type==="short_text"&&field.patternMessage?field.patternMessage:labels.invalid;case"other_required":return labels.otherRequired;case"too_few_options":return field.type==="choice"&&field.minSelections!==void 0?fill(labels.tooFewOptions,{min:field.minSelections}):labels.invalid;case"too_many_options":return field.type==="choice"&&field.maxSelections!==void 0?fill(labels.tooManyOptions,{max:field.maxSelections}):labels.invalid;case"invalid_number":return labels.invalidNumber;case"not_integer":return labels.notInteger;case"out_of_range":{if(field.type!=="number")return labels.invalid;const{min,max}=field;if(min!==void 0&&max!==void 0)return fill(labels.numberRange,{min,max});if(min!==void 0)return fill(labels.numberMin,{min});if(max!==void 0)return fill(labels.numberMax,{max});return labels.invalid}case"invalid_url":return labels.invalidUrl;case"date_out_of_range":{if(field.type!=="date")return labels.invalid;const min=resolveFormDateBound(field.range?.min,today);const max=resolveFormDateBound(field.range?.max,today);const show=date=>formatCalendarDate(date,"date",{locale});if(min&&max)return fill(labels.dateRange,{min:show(min),max:show(max)});if(min)return fill(labels.dateMin,{min:show(min)});if(max)return fill(labels.dateMax,{max:show(max)});return labels.invalid}case"invalid_address":return labels.invalidAddress;case"invalid_tax_id":return labels.invalidTaxId;case"invalid_postal_code":return labels.invalidPostalCode;case"invalid":return labels.invalid;case"required":case"invalid_option":return labels.required}}function todayIn(timeZone){const now=new Date;if(timeZone){try{const date=toCalendarDateIn(now,timeZone);if(date)return date}catch{}}const pad=n=>String(n).padStart(2,"0");return`${now.getFullYear()}-${pad(now.getMonth()+1)}-${pad(now.getDate())}`}function submitErrorLabel(error,labels){switch(error){case"outdated":return labels.outdated;case"edge_challenge":return labels.edgeChallenge;case"duplicate":return labels.duplicate;case"daily_limit":case"temporarily_unavailable":return labels.temporarilyUnavailable;case"rate_limited":return labels.rateLimited;case"verification_expired":return labels.verificationExpired;case"too_large":return labels.tooLarge;case"invalid_answers":case"server_error":return labels.error}}function cssAttributeValue(value){return value.replace(/["\\]/g,"\\$&")}function dispatchLifecycle(detail){if(typeof window==="undefined")return;window.dispatchEvent(new CustomEvent(FORM_LIFECYCLE_EVENT,{detail}))}function singleLineInputProps(field,today){switch(field.type){case"short_text":return{type:"text",maxLength:field.maxLength,autoComplete:field.contactMapping==="name"?"name":void 0};case"email":return{type:"email",inputMode:"email",autoComplete:"email"};case"date":return{type:"date",min:resolveFormDateBound(field.range?.min,today)??void 0,max:resolveFormDateBound(field.range?.max,today)??void 0};case"time":return{type:"time"};case"number":return{type:"text",inputMode:field.integer&&(field.min??-1)>=0?"numeric":"decimal",autoComplete:"off"};case"url":return{type:"url",inputMode:"url",autoComplete:"url",autoCapitalize:"none",spellCheck:false,placeholder:"https://"};default:return null}}function useFormController(options){const{form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues:hiddenValuesProp,isEditing=false,labels:labelsProp,locale,websiteName,botProtectionConfig,botProtectionPending=false}=options;const formId=form?.id??options.formId??"";const labels=useMemo2(()=>({...DEFAULT_FORM_LABELS,...labelsProp}),[labelsProp]);const formFields=form?.fields;const fields=useMemo2(()=>(formFields??[]).filter(field=>isKnownFormFieldType(field.type)),[formFields]);const consentLabel=form?resolveConsentLabel(form.settings,labels,websiteName):null;const canSubmit=Boolean(submitUrl)&&!isEditing&&form!==null;const[serverState,setServerState]=useState2(null);const availability=serverState??(form?resolveFormAvailability(form):"open");const isClosed=availability!=="open";const[answers,setAnswers]=useState2({});const[otherText,setOtherText]=useState2({});const answersRef=useRef2(answers);const otherTextRef=useRef2(otherText);const marketingOptInRef=useRef2(false);const updateAnswers=useCallback(update=>{const next=update(answersRef.current);if(next===answersRef.current)return;answersRef.current=next;setAnswers(next)},[]);const[uploadUnavailable,setUploadUnavailable]=useState2({});const[uploadBusy,setUploadBusy]=useState2({});const anyUploadBusy=Object.values(uploadBusy).some(Boolean);const uploadsInFlightRef=useRef2({});const hasUploadInFlight=useCallback(()=>Object.values(uploadsInFlightRef.current).some(count=>count>0),[]);const consentMode=form?.settings.marketingConsent??"off";const[marketingOptIn,setMarketingOptInState]=useState2(false);const setMarketingOptIn=useCallback(checked=>{marketingOptInRef.current=checked;setMarketingOptInState(checked)},[]);const[errors,setErrors]=useState2({});const[submitError,setSubmitError]=useState2(null);const[status,setStatusState]=useState2("idle");const statusRef=useRef2("idle");const setStatus=useCallback(next=>{statusRef.current=next;setStatusState(next)},[]);const[result,setResult]=useState2(null);const[altchaKey,setAltchaKey]=useState2(0);const[redirecting,setRedirecting]=useState2(false);const declaredHiddenFields=form?.settings.hiddenFields;const hiddenFields=useMemo2(()=>declaredHiddenFields??[],[declaredHiddenFields]);const[urlHiddenValues,setUrlHiddenValues]=useState2({});const hiddenFieldIds=JSON.stringify(hiddenFields.map(hidden=>hidden.id));useEffect2(()=>{const ids=JSON.parse(hiddenFieldIds);if(ids.length===0||typeof window==="undefined")return;const params=new URLSearchParams(window.location.search);const next={};for(const id of ids){const value=params.get(id);if(value)next[id]=value}setUrlHiddenValues(next)},[hiddenFieldIds]);const hiddenValues=useMemo2(()=>({...urlHiddenValues,...hiddenValuesProp??{}}),[urlHiddenValues,hiddenValuesProp]);const hasRules=useMemo2(()=>hasVisibilityRules(fields),[fields]);const visibleFieldsFor=useCallback(current=>{if(!hasRules)return fields;const visible=resolveVisibleFieldIds(fields,{...hiddenValues,...current});return fields.filter(field=>visible.has(field.id))},[hasRules,fields,hiddenValues]);const visibleFields=useMemo2(()=>visibleFieldsFor(answers),[visibleFieldsFor,answers]);const startedRef=useRef2(false);const viewedRef=useRef2(false);const rootRef=useRef2(null);const[rootElement,setRootElement]=useState2(null);const setRoot=useCallback(element=>{rootRef.current=element;setRootElement(element)},[]);const fieldIdPrefix=`form-${useId().replace(/[^A-Za-z0-9_-]/g,"")}-field`;const inputIdOf=useCallback(fieldId=>`${fieldIdPrefix}-${fieldId}`,[fieldIdPrefix]);const protection=useBotProtection({variant:"full",context:formId,entry:"forms",needsUploadToken:fields.some(field=>field.type==="file"||field.type==="tax_id"),...challengeUrl?{challengeUrl}:{},...altchaChallengeUrl?{altchaChallengeUrl}:{},...botProtectionConfig!==void 0?{config:botProtectionConfig}:{}});const protectionSubmittable=protection.isSubmittable&&!botProtectionPending;const uploadReady=protection.isUploadReady&&!botProtectionPending;const uploadUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/upload-request"):null;const taxIdLookupUrl=canSubmit&&submitUrl?submitUrl.replace(/\/submit$/,"/tax-id-lookup"):null;const taxIdLookupReady=Boolean(taxIdLookupUrl)&&uploadReady;const getUploadProtectionData=protection.getUploadProtectionData;const lookupTaxId=useCallback(async(fieldId,input)=>{if(!taxIdLookupUrl)return null;try{const res=await fetch(taxIdLookupUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({fieldId,...input,...getUploadProtectionData()})});if(!res.ok)return null;const data=await res.json();if(!data||data.ok===false||typeof data.status!=="string")return null;return{...data,ok:true}}catch{return null}},[taxIdLookupUrl,getUploadProtectionData]);useEffect2(()=>{if(!canSubmit||viewedRef.current||!rootElement)return;const el=rootElement;if(typeof IntersectionObserver==="undefined"){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});return}const io=new IntersectionObserver(entries=>{if(entries.some(e=>e.isIntersecting)&&!viewedRef.current){viewedRef.current=true;dispatchLifecycle({type:"form_view",formId});io.disconnect()}},{threshold:.3});io.observe(el);return()=>io.disconnect()},[canSubmit,formId,rootElement]);const lastFieldRef=useRef2(null);const abandonRef=useRef2({status,visibleFields,answers});useEffect2(()=>{abandonRef.current={status,visibleFields,answers}},[status,visibleFields,answers]);useEffect2(()=>{if(!canSubmit||typeof window==="undefined")return;let sent=false;const onPageHide=()=>{const latest=abandonRef.current;if(sent||!startedRef.current||latest.status==="success")return;sent=true;dispatchLifecycle({type:"form_abandon",formId,lastFieldId:lastFieldRef.current,answeredCount:countAnswered(latest.visibleFields,latest.answers)})};window.addEventListener("pagehide",onPageHide);return()=>window.removeEventListener("pagehide",onPageHide)},[canSubmit,formId]);const markStarted=useCallback(()=>{protection.registerFocus();if(startedRef.current||!canSubmit)return;startedRef.current=true;dispatchLifecycle({type:"form_start",formId})},[protection,canSubmit,formId]);const focusField=useCallback(fieldId=>{lastFieldRef.current=fieldId;markStarted()},[markStarted]);const clearError=useCallback(id=>{setErrors(prev=>{if(!ownFieldValue(prev,id))return prev;const next={...prev};delete next[id];return next})},[]);const setAnswer=useCallback((id,value)=>{lastFieldRef.current=id;updateAnswers(prev=>({...prev,[id]:value}));clearError(id);setSubmitError(null)},[clearError,updateAnswers]);const setOtherAnswer=useCallback((id,text)=>{otherTextRef.current={...otherTextRef.current,[id]:text};setOtherText(otherTextRef.current);clearError(id)},[clearError]);const[today,setToday]=useState2(null);const timezone=form?.timezone;useEffect2(()=>{setToday(todayIn(timezone))},[timezone]);const fieldTypes=useMemo2(()=>Array.from(new Set(fields.map(field=>field.type))),[fields]);useEffect2(()=>{loadFormFieldValidators(fieldTypes).catch(()=>void 0)},[fieldTypes]);const[preparing,setPreparing]=useState2(false);const preparingRef=useRef2(false);const resendSameRef=useRef2(false);const defaultPhoneCountry=form?.defaultPhoneCountry;const validationCtx=useMemo2(()=>({defaultPhoneCountry,fileRequired:{exempt:Object.keys(uploadUnavailable).filter(id=>uploadUnavailable[id])},today}),[defaultPhoneCountry,uploadUnavailable,today]);const errorCtx=useMemo2(()=>({labels,today:today??todayIn(timezone),locale:locale||(typeof navigator!=="undefined"?navigator.language:"en")}),[labels,today,timezone,locale]);const validateOne=useCallback(field=>{if(!canValidateFormField(field.type))return;const code=validateFormAnswerWith(loadedFormFieldValidators(),field,{answers:answersRef.current,otherText:otherTextRef.current},validationCtx);if(code&&code!=="required")setErrors(prev=>({...prev,[field.id]:code}));else clearError(field.id)},[validationCtx,clearError]);const validateField=useCallback(fieldId=>{const field=fields.find(f=>f.id===fieldId);if(field)validateOne(field)},[fields,validateOne]);const focusFirstError=useCallback(errorIds=>{const root=rootRef.current;if(!root)return;for(const field of fields){if(!errorIds.includes(field.id))continue;const el=root.querySelector(`[id="${cssAttributeValue(inputIdOf(field.id))}"]`);if(!el)continue;el.scrollIntoView?.({behavior:"smooth",block:"center"});el.focus({preventScroll:true});return}},[fields,inputIdOf]);const submitAnswers=useCallback(async validators=>{if(!canSubmit||!form||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight())return;const current=answersRef.current;const optedIn=marketingOptInRef.current;const validated=validateFormAnswersWith(validators,fields,{answers:{...hiddenValues,...current},otherText:otherTextRef.current},{...validationCtx,hiddenFields});if(!validated.ok){setErrors(validated.errors);focusFirstError(Object.keys(validated.errors));return}setStatus("submitting");setSubmitError(null);let sent=false;try{if(!resendSameRef.current)await protection.prepare();sent=true;const res=await fetch(submitUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({answers:validated.answers,...consentMode==="submit"?{consent:"submit_statement",consentTextId:form.consentTextId}:consentMode==="checkbox"&&optedIn?{consent:"checked",consentTextId:form.consentTextId}:{},locale:typeof navigator!=="undefined"?navigator.language:void 0,...locale?{pageLocale:locale}:{},pagePath:typeof window!=="undefined"?window.location.pathname:void 0,attribution:currentFormAttribution()??void 0,...protection.getProtectionData()})});if(res.headers.get("cf-mitigated")==="challenge"){setStatus("idle");setSubmitError("edge_challenge");resendSameRef.current=false;protection.renewCaptcha();return}const data=sanitizeFormSubmitResponse(res.status===429?{ok:false,error:"rate_limited"}:res.status===503?{ok:false,error:"temporarily_unavailable"}:await res.json().catch(()=>null));setStatus("idle");const resendSame=!data.ok&&data.error==="temporarily_unavailable";resendSameRef.current=resendSame;if(data.ok?Boolean(data.state):!resendSame){protection.renewCaptcha()}if(data.ok){if(data.state){setServerState(data.state);return}setStatus("success");const redirectUrl=data.redirectUrl??parseFormRedirectUrl(form.redirectUrl,{maxLength:FORM_REDIRECT_EXPANDED_URL_MAX})?.url;const detail={formId:form.id,...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}};setResult({...redirectUrl?{redirectUrl}:{},...data.submissionId?{submissionId:data.submissionId}:{}});onSuccess?.(detail);if(redirectUrl&&followRedirect){setRedirecting(true);window.location.assign(redirectUrl)}return}const errorIds=data.error==="invalid_answers"&&data.errors?Object.keys(data.errors):[];const renderedIds=new Set(visibleFieldsFor(current).map(f=>f.id));setSubmitError(errorIds.some(id=>!renderedIds.has(id))?"outdated":data.error);if(errorIds.length>0){setErrors(data.errors);focusFirstError(errorIds)}if(data.error==="verification_expired"||data.error==="duplicate")setAltchaKey(k=>k+1)}catch{setStatus("idle");setSubmitError("server_error");if(sent)resendSameRef.current=true;else protection.renewCaptcha()}},[canSubmit,form,setStatus,isClosed,anyUploadBusy,hasUploadInFlight,validationCtx,focusFirstError,fields,visibleFieldsFor,hiddenFields,hiddenValues,followRedirect,submitUrl,consentMode,locale,protection,onSuccess]);const submitAnswersRef=useRef2(submitAnswers);useEffect2(()=>{submitAnswersRef.current=submitAnswers},[submitAnswers]);const handleSubmit=useCallback(async e=>{e?.preventDefault();if(!canSubmit||statusRef.current!=="idle"||isClosed||anyUploadBusy||hasUploadInFlight()||preparingRef.current||!protectionSubmittable)return;if(hasFormFieldValidators(fieldTypes))return submitAnswers(loadedFormFieldValidators());preparingRef.current=true;setPreparing(true);let timer;try{await Promise.race([loadFormFieldValidators(fieldTypes),new Promise(resolve=>timer=setTimeout(resolve,VALIDATOR_WAIT_MS))])}catch{}finally{clearTimeout(timer);preparingRef.current=false;setPreparing(false)}await submitAnswersRef.current(loadedFormFieldValidators())},[canSubmit,isClosed,anyUploadBusy,hasUploadInFlight,protectionSubmittable,fieldTypes,submitAnswers]);const autofilledRef=useRef2({});const fillCompanyName=useCallback((targetId,name)=>{updateAnswers(prev=>{const currentValue=prev[targetId];const text=typeof currentValue==="string"?currentValue:"";if(text.trim()!==""&&text!==autofilledRef.current[targetId])return prev;autofilledRef.current[targetId]=name;return{...prev,[targetId]:name}})},[updateAnswers]);const setUnavailable=useCallback((id,unavailable)=>{setUploadUnavailable(prev=>prev[id]===unavailable?prev:{...prev,[id]:unavailable})},[]);const setBusy=useCallback((id,busy)=>{setUploadBusy(prev=>prev[id]===busy?prev:{...prev,[id]:busy})},[]);const uploadFile=useCallback(async(fieldId,file,uploadOptions={})=>{const field=fields.find(f=>f.id===fieldId);if(!field||field.type!=="file")return{ok:false,reason:"not_a_file_question"};focusField(fieldId);if(!uploadUrl||!uploadReady)return{ok:false,reason:"not_ready"};const current=ownFieldValue(answersRef.current,fieldId);const accepted=Array.isArray(current)?current.length:0;const inFlight=ownFieldValue(uploadsInFlightRef.current,fieldId)??0;if(accepted+inFlight>=field.maxFiles)return{ok:false,reason:"too_many_files"};const problem=checkFormFile(field,file);if(problem)return{ok:false,reason:problem};uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:inFlight+1};setBusy(fieldId,true);try{const uploaded=await uploadFormFile({uploadUrl,fieldId,file,protection:getUploadProtectionData(),onProgress:uploadOptions.onProgress,signal:uploadOptions.signal});if(uploaded.ok){updateAnswers(prev=>{const ids=Array.isArray(prev[fieldId])?prev[fieldId]:[];return{...prev,[fieldId]:[...ids,uploaded.uploadId]}});clearError(fieldId);setSubmitError(null)}else if(uploaded.reason==="unavailable"){setUnavailable(fieldId,true)}return uploaded}finally{const left=Math.max(0,(ownFieldValue(uploadsInFlightRef.current,fieldId)??1)-1);uploadsInFlightRef.current={...uploadsInFlightRef.current,[fieldId]:left};if(left===0)setBusy(fieldId,false)}},[fields,uploadUrl,uploadReady,focusField,setBusy,getUploadProtectionData,updateAnswers,clearError,setUnavailable]);const errorMessage=useCallback(fieldId=>{const code=ownFieldValue(errors,fieldId);if(!code)return void 0;const field=fields.find(f=>f.id===fieldId);return field?errorLabel(code,field,errorCtx):labels.invalid},[errors,fields,errorCtx,labels.invalid]);return{form,formId,labels,fields,visibleFields,canSubmit,availability,isClosed,status,preparing,redirecting,result,successMessage:form?.settings.successMessage||labels.success,answers,setAnswer,otherText,setOtherAnswer,errors,errorMessage,validateField,validateOne,submitError,submitErrorMessage:submitError?submitErrorLabel(submitError,labels):null,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,inputIdOf,setRoot,markStarted,focusField,handleSubmit,submitDisabled:!canSubmit||status==="submitting"||preparing||!protectionSubmittable||anyUploadBusy,uploadUrl,uploadReady,getUploadProtectionData,setUploadUnavailable:setUnavailable,setUploadBusy:setBusy,uploadFile,lookupTaxId:taxIdLookupReady?lookupTaxId:null,fillCompanyName,phoneCountryOf:field=>field.type==="phone"?resolveFormPhoneCountry(field,form?.defaultPhoneCountry):null,siteCountry:form?.defaultPhoneCountry??null}}import{forwardRef}from"react";import{jsx as jsx3}from"react/jsx-runtime";var NativeInput=forwardRef(function NativeInput2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("input",{...ime.props,...props,ref:setRef})});var NativeTextarea=forwardRef(function NativeTextarea2({onKeyDown,onCompositionStart,onCompositionEnd,...props},forwarded){const ime=useComposingEnterGuard({onKeyDown,onCompositionStart,onCompositionEnd});const{ref,setRef}=useControlRef(forwarded);useAdoptTypedOnMount(ref,props.onChange);return jsx3("textarea",{...ime.props,...props,ref:setRef})});import{jsx as jsx4,jsxs as jsxs3}from"react/jsx-runtime";function shouldSpanFullRow(field){return field.type==="long_text"||field.type==="file"||field.type==="statement"||field.type==="address"}function onGroupBlur(onBlur){return e=>{if(e.relatedTarget&&e.currentTarget.contains(e.relatedTarget))return;onBlur()}}var INPUT_CLASS=cn("w-full py-2.5",FORM_FIELD_CLASS);function FormWidget({form,maxColumns,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect=true,hiddenValues,isEditing=false,labels:labelsProp,locale,websiteName,captchaTheme}){const controller=useFormController({form,submitUrl,challengeUrl,altchaChallengeUrl,onSuccess,followRedirect,hiddenValues,isEditing,labels:labelsProp,locale,websiteName});const{labels,visibleFields,availability,isClosed,status,preparing,redirecting,answers,otherText,consentMode,consentLabel,marketingOptIn,setMarketingOptIn,protection,altchaKey,today,submitError,submitErrorMessage,uploadUrl,lookupTaxId}=controller;const gridClass=getGridColumnsClass(maxColumns,visibleFields.length);const isPreview=isEditing&&submitUrl===void 0;return jsx4(FormFieldUnavailableLabelContext.Provider,{value:labels.error,children:jsx4("div",{ref:controller.setRoot,className:"w-full min-w-0",children:isClosed?jsx4("p",{className:cn("rounded-lg px-4 py-6 text-center text-sm",TONE_BG_TINT,FORM_FG_MUTED),children:availability==="not_open"?labels.notOpenYet:availability==="full"?labels.full:labels.closed}):status==="success"?jsxs3("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[jsx4(CircleCheck,{className:cn("h-10 w-10",FORM_ACCENT_ICON)}),jsx4("p",{className:cn("whitespace-pre-wrap text-base",FORM_FG),children:controller.successMessage}),redirecting&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:labels.redirecting})]}):jsxs3("form",{onSubmit:controller.handleSubmit,noValidate:true,className:cn("grid gap-x-8 gap-y-7",gridClass),children:[jsx4(BotProtectionFields,{...protection.fieldProps,renderAltcha:false}),visibleFields.map(field=>jsx4(FieldRow,{inputId:controller.inputIdOf(field.id),className:shouldSpanFullRow(field)?"col-span-full":void 0,field,value:ownFieldValue(answers,field.id)??null,otherText:ownFieldValue(otherText,field.id)??"",onOtherTextChange:v=>controller.setOtherAnswer(field.id,v),error:controller.errorMessage(field.id),labels,today,phoneCountry:controller.phoneCountryOf(field),siteCountry:controller.siteCountry,onChange:v=>controller.setAnswer(field.id,v),onFocus:()=>controller.focusField(field.id),onBlur:()=>controller.validateOne(field),upload:{url:uploadUrl,ready:controller.uploadReady,getProtectionData:controller.getUploadProtectionData,onUnavailableChange:u=>controller.setUploadUnavailable(field.id,u),onBusyChange:b=>controller.setUploadBusy(field.id,b)},taxId:field.type==="tax_id"?{lookup:lookupTaxId?input=>lookupTaxId(field.id,input):void 0,onRegistryName:field.companyNameFieldId?name=>controller.fillCompanyName(field.companyNameFieldId,name):void 0}:void 0},field.id)),consentMode==="checkbox"&&jsxs3("label",{className:cn("col-span-full flex cursor-pointer items-start gap-2.5 pt-1 text-sm",FORM_FG),children:[jsx4(SiteChoiceInput,{type:"checkbox",className:"mt-0.5",checked:marketingOptIn,onFocus:controller.markStarted,onChange:e=>setMarketingOptIn(e.target.checked)}),jsx4("span",{children:consentLabel})]}),jsx4(BotProtectionChallenge,{...protection.challengeProps,locale,theme:captchaTheme,className:"col-span-full sm:max-w-sm"},altchaKey),submitError&&jsx4("p",{role:"alert",className:cn("col-span-full text-sm",FORM_DANGER),children:submitErrorMessage}),jsxs3("div",{className:"col-span-full flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-4",children:[jsxs3("button",{type:"submit",disabled:controller.submitDisabled,className:cn("inline-flex min-h-11 w-full items-center justify-center gap-2 rounded-lg px-5 py-2.5 text-[15px] font-medium transition sm:w-auto",FORM_SUBMIT_COLORS,"shadow-md hover:brightness-110 hover:shadow-lg","disabled:cursor-not-allowed disabled:opacity-60"),children:[(status==="submitting"||preparing)&&jsx4(LoaderCircle,{className:"h-4 w-4 animate-spin"}),status==="submitting"||preparing?labels.submitting:form.settings.submitLabel||labels.submit]}),isPreview&&jsx4("p",{className:cn("text-xs",FORM_FG_MUTED),children:labels.previewNotice})]}),consentMode==="submit"&&jsx4("p",{className:cn("col-span-full -mt-4 text-xs leading-relaxed",FORM_FG_MUTED),children:consentLabel})]})})})}function FieldRow({field,inputId,className,value,otherText,onOtherTextChange,error,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const errorId=`${inputId}-error`;const describedBy=error?errorId:void 0;if(field.type==="statement"){return jsxs3("div",{className:cn("min-w-0 space-y-1.5",className),children:[jsx4("p",{className:cn("text-base font-semibold leading-snug",FORM_FG),children:field.label}),field.description&&jsx4("p",{className:cn("whitespace-pre-wrap text-sm leading-relaxed",FORM_FG_MUTED),children:field.description})]})}return jsxs3("div",{className:cn("min-w-0 space-y-2",className),children:[jsxs3("label",{htmlFor:inputId,className:cn("block text-base font-semibold leading-snug",FORM_FG),children:[field.label,field.required&&jsx4("span",{"aria-hidden":true,className:cn("ml-0.5",FORM_DANGER),children:"*"})]}),field.description&&jsx4("p",{className:cn("text-sm",FORM_FG_MUTED),children:field.description}),jsx4(FieldInput,{field,inputId,describedBy,invalid:Boolean(error),value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}),error&&jsx4("p",{id:errorId,role:"alert",className:cn("text-xs",FORM_DANGER),children:error})]})}function OtherTextInput({className,placeholder,value,onFocus,onChange}){return jsx4("input",{type:"text",className:cn(INPUT_CLASS,className),placeholder,"aria-label":placeholder,value,onFocus,onChange:e=>onChange(e.target.value)})}function FieldInput({field,inputId,describedBy,invalid,value,otherText,onOtherTextChange,labels,phoneCountry,today,siteCountry,onChange,onFocus,onBlur,upload,taxId}){const{PhoneInput,FormAddressField,FormTaxIdField,FormFileField,FormChoiceDropdown}=useContext2(FormFieldComponentsContext)??ON_DEMAND_FORM_FIELDS;const common={id:inputId,"aria-describedby":describedBy,"aria-invalid":invalid||void 0,onFocus,onBlur,required:field.required,className:cn(INPUT_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)};const singleLine=singleLineInputProps(field,today);if(singleLine){return jsx4(NativeInput,{...common,...singleLine,value:typeof value==="string"?value:typeof value==="number"?String(value):"",onChange:e=>onChange(e.target.value)})}switch(field.type){case"short_text":case"email":case"date":case"time":case"number":case"url":return null;case"long_text":return jsx4(NativeTextarea,{...common,rows:4,maxLength:field.maxLength,value:typeof value==="string"?value:"",onChange:e=>onChange(e.target.value)});case"phone":return jsx4("div",{id:inputId,onFocus,onBlur:onGroupBlur(onBlur),tabIndex:-1,className:"outline-none",children:jsx4(PhoneInput,{value:typeof value==="string"?value:"",onChange:v=>onChange(v??null),defaultCountry:phoneCountry,error:invalid,controlClassName:cn(FORM_FIELD_CLASS,invalid&&FORM_FIELD_INVALID_CLASS)})});case"statement":return null;case"tax_id":return jsx4(FormTaxIdField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,lookup:taxId?.lookup,onRegistryName:taxId?.onRegistryName,onChange,onFocus,onBlur});case"address":return jsx4(FormAddressField,{field,inputId,describedBy,invalid,value,labels,siteCountry,controlClassName:FORM_FIELD_CLASS,onChange,onFocus,onBlur});case"choice":{const selected=Array.isArray(value)?value:typeof value==="string"&&value?[value]:[];const options=[...field.options.map(o=>({id:o.id,label:o.label})),...field.allowOther?[{id:OTHER_OPTION_PLACEHOLDER,label:labels.otherOption}]:[]];const showOther=field.allowOther&&selected.includes(OTHER_OPTION_PLACEHOLDER);if(field.display==="dropdown"&&!field.allowMultiple){return jsxs3("div",{className:"space-y-2.5",onBlur:onGroupBlur(onBlur),children:[jsx4(FormChoiceDropdown,{inputId,describedBy,invalid,value:selected[0]||void 0,options,placeholder:labels.selectPlaceholder,onChange,onFocus}),showOther&&jsx4(OtherTextInput,{placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}return jsxs3("div",{role:field.allowMultiple?"group":"radiogroup","aria-describedby":describedBy,className:"space-y-2.5 pt-0.5",onBlur:onGroupBlur(onBlur),children:[options.map((opt,i)=>{const checked=selected.includes(opt.id);return jsxs3("label",{className:cn("flex cursor-pointer items-center gap-2.5 text-[15px]",FORM_FG),children:[jsx4(SiteChoiceInput,{id:i===0?inputId:void 0,type:field.allowMultiple?"checkbox":"radio",name:inputId,checked,onFocus,onChange:()=>{if(field.allowMultiple){onChange(checked?selected.filter(x=>x!==opt.id):[...selected,opt.id])}else{onChange(opt.id)}}}),jsx4("span",{children:opt.label})]},opt.id)}),showOther&&jsx4(OtherTextInput,{className:"mt-1",placeholder:labels.otherPlaceholder,value:otherText,onFocus,onChange:onOtherTextChange})]})}case"rating":{const Icon=field.icon==="heart"?Heart:field.icon==="thumb"?ThumbsUp:Star;const current=typeof value==="number"?value:0;return jsx4("div",{role:"radiogroup","aria-describedby":describedBy,className:"flex flex-wrap gap-1.5",onBlur:onGroupBlur(onBlur),children:Array.from({length:field.max},(_,i)=>i+1).map(n=>{const active=n<=current;return jsx4("button",{type:"button",role:"radio","aria-checked":current===n,"aria-label":String(n),id:n===1?inputId:void 0,onFocus,onClick:()=>onChange(current===n?null:n),className:cn("flex h-10 w-10 items-center justify-center rounded-lg transition",TONE_BG_TINT_STRONG_HOVER),children:jsx4(Icon,{className:cn("h-6 w-6 transition",active?"fill-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))] text-[var(--site-accent-text,var(--brand-text,var(--brand-color,#FF5733)))]":TONE_TEXT_FAINT)})},n)})})}case"file":return jsx4(FormFileField,{field,inputId,describedBy,invalid,labels,uploadUrl:upload.url,protectionReady:upload.ready,getProtectionData:upload.getProtectionData,onChange,onUnavailableChange:upload.onUnavailableChange,onBusyChange:upload.onBusyChange,onFocus})}}import{createElement,useCallback as useCallback2,useMemo as useMemo3}from"react";function useKanorioForm(options){const{formId,definition,siteName,labels,hiddenValues,followRedirect,onSuccess,siteUrl:siteUrlOption,locale:localeOption}=options;const setup=useKanorioFormSetup({siteUrl:siteUrlOption,locale:localeOption},formId,definition,labels);const{ctx,form}=setup;const site=ctx.site;const botProtectionConfig=useMemo3(()=>site?parsePublicBotProtectionConfig(site.botProtection):null,[site]);const handleSuccess=useCallback2(detail=>{if(typeof window!=="undefined")window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}));onSuccess?.(detail)},[onSuccess]);const submitUrl=form?`${ctx.siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`:null;const controller=useFormController({form:setup.ready?form:null,formId,submitUrl,challengeUrl:`${ctx.siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${ctx.siteUrl}/api/form-protection/altcha`,onSuccess:handleSuccess,followRedirect,hiddenValues,labels:setup.mergedLabels,locale:ctx.locale,websiteName:siteName??null,botProtectionConfig,botProtectionPending:site===null});const{inputIdOf,answers,errors,today,setAnswer,focusField,validateField}=controller;const getInputProps=useCallback2(fieldId=>{const field=controller.fields.find(f=>f.id===fieldId);const inputId=inputIdOf(fieldId);const value=ownFieldValue(answers,fieldId);const typed=field?singleLineInputProps(field,today)??(field.type==="long_text"?{maxLength:field.maxLength}:{}):{};return{...typed,id:inputId,name:fieldId,value:typeof value==="string"?value:typeof value==="number"?String(value):"",required:Boolean(field&&"required"in field&&field.required),...ownFieldValue(errors,fieldId)?{"aria-invalid":true,"aria-describedby":`${inputId}-error`}:{},onChange:event=>setAnswer(fieldId,event.target.value),onFocus:()=>focusField(fieldId),onBlur:()=>validateField(fieldId)}},[controller.fields,inputIdOf,answers,today,errors,setAnswer,focusField,validateField]);const pending2=site===null;const captcha=controller.protection.challengeProps.captcha;const botProtection=createElement(KanorioBotProtection,{key:controller.altchaKey,...controller.protection.fieldProps,captcha,pending:pending2,locale:ctx.locale});const status=setup.loadFailed||setup.siteUnavailable||setup.textUnavailable?"unavailable":!setup.ready?"loading":controller.status==="success"?"success":controller.status==="submitting"||controller.preparing?"submitting":"ready";return{status,definition:setup.ready?form:null,fields:controller.visibleFields,availability:controller.availability,values:answers,setValue:setAnswer,otherText:controller.otherText,setOtherText:controller.setOtherAnswer,errors,errorMessage:controller.errorMessage,validateField,getInputProps,getErrorProps:fieldId=>({id:`${inputIdOf(fieldId)}-error`,role:"alert"}),formProps:{ref:controller.setRoot,onSubmit:event=>void controller.handleSubmit(event),onFocus:controller.markStarted,noValidate:true},botProtection,consent:{mode:controller.consentMode,text:form?.consentText??controller.consentLabel,checked:controller.marketingOptIn,setChecked:controller.setMarketingOptIn},canSubmit:status==="ready"&&!controller.isClosed&&!controller.submitDisabled,submit:()=>controller.handleSubmit(),submitError:controller.submitError,submitErrorMessage:controller.submitErrorMessage,result:controller.result,successMessage:controller.successMessage,uploadReady:controller.uploadReady&&status==="ready",uploadFile:controller.uploadFile,lookupTaxId:(fieldId,input)=>controller.lookupTaxId?controller.lookupTaxId(fieldId,input):Promise.resolve(null),labels:controller.labels}}import{jsx as jsx5}from"react/jsx-runtime";function KanorioForm({formId,definition:initialDefinition,maxColumns,siteName,labels,onSuccess,followRedirect,hiddenValues,className,...config}){const{ctx,form,loadFailed,siteUnavailable,mergedLabels,ready}=useKanorioFormSetup(config,formId,initialDefinition,labels);const site=ctx.site;const siteUrl=ctx.siteUrl;if(loadFailed){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"load_failed",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(siteUnavailable){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-error":"site_unavailable",children:mergedLabels?.temporarilyUnavailable??"This form isn\u2019t accepting responses right now."})}if(!ready||!form||!site){return jsx5(ElementsRoot,{context:ctx,className,"data-kanorio-form-loading":"",loading:true})}return jsx5(ElementsRoot,{context:ctx,className,children:jsx5(BotProtectionConfigProvider,{value:parsePublicBotProtectionConfig(site.botProtection),children:jsx5(FormWidget,{form,maxColumns,submitUrl:`${siteUrl}/api/v1/forms/${encodeURIComponent(form.id)}/submit`,challengeUrl:`${siteUrl}/api/form-protection/challenge`,altchaChallengeUrl:`${siteUrl}/api/form-protection/altcha`,locale:ctx.locale,websiteName:siteName,captchaTheme:ctx.theme,labels:mergedLabels,followRedirect,hiddenValues,onSuccess:detail=>{if(typeof window!=="undefined"){window.dispatchEvent(new CustomEvent(FORM_SUBMIT_EVENT,{detail}))}onSuccess?.(detail)}})})})}export{SITE_RETRY_DELAYS_MS,useKanorioForm,KanorioForm};
|
|
2
|
+
//# sourceMappingURL=chunk-J24HGQ7U.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{deliverablePlayerLabels}from"./chunk-MC63CLSM.js";import{LazyDeliverablePlayer}from"./chunk-UITC3NFQ.js";import{ElementsRoot}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{deliverablePlayerLabels}from"./chunk-MC63CLSM.js";import{LazyDeliverablePlayer}from"./chunk-UITC3NFQ.js";import{ElementsRoot}from"./chunk-7UCZ56EJ.js";import{KanorioApiError,createCustomerClient,useKanorio}from"./chunk-73S6VKNV.js";import{useEffect,useMemo,useState}from"react";import{jsx}from"react/jsx-runtime";function playerLabelsFrom(messages){return deliverablePlayerLabels(messages.account)}function KanorioUnit({deliverable,unit,onUnitChange,onProgress,renderUnauthenticated,tree:givenTree,client:givenClient,className,...config}){const ctx=useKanorio(config);const injected=Boolean(givenTree&&givenClient);const[state,setState]=useState(()=>givenTree&&givenClient?{status:"ready",tree:givenTree}:{status:"loading"});useEffect(()=>{let cancelled=false;if(injected){setState({status:"ready",tree:givenTree});return}if(!ctx.token){setState({status:"unauthenticated"});return}setState({status:"loading"});const client2=createCustomerClient({siteUrl:ctx.siteUrl,token:ctx.token});client2.get("/deliverables/{deliverableId}",{params:{deliverableId:deliverable},query:{locale:ctx.locale}}).then(res=>{if(!cancelled)setState({status:"ready",tree:res.deliverable})}).catch(error=>{if(cancelled)return;if(error instanceof KanorioApiError&&error.status===401){setState({status:"unauthenticated"});return}setState({status:"error",code:error instanceof KanorioApiError?error.code:"NETWORK_ERROR"})});return()=>{cancelled=true}},[ctx.siteUrl,ctx.token,deliverable,injected,givenTree]);const baseClient=givenClient??ctx.client;const client=useMemo(()=>{if(!onProgress)return baseClient;return{openUnit:baseClient.openUnit,submitQuiz:async input=>{const res=await baseClient.submitQuiz(input);if(res.ok)onProgress({unitId:input.unitId,percent:res.deliverable.percent,completed:res.deliverable.completed,deliverableJustCompleted:res.deliverableJustCompleted,coveredPercent:null});return res},getCertificate:baseClient.getCertificate,getTranscript:baseClient.getTranscript,reportProgress:async input=>{const res=await baseClient.reportProgress(input);if(res.ok&&res.deliverable)onProgress({unitId:input.unitId,percent:res.deliverable.percent,completed:res.deliverable.completed,deliverableJustCompleted:res.deliverableJustCompleted,coveredPercent:res.unitCoveredPercent??null});return res}}},[baseClient,onProgress]);if(!ctx.messages||state.status==="loading"){return jsx(ElementsRoot,{context:ctx,className,loading:true,children:jsx("div",{className:"h-64 w-full animate-pulse rounded-(--media-radius,12px) bg-(--media-surface)"})})}const a=ctx.messages.account;if(state.status==="unauthenticated"){return jsx(ElementsRoot,{context:ctx,className,children:renderUnauthenticated?renderUnauthenticated():jsx("p",{className:"rounded-(--media-radius,12px) bg-(--media-surface) p-4 text-sm text-(--media-surface-fg)",children:a.contentLocked})})}if(state.status==="error"){return jsx(ElementsRoot,{context:ctx,className,children:jsx("p",{role:"alert",className:"rounded-(--media-radius,12px) bg-(--media-surface) p-4 text-sm text-(--media-surface-fg)",children:state.code==="DELIVERABLE_NOT_FOUND"?a.contentEmptyTitle:a.contentLoadError})})}return jsx(ElementsRoot,{context:ctx,className,children:jsx(LazyDeliverablePlayer,{tree:state.tree,client,labels:playerLabelsFrom(ctx.messages),locale:ctx.locale,timeZone:ctx.timeZone,initialUnitId:unit??null,onUnitChange})})}export{playerLabelsFrom,KanorioUnit};
|
|
2
|
+
//# sourceMappingURL=chunk-JYBSXLT3.js.map
|