@treasuredata/web-sdk 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +8 -0
- package/README.md +807 -0
- package/dist/browser.d.ts +9 -0
- package/dist/checksums.txt +8 -0
- package/dist/core/config.d.ts +10 -0
- package/dist/core/config.template.d.ts +10 -0
- package/dist/core/configurator.d.ts +35 -0
- package/dist/core/sdk.d.ts +3 -0
- package/dist/index.d.ts +37 -0
- package/dist/init.d.ts +18 -0
- package/dist/loader.d.ts +59 -0
- package/dist/loader.js +1 -0
- package/dist/loader.min.js +1 -0
- package/dist/plugins/clicks.d.ts +21 -0
- package/dist/plugins/conversion-api.d.ts +23 -0
- package/dist/plugins/global-id.d.ts +17 -0
- package/dist/plugins/in-browser-message.d.ts +6 -0
- package/dist/plugins/page-personalize/bridge/constants.d.ts +9 -0
- package/dist/plugins/page-personalize/bridge/rpc.d.ts +15 -0
- package/dist/plugins/page-personalize/index.d.ts +34 -0
- package/dist/plugins/page-personalize/injection/inject.d.ts +17 -0
- package/dist/plugins/page-personalize/modes/preview.d.ts +3 -0
- package/dist/plugins/page-personalize/modes/spot-selection.d.ts +9 -0
- package/dist/plugins/page-personalize/offers.d.ts +72 -0
- package/dist/plugins/page-personalize/router.d.ts +17 -0
- package/dist/plugins/page-personalize/types.d.ts +27 -0
- package/dist/plugins/page-personalize/utils/selector-generator.d.ts +6 -0
- package/dist/plugins/personalization.d.ts +39 -0
- package/dist/plugins/record.d.ts +32 -0
- package/dist/plugins/server-cookie.d.ts +14 -0
- package/dist/plugins/session.d.ts +25 -0
- package/dist/plugins/track.d.ts +16 -0
- package/dist/plugins/utm.d.ts +16 -0
- package/dist/td-sdk.cjs +3263 -0
- package/dist/td-sdk.esm.js +3263 -0
- package/dist/td-sdk.esm.min.js +1 -0
- package/dist/td-sdk.js +3176 -0
- package/dist/td-sdk.min.cjs +1 -0
- package/dist/td-sdk.min.js +1 -0
- package/dist/treasure.d.ts +198 -0
- package/dist/types/index.d.ts +177 -0
- package/dist/utils/element.d.ts +20 -0
- package/dist/utils/lodash.d.ts +18 -0
- package/dist/utils/misc.d.ts +17 -0
- package/dist/utils/set-cookie.d.ts +14 -0
- package/dist/utils/uuid.d.ts +14 -0
- package/dist/utils/xhr.d.ts +58 -0
- package/dist/vendor/js-cookies.d.ts +19 -0
- package/package.json +90 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
function createSDK(e){if(!e||"string"!=typeof e.writeKey||!e.writeKey)throw new Error("TreasureSDK: writeKey is required");if(!e.database)throw new Error("TreasureSDK: database is required");const t={debug:(...t)=>{e.development},warn:(...e)=>{},error:(...e)=>{}},n={config:{...e},log:t},o={...n,use(e){n.log.debug(`Loading plugin: ${e.name}`);const t=e.setup(n,o);for(const n of Object.keys(t))if(n in o)throw new Error(`TreasureSDK: plugin "${e.name}" conflicts on "${n}"`);return Object.assign(o,t),o},getWriteKey:()=>n.config.writeKey,setWriteKey(e){if(!e||"string"!=typeof e)throw new Error("TreasureSDK: writeKey must be a non-empty string");n.config.writeKey=e}};return o}function isObject$1(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function isString(e){return"string"==typeof e}function isArray(e){return Array.isArray(e)}function isEmpty(e){return null==e||(isArray(e)||isString(e)?0===e.length:!!isObject$1(e)&&0===Object.keys(e).length)}function assign(e,...t){return Object.assign(e,...t)}function omit(e,...t){const n={...e};return t.forEach(e=>delete n[e]),n}function disposable(e){let t=!1;return function(){t||(t=!0,e())}}function invariant$1(e,t){if(!e)throw new Error(t)}function isLocalStorageAccessible(){const e="__td__";try{return localStorage.setItem(e,e),localStorage.removeItem(e),!0}catch{return!1}}const adlHeaders={"Content-Type":"application/vnd.treasuredata.v1+json",Accept:"application/vnd.treasuredata.v1+json"},globalIdAdlHeaders={"Content-Type":"application/vnd.treasuredata.v1.js+json",Accept:"application/vnd.treasuredata.v1.js+json"},CONFIG={VERSION:"1.0.0",HOST:"us01.records.in.treasuredata.com",DATABASE:"",PATHNAME:"/"};function encode(e){try{return encodeURIComponent(e)}catch(e){return null}}function decode(e){try{return decodeURIComponent(e)}catch(e){return null}}function handleSkey(e){const t=encode(e);return t?t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&"):""}const cookie={getItem(e){if(!e)return null;const t=new RegExp("(?:(?:^|.*;)\\s*"+handleSkey(e)+"\\s*\\=\\s*([^;]*).*$)|^.*$");return decode(document.cookie.replace(t,"$1"))||null},setItem(e,t,n,o,r,i,a){if(!e||/^(?:expires|max\-age|path|domain|secure)$/i.test(e))return!1;let s="";n&&("number"==typeof n?s=n===1/0?"; expires=Fri, 31 Dec 9999 23:59:59 GMT":"; max-age="+n:"string"==typeof n?s="; expires="+n:n instanceof Date&&(s="; expires="+n.toUTCString()));let c="";a&&"NONE"===a.toUpperCase()?c="; Secure; SameSite="+a:(i&&(c+="; Secure"),a&&(c+="; SameSite="+a));const l=encode(e),u=encode(t);return!(!l||!u)&&(document.cookie=[l,"=",u,s,r?"; domain="+r:"",o?"; path="+o:"",c].join(""),!0)},removeItem(e,t,n){if(!this.hasItem(e))return!1;const o=encode(e);return!!o&&(document.cookie=[o,"=; expires=Thu, 01 Jan 1970 00:00:00 GMT",n?"; domain="+n:"",t?"; path="+t:""].join(""),!0)},hasItem(e){if(!e)return!1;const t=encode(e);return!!t&&new RegExp("(?:^|;\\s*)"+t.replace(/[\\^$.*+?()[\]{}|]/g,"\\$&")+"\\s*\\=").test(document.cookie)},keys:()=>document.cookie.replace(/((?:^|\s*;)[^=]+)(?=;|$)|^\s*|\s*(?:=[^;]*)?(?:\1|$)/g,"").split(/\s*(?:=[^;]*)?;\s*/).map(e=>decode(e)).filter(e=>null!==e)};function validateOptions(e){invariant$1(isObject$1(e),"Check out our JavaScript SDK Usage Guide: https://github.com/treasure-data/td-js-sdk#api"),invariant$1(isString(e.writeKey),"Must provide a writeKey"),invariant$1(isString(e.database),"Must provide a database"),invariant$1(e.database&&/^[a-z0-9_]{3,255}$/.test(e.database),"Database must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _")}function defaultSSCCookieDomain(){if("undefined"==typeof document)return"localhost";const e=document.location.hostname.split(".");for(let t=e.length-2;t>=1;t--){const n=e.slice(t).join("."),o="_td_domain_"+n;if(cookie.setItem(o,n,3600,"/",n),cookie.getItem(o)===n)return n}return document.location.hostname}const DEFAULT_CONFIG={database:CONFIG.DATABASE,development:!1,globalIdCookie:"_td_global",host:CONFIG.HOST,logging:!0,pathname:CONFIG.PATHNAME,requestType:"fetch",jsonpTimeout:1e4,startInSignedMode:!1,useServerSideCookie:!1,sscDomain:defaultSSCCookieDomain,sscServer:function(e){return["ssc",e].join(".")},storeConsentByLocalStorage:!1};function configure(e){const t=assign({},{globals:{}},DEFAULT_CONFIG,e,{requestType:"fetch"});return validateOptions(t),t.endpoint||(t.endpoint="https://"+t.host+t.pathname),t.storage||(t.storage={name:"_td",domain:"undefined"!=typeof window&&"undefined"!=typeof document?document.location.hostname:"localhost",expires:63072e3,path:"/"}),t}function findDomains(e){const t=e.split("."),n=[];for(let e=t.length-1;e>=0;e--)n.push(t.slice(e).join("."));return n}function setCookie(e,t,n){const o={...e},r=e.domain.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/),i="localhost"===e.domain,a=e.customDomain,s=new Date;if(s.setSeconds(s.getSeconds()+o.expires),i)n?cookie.setItem(t,n,s,o.path):cookie.removeItem(t,o.path,o.domain);else if(r||a)n?cookie.setItem(t,n,s,o.path,o.domain,!0,"None"):cookie.removeItem(t,o.path,o.domain);else{const r=findDomains(e.domain),i=r.length;let a=0;if(n){if(cookie.getItem(t)===n)return;for(;a<i;a++)if(o.domain=r[a],cookie.setItem(t,n,s,o.path,o.domain,!0,"None"),cookie.getItem(t)===n){e.domain=o.domain;break}}else for(;a<i;a++)cookie.removeItem(t,e.path,r[a])}}function generateUUID$1(){if("undefined"!=typeof crypto&&crypto.randomUUID)return crypto.randomUUID();if("undefined"!=typeof crypto&&crypto.getRandomValues){const e=new Uint8Array(16);crypto.getRandomValues(e),e[6]=15&e[6]|64,e[8]=63&e[8]|128;const t=Array.from(e,e=>e.toString(16).padStart(2,"0")).join("");return`${t.slice(0,8)}-${t.slice(8,12)}-${t.slice(12,16)}-${t.slice(16,20)}-${t.slice(20)}`}throw new Error("Secure random number generation is not available in this environment")}function isValidUUID(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(e)}const FETCH_CREDENTIALS={"same-origin":"same-origin",include:"include",omit:"omit"};function toJSON(e){let t;try{t=JSON.parse(e)}catch{t={}}return t}function getCredentials(e={}){return FETCH_CREDENTIALS[e.credentials||"include"]||"include"}function post(e,t,n={}){const o=n.headers||{},r=getCredentials(n),i={method:"POST",headers:o,keepalive:!0,body:JSON.stringify(t)};return i.credentials=r,n.signal&&(i.signal=n.signal),fetch(e,i).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return toJSON(e)})}function get(e,t={}){const n=t.headers||{},o=getCredentials(t),r={method:"GET",headers:n};return r.credentials=o,t.signal&&(r.signal=t.signal),fetch(e,r).then(function(e){if(!e.ok)throw new Error(`HTTP ${e.status}: ${e.statusText}`);return e.text()}).then(function(e){return toJSON(e)})}function withTimeout(e,t,n){const o=new AbortController;let r;const i=new Promise((e,i)=>{r=setTimeout(()=>{o.abort(),i(new Error(n||"Operation Timeout"))},t)}),a=e(o.signal).finally(()=>{clearTimeout(r)});return Promise.race([a,i]).catch(e=>{if(clearTimeout(r),"AbortError"===e.name)throw new Error(n||"Operation Timeout");throw e})}function postWithTimeout(e,t,n,o={}){return withTimeout(n=>post(e,t,{...o,signal:n}),n,"Request Timeout")}function getWithTimeout(e,t,n={}){return withTimeout(t=>get(e,{...n,signal:t}),t,"Request Timeout")}function timeoutPromise(e,t,n){return withTimeout(t=>e(),t,n)}const api={post:post,get:get,postWithTimeout:postWithTimeout,getWithTimeout:getWithTimeout,withTimeout:withTimeout,timeoutPromise:timeoutPromise},SERVER_COOKIE_NAME="_td_ssc_id",COOKIE_NAME=SERVER_COOKIE_NAME;function serverCookie(){return{name:"serverCookie",setup(e,t){const n=e.config;let o,r;const i=()=>{};return{fetchServerCookie:function(e,a,s=!1){const c=e||i,l=a||i;if("function"==typeof t.inSignedMode&&!t.inSignedMode())return l("not in signed in mode");if(!n.useServerSideCookie)return l("server side cookie not enabled");if(r||(o="function"==typeof n.sscDomain?n.sscDomain():n.sscDomain||("undefined"!=typeof window?window.location.hostname:"localhost"),r="function"==typeof n.sscServer?n.sscServer(o):n.sscServer||`ssc.${o}`),!o||!r)return l("server cookie configuration not properly initialized");const u=`https://${r}/get_cookie_id?cookie_domain=${encodeURIComponent(o)}&r=${Date.now()}`,d=cookie.getItem(COOKIE_NAME);!d||s?api.getWithTimeout(u,1e4).then(e=>{c(e.td_ssc_id)}).catch(e=>{l(e)}):setTimeout(()=>{c(d)},0)}}}}}const BLOCKEVENTSCOOKIE="__td_blockEvents",SIGNEDMODECOOKIE="__td_signed";function configureStorage(e){if("none"===e)return null;const t="object"==typeof e&&null!==e?e:{};return{name:t.name||"_td",expires:t.expires??63072e3,domain:t.domain||document.location.hostname,customDomain:!!t.domain,path:t.path||"/"}}function setStorageCookie(e,t,n){try{setCookie(e,t,n||"")}catch{}}function session(){return{name:"session",setup(e,t){const n=e.config,o=n.startInSignedMode??!1,r=n.storeConsentByLocalStorage??!1,i={};function a(e,t){const n=e||"$global";return i[n]=i[n]||{},t?i[n]?.[t]??null:i[n]}const s=configureStorage(n.storage);let c;null!=n.clientId&&(c="number"==typeof n.clientId?n.clientId.toString():n.clientId),c&&"string"==typeof c||(s?.name&&"undefined"!=typeof document&&(c=cookie.getItem(s.name)??void 0),c&&"undefined"!==c||(c=generateUUID$1()));let l=c.replace(/\0/g,"");function u(){return l}function d(e,t){if(cookie.getItem(e.name)!==t)try{setCookie(e,e.name,t)}catch{}}function p(e,t){l=(t||generateUUID$1()).replace(/\0/g,"");const o=e||n.storage;if(o&&"object"==typeof o){const e=configureStorage(o);e?.expires&&g()&&d(e,l)}}function g(){if(r){if(!isLocalStorageAccessible())return o;const e=localStorage.getItem("__td_signed");return"false"!==e&&("true"===e||o)}if("undefined"==typeof document)return o;const e=cookie.getItem("__td_signed");return"false"!==e&&("true"===e||o)}function f(){if(i.$global&&delete i.$global.td_global_id,n.storage&&"object"==typeof n.storage){const e=n.globalIdCookie||"_td_global";setStorageCookie(n.storage,e,"")}if(isLocalStorageAccessible()){const e=n.globalIdCookie||"_td_global";try{localStorage.removeItem(e)}catch{}}}return s?.expires&&g()&&d(s,l),{inSignedMode:g,setSignedMode:function(){r?isLocalStorageAccessible()&&localStorage.setItem("__td_signed","true"):n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,"__td_signed","true");const e=u();p(n.storage,e)},setAnonymousMode:function(e){r?isLocalStorageAccessible()&&localStorage.setItem("__td_signed","false"):n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,"__td_signed","false"),e||(n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,n.storage.name),f(),t.removeServerCookie())},blockEvents:function(){n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,BLOCKEVENTSCOOKIE,"true")},unblockEvents:function(){n.storage&&"object"==typeof n.storage&&setStorageCookie(n.storage,BLOCKEVENTSCOOKIE,"false")},areEventsBlocked:function(){return"true"===cookie.getItem(BLOCKEVENTSCOOKIE)},getUUID:u,resetUUID:p,set:function(e,t,n){let o,r=t;"object"==typeof e&&null!==e?(r=e,o="$global"):o=e;const a=i[o]||{};i[o]=a,"object"==typeof r&&null!==r?Object.assign(a,r):"string"==typeof r&&void 0!==n&&(a[r]=n)},get:a,removeCachedGlobalID:f,removeServerCookie:function(){if(n.storage&&"object"==typeof n.storage){setStorageCookie(n.storage,SERVER_COOKIE_NAME,"");["__td_ssc","_td_ssc"].forEach(e=>{setStorageCookie(n.storage,e,"")}),n.useServerSideCookie&&n.globalIdCookie&&setStorageCookie(n.storage,n.globalIdCookie,"")}isLocalStorageAccessible()&&[SERVER_COOKIE_NAME,"__td_ssc","_td_ssc"].forEach(e=>{try{localStorage.removeItem(e)}catch{}})},isGlobalIdEnabled:function(){return"td_global_id"===a(void 0,"td_global_id")}}}}}const DEFAULT_HOST="us01.records.in.treasuredata.com",DEFAULT_PATHNAME="/";function validateRecord(e,t){invariant$1(isString(e),"Must provide a table"),invariant$1(/^[a-z0-9_]{3,255}$/.test(e),"Table must be between 3 and 255 characters and must consist only of lower case letters, numbers, and _"),invariant$1(isObject$1(t),"Must provide a record")}const _validateRecord=validateRecord;function record(){return{name:"record",setup(e,t){const n=e.config,o=n.host||DEFAULT_HOST,r=n.pathname||"/",i=n.endpoint||`https://${o}${r}`;let a=!1;if("undefined"!=typeof window&&window.addEventListener){const t=()=>{a=!0};window.addEventListener("beforeunload",t),window.addEventListener("unload",t),e._unloadHandlers=[()=>window.removeEventListener("beforeunload",t),()=>window.removeEventListener("unload",t)]}e._windowBeingUnloaded=()=>a;return{addRecord(o,r,a,s,c){validateRecord(o,r);const l=function(e,n){return Object.assign({},t.get("$global"),t.get(e),n)}(o,r),u=t.inSignedMode()?l:omitKeys(l,["td_ip","td_client_id","td_global_id"]),d={apikey:n.writeKey,record:u,time:null,url:`${i}${c?.database??n.database}/${o}`};null!=d.record.time&&(d.time=d.record.time),n.development?(e.log.debug("addRecord",d),a?.({success:!0,message:"Development mode - record not sent"})):t.areEventsBlocked()||submitRecord({...d,inSignedMode:t.inSignedMode(),isGlobalIdEnabled:t.isGlobalIdEnabled(),windowBeingUnloaded:e._windowBeingUnloaded?.()??!1,timeoutMs:n.jsonpTimeout??6e4},a,s)}}}}}function omitKeys(e,t){const n={};for(const o of Object.keys(e))if(!t.includes(o)){const t=e[o];void 0!==t&&(n[o]=t)}return n}async function submitRecord(e,t,n){const o=()=>{},r=t||o,i=n||o,a=["modified="+encodeURIComponent((new Date).getTime())];e.time&&a.push("time="+encodeURIComponent(e.time));const s=e.url+"?"+a.join("&"),c="a"===e.record.tag&&!!e.record.href,l={};l.Authorization="TD1 "+e.apikey,"undefined"!=typeof navigator&&(l["User-Agent"]=navigator.userAgent),e.inSignedMode&&e.isGlobalIdEnabled?Object.assign(l,globalIdAdlHeaders):Object.assign(l,adlHeaders);const u={events:[e.record]};try{if("undefined"!=typeof window&&(e.windowBeingUnloaded||c)){r(await api.postWithTimeout(s,u,e.timeoutMs,{headers:l,credentials:"include"}))}else{r(await api.post(s,u,{headers:l,credentials:"include"}))}}catch(e){i(e instanceof Error?{...e,name:e.name,message:e.message}:new Error("Unknown error occurred"))}}const POPUP_CONTAINER_ID="td-engage-popup-container";let inlineObserver=null,navigationCleanupInstalled=!1,accumulatedInline=[];function parseAppearance(e){if("object"==typeof e&&null!==e)return e;try{return JSON.parse(e)}catch{return{}}}function parseMessages(e){try{const t=e["td_in_browser.messages"];return t?JSON.parse(t):[]}catch{return[]}}function removeExistingPopup(){document.getElementById(POPUP_CONTAINER_ID)?.remove()}function isPopupDisplayed(){return null!==document.getElementById(POPUP_CONTAINER_ID)}function resetForNavigation(){removeExistingPopup(),inlineObserver&&(inlineObserver.disconnect(),inlineObserver=null),accumulatedInline=[]}function ensureNavigationCleanup(){if(!navigationCleanupInstalled&&"undefined"!=typeof window&&window.history){window.addEventListener("popstate",resetForNavigation),window.addEventListener("hashchange",resetForNavigation);try{const e=e=>{const t=window.history[e];window.history[e]=function(...e){const n=t.apply(this,e);return resetForNavigation(),n}};e("pushState"),e("replaceState")}catch{}navigationCleanupInstalled=!0}}function renderPopup(e){try{const t=parseAppearance(e.appearance_setting),n=window.innerWidth>620;removeExistingPopup();const o=t.position?.placement??"center",r=o.startsWith("top"),i=o.startsWith("bottom"),a=o.endsWith("left"),s=o.endsWith("right"),c=n?t.inset?.desktop??40:t.inset?.mobile??16,l=n?t.width?.desktop_max_width??600:t.width?.mobile_max_width??300,u=document.createElement("div");u.id=POPUP_CONTAINER_ID;const d=i?"end":r?"start":"center",p=a?"start":s?"end":"center";Object.assign(u.style,{position:!1===t.position?.fixed_on_scroll?"absolute":"fixed",inset:"0",display:"grid",placeItems:`${d} ${p}`,padding:`${c}px`,pointerEvents:"none",boxSizing:"border-box"}),u.style.setProperty("z-index","var(--td-popup-z-index, 2147483647)");const g=u.attachShadow({mode:"open"}),f=document.createElement("style");if(f.textContent="\n :host { --td-popup-z-index: 2147483647; --td-popup-frame-z-index: 1; --td-close-btn-cursor: pointer; --td-close-btn-line-height: 1; }\n .td-overlay { position: fixed; inset: 0; pointer-events: auto; }\n .td-frame { position: relative; width: 100%; pointer-events: auto; box-sizing: border-box; z-index: var(--td-popup-frame-z-index); }\n .td-close { position: absolute; background: transparent; border: none; cursor: var(--td-close-btn-cursor); line-height: var(--td-close-btn-line-height); padding: 0; display: flex; align-items: center; justify-content: center; z-index: 1; }\n ",g.appendChild(f),t.overlay?.enabled){const e=document.createElement("div");e.className="td-overlay",Object.assign(e.style,{background:t.overlay.color??"#000000B3"}),t.overlay.close_on_click_outside&&e.setAttribute("data-engage-popup-close",""),g.appendChild(e)}const m=document.createElement("div");m.className="td-frame";const _=t.background?.padding??0;if(Object.assign(m.style,{maxWidth:`${l}px`,background:t.background?.color??"#FFFFFF",borderRadius:`${t.background?.border_radius??8}px`,padding:`${_}px`}),!1!==t.close_button?.enabled){const e=t.close_button?.size??28,n=t.close_button?.offset_top??2,o=t.close_button?.offset_right??4,r=document.createElement("button");r.type="button",r.className="td-close",r.setAttribute("aria-label","Close"),r.setAttribute("data-engage-popup-close",""),Object.assign(r.style,{top:`${n}px`,right:`${o}px`,width:`${e}px`,height:`${e}px`,fontSize:.7*e+"px",color:t.close_button?.color??"#FFFFFF"}),r.textContent="×",m.appendChild(r)}const h=document.createElement("div");h.innerHTML=e.content_html,m.appendChild(h),g.appendChild(m),g.addEventListener("click",e=>{e.target.hasAttribute("data-engage-popup-close")&&u.remove()}),document.body.appendChild(u)}catch{}}function renderInline(e){if(e.css_selector)try{const t=document.querySelectorAll(e.css_selector);for(const n of t)n.innerHTML=e.content_html}catch{}}function compareMessages(e,t){const n=Number(t.created_at_millisecond??0)-Number(e.created_at_millisecond??0);if(0!==n)return n;const o=t._sectionName.localeCompare(e._sectionName);return 0!==o?o:t._arrayIndex-e._arrayIndex}function sortedInlineMessages(e){return e.filter(e=>"inline"===e.type&&e.css_selector).sort((e,t)=>-compareMessages(e,t))}function pickPopup(e){return e.filter(e=>"popup"===e.type).sort(compareMessages)[0]}function applyAccumulatedInline(){for(const e of accumulatedInline)renderInline(e)}function setupInlineObserver(){inlineObserver&&(inlineObserver.disconnect(),inlineObserver=null),0!==accumulatedInline.length&&(inlineObserver=new MutationObserver(()=>{inlineObserver.disconnect(),applyAccumulatedInline(),inlineObserver.observe(document.body,{childList:!0,subtree:!0})}),inlineObserver.observe(document.body,{childList:!0,subtree:!0}))}function extractMessages(e){const t=e.offers;if(!t)return[];const n=[];for(const[e,o]of Object.entries(t)){const t=o?.td_app;if(!t)continue;parseMessages(t).forEach((t,o)=>{n.push({...t,_sectionName:e,_arrayIndex:o})})}return n}function handlePersonalizationResponse(e){try{const t=extractMessages(e);if(0===t.length)return;if(ensureNavigationCleanup(),!isPopupDisplayed()){const e=pickPopup(t);e&&renderPopup(e)}const n=sortedInlineMessages(t);n.length>0&&(accumulatedInline.push(...n),applyAccumulatedInline(),setupInlineObserver())}catch{}}function configureValues(e,t){return{td_version:()=>t,td_client_id:e,td_charset:()=>(document.characterSet||document.charset||"-").toLowerCase(),td_language:()=>{const e=navigator;return(e&&(e.language||e.browserLanguage)||"-").toLowerCase()},td_color:()=>screen?screen.colorDepth+"-bit":"-",td_screen:()=>screen?`${screen.width}x${screen.height}`:"-",td_viewport:()=>{const e=document.documentElement&&document.documentElement.clientHeight,t=document.documentElement&&document.documentElement.clientWidth,n=window.innerHeight,o=window.innerWidth;return`${(t||0)<o?o:t||0}x${(e||0)<n?n:e||0}`},td_title:()=>document.title,td_description:()=>getMetaContent("description"),td_url:()=>document.location&&document.location.href&&document.location.href.split("#")[0]||"",td_user_agent:()=>[navigator.userAgent,`WEBSDK/${t}`].join(";"),td_platform:()=>navigator.platform||navigator.userAgentData?.platform||"-",td_host:()=>document.location.host,td_path:()=>document.location.pathname,td_referrer:()=>document.referrer}}function getMetaContent(e){const t=(document.head||document.getElementsByTagName("head")[0]).getElementsByTagName("meta"),n=t.length;for(let o=0;o<n;o++){const n=t[o];if(n&&n.getAttribute("name")===e)return(n.getAttribute("content")||"").substr(0,8192)}return""}function track(){return{name:"track",setup(e,t){const n=configureValues(()=>t.getUUID(),CONFIG.VERSION);function o(){const e={};for(const[t,o]of Object.entries(n))o&&(e[t]="function"==typeof o?o():o);return e}function r(n,r,i,a){const s=n||"events",c=o(),l=Object.assign(c,r),u=e.config.personalization;if(u){const n={endpoint:u.endpoint,database:u.database||e.config.database,table:s,token:u.token},i={...t.get("$global"),...t.get(s),...o(),...r};return void t.fetchPersonalization(n,i,e=>{handlePersonalizationResponse(e),"function"==typeof t.applyPersonalization&&t.applyPersonalization(e)},t=>{e.log.error("Personalization failed:",t)})}t.addRecord(s,l,i,a)}return{trackEvent:r,trackPageview:function(e,t,n,o){r(e||"pageviews",o?.payload??{},t,n)},getTrackValues:o,getPersonalizationConfig:function(){return e.config.personalization},setPersonalizationConfig:function(t){e.config.personalization=t}}}}}function getEventTarget(e){const t=e.target||e.srcElement||document;return 3===t.nodeType?t.parentNode:t}function addEventListener(e,t,n){if("addEventListener"in e)return e.addEventListener(t,o,!1),disposable(()=>{e.removeEventListener(t,o,!1)});if("attachEvent"in e)return e.attachEvent("on"+t,o),disposable(()=>{e.detachEvent("on"+t,o)});throw new Error("addEventListener not supported");function o(t){n.call(e,t||window.event)}}function htmlTreeAsString(e){const t=[];let n=0,o=0;let r,i=e;for(;i&&n++<5&&(r=htmlElementAsString(i),!("html"===r||n>1&&o+3*t.length+r.length>=80));)t.push(r),o+=r.length,i=i.parentNode;const a=t.reverse().join(" > ");return a.length>80?a.substring(0,77)+"...":a}function htmlElementAsString(e){const t=[];let n,o,r,i;if(!e||!e.tagName)return"";t.push(e.tagName.toLowerCase()),e.id&&t.push("#"+e.id);const a=e.className;if(a&&isString(a))for(n=a.split(" "),i=0;i<n.length;i++){const e=n[i];e&&e.trim()&&t.push("."+e.trim())}const s=["type","name","title","alt"];for(i=0;i<s.length;i++)o=s[i],r=e.getAttribute(o),r&&t.push("["+o+'="'+r+'"]');return t.join("")}function hasAttribute(e,t){return"function"==typeof e.hasAttribute?e.hasAttribute(t):null!==e.getAttribute(t)}const element=Object.freeze(Object.defineProperty({__proto__:null,addEventListener:addEventListener,getEventTarget:getEventTarget,hasAttribute:hasAttribute,htmlElementAsString:htmlElementAsString,htmlTreeAsString:htmlTreeAsString},Symbol.toStringTag,{value:"Module"}));function findElement(e){if(!e||!e.tagName)return null;let t=e,n=t.tagName.toLowerCase();for(;n&&"body"!==n&&t;){const e=t.getAttribute("type");if("input"===n&&"password"===e)return null;const o=t.getAttribute("role");if("button"===o||"link"===o||"a"===n||"button"===n||"input"===n)return t;t=t.parentNode,n=t&&t.tagName?t.tagName.toLowerCase():""}return null}function createTreeHasIgnoreAttribute(e){const t="data-"+e;return function n(o){return!(!o||!o.tagName||"html"===o.tagName.toLowerCase())&&(!(!hasAttribute(o,e)&&!hasAttribute(o,t))||n(o.parentNode))}}function getElementData(e){const t={tag:e.tagName.toLowerCase(),tree:htmlTreeAsString(e)};return["alt","class","href","id","name","role","title","type"].forEach(n=>{if(hasAttribute(e,n)){const o=e.getAttribute(n);o&&(t[n]=o)}}),t}function clicks(){return{name:"clicks",setup(e,t){let n=!1;return{trackClicks(e){if(n)return;const o={element:e?.element??window.document,extendClickData:e?.extendClickData??((e,t)=>t),ignoreAttribute:e?.ignoreAttribute??"td-ignore",tableName:e?.tableName??"clicks"},r=createTreeHasIgnoreAttribute(o.ignoreAttribute),i=addEventListener(o.element,"click",e=>{const n=findElement(getEventTarget(e));if(n&&!r(n)){const r=getElementData(n),i=o.extendClickData(e,r);i&&t.trackEvent(o.tableName,i)}});return n=!0,disposable(()=>{i(),n=!1})}}}}}const DEFAULT_UTM_PARAMS=["utm_id","utm_medium","utm_source_platform","utm_source","utm_campaign","utm_marketing_tactic"];function collectUTMParametersFromURL(e=DEFAULT_UTM_PARAMS){if("undefined"==typeof window||!window.location)return{};const t=window.location.search,n=new(window.URLSearchParams||URLSearchParams)(t);return e.some(e=>n.has(e))?e.reduce((e,t)=>{const o=n.get(t);return o&&(e[t]=o),e},{}):{}}function utm(e={}){return{name:"utm",setup(t,n){const o={customParameters:e.customParameters||DEFAULT_UTM_PARAMS,autoCollect:e.autoCollect??!0,table:e.table||"$global"};let r={};function i(){const e=collectUTMParametersFromURL(o.customParameters);return isObject$1(e)&&!isEmpty(e)&&("$global"===o.table?n.set(e):Object.keys(e).forEach(t=>{n.set(o.table,t,e[t])}),r={...r,...e}),e}return o.autoCollect&&i(),{getUTMParameters:function(){return{...r}},collectUTMParameters:i}}}}const DEFAULT_CDP_HOST="cdp.in.treasuredata.com";function invariant(e,t){if(!e)throw new Error(t)}function personalization(){return{name:"personalization",setup(e,t){const n=e.config.cdpHost||DEFAULT_CDP_HOST;return{fetchUserSegments:function(e,t,o){const r=()=>{},i=t||r,a=o||r,s=isObject$1(e)&&!isArray(e),c=s?e.audienceToken:e,l=s&&e.keys||{};invariant("string"==typeof c||isArray(c),`audienceToken must be a string or array; received "${String(c)}"`),invariant(isObject$1(l),`keys must be an object; received "${String(l)}"`);const u=isArray(c)?c.join(","):c,d=[];Object.keys(l).forEach(e=>{d.push(`key.${e}=${String(l[e])}`)});const p=d.join("&"),g=`https://${n}/cdp/lookup/collect/segments?version=2&token=${u}${p?"&"+p:""}`;api.getWithTimeout(g,1e4,{headers:{"Content-Type":"application/json"}}).then(i).catch(a)},fetchPersonalization:function(n,o,r,i){const a=()=>{},s=r||a,c=i||a;if(invariant(isObject$1(n),`config must be an object, received "${String(n)}"`),invariant(!!n.endpoint,"endpoint is invalid"),invariant(!!n.database,"database is invalid"),invariant(!!n.table,"table is invalid"),invariant(!!n.token,"token is invalid"),"function"==typeof t.areEventsBlocked&&t.areEventsBlocked())return;const l=`https://${n.endpoint}/public/${n.database}/${n.table}`;let u=o||{};"function"!=typeof t.inSignedMode||t.inSignedMode()||(u=omit(u,"td_ip","td_client_id","td_global_id")),api.postWithTimeout(l,u,1e4,{headers:{"Content-Type":"application/vnd.treasuredata.v1+json",Authorization:`TD1 ${e.config.writeKey}`,"WP13n-Token":n.token}}).then(s).catch(c)}}}}}const VENDOR_FUNCTION_MAPPINGS={google_ads:["getGoogle_gclid_Param","getGoogle_wbraid_Param"],google_ga:["getGoogle_ga_Cookie"],google_mp:["getGoogle_gcl_Cookies"],meta:["getFacebook_fbp_Cookie","getFacebook_fbc_Cookie","getFacebook_fbclid_Param"],instagram:["getInstagram_shbts_Cookie","getInstagram_shbid_Cookie","getInstagram_ds_user_id_Cookie","getInstagram_ig_did_Cookie"],yahoojp_ads:["getYahoo_ly_c_Param","getYahoo_ly_c_Cookie","getYahoo_ly_r_Cookie","getYahoo_ly_su_Cookie","getYahoo_yclid_Param","getYahoo_yj_r_Param","getYahoo_ycl_yjad_Cookie","getYahoo_yjr_yjad_Cookie","getYahoo_yjsu_yjad_Cookie"],line:["getLine_lt_cid_Cookie","getLine_lt_sid_Cookie","getLine_ldtag_cl_Param"],x:["getX_twclid_Param","getX_twclid_Cookie"],pinterest:["getPinterest_epik_Param","getPinterest_epik_Cookie"],snapchat:["getSnapchat_sccid_Param"],tiktok:["getTiktok_ttp_Cookie"],marketo:["getMarketo_mkto_trk_Cookie"],tealium:["getTealium_utag_main_Cookie"]};function getCookie(e){return"undefined"==typeof document?null:cookie.getItem(e)}function getCookieByNamePrefix(e){return"undefined"==typeof document?{}:cookie.keys().filter(t=>t.startsWith(e)).reduce((e,t)=>{const n=cookie.getItem(t);return null!==n&&(e[t]=n),e},{})}function getParam(e){if("undefined"==typeof window||!window.location)return null;const t=window.location.search;return new(window.URLSearchParams||URLSearchParams)(t).get(e)}function conversionAPI(){return{name:"conversionAPI",setup(e,t){const n={getGoogle_gclid_Param:()=>({gclid:getParam("gclid")}),getGoogle_wbraid_Param:()=>({wbraid:getParam("wbraid")}),getGoogle_ga_Cookie:()=>({_ga:getCookie("_ga")}),getGoogle_gcl_Cookies:(e={})=>getCookieByNamePrefix(e.gclPrefix||"_gcl"),getFacebook_fbp_Cookie:()=>({_fbp:getCookie("_fbp")}),getFacebook_fbc_Cookie:()=>({_fbc:getCookie("_fbc")}),getFacebook_fbclid_Param:()=>({fbclid:getParam("fbclid")}),getInstagram_shbts_Cookie:()=>({shbts:getCookie("shbts")}),getInstagram_shbid_Cookie:()=>({shbid:getCookie("shbid")}),getInstagram_ds_user_id_Cookie:()=>({ds_user_id:getCookie("ds_user_id")}),getInstagram_ig_did_Cookie:()=>({ig_did:getCookie("ig_did")}),getYahoo_yclid_Param:()=>({yclid:getParam("yclid")}),getYahoo_yj_r_Param:()=>({yj_r:getParam("yj_r")}),getYahoo_ycl_yjad_Cookie:()=>({_ycl_yjad:getCookie("_ycl_yjad")}),getYahoo_yjr_yjad_Cookie:()=>({_yjr_yjad:getCookie("_yjr_yjad")}),getYahoo_yjsu_yjad_Cookie:()=>({_yjsu_yjad:getCookie("_yjsu_yjad")}),getYahoo_ly_c_Param:()=>({ly_c:getParam("_ly_c")}),getYahoo_ly_c_Cookie:()=>({ly_c:getCookie("_ly_c")}),getYahoo_ly_r_Cookie:()=>({ly_r:getCookie("_ly_r")}),getYahoo_ly_su_Cookie:()=>({ly_su:getCookie("_ly_su")}),getLine_lt_cid_Cookie:()=>({__lt_cid:getCookie("__lt__cid")}),getLine_lt_sid_Cookie:()=>({__lt_sid:getCookie("__lt__sid")}),getLine_ldtag_cl_Param:()=>({ldtag_cl:getParam("ldtag_cl")}),getX_twclid_Param:()=>({twclid:getParam("twclid")}),getX_twclid_Cookie:()=>({_twclid:getCookie("_twclid")}),getPinterest_epik_Param:()=>({epik:getParam("epik")}),getPinterest_epik_Cookie:()=>({_epik:getCookie("_epik")}),getSnapchat_sccid_Param:()=>({ScCid:getParam("ScCid")}),getTiktok_ttp_Cookie:()=>({_ttp:getCookie("_ttp")}),getMarketo_mkto_trk_Cookie:()=>({_mkto_trk:getCookie("_mkto_trk")}),getTealium_utag_main_Cookie:()=>({utag_main:getCookie("utag_main")})};return{collectTags:function(e={},o={}){const r=isEmpty(e.vendors)&&isEmpty(e.cookies)&&isEmpty(e.params);let i={};isEmpty(e)||r?i=function(e={}){const t={};return Object.keys(VENDOR_FUNCTION_MAPPINGS).forEach(o=>{const r=VENDOR_FUNCTION_MAPPINGS[o];r&&r.forEach(o=>{const r=n[o](e);Object.assign(t,r)})}),Object.keys(t).reduce((e,n)=>(t[n]&&(e[n]=t[n]),e),{})}(o):(isEmpty(e.vendors)||Object.assign(i,function(e=[],t={}){return e.reduce((e,o)=>((VENDOR_FUNCTION_MAPPINGS[o]||[]).forEach(o=>{const r=n[o](t);Object.assign(e,r)}),e),{})}(e.vendors,o)),isEmpty(e.cookies)||Object.assign(i,function(e=[]){return e.reduce((e,t)=>(e[t]=getCookie(t),e),{})}(e.cookies)),isEmpty(e.params)||Object.assign(i,function(e=[]){return e.reduce((e,t)=>(e[t]=getParam(t),e),{})}(e.params))),Object.keys(i).forEach(e=>{const n=i[e];n&&t.set({[e]:n})})}}}}}const MODE_QUERY_PARAM="td-personalization-mode",INIT_MESSAGE_TYPE="td:p13n-studio:init",READY_MESSAGE_TYPE="td:p13n-studio:ready",PROD_ORIGINS=["https://console-development-next.us01.treasuredata.com","https://console-staging-next.us01.treasuredata.com","https://console-next.us01.treasuredata.com","https://console-staging-next.treasuredata.co.jp","https://console-next.treasuredata.co.jp","https://console-development-next.eu01.treasuredata.com","https://console-next.eu01.treasuredata.com","https://console-next.ap02.treasuredata.com","https://console-staging-next.ap03.treasuredata.com","https://console-next.ap03.treasuredata.com"],ALLOWED_PARENT_ORIGINS=Object.freeze([...PROD_ORIGINS]),proxyMarker=Symbol("Comlink.proxy"),createEndpoint=Symbol("Comlink.endpoint"),releaseProxy=Symbol("Comlink.releaseProxy"),finalizer=Symbol("Comlink.finalizer"),throwMarker=Symbol("Comlink.thrown"),isObject=e=>"object"==typeof e&&null!==e||"function"==typeof e,proxyTransferHandler={canHandle:e=>isObject(e)&&e[proxyMarker],serialize(e){const{port1:t,port2:n}=new MessageChannel;return expose(e,t),[n,[n]]},deserialize:e=>(e.start(),wrap(e))},throwTransferHandler={canHandle:e=>isObject(e)&&throwMarker in e,serialize({value:e}){let t;return t=e instanceof Error?{isError:!0,value:{message:e.message,name:e.name,stack:e.stack}}:{isError:!1,value:e},[t,[]]},deserialize(e){if(e.isError)throw Object.assign(new Error(e.value.message),e.value);throw e.value}},transferHandlers=new Map([["proxy",proxyTransferHandler],["throw",throwTransferHandler]]);function isAllowedOrigin(e,t){for(const n of e){if(t===n||"*"===n)return!0;if(n instanceof RegExp&&n.test(t))return!0}return!1}function expose(e,t=globalThis,n=["*"]){t.addEventListener("message",function o(r){if(!r||!r.data)return;if(!isAllowedOrigin(n,r.origin))return;const{id:i,type:a,path:s}=Object.assign({path:[]},r.data),c=(r.data.argumentList||[]).map(fromWireValue);let l;try{const t=s.slice(0,-1).reduce((e,t)=>e[t],e),n=s.reduce((e,t)=>e[t],e);switch(a){case"GET":l=n;break;case"SET":t[s.slice(-1)[0]]=fromWireValue(r.data.value),l=!0;break;case"APPLY":l=n.apply(t,c);break;case"CONSTRUCT":l=proxy(new n(...c));break;case"ENDPOINT":{const{port1:t,port2:n}=new MessageChannel;expose(e,n),l=transfer(t,[t])}break;case"RELEASE":l=void 0;break;default:return}}catch(e){l={value:e,[throwMarker]:0}}Promise.resolve(l).catch(e=>({value:e,[throwMarker]:0})).then(n=>{const[r,s]=toWireValue(n);t.postMessage(Object.assign(Object.assign({},r),{id:i}),s),"RELEASE"===a&&(t.removeEventListener("message",o),closeEndPoint(t),finalizer in e&&"function"==typeof e[finalizer]&&e[finalizer]())}).catch(e=>{const[n,o]=toWireValue({value:new TypeError("Unserializable return value"),[throwMarker]:0});t.postMessage(Object.assign(Object.assign({},n),{id:i}),o)})}),t.start&&t.start()}function isMessagePort(e){return"MessagePort"===e.constructor.name}function closeEndPoint(e){isMessagePort(e)&&e.close()}function wrap(e,t){const n=new Map;return e.addEventListener("message",function(e){const{data:t}=e;if(!t||!t.id)return;const o=n.get(t.id);if(o)try{o(t)}finally{n.delete(t.id)}}),createProxy(e,n,[],t)}function throwIfProxyReleased(e){if(e)throw new Error("Proxy has been released and is not useable")}function releaseEndpoint(e){return requestResponseMessage(e,new Map,{type:"RELEASE"}).then(()=>{closeEndPoint(e)})}const proxyCounter=new WeakMap,proxyFinalizers="FinalizationRegistry"in globalThis&&new FinalizationRegistry(e=>{const t=(proxyCounter.get(e)||0)-1;proxyCounter.set(e,t),0===t&&releaseEndpoint(e)});function registerProxy(e,t){const n=(proxyCounter.get(t)||0)+1;proxyCounter.set(t,n),proxyFinalizers&&proxyFinalizers.register(e,t,e)}function unregisterProxy(e){proxyFinalizers&&proxyFinalizers.unregister(e)}function createProxy(e,t,n=[],o=function(){}){let r=!1;const i=new Proxy(o,{get(o,a){if(throwIfProxyReleased(r),a===releaseProxy)return()=>{unregisterProxy(i),releaseEndpoint(e),t.clear(),r=!0};if("then"===a){if(0===n.length)return{then:()=>i};const o=requestResponseMessage(e,t,{type:"GET",path:n.map(e=>e.toString())}).then(fromWireValue);return o.then.bind(o)}return createProxy(e,t,[...n,a])},set(o,i,a){throwIfProxyReleased(r);const[s,c]=toWireValue(a);return requestResponseMessage(e,t,{type:"SET",path:[...n,i].map(e=>e.toString()),value:s},c).then(fromWireValue)},apply(o,i,a){throwIfProxyReleased(r);const s=n[n.length-1];if(s===createEndpoint)return requestResponseMessage(e,t,{type:"ENDPOINT"}).then(fromWireValue);if("bind"===s)return createProxy(e,t,n.slice(0,-1));const[c,l]=processArguments(a);return requestResponseMessage(e,t,{type:"APPLY",path:n.map(e=>e.toString()),argumentList:c},l).then(fromWireValue)},construct(o,i){throwIfProxyReleased(r);const[a,s]=processArguments(i);return requestResponseMessage(e,t,{type:"CONSTRUCT",path:n.map(e=>e.toString()),argumentList:a},s).then(fromWireValue)}});return registerProxy(i,e),i}function myFlat(e){return Array.prototype.concat.apply([],e)}function processArguments(e){const t=e.map(toWireValue);return[t.map(e=>e[0]),myFlat(t.map(e=>e[1]))]}const transferCache=new WeakMap;function transfer(e,t){return transferCache.set(e,t),e}function proxy(e){return Object.assign(e,{[proxyMarker]:!0})}function toWireValue(e){for(const[t,n]of transferHandlers)if(n.canHandle(e)){const[o,r]=n.serialize(e);return[{type:"HANDLER",name:t,value:o},r]}return[{type:"RAW",value:e},transferCache.get(e)||[]]}function fromWireValue(e){switch(e.type){case"HANDLER":return transferHandlers.get(e.name).deserialize(e.value);case"RAW":return e.value}}function requestResponseMessage(e,t,n,o){return new Promise(r=>{const i=generateUUID();t.set(i,r),e.start&&e.start(),e.postMessage(Object.assign({id:i},n),o)})}function generateUUID(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}function onParentPort(e){let t=null;const n=o=>{if(!ALLOWED_PARENT_ORIGINS.includes(o.origin))return;if(o.data!==INIT_MESSAGE_TYPE)return;const r=o.ports[0];r&&(window.removeEventListener("message",n),t=r,e(r))};window.addEventListener("message",n);try{window.parent.postMessage(READY_MESSAGE_TYPE,"*")}catch{}return{dispose(){window.removeEventListener("message",n),t?.close(),t=null}}}function exposeRpc(e){return onParentPort(t=>{expose(e,t)})}function wrapParentRpc(){let e=null;const t=onParentPort(t=>{t.start(),e=wrap(t)});return{getApi:()=>e,dispose(){t.dispose?.(),e=null}}}function querySpot(e,t){try{const n=e.querySelectorAll(t);return{element:n[0]??null,matchCount:n.length}}catch{return null}}function ensureShadowRoot(e){if(e.shadowRoot)return{ok:!0,shadow:e.shadowRoot};try{return{ok:!0,shadow:e.attachShadow({mode:"open"})}}catch(e){return{ok:!1,name:e instanceof Error?e.name:""}}}function classifyShadowError(e){switch(e){case"NotSupportedError":return"unsupported_element";case"InvalidStateError":return"already_has_shadow";default:return"injection_error"}}function applySpot(e,t){const n=querySpot(e,t.selector);if(!n)return{selector:t.selector,success:!1,reason:"invalid_spot"};if(!n.element)return{selector:t.selector,success:!1,reason:"not_found",matchCount:0};const o=ensureShadowRoot(n.element);if(!o.ok)return{selector:t.selector,success:!1,reason:classifyShadowError(o.name),matchCount:n.matchCount};const r=o.shadow;try{if(r.replaceChildren(),t.css){const n=e.createElement("style");n.textContent=t.css,r.appendChild(n)}if(t.html){const n=e.createElement("div");n.innerHTML=t.html,r.appendChild(n)}return{selector:t.selector,success:!0,matchCount:n.matchCount}}catch{return{selector:t.selector,success:!1,reason:"injection_error",matchCount:n.matchCount}}}function removeSpot(e,t){let n;try{n=e.querySelector(t.selector)}catch{return}const o=n?.shadowRoot;o&&o.replaceChildren(e.createElement("slot"))}function validateSpot(e){if(!e||"object"!=typeof e)return{ok:!1,reason:`not an object (${typeof e})`};const t=e;return"string"!=typeof t.selector?{ok:!1,reason:`selector not a string (${typeof t.selector})`}:0===t.selector.length?{ok:!1,reason:"selector empty"}:void 0!==t.html&&"string"!=typeof t.html?{ok:!1,reason:`html not a string (${typeof t.html})`}:void 0!==t.css&&"string"!=typeof t.css?{ok:!1,reason:`css not a string (${typeof t.css})`}:{ok:!0,spot:e}}function isSpotRef(e){if(!e||"object"!=typeof e)return!1;const t=e.selector;return"string"==typeof t&&t.length>0}function getSelector(e){return e&&"object"==typeof e&&"selector"in e?e.selector:null}function buildRpc(e){return{applySpots:async t=>(invariant$1(Array.isArray(t),"pagePersonalize/preview: applySpots requires an array"),t.map((t,n)=>{const o=validateSpot(t);if(!o.ok)return e.warn(`pagePersonalize/preview: applySpots[${n}] invalid_spot: ${o.reason}`),{selector:getSelector(t),success:!1,reason:"invalid_spot"};const r=applySpot(document,o.spot);return r.success||e.warn(`pagePersonalize/preview: applySpot "${r.selector}" -> ${r.reason}`+(void 0!==r.matchCount?` (matchCount=${r.matchCount})`:"")),r})),async removeSpots(t){invariant$1(Array.isArray(t),"pagePersonalize/preview: removeSpots requires an array");for(let n=0;n<t.length;n++){const o=t[n];isSpotRef(o)?removeSpot(document,o):e.warn(`pagePersonalize/preview: removeSpots[${n}] skipped malformed ref`)}}}}const previewHandler={mode:"preview",activate:e=>exposeRpc(buildRpc(e.log))},UNSTABLE_ID_PATTERNS=[/^[0-9]+$/,/^:r/,/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i],UNSTABLE_DATA_VALUE_PATTERNS=[/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i,/^[a-z0-9]{20,}$/i],UNSTABLE_CLASS_PATTERNS=[/^css-/,/^sc-/,/^emotion-/,/^[a-zA-Z0-9]{5,}$/],SEMANTIC_TAGS=["main","nav","header","footer","aside","article","section"],ARIA_LANDMARK_ROLES=["banner","complementary","contentinfo","form","main","navigation","region","search"];function isStableId(e){return!UNSTABLE_ID_PATTERNS.some(t=>t.test(e))}function isStableDataValue(e){return!UNSTABLE_DATA_VALUE_PATTERNS.some(t=>t.test(e))}function isStableClass(e){return!e.startsWith("p13n-sdk-")&&!UNSTABLE_CLASS_PATTERNS.some(t=>t.test(e))}function isUnique(e){return 1===document.querySelectorAll(e).length}function validate(e,t){try{return document.querySelector(e)===t}catch{return!1}}function getTagName(e){return e.localName}function tryDirectAnchor(e){if(e.id&&isStableId(e.id)){const t=`#${CSS.escape(e.id)}`;if(validate(t,e))return t}for(const t of e.attributes)if(t.name.startsWith("data-")&&t.value&&isStableDataValue(t.value)){const n=`[${CSS.escape(t.name)}="${CSS.escape(t.value)}"]`;if(isUnique(n)&&validate(n,e))return n}for(const t of e.classList)if(isStableClass(t)){const n=`.${CSS.escape(t)}`;if(isUnique(n)&&validate(n,e))return n}const t=getTagName(e);for(const n of e.classList)if(isStableClass(n)){const o=`${t}.${CSS.escape(n)}`;if(isUnique(o)&&validate(o,e))return o}const n=e.getAttribute("role");if(n&&ARIA_LANDMARK_ROLES.includes(n)){const t=`[role="${n}"]`;if(isUnique(t)&&validate(t,e))return t}return SEMANTIC_TAGS.includes(t)&&isUnique(t)&&validate(t,e)?t:null}function getNthOfTypeIndex(e){const t=getTagName(e);let n=1,o=e.previousElementSibling;for(;o;)o.localName===t&&n++,o=o.previousElementSibling;return n}function buildRelativePath(e,t){const n=[];let o=t;for(;o&&o!==e;){const e=getTagName(o),t=getNthOfTypeIndex(o);n.unshift(`${e}:nth-of-type(${t})`),o=o.parentElement}return n.join(" > ")}function tryAnchoredPath(e){let t=e.parentElement;for(;t&&t!==document.documentElement;){const n=tryDirectAnchor(t);if(n){const o=`${n} > ${buildRelativePath(t,e)}`;if(validate(o,e))return o}t=t.parentElement}return null}function buildFullPath(e){const t=[];let n=e;for(;n&&n!==document.documentElement;){const e=getTagName(n),o=getNthOfTypeIndex(n);t.unshift(`${e}:nth-of-type(${o})`),n=n.parentElement}const o=`html > ${t.join(" > ")}`;return validate(o,e)?o:null}function generateSelector(e){if(!e||e===document.documentElement||e===document.body)return e===document.body?"body":"html";const t=tryDirectAnchor(e);if(t)return t;const n=tryAnchoredPath(e);return n||(buildFullPath(e)??e.localName)}const SDK_ATTR="data-p13n-sdk",HIGHLIGHT_CLASS="p13n-sdk-highlight",SUPPRESSED_EVENTS=["mousedown","mouseup","pointerdown","pointerup","keydown","keyup","focusin","submit"],INJECTED_CSS=`\n .${HIGHLIGHT_CLASS} {\n outline: 2px solid blue !important;\n outline-offset: -2px !important;\n cursor: crosshair !important;\n }\n .p13n-sdk-tooltip {\n position: fixed;\n z-index: 2147483647;\n background: rgba(0, 0, 0, 0.8);\n color: #fff;\n font-family: monospace;\n font-size: 12px;\n padding: 4px 8px;\n border-radius: 4px;\n pointer-events: none;\n white-space: nowrap;\n }\n`;function isSdkElement(e){let t=e;for(;t;){if(t.hasAttribute&&t.hasAttribute(SDK_ATTR))return!0;t=t.parentElement}return!1}function getElementDimensions(e){if(0!==e.offsetWidth)return{width:e.offsetWidth,height:e.offsetHeight};const t=e.getBoundingClientRect();return{width:Math.round(t.width),height:Math.round(t.height)}}function createSelectionRuntime(e){let t=null;const n=document.createElement("style");n.setAttribute(SDK_ATTR,""),n.textContent=INJECTED_CSS,document.head.appendChild(n);const o=document.createElement("div");function r(e){let t=e.clientX+15,n=e.clientY+15;const r=o.getBoundingClientRect(),i=r.width||150,a=r.height||24;t+i>window.innerWidth&&(t=e.clientX-15-i),n+a>window.innerHeight&&(n=e.clientY-15-a),o.style.left=`${t}px`,o.style.top=`${n}px`}function i(e){const n=e.target;if(!(n instanceof HTMLElement))return;if(isSdkElement(n))return;t&&t!==n&&t.classList.remove(HIGHLIGHT_CLASS),t=n,n.classList.add(HIGHLIGHT_CLASS);const i=n.localName,{width:a,height:s}=getElementDimensions(n);o.textContent=`${i} ${a}×${s}`,o.style.display="block",r(e)}function a(e){"block"===o.style.display&&r(e)}function s(e){const n=e.target;n instanceof HTMLElement&&(isSdkElement(n)||(t===n&&(n.classList.remove(HIGHLIGHT_CLASS),t=null),o.style.display="none"))}function c(e){isSdkElement(e.target)||(e.preventDefault(),e.stopPropagation(),e.stopImmediatePropagation())}function l(t){const n=t.target;if(!(n instanceof HTMLElement))return;c(t);const o=generateSelector(n);e(o)}return o.className="p13n-sdk-tooltip",o.setAttribute(SDK_ATTR,""),o.style.display="none",document.body.appendChild(o),function(){document.addEventListener("mouseover",i,!0),document.addEventListener("mousemove",a,!0),document.addEventListener("mouseout",s,!0),document.addEventListener("click",l,!0);for(const e of SUPPRESSED_EVENTS)document.addEventListener(e,c,!0)}(),{dispose(){!function(){document.removeEventListener("mouseover",i,!0),document.removeEventListener("mousemove",a,!0),document.removeEventListener("mouseout",s,!0),document.removeEventListener("click",l,!0);for(const e of SUPPRESSED_EVENTS)document.removeEventListener(e,c,!0)}(),t&&(t.classList.remove(HIGHLIGHT_CLASS),t=null),o.style.display="none",o.remove(),n.remove(),t=null}}}const spotSelectionHandler={mode:"spot-selection",activate(e){const t=wrapParentRpc(),n=createSelectionRuntime(n=>{const o=t.getApi();o?o.onSpotSelected(n):e.log.warn("pagePersonalize/spot-selection: no parent RPC connection, cannot send selector")});return{dispose(){n.dispose?.(),t.dispose?.()}}}},MODE_HANDLERS={preview:previewHandler,"spot-selection":spotSelectionHandler};function readMode(){if("undefined"==typeof window||!window.location)return null;let e;try{e=new URLSearchParams(window.location.search).get(MODE_QUERY_PARAM)}catch{return null}return e&&Object.hasOwn(MODE_HANDLERS,e)?e:null}function runRouter(e){const t=readMode();if(!t)return null;let n;try{n=MODE_HANDLERS[t].activate(e)}catch(n){return e.log.error(`pagePersonalize: activation failed for mode "${t}":`,n),null}return n?t:null}function numAttr(e,t){const n=e[t];if("string"!=typeof n||0===n.length)return null;const o=Number(n);return Number.isFinite(o)?o:null}function strAttr(e,t){const n=e[t];return"string"==typeof n&&n.length>0?n:null}function isInWindow(e,t){const n=numAttr(e,"td_personalization.campaigns_start_date");if(null!==n&&t<n)return!1;const o=numAttr(e,"td_personalization.campaigns_end_date");return!(null!==o&&t>=o)}function isLiveOffer(e,t){const n=e.attributes;return!!n&&"object"==typeof n&&isInWindow(n,t)}function toScoredOffer(e){const t=e.attributes;if(!t)return null;const n=numAttr(t,"td_personalization.audience_rank");if(null===n)return null;return{offer:e,updated:numAttr(t,"td_personalization.campaign_updated_at")??-1/0,rank:n}}function maxBy(e,t){return e.reduce((e,n)=>null===e||t(n,e)?n:e,null)}function selectWinningOffer(e,t=Date.now()/1e3){const n=e?.offers;if(!n||"object"!=typeof n)return null;const o=maxBy(Object.values(n).filter(e=>isLiveOffer(e,t)).flatMap(e=>toScoredOffer(e)??[]),(e,t)=>e.updated>t.updated||e.updated===t.updated&&e.rank<t.rank);return o?.offer??null}function parseEntries(e){if("string"!=typeof e)return null;try{const t=JSON.parse(e);return Array.isArray(t)?t:null}catch{return null}}function toSpot(e){if(!e||"object"!=typeof e)return null;const{css_selector:t,html_value:n,css_value:o}=e;return"string"!=typeof t||0===t.length||"string"!=typeof n||"string"!=typeof o?null:{selector:t,html:n,css:o}}function decodeEntry(e,t){const n=toSpot(e);if(!n)return null;const o=e.id,r="number"==typeof o&&Number.isFinite(o)?String(o):null;return{spot:n,impression:t&&r?{campaign:t,creative:r}:null}}function decodeOffers(e,t){const n=selectWinningOffer(e,t);if(!n)return[];const o=n.attributes,r=o?strAttr(o,"td_personalization.campaign"):null,i=parseEntries(o?.["td_personalization.content"]);return i?i.flatMap(e=>decodeEntry(e,r)??[]):[]}const PERSONALIZATION_DATABASE="td_c360_personalization",PERSONALIZATION_TABLE="events",CLICKABLE_SELECTOR='a, button, [role="button"], [role="link"]',CAMPAIGN_ATTR="data-td-personalization-campaign",CREATIVE_ATTR="data-td-personalization-creative";function pagePersonalize(){return{name:"pagePersonalize",setup(e,t){const n=runRouter(e);function o(e,n){const o="function"==typeof t.getTrackValues?t.getTrackValues():{};t.addRecord("events",{...o,td_event:e,td_personalization_campaign:n.campaign,td_personalization_creative:n.creative},void 0,void 0,{database:PERSONALIZATION_DATABASE})}function r(e){const t=e.target;if(!(t instanceof Element&&t.closest(CLICKABLE_SELECTOR)))return;const n=e.currentTarget.host,r=n.getAttribute(CAMPAIGN_ATTR),i=n.getAttribute(CREATIVE_ATTR);r&&i&&o("click",{campaign:r,creative:i})}function i(e,t){const n=document.querySelector(e);n?.shadowRoot&&(n.setAttribute(CAMPAIGN_ATTR,t.campaign),n.setAttribute(CREATIVE_ATTR,t.creative),n.shadowRoot.addEventListener("click",r))}function a(e,t){if("undefined"!=typeof document&&(null===n||t?.force))for(const{spot:t,impression:n}of decodeOffers(e)){applySpot(document,t).success&&n&&(o("impression",n),i(t.selector,n))}}return{applyPersonalization:a,personalizePage:function(o,r,i,s){if(null!==n)return void e.log.debug(`pagePersonalize: personalizePage suppressed in "${n}" mode`);const c={};"undefined"!=typeof document&&document.location&&(c.td_url=document.location.href.split("#")[0],c.td_host=document.location.host,c.td_path=document.location.pathname),Object.assign(c,r),t.fetchPersonalization(o,c,e=>{const t=e;a(t),i?.(t)},s)}}}}}function globalId(){return{name:"globalId",setup(e,t){const n=e.config,o=()=>{};return{fetchGlobalID:function(e,r,i=!1,a={}){const s=e||o,c=r||o;if(!t.inSignedMode())return c("not in signed in mode");if(!t.isGlobalIdEnabled())return c("global id is not enabled");const l=n.globalIdCookie||"_td_global",u=cookie.getItem(l);if(u&&!i)return void setTimeout(()=>s(u),0);const d=a.sameSite||"None",p=`https://${n.host}`,g={Authorization:`TD1 ${n.writeKey}`,"Content-Type":globalIdAdlHeaders["Content-Type"],Accept:globalIdAdlHeaders.Accept};"undefined"!=typeof navigator&&(g["User-Agent"]=navigator.userAgent),api.get(p,{headers:g}).then(e=>{if(!e.global_id)return void s(null);const t=e.global_id,n=a.maxAge??6e3;cookie.setItem(l,t,n,a.path,a.domain,a.secure,d),s(t)}).catch(e=>{c(e)})}}}}}const LOADER_METHODS=["set","collectTags","blockEvents","unblockEvents","setSignedMode","setAnonymousMode","fetchServerCookie","fetchGlobalID","fetchUserSegments","fetchPersonalization","resetUUID","addRecord","trackEvent","trackPageview","trackClicks","ready"];function escapeForInlineScript(e){return e.replace(/[<>\u2028\u2029/]/g,e=>{switch(e){case"<":return"\\u003C";case">":return"\\u003E";case"/":return"\\u002F";case"\u2028":return"\\u2028";case"\u2029":return"\\u2029";default:return e}})}function createLoader(e,t){return`!function(t,e){if(void 0===e[t]){e[t]=function(){e[t].clients.push(this),this._init=[Array.prototype.slice.call(arguments)]},e[t].clients=[];for(var r=function(t){return function(){return this["_"+t]=this["_"+t]||[],this["_"+t].push(Array.prototype.slice.call(arguments)),this}},s=${escapeForInlineScript(JSON.stringify(LOADER_METHODS))},c=0;c<s.length;c++){var o=s[c];e[t].prototype[o]=r(o)}var n=document.createElement("script");n.type="text/javascript",n.async=!0,n.src=("https:"===document.location.protocol?"https:":"http:")+${escapeForInlineScript(JSON.stringify(t))};var i=document.getElementsByTagName("script")[0];i.parentNode.insertBefore(n,i)}}(${escapeForInlineScript(JSON.stringify(e))},this);`}function processQueuedCalls(e,t){e._init&&e._init.length,LOADER_METHODS.forEach(n=>{const o=e["_"+n];o&&Array.isArray(o)&&o.length>0&&o.forEach(e=>{"function"==typeof t[n]&&t[n].apply(t,e)})})}function replaceLoaderStub(e,t){const n="undefined"!=typeof window?window:globalThis;if(n[e]&&n[e].clients){const o=n[e].clients;n[e]=t,o.forEach(e=>{let n;if(e._init&&e._init.length>0){const o=e._init[0];n=new t(...o||[])}else n=new t;processQueuedCalls(e,n),Object.setPrototypeOf(e,n),Object.assign(e,n)})}}class Treasure{_sdk;constructor(e){return this instanceof Treasure?(this._sdk=this.init(e),this.bindMethods(),this):new Treasure(e)}init(e){return createSDK(configure(e)).use(session()).use(record()).use(track()).use(clicks()).use(utm()).use(personalization()).use(conversionAPI()).use(serverCookie()).use(globalId()).use(pagePersonalize())}bindMethods(){const e=new Set;let t=this._sdk;for(;t&&t!==Object.prototype;)Object.getOwnPropertyNames(t).forEach(n=>{"function"==typeof t[n]&&"constructor"!==n&&e.add(n)}),t=Object.getPrototypeOf(t);e.forEach(e=>{this.hasOwnProperty(e)||"init"===e||"bindMethods"===e||(this[e]=this._sdk[e].bind(this._sdk))})}get sdk(){return this._sdk}get config(){return this._sdk.config}static version="1.0.0";get version(){return Treasure.version}addRecord=(e,t,n,o,r)=>this._sdk.addRecord(e,t,n,o,r);trackEvent=(e,t,n,o)=>this._sdk.trackEvent(e,t,n,o);trackPageview=(e,t,n,o)=>this._sdk.trackPageview(e,t,n,o);trackClicks=e=>this._sdk.trackClicks(e);fetchUserSegments(e,t,n){return this._sdk.fetchUserSegments(e,t,n)}fetchPersonalization=(e,t,n,o)=>this._sdk.fetchPersonalization(e,t,n,o);applyPersonalization=(e,t)=>{this._sdk.applyPersonalization(e,t)};personalizePage=(e,t,n,o)=>{this._sdk.personalizePage(e,t,n,o)};collectUTMParameters=()=>this._sdk.collectUTMParameters();getUTMParameters=()=>this._sdk.getUTMParameters();set=(e,t,n)=>this._sdk.set(e,t,n);get=(e,t)=>this._sdk.get(e,t);setSignedMode=()=>this._sdk.setSignedMode();setAnonymousMode=e=>this._sdk.setAnonymousMode(e);inSignedMode=()=>this._sdk.inSignedMode();blockEvents=()=>this._sdk.blockEvents();unblockEvents=()=>this._sdk.unblockEvents();areEventsBlocked=()=>this._sdk.areEventsBlocked();resetUUID=()=>this._sdk.resetUUID();getTrackValues=()=>this._sdk.getTrackValues();getPersonalizationConfig=()=>this._sdk.getPersonalizationConfig();setPersonalizationConfig=e=>this._sdk.setPersonalizationConfig(e);getWriteKey=()=>this._sdk.getWriteKey();setWriteKey=e=>this._sdk.setWriteKey(e);collectTags=e=>this._sdk.collectTags(e);fetchServerCookie=(e,t,n)=>this._sdk.fetchServerCookie(e,t,n);fetchGlobalID=(e,t,n,o)=>this._sdk.fetchGlobalID(e,t,n,o)}function initSDK(e="td"){"undefined"!=typeof window&&(replaceLoaderStub(e,Treasure),window[e]||(window[e]=Treasure))}if("undefined"!=typeof window&&replaceLoaderStub("Treasure",Treasure),"undefined"!=typeof window&&"undefined"!=typeof document){const e=document.getElementsByTagName("script"),t=e[e.length-1];if(t&&t.hasAttribute("data-auto-init")){initSDK(t.getAttribute("data-global-name")||"td")}}const version="1.0.0";export{BLOCKEVENTSCOOKIE,DEFAULT_CONFIG,SERVER_COOKIE_NAME,SIGNEDMODECOOKIE,Treasure,_validateRecord,adlHeaders,clicks,configure,conversionAPI,cookie,createLoader,createSDK,Treasure as default,element as elementUtils,generateUUID$1 as generateUUID,globalId,globalIdAdlHeaders,initSDK,invariant$1 as invariant,isLocalStorageAccessible,isValidUUID,pagePersonalize,personalization,processQueuedCalls,record,replaceLoaderStub,serverCookie,session,setCookie,track,utm,version};
|