Comparing version 0.2.29 to 0.2.30
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.truetoformApi=t():e.truetoformApi=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:()=>y});const r="ttf-analytics-session-id",n="ttf-analytics-user-id",o=e=>{const t="localhost"===window.location.hostname||"https://truetoform-test-store.myshopify.com"===window.location.origin?"https://api.truetoform.online/v1":"https://api.truetoform.fit/v1",o=async(o,s,a=null,i=null,c=null)=>{const l=(()=>{const t={"Content-Type":"application/json","X-TTF-API-KEY":e},o=localStorage.getItem(r),s=localStorage.getItem(n);return o&&(t["X-TTF-SESSION-ID"]=o),s&&(t["X-TTF-USER-ID"]=s),t})();c&&(l["If-None-Match"]=c);const d={method:o,headers:l,body:a?JSON.stringify(a):null,credentials:"include",signal:i},u=await fetch(`${t}/${s}`,d);if(!u.ok){const e=await u.json();throw new Error(`Error ${u.status}: ${e?.message}`)}const g=u.headers.get("X-New-Session-ID"),m=u.headers.get("X-New-User-ID");if(g&&localStorage.setItem(r,g),m&&localStorage.setItem(n,m),204===u.status)return null;const f=u.headers.get("content-type");if(f&&f.includes("application/json")){return await u.json()}if(f&&f.includes("text/event-stream"))return u.body;if(304===u.status)return{currentETag:localStorage.getItem("ttf-sdk-eTag")};return await u.text()};return{get:(e,t,r)=>o("GET",e,null,t,r),post:(e,t,r)=>o("POST",e,t,r),put:(e,t,r)=>o("PUT",e,t,r),delete:(e,t)=>o("DELETE",e,null,t)}};class s{constructor(e){if(s.instance)return s.instance;this.eventQueue=[],this.MAX_BATCH_SIZE=50,this.MAX_TIME_INTERVAL=5e3,this.sendEventsTimer=null,this.client=e,this.loadQueueFromLocalStorage(),window.addEventListener("beforeunload",(()=>{this.sendEvents()})),window.addEventListener("storage",(e=>{console.log("Storage event:",e),"analyticsEventQueue"===e.key&&this.loadQueueFromLocalStorage()})),s.instance=this}static getInstance(e){return s.instance||(s.instance=new s(e)),s.instance}loadQueueFromLocalStorage(){try{const e=localStorage.getItem("analyticsEventQueue");e&&(this.eventQueue=JSON.parse(e))}catch(e){console.error("Failed to load event queue from localStorage:",e)}}saveQueueToLocalStorage(){try{localStorage.setItem("analyticsEventQueue",JSON.stringify(this.eventQueue))}catch(e){console.error("Failed to save event queue to localStorage:",e)}}enqueueEvent(e){const t=e.metadata.widgetState;t&&"object"==typeof t&&Object.keys(t).length&&(this.latestWidgetState=t),this.latestWidgetState&&(e.metadata.widgetState=this.latestWidgetState),this.eventQueue.push(e),this.saveQueueToLocalStorage(),this.checkAndSendEvents()}checkAndSendEvents(){console.log("Checking and sending events"),this.eventQueue.length>=this.MAX_BATCH_SIZE?this.sendEvents():this.sendEventsTimer||(this.sendEventsTimer=setTimeout((()=>{this.sendEvents()}),this.MAX_TIME_INTERVAL))}async sendEvents(){if(this.sendEventsTimer&&(clearTimeout(this.sendEventsTimer),this.sendEventsTimer=null),0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.saveQueueToLocalStorage(),console.log("Sending events:",e);try{await this.client.post("/analytics/event",{events:e})}catch(t){console.error("Failed to send events:",t),this.eventQueue=[...e,...this.eventQueue],this.saveQueueToLocalStorage()}}}const a=s,i="widget_interaction",c="host_interaction",l="user_update",d="conversion",u="custom",g=()=>{const e=(new Date).getHours();return e>=5&&e<12?"morning":e>=12&&e<14?"noon":e>=14&&e<18?"afternoon":e>=18&&e<21?"evening":"night"},m=()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,timeZoneOffset:(new Date).getTimezoneOffset()});function f(e){for(const t in e)void 0===e[t]?e[t]=null:"object"==typeof e[t]&&null!==e[t]&&f(e[t])}const h=e=>{const t=a.getInstance(e);return(e={})=>{const o=(o,s,a)=>{"string"!=typeof s&&(s=String(s)),"object"==typeof a&&null!==a||(a={});let i=null;a.startTime&&"number"==typeof a.startTime&&(i=Date.now()-a.startTime,delete a.startTime),a.duration=i;const c={category:o,name:s,props:a,analyticsUserId:localStorage.getItem(n),analyticsSessionId:localStorage.getItem(r),metadata:{timestamp:(new Date).toISOString(),localTimestamp:(new Date).toLocaleString(),timeZone:m().timeZone,timeZoneOffset:m().timeZoneOffset,timeOfDay:g(),pageUrl:window.location.href,referrerUrl:document.referrer,device:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",screenWidth:window.screen.width,screenHeight:window.screen.height,browserLanguage:navigator.language,browser:(l=navigator.userAgent,l.includes("Firefox")?"Firefox":l.includes("Edg")?"Edge":l.includes("Chrome")&&!l.includes("Chromium")?"Chrome":l.includes("Safari")&&!l.includes("Chrome")?"Safari":l.includes("Opera")||l.includes("OPR")?"Opera":l.includes("MSIE")||l.includes("Trident")?"Internet Explorer":"Unknown"),widgetState:e}};var l;return f(c),t.enqueueEvent(c),c};return{addWidgetInteractionEvent:(e,t={})=>o(i,e,t),addHostInteractionEvent:(e,t={})=>o(c,e,t),addUserUpdateEvent:(e,t={})=>o(l,e,t),addConversionEvent:(e,t={})=>o(d,e,t),addCustomEvent:(e,t={})=>o(u,e,t)}}},y=e=>{const t=o(e),s=h(t),a=e=>(0,s({}).addCustomEvent)("server_request",e),i=e=>{const r=Date.now();if(!e)throw new Error("survey data is required");return t.post("surveys",e).finally((()=>{a({name:"create_survey",startTime:r})}))},c=e=>{const r=Date.now();if(!e)throw new Error("session ID is required");return t.post("scans",{sessionId:e}).finally((()=>{a({name:"create_scan",startTime:r})}))};return{isStale:async()=>{const e=localStorage.getItem("ttf-sdk-eTag"),r=await t.get("stale-check",null,e),{currentETag:n}=r;return localStorage.setItem("ttf-sdk-eTag",n),e!==n},initAnalytics:async()=>t.post("analytics/init").then((e=>{const{userId:t,sessionId:o}=e;return localStorage.setItem(n,t),localStorage.setItem(r,o),e})),getGarment:e=>{const r=Date.now();if(!e)throw new Error("garment ID is required");return t.get(`garments/${e}`).finally((()=>{a({name:"get_garment",startTime:r,garmentId:e})}))},createSurvey:i,getSurvey:e=>{const r=Date.now();if(!e)throw new Error("survey ID is required");return t.get(`surveys/${e}`).finally((()=>{a({name:"get_survey",startTime:r,surveyId:e})}))},createScan:c,getScan:e=>{const r=Date.now();if(!e)throw new Error("scan ID is required");return t.get(`scans/${e}`).finally((()=>{a({name:"get_scan",startTime:r,scanId:e})}))},getPrediction:e=>{const r=Date.now();if(!e)throw new Error("prediction ID is required");return t.get(`predictions/${e}`).finally((()=>{a({name:"get_prediction",startTime:r,predictionId:e})}))},createSession:()=>{const e=Date.now();return t.post("sessions").finally((()=>{a({name:"create_session",startTime:e})}))},createScanPrediction:async(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("session ID is required");const o=await c(r);if(!o||!o.id)throw new Error("Failed to create scan");return t.post("predictions",{garmentId:e,creatorId:o.id}).finally((()=>{a({name:"create_scan_prediction",startTime:n,garmentId:e,sessionId:r})}))},createSurveyPrediction:async(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("survey data is required");const o=await i(r);if(!o||!o.id)throw new Error("Failed to create survey");return t.post("predictions",{garmentId:e,creatorId:o.id}).finally((()=>{a({name:"create_survey_prediction",startTime:n,garmentId:e,surveyId:o.id})}))},createPredictionFromId:(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("creator ID is required");return t.post("predictions",{garmentId:e,creatorId:r}).finally((()=>{a({name:"create_background_prediction",startTime:n,garmentId:e,creatorId:r})}))},getRealtimeSession:(e,{onChange:r,onSuccess:n,onError:o})=>{let s=()=>{};return async function(){try{const i=Date.now(),c=new AbortController,l=c.signal;s=()=>c.abort();const d=await t.get(`sessions/${e}`,l).finally((()=>{a({name:"get_realtime_session",startTime:i,sessionId:e})})),u=d?.getReader(),g=new TextDecoder;let{done:m,value:f}=await u.read();for(;!m;){const e=g.decode(f,{stream:!0});try{const t=JSON.parse(e);switch(console.log("SSE data:",t),t.type){case"SESSION_DATA":if(r&&"function"==typeof r)try{r(t.payload?.progress)}catch(e){console.error("Error calling onChange:",e)}if(n&&"function"==typeof n){if("READY"===t.payload?.progress)try{n(t.payload)}catch(e){console.error("Error calling onSuccess:",e)}}if(o&&"function"==typeof o){if("FAILED"===t.payload?.progress)try{o(t.payload)}catch(e){console.error("Error calling onError:",e)}}break;case"ERROR":if(console.error("SSE error:",t),o&&"function"==typeof o)try{o(t)}catch(e){console.error("Error calling onError:",e)}}}catch(e){if(console.error("Error parsing SSE data:",e),o&&"function"==typeof o)try{o({type:"ERROR",message:"Parsing error"})}catch(e){console.error("Error calling onError:",e)}}({done:m,value:f}=await u.read())}}catch(e){console.error("Stream error:",e),o&&"function"==typeof o&&o({type:"ERROR",message:"Stream error"})}}(),s},getSessionStatus:e=>{const r=Date.now();if(!e)throw new Error("session ID is required");return t.get(`sessions/${e}/status`).finally((()=>{a({name:"get_session_status",startTime:r})}))},getAnalyticsEvents:s}};return t})())); | ||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.truetoformApi=t():e.truetoformApi=t()}(this,(()=>(()=>{"use strict";var e={d:(t,r)=>{for(var n in r)e.o(r,n)&&!e.o(t,n)&&Object.defineProperty(t,n,{enumerable:!0,get:r[n]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r:e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})}},t={};e.r(t),e.d(t,{default:()=>y});const r="ttf-analytics-session-id",n="ttf-analytics-user-id",o=e=>{const t="localhost"===window.location.hostname||"https://truetoform-test-store.myshopify.com"===window.location.origin?"https://api.truetoform.online/v1":"https://api.truetoform.fit/v1",o=async(o,s,a=null,i=null,c=null)=>{const l=(()=>{const t={"Content-Type":"application/json","X-TTF-API-KEY":e},o=localStorage.getItem(r),s=localStorage.getItem(n);return o&&(t["X-TTF-SESSION-ID"]=o),s&&(t["X-TTF-USER-ID"]=s),t})();c&&(l["If-None-Match"]=c);const d={method:o,headers:l,body:a?JSON.stringify(a):null,credentials:"include",signal:i},u=await fetch(`${t}/${s}`,d);if(!u.ok){const e=await u.json();throw new Error(`Error ${u.status}: ${e?.message}`)}const g=u.headers.get("X-New-Session-ID"),m=u.headers.get("X-New-User-ID");if(g&&localStorage.setItem(r,g),m&&localStorage.setItem(n,m),204===u.status)return null;const f=u.headers.get("content-type");if(f&&f.includes("application/json")){return await u.json()}if(f&&f.includes("text/event-stream"))return u.body;if(304===u.status)return{currentETag:localStorage.getItem("ttf-sdk-eTag")};return await u.text()};return{get:(e,t,r)=>o("GET",e,null,t,r),post:(e,t,r)=>o("POST",e,t,r),put:(e,t,r)=>o("PUT",e,t,r),delete:(e,t)=>o("DELETE",e,null,t)}};class s{constructor(e){if(s.instance)return s.instance;this.eventQueue=[],this.MAX_BATCH_SIZE=50,this.MAX_TIME_INTERVAL=5e3,this.sendEventsTimer=null,this.client=e,this.loadQueueFromLocalStorage(),window.addEventListener("beforeunload",(()=>{this.sendEvents()})),window.addEventListener("storage",(e=>{console.log("Storage event:",e),"analyticsEventQueue"===e.key&&this.loadQueueFromLocalStorage()})),s.instance=this}static getInstance(e){return s.instance||(s.instance=new s(e)),s.instance}loadQueueFromLocalStorage(){try{const e=localStorage.getItem("analyticsEventQueue");e&&(this.eventQueue=JSON.parse(e))}catch(e){console.error("Failed to load event queue from localStorage:",e)}}saveQueueToLocalStorage(){try{localStorage.setItem("analyticsEventQueue",JSON.stringify(this.eventQueue))}catch(e){console.error("Failed to save event queue to localStorage:",e)}}enqueueEvent(e){const t=e.metadata.widgetState;t&&"object"==typeof t&&Object.keys(t).length&&(this.latestWidgetState=t),this.latestWidgetState&&(e.metadata.widgetState=this.latestWidgetState),this.eventQueue.push(e),this.saveQueueToLocalStorage(),this.checkAndSendEvents()}checkAndSendEvents(){console.log("Checking and sending events"),this.eventQueue.length>=this.MAX_BATCH_SIZE?this.sendEvents():this.sendEventsTimer||(this.sendEventsTimer=setTimeout((()=>{this.sendEvents()}),this.MAX_TIME_INTERVAL))}async sendEvents(){if(this.sendEventsTimer&&(clearTimeout(this.sendEventsTimer),this.sendEventsTimer=null),0===this.eventQueue.length)return;const e=[...this.eventQueue];this.eventQueue=[],this.saveQueueToLocalStorage(),console.log("Sending events:",e);try{await this.client.post("analytics/event",{events:e})}catch(t){console.error("Failed to send events:",t),this.eventQueue=[...e,...this.eventQueue],this.saveQueueToLocalStorage()}}}const a=s,i="widget_interaction",c="host_interaction",l="user_update",d="conversion",u="custom",g=()=>{const e=(new Date).getHours();return e>=5&&e<12?"morning":e>=12&&e<14?"noon":e>=14&&e<18?"afternoon":e>=18&&e<21?"evening":"night"},m=()=>({timeZone:Intl.DateTimeFormat().resolvedOptions().timeZone,timeZoneOffset:(new Date).getTimezoneOffset()});function f(e){for(const t in e)void 0===e[t]?e[t]=null:"object"==typeof e[t]&&null!==e[t]&&f(e[t])}const h=e=>{const t=a.getInstance(e);return(e={})=>{const o=(o,s,a)=>{"string"!=typeof s&&(s=String(s)),"object"==typeof a&&null!==a||(a={});let i=null;a.startTime&&"number"==typeof a.startTime&&(i=Date.now()-a.startTime,delete a.startTime),a.duration=i;const c={category:o,name:s,props:a,analyticsUserId:localStorage.getItem(n),analyticsSessionId:localStorage.getItem(r),metadata:{timestamp:(new Date).toISOString(),localTimestamp:(new Date).toLocaleString(),timeZone:m().timeZone,timeZoneOffset:m().timeZoneOffset,timeOfDay:g(),pageUrl:window.location.href,referrerUrl:document.referrer,device:/Mobi|Android/i.test(navigator.userAgent)?"mobile":"desktop",screenWidth:window.screen.width,screenHeight:window.screen.height,browserLanguage:navigator.language,browser:(l=navigator.userAgent,l.includes("Firefox")?"Firefox":l.includes("Edg")?"Edge":l.includes("Chrome")&&!l.includes("Chromium")?"Chrome":l.includes("Safari")&&!l.includes("Chrome")?"Safari":l.includes("Opera")||l.includes("OPR")?"Opera":l.includes("MSIE")||l.includes("Trident")?"Internet Explorer":"Unknown"),widgetState:e}};var l;return f(c),t.enqueueEvent(c),c};return{addWidgetInteractionEvent:(e,t={})=>o(i,e,t),addHostInteractionEvent:(e,t={})=>o(c,e,t),addUserUpdateEvent:(e,t={})=>o(l,e,t),addConversionEvent:(e,t={})=>o(d,e,t),addCustomEvent:(e,t={})=>o(u,e,t)}}},y=e=>{const t=o(e),s=h(t),a=e=>(0,s({}).addCustomEvent)("server_request",e),i=e=>{const r=Date.now();if(!e)throw new Error("survey data is required");return t.post("surveys",e).finally((()=>{a({name:"create_survey",startTime:r})}))},c=e=>{const r=Date.now();if(!e)throw new Error("session ID is required");return t.post("scans",{sessionId:e}).finally((()=>{a({name:"create_scan",startTime:r})}))};return{isStale:async()=>{const e=localStorage.getItem("ttf-sdk-eTag"),r=await t.get("stale-check",null,e),{currentETag:n}=r;return localStorage.setItem("ttf-sdk-eTag",n),e!==n},initAnalytics:async()=>t.post("analytics/init").then((e=>{const{userId:t,sessionId:o}=e;return localStorage.setItem(n,t),localStorage.setItem(r,o),e})),getGarment:e=>{const r=Date.now();if(!e)throw new Error("garment ID is required");return t.get(`garments/${e}`).finally((()=>{a({name:"get_garment",startTime:r,garmentId:e})}))},createSurvey:i,getSurvey:e=>{const r=Date.now();if(!e)throw new Error("survey ID is required");return t.get(`surveys/${e}`).finally((()=>{a({name:"get_survey",startTime:r,surveyId:e})}))},createScan:c,getScan:e=>{const r=Date.now();if(!e)throw new Error("scan ID is required");return t.get(`scans/${e}`).finally((()=>{a({name:"get_scan",startTime:r,scanId:e})}))},getPrediction:e=>{const r=Date.now();if(!e)throw new Error("prediction ID is required");return t.get(`predictions/${e}`).finally((()=>{a({name:"get_prediction",startTime:r,predictionId:e})}))},createSession:()=>{const e=Date.now();return t.post("sessions").finally((()=>{a({name:"create_session",startTime:e})}))},createScanPrediction:async(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("session ID is required");const o=await c(r);if(!o||!o.id)throw new Error("Failed to create scan");return t.post("predictions",{garmentId:e,creatorId:o.id}).finally((()=>{a({name:"create_scan_prediction",startTime:n,garmentId:e,sessionId:r})}))},createSurveyPrediction:async(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("survey data is required");const o=await i(r);if(!o||!o.id)throw new Error("Failed to create survey");return t.post("predictions",{garmentId:e,creatorId:o.id}).finally((()=>{a({name:"create_survey_prediction",startTime:n,garmentId:e,surveyId:o.id})}))},createPredictionFromId:(e,r)=>{const n=Date.now();if(!e)throw new Error("garment ID is required");if(!r)throw new Error("creator ID is required");return t.post("predictions",{garmentId:e,creatorId:r}).finally((()=>{a({name:"create_background_prediction",startTime:n,garmentId:e,creatorId:r})}))},getRealtimeSession:(e,{onChange:r,onSuccess:n,onError:o})=>{let s=()=>{};return async function(){try{const i=Date.now(),c=new AbortController,l=c.signal;s=()=>c.abort();const d=await t.get(`sessions/${e}`,l).finally((()=>{a({name:"get_realtime_session",startTime:i,sessionId:e})})),u=d?.getReader(),g=new TextDecoder;let{done:m,value:f}=await u.read();for(;!m;){const e=g.decode(f,{stream:!0});try{const t=JSON.parse(e);switch(console.log("SSE data:",t),t.type){case"SESSION_DATA":if(r&&"function"==typeof r)try{r(t.payload?.progress)}catch(e){console.error("Error calling onChange:",e)}if(n&&"function"==typeof n){if("READY"===t.payload?.progress)try{n(t.payload)}catch(e){console.error("Error calling onSuccess:",e)}}if(o&&"function"==typeof o){if("FAILED"===t.payload?.progress)try{o(t.payload)}catch(e){console.error("Error calling onError:",e)}}break;case"ERROR":if(console.error("SSE error:",t),o&&"function"==typeof o)try{o(t)}catch(e){console.error("Error calling onError:",e)}}}catch(e){if(console.error("Error parsing SSE data:",e),o&&"function"==typeof o)try{o({type:"ERROR",message:"Parsing error"})}catch(e){console.error("Error calling onError:",e)}}({done:m,value:f}=await u.read())}}catch(e){console.error("Stream error:",e),o&&"function"==typeof o&&o({type:"ERROR",message:"Stream error"})}}(),s},getSessionStatus:e=>{const r=Date.now();if(!e)throw new Error("session ID is required");return t.get(`sessions/${e}/status`).finally((()=>{a({name:"get_session_status",startTime:r})}))},getAnalyticsEvents:s}};return t})())); |
@@ -105,3 +105,3 @@ class EventQueue { | ||
try { | ||
await this.client.post("/analytics/event", { | ||
await this.client.post("analytics/event", { | ||
events: eventsToSend, | ||
@@ -108,0 +108,0 @@ }); |
{ | ||
"name": "ttf-api", | ||
"version": "0.2.29", | ||
"version": "0.2.30", | ||
"description": "The TrueToForm API SDK", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
37
38756
11
941