UNPKG

@bharath-ravi/clickwrap-sdk

Version:

Framework-agnostic Clickwrap SDK for JavaScript/TypeScript projects

2 lines (1 loc) 5.1 kB
var A="https://sdk.spotdraft.com/clickwrap/v1/index.js",x="https://sdk.spotdraft.com/clickwrap/v1/sdk.js",k=r=>r,C="data-sd-clickthrough-checkbox-id",w=(o=>(o.UNKNOWN_ERROR="SD_CT_000",o.INVALID_DOMAIN="SD_CT_001",o.INITIALIZATION_PARAMS_MISSING="SD_CT_002",o.EXECUTION_REQUIRED_FIELD_MISSING="SD_CT_003",o.POLICIES_NOT_ACCEPTED="SD_CT_004",o.FAILED_TO_LOAD_SDK="SD_CT_005",o.NOT_FOUND="SD_CT_006",o))(w||{}),E={SD_CT_000:"Something went wrong!",SD_CT_001:"Request received from invalid domain. Check if the domain is whitelisted in console",SD_CT_002:"init: Parameters missing. 'clickwrapId', 'hostLocationDomId' and 'baseUrl' are all required",SD_CT_003:"user_identifier is a required field",SD_CT_004:"Please accept the policies",SD_CT_005:"Failed to load SDK",SD_CT_006:"Clickthrough is not found. Please check the clickthrough ID"};function p(r){return r!=null,r==null?!1:typeof r=="string"?r!=="":!0}var s=(r,i="")=>{throw new Error(JSON.stringify({errorCode:r.toString(),message:`[SdClickthrough] ${E[r]}. ${i}`}))};var h=class{constructor(i,e){this.baseUrl=i,this.options=e}async get(i){let e=await fetch(`${this.baseUrl}/${i}`,{method:"GET",...this.options});return this.handleResponse(e)}async post(i,e){let t=await fetch(`${this.baseUrl}/${i}`,{method:"POST",body:JSON.stringify(e),...this.options});return this.handleResponse(t)}handleResponse(i){let e="Something went wrong. Please contact Spotdraft support if you continue to see this error";if(i.ok)return i.json();switch(i.status){case 400:console.error(e);break;case 401:console.error(e);break;case 403:throw s("SD_CT_001");case 404:throw s("SD_CT_006");case 500:console.error(e);break}}};var u=class{constructor(i){this.context=i}},_=(t=>(t.ACCEPTANCE_TOGGLED="acceptanceToggled",t.CLICKWRAP_SDK_LOAD_SUCCESS="sdClickthroughLoaded",t.CLICKWRAP_SDK_LOAD_FAILURE="sdClickthroughLoadFailed",t))(_||{});var I=(r,i,e)=>fetch(`${i}/api/v2.1/public/clickwrap/${r}/execute`,{method:"POST",headers:{"clickwrap-id":r,"Content-Type":"application/json"},body:JSON.stringify(e)}).then(t=>{if(t.ok)return t.json();let n=`${t.status.toString()}: ${t.statusText}`;throw new Error(n)}).catch(t=>{throw new Error(t.message)});var b=async(r,i)=>{try{let e=await fetch(`${i}/api/v2.1/public/clickwrap/${r}`,{headers:{"clickwrap-id":r}});return e.ok===!1&&(e.status===403&&s("SD_CT_001"),e.status===404&&s("SD_CT_006")),e.json()}catch(e){return console.error(e),e}};var S=class extends u{constructor(e){super(e);this._acceptedList={};this.viewedAgreements=new Set;this.eventListeners={};p(this.context.clickwrapId)&&p(this.context.baseUrl)&&p(this.context.hostLocationDomId)?this.client=new h(this.context.baseUrl,{headers:{"clickwrap-id":this.context.clickwrapId,"Content-Type":"application/json"}}):s("SD_CT_002")}isAccepted(){if(this.config?.settings.type==="INLINE")return!0;let e=!0,t=this._acceptedList;for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&!t[n]){e=!1;break}return e}isReacceptanceRequired(e){if(!this.client||!this.context.clickwrapId)throw new Error("Clickthrough SDK not initialized");return this.client.post(`api/v2.1/public/clickwrap/${this.context.clickwrapId}/consent_status`,{user_identifier:e})}async init(){this._acceptedList={};try{let e=await b(this.context.clickwrapId,this.context.baseUrl);if(!(e&&e.settings))return;this.config=e,e.settings.clickwrap_texts.forEach((n,c)=>this._acceptedList[c]=!1),this.addClickwrapElementToDOM(this.context.hostLocationDomId,e).forEach(n=>{n.addEventListener("change",c=>{let g=c.target,o=g.getAttribute(C);this._acceptedList[o]=g.checked,this.triggerEvent("acceptanceToggled",this.isAccepted())})})}catch(e){console.error(e)}}on(e,t){this.eventListeners[e]||(this.eventListeners[e]=[]),this.eventListeners[e].push(t)}submit(e){if((!e||!e.user_identifier)&&s("SD_CT_003"),this.isAccepted()||s("SD_CT_004"),this.config){let t=this.config?.agreements.map(n=>({id:n.id,version_id:n.current_version.id,has_clicked:this.viewedAgreements.has(n.id)}));return I(this.context.clickwrapId,this.context.baseUrl,{...e,clickwrap_public_id:this.config.public_id,agreements:t})}else throw s("SD_CT_000")}triggerEvent(e,t){this.eventListeners[e]&&this.eventListeners[e].forEach(function(n){n(t)})}addClickwrapElementToDOM(e,t){let n=[];t.settings.clickwrap_texts.forEach((o,m)=>{let a=document.createElement("div"),d=document.createElement("span");if(d.classList.add(k("sd-clickthrough-text")),t.settings.type!=="INLINE"){let l=document.createElement("input");l.type="checkbox",l.classList.add(k("sd-clickthrough-checkbox")),l.setAttribute(C,m.toString()),n.push(l),a.appendChild(l)}d.innerHTML=o,a.appendChild(d);let f=document.getElementById(e);f&&f.appendChild(a)});let c="data-agreement-id";return document.querySelectorAll(`a[${c}]`).forEach(o=>{o.addEventListener("click",m=>{let a=m.target,d=Number(a.getAttribute(c));this.viewedAgreements.add(d)})}),n}};export{A as CLICKWRAP_SCRIPT_PATH,x as CLICKWRAP_SDK_PATH,C as SD_CLICKWRAP_CHECKBOX_DATA_ATTR,S as SdClickthrough,w as SdClickthroughErrorCodes,E as SdClickthroughErrorMapping,_ as SdClickthroughEvents,k as classNameGuard};