@unifygtm/intent-react
Version:
Library for using the Unify Intent JS Client in a React app.
11 lines (8 loc) • 16.6 kB
JavaScript
var Q=Object.defineProperty,tt=Object.defineProperties,et=Object.getOwnPropertyDescriptors,U=Object.getOwnPropertySymbols,nt=Object.prototype.hasOwnProperty,it=Object.prototype.propertyIsEnumerable,x=(t,e,n)=>e in t?Q(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,c=(t,e)=>{for(var n in e||(e={}))nt.call(e,n)&&x(t,n,e[n]);if(U)for(var n of U(e))it.call(e,n)&&x(t,n,e[n]);return t},B=(t,e)=>tt(t,et(e)),K="https://unifyintent.com/analytics/api/v1",rt=/^[A-Za-z0-9._+%-]+@[A-Za-z0-9.-]+[.][A-Za-z]+$/;function P(t,e){var n;return((n=e==null?void 0:e.getTime())!=null?n:new Date().getTime())+t*60*1e3}var j=t=>({path:t!=null?t:window.location.pathname,query:ot(window.location.href),referrer:document.referrer,title:document.title,url:t!==void 0?st({location:window.location,pathname:t}):window.location.href});function st({location:t,pathname:e}){let n=new URL(t.href);return n.pathname=e,n.toString()}var z=()=>({userAgent:window.navigator.userAgent,userAgentData:window.navigator.userAgentData}),N=t=>{if(rt.test(t))return t},ot=t=>{let e=new URL(t).searchParams,n={};for(let[i,r]of e.entries())n[i]=r;return n},at=()=>{var t,e,n,i,r;let s=new URL(location.href),o={source:(t=s.searchParams.get("utm_source"))!=null?t:void 0,medium:(e=s.searchParams.get("utm_medium"))!=null?e:void 0,campaign:(n=s.searchParams.get("utm_campaign"))!=null?n:void 0,term:(i=s.searchParams.get("utm_term"))!=null?i:void 0,content:(r=s.searchParams.get("utm_content"))!=null?r:void 0};return B(c({locale:navigator.language},z()),{utm:o})},ut=class{constructor(t){this.getBaseActivityPayload=()=>({type:this.getActivityType(),anonymousUserId:this._intentContext.identityManager.getOrCreateAnonymousUserId(),sessionId:this._intentContext.sessionManager.getOrCreateSession().sessionId,context:at(),timestamp:new Date().toISOString()}),this._intentContext=t}track(){this._intentContext.apiClient.post(this.getActivityURL(),c(c({},this.getBaseActivityPayload()),this.getActivityData()))}},V=ut,ht=`${K}/page`,$=class extends V{constructor(t,e){super(t),this.getActivityData=()=>{var n;return{type:"page",properties:j((n=this._options)==null?void 0:n.pathname)}},this._options=e}getActivityType(){return"page"}getActivityURL(){return ht}},lt=`${K}/identify`,H=class extends V{constructor(t,{email:e}){super(t),this.getActivityData=()=>({type:"identify",traits:{email:this._email}}),this._email=e}getActivityType(){return"identify"}getActivityURL(){return lt}},p,ct=new Uint8Array(16);function dt(){if(!p&&(p=typeof crypto!="undefined"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!p))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return p(ct)}var u=[];for(let t=0;t<256;++t)u.push((t+256).toString(16).slice(1));function ft(t,e=0){return u[t[e+0]]+u[t[e+1]]+u[t[e+2]]+u[t[e+3]]+"-"+u[t[e+4]]+u[t[e+5]]+"-"+u[t[e+6]]+u[t[e+7]]+"-"+u[t[e+8]]+u[t[e+9]]+"-"+u[t[e+10]]+u[t[e+11]]+u[t[e+12]]+u[t[e+13]]+u[t[e+14]]+u[t[e+15]]}var yt=typeof crypto!="undefined"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),E={randomUUID:yt};function pt(t,e,n){if(E.randomUUID&&!e&&!t)return E.randomUUID();t=t||{};let i=t.random||(t.rng||dt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){n=n||0;for(let r=0;r<16;++r)e[n+r]=i[r];return e}return ft(i)}var Z=pt;function m(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var i in n)t[i]=n[i]}return t}var mt={read:function(t){return t[0]==='"'&&(t=t.slice(1,-1)),t.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(t){return encodeURIComponent(t).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}};function C(t,e){function n(r,s,o){if(typeof document!="undefined"){o=m({},e,o),typeof o.expires=="number"&&(o.expires=new Date(Date.now()+o.expires*864e5)),o.expires&&(o.expires=o.expires.toUTCString()),r=encodeURIComponent(r).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var a="";for(var l in o)o[l]&&(a+="; "+l,o[l]!==!0&&(a+="="+o[l].split(";")[0]));return document.cookie=r+"="+t.write(s,r)+a}}function i(r){if(!(typeof document=="undefined"||arguments.length&&!r)){for(var s=document.cookie?document.cookie.split("; "):[],o={},a=0;a<s.length;a++){var l=s[a].split("="),f=l.slice(1).join("=");try{var _=decodeURIComponent(l[0]);if(o[_]=t.read(f,_),r===_)break}catch(oe){}}return r?o[r]:o}}return Object.create({set:n,get:i,remove:function(r,s){n(r,"",m({},s,{expires:-1}))},withAttributes:function(r){return C(this.converter,m({},this.attributes,r))},withConverter:function(r){return C(m({},this.converter,r),this.attributes)}},{attributes:{value:Object.freeze(e)},converter:{value:Object.freeze(t)}})}var I=C(mt,{path:"/"}),d=typeof Buffer=="function",T=typeof TextDecoder=="function"?new TextDecoder:void 0,D=typeof TextEncoder=="function"?new TextEncoder:void 0,gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",y=Array.prototype.slice.call(gt),g=(t=>{let e={};return t.forEach((n,i)=>e[n]=i),e})(y),vt=/^(?:[A-Za-z\d+\/]{4})*?(?:[A-Za-z\d+\/]{2}(?:==)?|[A-Za-z\d+\/]{3}=?)?$/,h=String.fromCharCode.bind(String),M=typeof Uint8Array.from=="function"?Uint8Array.from.bind(Uint8Array):t=>new Uint8Array(Array.prototype.slice.call(t,0)),_t=t=>t.replace(/=/g,"").replace(/[+\/]/g,e=>e=="+"?"-":"_"),q=t=>t.replace(/[^A-Za-z0-9\+\/]/g,""),It=t=>{let e,n,i,r,s="",o=t.length%3;for(let a=0;a<t.length;){if((n=t.charCodeAt(a++))>255||(i=t.charCodeAt(a++))>255||(r=t.charCodeAt(a++))>255)throw new TypeError("invalid character found");e=n<<16|i<<8|r,s+=y[e>>18&63]+y[e>>12&63]+y[e>>6&63]+y[e&63]}return o?s.slice(0,o-3)+"===".substring(o):s},J=typeof btoa=="function"?t=>btoa(t):d?t=>Buffer.from(t,"binary").toString("base64"):It,wt=d?t=>Buffer.from(t).toString("base64"):t=>{let e=[];for(let n=0,i=t.length;n<i;n+=4096)e.push(h.apply(null,t.subarray(n,n+4096)));return J(e.join(""))},At=t=>{if(t.length<2){var e=t.charCodeAt(0);return e<128?t:e<2048?h(192|e>>>6)+h(128|e&63):h(224|e>>>12&15)+h(128|e>>>6&63)+h(128|e&63)}else{var e=65536+(t.charCodeAt(0)-55296)*1024+(t.charCodeAt(1)-56320);return h(240|e>>>18&7)+h(128|e>>>12&63)+h(128|e>>>6&63)+h(128|e&63)}},bt=/[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g,Ct=t=>t.replace(bt,At),O=d?t=>Buffer.from(t,"utf8").toString("base64"):D?t=>wt(D.encode(t)):t=>J(Ct(t)),W=(t,e=!1)=>e?_t(O(t)):O(t),St=/[\xC0-\xDF][\x80-\xBF]|[\xE0-\xEF][\x80-\xBF]{2}|[\xF0-\xF7][\x80-\xBF]{3}/g,Ut=t=>{switch(t.length){case 4:var e=(7&t.charCodeAt(0))<<18|(63&t.charCodeAt(1))<<12|(63&t.charCodeAt(2))<<6|63&t.charCodeAt(3),n=e-65536;return h((n>>>10)+55296)+h((n&1023)+56320);case 3:return h((15&t.charCodeAt(0))<<12|(63&t.charCodeAt(1))<<6|63&t.charCodeAt(2));default:return h((31&t.charCodeAt(0))<<6|63&t.charCodeAt(1))}},xt=t=>t.replace(St,Ut),Pt=t=>{if(t=t.replace(/\s+/g,""),!vt.test(t))throw new TypeError("malformed base64.");t+="==".slice(2-(t.length&3));let e,n="",i,r;for(let s=0;s<t.length;)e=g[t.charAt(s++)]<<18|g[t.charAt(s++)]<<12|(i=g[t.charAt(s++)])<<6|(r=g[t.charAt(s++)]),n+=i===64?h(e>>16&255):r===64?h(e>>16&255,e>>8&255):h(e>>16&255,e>>8&255,e&255);return n},Y=typeof atob=="function"?t=>atob(q(t)):d?t=>Buffer.from(t,"base64").toString("binary"):Pt,Et=d?t=>M(Buffer.from(t,"base64")):t=>M(Y(t).split("").map(e=>e.charCodeAt(0))),Tt=d?t=>Buffer.from(t,"base64").toString("utf8"):T?t=>T.decode(Et(t)):t=>xt(Y(t)),Dt=t=>q(t.replace(/[-_]/g,e=>e=="-"?"+":"/")),Mt=t=>Tt(Dt(t)),w="test";function F(t){return W(JSON.stringify(t))}function Ot(t){return JSON.parse(Mt(t))}function Ft(){try{return localStorage.setItem(w,w),localStorage.removeItem(w),!0}catch(t){return!1}}function kt(t){return(t!=null?t:window.location.hostname).split(".").slice(-2).join(".")}var Rt=class{constructor(t){this.get=e=>{let n=this.retrieveValue(this.buildKey(e));return n?Ot(n):null},this.set=(e,n)=>{this.storeValue(this.buildKey(e),F(n))},this.buildKey=e=>F(`${this._writeKey}_${e}`),this._writeKey=t}},G=Rt,Lt=class extends G{retrieveValue(t){var e;let n=(e=I.get(t))!=null?e:null;return n&&(I.remove(t),this.storeValue(t,n)),n}storeValue(t,e){I.set(t,e,{domain:`.${kt()}`,expires:365})}},Bt=class extends G{constructor(t){super(t),this.retrieveValue=e=>this._localStorageAvailable?localStorage.getItem(e):null,this.storeValue=(e,n)=>{this._localStorageAvailable&&localStorage.setItem(e,n)},this._localStorageAvailable=Ft()}},k="anonymousUserId",Kt=class{constructor(t){this.getOrCreateAnonymousUserId=()=>{if(this._anonymousUserId)return this._anonymousUserId;let e=this.getAnonymousUserId()||this.createAnonymousUserId();return this._anonymousUserId=e,e},this.getAnonymousUserId=()=>this._storageService.get(k),this.createAnonymousUserId=()=>{let e=Z();return this._storageService.set(k,e),e},this._storageService=new Lt(t),this._anonymousUserId=null}},R="clientSession",L=30,jt=class{constructor(t){this.getOrCreateSession=()=>this.getAndUpdateSession()||this.createSession(),this.getAndUpdateSession=()=>{let e=this._currentSession||this.getStoredSession();if(e&&e.expiration>new Date().getTime())return this.updateSessionExpiration(e)},this.createSession=(e=L)=>{let n=c({sessionId:Z(),startTime:new Date,expiration:P(e),initial:j()},z());return this._currentSession=n,this.setStoredSession(n),n},this.updateSessionExpiration=(e,n=L)=>{let i=B(c({},e),{expiration:P(n)});return this._currentSession=i,this.setStoredSession(i),i},this.getStoredSession=()=>this._storageService.get(R),this.setStoredSession=e=>{this._storageService.set(R,e)},this._writeKey=t,this._storageService=new Bt(this._writeKey),this._currentSession=null}},zt=class{constructor(t){this.post=(e,n)=>{let i=JSON.stringify(n),r=this.getAuthString(this._writeKey);if(fetch)fetch(e,{method:"POST",body:i,credentials:"include",headers:{"Content-type":"application/json; charset=UTF-8",Authorization:this.getAuthString(this._writeKey)},keepalive:!0}).catch(()=>{});else{let s=new XMLHttpRequest;s.open("POST",e,!0),s.setRequestHeader("Content-type","application/json; charset=UTF-8"),s.setRequestHeader("Authorization",r),s.send(i)}},this._writeKey=t}getAuthString(t){return`Basic ${W(t+":")}`}};function S({message:t}){console.debug(`%c[Unify]: %c${t}`,"font-weight: bold;","")}var Nt="https://forms.default.com",Vt="https://capture.navattic.com",$t=["default.form_completed","deafult.form_page_submitted","default.form_page_submitted"],A="user.email",Ht="email";function Zt(t){return $t.includes(t.event)}var b=class{constructor(t){this.startAutoPage=()=>{this._historyMonitored||this.monitorHistory(),this._autoPage=!0},this.stopAutoPage=()=>{this._historyMonitored&&window.removeEventListener("popstate",this.maybeTrackPage),this._autoPage=!1},this.startAutoIdentify=()=>{this._autoIdentify=!0,this.refreshMonitoredInputs(),setInterval(this.refreshMonitoredInputs,2e3),this.subscribeToThirdPartyMessages()},this.stopAutoIdentify=()=>{this._monitoredInputs.forEach(i=>{i.isConnected&&(i.removeEventListener("blur",this.handleInputBlur),i.removeEventListener("keydown",this.handleInputKeydown))}),this._monitoredInputs.clear(),this.unsubscribeFromThirdPartyMessages(),this._autoIdentify=!1},this.monitorHistory=()=>{let i=history.pushState;history.pushState=(...s)=>{i.apply(history,s),this.maybeTrackPage()};let r=history.replaceState;history.replaceState=(...s)=>{r.apply(history,s),this.maybeTrackPage()},window.addEventListener("popstate",this.maybeTrackPage),this._historyMonitored=!0},this.maybeTrackPage=()=>{this._autoPage&&(!this._lastLocation||qt(this._lastLocation,window.location))&&(new $(this._intentContext).track(),this._lastLocation=c({},window.location))},this.refreshMonitoredInputs=()=>{this._autoIdentify&&(this._monitoredInputs.forEach(i=>{i.isConnected||this._monitoredInputs.delete(i)}),Array.from(document.getElementsByTagName("input")).filter(i=>!this._monitoredInputs.has(i)&&Jt(i)).forEach(i=>{i.addEventListener("blur",this.handleInputBlur),i.addEventListener("keydown",this.handleInputKeydown),this._monitoredInputs.add(i)}))},this.subscribeToThirdPartyMessages=()=>{window.addEventListener("message",this.handleThirdPartyMessage)},this.unsubscribeFromThirdPartyMessages=()=>{window.removeEventListener("message",this.handleThirdPartyMessage)},this.handleThirdPartyMessage=i=>{if(!this._autoIdentify)return;let r;try{switch(i.origin){case Nt:{r="Default",this.handleDefaultFormMessage(i);break}case Vt:{r="Navattic",this.handleNavatticDemoMessage(i);break}}}catch(s){S({message:`Error occurred while handling message from third-party (${r}): ${s.message}`})}},this.handleDefaultFormMessage=i=>{if(this._autoIdentify&&Zt(i.data)){let r=i.data.payload.email;r&&this.maybeIdentifyInputEmail(r)}},this.handleNavatticDemoMessage=i=>{var r,s,o;if(this._autoIdentify)if(i.data.type==="IDENTIFY_USER"){let a=(r=i.data.eventAttributes.FORM)==null?void 0:r[A];if(a)this.maybeIdentifyInputEmail(a);else{let l=(s=Object.values(i.data.eventAttributes).find(f=>A in f))==null?void 0:s[A];l&&this.maybeIdentifyInputEmail(l)}}else{let a=((o=i.data.properties)!=null?o:[]).find(({object:l,name:f})=>l==="END_USER"&&f===Ht);a&&this.maybeIdentifyInputEmail(a.value)}},this.handleInputBlur=i=>{this._autoIdentify&&i.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(i.target.value)},this.handleInputKeydown=i=>{this._autoIdentify&&i.key==="Enter"&&i.target instanceof HTMLInputElement&&this.maybeIdentifyInputEmail(i.target.value)},this.maybeIdentifyInputEmail=i=>{if(this._autoIdentify&&i){if(!N(i)||this._submittedEmails.has(i))return;new H(this._intentContext,{email:i}).track(),this._submittedEmails.add(i)}},this.__getMonitoredInputs=()=>this._monitoredInputs,this.__getSubmittedEmails=()=>this._submittedEmails;var e,n;this._intentContext=t,this._monitoredInputs=new Set,this._submittedEmails=new Set,this._autoPage=(e=t.clientConfig.autoPage)!=null?e:!1,this._autoIdentify=(n=t.clientConfig.autoIdentify)!=null?n:!1,this._historyMonitored=!1,this._autoPage&&(this.startAutoPage(),this.maybeTrackPage()),this._autoIdentify&&this.startAutoIdentify()}};function qt(t,e){return t.hostname!==e.hostname||t.pathname!==e.pathname}function Jt(t){return t.type==="email"||t.type==="text"}var Wt={autoPage:!1,autoIdentify:!1},Yt=class{constructor(t,e=Wt){this._mounted=!1,this.mount=()=>{if(typeof window=="undefined")return;if(window.unify!==void 0&&!Array.isArray(window.unify)){S({message:"UnifyIntentClient already exists on window, a new one will not be created."});return}let n=new zt(this._writeKey),i=new jt(this._writeKey);i.getOrCreateSession();let r=new Kt(this._writeKey);r.getOrCreateAnonymousUserId(),this._context={writeKey:this._writeKey,clientConfig:this._config,apiClient:n,sessionManager:i,identityManager:r},(this._config.autoPage||this._config.autoIdentify)&&(this._intentAgent=new b(this._context)),this._mounted=!0,Gt(this),window.unify=this},this.unmount=()=>{typeof window!="undefined"&&(this._config.autoPage&&this.stopAutoPage(),this._config.autoIdentify&&this.stopAutoIdentify(),this._mounted=!1,window.unify=void 0)},this.page=n=>{this._mounted&&new $(this._context,n).track()},this.identify=n=>{if(!this._mounted)return!1;let i=N(n);return i?(new H(this._context,{email:i}).track(),!0):!1},this.startAutoPage=()=>{this._mounted&&(this._intentAgent||(this._intentAgent=new b(this._context)),this._intentAgent.startAutoPage())},this.stopAutoPage=()=>{var n;this._mounted&&((n=this._intentAgent)==null||n.stopAutoPage())},this.startAutoIdentify=()=>{this._mounted&&(this._intentAgent||(this._intentAgent=new b(this._context)),this._intentAgent.startAutoIdentify())},this.stopAutoIdentify=()=>{var n;this._mounted&&((n=this._intentAgent)==null||n.stopAutoIdentify())},this._writeKey=t,this._config=e}};function Gt(t){(Array.isArray(window.unify)?[...window.unify]:[]).forEach(([e,n])=>{if(typeof t[e]=="function")try{Array.isArray(n)?t[e].call(t,...n):t[e].call(t)}catch(i){S({message:i==null?void 0:i.message})}})}import X,{useEffect as Xt,useState as Qt}from"react";var te={client:null},v=X.createContext(te);v.displayName="UnifyIntentContext";var ee=({intentClient:t,children:e})=>{let[n]=Qt(t);return Xt(()=>(n.mount(),()=>{n.unmount()}),[]),X.createElement(v.Provider,{value:{client:n}},e)},ne=ee;import{useContext as ie}from"react";function re(){let{client:t}=ie(v);if(t===null)throw new Error("useUnifyIntent can only be used within a UnifyIntentProvider.");return t}var se=re;export{Yt as UnifyIntentClient,ne as UnifyIntentProvider,se as useUnifyIntent};
/*! Bundled license information:
@unifygtm/intent-client/dist/js/client/index.esm.js:
(*! Bundled license information:
js-cookie/dist/js.cookie.mjs:
(*! js-cookie v3.0.5 | MIT *)
*)
*/