@usesophi/sophi-web-object 1.1.6 → 1.2.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/sophi.min.js CHANGED
@@ -1,4 +1,4 @@
1
1
  "use strict";/*!
2
- * sophi-web-object v1.1.6
2
+ * sophi-web-object v1.2.1-beta.1
3
3
  * Framework-agnostic e-commerce tracking script
4
- */var SophiTracker=function(){"use strict";const O="https://api.usesophi.com",C={endpoint:O,maxRetries:3,debounceMs:300,debug:!1};let g=null;function x(e){if(!e.apiKey)throw new Error("[Sophi] config.apiKey is required.");return g=Object.assign(Object.assign(Object.assign({},C),e),{apiKey:e.apiKey,endpoint:O}),g}function d(){if(!g)throw new Error("[Sophi] Config not initialised. Call initConfig() first.");return g}function l(...e){g?.debug&&console.log("[Sophi]",...e)}function c(...e){console.warn("[Sophi]",...e)}function P(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t*16777619>>>0;return t.toString(16).padStart(8,"0")}function p(e){const{apiKey:t}=d();return`sophi-${P(t)}-${e}`}function k(e){const t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${e}=`));return t?decodeURIComponent(t.slice(e.length+1)):null}function b(e,t,n=30){const o=n*86400;document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${o}; path=/; SameSite=Lax`}function v(e){document.cookie=`${e}=; max-age=0; path=/; SameSite=Lax`}async function I(e){const{endpoint:t,apiKey:n,userId:o}=d(),i={"Content-Type":"application/json",Accept:"application/json","x-api-key":n};e&&(i["x-sophi-client-id"]=e);const s=await fetch(`${t}/auth/v1/client/session`,{method:"POST",headers:i,body:JSON.stringify({externalUserId:o})});if(!s.ok)throw new Error(`[Sophi] Session creation failed: HTTP ${s.status}`);return s.json()}async function K(e,t){const{endpoint:n}=d(),o=k(p("access-token"));if(!o){c("[Sophi] Skipping user merge \u2014 no access token available");return}const i=await fetch(`${n}/auth/v1/client/update`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${o}`,"x-sophi-client-id":e},body:JSON.stringify({externalUserId:t})});i.ok||c(`[Sophi] User merge failed: HTTP ${i.status} \u2014 continuing with session creation`)}let y=null;function _(){return y||(y=(async()=>{const e=k(p("client-id")),t=k(p("external-user-id")),{userId:n}=d();let o=e;if(e){const a=t||null,u=n?.trim()||null;a===u||(a&&!u?(v(p("access-token")),v(p("client-id")),v(p("external-user-id")),o=null,l("Logout detected \u2014 cleared stored session")):a&&u&&a!==u?(v(p("access-token")),v(p("client-id")),v(p("external-user-id")),o=null,l("User switch detected \u2014 cleared stored session")):!a&&u&&(l("Merging guest session to logged-in user"),await K(e,u)))}l("Creating session");const i=await I(o),{accessToken:s,clientId:r}=i.data;return b(p("access-token"),s),b(p("client-id"),r),b(p("external-user-id"),n??""),l("Session created and stored in cookies"),{accessToken:s,clientId:r}})(),y)}function A(){y=null,l("Session promise reset (cookies preserved)")}async function U(e){var t;const{endpoint:n}=d(),{accessToken:o,clientId:i}=await _(),s=`${n}/event/v1/external-events`,r=JSON.stringify(e),a={"Content-Type":"application/json",Authorization:`Bearer ${o}`,"x-sophi-client-id":i};l("Sending event:",e.event_type,(t=e.page)===null||t===void 0?void 0:t.url),typeof fetch<"u"?await D(s,r,a):await R(s,r,a)}async function D(e,t,n){const o=await fetch(e,{method:"POST",headers:n,body:t});if(!o.ok)throw new Error(`[Sophi] HTTP ${o.status} from ${e}`)}function R(e,t,n){return new Promise((o,i)=>{const s=new XMLHttpRequest;s.open("POST",e,!0);for(const[r,a]of Object.entries(n))s.setRequestHeader(r,a);s.onload=()=>{s.status>=200&&s.status<300?o():i(new Error(`[Sophi] XHR HTTP ${s.status}`))},s.onerror=()=>i(new Error("[Sophi] XHR network error")),s.send(t)})}function M(e,t){const{endpoint:n}=d(),o=`${n}/event/v1/external-events`;if(typeof navigator>"u"||!navigator.sendBeacon)return c("sendBeacon not available \u2014 event may be lost on page unload"),!1;const i=new Blob([JSON.stringify(e)],{type:"application/json"});return navigator.sendBeacon(o,i)}const f=[];let w=null,S=!1;function H(e){f.push({envelope:e,attempts:0}),l(`Queued event: ${e.event_type} (queue size: ${f.length})`),T()}function T(){if(w!==null)return;const{debounceMs:e=300}=d();w=setTimeout(()=>{w=null,L()},e)}async function L(){if(S||f.length===0)return;S=!0;const{maxRetries:e=3}=d(),t=f.splice(0,f.length);for(const n of t)try{await U(n.envelope),l(`Sent event: ${n.envelope.event_type}`)}catch(o){if(n.attempts+=1,n.attempts<e){const i=Math.pow(2,n.attempts)*500;c(`Event ${n.envelope.event_type} failed (attempt ${n.attempts}/${e}). Retrying in ${i}ms.`),setTimeout(()=>{f.push(n),T()},i)}else c(`Event ${n.envelope.event_type} dropped after ${e} attempts.`,o)}S=!1}async function N(){if(f.length===0)return;const e=await _().catch(()=>null);if(e){for(const t of f)M(t.envelope,e.accessToken);f.length=0}}function B(e,t,n){return e.type?e.url?Object.assign({event_type:"page_view",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:t,page:e},n):(c("page.url is required \u2014 skipping page_view event"),null):(c("page.type is required \u2014 skipping page_view event"),null)}function z(e,t,n,o){if(!e.consent)return c("user.consent is required \u2014 skipping identify event"),null;if(typeof e.consent.gdpr_optin>"u")return c("user.consent.gdpr_optin is required \u2014 skipping identify event"),null;let i={consent:e.consent};return e.consent.gdpr_optin&&(e.identity&&(i.identity=e.identity),e.profile&&(i.profile=e.profile)),e.behavior&&(i.behavior=e.behavior),e.segmentation&&(i.segmentation=e.segmentation),e.custom&&(i.custom=e.custom),Object.assign({event_type:"identify",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,user:i},o)}const J=["id","category_ids","name","url","product_image_url","taxonomy","currency","unit_price","unit_sale_price","in_stock"];function F(e,t,n,o,i){for(const s of J){const r=e[s];if(r==null||Array.isArray(r)&&r.length===0)return c(`product.${s} is required \u2014 skipping ${o} event`),null}return Object.assign({event_type:o,client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,product:e},i)}function W(e,t,n,o,i){if(typeof e.total!="number")return c("basket.total is required \u2014 skipping basket event"),null;if(!e.currency)return c("basket.currency is required \u2014 skipping basket event"),null;if(!Array.isArray(e.line_items)||e.line_items.length===0)return c("basket.line_items must be a non-empty array \u2014 skipping basket event"),null;for(let s=0;s<e.line_items.length;s++){const r=e.line_items[s];if(!r.product_id)return c(`basket.line_items[${s}].product_id is required \u2014 skipping basket event`),null;if(typeof r.quantity!="number"||r.quantity<1)return c(`basket.line_items[${s}].quantity must be an integer \u2265 1 \u2014 skipping basket event`),null;if(!r.currency)return c(`basket.line_items[${s}].currency is required \u2014 skipping basket event`),null;if(typeof r.line_total!="number")return c(`basket.line_items[${s}].line_total is required \u2014 skipping basket event`),null}return Object.assign({event_type:o,client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,basket:e},i)}function X(e,t,n,o){return!e.category_id&&!e.slug&&!e.search_query?(c("listing requires at least one of category_id, slug, or search_query \u2014 skipping listing_view event"),null):Object.assign({event_type:"listing_view",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,listing:e},o)}function Q(e,t,n,o){if(!e.order_id)return c("transaction.order_id is required \u2014 skipping purchase event"),null;if(!e.currency)return c("transaction.currency is required \u2014 skipping purchase event"),null;if(typeof e.total!="number")return c("transaction.total is required \u2014 skipping purchase event"),null;if(!Array.isArray(e.line_items)||e.line_items.length===0)return c("transaction.line_items must be a non-empty array \u2014 skipping purchase event"),null;for(let i=0;i<e.line_items.length;i++){const s=e.line_items[i];if(!s.product_id)return c(`transaction.line_items[${i}].product_id is required \u2014 skipping purchase event`),null;if(typeof s.quantity!="number"||s.quantity<1)return c(`transaction.line_items[${i}].quantity must be an integer \u2265 1 \u2014 skipping purchase event`),null;if(!s.currency)return c(`transaction.line_items[${i}].currency is required \u2014 skipping purchase event`),null;if(typeof s.line_total!="number")return c(`transaction.line_items[${i}].line_total is required \u2014 skipping purchase event`),null}return Object.assign({event_type:"purchase",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,transaction:e},o)}const h='"1.1.6"',V={page:"page_view",user:"identify",product:"product_view",basket:"basket_view",listing:"listing_view",transaction:"purchase"};function Y(e,t){var n,o;const i=e.page;if(!i)return c("sophi_object.page is required to send any event \u2014 skipping"),null;const s=(o=(n=e.event_type)!==null&&n!==void 0?n:V[t])!==null&&o!==void 0?o:"custom",r={user:e.user,product:e.product,basket:e.basket,listing:e.listing,transaction:e.transaction};switch(t){case"page":{const a={user:r.user,product:r.product,basket:r.basket,listing:r.listing,transaction:r.transaction},u=B(i,h,a);return u?Object.assign(Object.assign({},u),{event_type:s}):null}case"user":{if(!e.user)return null;const a={product:r.product,basket:r.basket,listing:r.listing,transaction:r.transaction},u=z(e.user,i,h,a);return u?Object.assign(Object.assign({},u),{event_type:s}):null}case"product":{if(!e.product)return null;const a={user:r.user,basket:r.basket,listing:r.listing,transaction:r.transaction};return F(e.product,i,h,s,a)}case"basket":{if(!e.basket)return null;const a={user:r.user,product:r.product,listing:r.listing,transaction:r.transaction};return W(e.basket,i,h,s,a)}case"listing":{if(!e.listing)return null;const a={user:r.user,product:r.product,basket:r.basket,transaction:r.transaction},u=X(e.listing,i,h,a);return u?Object.assign(Object.assign({},u),{event_type:s}):null}case"transaction":{if(!e.transaction)return null;const a={user:r.user,product:r.product,basket:r.basket,listing:r.listing},u=Q(e.transaction,i,h,a);return u?Object.assign(Object.assign({},u),{event_type:s}):null}default:return null}}function $(e,t){E(e,t,!0)}function G(e,t){E(e,t,!1)}function E(e,t,n){const o=Y(t,e);o&&(n&&l(`Collected: ${o.event_type} (triggered by: ${e})`),H(o))}function Z(e){const t=["page","user","product","basket","listing","transaction"];for(const n of t)e[n]!==void 0&&$(n,e)}let m=0;function ee(){m+=1}function te(){m>0&&(m-=1)}function ne(){return m>0}const ie=new Set(["page","user","product","basket","listing","transaction"]);function se(e){return new Proxy(e,{set(t,n,o){const i=n;return t[n]=o,ie.has(i)&&!ne()&&(l(`Detected update on sophi_object.${String(n)}`),$(i,t)),!0}})}const q={push(e){var t;if(!window.sophi_object){c("SophiTracker.push() called before initialisation \u2014 ignoring.");return}const n=["page","user","product","basket","listing","transaction"],o=Object.prototype.hasOwnProperty.call(e,"event_type");if(o){ee();try{for(const[s,r]of Object.entries(e))window.sophi_object[s]=r}finally{te()}const i=oe(e);if(i){const s=re(e,window.sophi_object);G(i,s)}l(`Explicit push ${String((t=e.event_type)!==null&&t!==void 0?t:"custom")} queued once`)}else{for(const[s,r]of Object.entries(e))window.sophi_object[s]=r;const i=n.filter(s=>s in e);for(const s of i)$(s,window.sophi_object)}o&&delete window.sophi_object.event_type},updateUser(e){var t;if(!(!((t=window.sophi_object)===null||t===void 0)&&t.config)){c("SophiTracker.updateUser() called before initialisation \u2014 ignoring.");return}x(Object.assign(Object.assign({},d()),{userId:e})),A(),window.sophi_object.config.userId=e??"",_()},getSession:_};function oe(e){var t;return(t=["transaction","basket","product","listing","user","page"].find(o=>o in e))!==null&&t!==void 0?t:null}function re(e,t){const n={event_type:e.event_type};("page"in e||t.page)&&(n.page=t.page);const o=["user","product","basket","listing","transaction"];for(const i of o)i in e&&(n[i]=t[i]);return n}async function j(){const e=window.sophi_object,t=e?.config,n=t?.apiKey;if(!e||!n){c('window.sophi_object.config.apiKey is missing. Define window.sophi_object = { config: { apiKey: "..." }, ... } before loading the script.');return}x(Object.assign(Object.assign({},t),{apiKey:n})),delete e.config.apiKey,l("Initialising Sophi Web Object"),await _(),window.sophi_object=se(e),Z(e),window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&N()}),l("Ready")}return window.SophiTracker=q,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void j()):j(),q}();
4
+ */var SophiTracker=function(b){"use strict";const F="https://api.usesophi.com",Y={endpoint:F,maxRetries:3,debounceMs:300,debug:!1};let v=null;function N(e){if(!e.apiKey)throw new Error("[Sophi] config.apiKey is required.");return v=Object.assign(Object.assign(Object.assign({},Y),e),{apiKey:e.apiKey,endpoint:F}),v}function g(){if(!v)throw new Error("[Sophi] Config not initialised. Call initConfig() first.");return v}function u(...e){v?.debug&&console.log("[Sophi]",...e)}function a(...e){console.warn("[Sophi]",...e)}function z(e){let t=2166136261;for(let n=0;n<e.length;n++)t^=e.charCodeAt(n),t=t*16777619>>>0;return t.toString(16).padStart(8,"0")}function p(e){const{apiKey:t}=g();return`sophi-${z(t)}-${e}`}function E(e){const t=document.cookie.split(";").map(n=>n.trim()).find(n=>n.startsWith(`${e}=`));return t?decodeURIComponent(t.slice(e.length+1)):null}function I(e,t,n=30){const s=n*86400;document.cookie=`${e}=${encodeURIComponent(t)}; max-age=${s}; path=/; SameSite=Lax`}function h(e){document.cookie=`${e}=; max-age=0; path=/; SameSite=Lax`}async function W(e){const{endpoint:t,apiKey:n,userId:s}=g(),i={"Content-Type":"application/json",Accept:"application/json","x-api-key":n};e&&(i["x-sophi-client-id"]=e);const o=await fetch(`${t}/auth/v1/client/session`,{method:"POST",headers:i,body:JSON.stringify({externalUserId:s})});if(!o.ok)throw new Error(`[Sophi] Session creation failed: HTTP ${o.status}`);return o.json()}async function J(e,t){const{endpoint:n}=g(),s=E(p("access-token"));if(!s){a("[Sophi] Skipping user merge \u2014 no access token available");return}const i=await fetch(`${n}/auth/v1/client/update`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json",Authorization:`Bearer ${s}`,"x-sophi-client-id":e},body:JSON.stringify({externalUserId:t})});i.ok||a(`[Sophi] User merge failed: HTTP ${i.status} \u2014 continuing with session creation`)}let m=null;function k(){return m||(m=(async()=>{const e=E(p("client-id")),t=E(p("external-user-id")),{userId:n}=g();let s=e;if(e){const c=t||null,l=n?.trim()||null;c===l||(c&&!l?(h(p("access-token")),h(p("client-id")),h(p("external-user-id")),s=null,u("Logout detected \u2014 cleared stored session")):c&&l&&c!==l?(h(p("access-token")),h(p("client-id")),h(p("external-user-id")),s=null,u("User switch detected \u2014 cleared stored session")):!c&&l&&(u("Merging guest session to logged-in user"),await J(e,l)))}u("Creating session");const i=await W(s),{accessToken:o,clientId:r}=i.data;return I(p("access-token"),o),I(p("client-id"),r),I(p("external-user-id"),n??""),u("Session created and stored in cookies"),{accessToken:o,clientId:r}})(),m)}function X(){m=null,u("Session promise reset (cookies preserved)")}function V(){m=null,h(p("access-token")),h(p("client-id")),h(p("external-user-id")),u("Session cleared")}async function Z(e){var t;const{endpoint:n}=g(),{accessToken:s,clientId:i}=await k(),o=`${n}/event/v1/external-events`,r=JSON.stringify(e),c={"Content-Type":"application/json",Authorization:`Bearer ${s}`,"x-sophi-client-id":i};u("Sending event:",e.event_type,(t=e.page)===null||t===void 0?void 0:t.url),typeof fetch<"u"?await ee(o,r,c):await te(o,r,c)}async function ee(e,t,n){const s=await fetch(e,{method:"POST",headers:n,body:t});if(!s.ok)throw new Error(`[Sophi] HTTP ${s.status} from ${e}`)}function te(e,t,n){return new Promise((s,i)=>{const o=new XMLHttpRequest;o.open("POST",e,!0);for(const[r,c]of Object.entries(n))o.setRequestHeader(r,c);o.onload=()=>{o.status>=200&&o.status<300?s():i(new Error(`[Sophi] XHR HTTP ${o.status}`))},o.onerror=()=>i(new Error("[Sophi] XHR network error")),o.send(t)})}function ne(e,t){const{endpoint:n}=g(),s=`${n}/event/v1/external-events`;if(typeof navigator>"u"||!navigator.sendBeacon)return a("sendBeacon not available \u2014 event may be lost on page unload"),!1;const i=new Blob([JSON.stringify(e)],{type:"application/json"});return navigator.sendBeacon(s,i)}let P=!0;function O(e){P=e}function $(){return P}const y=[];let T=null,x=!1;function ie(e){if(!$()){u(`Dropped event (no storage consent): ${e.event_type}`);return}y.push({envelope:e,attempts:0}),u(`Queued event: ${e.event_type} (queue size: ${y.length})`),U()}function U(){if(T!==null)return;const{debounceMs:e=300}=g();T=setTimeout(()=>{T=null,se()},e)}async function se(){if(x||y.length===0)return;x=!0;const{maxRetries:e=3}=g(),t=y.splice(0,y.length);for(const n of t)try{await Z(n.envelope),u(`Sent event: ${n.envelope.event_type}`)}catch(s){if(n.attempts+=1,n.attempts<e){const i=Math.pow(2,n.attempts)*500;a(`Event ${n.envelope.event_type} failed (attempt ${n.attempts}/${e}). Retrying in ${i}ms.`),setTimeout(()=>{y.push(n),U()},i)}else a(`Event ${n.envelope.event_type} dropped after ${e} attempts.`,s)}x=!1}async function oe(){if(y.length===0)return;const e=await k().catch(()=>null);if(e){for(const t of y)ne(t.envelope,e.accessToken);y.length=0}}function re(e,t,n){return e.type?e.url?Object.assign({event_type:"page_view",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:t,page:e},n):(a("page.url is required \u2014 skipping page_view event"),null):(a("page.type is required \u2014 skipping page_view event"),null)}function ae(e,t,n,s){if(!e.consent)return a("user.consent is required \u2014 skipping identify event"),null;if(typeof e.consent.gdpr_optin>"u")return a("user.consent.gdpr_optin is required \u2014 skipping identify event"),null;let i={consent:e.consent};return e.consent.gdpr_optin&&(e.identity&&(i.identity=e.identity),e.profile&&(i.profile=e.profile)),e.behavior&&(i.behavior=e.behavior),e.segmentation&&(i.segmentation=e.segmentation),e.custom&&(i.custom=e.custom),Object.assign({event_type:"identify",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,user:i},s)}const ce=["id","category_ids","name","url","product_image_url","taxonomy","currency","unit_price","unit_sale_price","in_stock"];function ue(e,t,n,s,i){for(const o of ce){const r=e[o];if(r==null||Array.isArray(r)&&r.length===0)return a(`product.${o} is required \u2014 skipping ${s} event`),null}return Object.assign({event_type:s,client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,product:e},i)}function le(e,t,n,s,i){if(typeof e.total!="number")return a("basket.total is required \u2014 skipping basket event"),null;if(!e.currency)return a("basket.currency is required \u2014 skipping basket event"),null;if(!Array.isArray(e.line_items)||e.line_items.length===0)return a("basket.line_items must be a non-empty array \u2014 skipping basket event"),null;for(let o=0;o<e.line_items.length;o++){const r=e.line_items[o];if(!r.product_id)return a(`basket.line_items[${o}].product_id is required \u2014 skipping basket event`),null;if(typeof r.quantity!="number"||r.quantity<1)return a(`basket.line_items[${o}].quantity must be an integer \u2265 1 \u2014 skipping basket event`),null;if(!r.currency)return a(`basket.line_items[${o}].currency is required \u2014 skipping basket event`),null;if(typeof r.line_total!="number")return a(`basket.line_items[${o}].line_total is required \u2014 skipping basket event`),null}return Object.assign({event_type:s,client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,basket:e},i)}function pe(e,t,n,s){return!e.category_id&&!e.slug&&!e.search_query?(a("listing requires at least one of category_id, slug, or search_query \u2014 skipping listing_view event"),null):Object.assign({event_type:"listing_view",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,listing:e},s)}function de(e,t,n,s){if(!e.order_id)return a("transaction.order_id is required \u2014 skipping purchase event"),null;if(!e.currency)return a("transaction.currency is required \u2014 skipping purchase event"),null;if(typeof e.total!="number")return a("transaction.total is required \u2014 skipping purchase event"),null;if(!Array.isArray(e.line_items)||e.line_items.length===0)return a("transaction.line_items must be a non-empty array \u2014 skipping purchase event"),null;for(let i=0;i<e.line_items.length;i++){const o=e.line_items[i];if(!o.product_id)return a(`transaction.line_items[${i}].product_id is required \u2014 skipping purchase event`),null;if(typeof o.quantity!="number"||o.quantity<1)return a(`transaction.line_items[${i}].quantity must be an integer \u2265 1 \u2014 skipping purchase event`),null;if(!o.currency)return a(`transaction.line_items[${i}].currency is required \u2014 skipping purchase event`),null;if(typeof o.line_total!="number")return a(`transaction.line_items[${i}].line_total is required \u2014 skipping purchase event`),null}return Object.assign({event_type:"purchase",client_timestamp:Math.floor(Date.now()/1e3),sdk_version:n,page:t,transaction:e},s)}const w='"1.2.1-beta.1"',fe={page:"page_view",user:"identify",product:"product_view",basket:"basket_view",listing:"listing_view",transaction:"purchase"};function ge(e,t){var n,s;const i=e.page;if(!i)return a("sophi_object.page is required to send any event \u2014 skipping"),null;const o=(s=(n=e.event_type)!==null&&n!==void 0?n:fe[t])!==null&&s!==void 0?s:"custom",r={user:e.user,product:e.product,basket:e.basket,listing:e.listing,transaction:e.transaction};switch(t){case"page":{const c={user:r.user,product:r.product,basket:r.basket,listing:r.listing,transaction:r.transaction},l=re(i,w,c);return l?Object.assign(Object.assign({},l),{event_type:o}):null}case"user":{if(!e.user)return null;const c={product:r.product,basket:r.basket,listing:r.listing,transaction:r.transaction},l=ae(e.user,i,w,c);return l?Object.assign(Object.assign({},l),{event_type:o}):null}case"product":{if(!e.product)return null;const c={user:r.user,basket:r.basket,listing:r.listing,transaction:r.transaction};return ue(e.product,i,w,o,c)}case"basket":{if(!e.basket)return null;const c={user:r.user,product:r.product,listing:r.listing,transaction:r.transaction};return le(e.basket,i,w,o,c)}case"listing":{if(!e.listing)return null;const c={user:r.user,product:r.product,basket:r.basket,transaction:r.transaction},l=pe(e.listing,i,w,c);return l?Object.assign(Object.assign({},l),{event_type:o}):null}case"transaction":{if(!e.transaction)return null;const c={user:r.user,product:r.product,basket:r.basket,listing:r.listing},l=de(e.transaction,i,w,c);return l?Object.assign(Object.assign({},l),{event_type:o}):null}default:return null}}function A(e,t){K(e,t,!0)}function he(e,t){K(e,t,!1)}function K(e,t,n){const s=ge(t,e);s&&(n&&u(`Collected: ${s.event_type} (triggered by: ${e})`),ie(s))}function G(e){const t=["page","user","product","basket","listing","transaction"];for(const n of t)e[n]!==void 0&&A(n,e)}let S=0;function ye(){S+=1}function ve(){S>0&&(S-=1)}function _e(){return S>0}const be=new Set(["page","user","product","basket","listing","transaction"]);function B(e){return new Proxy(e,{set(t,n,s){const i=n;return t[n]=s,be.has(i)&&!_e()&&(u(`Detected update on sophi_object.${String(n)}`),A(i,t)),!0}})}const d={BUFFERING:"BUFFERING",DRAINING:"DRAINING",READY:"READY",FAILED:"FAILED"};let j=d.BUFFERING;const f=[];function L(){return j}function _(e){j=e}function me(){j=d.BUFFERING,f.length=0}let q=!1,D=!1;function M(e){var t;if(!window.sophi_object){a("SophiTracker.push() called before initialisation \u2014 ignoring.");return}const n=["page","user","product","basket","listing","transaction"],s=Object.prototype.hasOwnProperty.call(e,"event_type");if(s){ye();try{for(const[o,r]of Object.entries(e))window.sophi_object[o]=r}finally{ve()}const i=ke(e);if(i){const o=we(e,window.sophi_object);he(i,o)}u(`Explicit push ${String((t=e.event_type)!==null&&t!==void 0?t:"custom")} queued once`)}else{for(const[o,r]of Object.entries(e))window.sophi_object[o]=r;const i=n.filter(o=>o in e);for(const o of i)A(o,window.sophi_object)}s&&delete window.sophi_object.event_type}function H(){for(_(d.DRAINING);f.length>0;){const e=f.splice(0,1)[0];M(e[0])}_(d.READY)}const R={push(e){const t=L();if(t===d.BUFFERING||t===d.DRAINING){f.push([e]);return}if(t===d.FAILED){a("SophiTracker.push() called after bootstrap failure \u2014 ignoring.");return}M(e)},updateUser(e){var t;if(!(!((t=window.sophi_object)===null||t===void 0)&&t.config)){a("SophiTracker.updateUser() called before initialisation \u2014 ignoring.");return}N(Object.assign(Object.assign({},g()),{userId:e})),X(),window.sophi_object.config.userId=e??"",k()},setConsent(e){if(e){if($())return;const t=L();if(t===d.BUFFERING||t===d.DRAINING)return;O(!0),_(d.BUFFERING),u("Storage consent granted \u2014 activating Web Object."),(async()=>{try{await k(),window.sophi_object&&G(window.sophi_object),H(),Q()}catch(n){a("setConsent activation failed",n),_(d.FAILED),f.length=0}})()}else{if(!$())return;O(!1),V(),u("Storage consent withdrawn \u2014 Web Object is now passive.")}},getSession:k};function ke(e){var t;return(t=["transaction","basket","product","listing","user","page"].find(s=>s in e))!==null&&t!==void 0?t:null}function we(e,t){const n={event_type:e.event_type};("page"in e||t.page)&&(n.page=t.page);const s=["user","product","basket","listing","transaction"];for(const i of s)i in e&&(n[i]=t[i]);return n}async function C(){if(q)return;q=!0;const e=window.sophi_object,t=e?.config,n=t?.apiKey;if(!e||!n){a('window.sophi_object.config.apiKey is missing. Define window.sophi_object = { config: { apiKey: "..." }, ... } before loading the script.'),_(d.FAILED),f.length=0;return}N(Object.assign(Object.assign({},t),{apiKey:n})),delete e.config.apiKey;const s=g().storageConsent!==!1;if(O(s),!s){u("Initialised in anonymous mode \u2014 no session, cookies, or events until consent is granted."),window.sophi_object=B(e),f.length>0&&(u(`Clearing ${f.length} buffered push(es) \u2014 no storage consent.`),f.length=0),_(d.READY);return}u("Initialising Sophi Web Object");try{await k()}catch(i){a("Bootstrap failed \u2014 session could not be established.",i),_(d.FAILED),f.length=0;return}window.sophi_object=B(e),G(e),H(),Q(),u("Ready")}function Q(){D||(D=!0,window.addEventListener("visibilitychange",()=>{document.visibilityState==="hidden"&&oe()}))}function Se(){const e=window.SophiTracker;if(e==null||typeof e!="object")return;const t=e.push;if(typeof t!="function")return;const n=t;if(Array.isArray(n._sophiQ)){const s=n._sophiQ;for(const i of s)Array.isArray(i)&&i.length>0&&f.push(i);s.length=0}typeof n._sophiSetFwd=="function"&&n._sophiSetFwd(s=>R.push(s))}Se(),window.SophiTracker=R,document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>void C()):C();function Ee(){q=!1,D=!1}return b._bootstrap=C,b._resetBootstrapGuard=Ee,b.default=R,b.resetTrackerState=me,Object.defineProperty(b,"__esModule",{value:!0}),b}({});
@@ -0,0 +1,2 @@
1
+ export declare function setStorageConsentState(granted: boolean): void;
2
+ export declare function hasStorageConsent(): boolean;
@@ -1,5 +1,6 @@
1
1
  import type { SophiObjectShape, ExternalEventType } from './types';
2
2
  import { getSession } from './auth';
3
+ import { resetTrackerState } from './tracker-state';
3
4
  declare global {
4
5
  interface Window {
5
6
  sophi_object?: SophiObjectShape;
@@ -11,6 +12,10 @@ declare const SophiTracker: {
11
12
  * Manually push a partial sophi_object update and fire an event.
12
13
  * Pass `event_type` to override the default mapping.
13
14
  *
15
+ * Calls made before or during bootstrap are buffered in FIFO order and
16
+ * drained after initialisation completes. Calls after a fatal bootstrap
17
+ * failure are discarded with a warning.
18
+ *
14
19
  * @example
15
20
  * // Override event type for add_to_cart (needs both product + basket)
16
21
  * SophiTracker.push({ event_type: 'add_to_cart', product: { ... }, basket: { ... } })
@@ -26,8 +31,29 @@ declare const SophiTracker: {
26
31
  * the session with the updated identity.
27
32
  */
28
33
  updateUser(userId: string | undefined): void;
34
+ /**
35
+ * Grant or withdraw storage consent at runtime.
36
+ *
37
+ * The Web Object loads passively when there is no consent (no session, no
38
+ * cookies, no events). Calling `setConsent(true)` activates it: it creates a
39
+ * session, writes cookies, and starts sending events (including the current
40
+ * sophi_object snapshot). `setConsent(false)` makes it passive again and
41
+ * clears the session cookies.
42
+ *
43
+ * push() calls made after setConsent(true) and before activation completes
44
+ * are buffered in the pending queue and drained once the session is ready.
45
+ * Concurrent or repeated setConsent(true) calls while activation is in
46
+ * progress are ignored.
47
+ */
48
+ setConsent(granted: boolean): void;
29
49
  /** Expose session info for debugging */
30
50
  getSession: typeof getSession;
31
51
  };
52
+ declare function bootstrap(): Promise<void>;
32
53
  export default SophiTracker;
33
54
  export type { ExternalEventType, SophiObjectShape };
55
+ export { resetTrackerState };
56
+ /** Reset the bootstrap guard between tests. */
57
+ export declare function _resetBootstrapGuard(): void;
58
+ /** Trigger bootstrap() directly in tests without the DOMContentLoaded dance. */
59
+ export { bootstrap as _bootstrap };
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Pre-load command queue and lifecycle state.
3
+ *
4
+ * Lifecycle:
5
+ * BUFFERING → bootstrap succeeds → DRAINING → READY
6
+ * BUFFERING → fatal error → FAILED
7
+ *
8
+ * Do not import this module in tests without calling resetTrackerState()
9
+ * in beforeEach — module-level state persists across tests within the same
10
+ * file unless explicitly reset.
11
+ */
12
+ import type { SophiObjectShape } from './types';
13
+ /** Typed tuple matching the public SophiTracker.push() signature. */
14
+ export type PushArgs = [Partial<Omit<SophiObjectShape, 'config'>>];
15
+ export declare const TrackerState: {
16
+ /** Bundle has executed but bootstrap has not yet completed. */
17
+ readonly BUFFERING: "BUFFERING";
18
+ /** Pending queue is being drained; new pushes append to the same queue. */
19
+ readonly DRAINING: "DRAINING";
20
+ /** Bootstrap complete; push() calls are processed immediately. */
21
+ readonly READY: "READY";
22
+ /** Fatal bootstrap failure; push() calls are discarded with a warning. */
23
+ readonly FAILED: "FAILED";
24
+ };
25
+ export type TrackerState = (typeof TrackerState)[keyof typeof TrackerState];
26
+ /** Pre-load and bootstrap-time pending push() calls in FIFO order. */
27
+ export declare const pendingQueue: PushArgs[];
28
+ export declare function getState(): TrackerState;
29
+ export declare function setState(s: TrackerState): void;
30
+ /**
31
+ * Reset all module-level state to initial values.
32
+ * For test isolation only — do not call in production code.
33
+ */
34
+ export declare function resetTrackerState(): void;
@@ -10,6 +10,13 @@ export interface SophiConfig {
10
10
  debounceMs?: number;
11
11
  /** Whether to print debug logs to the console. Default: false */
12
12
  debug?: boolean;
13
+ /**
14
+ * Whether the Web Object may persist cookies and send events. Default: true.
15
+ * When false (anonymous / no cookie consent) the SDK stays passive: no
16
+ * session is created, no cookies are written, and no events are sent. Call
17
+ * {@link SophiTracker.setConsent} to activate once consent is granted.
18
+ */
19
+ storageConsent?: boolean;
13
20
  }
14
21
  export interface SophiSession {
15
22
  accessToken: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@usesophi/sophi-web-object",
3
- "version": "1.1.6",
3
+ "version": "1.2.1-beta.1",
4
4
  "description": "Framework-agnostic e-commerce tracking script for Sophi",
5
5
  "type": "module",
6
6
  "main": "dist/sophi.js",