@bilyai/js 2.0.4 → 2.0.6
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/CHANGELOG.md +5 -0
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 2.0.6 - 2026-09-09
|
|
4
|
+
|
|
5
|
+
- Keeps unknown order values absent when product prices or quantities are incomplete, instead of reporting a free order.
|
|
6
|
+
- Preserves explicit zero totals and totals calculated from complete product lines.
|
|
7
|
+
|
|
3
8
|
## 2.0.4 - 2026-09-07
|
|
4
9
|
|
|
5
10
|
- Omits calculated order money when finite product inputs overflow, while preserving explicit finite totals and zero.
|
package/dist/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
'use strict';var Ae=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function g(){return typeof window!="undefined"&&typeof document!="undefined"}function O(){if(!g())return null;let e=window[Ae];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function k(e,...n){if(typeof e=="function")return e(...n)}var U="sh_client_id",V=null;function Me(){var t,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((t=n[6])!=null?t:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return `${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function xe(){if(!g())return null;try{let e=window.localStorage.getItem(U);return (e==null?void 0:e.trim())||null}catch{return null}}function Ce(e){if(g())try{window.localStorage.setItem(U,e);}catch{}}function De(e){try{let n=k(e==null?void 0:e.get,U);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function ee(e,n){try{let r=k(e==null?void 0:e.set,U,n);r&&typeof r.then=="function"&&Promise.resolve(r).catch(()=>{});}catch{}}function $(e){var r,t;if(!g())return null;let n=(t=(r=V!=null?V:xe())!=null?r:De(e))!=null?t:Me();return V=n,Ce(n),ee(e,n),n}var ae={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},Oe=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),ze={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},Fe={city:"ct",country:"cn",state:"st",zip:"zp"};function p(e){return e!=null&&e!==""}function He(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function I(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function Ne(e){return He({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:I(e.price),product_id:e.id,quantity:I(e.quantity,1),sku:e.sku})}function fe(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null).map(Ne):[]}function ne(e){let n=Object.prototype.hasOwnProperty.call(ae,e)?ae[e]:void 0;return typeof n=="string"?n:e}function me(e){return Oe.has(ne(e))}function Qe(){var r;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function ye(e={},n){var ce;let{client:r,order:t,pageTitle:i,products:o,searchQuery:d,sourceUrl:a,userAgent:v,...C}=e,u={...C};if(n&&(u.sh_client_id=n),r){for(let[y,D]of Object.entries(ze)){let R=r[y];p(R)&&(u[D]=R);}if(r.address)for(let[y,D]of Object.entries(Fe)){let R=r.address[y];p(R)&&(u[D]=R);}}if(p(i)&&(u.page_title=i),p(a)&&(u.event_source_url=a,u.dl=a,u.landing_url=a),p(v)&&(u.uA=v),t){u.order_id=t.id;let y=fe(t.products);y.length>0&&(u.products=y);let D=y.reduce((J,q)=>{let Ue=typeof q.price=="number"?q.price:0,_e=typeof q.quantity=="number"?q.quantity:1;return J+Ue*_e},0),R=I(t.total,I(D));R!==void 0?(u.value=R,u.revenue=R):(delete u.value,delete u.revenue),I(t.tax)!==void 0&&(u.tax=t.tax),I(t.shippingFees)!==void 0&&(u.shippingFees=t.shippingFees),I(t.discount)!==void 0&&(u.discount=t.discount),p(t.discountCode)&&(u.discountCode=t.discountCode);let Le=(ce=y.find(J=>p(J.currency)))==null?void 0:ce.currency,de=p(t.currency)?t.currency:Le;p(de)&&(u.currency=de);}else {let y=fe(o);y.length>0&&(u.products=y);}return p(d)&&(u.search_query=d,u.query=d),u.ts=typeof C.ts=="string"?C.ts:new Date().toISOString(),u.event_id=p(C.event_id)?C.event_id:Qe(),u}var te=100,je=1e3,ge=15e3,qe=1e3,Ve=6e4,P="bily-tracking-script",pe="__bilySdkFacade",$e=["",`bily-${[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("")}`,"i.js"].join("/"),E=null,W=false,l="idle",z=te,b=[],A=ie(),F=0,K=null,_=null,c=null,Q=false,X=false,N=false,B=null,f=null,M=false,x=null,w=null,T=null,Y=false;function ie(){let e,n,r=new Promise((t,i)=>{e=t,n=i;});return r.catch(()=>{}),{promise:r,reject:n,resolve:e}}function h(e,n,r){if(!(!W||typeof console=="undefined")){if(e==="warn"){r===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,r);return}r===void 0?console.info("[Bily]",n):console.info("[Bily]",n,r);}}function we(e){return Number.isFinite(e)?Math.min(je,Math.max(1,Math.floor(e!=null?e:te))):te}function he(e){return Number.isFinite(e)?Math.min(Ve,Math.max(qe,Math.floor(e!=null?e:ge))):ge}function oe(e){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function Ee(e){let n=oe(e.trim());return n.pathname=$e,n.search="",n.hash="",n.toString()}function be(e){let n=e.trim();return oe(n),n}function We(e){try{return /\.m?js$/i.test(oe(e.trim()).pathname)}catch{return false}}function Ke(e,n){var t,i,o;if(typeof e=="string"){let d=We(e)?be(e):Ee(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:he(n==null?void 0:n.loadTimeoutMs),maxQueueSize:we(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:d}}let r=(t=e.scriptUrl)!=null?t:e.trackingDomain;if(!(r!=null&&r.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:he(e.loadTimeoutMs),maxQueueSize:we(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?be(e.scriptUrl):Ee(r)}}function S(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Be(e){let n=document.getElementById(P);if(n instanceof HTMLScriptElement&&S(n.src,e))return n;for(let r of Array.from(document.querySelectorAll("script[src]")))if(S(r.src,e))return r;return null}function ue(e){if(!e)return false;let n=document.getElementById(P);return n instanceof HTMLScriptElement&&!S(n.src,e)}function G(){return new Error("A Bily browser script is already installed with a different URL.")}function ve(e,n=E,r=false){if(!e||!n)return null;let t=document.getElementById(P);return !e.isConnected||!S(e.src,n)||r&&t!==e||t instanceof HTMLScriptElement&&t!==e?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):null}function Xe(){return Y?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):c?ve(c,B,N):ve(f,E,M)}function Ye(){return !x||O()===x?null:new Error("The Bily browser runtime no longer matches the active script. Reload the page before initializing again.")}function L(){var e;return (e=Xe())!=null?e:Ye()}function m(e=E){if(Y||!e||L()||!(c!=null?c:f)||X&&!Q)return null;let r=O();return x&&r!==x?null:r&&!ue(e)?r:null}function Se(e,n){let r=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let t=k(r,n.event,n.payload);t&&typeof t.then=="function"&&Promise.resolve(t).catch(i=>h("warn","Event delivery failed.",i));}catch(t){h("warn","Event delivery failed.",t);}}function Ge(e){if(m()!==e)return false;let n=b;b=[];for(let r=0;r<n.length;r+=1){if(m()!==e)return b=[...n.slice(r),...b],false;Se(e,n[r]);}return m()===e}function le(){K!==null&&window.clearTimeout(K),K=null,_!==null&&window.clearTimeout(_),_=null;}function Z(e){return e===F&&l==="loading"}function j(e,n){if(n!==void 0&&!Z(n))return false;let r=L();if(r)return s(r,n,true),false;if(m()!==e)return s(G(),n,true),false;let t=c!=null?c:f,i=c?N:M;le(),x=e;let o=$(e);return o&&ee(e,o),m()!==e||!Ge(e)?(s(new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."),n,true),false):(l="ready",f=t,M=i,c=null,Q=false,X=false,N=false,B=null,w=null,T=null,A.resolve(),h("info","Ready."),true)}function s(e,n,r=false){if(n!==void 0&&!Z(n))return;l==="ready"&&(A=ie()),r&&(Y=true),le(),l="error";let t=c!=null?c:f,i=c?B:E;(t==null?void 0:t.dataset.bilySdkOwned)==="true"?t.remove():!r&&t&&i&&(w=t,T=i),r&&(w=null,T=null),c=null,Q=false,X=false,N=false,B=null,f=null,M=false,x=null,A.reject(e),h("warn",e.message);}function H(e){if(!Z(e))return;let n=L();if(n){s(n,e,true);return}let r=m();if(r){j(r,e);return}_===null&&(_=window.setTimeout(()=>{_=null,H(e);},16));}function Ze(e){Z(e)&&(Q=true,H(e));}function re(e,n,r=false){let t=++F;c=e,Q=!r,X=r,N=e.id===P,B=E,f=null,M=false,le(),K=window.setTimeout(()=>{let i=L();if(i){s(i,t,true);return}let o=m();if(o){j(o,t);return}s(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Ze(t),{once:true}),e.addEventListener("error",()=>s(new Error(`Unable to load the Bily browser script from ${B!=null?B:"the configured URL"}.`),t),{once:true});}function Je(e){let n=document.createElement("script");for(let r of Array.from(e.attributes))n.setAttribute(r.name,r.value);return n.async=e.async,n.referrerPolicy=e.referrerPolicy,e.nonce&&(n.nonce=e.nonce),n}function en(e){var o,d;let n=document.getElementById(P);if(n instanceof HTMLScriptElement&&!S(n.src,e.scriptUrl)){s(G(),void 0,true);return}if(w!=null&&w.isConnected&&T&&S(T,e.scriptUrl)&&S(w.src,e.scriptUrl)){if(O()){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}let a=w,v=Je(a);w=null,T=null,re(v,e.loadTimeoutMs,true),a.replaceWith(v),H(F);return}w=null,T=null;let r=Be(e.scriptUrl);if(r){re(r,e.loadTimeoutMs),H(F);return}let t=document.createElement("script");t.id=P,t.src=e.scriptUrl,t.async=true,t.referrerPolicy="strict-origin-when-cross-origin",t.dataset.bilySdkOwned="true",e.nonce&&(t.nonce=e.nonce),re(t,e.loadTimeoutMs,true);let i=(d=(o=document.head)!=null?o:document.body)!=null?d:document.documentElement;if(!i){s(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(t),H(F);}function Re(e){b.length>=z&&(b.shift(),h("warn",`Event queue reached ${z}; the oldest event was discarded.`)),b.push(e);}function ke(e,n,r){if(!g())return;let t;try{t=String(e!=null?e:"").trim();}catch(v){h("warn","Ignored an event whose name could not be read.",v);return}if(!t){h("warn","Ignored an event with an empty name.");return}se();let i=L();i&&s(i,void 0,true);let o=l==="error"?null:m(),d=$(o),a;try{a={channel:r!=null?r:me(t)?"ecommerce":"track",event:ne(t),payload:{...ye(n!=null?n:{},d),source:"web"}};}catch(v){h("warn",`Ignored ${t} because its payload could not be read.`,v);return}if(o&&l!=="error"){if(l!=="ready"&&!j(o)){Re(a);return}if(l==="ready"&&m()===o){Se(o,a);return}}Re(a);}function se(){if(!g())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[pe])===true)return;let r={[pe]:true,ecommerce:(t,i)=>ke(t,i,"ecommerce"),get:t=>{if(t===U)return Pe();let i=m();return k(i==null?void 0:i.get,t)},set:(t,i)=>{let o=m();return k(o==null?void 0:o.set,t,i)},track:(t,i)=>Te(t,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:r,writable:!0});}catch{try{e.bily=r;}catch{}}}function Ie(e,n){var o;if(!g())return;let r;try{r=Ke(e,n);}catch(d){if(E&&(l==="loading"||l==="ready")){h("warn","An invalid second initialization was ignored.");return}try{W=typeof e=="object"&&e!==null&&((o=e.debug)!=null?o:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{W=false;}let a=d instanceof Error?d:new Error(String(d));s(a);return}if(E&&!S(E,r.scriptUrl)&&l!=="error"){h("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}if(Y){h("warn","Reload the page before initializing Bily again.");return}let t=L();if(t){s(t,void 0,true);return}if(W=r.debug,z=r.maxQueueSize,b.length>z&&(b=b.slice(-z)),se(),l==="loading"||l==="ready")return;l==="error"&&(A=ie(),l="idle"),E=r.scriptUrl;let i=O();if(i){if(ue(r.scriptUrl)){s(G(),void 0,true);return}if(f=Be(r.scriptUrl),!f||f===w){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}M=(f==null?void 0:f.id)===P,j(i);return}l="loading",en(r);}function Te(e,n){ke(e,n);}function Pe(){return g()?(se(),$(l==="error"?null:m())):null}function nn(){if(!g())return Promise.resolve();let e=L();if(e&&s(e,void 0,true),ue(E)&&s(G(),void 0,true),l==="error")return A.promise;let n=m();return n&&l!=="ready"&&j(n),A.promise}function mn(e,n){Ie(e,n);}exports.getBilyTrackingId=Pe;exports.init=mn;exports.ready=nn;exports.track=Te;
|
|
1
|
+
'use strict';var Ue=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function g(){return typeof window!="undefined"&&typeof document!="undefined"}function O(){if(!g())return null;let e=window[Ue];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function T(e,...n){if(typeof e=="function")return e(...n)}var U="sh_client_id",V=null;function _e(){var t,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((t=n[6])!=null?t:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return `${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Me(){if(!g())return null;try{let e=window.localStorage.getItem(U);return (e==null?void 0:e.trim())||null}catch{return null}}function xe(e){if(g())try{window.localStorage.setItem(U,e);}catch{}}function Ce(e){try{let n=T(e==null?void 0:e.get,U);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function ee(e,n){try{let r=T(e==null?void 0:e.set,U,n);r&&typeof r.then=="function"&&Promise.resolve(r).catch(()=>{});}catch{}}function $(e){var r,t;if(!g())return null;let n=(t=(r=V!=null?V:Me())!=null?r:Ce(e))!=null?t:_e();return V=n,xe(n),ee(e,n),n}var fe={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},De=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),Oe={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},ze={city:"ct",country:"cn",state:"st",zip:"zp"};function p(e){return e!=null&&e!==""}function Fe(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function B(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function He(e){return Fe({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:B(e.price),product_id:e.id,quantity:B(e.quantity,1),sku:e.sku})}function me(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)).map(He):[]}function ne(e){let n=Object.prototype.hasOwnProperty.call(fe,e)?fe[e]:void 0;return typeof n=="string"?n:e}function ye(e){return De.has(ne(e))}function Ne(){var r;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function ge(e={},n){var ce;let{client:r,order:t,pageTitle:i,products:o,searchQuery:d,sourceUrl:a,userAgent:R,...D}=e,u={...D};if(n&&(u.sh_client_id=n),r){for(let[y,q]of Object.entries(Oe)){let I=r[y];p(I)&&(u[q]=I);}if(r.address)for(let[y,q]of Object.entries(ze)){let I=r.address[y];p(I)&&(u[q]=I);}}if(p(i)&&(u.page_title=i),p(a)&&(u.event_source_url=a,u.dl=a,u.landing_url=a),p(R)&&(u.uA=R),t){u.order_id=t.id;let y=me(t.products);y.length>0&&(u.products=y);let I=Array.isArray(t.products)&&t.products.length>0&&t.products.every(E=>E!==null&&typeof E=="object"&&!Array.isArray(E)&&B(E.price)!==void 0&&(E.quantity===void 0||B(E.quantity)!==void 0))?y.reduce((E,ae)=>E+ae.price*ae.quantity,0):void 0,J=B(t.total,B(I));J!==void 0?(u.value=J,u.revenue=J):(delete u.value,delete u.revenue),B(t.tax)!==void 0&&(u.tax=t.tax),B(t.shippingFees)!==void 0&&(u.shippingFees=t.shippingFees),B(t.discount)!==void 0&&(u.discount=t.discount),p(t.discountCode)&&(u.discountCode=t.discountCode);let Le=(ce=y.find(E=>p(E.currency)))==null?void 0:ce.currency,de=p(t.currency)?t.currency:Le;p(de)&&(u.currency=de);}else {let y=me(o);y.length>0&&(u.products=y);}return p(d)&&(u.search_query=d,u.query=d),u.ts=typeof D.ts=="string"?D.ts:new Date().toISOString(),u.event_id=p(D.event_id)?D.event_id:Ne(),u}var te=100,Qe=1e3,pe=15e3,je=1e3,qe=6e4,A="bily-tracking-script",we="__bilySdkFacade",Ve=["",`bily-${[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("")}`,"i.js"].join("/"),b=null,W=false,l="idle",z=te,v=[],M=ie(),F=0,K=null,_=null,c=null,Q=false,X=false,N=false,S=null,f=null,x=false,C=null,w=null,P=null,Y=false;function ie(){let e,n,r=new Promise((t,i)=>{e=t,n=i;});return r.catch(()=>{}),{promise:r,reject:n,resolve:e}}function h(e,n,r){if(!(!W||typeof console=="undefined")){if(e==="warn"){r===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,r);return}r===void 0?console.info("[Bily]",n):console.info("[Bily]",n,r);}}function he(e){return Number.isFinite(e)?Math.min(Qe,Math.max(1,Math.floor(e!=null?e:te))):te}function Ee(e){return Number.isFinite(e)?Math.min(qe,Math.max(je,Math.floor(e!=null?e:pe))):pe}function oe(e){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function be(e){let n=oe(e.trim());return n.pathname=Ve,n.search="",n.hash="",n.toString()}function ve(e){let n=e.trim();return oe(n),n}function $e(e){try{return /\.m?js$/i.test(oe(e.trim()).pathname)}catch{return false}}function We(e,n){var t,i,o;if(typeof e=="string"){let d=$e(e)?ve(e):be(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:Ee(n==null?void 0:n.loadTimeoutMs),maxQueueSize:he(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:d}}let r=(t=e.scriptUrl)!=null?t:e.trackingDomain;if(!(r!=null&&r.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:Ee(e.loadTimeoutMs),maxQueueSize:he(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?ve(e.scriptUrl):be(r)}}function k(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Se(e){let n=document.getElementById(A);if(n instanceof HTMLScriptElement&&k(n.src,e))return n;for(let r of Array.from(document.querySelectorAll("script[src]")))if(k(r.src,e))return r;return null}function ue(e){if(!e)return false;let n=document.getElementById(A);return n instanceof HTMLScriptElement&&!k(n.src,e)}function G(){return new Error("A Bily browser script is already installed with a different URL.")}function Re(e,n=b,r=false){if(!e||!n)return null;let t=document.getElementById(A);return !e.isConnected||!k(e.src,n)||r&&t!==e||t instanceof HTMLScriptElement&&t!==e?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):null}function Ke(){return Y?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):c?Re(c,S,N):Re(f,b,x)}function Xe(){return !C||O()===C?null:new Error("The Bily browser runtime no longer matches the active script. Reload the page before initializing again.")}function L(){var e;return (e=Ke())!=null?e:Xe()}function m(e=b){if(Y||!e||L()||!(c!=null?c:f)||X&&!Q)return null;let r=O();return C&&r!==C?null:r&&!ue(e)?r:null}function ke(e,n){let r=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let t=T(r,n.event,n.payload);t&&typeof t.then=="function"&&Promise.resolve(t).catch(i=>h("warn","Event delivery failed.",i));}catch(t){h("warn","Event delivery failed.",t);}}function Ye(e){if(m()!==e)return false;let n=v;v=[];for(let r=0;r<n.length;r+=1){if(m()!==e)return v=[...n.slice(r),...v],false;ke(e,n[r]);}return m()===e}function le(){K!==null&&window.clearTimeout(K),K=null,_!==null&&window.clearTimeout(_),_=null;}function Z(e){return e===F&&l==="loading"}function j(e,n){if(n!==void 0&&!Z(n))return false;let r=L();if(r)return s(r,n,true),false;if(m()!==e)return s(G(),n,true),false;let t=c!=null?c:f,i=c?N:x;le(),C=e;let o=$(e);return o&&ee(e,o),m()!==e||!Ye(e)?(s(new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."),n,true),false):(l="ready",f=t,x=i,c=null,Q=false,X=false,N=false,S=null,w=null,P=null,M.resolve(),h("info","Ready."),true)}function s(e,n,r=false){if(n!==void 0&&!Z(n))return;l==="ready"&&(M=ie()),r&&(Y=true),le(),l="error";let t=c!=null?c:f,i=c?S:b;(t==null?void 0:t.dataset.bilySdkOwned)==="true"?t.remove():!r&&t&&i&&(w=t,P=i),r&&(w=null,P=null),c=null,Q=false,X=false,N=false,S=null,f=null,x=false,C=null,M.reject(e),h("warn",e.message);}function H(e){if(!Z(e))return;let n=L();if(n){s(n,e,true);return}let r=m();if(r){j(r,e);return}_===null&&(_=window.setTimeout(()=>{_=null,H(e);},16));}function Ge(e){Z(e)&&(Q=true,H(e));}function re(e,n,r=false){let t=++F;c=e,Q=!r,X=r,N=e.id===A,S=b,f=null,x=false,le(),K=window.setTimeout(()=>{let i=L();if(i){s(i,t,true);return}let o=m();if(o){j(o,t);return}s(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Ge(t),{once:true}),e.addEventListener("error",()=>s(new Error(`Unable to load the Bily browser script from ${S!=null?S:"the configured URL"}.`),t),{once:true});}function Ze(e){let n=document.createElement("script");for(let r of Array.from(e.attributes))n.setAttribute(r.name,r.value);return n.async=e.async,n.referrerPolicy=e.referrerPolicy,e.nonce&&(n.nonce=e.nonce),n}function Je(e){var o,d;let n=document.getElementById(A);if(n instanceof HTMLScriptElement&&!k(n.src,e.scriptUrl)){s(G(),void 0,true);return}if(w!=null&&w.isConnected&&P&&k(P,e.scriptUrl)&&k(w.src,e.scriptUrl)){if(O()){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}let a=w,R=Ze(a);w=null,P=null,re(R,e.loadTimeoutMs,true),a.replaceWith(R),H(F);return}w=null,P=null;let r=Se(e.scriptUrl);if(r){re(r,e.loadTimeoutMs),H(F);return}let t=document.createElement("script");t.id=A,t.src=e.scriptUrl,t.async=true,t.referrerPolicy="strict-origin-when-cross-origin",t.dataset.bilySdkOwned="true",e.nonce&&(t.nonce=e.nonce),re(t,e.loadTimeoutMs,true);let i=(d=(o=document.head)!=null?o:document.body)!=null?d:document.documentElement;if(!i){s(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(t),H(F);}function Be(e){v.length>=z&&(v.shift(),h("warn",`Event queue reached ${z}; the oldest event was discarded.`)),v.push(e);}function Ie(e,n,r){if(!g())return;let t;try{t=String(e!=null?e:"").trim();}catch(R){h("warn","Ignored an event whose name could not be read.",R);return}if(!t){h("warn","Ignored an event with an empty name.");return}se();let i=L();i&&s(i,void 0,true);let o=l==="error"?null:m(),d=$(o),a;try{a={channel:r!=null?r:ye(t)?"ecommerce":"track",event:ne(t),payload:{...ge(n!=null?n:{},d),source:"web"}};}catch(R){h("warn",`Ignored ${t} because its payload could not be read.`,R);return}if(o&&l!=="error"){if(l!=="ready"&&!j(o)){Be(a);return}if(l==="ready"&&m()===o){ke(o,a);return}}Be(a);}function se(){if(!g())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[we])===true)return;let r={[we]:true,ecommerce:(t,i)=>Ie(t,i,"ecommerce"),get:t=>{if(t===U)return Ae();let i=m();return T(i==null?void 0:i.get,t)},set:(t,i)=>{let o=m();return T(o==null?void 0:o.set,t,i)},track:(t,i)=>Pe(t,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:r,writable:!0});}catch{try{e.bily=r;}catch{}}}function Te(e,n){var o;if(!g())return;let r;try{r=We(e,n);}catch(d){if(b&&(l==="loading"||l==="ready")){h("warn","An invalid second initialization was ignored.");return}try{W=typeof e=="object"&&e!==null&&((o=e.debug)!=null?o:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{W=false;}let a=d instanceof Error?d:new Error(String(d));s(a);return}if(b&&!k(b,r.scriptUrl)&&l!=="error"){h("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}if(Y){h("warn","Reload the page before initializing Bily again.");return}let t=L();if(t){s(t,void 0,true);return}if(W=r.debug,z=r.maxQueueSize,v.length>z&&(v=v.slice(-z)),se(),l==="loading"||l==="ready")return;l==="error"&&(M=ie(),l="idle"),b=r.scriptUrl;let i=O();if(i){if(ue(r.scriptUrl)){s(G(),void 0,true);return}if(f=Se(r.scriptUrl),!f||f===w){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}x=(f==null?void 0:f.id)===A,j(i);return}l="loading",Je(r);}function Pe(e,n){Ie(e,n);}function Ae(){return g()?(se(),$(l==="error"?null:m())):null}function en(){if(!g())return Promise.resolve();let e=L();if(e&&s(e,void 0,true),ue(b)&&s(G(),void 0,true),l==="error")return M.promise;let n=m();return n&&l!=="ready"&&j(n),M.promise}function fn(e,n){Te(e,n);}exports.getBilyTrackingId=Ae;exports.init=fn;exports.ready=en;exports.track=Pe;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ae=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function g(){return typeof window!="undefined"&&typeof document!="undefined"}function O(){if(!g())return null;let e=window[Ae];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function k(e,...n){if(typeof e=="function")return e(...n)}var U="sh_client_id",V=null;function Me(){var t,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((t=n[6])!=null?t:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return `${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function xe(){if(!g())return null;try{let e=window.localStorage.getItem(U);return (e==null?void 0:e.trim())||null}catch{return null}}function Ce(e){if(g())try{window.localStorage.setItem(U,e);}catch{}}function De(e){try{let n=k(e==null?void 0:e.get,U);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function ee(e,n){try{let r=k(e==null?void 0:e.set,U,n);r&&typeof r.then=="function"&&Promise.resolve(r).catch(()=>{});}catch{}}function $(e){var r,t;if(!g())return null;let n=(t=(r=V!=null?V:xe())!=null?r:De(e))!=null?t:Me();return V=n,Ce(n),ee(e,n),n}var ae={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},Oe=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),ze={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},Fe={city:"ct",country:"cn",state:"st",zip:"zp"};function p(e){return e!=null&&e!==""}function He(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function I(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function Ne(e){return He({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:I(e.price),product_id:e.id,quantity:I(e.quantity,1),sku:e.sku})}function fe(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null).map(Ne):[]}function ne(e){let n=Object.prototype.hasOwnProperty.call(ae,e)?ae[e]:void 0;return typeof n=="string"?n:e}function me(e){return Oe.has(ne(e))}function Qe(){var r;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function ye(e={},n){var ce;let{client:r,order:t,pageTitle:i,products:o,searchQuery:d,sourceUrl:a,userAgent:v,...C}=e,u={...C};if(n&&(u.sh_client_id=n),r){for(let[y,D]of Object.entries(ze)){let R=r[y];p(R)&&(u[D]=R);}if(r.address)for(let[y,D]of Object.entries(Fe)){let R=r.address[y];p(R)&&(u[D]=R);}}if(p(i)&&(u.page_title=i),p(a)&&(u.event_source_url=a,u.dl=a,u.landing_url=a),p(v)&&(u.uA=v),t){u.order_id=t.id;let y=fe(t.products);y.length>0&&(u.products=y);let D=y.reduce((J,q)=>{let Ue=typeof q.price=="number"?q.price:0,_e=typeof q.quantity=="number"?q.quantity:1;return J+Ue*_e},0),R=I(t.total,I(D));R!==void 0?(u.value=R,u.revenue=R):(delete u.value,delete u.revenue),I(t.tax)!==void 0&&(u.tax=t.tax),I(t.shippingFees)!==void 0&&(u.shippingFees=t.shippingFees),I(t.discount)!==void 0&&(u.discount=t.discount),p(t.discountCode)&&(u.discountCode=t.discountCode);let Le=(ce=y.find(J=>p(J.currency)))==null?void 0:ce.currency,de=p(t.currency)?t.currency:Le;p(de)&&(u.currency=de);}else {let y=fe(o);y.length>0&&(u.products=y);}return p(d)&&(u.search_query=d,u.query=d),u.ts=typeof C.ts=="string"?C.ts:new Date().toISOString(),u.event_id=p(C.event_id)?C.event_id:Qe(),u}var te=100,je=1e3,ge=15e3,qe=1e3,Ve=6e4,P="bily-tracking-script",pe="__bilySdkFacade",$e=["",`bily-${[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("")}`,"i.js"].join("/"),E=null,W=false,l="idle",z=te,b=[],A=ie(),F=0,K=null,_=null,c=null,Q=false,X=false,N=false,B=null,f=null,M=false,x=null,w=null,T=null,Y=false;function ie(){let e,n,r=new Promise((t,i)=>{e=t,n=i;});return r.catch(()=>{}),{promise:r,reject:n,resolve:e}}function h(e,n,r){if(!(!W||typeof console=="undefined")){if(e==="warn"){r===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,r);return}r===void 0?console.info("[Bily]",n):console.info("[Bily]",n,r);}}function we(e){return Number.isFinite(e)?Math.min(je,Math.max(1,Math.floor(e!=null?e:te))):te}function he(e){return Number.isFinite(e)?Math.min(Ve,Math.max(qe,Math.floor(e!=null?e:ge))):ge}function oe(e){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function Ee(e){let n=oe(e.trim());return n.pathname=$e,n.search="",n.hash="",n.toString()}function be(e){let n=e.trim();return oe(n),n}function We(e){try{return /\.m?js$/i.test(oe(e.trim()).pathname)}catch{return false}}function Ke(e,n){var t,i,o;if(typeof e=="string"){let d=We(e)?be(e):Ee(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:he(n==null?void 0:n.loadTimeoutMs),maxQueueSize:we(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:d}}let r=(t=e.scriptUrl)!=null?t:e.trackingDomain;if(!(r!=null&&r.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:he(e.loadTimeoutMs),maxQueueSize:we(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?be(e.scriptUrl):Ee(r)}}function S(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Be(e){let n=document.getElementById(P);if(n instanceof HTMLScriptElement&&S(n.src,e))return n;for(let r of Array.from(document.querySelectorAll("script[src]")))if(S(r.src,e))return r;return null}function ue(e){if(!e)return false;let n=document.getElementById(P);return n instanceof HTMLScriptElement&&!S(n.src,e)}function G(){return new Error("A Bily browser script is already installed with a different URL.")}function ve(e,n=E,r=false){if(!e||!n)return null;let t=document.getElementById(P);return !e.isConnected||!S(e.src,n)||r&&t!==e||t instanceof HTMLScriptElement&&t!==e?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):null}function Xe(){return Y?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):c?ve(c,B,N):ve(f,E,M)}function Ye(){return !x||O()===x?null:new Error("The Bily browser runtime no longer matches the active script. Reload the page before initializing again.")}function L(){var e;return (e=Xe())!=null?e:Ye()}function m(e=E){if(Y||!e||L()||!(c!=null?c:f)||X&&!Q)return null;let r=O();return x&&r!==x?null:r&&!ue(e)?r:null}function Se(e,n){let r=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let t=k(r,n.event,n.payload);t&&typeof t.then=="function"&&Promise.resolve(t).catch(i=>h("warn","Event delivery failed.",i));}catch(t){h("warn","Event delivery failed.",t);}}function Ge(e){if(m()!==e)return false;let n=b;b=[];for(let r=0;r<n.length;r+=1){if(m()!==e)return b=[...n.slice(r),...b],false;Se(e,n[r]);}return m()===e}function le(){K!==null&&window.clearTimeout(K),K=null,_!==null&&window.clearTimeout(_),_=null;}function Z(e){return e===F&&l==="loading"}function j(e,n){if(n!==void 0&&!Z(n))return false;let r=L();if(r)return s(r,n,true),false;if(m()!==e)return s(G(),n,true),false;let t=c!=null?c:f,i=c?N:M;le(),x=e;let o=$(e);return o&&ee(e,o),m()!==e||!Ge(e)?(s(new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."),n,true),false):(l="ready",f=t,M=i,c=null,Q=false,X=false,N=false,B=null,w=null,T=null,A.resolve(),h("info","Ready."),true)}function s(e,n,r=false){if(n!==void 0&&!Z(n))return;l==="ready"&&(A=ie()),r&&(Y=true),le(),l="error";let t=c!=null?c:f,i=c?B:E;(t==null?void 0:t.dataset.bilySdkOwned)==="true"?t.remove():!r&&t&&i&&(w=t,T=i),r&&(w=null,T=null),c=null,Q=false,X=false,N=false,B=null,f=null,M=false,x=null,A.reject(e),h("warn",e.message);}function H(e){if(!Z(e))return;let n=L();if(n){s(n,e,true);return}let r=m();if(r){j(r,e);return}_===null&&(_=window.setTimeout(()=>{_=null,H(e);},16));}function Ze(e){Z(e)&&(Q=true,H(e));}function re(e,n,r=false){let t=++F;c=e,Q=!r,X=r,N=e.id===P,B=E,f=null,M=false,le(),K=window.setTimeout(()=>{let i=L();if(i){s(i,t,true);return}let o=m();if(o){j(o,t);return}s(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Ze(t),{once:true}),e.addEventListener("error",()=>s(new Error(`Unable to load the Bily browser script from ${B!=null?B:"the configured URL"}.`),t),{once:true});}function Je(e){let n=document.createElement("script");for(let r of Array.from(e.attributes))n.setAttribute(r.name,r.value);return n.async=e.async,n.referrerPolicy=e.referrerPolicy,e.nonce&&(n.nonce=e.nonce),n}function en(e){var o,d;let n=document.getElementById(P);if(n instanceof HTMLScriptElement&&!S(n.src,e.scriptUrl)){s(G(),void 0,true);return}if(w!=null&&w.isConnected&&T&&S(T,e.scriptUrl)&&S(w.src,e.scriptUrl)){if(O()){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}let a=w,v=Je(a);w=null,T=null,re(v,e.loadTimeoutMs,true),a.replaceWith(v),H(F);return}w=null,T=null;let r=Be(e.scriptUrl);if(r){re(r,e.loadTimeoutMs),H(F);return}let t=document.createElement("script");t.id=P,t.src=e.scriptUrl,t.async=true,t.referrerPolicy="strict-origin-when-cross-origin",t.dataset.bilySdkOwned="true",e.nonce&&(t.nonce=e.nonce),re(t,e.loadTimeoutMs,true);let i=(d=(o=document.head)!=null?o:document.body)!=null?d:document.documentElement;if(!i){s(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(t),H(F);}function Re(e){b.length>=z&&(b.shift(),h("warn",`Event queue reached ${z}; the oldest event was discarded.`)),b.push(e);}function ke(e,n,r){if(!g())return;let t;try{t=String(e!=null?e:"").trim();}catch(v){h("warn","Ignored an event whose name could not be read.",v);return}if(!t){h("warn","Ignored an event with an empty name.");return}se();let i=L();i&&s(i,void 0,true);let o=l==="error"?null:m(),d=$(o),a;try{a={channel:r!=null?r:me(t)?"ecommerce":"track",event:ne(t),payload:{...ye(n!=null?n:{},d),source:"web"}};}catch(v){h("warn",`Ignored ${t} because its payload could not be read.`,v);return}if(o&&l!=="error"){if(l!=="ready"&&!j(o)){Re(a);return}if(l==="ready"&&m()===o){Se(o,a);return}}Re(a);}function se(){if(!g())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[pe])===true)return;let r={[pe]:true,ecommerce:(t,i)=>ke(t,i,"ecommerce"),get:t=>{if(t===U)return Pe();let i=m();return k(i==null?void 0:i.get,t)},set:(t,i)=>{let o=m();return k(o==null?void 0:o.set,t,i)},track:(t,i)=>Te(t,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:r,writable:!0});}catch{try{e.bily=r;}catch{}}}function Ie(e,n){var o;if(!g())return;let r;try{r=Ke(e,n);}catch(d){if(E&&(l==="loading"||l==="ready")){h("warn","An invalid second initialization was ignored.");return}try{W=typeof e=="object"&&e!==null&&((o=e.debug)!=null?o:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{W=false;}let a=d instanceof Error?d:new Error(String(d));s(a);return}if(E&&!S(E,r.scriptUrl)&&l!=="error"){h("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}if(Y){h("warn","Reload the page before initializing Bily again.");return}let t=L();if(t){s(t,void 0,true);return}if(W=r.debug,z=r.maxQueueSize,b.length>z&&(b=b.slice(-z)),se(),l==="loading"||l==="ready")return;l==="error"&&(A=ie(),l="idle"),E=r.scriptUrl;let i=O();if(i){if(ue(r.scriptUrl)){s(G(),void 0,true);return}if(f=Be(r.scriptUrl),!f||f===w){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}M=(f==null?void 0:f.id)===P,j(i);return}l="loading",en(r);}function Te(e,n){ke(e,n);}function Pe(){return g()?(se(),$(l==="error"?null:m())):null}function nn(){if(!g())return Promise.resolve();let e=L();if(e&&s(e,void 0,true),ue(E)&&s(G(),void 0,true),l==="error")return A.promise;let n=m();return n&&l!=="ready"&&j(n),A.promise}function mn(e,n){Ie(e,n);}export{Pe as getBilyTrackingId,mn as init,nn as ready,Te as track};
|
|
1
|
+
var Ue=[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("");function g(){return typeof window!="undefined"&&typeof document!="undefined"}function O(){if(!g())return null;let e=window[Ue];if(!e||typeof e!="object")return null;let n=e;return typeof n.track=="function"?n:null}function T(e,...n){if(typeof e=="function")return e(...n)}var U="sh_client_id",V=null;function _e(){var t,i;let e=globalThis.crypto;if(typeof(e==null?void 0:e.randomUUID)=="function")return e.randomUUID();let n=new Uint8Array(16);if(typeof(e==null?void 0:e.getRandomValues)=="function")e.getRandomValues(n);else for(let o=0;o<n.length;o+=1)n[o]=Math.floor(Math.random()*256);n[6]=((t=n[6])!=null?t:0)&15|64,n[8]=((i=n[8])!=null?i:0)&63|128;let r=Array.from(n,o=>o.toString(16).padStart(2,"0")).join("");return `${r.slice(0,8)}-${r.slice(8,12)}-${r.slice(12,16)}-${r.slice(16,20)}-${r.slice(20)}`}function Me(){if(!g())return null;try{let e=window.localStorage.getItem(U);return (e==null?void 0:e.trim())||null}catch{return null}}function xe(e){if(g())try{window.localStorage.setItem(U,e);}catch{}}function Ce(e){try{let n=T(e==null?void 0:e.get,U);return n&&typeof n.then=="function"&&Promise.resolve(n).catch(()=>{}),typeof n=="string"&&n.trim()?n.trim():null}catch{return null}}function ee(e,n){try{let r=T(e==null?void 0:e.set,U,n);r&&typeof r.then=="function"&&Promise.resolve(r).catch(()=>{});}catch{}}function $(e){var r,t;if(!g())return null;let n=(t=(r=V!=null?V:Me())!=null?r:Ce(e))!=null?t:_e();return V=n,xe(n),ee(e,n),n}var fe={"Add to Wishlist":"Product Added to Wishlist","Category Viewed":"ViewCategory","Contact Form Submitted":"Contact","New Customer Order":"New Customer Purchase",Pageview:"PageView","Payment Add Address Info":"Checkout Address Info Submitted","Payment Add Contact Info":"AddContactInfo","Payment Add Shipping Info":"AddShippingInfo","Product Added To Wishlist":"Product Added to Wishlist","Remove from Cart":"Product Removed From Cart","Remove from Wishlist":"Product Removed From Wishlist",Search:"Products Searched"},De=new Set(["Product List Viewed","Products Searched","Product Clicked","Product Added","Product Added to Wishlist","Product Removed","Product Viewed","Cart Viewed","Checkout Started","Checkout Step Viewed","Checkout Step Completed","Payment Info Entered","Shipping Info Entered","Order Completed","Order Updated","Order Refunded","Order Cancelled","Clicked Promotion","Viewed Promotion"]),Oe={dateOfBirth:"dob",email:"em",firstname:"fn",gender:"ge",lastname:"ln",phone:"ph",userId:"uid",userGroup:"user_group"},ze={city:"ct",country:"cn",state:"st",zip:"zp"};function p(e){return e!=null&&e!==""}function Fe(e){return Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}function B(e,n){return typeof e=="number"&&Number.isFinite(e)?e:n}function He(e){return Fe({brand:e.brand,category:e.category,currency:e.currency,image:e.image,name:e.name,price:B(e.price),product_id:e.id,quantity:B(e.quantity,1),sku:e.sku})}function me(e){return Array.isArray(e)?e.filter(n=>typeof n=="object"&&n!==null&&!Array.isArray(n)).map(He):[]}function ne(e){let n=Object.prototype.hasOwnProperty.call(fe,e)?fe[e]:void 0;return typeof n=="string"?n:e}function ye(e){return De.has(ne(e))}function Ne(){var r;let e=Math.random().toString(36).slice(2)+Math.random().toString(36).slice(2),n=typeof((r=globalThis.crypto)==null?void 0:r.randomUUID)=="function"?globalThis.crypto.randomUUID():Date.now();return `${e}-${n}`}function ge(e={},n){var ce;let{client:r,order:t,pageTitle:i,products:o,searchQuery:d,sourceUrl:a,userAgent:R,...D}=e,u={...D};if(n&&(u.sh_client_id=n),r){for(let[y,q]of Object.entries(Oe)){let I=r[y];p(I)&&(u[q]=I);}if(r.address)for(let[y,q]of Object.entries(ze)){let I=r.address[y];p(I)&&(u[q]=I);}}if(p(i)&&(u.page_title=i),p(a)&&(u.event_source_url=a,u.dl=a,u.landing_url=a),p(R)&&(u.uA=R),t){u.order_id=t.id;let y=me(t.products);y.length>0&&(u.products=y);let I=Array.isArray(t.products)&&t.products.length>0&&t.products.every(E=>E!==null&&typeof E=="object"&&!Array.isArray(E)&&B(E.price)!==void 0&&(E.quantity===void 0||B(E.quantity)!==void 0))?y.reduce((E,ae)=>E+ae.price*ae.quantity,0):void 0,J=B(t.total,B(I));J!==void 0?(u.value=J,u.revenue=J):(delete u.value,delete u.revenue),B(t.tax)!==void 0&&(u.tax=t.tax),B(t.shippingFees)!==void 0&&(u.shippingFees=t.shippingFees),B(t.discount)!==void 0&&(u.discount=t.discount),p(t.discountCode)&&(u.discountCode=t.discountCode);let Le=(ce=y.find(E=>p(E.currency)))==null?void 0:ce.currency,de=p(t.currency)?t.currency:Le;p(de)&&(u.currency=de);}else {let y=me(o);y.length>0&&(u.products=y);}return p(d)&&(u.search_query=d,u.query=d),u.ts=typeof D.ts=="string"?D.ts:new Date().toISOString(),u.event_id=p(D.event_id)?D.event_id:Ne(),u}var te=100,Qe=1e3,pe=15e3,je=1e3,qe=6e4,A="bily-tracking-script",we="__bilySdkFacade",Ve=["",`bily-${[122,97,114,97,122].map(e=>String.fromCharCode(e)).join("")}`,"i.js"].join("/"),b=null,W=false,l="idle",z=te,v=[],M=ie(),F=0,K=null,_=null,c=null,Q=false,X=false,N=false,S=null,f=null,x=false,C=null,w=null,P=null,Y=false;function ie(){let e,n,r=new Promise((t,i)=>{e=t,n=i;});return r.catch(()=>{}),{promise:r,reject:n,resolve:e}}function h(e,n,r){if(!(!W||typeof console=="undefined")){if(e==="warn"){r===void 0?console.warn("[Bily]",n):console.warn("[Bily]",n,r);return}r===void 0?console.info("[Bily]",n):console.info("[Bily]",n,r);}}function he(e){return Number.isFinite(e)?Math.min(Qe,Math.max(1,Math.floor(e!=null?e:te))):te}function Ee(e){return Number.isFinite(e)?Math.min(qe,Math.max(je,Math.floor(e!=null?e:pe))):pe}function oe(e){let n=new URL(e),r=n.hostname==="localhost"||n.hostname==="127.0.0.1"||n.hostname==="[::1]";if(n.protocol!=="https:"&&!(n.protocol==="http:"&&r))throw new Error("Bily script URLs must use HTTPS (HTTP is allowed for local development).");return n}function be(e){let n=oe(e.trim());return n.pathname=Ve,n.search="",n.hash="",n.toString()}function ve(e){let n=e.trim();return oe(n),n}function $e(e){try{return /\.m?js$/i.test(oe(e.trim()).pathname)}catch{return false}}function We(e,n){var t,i,o;if(typeof e=="string"){let d=$e(e)?ve(e):be(e);return {debug:(n==null?void 0:n.verbose)===true,loadTimeoutMs:Ee(n==null?void 0:n.loadTimeoutMs),maxQueueSize:he(n==null?void 0:n.maxQueueSize),nonce:n==null?void 0:n.nonce,scriptUrl:d}}let r=(t=e.scriptUrl)!=null?t:e.trackingDomain;if(!(r!=null&&r.trim()))throw new Error("Provide a Bily scriptUrl or trackingDomain.");return {debug:(o=(i=e.debug)!=null?i:e.verbose)!=null?o:false,loadTimeoutMs:Ee(e.loadTimeoutMs),maxQueueSize:he(e.maxQueueSize),nonce:e.nonce,scriptUrl:e.scriptUrl?ve(e.scriptUrl):be(r)}}function k(e,n){try{return new URL(e,document.baseURI).toString()===new URL(n,document.baseURI).toString()}catch{return e===n}}function Se(e){let n=document.getElementById(A);if(n instanceof HTMLScriptElement&&k(n.src,e))return n;for(let r of Array.from(document.querySelectorAll("script[src]")))if(k(r.src,e))return r;return null}function ue(e){if(!e)return false;let n=document.getElementById(A);return n instanceof HTMLScriptElement&&!k(n.src,e)}function G(){return new Error("A Bily browser script is already installed with a different URL.")}function Re(e,n=b,r=false){if(!e||!n)return null;let t=document.getElementById(A);return !e.isConnected||!k(e.src,n)||r&&t!==e||t instanceof HTMLScriptElement&&t!==e?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):null}function Ke(){return Y?new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."):c?Re(c,S,N):Re(f,b,x)}function Xe(){return !C||O()===C?null:new Error("The Bily browser runtime no longer matches the active script. Reload the page before initializing again.")}function L(){var e;return (e=Ke())!=null?e:Xe()}function m(e=b){if(Y||!e||L()||!(c!=null?c:f)||X&&!Q)return null;let r=O();return C&&r!==C?null:r&&!ue(e)?r:null}function ke(e,n){let r=n.channel==="ecommerce"&&typeof e.ecommerce=="function"?e.ecommerce:e.track;try{let t=T(r,n.event,n.payload);t&&typeof t.then=="function"&&Promise.resolve(t).catch(i=>h("warn","Event delivery failed.",i));}catch(t){h("warn","Event delivery failed.",t);}}function Ye(e){if(m()!==e)return false;let n=v;v=[];for(let r=0;r<n.length;r+=1){if(m()!==e)return v=[...n.slice(r),...v],false;ke(e,n[r]);}return m()===e}function le(){K!==null&&window.clearTimeout(K),K=null,_!==null&&window.clearTimeout(_),_=null;}function Z(e){return e===F&&l==="loading"}function j(e,n){if(n!==void 0&&!Z(n))return false;let r=L();if(r)return s(r,n,true),false;if(m()!==e)return s(G(),n,true),false;let t=c!=null?c:f,i=c?N:x;le(),C=e;let o=$(e);return o&&ee(e,o),m()!==e||!Ye(e)?(s(new Error("The Bily browser script no longer matches the active URL. Reload the page before initializing again."),n,true),false):(l="ready",f=t,x=i,c=null,Q=false,X=false,N=false,S=null,w=null,P=null,M.resolve(),h("info","Ready."),true)}function s(e,n,r=false){if(n!==void 0&&!Z(n))return;l==="ready"&&(M=ie()),r&&(Y=true),le(),l="error";let t=c!=null?c:f,i=c?S:b;(t==null?void 0:t.dataset.bilySdkOwned)==="true"?t.remove():!r&&t&&i&&(w=t,P=i),r&&(w=null,P=null),c=null,Q=false,X=false,N=false,S=null,f=null,x=false,C=null,M.reject(e),h("warn",e.message);}function H(e){if(!Z(e))return;let n=L();if(n){s(n,e,true);return}let r=m();if(r){j(r,e);return}_===null&&(_=window.setTimeout(()=>{_=null,H(e);},16));}function Ge(e){Z(e)&&(Q=true,H(e));}function re(e,n,r=false){let t=++F;c=e,Q=!r,X=r,N=e.id===A,S=b,f=null,x=false,le(),K=window.setTimeout(()=>{let i=L();if(i){s(i,t,true);return}let o=m();if(o){j(o,t);return}s(new Error(`Bily did not become ready within ${n}ms.`),t);},n),e.addEventListener("load",()=>Ge(t),{once:true}),e.addEventListener("error",()=>s(new Error(`Unable to load the Bily browser script from ${S!=null?S:"the configured URL"}.`),t),{once:true});}function Ze(e){let n=document.createElement("script");for(let r of Array.from(e.attributes))n.setAttribute(r.name,r.value);return n.async=e.async,n.referrerPolicy=e.referrerPolicy,e.nonce&&(n.nonce=e.nonce),n}function Je(e){var o,d;let n=document.getElementById(A);if(n instanceof HTMLScriptElement&&!k(n.src,e.scriptUrl)){s(G(),void 0,true);return}if(w!=null&&w.isConnected&&P&&k(P,e.scriptUrl)&&k(w.src,e.scriptUrl)){if(O()){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}let a=w,R=Ze(a);w=null,P=null,re(R,e.loadTimeoutMs,true),a.replaceWith(R),H(F);return}w=null,P=null;let r=Se(e.scriptUrl);if(r){re(r,e.loadTimeoutMs),H(F);return}let t=document.createElement("script");t.id=A,t.src=e.scriptUrl,t.async=true,t.referrerPolicy="strict-origin-when-cross-origin",t.dataset.bilySdkOwned="true",e.nonce&&(t.nonce=e.nonce),re(t,e.loadTimeoutMs,true);let i=(d=(o=document.head)!=null?o:document.body)!=null?d:document.documentElement;if(!i){s(new Error("Bily could not find a document element for its browser script."));return}i.appendChild(t),H(F);}function Be(e){v.length>=z&&(v.shift(),h("warn",`Event queue reached ${z}; the oldest event was discarded.`)),v.push(e);}function Ie(e,n,r){if(!g())return;let t;try{t=String(e!=null?e:"").trim();}catch(R){h("warn","Ignored an event whose name could not be read.",R);return}if(!t){h("warn","Ignored an event with an empty name.");return}se();let i=L();i&&s(i,void 0,true);let o=l==="error"?null:m(),d=$(o),a;try{a={channel:r!=null?r:ye(t)?"ecommerce":"track",event:ne(t),payload:{...ge(n!=null?n:{},d),source:"web"}};}catch(R){h("warn",`Ignored ${t} because its payload could not be read.`,R);return}if(o&&l!=="error"){if(l!=="ready"&&!j(o)){Be(a);return}if(l==="ready"&&m()===o){ke(o,a);return}}Be(a);}function se(){if(!g())return;let e=window,n;try{n=e.bily;}catch{return}if((n==null?void 0:n[we])===true)return;let r={[we]:true,ecommerce:(t,i)=>Ie(t,i,"ecommerce"),get:t=>{if(t===U)return Ae();let i=m();return T(i==null?void 0:i.get,t)},set:(t,i)=>{let o=m();return T(o==null?void 0:o.set,t,i)},track:(t,i)=>Pe(t,i)};try{Object.defineProperty(e,"bily",{configurable:!0,value:r,writable:!0});}catch{try{e.bily=r;}catch{}}}function Te(e,n){var o;if(!g())return;let r;try{r=We(e,n);}catch(d){if(b&&(l==="loading"||l==="ready")){h("warn","An invalid second initialization was ignored.");return}try{W=typeof e=="object"&&e!==null&&((o=e.debug)!=null?o:e.verbose)||typeof e=="string"&&(n==null?void 0:n.verbose)===!0;}catch{W=false;}let a=d instanceof Error?d:new Error(String(d));s(a);return}if(b&&!k(b,r.scriptUrl)&&l!=="error"){h("warn","Bily is already initialized with a different script URL; the second initialization was ignored.");return}if(Y){h("warn","Reload the page before initializing Bily again.");return}let t=L();if(t){s(t,void 0,true);return}if(W=r.debug,z=r.maxQueueSize,v.length>z&&(v=v.slice(-z)),se(),l==="loading"||l==="ready")return;l==="error"&&(M=ie(),l="idle"),b=r.scriptUrl;let i=O();if(i){if(ue(r.scriptUrl)){s(G(),void 0,true);return}if(f=Se(r.scriptUrl),!f||f===w){s(new Error("An existing Bily browser runtime cannot be matched to the configured script. Reload the page before initializing again."),void 0,true);return}x=(f==null?void 0:f.id)===A,j(i);return}l="loading",Je(r);}function Pe(e,n){Ie(e,n);}function Ae(){return g()?(se(),$(l==="error"?null:m())):null}function en(){if(!g())return Promise.resolve();let e=L();if(e&&s(e,void 0,true),ue(b)&&s(G(),void 0,true),l==="error")return M.promise;let n=m();return n&&l!=="ready"&&j(n),M.promise}function fn(e,n){Te(e,n);}export{Ae as getBilyTrackingId,fn as init,en as ready,Pe as track};
|