@bitpalm/ai-agents 0.1.14 → 0.1.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -76,6 +76,7 @@ The widget already detects common field names automatically. For custom forms, y
76
76
  - `data-bp-phone`
77
77
  - `data-bp-name` (or `data-bp-first-name` / `data-bp-last-name`)
78
78
  - `data-bp-company`
79
+ - `data-bp-field="email|phone|name|first-name|last-name|company"` (generic fallback)
79
80
 
80
81
  Disable auto-identity for one specific form:
81
82
 
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var N=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var st=Object.prototype.hasOwnProperty;var rt=(n,a)=>{for(var c in a)N(n,c,{get:a[c],enumerable:!0})},lt=(n,a,c,l)=>{if(a&&typeof a=="object"||typeof a=="function")for(let d of it(a))!st.call(n,d)&&d!==c&&N(n,d,{get:()=>a[d],enumerable:!(l=ot(a,d))||l.enumerable});return n};var ct=n=>lt(N({},"__esModule",{value:!0}),n);var yt={};rt(yt,{createWidget:()=>U});module.exports=ct(yt);var dt="https://agents.bitpalm.ae",u="_bp_",pt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]);function f(n,a=180){return n?n.replace(/\s+/g," ").trim().slice(0,a):""}function mt(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function T(n,a){for(let c of a)if(n.includes(c))return!0;return!1}function D(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function F(n){let a=f(n,50);if(!a)return"";let c=a.startsWith("+"),l=a.replace(/\D/g,"");return l.length<6?"":`${c?"+":""}${l.slice(0,20)}`}function $(n,a){for(let c of a){let l=n.querySelector(c),d=f(l?.value);if(d)return d}return""}function ut(n){let a=f($(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),c=F($(n,["[data-bp-phone]","[data-bitpalm-phone]"])),l=f($(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),d=f($(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),x=f($(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),v=f($(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let t of Array.from(n.elements)){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)||t.disabled||t instanceof HTMLInputElement&&pt.has(t.type.toLowerCase()))continue;let W=t.hasAttribute("data-bp-email")||t.hasAttribute("data-bitpalm-email")||t.hasAttribute("data-bp-phone")||t.hasAttribute("data-bitpalm-phone")||t.hasAttribute("data-bp-name")||t.hasAttribute("data-bitpalm-name")||t.hasAttribute("data-bp-full-name")||t.hasAttribute("data-bitpalm-full-name")||t.hasAttribute("data-bp-first-name")||t.hasAttribute("data-bitpalm-first-name")||t.hasAttribute("data-bp-last-name")||t.hasAttribute("data-bitpalm-last-name")||t.hasAttribute("data-bp-company")||t.hasAttribute("data-bitpalm-company");if(t instanceof HTMLInputElement&&t.type.toLowerCase()==="hidden"&&!W)continue;let p=f(t.value);if(!p)continue;let _=t instanceof HTMLInputElement?t.type.toLowerCase():"",o=mt([t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("placeholder"),t.getAttribute("aria-label"),t.getAttribute("data-field"),t.getAttribute("data-name")].filter(Boolean).join(" ")),g=_==="email"||T(o,[" email "," e mail "," mail "," correo "]),A=_==="tel"||T(o,[" phone "," mobile "," tel "," whatsapp "," handy "," telefon "," kontakt "]),M=T(o,[" company "," firma "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),w=T(o,[" first name "," firstname "," given name "," given name "," givenname "," vorname "]),I=T(o,[" last name "," lastname "," family name "," familyname "," surname "," nachname "]),P=T(o,[" full name "," fullname "," contact name "," name "])&&!g&&!A;if(!a&&g&&D(p)){a=p.toLowerCase();continue}if(!c&&A){let b=F(p);if(b){c=b;continue}}if(!v&&M){v=f(p,160);continue}if(!d&&w){d=f(p,100);continue}if(!x&&I){x=f(p,100);continue}if(!l&&P&&!D(p)&&!F(p)){l=f(p,140);continue}!a&&D(p)&&T(o,[" mail "," email "," e mail "])&&(a=p.toLowerCase())}l||(l=f([d,x].filter(Boolean).join(" "),140));let i={...l?{name:l}:{},...a?{email:a}:{},...c?{phone:c}:{},...v?{company:v}:{}};return Object.keys(i).length>0?i:null}function ft(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function U(n){let{slug:a,locale:c=ft(),baseUrl:l=dt,token:d,zIndex:x=9999,autoIdentify:v=!0}=n,i=document,t=i.createElement("iframe"),W=`${l}/t/${a}/widget`,p=new URLSearchParams({locale:c});d&&p.set("token",d),t.src=`${W}?${p.toString()}`,t.allow="clipboard-write",t.setAttribute("allowtransparency","true"),t.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${x};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,i.body.appendChild(t);let _=new URL(t.src).origin,o=i.createElement("div");if(o.setAttribute("role","button"),o.setAttribute("aria-label","Chat"),o.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${x-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,o.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',o.onmouseenter=()=>{o.style.transform="scale(1.1)"},o.onmouseleave=()=>{o.style.transform="scale(1)"},o.onclick=()=>at(),i.body.appendChild(o),!i.getElementById("_bp_fade")){let e=i.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",i.head.appendChild(e)}let g=null,A=!1,M=!1,w=()=>{g&&(g.remove(),g=null)},I=()=>{},P=e=>{if(e.origin===_){if(e.data?.type==="bitpalm-widget-config"){M=!1,A=!0,t.style.display==="none"&&(t.style.display=""),e.data.primaryColor&&(o.style.background=e.data.primaryColor,o.style.boxShadow=e.data.chatShadow==="none"?"none":`0 0 15px ${e.data.primaryColor}50`);let s=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){o.innerHTML="";let r=i.createElement("span");r.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${s}`;let m=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");m?(m.querySelectorAll("script,foreignObject").forEach(E=>E.remove()),m.querySelectorAll("*").forEach(E=>{for(let L of[...E.attributes])(L.name.startsWith("on")||L.value&&L.value.includes("javascript:"))&&E.removeAttribute(L.name)}),m.setAttribute("width","24"),m.setAttribute("height","24"),m.style.display="block",r.appendChild(m)):r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',o.appendChild(r)}else{let r=o.querySelector("svg");r&&(r.style.stroke=s)}o.style.display="flex",requestAnimationFrame(()=>{o.style.opacity="1"})}if(e.data?.type==="bitpalm-widget-resize"){let s=e.data.width>0,r=window.innerWidth<=640;s?(t.style.width=r?`${window.innerWidth}px`:`${e.data.width}px`,t.style.height=r?`${window.innerHeight}px`:`${e.data.height}px`,r&&(t.style.left="0",t.style.top="0"),t.style.opacity="1",t.style.pointerEvents="auto"):(t.style.width="1px",t.style.height="1px",t.style.left="",t.style.top="",t.style.opacity="0",t.style.pointerEvents="none"),o.style.display=s?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(M||!A)return;w(),g=i.createElement("div"),g.style.cssText=`position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${x-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let s=(e.data.message||"").replace(/</g,"&lt;");g.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${s}</p><div style="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;"></div>`;let r=i.createElement("button");r.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",r.innerHTML="&#10005;",r.onclick=h=>{h.stopPropagation(),w(),t.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},g.onclick=()=>{w(),o.style.display="none",t.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},g.appendChild(r),i.body.appendChild(g)}e.data?.type==="bitpalm-trigger-hide"&&w(),e.data?.type==="bitpalm-request-context"&&I(),e.data?.type==="bitpalm-widget-blocked"&&(M=!0,A=!1,o.style.display="none",w(),t.style.display="none")}};window.addEventListener("message",P);let b=!1;try{b=localStorage.getItem(`${u}optout`)==="1"}catch{}let B=`${u}vid`,y="";if(!b){try{y=localStorage.getItem(B)||""}catch{}if(!y){let e=i.cookie.match(new RegExp(`(?:^|; )${B}=([^;]+)`));y=e?decodeURIComponent(e[1]):""}y||(y=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(B,y)}catch{}try{i.cookie=`${B}=${encodeURIComponent(y)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!b)try{let e=new URLSearchParams(location.search),s={};for(let k of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let m=e.get(k);m&&(s[k]=m)}let r=JSON.stringify({tenant_slug:a,visitor_id:y,url:location.href,referrer:i.referrer||void 0,...Object.keys(s).length>0?{utm:s}:{}}),h=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(h,new Blob([r],{type:"application/json"})):fetch(h,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let q="",J=0,Y=e=>{if(b||!v||!y)return;let s=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(s instanceof HTMLFormElement))return;let r=(s.getAttribute("data-bp-identify")||s.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(r==="off"||r==="false"||r==="0")return;let h=ut(s);if(!h)return;let k=[s.getAttribute("id")||"",s.getAttribute("name")||"",s.getAttribute("action")||"",h.email||"",h.phone||"",h.name||"",h.company||""].join("|").toLowerCase(),m=Date.now();if(!(k===q&&m-J<8e3)){q=k,J=m;try{let E=JSON.stringify({tenant_slug:a,visitor_id:y,url:location.href,referrer:i.referrer||void 0,...h}),L=`${l}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(L,new Blob([E],{type:"application/json"})):fetch(L,{method:"POST",body:E,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!b&&v&&i.addEventListener("submit",Y,!0);let C=parseInt(sessionStorage.getItem(`${u}pages`)||"0")+1;sessionStorage.setItem(`${u}pages`,String(C));let S=JSON.parse(sessionStorage.getItem(`${u}hist`)||"[]");S.push(location.href),S.length>20&&(S=S.slice(-20)),sessionStorage.setItem(`${u}hist`,JSON.stringify(S));let G=Date.now(),H=parseInt(sessionStorage.getItem(`${u}site_start`)||"0");H||(H=G,sessionStorage.setItem(`${u}site_start`,String(H)));let V=[];I=()=>{let e=!1;try{e=!!localStorage.getItem(`${u}visited`)}catch{e=!1}if(t.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:i.title,returning:e,pageCount:C,pageHistory:S,loadedAt:G,siteStart:H,locale:c,visitorId:b?"":y},"*"),!e&&!b)try{localStorage.setItem(`${u}visited`,"1")}catch{}},t.addEventListener("load",()=>{I(),[120,450,1100].forEach(e=>{let s=setTimeout(()=>I(),e);V.push(s)})});let Z=history.pushState.bind(history),K=history.replaceState.bind(history),O=()=>{C++,sessionStorage.setItem(`${u}pages`,String(C));let e=JSON.parse(sessionStorage.getItem(`${u}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),S=e,sessionStorage.setItem(`${u}hist`,JSON.stringify(e)),t.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:i.title,pageCount:C,pageHistory:e,loadedAt:Date.now()},"*"),!b)try{let s=JSON.stringify({tenant_slug:a,visitor_id:y,url:location.href}),r=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(r,new Blob([s],{type:"application/json"})):fetch(r,{method:"POST",body:s,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){Z(...e),O()},history.replaceState=function(...e){K(...e),O()},window.addEventListener("popstate",O);let X=-1,j,Q=()=>{clearTimeout(j),j=setTimeout(()=>{let e=Math.max(i.documentElement.scrollHeight,i.body.scrollHeight)-window.innerHeight,s=e>0?Math.round(window.scrollY/e*100):100;s!==X&&(X=s,t.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:s},"*"))},500)};window.addEventListener("scroll",Q,{passive:!0});let tt=e=>{e.clientY<=0&&t.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};i.addEventListener("mouseout",tt);let z,et=!1,R=()=>{clearTimeout(z),!et&&(z=setTimeout(()=>{et=!0,t.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},nt=["mousemove","keydown","scroll","touchstart"];nt.forEach(e=>i.addEventListener(e,R,{passive:!0})),R();let at=()=>{o.style.display="none",w(),t.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=t.src.split("#")[0];t.src=`${e}#bp-open-${Date.now()}`};return{open:at,close:()=>{t.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",P),window.removeEventListener("scroll",Q),window.removeEventListener("popstate",O),i.removeEventListener("mouseout",tt),i.removeEventListener("submit",Y,!0),nt.forEach(e=>i.removeEventListener(e,R)),clearTimeout(j),clearTimeout(z),V.forEach(e=>clearTimeout(e)),history.pushState=Z,history.replaceState=K,w(),o.remove(),t.remove()}}}function gt(n){if(n==null)return;let a=n.trim().toLowerCase();if(["1","true","yes","on"].includes(a))return!0;if(["0","false","no","off"].includes(a))return!1}if(typeof document<"u"){let n=document.currentScript;if(n?.dataset.slug){let a=()=>{U({slug:n.dataset.slug,locale:n.dataset.locale,baseUrl:n.dataset.baseUrl,token:n.dataset.token,zIndex:n.dataset.zIndex?Number(n.dataset.zIndex):void 0,autoIdentify:gt(n.dataset.autoIdentify)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",a):a()}}0&&(module.exports={createWidget});
1
+ "use strict";var J=Object.defineProperty;var dt=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var mt=Object.prototype.hasOwnProperty;var ut=(n,e)=>{for(var c in e)J(n,c,{get:e[c],enumerable:!0})},ft=(n,e,c,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let m of pt(e))!mt.call(n,m)&&m!==c&&J(n,m,{get:()=>e[m],enumerable:!(o=dt(e,m))||o.enumerable});return n};var gt=n=>ft(J({},"__esModule",{value:!0}),n);var At={};ut(At,{createWidget:()=>U});module.exports=gt(At);var ht="https://agents.bitpalm.ae",h="_bp_",yt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),bt=8e3,rt=`${h}identify_signature`,lt=`${h}identify_fingerprint`,ct=`${h}identify_sent_at`;function u(n,e=180){return n?n.replace(/\s+/g," ").trim().slice(0,e):""}function wt(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function H(n,e){for(let c of e)if(n.includes(c))return!0;return!1}function _(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function $(n){let e=u(n,50);if(!e)return"";let c=e.startsWith("+"),o=e.replace(/\D/g,"");return o.length<6?"":`${c?"+":""}${o.slice(0,20)}`}function B(n,e){for(let c of e){let o=n.querySelector(c),m=u(o?.value);if(m)return m}return""}function xt(n){return u(n.getAttribute("data-bp-field")||n.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function St(n){return n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function vt(n,e){let c=[],o=(i,x=140)=>{let a=u(i,x);a&&c.push(a)};o(e.name),o(e.id),o(e.getAttribute("autocomplete")),o(e.getAttribute("placeholder")),o(e.getAttribute("aria-label")),o(e.getAttribute("data-field")),o(e.getAttribute("data-name")),o(e.getAttribute("data-label")),o(e.getAttribute("data-bp-field")),o(e.getAttribute("data-bitpalm-field"));let m=new Set,y=i=>{let x=u(i,200);!x||m.has(x)||(m.add(x),c.push(x))};for(let i of Array.from(e.labels||[]))y(i.textContent);if(e.id){let i=n.querySelector(`label[for="${St(e.id)}"]`);y(i?.textContent)}let g=e.closest("label");y(g?.textContent);let r=e.getAttribute("aria-labelledby");if(r)for(let i of r.split(/\s+/)){if(!i)continue;let x=n.ownerDocument.getElementById(i);y(x?.textContent)}return c}function Et(n){let e=u(B(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),c=$(B(n,["[data-bp-phone]","[data-bitpalm-phone]"])),o=u(B(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),m=u(B(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),y=u(B(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),g=u(B(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let a of Array.from(n.elements)){if(!(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement)||a.disabled||a instanceof HTMLInputElement&&yt.has(a.type.toLowerCase()))continue;let f=xt(a),p=a.hasAttribute("data-bp-email")||a.hasAttribute("data-bitpalm-email")||a.hasAttribute("data-bp-phone")||a.hasAttribute("data-bitpalm-phone")||a.hasAttribute("data-bp-name")||a.hasAttribute("data-bitpalm-name")||a.hasAttribute("data-bp-full-name")||a.hasAttribute("data-bitpalm-full-name")||a.hasAttribute("data-bp-first-name")||a.hasAttribute("data-bitpalm-first-name")||a.hasAttribute("data-bp-last-name")||a.hasAttribute("data-bitpalm-last-name")||a.hasAttribute("data-bp-company")||a.hasAttribute("data-bitpalm-company")||!!f;if(a instanceof HTMLInputElement&&a.type.toLowerCase()==="hidden"&&!p)continue;let s=u(a.value);if(!s)continue;let C=a instanceof HTMLInputElement?a.type.toLowerCase():"",v=wt(vt(n,a).join(" "));if(!e&&f==="email"&&_(s)){e=s.toLowerCase();continue}if(!c&&(f==="phone"||f==="tel"||f==="mobile"||f==="whatsapp")){let L=$(s);if(L){c=L;continue}}if(!g&&f==="company"){g=u(s,160);continue}if(!m&&(f==="first-name"||f==="firstname")){m=u(s,100);continue}if(!y&&(f==="last-name"||f==="lastname"||f==="surname")){y=u(s,100);continue}if(!o&&(f==="name"||f==="full-name"||f==="fullname")){!_(s)&&!$(s)&&(o=u(s,140));continue}let E=C==="email"||H(v,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),M=C==="tel"||H(v,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),F=H(v,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),I=H(v,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),P=H(v,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),b=H(v,[" full name "," fullname "," contact name "," name "])&&!E&&!M;if(!e&&E&&_(s)){e=s.toLowerCase();continue}if(!c&&M){let L=$(s);if(L){c=L;continue}}if(!g&&F){g=u(s,160);continue}if(!m&&I){m=u(s,100);continue}if(!y&&P){y=u(s,100);continue}if(!o&&b&&!_(s)&&!$(s)){o=u(s,140);continue}!e&&_(s)&&(e=s.toLowerCase())}if(o&&(_(o)||$(o))&&(o=""),g&&(_(g)||$(g))&&(g=""),o||(o=u([m,y].filter(Boolean).join(" "),140)),o&&e&&o.toLowerCase()===e.toLowerCase()&&(o=""),!!!(e||c)&&!!!(o&&g))return null;let x={...o?{name:o}:{},...e?{email:e}:{},...c?{phone:c}:{},...g?{company:g}:{}};return Object.keys(x).length>0?x:null}function It(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function Lt(){if(typeof window>"u")return!1;let n=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(n))return!0;let c=window.matchMedia("(pointer: coarse)").matches,o=window.matchMedia("(hover: none)").matches,m=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return c&&o&&m<=900}function U(n){let{slug:e,locale:c=It(),baseUrl:o=ht,token:m,zIndex:y=9999,autoIdentify:g=!0}=n,r=document,i=r.createElement("iframe"),x=`${o}/t/${e}/widget`,a=new URLSearchParams({locale:c});m&&a.set("token",m),i.src=`${x}?${a.toString()}`,i.allow="clipboard-write",i.setAttribute("allowtransparency","true"),i.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${y};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,r.body.appendChild(i);let f=new URL(i.src).origin,p=r.createElement("div");if(p.setAttribute("role","button"),p.setAttribute("aria-label","Chat"),p.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${y-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,p.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',p.onmouseenter=()=>{p.style.transform="scale(1.1)"},p.onmouseleave=()=>{p.style.transform="scale(1)"},p.onclick=()=>ot(),r.body.appendChild(p),!r.getElementById("_bp_fade")){let t=r.createElement("style");t.id="_bp_fade",t.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",r.head.appendChild(t)}let s=null,C=!1,v=!1,E=()=>{s&&(s.remove(),s=null)},M=()=>{},F=t=>{if(t.origin===f){if(t.data?.type==="bitpalm-widget-config"){v=!1,C=!0,i.style.display==="none"&&(i.style.display=""),t.data.primaryColor&&(p.style.background=t.data.primaryColor,p.style.boxShadow=t.data.chatShadow==="none"?"none":`0 0 15px ${t.data.primaryColor}50`);let l=t.data.chatButtonIconColor||"black";if(t.data.chatButtonIconSvg){p.innerHTML="";let d=r.createElement("span");d.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${l}`;let w=new DOMParser().parseFromString(t.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");w?(w.querySelectorAll("script,foreignObject").forEach(A=>A.remove()),w.querySelectorAll("*").forEach(A=>{for(let N of[...A.attributes])(N.name.startsWith("on")||N.value&&N.value.includes("javascript:"))&&A.removeAttribute(N.name)}),w.setAttribute("width","24"),w.setAttribute("height","24"),w.style.display="block",d.appendChild(w)):d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',p.appendChild(d)}else{let d=p.querySelector("svg");d&&(d.style.stroke=l)}p.style.display="flex",requestAnimationFrame(()=>{p.style.opacity="1"})}if(t.data?.type==="bitpalm-widget-resize"){let l=t.data.width>0,d=Lt();l?(i.style.width=d?`${window.innerWidth}px`:`${t.data.width}px`,i.style.height=d?`${window.innerHeight}px`:`${t.data.height}px`,d&&(i.style.left="0",i.style.top="0"),i.style.opacity="1",i.style.pointerEvents="auto"):(i.style.width="1px",i.style.height="1px",i.style.left="",i.style.top="",i.style.opacity="0",i.style.pointerEvents="none"),p.style.display=l?"none":"flex"}if(t.data?.type==="bitpalm-trigger-show"){if(v||!C)return;E(),s=r.createElement("div"),s.style.cssText=`position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${y-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let l=(t.data.message||"").replace(/</g,"&lt;");s.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${l}</p><div style="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;"></div>`;let d=r.createElement("button");d.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",d.innerHTML="&#10005;",d.onclick=S=>{S.stopPropagation(),E(),i.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},s.onclick=()=>{E(),p.style.display="none",i.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},s.appendChild(d),r.body.appendChild(s)}t.data?.type==="bitpalm-trigger-hide"&&E(),t.data?.type==="bitpalm-request-context"&&M(),t.data?.type==="bitpalm-widget-blocked"&&(v=!0,C=!1,p.style.display="none",E(),i.style.display="none")}};window.addEventListener("message",F);let I=!1;try{I=localStorage.getItem(`${h}optout`)==="1"}catch{}let P=`${h}vid`,b="";if(!I){try{b=localStorage.getItem(P)||""}catch{}if(!b){let t=r.cookie.match(new RegExp(`(?:^|; )${P}=([^;]+)`));b=t?decodeURIComponent(t[1]):""}b||(b=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(P,b)}catch{}try{r.cookie=`${P}=${encodeURIComponent(b)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!I)try{let t=new URLSearchParams(location.search),l={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let w=t.get(T);w&&(l[T]=w)}let d=JSON.stringify({tenant_slug:e,visitor_id:b,url:location.href,referrer:r.referrer||void 0,...Object.keys(l).length>0?{utm:l}:{}}),S=`${o}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(S,new Blob([d],{type:"application/json"})):fetch(S,{method:"POST",body:d,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let L="",R="",j=0;try{L=sessionStorage.getItem(rt)||"",R=sessionStorage.getItem(lt)||"";let t=parseInt(sessionStorage.getItem(ct)||"0",10);Number.isFinite(t)&&t>0&&(j=t)}catch{}let G=t=>{if(I||!g||!b)return;let l=t.target instanceof HTMLFormElement?t.target:t.target instanceof Element?t.target.closest("form"):null;if(!(l instanceof HTMLFormElement))return;let d=(l.getAttribute("data-bp-identify")||l.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(d==="off"||d==="false"||d==="0")return;let S=Et(l);if(!S)return;let T=[S.email||"",S.phone||"",S.name||"",S.company||""].join("|").toLowerCase(),w=[l.getAttribute("id")||"",l.getAttribute("name")||"",l.getAttribute("action")||"",T].join("|").toLowerCase(),A=Date.now();if(!(A-j<bt&&(w===L||T===R))){L=w,R=T,j=A;try{sessionStorage.setItem(rt,w),sessionStorage.setItem(lt,T),sessionStorage.setItem(ct,String(A))}catch{}try{let at=JSON.stringify({tenant_slug:e,visitor_id:b,url:location.href,referrer:r.referrer||void 0,...S}),st=`${o}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(st,new Blob([at],{type:"application/json"})):fetch(st,{method:"POST",body:at,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!I&&g&&r.addEventListener("submit",G,!0);let D=parseInt(sessionStorage.getItem(`${h}pages`)||"0")+1;sessionStorage.setItem(`${h}pages`,String(D));let k=JSON.parse(sessionStorage.getItem(`${h}hist`)||"[]");k.push(location.href),k.length>20&&(k=k.slice(-20)),sessionStorage.setItem(`${h}hist`,JSON.stringify(k));let K=Date.now(),W=parseInt(sessionStorage.getItem(`${h}site_start`)||"0");W||(W=K,sessionStorage.setItem(`${h}site_start`,String(W)));let V=[];M=()=>{let t=!1;try{t=!!localStorage.getItem(`${h}visited`)}catch{t=!1}if(i.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:r.title,returning:t,pageCount:D,pageHistory:k,loadedAt:K,siteStart:W,locale:c,visitorId:I?"":b},"*"),!t&&!I)try{localStorage.setItem(`${h}visited`,"1")}catch{}},i.addEventListener("load",()=>{M(),[120,450,1100].forEach(t=>{let l=setTimeout(()=>M(),t);V.push(l)})});let Z=history.pushState.bind(history),X=history.replaceState.bind(history),O=()=>{D++,sessionStorage.setItem(`${h}pages`,String(D));let t=JSON.parse(sessionStorage.getItem(`${h}hist`)||"[]");if(t.push(location.href),t.length>20&&t.splice(0,t.length-20),k=t,sessionStorage.setItem(`${h}hist`,JSON.stringify(t)),i.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:r.title,pageCount:D,pageHistory:t,loadedAt:Date.now()},"*"),!I)try{let l=JSON.stringify({tenant_slug:e,visitor_id:b,url:location.href}),d=`${o}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(d,new Blob([l],{type:"application/json"})):fetch(d,{method:"POST",body:l,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...t){Z(...t),O()},history.replaceState=function(...t){X(...t),O()},window.addEventListener("popstate",O);let Q=-1,z,tt=()=>{clearTimeout(z),z=setTimeout(()=>{let t=Math.max(r.documentElement.scrollHeight,r.body.scrollHeight)-window.innerHeight,l=t>0?Math.round(window.scrollY/t*100):100;l!==Q&&(Q=l,i.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:l},"*"))},500)};window.addEventListener("scroll",tt,{passive:!0});let et=t=>{t.clientY<=0&&i.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};r.addEventListener("mouseout",et);let Y,nt=!1,q=()=>{clearTimeout(Y),!nt&&(Y=setTimeout(()=>{nt=!0,i.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},it=["mousemove","keydown","scroll","touchstart"];it.forEach(t=>r.addEventListener(t,q,{passive:!0})),q();let ot=()=>{p.style.display="none",E(),i.contentWindow?.postMessage({type:"bitpalm-open"},"*");let t=i.src.split("#")[0];i.src=`${t}#bp-open-${Date.now()}`};return{open:ot,close:()=>{i.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",F),window.removeEventListener("scroll",tt),window.removeEventListener("popstate",O),r.removeEventListener("mouseout",et),r.removeEventListener("submit",G,!0),it.forEach(t=>r.removeEventListener(t,q)),clearTimeout(z),clearTimeout(Y),V.forEach(t=>clearTimeout(t)),history.pushState=Z,history.replaceState=X,E(),p.remove(),i.remove()}}}function Tt(n){if(n==null)return;let e=n.trim().toLowerCase();if(["1","true","yes","on"].includes(e))return!0;if(["0","false","no","off"].includes(e))return!1}if(typeof document<"u"){let n=document.currentScript;if(n?.dataset.slug){let e=()=>{U({slug:n.dataset.slug,locale:n.dataset.locale,baseUrl:n.dataset.baseUrl,token:n.dataset.token,zIndex:n.dataset.zIndex?Number(n.dataset.zIndex):void 0,autoIdentify:Tt(n.dataset.autoIdentify)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e):e()}}0&&(module.exports={createWidget});
2
2
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/widget.ts"],"sourcesContent":["export { createWidget } from \"./widget\";\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nimport { createWidget } from \"./widget\";\n\nfunction parseBoolean(value: string | undefined): boolean | undefined {\n if (value == null) return undefined;\n const normalized = value.trim().toLowerCase();\n if ([\"1\", \"true\", \"yes\", \"on\"].includes(normalized)) return true;\n if ([\"0\", \"false\", \"no\", \"off\"].includes(normalized)) return false;\n return undefined;\n}\n\n/**\n * Auto-init from script tag:\n * <script src=\"https://cdn.bitpalm.ae/widget.js\" data-slug=\"my-agent\"></script>\n */\nif (typeof document !== \"undefined\") {\n const script = document.currentScript as HTMLScriptElement | null;\n if (script?.dataset.slug) {\n const init = () => {\n createWidget({\n slug: script!.dataset.slug!,\n locale: script!.dataset.locale,\n baseUrl: script!.dataset.baseUrl,\n token: script!.dataset.token,\n zIndex: script!.dataset.zIndex ? Number(script!.dataset.zIndex) : undefined,\n autoIdentify: parseBoolean(script!.dataset.autoIdentify),\n });\n };\n\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n }\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\nconst IGNORED_INPUT_TYPES = new Set([\"password\", \"file\", \"checkbox\", \"radio\", \"submit\", \"button\", \"reset\", \"image\"]);\n\ntype IdentityPayload = {\n name?: string;\n email?: string;\n phone?: string;\n company?: string;\n};\n\nfunction normalizeText(value: string | null | undefined, maxLen = 180): string {\n if (!value) return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, maxLen);\n}\n\nfunction normalizeTokens(value: string | null | undefined): string {\n if (!value) return \"\";\n return ` ${value.toLowerCase().replace(/[_-]+/g, \" \").replace(/[^a-z0-9\\s@.]/g, \" \").replace(/\\s+/g, \" \").trim()} `;\n}\n\nfunction includesAny(haystack: string, needles: string[]): boolean {\n for (const needle of needles) {\n if (haystack.includes(needle)) return true;\n }\n return false;\n}\n\nfunction isEmail(value: string): boolean {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/i.test(value);\n}\n\nfunction normalizePhone(value: string): string {\n const trimmed = normalizeText(value, 50);\n if (!trimmed) return \"\";\n const hasPlus = trimmed.startsWith(\"+\");\n const digits = trimmed.replace(/\\D/g, \"\");\n if (digits.length < 6) return \"\";\n return `${hasPlus ? \"+\" : \"\"}${digits.slice(0, 20)}`;\n}\n\nfunction getExplicitValue(form: HTMLFormElement, selectors: string[]): string {\n for (const selector of selectors) {\n const el = form.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(selector);\n const value = normalizeText(el?.value);\n if (value) return value;\n }\n return \"\";\n}\n\nfunction extractIdentityFromForm(form: HTMLFormElement): IdentityPayload | null {\n let email = normalizeText(getExplicitValue(form, [\n \"[data-bp-email]\",\n \"[data-bitpalm-email]\",\n ]), 140).toLowerCase();\n\n let phone = normalizePhone(getExplicitValue(form, [\n \"[data-bp-phone]\",\n \"[data-bitpalm-phone]\",\n ]));\n\n let name = normalizeText(getExplicitValue(form, [\n \"[data-bp-name]\",\n \"[data-bitpalm-name]\",\n \"[data-bp-full-name]\",\n \"[data-bitpalm-full-name]\",\n ]));\n\n let firstName = normalizeText(getExplicitValue(form, [\n \"[data-bp-first-name]\",\n \"[data-bitpalm-first-name]\",\n ]));\n\n let lastName = normalizeText(getExplicitValue(form, [\n \"[data-bp-last-name]\",\n \"[data-bitpalm-last-name]\",\n ]));\n\n let company = normalizeText(getExplicitValue(form, [\n \"[data-bp-company]\",\n \"[data-bitpalm-company]\",\n ]));\n\n for (const rawEl of Array.from(form.elements)) {\n if (!(rawEl instanceof HTMLInputElement || rawEl instanceof HTMLTextAreaElement || rawEl instanceof HTMLSelectElement)) continue;\n if (rawEl.disabled) continue;\n if (rawEl instanceof HTMLInputElement && IGNORED_INPUT_TYPES.has(rawEl.type.toLowerCase())) continue;\n\n const explicitField =\n rawEl.hasAttribute(\"data-bp-email\") ||\n rawEl.hasAttribute(\"data-bitpalm-email\") ||\n rawEl.hasAttribute(\"data-bp-phone\") ||\n rawEl.hasAttribute(\"data-bitpalm-phone\") ||\n rawEl.hasAttribute(\"data-bp-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-name\") ||\n rawEl.hasAttribute(\"data-bp-full-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-full-name\") ||\n rawEl.hasAttribute(\"data-bp-first-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-first-name\") ||\n rawEl.hasAttribute(\"data-bp-last-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-last-name\") ||\n rawEl.hasAttribute(\"data-bp-company\") ||\n rawEl.hasAttribute(\"data-bitpalm-company\");\n\n if (rawEl instanceof HTMLInputElement && rawEl.type.toLowerCase() === \"hidden\" && !explicitField) continue;\n\n const value = normalizeText(rawEl.value);\n if (!value) continue;\n\n const type = rawEl instanceof HTMLInputElement ? rawEl.type.toLowerCase() : \"\";\n const tokens = normalizeTokens([\n rawEl.name,\n rawEl.id,\n rawEl.getAttribute(\"autocomplete\"),\n rawEl.getAttribute(\"placeholder\"),\n rawEl.getAttribute(\"aria-label\"),\n rawEl.getAttribute(\"data-field\"),\n rawEl.getAttribute(\"data-name\"),\n ].filter(Boolean).join(\" \"));\n\n const emailLike = type === \"email\" || includesAny(tokens, [\" email \", \" e mail \", \" mail \", \" correo \"]);\n const phoneLike = type === \"tel\" || includesAny(tokens, [\" phone \", \" mobile \", \" tel \", \" whatsapp \", \" handy \", \" telefon \", \" kontakt \"]);\n const companyLike = includesAny(tokens, [\" company \", \" firma \", \" organization \", \" organisation \", \" business \", \" unternehmen \", \" agency \", \" brokerage \"]);\n const firstNameLike = includesAny(tokens, [\" first name \", \" firstname \", \" given name \", \" given name \", \" givenname \", \" vorname \"]);\n const lastNameLike = includesAny(tokens, [\" last name \", \" lastname \", \" family name \", \" familyname \", \" surname \", \" nachname \"]);\n const fullNameLike = includesAny(tokens, [\" full name \", \" fullname \", \" contact name \", \" name \"]) && !emailLike && !phoneLike;\n\n if (!email && emailLike && isEmail(value)) {\n email = value.toLowerCase();\n continue;\n }\n if (!phone && phoneLike) {\n const normalized = normalizePhone(value);\n if (normalized) {\n phone = normalized;\n continue;\n }\n }\n if (!company && companyLike) {\n company = normalizeText(value, 160);\n continue;\n }\n if (!firstName && firstNameLike) {\n firstName = normalizeText(value, 100);\n continue;\n }\n if (!lastName && lastNameLike) {\n lastName = normalizeText(value, 100);\n continue;\n }\n if (!name && fullNameLike && !isEmail(value) && !normalizePhone(value)) {\n name = normalizeText(value, 140);\n continue;\n }\n\n if (!email && isEmail(value) && includesAny(tokens, [\" mail \", \" email \", \" e mail \"])) {\n email = value.toLowerCase();\n }\n }\n\n if (!name) {\n name = normalizeText([firstName, lastName].filter(Boolean).join(\" \"), 140);\n }\n\n const identity: IdentityPayload = {\n ...(name ? { name } : {}),\n ...(email ? { email } : {}),\n ...(phone ? { phone } : {}),\n ...(company ? { company } : {}),\n };\n\n return Object.keys(identity).length > 0 ? identity : null;\n}\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n token,\n zIndex = 9999,\n autoIdentify = true,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n const qs = new URLSearchParams({ locale });\n if (token) qs.set(\"token\", token);\n iframe.src = `${widgetUrl}?${qs.toString()}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.style.cssText = `position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n let launcherReady = false;\n let widgetBlocked = false;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n let sendParentContext = () => {};\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n widgetBlocked = false;\n launcherReady = true;\n if (iframe.style.display === \"none\") iframe.style.display = \"\";\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = window.innerWidth <= 640;\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n if (widgetBlocked || !launcherReady) return;\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"&lt;\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;\"></div>`;\n const close = d.createElement(\"button\");\n close.style.cssText = \"position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;\";\n close.innerHTML = \"&#10005;\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Iframe requests latest parent context (avoids first-load race conditions)\n if (e.data?.type === \"bitpalm-request-context\") {\n sendParentContext();\n }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n widgetBlocked = true;\n launcherReady = false;\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Auto-identify visitor from form submissions on host page ---\n let lastIdentitySignature = \"\";\n let lastIdentitySentAt = 0;\n const handleFormSubmit = (event: Event) => {\n if (optedOut || !autoIdentify || !visitorId) return;\n\n const form = event.target instanceof HTMLFormElement\n ? event.target\n : event.target instanceof Element\n ? event.target.closest(\"form\")\n : null;\n if (!(form instanceof HTMLFormElement)) return;\n\n const formIdentifySetting = (form.getAttribute(\"data-bp-identify\") || form.getAttribute(\"data-bitpalm-identify\") || \"\").toLowerCase();\n if (formIdentifySetting === \"off\" || formIdentifySetting === \"false\" || formIdentifySetting === \"0\") return;\n\n const identity = extractIdentityFromForm(form);\n if (!identity) return;\n\n const signature = [\n form.getAttribute(\"id\") || \"\",\n form.getAttribute(\"name\") || \"\",\n form.getAttribute(\"action\") || \"\",\n identity.email || \"\",\n identity.phone || \"\",\n identity.name || \"\",\n identity.company || \"\",\n ].join(\"|\").toLowerCase();\n\n const now = Date.now();\n if (signature === lastIdentitySignature && now - lastIdentitySentAt < 8000) return;\n lastIdentitySignature = signature;\n lastIdentitySentAt = now;\n\n try {\n const payload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...identity,\n });\n const identifyUrl = `${baseUrl}/api/widget/identify`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(identifyUrl, new Blob([payload], { type: \"application/json\" }));\n } else {\n fetch(identifyUrl, { method: \"POST\", body: payload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch {\n // ignore\n }\n };\n\n if (!optedOut && autoIdentify) {\n d.addEventListener(\"submit\", handleFormSubmit, true);\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n const contextRetryTimers: ReturnType<typeof setTimeout>[] = [];\n sendParentContext = () => {\n let returning = false;\n try {\n returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n } catch {\n returning = false;\n }\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) {\n try { localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\"); } catch { /* ignore */ }\n }\n };\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n sendParentContext();\n [120, 450, 1100].forEach((delay) => {\n const timer = setTimeout(() => sendParentContext(), delay);\n contextRetryTimers.push(timer);\n });\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n hist = h;\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n d.removeEventListener(\"submit\", handleFormSubmit, true);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n contextRetryTimers.forEach((t) => clearTimeout(t));\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget, destroy };\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,IAAA,eAAAC,GAAAH,ICEA,IAAMI,GAAmB,4BACnBC,EAAiB,OACjBC,GAAsB,IAAI,IAAI,CAAC,WAAY,OAAQ,WAAY,QAAS,SAAU,SAAU,QAAS,OAAO,CAAC,EASnH,SAASC,EAAcC,EAAkCC,EAAS,IAAa,CAC7E,OAAKD,EACEA,EAAM,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAGC,CAAM,EADrC,EAErB,CAEA,SAASC,GAAgBF,EAA0C,CACjE,OAAKA,EACE,IAAIA,EAAM,YAAY,EAAE,QAAQ,SAAU,GAAG,EAAE,QAAQ,iBAAkB,GAAG,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,C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EACpB,QAAQ,aAAeC,EACvBzC,EAAa,EACbN,EAAI,OAAO,EACXJ,EAAO,OAAO,CAChB,CAEuD,CACzD,CDnmBA,SAASqE,GAAaC,EAAgD,CACpE,GAAIA,GAAS,KAAM,OACnB,IAAMC,EAAaD,EAAM,KAAK,EAAE,YAAY,EAC5C,GAAI,CAAC,IAAK,OAAQ,MAAO,IAAI,EAAE,SAASC,CAAU,EAAG,MAAO,GAC5D,GAAI,CAAC,IAAK,QAAS,KAAM,KAAK,EAAE,SAASA,CAAU,EAAG,MAAO,EAE/D,CAMA,GAAI,OAAO,SAAa,IAAa,CACnC,IAAMC,EAAS,SAAS,cACxB,GAAIA,GAAQ,QAAQ,KAAM,CACxB,IAAMC,EAAO,IAAM,CACjBC,EAAa,CACX,KAAMF,EAAQ,QAAQ,KACtB,OAAQA,EAAQ,QAAQ,OACxB,QAASA,EAAQ,QAAQ,QACzB,MAAOA,EAAQ,QAAQ,MACvB,OAAQA,EAAQ,QAAQ,OAAS,OAAOA,EAAQ,QAAQ,MAAM,EAAI,OAClE,aAAcH,GAAaG,EAAQ,QAAQ,YAAY,CACzD,CAAC,CACH,EAEI,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBC,CAAI,EAElDA,EAAK,CAET,CACF","names":["src_exports","__export","createWidget","__toCommonJS","DEFAULT_BASE_URL","STORAGE_PREFIX","IGNORED_INPUT_TYPES","normalizeText","value","maxLen","normalizeTokens","includesAny","haystack","needles","needle","isEmail","normalizePhone","trimmed","hasPlus","digits","getExplicitValue","form","selectors","selector","el","extractIdentityFromForm","email","phone","name","firstName","lastName","company","rawEl","explicitField","type","tokens","emailLike","phoneLike","companyLike","firstNameLike","lastNameLike","fullNameLike","normalized","identity","detectLocale","lang","createWidget","options","slug","locale","baseUrl","token","zIndex","autoIdentify","d","iframe","widgetUrl","qs","origin","btn","openWidget","s","bubble","launcherReady","widgetBlocked","removeBubble","sendParentContext","handleMessage","ic","sp","svg","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","lastIdentitySignature","lastIdentitySentAt","handleFormSubmit","event","formIdentifySetting","signature","now","payload","identifyUrl","pageCount","hist","loadedAt","siteStart","contextRetryTimers","returning","delay","timer","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","t","parseBoolean","value","normalized","script","init","createWidget"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/widget.ts"],"sourcesContent":["export { createWidget } from \"./widget\";\nexport type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nimport { createWidget } from \"./widget\";\n\nfunction parseBoolean(value: string | undefined): boolean | undefined {\n if (value == null) return undefined;\n const normalized = value.trim().toLowerCase();\n if ([\"1\", \"true\", \"yes\", \"on\"].includes(normalized)) return true;\n if ([\"0\", \"false\", \"no\", \"off\"].includes(normalized)) return false;\n return undefined;\n}\n\n/**\n * Auto-init from script tag:\n * <script src=\"https://cdn.bitpalm.ae/widget.js\" data-slug=\"my-agent\"></script>\n */\nif (typeof document !== \"undefined\") {\n const script = document.currentScript as HTMLScriptElement | null;\n if (script?.dataset.slug) {\n const init = () => {\n createWidget({\n slug: script!.dataset.slug!,\n locale: script!.dataset.locale,\n baseUrl: script!.dataset.baseUrl,\n token: script!.dataset.token,\n zIndex: script!.dataset.zIndex ? Number(script!.dataset.zIndex) : undefined,\n autoIdentify: parseBoolean(script!.dataset.autoIdentify),\n });\n };\n\n if (document.readyState === \"loading\") {\n document.addEventListener(\"DOMContentLoaded\", init);\n } else {\n init();\n }\n }\n}\n","import type { BitPalmAgentOptions, BitPalmAgentInstance } from \"./types\";\n\nconst DEFAULT_BASE_URL = \"https://agents.bitpalm.ae\";\nconst STORAGE_PREFIX = \"_bp_\";\nconst IGNORED_INPUT_TYPES = new Set([\"password\", \"file\", \"checkbox\", \"radio\", \"submit\", \"button\", \"reset\", \"image\"]);\nconst IDENTITY_DEDUPE_WINDOW_MS = 8_000;\nconst IDENTITY_SIGNATURE_KEY = `${STORAGE_PREFIX}identify_signature`;\nconst IDENTITY_FINGERPRINT_KEY = `${STORAGE_PREFIX}identify_fingerprint`;\nconst IDENTITY_SENT_AT_KEY = `${STORAGE_PREFIX}identify_sent_at`;\n\ntype FormFieldElement = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;\n\ntype IdentityPayload = {\n name?: string;\n email?: string;\n phone?: string;\n company?: string;\n};\n\nfunction normalizeText(value: string | null | undefined, maxLen = 180): string {\n if (!value) return \"\";\n return value.replace(/\\s+/g, \" \").trim().slice(0, maxLen);\n}\n\nfunction normalizeTokens(value: string | null | undefined): string {\n if (!value) return \"\";\n return ` ${value.toLowerCase().replace(/[_-]+/g, \" \").replace(/[^a-z0-9\\s@.]/g, \" \").replace(/\\s+/g, \" \").trim()} `;\n}\n\nfunction includesAny(haystack: string, needles: string[]): boolean {\n for (const needle of needles) {\n if (haystack.includes(needle)) return true;\n }\n return false;\n}\n\nfunction isEmail(value: string): boolean {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]{2,}$/i.test(value);\n}\n\nfunction normalizePhone(value: string): string {\n const trimmed = normalizeText(value, 50);\n if (!trimmed) return \"\";\n const hasPlus = trimmed.startsWith(\"+\");\n const digits = trimmed.replace(/\\D/g, \"\");\n if (digits.length < 6) return \"\";\n return `${hasPlus ? \"+\" : \"\"}${digits.slice(0, 20)}`;\n}\n\nfunction getExplicitValue(form: HTMLFormElement, selectors: string[]): string {\n for (const selector of selectors) {\n const el = form.querySelector<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>(selector);\n const value = normalizeText(el?.value);\n if (value) return value;\n }\n return \"\";\n}\n\nfunction getFieldHint(el: FormFieldElement): string {\n return normalizeText(el.getAttribute(\"data-bp-field\") || el.getAttribute(\"data-bitpalm-field\"), 64)\n .toLowerCase()\n .replace(/[_\\s]+/g, \"-\");\n}\n\nfunction escapeAttrSelectorValue(value: string): string {\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"');\n}\n\nfunction collectElementTokenParts(form: HTMLFormElement, el: FormFieldElement): string[] {\n const parts: string[] = [];\n const pushText = (value: string | null | undefined, maxLen = 140) => {\n const clean = normalizeText(value, maxLen);\n if (clean) parts.push(clean);\n };\n\n pushText(el.name);\n pushText(el.id);\n pushText(el.getAttribute(\"autocomplete\"));\n pushText(el.getAttribute(\"placeholder\"));\n pushText(el.getAttribute(\"aria-label\"));\n pushText(el.getAttribute(\"data-field\"));\n pushText(el.getAttribute(\"data-name\"));\n pushText(el.getAttribute(\"data-label\"));\n pushText(el.getAttribute(\"data-bp-field\"));\n pushText(el.getAttribute(\"data-bitpalm-field\"));\n\n const seenLabels = new Set<string>();\n const pushLabel = (value: string | null | undefined) => {\n const label = normalizeText(value, 200);\n if (!label || seenLabels.has(label)) return;\n seenLabels.add(label);\n parts.push(label);\n };\n\n for (const label of Array.from(el.labels || [])) {\n pushLabel(label.textContent);\n }\n\n if (el.id) {\n const forLabel = form.querySelector(`label[for=\"${escapeAttrSelectorValue(el.id)}\"]`);\n pushLabel(forLabel?.textContent);\n }\n\n const nearestLabel = el.closest(\"label\");\n pushLabel(nearestLabel?.textContent);\n\n const ariaLabelledBy = el.getAttribute(\"aria-labelledby\");\n if (ariaLabelledBy) {\n for (const id of ariaLabelledBy.split(/\\s+/)) {\n if (!id) continue;\n const ref = form.ownerDocument.getElementById(id);\n pushLabel(ref?.textContent);\n }\n }\n\n return parts;\n}\n\nfunction extractIdentityFromForm(form: HTMLFormElement): IdentityPayload | null {\n let email = normalizeText(getExplicitValue(form, [\n \"[data-bp-email]\",\n \"[data-bitpalm-email]\",\n ]), 140).toLowerCase();\n\n let phone = normalizePhone(getExplicitValue(form, [\n \"[data-bp-phone]\",\n \"[data-bitpalm-phone]\",\n ]));\n\n let name = normalizeText(getExplicitValue(form, [\n \"[data-bp-name]\",\n \"[data-bitpalm-name]\",\n \"[data-bp-full-name]\",\n \"[data-bitpalm-full-name]\",\n ]));\n\n let firstName = normalizeText(getExplicitValue(form, [\n \"[data-bp-first-name]\",\n \"[data-bitpalm-first-name]\",\n ]));\n\n let lastName = normalizeText(getExplicitValue(form, [\n \"[data-bp-last-name]\",\n \"[data-bitpalm-last-name]\",\n ]));\n\n let company = normalizeText(getExplicitValue(form, [\n \"[data-bp-company]\",\n \"[data-bitpalm-company]\",\n ]));\n\n for (const rawEl of Array.from(form.elements)) {\n if (!(rawEl instanceof HTMLInputElement || rawEl instanceof HTMLTextAreaElement || rawEl instanceof HTMLSelectElement)) continue;\n if (rawEl.disabled) continue;\n if (rawEl instanceof HTMLInputElement && IGNORED_INPUT_TYPES.has(rawEl.type.toLowerCase())) continue;\n const fieldHint = getFieldHint(rawEl);\n\n const explicitField =\n rawEl.hasAttribute(\"data-bp-email\") ||\n rawEl.hasAttribute(\"data-bitpalm-email\") ||\n rawEl.hasAttribute(\"data-bp-phone\") ||\n rawEl.hasAttribute(\"data-bitpalm-phone\") ||\n rawEl.hasAttribute(\"data-bp-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-name\") ||\n rawEl.hasAttribute(\"data-bp-full-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-full-name\") ||\n rawEl.hasAttribute(\"data-bp-first-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-first-name\") ||\n rawEl.hasAttribute(\"data-bp-last-name\") ||\n rawEl.hasAttribute(\"data-bitpalm-last-name\") ||\n rawEl.hasAttribute(\"data-bp-company\") ||\n rawEl.hasAttribute(\"data-bitpalm-company\") ||\n !!fieldHint;\n\n if (rawEl instanceof HTMLInputElement && rawEl.type.toLowerCase() === \"hidden\" && !explicitField) continue;\n\n const value = normalizeText(rawEl.value);\n if (!value) continue;\n\n const type = rawEl instanceof HTMLInputElement ? rawEl.type.toLowerCase() : \"\";\n const tokens = normalizeTokens(collectElementTokenParts(form, rawEl).join(\" \"));\n\n if (!email && fieldHint === \"email\" && isEmail(value)) {\n email = value.toLowerCase();\n continue;\n }\n if (!phone && (fieldHint === \"phone\" || fieldHint === \"tel\" || fieldHint === \"mobile\" || fieldHint === \"whatsapp\")) {\n const normalized = normalizePhone(value);\n if (normalized) {\n phone = normalized;\n continue;\n }\n }\n if (!company && fieldHint === \"company\") {\n company = normalizeText(value, 160);\n continue;\n }\n if (!firstName && (fieldHint === \"first-name\" || fieldHint === \"firstname\")) {\n firstName = normalizeText(value, 100);\n continue;\n }\n if (!lastName && (fieldHint === \"last-name\" || fieldHint === \"lastname\" || fieldHint === \"surname\")) {\n lastName = normalizeText(value, 100);\n continue;\n }\n if (!name && (fieldHint === \"name\" || fieldHint === \"full-name\" || fieldHint === \"fullname\")) {\n if (!isEmail(value) && !normalizePhone(value)) name = normalizeText(value, 140);\n continue;\n }\n\n const emailLike = type === \"email\" || includesAny(tokens, [\" email \", \" e mail \", \" mail \", \" email adresse \", \" mailadresse \", \" correo \"]);\n const phoneLike = type === \"tel\" || includesAny(tokens, [\" phone \", \" phone number \", \" mobile \", \" tel \", \" telefon \", \" telefonnummer \", \" whatsapp \", \" handy \", \" kontakt \", \" nummer \"]);\n const companyLike = includesAny(tokens, [\" company \", \" company name \", \" firma \", \" firmenname \", \" organization \", \" organisation \", \" business \", \" unternehmen \", \" agency \", \" brokerage \"]);\n const firstNameLike = includesAny(tokens, [\" first name \", \" firstname \", \" given name \", \" givenname \", \" vorname \", \" fname \"]);\n const lastNameLike = includesAny(tokens, [\" last name \", \" lastname \", \" family name \", \" familyname \", \" surname \", \" nachname \", \" lname \"]);\n const fullNameLike = includesAny(tokens, [\" full name \", \" fullname \", \" contact name \", \" name \"]) && !emailLike && !phoneLike;\n\n if (!email && emailLike && isEmail(value)) {\n email = value.toLowerCase();\n continue;\n }\n if (!phone && phoneLike) {\n const normalized = normalizePhone(value);\n if (normalized) {\n phone = normalized;\n continue;\n }\n }\n if (!company && companyLike) {\n company = normalizeText(value, 160);\n continue;\n }\n if (!firstName && firstNameLike) {\n firstName = normalizeText(value, 100);\n continue;\n }\n if (!lastName && lastNameLike) {\n lastName = normalizeText(value, 100);\n continue;\n }\n if (!name && fullNameLike && !isEmail(value) && !normalizePhone(value)) {\n name = normalizeText(value, 140);\n continue;\n }\n\n if (!email && isEmail(value)) {\n email = value.toLowerCase();\n }\n }\n\n if (name && (isEmail(name) || normalizePhone(name))) {\n name = \"\";\n }\n if (company && (isEmail(company) || normalizePhone(company))) {\n company = \"\";\n }\n\n if (!name) {\n name = normalizeText([firstName, lastName].filter(Boolean).join(\" \"), 140);\n }\n\n if (name && email && name.toLowerCase() === email.toLowerCase()) {\n name = \"\";\n }\n\n const hasContactSignal = !!(email || phone);\n const hasStrongProfileSignal = !!(name && company);\n if (!hasContactSignal && !hasStrongProfileSignal) {\n return null;\n }\n\n const identity: IdentityPayload = {\n ...(name ? { name } : {}),\n ...(email ? { email } : {}),\n ...(phone ? { phone } : {}),\n ...(company ? { company } : {}),\n };\n\n return Object.keys(identity).length > 0 ? identity : null;\n}\n\nfunction detectLocale(): string {\n if (typeof document !== \"undefined\") {\n const lang = document.documentElement.lang;\n if (lang) return lang.slice(0, 2).toLowerCase();\n }\n return \"en\";\n}\n\nfunction isMobileWidgetDevice(): boolean {\n if (typeof window === \"undefined\") return false;\n const userAgent = typeof navigator !== \"undefined\" ? navigator.userAgent : \"\";\n const isMobileUa = /Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(userAgent);\n if (isMobileUa) return true;\n\n const coarsePointer = window.matchMedia(\"(pointer: coarse)\").matches;\n const noHover = window.matchMedia(\"(hover: none)\").matches;\n const minScreenSide = Math.min(\n window.screen?.width || window.innerWidth,\n window.screen?.height || window.innerHeight,\n );\n return coarsePointer && noHover && minScreenSide <= 900;\n}\n\nexport function createWidget(options: BitPalmAgentOptions): BitPalmAgentInstance {\n const {\n slug,\n locale = detectLocale(),\n baseUrl = DEFAULT_BASE_URL,\n token,\n zIndex = 9999,\n autoIdentify = true,\n } = options;\n\n const d = document;\n\n // --- Iframe ---\n const iframe = d.createElement(\"iframe\");\n const widgetUrl = `${baseUrl}/t/${slug}/widget`;\n const qs = new URLSearchParams({ locale });\n if (token) qs.set(\"token\", token);\n iframe.src = `${widgetUrl}?${qs.toString()}`;\n iframe.allow = \"clipboard-write\";\n iframe.setAttribute(\"allowtransparency\", \"true\");\n iframe.style.cssText = `position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${zIndex};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`;\n d.body.appendChild(iframe);\n\n const origin = new URL(iframe.src).origin;\n\n // --- Native launcher button ---\n const btn = d.createElement(\"div\");\n btn.setAttribute(\"role\", \"button\");\n btn.setAttribute(\"aria-label\", \"Chat\");\n btn.style.cssText = `position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${zIndex - 1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`;\n btn.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"black\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n btn.onmouseenter = () => { btn.style.transform = \"scale(1.1)\"; };\n btn.onmouseleave = () => { btn.style.transform = \"scale(1)\"; };\n btn.onclick = () => openWidget();\n d.body.appendChild(btn);\n\n // --- Fade animation for trigger bubbles ---\n if (!d.getElementById(\"_bp_fade\")) {\n const s = d.createElement(\"style\");\n s.id = \"_bp_fade\";\n s.textContent = \"@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}\";\n d.head.appendChild(s);\n }\n\n // --- Trigger bubble ---\n let bubble: HTMLDivElement | null = null;\n let launcherReady = false;\n let widgetBlocked = false;\n const removeBubble = () => {\n if (bubble) { bubble.remove(); bubble = null; }\n };\n let sendParentContext = () => {};\n\n // --- postMessage handler ---\n const handleMessage = (e: MessageEvent) => {\n if (e.origin !== origin) return;\n\n // Widget config (colors, icon)\n if (e.data?.type === \"bitpalm-widget-config\") {\n widgetBlocked = false;\n launcherReady = true;\n if (iframe.style.display === \"none\") iframe.style.display = \"\";\n if (e.data.primaryColor) {\n btn.style.background = e.data.primaryColor;\n btn.style.boxShadow = e.data.chatShadow === \"none\" ? \"none\" : `0 0 15px ${e.data.primaryColor}50`;\n }\n const ic = e.data.chatButtonIconColor || \"black\";\n if (e.data.chatButtonIconSvg) {\n btn.innerHTML = \"\";\n const sp = d.createElement(\"span\");\n sp.style.cssText = `display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${ic}`;\n const parser = new DOMParser();\n const doc = parser.parseFromString(e.data.chatButtonIconSvg, \"image/svg+xml\");\n const svg = doc.querySelector(\"svg\");\n if (svg) {\n // Remove dangerous elements and attributes\n svg.querySelectorAll(\"script,foreignObject\").forEach(el => el.remove());\n svg.querySelectorAll(\"*\").forEach(el => {\n for (const attr of [...el.attributes]) {\n if (attr.name.startsWith(\"on\") || (attr.value && attr.value.includes(\"javascript:\"))) {\n el.removeAttribute(attr.name);\n }\n }\n });\n svg.setAttribute(\"width\", \"24\");\n svg.setAttribute(\"height\", \"24\");\n svg.style.display = \"block\";\n sp.appendChild(svg);\n } else {\n // Fallback: use default icon\n sp.innerHTML = '<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-linecap=\"round\" stroke-linejoin=\"round\"><path d=\"M7.9 20A9 9 0 1 0 4 16.1L2 22Z\"/></svg>';\n }\n btn.appendChild(sp);\n } else {\n const sv = btn.querySelector(\"svg\");\n if (sv) (sv as SVGElement).style.stroke = ic;\n }\n btn.style.display = \"flex\";\n // Fade in after styles are applied\n requestAnimationFrame(() => { btn.style.opacity = \"1\"; });\n }\n\n // Resize — use full viewport on mobile\n if (e.data?.type === \"bitpalm-widget-resize\") {\n const isOpen = e.data.width > 0;\n const mobile = isMobileWidgetDevice();\n if (isOpen) {\n iframe.style.width = mobile ? `${window.innerWidth}px` : `${e.data.width}px`;\n iframe.style.height = mobile ? `${window.innerHeight}px` : `${e.data.height}px`;\n if (mobile) { iframe.style.left = \"0\"; iframe.style.top = \"0\"; }\n iframe.style.opacity = \"1\";\n iframe.style.pointerEvents = \"auto\";\n } else {\n iframe.style.width = \"1px\";\n iframe.style.height = \"1px\";\n iframe.style.left = \"\";\n iframe.style.top = \"\";\n iframe.style.opacity = \"0\";\n iframe.style.pointerEvents = \"none\";\n }\n btn.style.display = isOpen ? \"none\" : \"flex\";\n }\n\n // Trigger bubble show\n if (e.data?.type === \"bitpalm-trigger-show\") {\n if (widgetBlocked || !launcherReady) return;\n removeBubble();\n bubble = d.createElement(\"div\");\n bubble.style.cssText = `position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${zIndex - 1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;\n const msg = (e.data.message || \"\").replace(/</g, \"&lt;\");\n bubble.innerHTML = `<p style=\"font-size:14px;color:#1f2937;margin:0;\">${msg}</p><div style=\"position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;\"></div>`;\n const close = d.createElement(\"button\");\n close.style.cssText = \"position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;\";\n close.innerHTML = \"&#10005;\";\n close.onclick = (ev) => { ev.stopPropagation(); removeBubble(); iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-dismiss\" }, \"*\"); };\n bubble.onclick = () => { removeBubble(); btn.style.display = \"none\"; iframe.contentWindow?.postMessage({ type: \"bitpalm-trigger-engaged\" }, \"*\"); };\n bubble.appendChild(close);\n d.body.appendChild(bubble);\n }\n\n // Trigger bubble hide\n if (e.data?.type === \"bitpalm-trigger-hide\") { removeBubble(); }\n\n // Iframe requests latest parent context (avoids first-load race conditions)\n if (e.data?.type === \"bitpalm-request-context\") {\n sendParentContext();\n }\n\n // Widget blocked (excluded path or access denied) — hide button & iframe\n if (e.data?.type === \"bitpalm-widget-blocked\") {\n widgetBlocked = true;\n launcherReady = false;\n btn.style.display = \"none\";\n removeBubble();\n iframe.style.display = \"none\";\n }\n };\n window.addEventListener(\"message\", handleMessage);\n\n // --- Privacy opt-out check ---\n let optedOut = false;\n try { optedOut = localStorage.getItem(`${STORAGE_PREFIX}optout`) === \"1\"; } catch { /* ignore */ }\n\n // --- Persistent Visitor ID (skip if opted out) ---\n const VID_KEY = `${STORAGE_PREFIX}vid`;\n let visitorId = \"\";\n if (!optedOut) {\n try { visitorId = localStorage.getItem(VID_KEY) || \"\"; } catch { /* ignore */ }\n if (!visitorId) {\n // Fallback: try reading from cookie\n const match = d.cookie.match(new RegExp(`(?:^|; )${VID_KEY}=([^;]+)`));\n visitorId = match ? decodeURIComponent(match[1]) : \"\";\n }\n if (!visitorId) {\n visitorId = crypto.randomUUID ? crypto.randomUUID() : (`${Date.now()}-${Math.random().toString(36).slice(2, 11)}`);\n }\n // Persist in both localStorage and cookie (cookie survives Safari ITP clearing localStorage)\n try { localStorage.setItem(VID_KEY, visitorId); } catch { /* ignore */ }\n try {\n const maxAge = 365 * 24 * 60 * 60; // 1 year\n d.cookie = `${VID_KEY}=${encodeURIComponent(visitorId)};path=/;max-age=${maxAge};SameSite=Lax`;\n } catch { /* ignore */ }\n }\n\n // --- Visitor beacon: track page view even without chat (skip if opted out) ---\n if (!optedOut) {\n try {\n const utmParams = new URLSearchParams(location.search);\n const utm: Record<string, string> = {};\n for (const key of [\"utm_source\", \"utm_medium\", \"utm_campaign\", \"utm_term\", \"utm_content\"]) {\n const val = utmParams.get(key);\n if (val) utm[key] = val;\n }\n const beaconPayload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...(Object.keys(utm).length > 0 ? { utm } : {}),\n });\n const beaconUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(beaconUrl, new Blob([beaconPayload], { type: \"application/json\" }));\n } else {\n fetch(beaconUrl, { method: \"POST\", body: beaconPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n\n // --- Auto-identify visitor from form submissions on host page ---\n let lastIdentitySignature = \"\";\n let lastIdentityFingerprint = \"\";\n let lastIdentitySentAt = 0;\n try {\n lastIdentitySignature = sessionStorage.getItem(IDENTITY_SIGNATURE_KEY) || \"\";\n lastIdentityFingerprint = sessionStorage.getItem(IDENTITY_FINGERPRINT_KEY) || \"\";\n const storedAt = parseInt(sessionStorage.getItem(IDENTITY_SENT_AT_KEY) || \"0\", 10);\n if (Number.isFinite(storedAt) && storedAt > 0) {\n lastIdentitySentAt = storedAt;\n }\n } catch {\n // ignore\n }\n\n const handleFormSubmit = (event: Event) => {\n if (optedOut || !autoIdentify || !visitorId) return;\n\n const form = event.target instanceof HTMLFormElement\n ? event.target\n : event.target instanceof Element\n ? event.target.closest(\"form\")\n : null;\n if (!(form instanceof HTMLFormElement)) return;\n\n const formIdentifySetting = (form.getAttribute(\"data-bp-identify\") || form.getAttribute(\"data-bitpalm-identify\") || \"\").toLowerCase();\n if (formIdentifySetting === \"off\" || formIdentifySetting === \"false\" || formIdentifySetting === \"0\") return;\n\n const identity = extractIdentityFromForm(form);\n if (!identity) return;\n\n const identityFingerprint = [\n identity.email || \"\",\n identity.phone || \"\",\n identity.name || \"\",\n identity.company || \"\",\n ].join(\"|\").toLowerCase();\n\n const signature = [\n form.getAttribute(\"id\") || \"\",\n form.getAttribute(\"name\") || \"\",\n form.getAttribute(\"action\") || \"\",\n identityFingerprint,\n ].join(\"|\").toLowerCase();\n\n const now = Date.now();\n const insideDedupWindow = now - lastIdentitySentAt < IDENTITY_DEDUPE_WINDOW_MS;\n if (insideDedupWindow && (signature === lastIdentitySignature || identityFingerprint === lastIdentityFingerprint)) {\n return;\n }\n\n lastIdentitySignature = signature;\n lastIdentityFingerprint = identityFingerprint;\n lastIdentitySentAt = now;\n try {\n sessionStorage.setItem(IDENTITY_SIGNATURE_KEY, signature);\n sessionStorage.setItem(IDENTITY_FINGERPRINT_KEY, identityFingerprint);\n sessionStorage.setItem(IDENTITY_SENT_AT_KEY, String(now));\n } catch {\n // ignore\n }\n\n try {\n const payload = JSON.stringify({\n tenant_slug: slug,\n visitor_id: visitorId,\n url: location.href,\n referrer: d.referrer || undefined,\n ...identity,\n });\n const identifyUrl = `${baseUrl}/api/widget/identify`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(identifyUrl, new Blob([payload], { type: \"application/json\" }));\n } else {\n fetch(identifyUrl, { method: \"POST\", body: payload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch {\n // ignore\n }\n };\n\n if (!optedOut && autoIdentify) {\n d.addEventListener(\"submit\", handleFormSubmit, true);\n }\n\n // --- Visitor Intelligence: page counter + history ---\n let pageCount = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}pages`) || \"0\") + 1;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n\n let hist: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n hist.push(location.href);\n if (hist.length > 20) hist = hist.slice(-20);\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(hist));\n\n const loadedAt = Date.now();\n let siteStart = parseInt(sessionStorage.getItem(`${STORAGE_PREFIX}site_start`) || \"0\");\n if (!siteStart) {\n siteStart = loadedAt;\n sessionStorage.setItem(`${STORAGE_PREFIX}site_start`, String(siteStart));\n }\n\n const contextRetryTimers: ReturnType<typeof setTimeout>[] = [];\n sendParentContext = () => {\n let returning = false;\n try {\n returning = !!localStorage.getItem(`${STORAGE_PREFIX}visited`);\n } catch {\n returning = false;\n }\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-parent-context\",\n url: location.href,\n title: d.title,\n returning,\n pageCount,\n pageHistory: hist,\n loadedAt,\n siteStart,\n locale,\n visitorId: optedOut ? \"\" : visitorId,\n }, \"*\");\n if (!returning && !optedOut) {\n try { localStorage.setItem(`${STORAGE_PREFIX}visited`, \"1\"); } catch { /* ignore */ }\n }\n };\n\n // --- Send parent context on iframe load ---\n iframe.addEventListener(\"load\", () => {\n sendParentContext();\n [120, 450, 1100].forEach((delay) => {\n const timer = setTimeout(() => sendParentContext(), delay);\n contextRetryTimers.push(timer);\n });\n });\n\n // --- SPA navigation detection ---\n const origPush = history.pushState.bind(history);\n const origReplace = history.replaceState.bind(history);\n\n const onNav = () => {\n pageCount++;\n sessionStorage.setItem(`${STORAGE_PREFIX}pages`, String(pageCount));\n const h: string[] = JSON.parse(sessionStorage.getItem(`${STORAGE_PREFIX}hist`) || \"[]\");\n h.push(location.href);\n if (h.length > 20) h.splice(0, h.length - 20);\n hist = h;\n sessionStorage.setItem(`${STORAGE_PREFIX}hist`, JSON.stringify(h));\n iframe.contentWindow?.postMessage({\n type: \"bitpalm-page-change\",\n url: location.href,\n title: d.title,\n pageCount,\n pageHistory: h,\n loadedAt: Date.now(),\n }, \"*\");\n // Track page view for visitor (skip if opted out)\n if (!optedOut) {\n try {\n const navPayload = JSON.stringify({ tenant_slug: slug, visitor_id: visitorId, url: location.href });\n const navUrl = `${baseUrl}/api/widget/impression`;\n if (typeof navigator.sendBeacon === \"function\") {\n navigator.sendBeacon(navUrl, new Blob([navPayload], { type: \"application/json\" }));\n } else {\n fetch(navUrl, { method: \"POST\", body: navPayload, headers: { \"Content-Type\": \"application/json\" }, keepalive: true }).catch(() => {});\n }\n } catch { /* ignore */ }\n }\n };\n\n history.pushState = function (...args: Parameters<typeof history.pushState>) {\n origPush(...args);\n onNav();\n };\n history.replaceState = function (...args: Parameters<typeof history.replaceState>) {\n origReplace(...args);\n onNav();\n };\n window.addEventListener(\"popstate\", onNav);\n\n // --- Scroll depth tracking ---\n let lastScrollDepth = -1;\n let scrollTimeout: ReturnType<typeof setTimeout>;\n const handleScroll = () => {\n clearTimeout(scrollTimeout);\n scrollTimeout = setTimeout(() => {\n const total = Math.max(d.documentElement.scrollHeight, d.body.scrollHeight) - window.innerHeight;\n const pct = total > 0 ? Math.round(window.scrollY / total * 100) : 100;\n if (pct !== lastScrollDepth) {\n lastScrollDepth = pct;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-scroll-depth\", percent: pct }, \"*\");\n }\n }, 500);\n };\n window.addEventListener(\"scroll\", handleScroll, { passive: true });\n\n // --- Exit intent ---\n const handleMouseOut = (e: MouseEvent) => {\n if (e.clientY <= 0) {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-exit-intent\" }, \"*\");\n }\n };\n d.addEventListener(\"mouseout\", handleMouseOut);\n\n // --- Inactivity detection (15s) ---\n let idleTimer: ReturnType<typeof setTimeout>;\n let idleFired = false;\n const resetIdle = () => {\n clearTimeout(idleTimer);\n if (idleFired) return;\n idleTimer = setTimeout(() => {\n idleFired = true;\n iframe.contentWindow?.postMessage({ type: \"bitpalm-inactivity\" }, \"*\");\n }, 15_000);\n };\n const idleEvents = [\"mousemove\", \"keydown\", \"scroll\", \"touchstart\"] as const;\n idleEvents.forEach((ev) => d.addEventListener(ev, resetIdle, { passive: true }));\n resetIdle();\n\n // --- Public API ---\n const openWidget = () => {\n btn.style.display = \"none\";\n removeBubble();\n // Primary: postMessage\n iframe.contentWindow?.postMessage({ type: \"bitpalm-open\" }, \"*\");\n // Fallback for mobile: trigger hashchange inside iframe (no reload)\n const base = iframe.src.split(\"#\")[0];\n iframe.src = `${base}#bp-open-${Date.now()}`;\n };\n\n const closeWidget = () => {\n iframe.contentWindow?.postMessage({ type: \"bitpalm-close\" }, \"*\");\n };\n\n const destroy = () => {\n window.removeEventListener(\"message\", handleMessage);\n window.removeEventListener(\"scroll\", handleScroll);\n window.removeEventListener(\"popstate\", onNav);\n d.removeEventListener(\"mouseout\", handleMouseOut);\n d.removeEventListener(\"submit\", handleFormSubmit, true);\n idleEvents.forEach((ev) => d.removeEventListener(ev, resetIdle));\n clearTimeout(scrollTimeout);\n clearTimeout(idleTimer);\n contextRetryTimers.forEach((t) => clearTimeout(t));\n history.pushState = origPush;\n history.replaceState = origReplace;\n removeBubble();\n btn.remove();\n iframe.remove();\n };\n\n return { open: openWidget, close: closeWidget, destroy };\n}\n"],"mappings":"mbAAA,IAAAA,GAAA,GAAAC,GAAAD,GAAA,kBAAAE,IAAA,eAAAC,GAAAH,ICEA,IAAMI,GAAmB,4BACnBC,EAAiB,OACjBC,GAAsB,IAAI,IAAI,CAAC,WAAY,OAAQ,WAAY,QAAS,SAAU,SAAU,QAAS,OAAO,CAAC,EAC7GC,GAA4B,IAC5BC,GAAyB,GAAGH,CAAc,qBAC1CI,GAA2B,GAAGJ,CAAc,uBAC5CK,GAAuB,GAAGL,CAAc,mBAW9C,SAASM,EAAcC,EAAkCC,EAAS,IAAa,CAC7E,OAAKD,EACEA,EAAM,QAAQ,OAAQ,GAAG,EAAE,KAAK,EAAE,MAAM,EAAGC,CAAM,EADrC,EAErB,CAEA,SAASC,GAAgBF,EAA0C,CACjE,OAAKA,EACE,IAAIA,EAAM,YAAY,EAAE,QAAQ,SAAU,GAAG,EAAE,QAAQ,iBAAkB,GAAG,EAAE,QAAQ,OAAQ,GAAG,EAAE,KAAK,CAAC,IAD7F,EAErB,CAEA,SAASG,EAAYC,EAAkBC,EAA4B,CACjE,QAAWC,KAAUD,EACnB,GAAID,EAAS,SAASE,CAAM,EAAG,MAAO,GAExC,MAAO,EACT,CAEA,SAASC,EAAQP,EAAwB,CACvC,MAAO,iCAAiC,KAA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ACzB,MAAOA,EAAQ,QAAQ,MACvB,OAAQA,EAAQ,QAAQ,OAAS,OAAOA,EAAQ,QAAQ,MAAM,EAAI,OAClE,aAAcH,GAAaG,EAAQ,QAAQ,YAAY,CACzD,CAAC,CACH,EAEI,SAAS,aAAe,UAC1B,SAAS,iBAAiB,mBAAoBC,CAAI,EAElDA,EAAK,CAET,CACF","names":["src_exports","__export","createWidget","__toCommonJS","DEFAULT_BASE_URL","STORAGE_PREFIX","IGNORED_INPUT_TYPES","IDENTITY_DEDUPE_WINDOW_MS","IDENTITY_SIGNATURE_KEY","IDENTITY_FINGERPRINT_KEY","IDENTITY_SENT_AT_KEY","normalizeText","value","maxLen","normalizeTokens","includesAny","haystack","needles","needle","isEmail","normalizePhone","trimmed","hasPlus","digits","getExplicitValue","form","selectors","selector","el","getFieldHint","escapeAttrSelectorValue","collectElementTokenParts","parts","pushText","clean","seenLabels","pushLabel","label","forLabel","nearestLabel","ariaLabelledBy","id","ref","extractIdentityFromForm","email","phone","name","firstName","lastName","company","rawEl","fieldHint","explicitField","type","tokens","normalized","emailLike","phoneLike","companyLike","firstNameLike","lastNameLike","fullNameLike","identity","detectLocale","lang","isMobileWidgetDevice","userAgent","coarsePointer","noHover","minScreenSide","createWidget","options","slug","locale","baseUrl","token","zIndex","autoIdentify","d","iframe","widgetUrl","qs","origin","btn","openWidget","s","bubble","launcherReady","widgetBlocked","removeBubble","sendParentContext","handleMessage","e","ic","sp","svg","attr","sv","isOpen","mobile","msg","close","ev","optedOut","VID_KEY","visitorId","match","utmParams","utm","key","val","beaconPayload","beaconUrl","lastIdentitySignature","lastIdentityFingerprint","lastIdentitySentAt","storedAt","handleFormSubmit","event","formIdentifySetting","identityFingerprint","signature","now","payload","identifyUrl","pageCount","hist","loadedAt","siteStart","contextRetryTimers","returning","delay","timer","origPush","origReplace","onNav","h","navPayload","navUrl","args","lastScrollDepth","scrollTimeout","handleScroll","total","pct","handleMouseOut","idleTimer","idleFired","resetIdle","idleEvents","base","parseBoolean","value","normalized","script","init","createWidget"]}
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var at="https://agents.bitpalm.ae",m="_bp_",ot=new Set(["password","file","checkbox","radio","submit","button","reset","image"]);function u(n,s=180){return n?n.replace(/\s+/g," ").trim().slice(0,s):""}function it(n){return n?` ${n.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function T(n,s){for(let d of s)if(n.includes(d))return!0;return!1}function R(n){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(n)}function N(n){let s=u(n,50);if(!s)return"";let d=s.startsWith("+"),l=s.replace(/\D/g,"");return l.length<6?"":`${d?"+":""}${l.slice(0,20)}`}function $(n,s){for(let d of s){let l=n.querySelector(d),b=u(l?.value);if(b)return b}return""}function st(n){let s=u($(n,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),d=N($(n,["[data-bp-phone]","[data-bitpalm-phone]"])),l=u($(n,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),b=u($(n,["[data-bp-first-name]","[data-bitpalm-first-name]"])),x=u($(n,["[data-bp-last-name]","[data-bitpalm-last-name]"])),v=u($(n,["[data-bp-company]","[data-bitpalm-company]"]));for(let t of Array.from(n.elements)){if(!(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)||t.disabled||t instanceof HTMLInputElement&&ot.has(t.type.toLowerCase()))continue;let U=t.hasAttribute("data-bp-email")||t.hasAttribute("data-bitpalm-email")||t.hasAttribute("data-bp-phone")||t.hasAttribute("data-bitpalm-phone")||t.hasAttribute("data-bp-name")||t.hasAttribute("data-bitpalm-name")||t.hasAttribute("data-bp-full-name")||t.hasAttribute("data-bitpalm-full-name")||t.hasAttribute("data-bp-first-name")||t.hasAttribute("data-bitpalm-first-name")||t.hasAttribute("data-bp-last-name")||t.hasAttribute("data-bitpalm-last-name")||t.hasAttribute("data-bp-company")||t.hasAttribute("data-bitpalm-company");if(t instanceof HTMLInputElement&&t.type.toLowerCase()==="hidden"&&!U)continue;let c=u(t.value);if(!c)continue;let _=t instanceof HTMLInputElement?t.type.toLowerCase():"",a=it([t.name,t.id,t.getAttribute("autocomplete"),t.getAttribute("placeholder"),t.getAttribute("aria-label"),t.getAttribute("data-field"),t.getAttribute("data-name")].filter(Boolean).join(" ")),f=_==="email"||T(a,[" email "," e mail "," mail "," correo "]),A=_==="tel"||T(a,[" phone "," mobile "," tel "," whatsapp "," handy "," telefon "," kontakt "]),M=T(a,[" company "," firma "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),w=T(a,[" first name "," firstname "," given name "," given name "," givenname "," vorname "]),I=T(a,[" last name "," lastname "," family name "," familyname "," surname "," nachname "]),P=T(a,[" full name "," fullname "," contact name "," name "])&&!f&&!A;if(!s&&f&&R(c)){s=c.toLowerCase();continue}if(!d&&A){let h=N(c);if(h){d=h;continue}}if(!v&&M){v=u(c,160);continue}if(!b&&w){b=u(c,100);continue}if(!x&&I){x=u(c,100);continue}if(!l&&P&&!R(c)&&!N(c)){l=u(c,140);continue}!s&&R(c)&&T(a,[" mail "," email "," e mail "])&&(s=c.toLowerCase())}l||(l=u([b,x].filter(Boolean).join(" "),140));let o={...l?{name:l}:{},...s?{email:s}:{},...d?{phone:d}:{},...v?{company:v}:{}};return Object.keys(o).length>0?o:null}function rt(){if(typeof document<"u"){let n=document.documentElement.lang;if(n)return n.slice(0,2).toLowerCase()}return"en"}function D(n){let{slug:s,locale:d=rt(),baseUrl:l=at,token:b,zIndex:x=9999,autoIdentify:v=!0}=n,o=document,t=o.createElement("iframe"),U=`${l}/t/${s}/widget`,c=new URLSearchParams({locale:d});b&&c.set("token",b),t.src=`${U}?${c.toString()}`,t.allow="clipboard-write",t.setAttribute("allowtransparency","true"),t.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${x};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,o.body.appendChild(t);let _=new URL(t.src).origin,a=o.createElement("div");if(a.setAttribute("role","button"),a.setAttribute("aria-label","Chat"),a.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${x-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,a.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',a.onmouseenter=()=>{a.style.transform="scale(1.1)"},a.onmouseleave=()=>{a.style.transform="scale(1)"},a.onclick=()=>nt(),o.body.appendChild(a),!o.getElementById("_bp_fade")){let e=o.createElement("style");e.id="_bp_fade",e.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",o.head.appendChild(e)}let f=null,A=!1,M=!1,w=()=>{f&&(f.remove(),f=null)},I=()=>{},P=e=>{if(e.origin===_){if(e.data?.type==="bitpalm-widget-config"){M=!1,A=!0,t.style.display==="none"&&(t.style.display=""),e.data.primaryColor&&(a.style.background=e.data.primaryColor,a.style.boxShadow=e.data.chatShadow==="none"?"none":`0 0 15px ${e.data.primaryColor}50`);let i=e.data.chatButtonIconColor||"black";if(e.data.chatButtonIconSvg){a.innerHTML="";let r=o.createElement("span");r.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${i}`;let p=new DOMParser().parseFromString(e.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");p?(p.querySelectorAll("script,foreignObject").forEach(E=>E.remove()),p.querySelectorAll("*").forEach(E=>{for(let L of[...E.attributes])(L.name.startsWith("on")||L.value&&L.value.includes("javascript:"))&&E.removeAttribute(L.name)}),p.setAttribute("width","24"),p.setAttribute("height","24"),p.style.display="block",r.appendChild(p)):r.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',a.appendChild(r)}else{let r=a.querySelector("svg");r&&(r.style.stroke=i)}a.style.display="flex",requestAnimationFrame(()=>{a.style.opacity="1"})}if(e.data?.type==="bitpalm-widget-resize"){let i=e.data.width>0,r=window.innerWidth<=640;i?(t.style.width=r?`${window.innerWidth}px`:`${e.data.width}px`,t.style.height=r?`${window.innerHeight}px`:`${e.data.height}px`,r&&(t.style.left="0",t.style.top="0"),t.style.opacity="1",t.style.pointerEvents="auto"):(t.style.width="1px",t.style.height="1px",t.style.left="",t.style.top="",t.style.opacity="0",t.style.pointerEvents="none"),a.style.display=i?"none":"flex"}if(e.data?.type==="bitpalm-trigger-show"){if(M||!A)return;w(),f=o.createElement("div"),f.style.cssText=`position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${x-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let i=(e.data.message||"").replace(/</g,"&lt;");f.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${i}</p><div style="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;"></div>`;let r=o.createElement("button");r.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",r.innerHTML="&#10005;",r.onclick=y=>{y.stopPropagation(),w(),t.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},f.onclick=()=>{w(),a.style.display="none",t.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},f.appendChild(r),o.body.appendChild(f)}e.data?.type==="bitpalm-trigger-hide"&&w(),e.data?.type==="bitpalm-request-context"&&I(),e.data?.type==="bitpalm-widget-blocked"&&(M=!0,A=!1,a.style.display="none",w(),t.style.display="none")}};window.addEventListener("message",P);let h=!1;try{h=localStorage.getItem(`${m}optout`)==="1"}catch{}let B=`${m}vid`,g="";if(!h){try{g=localStorage.getItem(B)||""}catch{}if(!g){let e=o.cookie.match(new RegExp(`(?:^|; )${B}=([^;]+)`));g=e?decodeURIComponent(e[1]):""}g||(g=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(B,g)}catch{}try{o.cookie=`${B}=${encodeURIComponent(g)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!h)try{let e=new URLSearchParams(location.search),i={};for(let k of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let p=e.get(k);p&&(i[k]=p)}let r=JSON.stringify({tenant_slug:s,visitor_id:g,url:location.href,referrer:o.referrer||void 0,...Object.keys(i).length>0?{utm:i}:{}}),y=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(y,new Blob([r],{type:"application/json"})):fetch(y,{method:"POST",body:r,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let F="",q=0,J=e=>{if(h||!v||!g)return;let i=e.target instanceof HTMLFormElement?e.target:e.target instanceof Element?e.target.closest("form"):null;if(!(i instanceof HTMLFormElement))return;let r=(i.getAttribute("data-bp-identify")||i.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(r==="off"||r==="false"||r==="0")return;let y=st(i);if(!y)return;let k=[i.getAttribute("id")||"",i.getAttribute("name")||"",i.getAttribute("action")||"",y.email||"",y.phone||"",y.name||"",y.company||""].join("|").toLowerCase(),p=Date.now();if(!(k===F&&p-q<8e3)){F=k,q=p;try{let E=JSON.stringify({tenant_slug:s,visitor_id:g,url:location.href,referrer:o.referrer||void 0,...y}),L=`${l}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(L,new Blob([E],{type:"application/json"})):fetch(L,{method:"POST",body:E,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!h&&v&&o.addEventListener("submit",J,!0);let C=parseInt(sessionStorage.getItem(`${m}pages`)||"0")+1;sessionStorage.setItem(`${m}pages`,String(C));let S=JSON.parse(sessionStorage.getItem(`${m}hist`)||"[]");S.push(location.href),S.length>20&&(S=S.slice(-20)),sessionStorage.setItem(`${m}hist`,JSON.stringify(S));let Y=Date.now(),H=parseInt(sessionStorage.getItem(`${m}site_start`)||"0");H||(H=Y,sessionStorage.setItem(`${m}site_start`,String(H)));let G=[];I=()=>{let e=!1;try{e=!!localStorage.getItem(`${m}visited`)}catch{e=!1}if(t.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:o.title,returning:e,pageCount:C,pageHistory:S,loadedAt:Y,siteStart:H,locale:d,visitorId:h?"":g},"*"),!e&&!h)try{localStorage.setItem(`${m}visited`,"1")}catch{}},t.addEventListener("load",()=>{I(),[120,450,1100].forEach(e=>{let i=setTimeout(()=>I(),e);G.push(i)})});let V=history.pushState.bind(history),Z=history.replaceState.bind(history),O=()=>{C++,sessionStorage.setItem(`${m}pages`,String(C));let e=JSON.parse(sessionStorage.getItem(`${m}hist`)||"[]");if(e.push(location.href),e.length>20&&e.splice(0,e.length-20),S=e,sessionStorage.setItem(`${m}hist`,JSON.stringify(e)),t.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:o.title,pageCount:C,pageHistory:e,loadedAt:Date.now()},"*"),!h)try{let i=JSON.stringify({tenant_slug:s,visitor_id:g,url:location.href}),r=`${l}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(r,new Blob([i],{type:"application/json"})):fetch(r,{method:"POST",body:i,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...e){V(...e),O()},history.replaceState=function(...e){Z(...e),O()},window.addEventListener("popstate",O);let K=-1,W,X=()=>{clearTimeout(W),W=setTimeout(()=>{let e=Math.max(o.documentElement.scrollHeight,o.body.scrollHeight)-window.innerHeight,i=e>0?Math.round(window.scrollY/e*100):100;i!==K&&(K=i,t.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:i},"*"))},500)};window.addEventListener("scroll",X,{passive:!0});let Q=e=>{e.clientY<=0&&t.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};o.addEventListener("mouseout",Q);let j,tt=!1,z=()=>{clearTimeout(j),!tt&&(j=setTimeout(()=>{tt=!0,t.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},et=["mousemove","keydown","scroll","touchstart"];et.forEach(e=>o.addEventListener(e,z,{passive:!0})),z();let nt=()=>{a.style.display="none",w(),t.contentWindow?.postMessage({type:"bitpalm-open"},"*");let e=t.src.split("#")[0];t.src=`${e}#bp-open-${Date.now()}`};return{open:nt,close:()=>{t.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",P),window.removeEventListener("scroll",X),window.removeEventListener("popstate",O),o.removeEventListener("mouseout",Q),o.removeEventListener("submit",J,!0),et.forEach(e=>o.removeEventListener(e,z)),clearTimeout(W),clearTimeout(j),G.forEach(e=>clearTimeout(e)),history.pushState=V,history.replaceState=Z,w(),a.remove(),t.remove()}}}function lt(n){if(n==null)return;let s=n.trim().toLowerCase();if(["1","true","yes","on"].includes(s))return!0;if(["0","false","no","off"].includes(s))return!1}if(typeof document<"u"){let n=document.currentScript;if(n?.dataset.slug){let s=()=>{D({slug:n.dataset.slug,locale:n.dataset.locale,baseUrl:n.dataset.baseUrl,token:n.dataset.token,zIndex:n.dataset.zIndex?Number(n.dataset.zIndex):void 0,autoIdentify:lt(n.dataset.autoIdentify)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",s):s()}}export{D as createWidget};
1
+ var ct="https://agents.bitpalm.ae",h="_bp_",dt=new Set(["password","file","checkbox","radio","submit","button","reset","image"]),pt=8e3,st=`${h}identify_signature`,rt=`${h}identify_fingerprint`,lt=`${h}identify_sent_at`;function m(e,n=180){return e?e.replace(/\s+/g," ").trim().slice(0,n):""}function mt(e){return e?` ${e.toLowerCase().replace(/[_-]+/g," ").replace(/[^a-z0-9\s@.]/g," ").replace(/\s+/g," ").trim()} `:""}function H(e,n){for(let p of n)if(e.includes(p))return!0;return!1}function _(e){return/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i.test(e)}function $(e){let n=m(e,50);if(!n)return"";let p=n.startsWith("+"),o=n.replace(/\D/g,"");return o.length<6?"":`${p?"+":""}${o.slice(0,20)}`}function B(e,n){for(let p of n){let o=e.querySelector(p),f=m(o?.value);if(f)return f}return""}function ut(e){return m(e.getAttribute("data-bp-field")||e.getAttribute("data-bitpalm-field"),64).toLowerCase().replace(/[_\s]+/g,"-")}function ft(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function gt(e,n){let p=[],o=(i,x=140)=>{let a=m(i,x);a&&p.push(a)};o(n.name),o(n.id),o(n.getAttribute("autocomplete")),o(n.getAttribute("placeholder")),o(n.getAttribute("aria-label")),o(n.getAttribute("data-field")),o(n.getAttribute("data-name")),o(n.getAttribute("data-label")),o(n.getAttribute("data-bp-field")),o(n.getAttribute("data-bitpalm-field"));let f=new Set,y=i=>{let x=m(i,200);!x||f.has(x)||(f.add(x),p.push(x))};for(let i of Array.from(n.labels||[]))y(i.textContent);if(n.id){let i=e.querySelector(`label[for="${ft(n.id)}"]`);y(i?.textContent)}let g=n.closest("label");y(g?.textContent);let r=n.getAttribute("aria-labelledby");if(r)for(let i of r.split(/\s+/)){if(!i)continue;let x=e.ownerDocument.getElementById(i);y(x?.textContent)}return p}function ht(e){let n=m(B(e,["[data-bp-email]","[data-bitpalm-email]"]),140).toLowerCase(),p=$(B(e,["[data-bp-phone]","[data-bitpalm-phone]"])),o=m(B(e,["[data-bp-name]","[data-bitpalm-name]","[data-bp-full-name]","[data-bitpalm-full-name]"])),f=m(B(e,["[data-bp-first-name]","[data-bitpalm-first-name]"])),y=m(B(e,["[data-bp-last-name]","[data-bitpalm-last-name]"])),g=m(B(e,["[data-bp-company]","[data-bitpalm-company]"]));for(let a of Array.from(e.elements)){if(!(a instanceof HTMLInputElement||a instanceof HTMLTextAreaElement||a instanceof HTMLSelectElement)||a.disabled||a instanceof HTMLInputElement&&dt.has(a.type.toLowerCase()))continue;let u=ut(a),d=a.hasAttribute("data-bp-email")||a.hasAttribute("data-bitpalm-email")||a.hasAttribute("data-bp-phone")||a.hasAttribute("data-bitpalm-phone")||a.hasAttribute("data-bp-name")||a.hasAttribute("data-bitpalm-name")||a.hasAttribute("data-bp-full-name")||a.hasAttribute("data-bitpalm-full-name")||a.hasAttribute("data-bp-first-name")||a.hasAttribute("data-bitpalm-first-name")||a.hasAttribute("data-bp-last-name")||a.hasAttribute("data-bitpalm-last-name")||a.hasAttribute("data-bp-company")||a.hasAttribute("data-bitpalm-company")||!!u;if(a instanceof HTMLInputElement&&a.type.toLowerCase()==="hidden"&&!d)continue;let s=m(a.value);if(!s)continue;let C=a instanceof HTMLInputElement?a.type.toLowerCase():"",v=mt(gt(e,a).join(" "));if(!n&&u==="email"&&_(s)){n=s.toLowerCase();continue}if(!p&&(u==="phone"||u==="tel"||u==="mobile"||u==="whatsapp")){let L=$(s);if(L){p=L;continue}}if(!g&&u==="company"){g=m(s,160);continue}if(!f&&(u==="first-name"||u==="firstname")){f=m(s,100);continue}if(!y&&(u==="last-name"||u==="lastname"||u==="surname")){y=m(s,100);continue}if(!o&&(u==="name"||u==="full-name"||u==="fullname")){!_(s)&&!$(s)&&(o=m(s,140));continue}let E=C==="email"||H(v,[" email "," e mail "," mail "," email adresse "," mailadresse "," correo "]),M=C==="tel"||H(v,[" phone "," phone number "," mobile "," tel "," telefon "," telefonnummer "," whatsapp "," handy "," kontakt "," nummer "]),F=H(v,[" company "," company name "," firma "," firmenname "," organization "," organisation "," business "," unternehmen "," agency "," brokerage "]),I=H(v,[" first name "," firstname "," given name "," givenname "," vorname "," fname "]),P=H(v,[" last name "," lastname "," family name "," familyname "," surname "," nachname "," lname "]),b=H(v,[" full name "," fullname "," contact name "," name "])&&!E&&!M;if(!n&&E&&_(s)){n=s.toLowerCase();continue}if(!p&&M){let L=$(s);if(L){p=L;continue}}if(!g&&F){g=m(s,160);continue}if(!f&&I){f=m(s,100);continue}if(!y&&P){y=m(s,100);continue}if(!o&&b&&!_(s)&&!$(s)){o=m(s,140);continue}!n&&_(s)&&(n=s.toLowerCase())}if(o&&(_(o)||$(o))&&(o=""),g&&(_(g)||$(g))&&(g=""),o||(o=m([f,y].filter(Boolean).join(" "),140)),o&&n&&o.toLowerCase()===n.toLowerCase()&&(o=""),!!!(n||p)&&!!!(o&&g))return null;let x={...o?{name:o}:{},...n?{email:n}:{},...p?{phone:p}:{},...g?{company:g}:{}};return Object.keys(x).length>0?x:null}function yt(){if(typeof document<"u"){let e=document.documentElement.lang;if(e)return e.slice(0,2).toLowerCase()}return"en"}function bt(){if(typeof window>"u")return!1;let e=typeof navigator<"u"?navigator.userAgent:"";if(/Android|iPhone|iPad|iPod|IEMobile|Windows Phone|Mobile/i.test(e))return!0;let p=window.matchMedia("(pointer: coarse)").matches,o=window.matchMedia("(hover: none)").matches,f=Math.min(window.screen?.width||window.innerWidth,window.screen?.height||window.innerHeight);return p&&o&&f<=900}function q(e){let{slug:n,locale:p=yt(),baseUrl:o=ct,token:f,zIndex:y=9999,autoIdentify:g=!0}=e,r=document,i=r.createElement("iframe"),x=`${o}/t/${n}/widget`,a=new URLSearchParams({locale:p});f&&a.set("token",f),i.src=`${x}?${a.toString()}`,i.allow="clipboard-write",i.setAttribute("allowtransparency","true"),i.style.cssText=`position:fixed;bottom:0;right:0;width:1px;height:1px;border:none;z-index:${y};background:transparent;color-scheme:normal;opacity:0;pointer-events:none;`,r.body.appendChild(i);let u=new URL(i.src).origin,d=r.createElement("div");if(d.setAttribute("role","button"),d.setAttribute("aria-label","Chat"),d.style.cssText=`position:fixed;bottom:24px;right:24px;width:56px;height:56px;border-radius:50%;display:none;align-items:center;justify-content:center;cursor:pointer;z-index:${y-1};background:#00ff41;box-shadow:0 0 15px rgba(0,255,65,0.31);transition:transform .2s,opacity .3s;opacity:0;`,d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="black" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',d.onmouseenter=()=>{d.style.transform="scale(1.1)"},d.onmouseleave=()=>{d.style.transform="scale(1)"},d.onclick=()=>it(),r.body.appendChild(d),!r.getElementById("_bp_fade")){let t=r.createElement("style");t.id="_bp_fade",t.textContent="@keyframes _bp_fade{from{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}",r.head.appendChild(t)}let s=null,C=!1,v=!1,E=()=>{s&&(s.remove(),s=null)},M=()=>{},F=t=>{if(t.origin===u){if(t.data?.type==="bitpalm-widget-config"){v=!1,C=!0,i.style.display==="none"&&(i.style.display=""),t.data.primaryColor&&(d.style.background=t.data.primaryColor,d.style.boxShadow=t.data.chatShadow==="none"?"none":`0 0 15px ${t.data.primaryColor}50`);let l=t.data.chatButtonIconColor||"black";if(t.data.chatButtonIconSvg){d.innerHTML="";let c=r.createElement("span");c.style.cssText=`display:flex;align-items:center;justify-content:center;width:24px;height:24px;color:${l}`;let w=new DOMParser().parseFromString(t.data.chatButtonIconSvg,"image/svg+xml").querySelector("svg");w?(w.querySelectorAll("script,foreignObject").forEach(A=>A.remove()),w.querySelectorAll("*").forEach(A=>{for(let N of[...A.attributes])(N.name.startsWith("on")||N.value&&N.value.includes("javascript:"))&&A.removeAttribute(N.name)}),w.setAttribute("width","24"),w.setAttribute("height","24"),w.style.display="block",c.appendChild(w)):c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7.9 20A9 9 0 1 0 4 16.1L2 22Z"/></svg>',d.appendChild(c)}else{let c=d.querySelector("svg");c&&(c.style.stroke=l)}d.style.display="flex",requestAnimationFrame(()=>{d.style.opacity="1"})}if(t.data?.type==="bitpalm-widget-resize"){let l=t.data.width>0,c=bt();l?(i.style.width=c?`${window.innerWidth}px`:`${t.data.width}px`,i.style.height=c?`${window.innerHeight}px`:`${t.data.height}px`,c&&(i.style.left="0",i.style.top="0"),i.style.opacity="1",i.style.pointerEvents="auto"):(i.style.width="1px",i.style.height="1px",i.style.left="",i.style.top="",i.style.opacity="0",i.style.pointerEvents="none"),d.style.display=l?"none":"flex"}if(t.data?.type==="bitpalm-trigger-show"){if(v||!C)return;E(),s=r.createElement("div"),s.style.cssText=`position:fixed;bottom:90px;right:24px;max-width:240px;background:#fff;border-radius:16px;padding:12px 32px 12px 12px;box-shadow:0 2px 20px rgba(0,0,0,0.08);cursor:pointer;z-index:${y-1};font-family:system-ui,sans-serif;animation:_bp_fade .3s;`;let l=(t.data.message||"").replace(/</g,"&lt;");s.innerHTML=`<p style="font-size:14px;color:#1f2937;margin:0;">${l}</p><div style="position:absolute;bottom:-8px;right:20px;width:0;height:0;border-left:8px solid transparent;border-right:8px solid transparent;border-top:8px solid #fff;"></div>`;let c=r.createElement("button");c.style.cssText="position:absolute;top:-8px;right:-8px;width:28px;height:28px;border-radius:50%;background:#fff;border:none;box-shadow:0 1px 4px rgba(0,0,0,0.1);cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:14px;color:#9ca3af;",c.innerHTML="&#10005;",c.onclick=S=>{S.stopPropagation(),E(),i.contentWindow?.postMessage({type:"bitpalm-trigger-dismiss"},"*")},s.onclick=()=>{E(),d.style.display="none",i.contentWindow?.postMessage({type:"bitpalm-trigger-engaged"},"*")},s.appendChild(c),r.body.appendChild(s)}t.data?.type==="bitpalm-trigger-hide"&&E(),t.data?.type==="bitpalm-request-context"&&M(),t.data?.type==="bitpalm-widget-blocked"&&(v=!0,C=!1,d.style.display="none",E(),i.style.display="none")}};window.addEventListener("message",F);let I=!1;try{I=localStorage.getItem(`${h}optout`)==="1"}catch{}let P=`${h}vid`,b="";if(!I){try{b=localStorage.getItem(P)||""}catch{}if(!b){let t=r.cookie.match(new RegExp(`(?:^|; )${P}=([^;]+)`));b=t?decodeURIComponent(t[1]):""}b||(b=crypto.randomUUID?crypto.randomUUID():`${Date.now()}-${Math.random().toString(36).slice(2,11)}`);try{localStorage.setItem(P,b)}catch{}try{r.cookie=`${P}=${encodeURIComponent(b)};path=/;max-age=31536000;SameSite=Lax`}catch{}}if(!I)try{let t=new URLSearchParams(location.search),l={};for(let T of["utm_source","utm_medium","utm_campaign","utm_term","utm_content"]){let w=t.get(T);w&&(l[T]=w)}let c=JSON.stringify({tenant_slug:n,visitor_id:b,url:location.href,referrer:r.referrer||void 0,...Object.keys(l).length>0?{utm:l}:{}}),S=`${o}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(S,new Blob([c],{type:"application/json"})):fetch(S,{method:"POST",body:c,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}let L="",U="",R=0;try{L=sessionStorage.getItem(st)||"",U=sessionStorage.getItem(rt)||"";let t=parseInt(sessionStorage.getItem(lt)||"0",10);Number.isFinite(t)&&t>0&&(R=t)}catch{}let J=t=>{if(I||!g||!b)return;let l=t.target instanceof HTMLFormElement?t.target:t.target instanceof Element?t.target.closest("form"):null;if(!(l instanceof HTMLFormElement))return;let c=(l.getAttribute("data-bp-identify")||l.getAttribute("data-bitpalm-identify")||"").toLowerCase();if(c==="off"||c==="false"||c==="0")return;let S=ht(l);if(!S)return;let T=[S.email||"",S.phone||"",S.name||"",S.company||""].join("|").toLowerCase(),w=[l.getAttribute("id")||"",l.getAttribute("name")||"",l.getAttribute("action")||"",T].join("|").toLowerCase(),A=Date.now();if(!(A-R<pt&&(w===L||T===U))){L=w,U=T,R=A;try{sessionStorage.setItem(st,w),sessionStorage.setItem(rt,T),sessionStorage.setItem(lt,String(A))}catch{}try{let ot=JSON.stringify({tenant_slug:n,visitor_id:b,url:location.href,referrer:r.referrer||void 0,...S}),at=`${o}/api/widget/identify`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(at,new Blob([ot],{type:"application/json"})):fetch(at,{method:"POST",body:ot,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}}};!I&&g&&r.addEventListener("submit",J,!0);let D=parseInt(sessionStorage.getItem(`${h}pages`)||"0")+1;sessionStorage.setItem(`${h}pages`,String(D));let k=JSON.parse(sessionStorage.getItem(`${h}hist`)||"[]");k.push(location.href),k.length>20&&(k=k.slice(-20)),sessionStorage.setItem(`${h}hist`,JSON.stringify(k));let G=Date.now(),W=parseInt(sessionStorage.getItem(`${h}site_start`)||"0");W||(W=G,sessionStorage.setItem(`${h}site_start`,String(W)));let K=[];M=()=>{let t=!1;try{t=!!localStorage.getItem(`${h}visited`)}catch{t=!1}if(i.contentWindow?.postMessage({type:"bitpalm-parent-context",url:location.href,title:r.title,returning:t,pageCount:D,pageHistory:k,loadedAt:G,siteStart:W,locale:p,visitorId:I?"":b},"*"),!t&&!I)try{localStorage.setItem(`${h}visited`,"1")}catch{}},i.addEventListener("load",()=>{M(),[120,450,1100].forEach(t=>{let l=setTimeout(()=>M(),t);K.push(l)})});let V=history.pushState.bind(history),Z=history.replaceState.bind(history),O=()=>{D++,sessionStorage.setItem(`${h}pages`,String(D));let t=JSON.parse(sessionStorage.getItem(`${h}hist`)||"[]");if(t.push(location.href),t.length>20&&t.splice(0,t.length-20),k=t,sessionStorage.setItem(`${h}hist`,JSON.stringify(t)),i.contentWindow?.postMessage({type:"bitpalm-page-change",url:location.href,title:r.title,pageCount:D,pageHistory:t,loadedAt:Date.now()},"*"),!I)try{let l=JSON.stringify({tenant_slug:n,visitor_id:b,url:location.href}),c=`${o}/api/widget/impression`;typeof navigator.sendBeacon=="function"?navigator.sendBeacon(c,new Blob([l],{type:"application/json"})):fetch(c,{method:"POST",body:l,headers:{"Content-Type":"application/json"},keepalive:!0}).catch(()=>{})}catch{}};history.pushState=function(...t){V(...t),O()},history.replaceState=function(...t){Z(...t),O()},window.addEventListener("popstate",O);let X=-1,j,Q=()=>{clearTimeout(j),j=setTimeout(()=>{let t=Math.max(r.documentElement.scrollHeight,r.body.scrollHeight)-window.innerHeight,l=t>0?Math.round(window.scrollY/t*100):100;l!==X&&(X=l,i.contentWindow?.postMessage({type:"bitpalm-scroll-depth",percent:l},"*"))},500)};window.addEventListener("scroll",Q,{passive:!0});let tt=t=>{t.clientY<=0&&i.contentWindow?.postMessage({type:"bitpalm-exit-intent"},"*")};r.addEventListener("mouseout",tt);let z,et=!1,Y=()=>{clearTimeout(z),!et&&(z=setTimeout(()=>{et=!0,i.contentWindow?.postMessage({type:"bitpalm-inactivity"},"*")},15e3))},nt=["mousemove","keydown","scroll","touchstart"];nt.forEach(t=>r.addEventListener(t,Y,{passive:!0})),Y();let it=()=>{d.style.display="none",E(),i.contentWindow?.postMessage({type:"bitpalm-open"},"*");let t=i.src.split("#")[0];i.src=`${t}#bp-open-${Date.now()}`};return{open:it,close:()=>{i.contentWindow?.postMessage({type:"bitpalm-close"},"*")},destroy:()=>{window.removeEventListener("message",F),window.removeEventListener("scroll",Q),window.removeEventListener("popstate",O),r.removeEventListener("mouseout",tt),r.removeEventListener("submit",J,!0),nt.forEach(t=>r.removeEventListener(t,Y)),clearTimeout(j),clearTimeout(z),K.forEach(t=>clearTimeout(t)),history.pushState=V,history.replaceState=Z,E(),d.remove(),i.remove()}}}function wt(e){if(e==null)return;let n=e.trim().toLowerCase();if(["1","true","yes","on"].includes(n))return!0;if(["0","false","no","off"].includes(n))return!1}if(typeof document<"u"){let e=document.currentScript;if(e?.dataset.slug){let n=()=>{q({slug:e.dataset.slug,locale:e.dataset.locale,baseUrl:e.dataset.baseUrl,token:e.dataset.token,zIndex:e.dataset.zIndex?Number(e.dataset.zIndex):void 0,autoIdentify:wt(e.dataset.autoIdentify)})};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",n):n()}}export{q as createWidget};
2
2
  //# sourceMappingURL=index.js.map